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