systemc-clang 2.0.0
Parsing SystemC constructs
Loading...
Searching...
No Matches
utils.py
Go to the documentation of this file.
1"""Utility library"""
2from inspect import currentframe, getframeinfo, stack
3import os
4from lark import Tree
5
6def tidify(verilog, current_indent = 0, indent_width = 2):
7 """makes the generated verilog looks a bit better, may be subject to changes later"""
8 add_indent_pattern = re.compile(r'(^(module|if|always|for|case)|(\: begin))')
9 sub_indent_pattern = re.compile(r'^(endmodule|end)')
10 sub_add_indent_pattern = re.compile(r'^(\‍)\;|end else begin)')
11 res = []
12 for l in verilog.splitlines():
13 if add_indent_pattern.search(l):
14 s = ' ' * (current_indent) + l
15 current_indent += indent_width
16 elif sub_add_indent_pattern.search(l):
17 s = ' ' * (current_indent - indent_width) + l
18 elif sub_indent_pattern.search(l):
19 current_indent -= indent_width
20 s = ' ' * (current_indent) + l
21 else:
22 s = ' ' * current_indent + l
23 # print(s)
24 res.append(s)
25
26 return '\n'.join(res)
27
28
29debug = True
30def p(decorated):
31 """a decorator that helps printing out the transformation results"""
32 if debug:
33 def wrapper(self, args):
34 print(f'[DBG] {decorated.__name__}: \n{args} \n\n')
35 res = decorated(self, args)
36 print(f'[DBG] returns: {res}\n')
37 return res
38 return wrapper
39 else:
40 return decorated
41
42
43def dprint(*arg, **kwargs):
44 """debug utility for printing, prints line number"""
45 frameinfo = currentframe()
46 caller = getframeinfo(stack()[1][0])
47 print(os.path.basename(caller.filename), ': L', frameinfo.f_back.f_lineno, ":", "\u001b[31m", *arg, "\u001b[0m", **kwargs)
48
49
50def is_tree_type(t, name):
51 """Check whether t is lark Tree and whether the tree type is name"""
52 return isinstance(t, Tree) and t.data == name
53
54
55def is_tree_types(t, names):
56 """Check whether t is lark Tree and whether the tree type is name"""
57 if not isinstance(names, list):
58 raise ValueError('name argument should be list')
59 return isinstance(t, Tree) and t.data in names
60
61
62def get_ids_in_tree(tree):
63 """get all ids"""
64 __id_types = ['hvarref']
65 if not isinstance(tree, Tree):
66 raise ValueError('Only Tree type is accepted')
67 res = []
68 for t in tree.iter_subtrees():
69 if is_tree_types(t, __id_types):
70 assert t.children[0], 'hvarref should only contain one children'
71 res.append(t.children[0])
72 return res
73
74
75def get_ids_in_tree_dfs(tree):
76 """get all ids"""
77 # __id_types = ['hvarref']
78 # if not isinstance(tree, Tree):
79 # raise ValueError('Only Tree type is accepted')
80 # res = []
81 # for t in tree.iter_subtrees():
82 # if is_tree_types(t, __id_types):
83 # assert t.children[0], 'hvarref should only contain one children'
84 # res.append(t.children[0])
85 # return res
86
87 res = []
88 dfs_stack = list()
89 dfs_stack.append(tree)
90 i = 0
91 while len(dfs_stack) != 0:
92 t = dfs_stack.pop(0)
93 for idx in range(len(t.children)):
94 nxt = t.children[idx]
95 if isinstance(nxt, Tree):
96 dfs_stack.append(nxt)
97 elif is_tree_types(t, __id_types):
98 assert t.children[0], 'hvarref should only contain one children'
99 res.append(t.children[0])
100 return res
101
102
103def set_ids_in_tree_dfs(tree, ids):
104 __id_types = ['hvarref']
105 dfs_stack = list()
106 dfs_stack.append(tree)
107 i = 0
108 while len(dfs_stack) != 0:
109 t = dfs_stack.pop(0)
110 for idx in range(len(t.children)):
111 nxt = t.children[idx]
112 if isinstance(nxt, Tree):
113 dfs_stack.append(nxt)
114 elif is_tree_types(t, __id_types):
115 t.children[idx] = ids[i](t.children[idx])
116 i += 1
117
118
119def alternate_ids(tree, ops):
120 """Change the ids within a tree, given operations ops as an array of lambdas"""
121 ids = get_ids_in_tree(tree)
122 if len(ops) != len(ids):
123 raise ValueError('ops should have the same length as ids')
124 for idx, _ in enumerate(ids):
125 ops[idx](ids[idx])
126
tidify(verilog, current_indent=0, indent_width=2)
Definition utils.py:6