用Python写一个统计Verilog代码行数的脚本,首先打开指定的文件并读取全部内容。然后使用正则表达式去除注释,并按行分割并去除空白字符。接下来,它统计不在模块定义、包定义、函数定义、任务定义、generate块等特殊语句内的代码行数。然后,它查找每个模块实例化语句,并递归计算每个模块的行数,将其加入总行数中。最后,它查找每个 include 语句,并递归计算每个 included 文件的行数,将其加入总行数中。最终返回总行数。也同时输出各个子模块,include文件的对应的代码行数
时间: 2024-02-05 22:12:42 浏览: 171
Shell脚本统计文件行数的8种方法
5星 · 资源好评率100%
以下是一个基本的Verilog代码行数统计脚本,它可以完成所述的功能:
```python
import re
def count_verilog_lines(filename):
with open(filename, 'r') as f:
content = f.read()
# remove comments
pattern = r'(/\*.*?\*/|//.*?$)'
content = re.sub(pattern, '', content, flags=re.MULTILINE | re.DOTALL)
# remove whitespace
content = re.sub(r'\s+', ' ', content)
# split into lines
lines = content.split('\n')
# count non-special lines
special_keywords = ['module', 'endmodule', 'package', 'endpackage', 'function', 'endfunction', 'task', 'endtask', 'generate']
special_line = False
count = 0
sub_counts = {}
for line in lines:
if any(keyword in line for keyword in special_keywords):
special_line = not special_line
if not special_line:
sub_module_name = re.search(r'\.(\w+)\s*\(', line).group(1)
sub_counts[sub_module_name] = count
count = 0
elif not special_line and line.strip() != '':
count += 1
# count sub-modules
include_files = set()
include_pattern = r'^\s*`include\s+["<](\S+)[">].*$'
module_pattern = r'^\s*(\w+)\s+(\w+)\s*\('
for line in lines:
include_match = re.match(include_pattern, line)
if include_match:
include_file = include_match.group(1)
include_files.add(include_file)
include_count = count_verilog_lines(include_file)
count += include_count
else:
module_match = re.match(module_pattern, line)
if module_match:
sub_module_name = module_match.group(2)
sub_counts[sub_module_name] = count_verilog_lines(filename)
# print results
print('Total lines:', count)
print('Sub-module lines:')
for sub_module_name, sub_count in sub_counts.items():
print(sub_module_name, sub_count)
print('Included files:')
for include_file in include_files:
print(include_file, count_verilog_lines(include_file))
return count
```
该脚本首先读取指定的文件,并使用正则表达式去除注释。然后,它将内容按行分割并去除空白字符。接下来,它遍历每一行,统计不在特殊语句内的代码行数,并记录每个子模块的名称和行数。随后,它查找每个 include 语句,并递归计算每个 included 文件的行数,将其加入总行数中。最后,它查找每个模块实例化语句,并递归计算每个模块的行数,将其加入总行数中。最终返回总行数,并输出各个子模块,include文件的对应的代码行数。
阅读全文