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