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:
|
368
|
102 for tk in baselex.tokenize(tok_spec, line):
|
|
103 yield tk
|
319
|
104 yield Token(EOF, EOF)
|
318
|
105 self.tokens = tokenize()
|
|
106 self.token = self.tokens.__next__()
|
|
107
|
|
108 def next_token(self):
|
|
109 t = self.token
|
319
|
110 if t.typ != EOF:
|
318
|
111 self.token = self.tokens.__next__()
|
|
112 return t
|
|
113
|
|
114
|
319
|
115 class Rule:
|
320
|
116 """ A rewrite rule. Specifies a tree that can be rewritten into a result
|
|
117 at a specific cost """
|
357
|
118 def __init__(self, non_term, tree, cost, acceptance, template):
|
319
|
119 self.non_term = non_term
|
|
120 self.tree = tree
|
|
121 self.cost = cost
|
357
|
122 self.acceptance = acceptance
|
319
|
123 self.template = template
|
|
124 self.nr = 0
|
|
125
|
|
126 def __repr__(self):
|
|
127 return '{} -> {} ${}'.format(self.non_term, self.tree, self.cost)
|
|
128
|
|
129
|
|
130 class Symbol:
|
|
131 def __init__(self, name):
|
|
132 self.name = name
|
|
133
|
|
134
|
|
135 class Term(Symbol):
|
|
136 pass
|
|
137
|
|
138
|
|
139 class Nonterm(Symbol):
|
|
140 def __init__(self, name):
|
|
141 super().__init__(name)
|
320
|
142 self.chain_rules = []
|
319
|
143
|
|
144
|
|
145 class BurgSystem:
|
|
146 def __init__(self):
|
|
147 self.rules = []
|
|
148 self.symbols = {}
|
|
149 self.goal = None
|
|
150
|
|
151 def symType(self, t):
|
|
152 return (s.name for s in self.symbols.values() if type(s) is t)
|
|
153
|
|
154 terminals = property(lambda s: s.symType(Term))
|
|
155
|
|
156 non_terminals = property(lambda s: s.symType(Nonterm))
|
|
157
|
357
|
158 def add_rule(self, non_term, tree, cost, acceptance, template):
|
|
159 template = template.strip()
|
320
|
160 if not template:
|
|
161 template = 'pass'
|
357
|
162 rule = Rule(non_term, tree, cost, acceptance, template)
|
320
|
163 if len(tree.children) == 0 and tree.name not in self.terminals:
|
|
164 self.non_term(tree.name).chain_rules.append(rule)
|
319
|
165 self.non_term(rule.non_term)
|
|
166 self.rules.append(rule)
|
|
167 rule.nr = len(self.rules)
|
|
168
|
|
169 def non_term(self, name):
|
|
170 if name in self.terminals:
|
|
171 raise BurgError('Cannot redefine terminal')
|
|
172 if not self.goal:
|
|
173 self.goal = name
|
320
|
174 return self.install(name, Nonterm)
|
319
|
175
|
|
176 def tree(self, name, *args):
|
|
177 return Tree(name, *args)
|
|
178
|
|
179 def install(self, name, t):
|
|
180 assert type(name) is str
|
|
181 if name in self.symbols:
|
|
182 assert type(self.symbols[name]) is t
|
|
183 else:
|
|
184 self.symbols[name] = t(name)
|
320
|
185 return self.symbols[name]
|
319
|
186
|
|
187 def add_terminal(self, terminal):
|
|
188 self.install(terminal, Term)
|
|
189
|
|
190
|
|
191 class BurgError(Exception):
|
|
192 pass
|
|
193
|
|
194
|
318
|
195 class BurgParser(burg_parser.Parser):
|
319
|
196 """ Derived from automatically generated parser """
|
|
197 def parse(self, l):
|
|
198 self.system = BurgSystem()
|
|
199 super().parse(l)
|
|
200 return self.system
|
|
201
|
|
202
|
|
203 class BurgGenerator:
|
|
204 def print(self, *args):
|
|
205 """ Print helper function that prints to output file """
|
|
206 print(*args, file=self.output_file)
|
|
207
|
|
208 def generate(self, system, output_file):
|
|
209 """ Generate script that implements the burg spec """
|
|
210 self.output_file = output_file
|
|
211 self.system = system
|
|
212
|
|
213 self.print('#!/usr/bin/python')
|
|
214 self.print('from tree import Tree, BaseMatcher, State')
|
322
|
215 for header in self.system.header_lines:
|
|
216 self.print(header)
|
319
|
217 self.print()
|
|
218 self.print('class Matcher(BaseMatcher):')
|
320
|
219 self.print(' def __init__(self):')
|
|
220 self.print(' self.kid_functions = {}')
|
|
221 self.print(' self.nts_map = {}')
|
|
222 self.print(' self.pat_f = {}')
|
319
|
223 for rule in self.system.rules:
|
|
224 kids, dummy = self.compute_kids(rule.tree, 't')
|
320
|
225 rule.num_nts = len(dummy)
|
319
|
226 lf = 'lambda t: [{}]'.format(', '.join(kids), rule)
|
320
|
227 pf = 'self.P{}'.format(rule.nr)
|
|
228 self.print(' # {}: {}'.format(rule.nr, rule))
|
|
229 self.print(' self.kid_functions[{}] = {}'.format(rule.nr, lf))
|
|
230 self.print(' self.nts_map[{}] = {}'.format(rule.nr, dummy))
|
|
231 self.print(' self.pat_f[{}] = {}'.format(rule.nr, pf))
|
|
232 self.print()
|
|
233 for rule in self.system.rules:
|
|
234 if rule.num_nts > 0:
|
357
|
235 args = ', '.join('c{}'.format(x) for x in range(rule.num_nts))
|
|
236 args = ', ' + args
|
320
|
237 else:
|
|
238 args = ''
|
357
|
239 # Create template function:
|
322
|
240 self.print(' def P{}(self, tree{}):'.format(rule.nr, args))
|
|
241 template = rule.template
|
|
242 for t in template.split(';'):
|
|
243 self.print(' {}'.format(t.strip()))
|
357
|
244 # Create acceptance function:
|
|
245 if rule.acceptance:
|
|
246 self.print(' def A{}(self, tree):'.format(rule.nr))
|
|
247 for t in rule.acceptance.split(';'):
|
|
248 self.print(' {}'.format(t.strip()))
|
319
|
249 self.emit_state()
|
320
|
250 self.print(' def gen(self, tree):')
|
|
251 self.print(' self.burm_label(tree)')
|
|
252 self.print(' if not tree.state.has_goal("{}"):'.format(self.system.goal))
|
357
|
253 self.print(' raise Exception("Tree {} not covered".format(tree))')
|
323
|
254 self.print(' return self.apply_rules(tree, "{}")'.format(self.system.goal))
|
319
|
255
|
|
256 def emit_record(self, rule, state_var):
|
|
257 # TODO: check for rules fullfilled (by not using 999999)
|
357
|
258 acc = ''
|
|
259 if rule.acceptance:
|
|
260 acc = ' and self.A{}(tree)'.format(rule.nr)
|
322
|
261 self.print(' nts = self.nts({})'.format(rule.nr))
|
|
262 self.print(' kids = self.kids(tree, {})'.format(rule.nr))
|
357
|
263 self.print(' if all(x.state.has_goal(y) for x, y in zip(kids, nts)){}:'.format(acc))
|
354
|
264 self.print(' c = sum(x.state.get_cost(y) for x, y in zip(kids, nts)) + {}'.format(rule.cost))
|
|
265 self.print(' tree.state.set_cost("{}", c, {})'.format(rule.non_term, rule.nr))
|
320
|
266 for cr in self.system.symbols[rule.non_term].chain_rules:
|
354
|
267 self.print(' # Chain rule: {}'.format(cr))
|
|
268 self.print(' tree.state.set_cost("{}", c + {}, {})'.format(cr.non_term, cr.cost, cr.nr))
|
319
|
269
|
|
270 def emit_state(self):
|
|
271 """ Emit a function that assigns a new state to a node """
|
320
|
272 self.print(' def burm_state(self, tree):')
|
322
|
273 self.print(' tree.state = State()')
|
319
|
274 for term in self.system.terminals:
|
|
275 self.emitcase(term)
|
|
276 self.print()
|
|
277
|
|
278 def emitcase(self, term):
|
|
279 rules = [rule for rule in self.system.rules if rule.tree.name == term]
|
|
280 for rule in rules:
|
|
281 condition = self.emittest(rule.tree, 'tree')
|
322
|
282 self.print(' if {}:'.format(condition))
|
319
|
283 self.emit_record(rule, 'state')
|
|
284
|
|
285 def compute_kids(self, t, root_name):
|
|
286 """ Compute of a pattern the blanks that must be provided from below in the tree """
|
|
287 if t.name in self.system.non_terminals:
|
|
288 return [root_name], [t.name]
|
|
289 else:
|
|
290 k = []
|
|
291 nts = []
|
|
292 for i, c in enumerate(t.children):
|
|
293 pfx = root_name + '.children[{}]'.format(i)
|
|
294 kf, dummy = self.compute_kids(c, pfx)
|
|
295 nts.extend(dummy)
|
|
296 k.extend(kf)
|
|
297 return k, nts
|
|
298
|
|
299
|
|
300 def emittest(self, tree, prefix):
|
|
301 """ Generate condition for a tree pattern """
|
|
302 ct = (c for c in tree.children if c.name not in self.system.non_terminals)
|
|
303 child_tests = (self.emittest(c, prefix + '.children[{}]'.format(i)) for i, c in enumerate(ct))
|
|
304 child_tests = ('({})'.format(ct) for ct in child_tests)
|
|
305 child_tests = ' and '.join(child_tests)
|
|
306 child_tests = ' and ' + child_tests if child_tests else ''
|
|
307 tst = '{}.name == "{}"'.format(prefix, tree.name)
|
|
308 return tst + child_tests
|
318
|
309
|
|
310
|
321
|
311 def make_argument_parser():
|
|
312 """ Constructs an argument parser """
|
318
|
313 parser = argparse.ArgumentParser(description='pyburg bottom up rewrite system generator compiler compiler')
|
|
314 parser.add_argument('source', type=argparse.FileType('r'), \
|
|
315 help='the parser specification')
|
|
316 parser.add_argument('-o', '--output', type=argparse.FileType('w'), \
|
|
317 default=sys.stdout)
|
321
|
318 return parser
|
|
319
|
322
|
320 def load_as_module(filename):
|
|
321 """ Load a parser spec file, generate LR tables and create module """
|
|
322 ob = io.StringIO()
|
|
323 args = argparse.Namespace(source=open(filename), output=ob)
|
|
324 main(args)
|
|
325
|
|
326 matcher_mod = types.ModuleType('generated_matcher')
|
|
327 exec(ob.getvalue(), matcher_mod.__dict__)
|
|
328 return matcher_mod
|
|
329
|
321
|
330
|
|
331 def main(args):
|
318
|
332 src = args.source.read()
|
|
333 args.source.close()
|
|
334
|
319
|
335 # Parse specification into burgsystem:
|
318
|
336 l = BurgLexer()
|
|
337 p = BurgParser()
|
|
338 l.feed(src)
|
319
|
339 burg_system = p.parse(l)
|
|
340
|
|
341 # Generate matcher:
|
|
342 generator = BurgGenerator()
|
|
343 generator.generate(burg_system, args.output)
|
318
|
344
|
321
|
345
|
318
|
346 if __name__ == '__main__':
|
321
|
347 # Parse arguments:
|
|
348 args = make_argument_parser().parse_args()
|
|
349 main(args)
|