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