318
|
1 #!/usr/bin/python
|
|
2
|
319
|
3 """
|
|
4 Bottom up rewrite generator.
|
|
5
|
|
6 This script takes as input a description of patterns and outputs a
|
|
7 matcher class that can match trees given the patterns.
|
|
8
|
|
9 Patterns are specified as follows:
|
|
10 reg -> ADDI32(reg, reg) 2 (. add $1 $2 .)
|
|
11 reg -> MULI32(reg, reg) 3 (. .)
|
|
12 or a multiply add:
|
|
13 reg -> ADDI32(MULI32(reg, reg), reg) 4 (. muladd $1, $2, $3 .)
|
|
14 The general specification pattern is:
|
|
15 [result] -> [tree] [cost] [template code]
|
|
16
|
|
17 A tree is described using parenthesis notation. For example a node X with
|
|
18 three
|
|
19 child nodes is described as:
|
|
20 X(a, b, b)
|
|
21 Trees can be nested:
|
|
22 X(Y(a, a), a)
|
|
23 The 'a' in the example above indicates an open connection to a next tree
|
|
24 pattern.
|
|
25
|
320
|
26 In the example above 'reg' is a non-terminal. ADDI32 is a terminal. non-terminals
|
|
27 cannot have child nodes. A special case occurs in this case:
|
|
28 reg -> rc
|
|
29 where 'rc' is a non-terminal. This is an example of a chain rule. Chain rules
|
|
30 can be used to allow several variants of non-terminals.
|
|
31
|
319
|
32 The generated matcher uses dynamic programming to find the best match of the
|
|
33 tree. This strategy consists of two steps:
|
|
34 - label: During this phase the given tree is traversed in a bottom up way.
|
|
35 each node is labelled with a possible matching rule and the corresponding cost.
|
|
36 - select: In this step, the tree is traversed again, selecting at each point
|
|
37 the cheapest way to get to the goal.
|
|
38
|
|
39 """
|
|
40
|
318
|
41 import sys
|
|
42 import argparse
|
|
43 from ppci import Token
|
319
|
44 import burg_parser # Automatically generated
|
|
45 from pyyacc import ParserException, EOF
|
|
46 import baselex
|
|
47 from tree import Tree
|
318
|
48
|
|
49
|
|
50 class BurgLexer:
|
|
51 def feed(self, txt):
|
|
52 tok_spec = [
|
319
|
53 ('id', r'[A-Za-z][A-Za-z\d_]*', lambda typ, val: (typ, val)),
|
|
54 ('kw', r'%[A-Za-z][A-Za-z\d_]*', lambda typ, val: (val, val)),
|
|
55 ('number', r'\d+', lambda typ, val: (typ, int(val))),
|
|
56 ('STRING', r"'[^']*'", lambda typ, val: ('id', val[1:-1])),
|
|
57 ('template', r"\(\..*\.\)", lambda typ, val: (typ, val)),
|
|
58 ('OTHER', r'[:;\|\(\),]', lambda typ, val: (val, val)),
|
|
59 ('SKIP', r'[ ]', None)
|
318
|
60 ]
|
|
61
|
|
62 lines = txt.split('\n')
|
|
63
|
|
64 def tokenize():
|
|
65 for line in lines:
|
|
66 line = line.strip()
|
|
67 if not line:
|
|
68 continue # Skip empty lines
|
319
|
69 elif line == '%%':
|
318
|
70 yield Token('%%', '%%')
|
319
|
71 else:
|
|
72 yield from baselex.tokenize(tok_spec, line)
|
|
73 yield Token(EOF, EOF)
|
318
|
74 self.tokens = tokenize()
|
|
75 self.token = self.tokens.__next__()
|
|
76
|
|
77 def next_token(self):
|
|
78 t = self.token
|
319
|
79 if t.typ != EOF:
|
318
|
80 self.token = self.tokens.__next__()
|
|
81 return t
|
|
82
|
|
83
|
319
|
84 class Rule:
|
320
|
85 """ A rewrite rule. Specifies a tree that can be rewritten into a result
|
|
86 at a specific cost """
|
319
|
87 def __init__(self, non_term, tree, cost, template):
|
|
88 self.non_term = non_term
|
|
89 self.tree = tree
|
|
90 self.cost = cost
|
|
91 self.template = template
|
|
92 self.nr = 0
|
|
93
|
|
94 def __repr__(self):
|
|
95 return '{} -> {} ${}'.format(self.non_term, self.tree, self.cost)
|
|
96
|
|
97
|
|
98 class Symbol:
|
|
99 def __init__(self, name):
|
|
100 self.name = name
|
|
101
|
|
102
|
|
103 class Term(Symbol):
|
|
104 pass
|
|
105
|
|
106
|
|
107 class Nonterm(Symbol):
|
|
108 def __init__(self, name):
|
|
109 super().__init__(name)
|
320
|
110 self.chain_rules = []
|
319
|
111
|
|
112
|
|
113 class BurgSystem:
|
|
114 def __init__(self):
|
|
115 self.rules = []
|
|
116 self.symbols = {}
|
|
117 self.goal = None
|
|
118
|
|
119 def symType(self, t):
|
|
120 return (s.name for s in self.symbols.values() if type(s) is t)
|
|
121
|
|
122 terminals = property(lambda s: s.symType(Term))
|
|
123
|
|
124 non_terminals = property(lambda s: s.symType(Nonterm))
|
|
125
|
|
126 def add_rule(self, non_term, tree, cost, template):
|
320
|
127 template = template[2:-2].strip()
|
|
128 if not template:
|
|
129 template = 'pass'
|
319
|
130 rule = Rule(non_term, tree, cost, template)
|
320
|
131 if len(tree.children) == 0 and tree.name not in self.terminals:
|
|
132 print('chain:', rule)
|
|
133 self.non_term(tree.name).chain_rules.append(rule)
|
319
|
134 self.non_term(rule.non_term)
|
|
135 self.rules.append(rule)
|
|
136 rule.nr = len(self.rules)
|
|
137
|
|
138 def non_term(self, name):
|
|
139 if name in self.terminals:
|
|
140 raise BurgError('Cannot redefine terminal')
|
|
141 if not self.goal:
|
|
142 self.goal = name
|
320
|
143 return self.install(name, Nonterm)
|
319
|
144
|
|
145 def tree(self, name, *args):
|
|
146 return Tree(name, *args)
|
|
147
|
|
148 def install(self, name, t):
|
|
149 assert type(name) is str
|
|
150 if name in self.symbols:
|
|
151 assert type(self.symbols[name]) is t
|
|
152 else:
|
|
153 self.symbols[name] = t(name)
|
320
|
154 return self.symbols[name]
|
319
|
155
|
|
156 def add_terminal(self, terminal):
|
|
157 self.install(terminal, Term)
|
|
158
|
|
159
|
|
160 class BurgError(Exception):
|
|
161 pass
|
|
162
|
|
163
|
318
|
164 class BurgParser(burg_parser.Parser):
|
319
|
165 """ Derived from automatically generated parser """
|
|
166 def parse(self, l):
|
|
167 self.system = BurgSystem()
|
|
168 super().parse(l)
|
|
169 return self.system
|
|
170
|
|
171
|
|
172 class BurgGenerator:
|
|
173 def print(self, *args):
|
|
174 """ Print helper function that prints to output file """
|
|
175 print(*args, file=self.output_file)
|
|
176
|
|
177 def generate(self, system, output_file):
|
|
178 """ Generate script that implements the burg spec """
|
|
179 self.output_file = output_file
|
|
180 self.system = system
|
|
181
|
|
182 self.print('#!/usr/bin/python')
|
|
183 self.print('from tree import Tree, BaseMatcher, State')
|
|
184 self.print()
|
|
185 self.print('class Matcher(BaseMatcher):')
|
320
|
186 self.print(' def __init__(self):')
|
|
187 self.print(' self.kid_functions = {}')
|
|
188 self.print(' self.nts_map = {}')
|
|
189 self.print(' self.pat_f = {}')
|
319
|
190 for rule in self.system.rules:
|
|
191 kids, dummy = self.compute_kids(rule.tree, 't')
|
320
|
192 rule.num_nts = len(dummy)
|
319
|
193 lf = 'lambda t: [{}]'.format(', '.join(kids), rule)
|
320
|
194 pf = 'self.P{}'.format(rule.nr)
|
|
195 self.print(' # {}: {}'.format(rule.nr, rule))
|
|
196 self.print(' self.kid_functions[{}] = {}'.format(rule.nr, lf))
|
|
197 self.print(' self.nts_map[{}] = {}'.format(rule.nr, dummy))
|
|
198 self.print(' self.pat_f[{}] = {}'.format(rule.nr, pf))
|
|
199 self.print()
|
|
200 for rule in self.system.rules:
|
|
201 if rule.num_nts > 0:
|
|
202 args = ', ' + ', '.join('nt{}'.format(x) for x in range(rule.num_nts))
|
|
203 else:
|
|
204 args = ''
|
|
205 self.print(' def P{}(self{}):'.format(rule.nr, args))
|
|
206 self.print(' {}'.format(rule.template))
|
319
|
207 self.emit_state()
|
320
|
208 self.print(' def gen(self, tree):')
|
|
209 self.print(' self.burm_label(tree)')
|
|
210 self.print(' if not tree.state.has_goal("{}"):'.format(self.system.goal))
|
|
211 self.print(' raise Exception("Tree not covered")')
|
|
212 self.print(' self.apply_rules(tree, "{}")'.format(self.system.goal))
|
319
|
213
|
|
214 def emit_record(self, rule, state_var):
|
|
215 # TODO: check for rules fullfilled (by not using 999999)
|
|
216 self.print(' nts = self.nts({})'.format(rule.nr))
|
|
217 self.print(' kids = self.kids(tree, {})'.format(rule.nr))
|
|
218 self.print(' c = sum(x.state.get_cost(y) for x, y in zip(kids, nts)) + {}'.format(rule.cost))
|
|
219 self.print(' tree.state.set_cost("{}", c, {})'.format(rule.non_term, rule.nr))
|
320
|
220 for cr in self.system.symbols[rule.non_term].chain_rules:
|
|
221 self.print(' # Chain rule: {}'.format(cr))
|
|
222 self.print(' tree.state.set_cost("{}", c + {}, {})'.format(cr.non_term, cr.cost, cr.nr))
|
319
|
223
|
|
224 def emit_state(self):
|
|
225 """ Emit a function that assigns a new state to a node """
|
320
|
226 self.print(' def burm_state(self, tree):')
|
|
227 self.print(' tree.state = State()')
|
319
|
228 for term in self.system.terminals:
|
|
229 self.emitcase(term)
|
|
230 self.print()
|
|
231
|
|
232 def emitcase(self, term):
|
|
233 rules = [rule for rule in self.system.rules if rule.tree.name == term]
|
|
234 for rule in rules:
|
|
235 condition = self.emittest(rule.tree, 'tree')
|
320
|
236 self.print(' if {}:'.format(condition))
|
319
|
237 self.emit_record(rule, 'state')
|
|
238
|
|
239 def compute_kids(self, t, root_name):
|
|
240 """ Compute of a pattern the blanks that must be provided from below in the tree """
|
|
241 if t.name in self.system.non_terminals:
|
|
242 return [root_name], [t.name]
|
|
243 else:
|
|
244 k = []
|
|
245 nts = []
|
|
246 for i, c in enumerate(t.children):
|
|
247 pfx = root_name + '.children[{}]'.format(i)
|
|
248 kf, dummy = self.compute_kids(c, pfx)
|
|
249 nts.extend(dummy)
|
|
250 k.extend(kf)
|
|
251 return k, nts
|
|
252
|
|
253
|
|
254 def emittest(self, tree, prefix):
|
|
255 """ Generate condition for a tree pattern """
|
|
256 ct = (c for c in tree.children if c.name not in self.system.non_terminals)
|
|
257 child_tests = (self.emittest(c, prefix + '.children[{}]'.format(i)) for i, c in enumerate(ct))
|
|
258 child_tests = ('({})'.format(ct) for ct in child_tests)
|
|
259 child_tests = ' and '.join(child_tests)
|
|
260 child_tests = ' and ' + child_tests if child_tests else ''
|
|
261 tst = '{}.name == "{}"'.format(prefix, tree.name)
|
|
262 return tst + child_tests
|
318
|
263
|
|
264
|
|
265 def main():
|
|
266 # Parse arguments:
|
|
267 parser = argparse.ArgumentParser(description='pyburg bottom up rewrite system generator compiler compiler')
|
|
268 parser.add_argument('source', type=argparse.FileType('r'), \
|
|
269 help='the parser specification')
|
|
270 parser.add_argument('-o', '--output', type=argparse.FileType('w'), \
|
|
271 default=sys.stdout)
|
|
272 args = parser.parse_args()
|
|
273 src = args.source.read()
|
|
274 args.source.close()
|
|
275
|
319
|
276 # Parse specification into burgsystem:
|
318
|
277 l = BurgLexer()
|
|
278 p = BurgParser()
|
|
279 l.feed(src)
|
319
|
280 burg_system = p.parse(l)
|
|
281
|
|
282 # Generate matcher:
|
|
283 generator = BurgGenerator()
|
|
284 generator.generate(burg_system, args.output)
|
318
|
285
|
|
286 if __name__ == '__main__':
|
|
287 main()
|