利用python自动生成verilog模块例化模板

2022-10-17,,,,

一、前言

  初入职场,一直忙着熟悉工作,就没什么时间更新博客。今天受“利奇马”的影响,只好宅在家中,写写技术文章。芯片设计规模日益庞大,编写脚本成了芯片开发人员必要的软技能。模块端口动不动就几十上百个,手动编写代码伤不起。实现verilog模块例化模板自动生成也算是我自砸饭碗的第一步了o(∩_∩)o!

二、代码设计

  要自动生成模块例化模板总共分三步:1 打开设计文件,读取内容 2 正则匹配 3 打开指定上层文件,写入例化模板。涉及到的知识点主要有文件读写和正则匹配。该脚本分别用两个表达式匹配模块名称和端口列表,之后把两者按照verilog模块例化的代码规则写入到指定文件。具体细节上代码之后再说:

 1 #!/usr/bin/python
 2 
 3 import re
 4 import os
 5 
 6 #regex compile
 7 regex_module = re.compile('(module)(\s+)(\w+)');
 8 regex_ports = re.compile(r'''
 9 (input|output)  #0
10 (\s+)           #1
11 (reg|wire|\s+)  #2
12 (\s+)           #3
13 (\[\w+\-1\:0\])?#4
14 (\s+)           #5
15 (\w+)           #6
16 ''',re.verbose);
17 
18 directory = os.getcwd()
19 #open the design file
20 file_design = input('please enter the file name:')
21 with open(directory+'/'+file_design,'r') as file_obj:
22   comment = file_obj.read()
23 
24 #regex match module name
25 module_obj = regex_module.search(comment)
26 print(module_obj.group())
27 #regex match ports name
28 groups_ports = regex_ports.findall(comment)
29 print('\nnumber of ports:',len(groups_ports))
30 
31 #write the instantiation templete to an assigned file
32 file_tb = input('please enter the top file name:')
33 with open(directory+'/'+file_tb,'a') as file_obj2:
34   if module_obj is not none:
35     file_obj2.write(module_obj.group(3)+' uut\n(\n')
36 
37     num = len(groups_ports)   
38     for i in range(num):
39       if i == num-1:
40         file_obj2.write('.'+groups_ports[i][6]+'  ()\n')
41       else:
42         file_obj2.write('.'+groups_ports[i][6]+'  (),\n')
43     file_obj2.write(');\n')

  python的文件读写非常简洁,使用with open打开可以确保在合适的时候自动关闭文件,防止数据受损丢失。为了保证代码通用性,使用os.getcwd获取当前脚本所在路径,这样改动路径时不需要再次修改代码即可照常运行。至于正则匹配在之前的博文:python中正则表达式与模式匹配 - 没落骑士 - 博客 https://www.cnblogs.com/moluoqishi/p/10825221.html 中已经描述的比较详尽了,这里不再赘述。有一点需要注意,search和findall返回的数据结构不同,依次是匹配对象和匹配内容列表。

三、运行结果

 最后我们来看下运行结果。命令行:

  设计源文件及写入文件:

                                               

  脚本正确生成设计模块的例化模板,后续再进一步优化。

《利用python自动生成verilog模块例化模板.doc》

下载本文的Word格式文档,以方便收藏与打印。