python怎能删除verilog文件中的多行注释

Viewed 145

python怎能删除verilog文件中的多行注释?假设有多处、和嵌套。

2 Answers

一个笨方法,用for来遍历verilog文本。如下:

def remove_comment_multiline(txt):
    # 先找出所有多行注释开始和结束的位置
    begin_flag = 0
    begin_position = 0
    hier = 0
    m = [] # 用于存放多行注释开始结束位置信息
    total_len = len(txt)
    for i in range(total_len):
        # 遇到开始符/*
        if begin_flag == 0 and txt[i] == '/' and txt[i+1] == '*':
            begin_flag = 1
            begin_position = i
		# 处理注释嵌套
        elif begin_flag == 1 and txt[i] == '/' and txt[i+1] == '*':
            hier = hier + 1
        # 处理注释嵌套
        elif begin_flag == 1 and hier > 0 and txt[i-1] == '*' and txt[i] == '/':
            hier = hier - 1
        # 遇到注释结束符*/
        elif begin_flag == 1 and hier == 0 and txt[i-1] == '*' and txt[i] == '/':
            begin_flag = 0
            m.append([begin_position, i])

    # 根据多行注释开始结束位置进行字符串拼接,跳过注释部分
    ret = ''
    last_position = 0
    for i in range(len(m)):
        p = m[i]
        begin_position = p[0]
        end_position = p[1]
        print(i, begin_position, end_position, last_position)
        if i == 0:
            if p[0] != 0:
                ret += txt[0:begin_position]
            last_position = end_position + 1
        elif i < len(m)-1:
            ret += txt[last_position:begin_position]
            last_position = end_position + 1
        elif i == len(m)-1:
            ret += txt[last_position:begin_position]
            last_position = end_position + 1
            print(end_position, last_position, total_len)
            if end_position != total_len-1:
                ret += txt[end_position+1:]

    return ret
  1. 按行解析,然后匹配上标识符之后记录层数,并记录行列号。
  2. 全部解析完成后可以得到一个嵌套字典。
  3. 处理字典,只处理最外层;删除匹配的开始位置之后、结束位置之前部分,开始结束行中间的行全部删除。