318
|
1 #!/usr/bin/python
|
|
2
|
319
|
3 """
|
334
|
4 Parser generator utility. This script can generate a python script from a
|
319
|
5 grammar description.
|
|
6
|
|
7 Invoke the script on a grammar specification file:
|
|
8
|
|
9 .. code::
|
|
10
|
|
11 $ ./yacc.py test.x -o test_parser.py
|
|
12
|
|
13 And use the generated parser by deriving a user class:
|
|
14
|
|
15
|
|
16 .. code::
|
|
17
|
|
18 import test_parser
|
|
19 class MyParser(test_parser.Parser):
|
|
20 pass
|
|
21 p = MyParser()
|
|
22 p.parse()
|
|
23
|
|
24
|
321
|
25 Alternatively you can load the parser on the fly:
|
|
26
|
|
27 .. code::
|
|
28
|
|
29 import yacc
|
|
30 parser_mod = yacc.load_as_module('mygrammar.x')
|
|
31 class MyParser(parser_mod.Parser):
|
|
32 pass
|
|
33 p = MyParser()
|
|
34 p.parse()
|
|
35
|
319
|
36 """
|
318
|
37
|
|
38 import argparse
|
|
39 import re
|
|
40 import sys
|
|
41 import datetime
|
321
|
42 import types
|
|
43 import io
|
323
|
44 import logging
|
334
|
45 from pyyacc import Grammar
|
318
|
46
|
|
47
|
|
48 class XaccLexer:
|
|
49 def __init__(self):
|
|
50 pass
|
|
51
|
|
52 def feed(self, txt):
|
|
53 # Create a regular expression for the lexing part:
|
|
54 tok_spec = [
|
|
55 ('ID', r'[A-Za-z][A-Za-z\d_]*'),
|
|
56 ('STRING', r"'[^']*'"),
|
|
57 ('BRACEDCODE', r"\{[^\}]*\}"),
|
|
58 ('OTHER', r'[:;\|]'),
|
|
59 ('SKIP', r'[ ]')
|
|
60 ]
|
|
61 tok_re = '|'.join('(?P<%s>%s)' % pair for pair in tok_spec)
|
|
62 gettok = re.compile(tok_re).match
|
|
63
|
|
64 lines = txt.split('\n')
|
|
65
|
|
66 def tokenize_line(line):
|
|
67 """ Generator that splits up a line into tokens """
|
|
68 mo = gettok(line)
|
|
69 pos = 0
|
|
70 while mo:
|
|
71 typ = mo.lastgroup
|
|
72 val = mo.group(typ)
|
|
73 if typ == 'ID':
|
|
74 yield (typ, val)
|
|
75 elif typ == 'STRING':
|
|
76 typ = 'ID'
|
|
77 yield (typ, val[1:-1])
|
|
78 elif typ == 'OTHER':
|
|
79 typ = val
|
|
80 yield (typ, val)
|
|
81 elif typ == 'BRACEDCODE':
|
|
82 yield (typ, val)
|
|
83 elif typ == 'SKIP':
|
|
84 pass
|
|
85 else:
|
|
86 raise NotImplementedError(str(typ))
|
|
87 pos = mo.end()
|
|
88 mo = gettok(line, pos)
|
|
89 if len(line) != pos:
|
|
90 raise ParseError('Lex fault at {}'.format(line))
|
|
91
|
|
92 def tokenize():
|
|
93 section = 0
|
|
94 for line in lines:
|
|
95 line = line.strip()
|
|
96 if not line:
|
|
97 continue # Skip empty lines
|
|
98 if line == '%%':
|
|
99 section += 1
|
|
100 yield('%%', '%%')
|
|
101 continue
|
|
102 if section == 0:
|
|
103 if line.startswith('%tokens'):
|
|
104 yield('%tokens', '%tokens')
|
|
105 yield from tokenize_line(line[7:])
|
|
106 else:
|
|
107 yield ('HEADER', line)
|
|
108 elif section == 1:
|
|
109 yield from tokenize_line(line)
|
|
110 yield ('eof', 'eof')
|
|
111 self.tokens = tokenize()
|
|
112 self.token = self.tokens.__next__()
|
|
113
|
|
114 def next_token(self):
|
|
115 t = self.token
|
|
116 if t[0] != 'eof':
|
|
117 self.token = self.tokens.__next__()
|
|
118 return t
|
|
119
|
|
120
|
|
121 class ParseError(Exception):
|
|
122 pass
|
|
123
|
|
124
|
|
125 class XaccParser:
|
|
126 """ Implements a recursive descent parser to parse grammar rules.
|
|
127 We could have made an generated parser, but that would yield a chicken
|
|
128 egg issue.
|
|
129 """
|
|
130 def __init__(self, lexer):
|
|
131 self.lexer = lexer
|
|
132
|
|
133 @property
|
|
134 def Peak(self):
|
|
135 """ Sneak peak to the next token in line """
|
|
136 return self.lexer.token[0]
|
|
137
|
|
138 def next_token(self):
|
|
139 """ Take the next token """
|
|
140 return self.lexer.next_token()
|
|
141
|
|
142 def consume(self, typ):
|
|
143 """ Eat next token of type typ or raise an exception """
|
|
144 if self.Peak == typ:
|
|
145 return self.next_token()
|
|
146 else:
|
|
147 raise ParseError('Expected {}, but got {}'.format(typ, self.Peak))
|
|
148
|
|
149 def has_consumed(self, typ):
|
|
150 """ Consume typ if possible and return true if so """
|
|
151 if self.Peak == typ:
|
|
152 self.consume(typ)
|
|
153 return True
|
|
154 return False
|
|
155
|
|
156 def parse_grammar(self):
|
|
157 """ Entry parse function into recursive descent parser """
|
|
158 # parse header
|
|
159 headers = []
|
|
160 terminals = []
|
|
161 while self.Peak in ['HEADER', '%tokens']:
|
|
162 if self.Peak == '%tokens':
|
|
163 self.consume('%tokens')
|
|
164 while self.Peak == 'ID':
|
|
165 terminals.append(self.consume('ID')[1])
|
|
166 else:
|
|
167 headers.append(self.consume('HEADER')[1])
|
|
168 self.consume('%%')
|
319
|
169 self.headers = headers
|
318
|
170 self.grammar = Grammar(terminals)
|
|
171 while self.Peak != 'eof':
|
|
172 self.parse_rule()
|
|
173 return self.grammar
|
|
174
|
|
175 def parse_symbol(self):
|
|
176 return self.consume('ID')[1]
|
|
177
|
|
178 def parse_rhs(self):
|
319
|
179 """ Parse the right hand side of a rule definition """
|
318
|
180 symbols = []
|
|
181 while self.Peak not in [';', 'BRACEDCODE', '|']:
|
|
182 symbols.append(self.parse_symbol())
|
|
183 if self.Peak == 'BRACEDCODE':
|
|
184 action = self.consume('BRACEDCODE')[1]
|
|
185 action = action[1:-1].strip()
|
|
186 else:
|
|
187 action = None
|
|
188 return symbols, action
|
|
189
|
|
190 def parse_rule(self):
|
319
|
191 """ Parse a rule definition """
|
318
|
192 p = self.parse_symbol()
|
|
193 self.consume(':')
|
|
194 symbols, action = self.parse_rhs()
|
|
195 self.grammar.add_production(p, symbols, action)
|
|
196 while self.has_consumed('|'):
|
|
197 symbols, action = self.parse_rhs()
|
|
198 self.grammar.add_production(p, symbols, action)
|
|
199 self.consume(';')
|
|
200
|
|
201
|
|
202 class XaccGenerator:
|
|
203 """ Generator that writes generated parser to file """
|
|
204 def __init__(self):
|
323
|
205 self.logger = logging.getLogger('yacc')
|
318
|
206
|
319
|
207 def generate(self, grammar, headers, output_file):
|
321
|
208 self.output_file = output_file
|
318
|
209 self.grammar = grammar
|
319
|
210 self.headers = headers
|
323
|
211 self.logger.info('Generating parser for grammar {}'.format(grammar))
|
318
|
212 self.action_table, self.goto_table = grammar.doGenerate()
|
321
|
213 self.generate_python_script()
|
318
|
214
|
321
|
215 def print(self, *args):
|
|
216 """ Print helper function that prints to output file """
|
|
217 print(*args, file=self.output_file)
|
|
218
|
|
219 def generate_python_script(self):
|
318
|
220 """ Generate python script with the parser table """
|
321
|
221 self.print('#!/usr/bin/python')
|
318
|
222 stamp = datetime.datetime.now().ctime()
|
321
|
223 self.print('""" Automatically generated by xacc on {} """'.format(stamp))
|
|
224 self.print('from pyyacc import LRParser, Reduce, Shift, Accept, Production, Grammar')
|
|
225 self.print('from ppci import Token')
|
|
226 self.print('')
|
319
|
227 for h in self.headers:
|
|
228 print(h, file=output_file)
|
321
|
229 self.print('')
|
|
230 self.print('class Parser(LRParser):')
|
|
231 self.print(' def __init__(self):')
|
318
|
232 # Generate rules:
|
321
|
233 self.print(' self.start_symbol = "{}"'.format(self.grammar.start_symbol))
|
|
234 self.print(' self.grammar = Grammar({})'.format(self.grammar.terminals))
|
318
|
235 for rule_number, rule in enumerate(self.grammar.productions):
|
|
236 rule.f_name = 'action_{}_{}'.format(rule.name, rule_number)
|
321
|
237 self.print(' self.grammar.add_production("{}", {}, self.{})'.format(rule.name, rule.symbols, rule.f_name))
|
318
|
238 # Fill action table:
|
321
|
239 self.print(' self.action_table = {}')
|
318
|
240 for state in self.action_table:
|
|
241 action = self.action_table[state]
|
321
|
242 self.print(' self.action_table[{}] = {}'.format(state, action))
|
|
243 self.print('')
|
318
|
244
|
|
245 # Fill goto table:
|
321
|
246 self.print(' self.goto_table = {}')
|
334
|
247 for state_number in self.goto_table:
|
|
248 to = self.goto_table[state_number]
|
|
249 self.print(' self.goto_table[{}] = {}'.format(state_number, to))
|
321
|
250 self.print('')
|
318
|
251
|
|
252 # Generate a function for each action:
|
|
253 for rule in self.grammar.productions:
|
334
|
254 num_symbols = len(rule.symbols)
|
|
255 args = ', '.join('arg{}'.format(n + 1) for n in range(num_symbols))
|
321
|
256 self.print(' def {}(self, {}):'.format(rule.f_name, args))
|
318
|
257 if rule.f == None:
|
|
258 semantics = 'pass'
|
|
259 else:
|
|
260 semantics = str(rule.f)
|
|
261 if semantics.strip() == '':
|
|
262 semantics = 'pass'
|
334
|
263 for n in range(num_symbols):
|
318
|
264 semantics = semantics.replace('${}'.format(n + 1), 'arg{}'.format(n + 1))
|
321
|
265 self.print(' {}'.format(semantics))
|
322
|
266 self.print('')
|
318
|
267
|
|
268
|
321
|
269 def make_argument_parser():
|
318
|
270 # Parse arguments:
|
|
271 parser = argparse.ArgumentParser(description='xacc compiler compiler')
|
|
272 parser.add_argument('source', type=argparse.FileType('r'), \
|
|
273 help='the parser specification')
|
|
274 parser.add_argument('-o', '--output', type=argparse.FileType('w'), \
|
|
275 default=sys.stdout)
|
322
|
276 return parser
|
321
|
277
|
|
278
|
|
279 def load_as_module(filename):
|
|
280 """ Load a parser spec file, generate LR tables and create module """
|
|
281 ob = io.StringIO()
|
|
282 args = argparse.Namespace(source=open(filename), output=ob)
|
|
283 main(args)
|
|
284
|
|
285 parser_mod = types.ModuleType('generated_parser')
|
|
286 exec(ob.getvalue(), parser_mod.__dict__)
|
|
287 return parser_mod
|
|
288
|
|
289 def main(args):
|
318
|
290 src = args.source.read()
|
|
291 args.source.close()
|
|
292
|
|
293 # Construction of generator parts:
|
|
294 lexer = XaccLexer()
|
|
295 parser = XaccParser(lexer)
|
|
296 generator = XaccGenerator()
|
|
297
|
|
298 # Sequence source through the generator parts:
|
|
299 lexer.feed(src)
|
|
300 grammar = parser.parse_grammar()
|
319
|
301 generator.generate(grammar, parser.headers, args.output)
|
318
|
302
|
|
303
|
|
304 if __name__ == '__main__':
|
321
|
305 args = make_argument_parser().parse_args()
|
|
306 main(args)
|