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')
|
368
|
105 for tk in tokenize_line(line[7:]):
|
|
106 yield tk
|
318
|
107 else:
|
|
108 yield ('HEADER', line)
|
|
109 elif section == 1:
|
368
|
110 for tk in tokenize_line(line):
|
|
111 yield tk
|
318
|
112 yield ('eof', 'eof')
|
|
113 self.tokens = tokenize()
|
|
114 self.token = self.tokens.__next__()
|
|
115
|
|
116 def next_token(self):
|
|
117 t = self.token
|
|
118 if t[0] != 'eof':
|
|
119 self.token = self.tokens.__next__()
|
|
120 return t
|
|
121
|
|
122
|
|
123 class ParseError(Exception):
|
|
124 pass
|
|
125
|
|
126
|
|
127 class XaccParser:
|
|
128 """ Implements a recursive descent parser to parse grammar rules.
|
|
129 We could have made an generated parser, but that would yield a chicken
|
|
130 egg issue.
|
|
131 """
|
|
132 def __init__(self, lexer):
|
|
133 self.lexer = lexer
|
|
134
|
|
135 @property
|
|
136 def Peak(self):
|
|
137 """ Sneak peak to the next token in line """
|
|
138 return self.lexer.token[0]
|
|
139
|
|
140 def next_token(self):
|
|
141 """ Take the next token """
|
|
142 return self.lexer.next_token()
|
|
143
|
|
144 def consume(self, typ):
|
|
145 """ Eat next token of type typ or raise an exception """
|
|
146 if self.Peak == typ:
|
|
147 return self.next_token()
|
|
148 else:
|
|
149 raise ParseError('Expected {}, but got {}'.format(typ, self.Peak))
|
|
150
|
|
151 def has_consumed(self, typ):
|
|
152 """ Consume typ if possible and return true if so """
|
|
153 if self.Peak == typ:
|
|
154 self.consume(typ)
|
|
155 return True
|
|
156 return False
|
|
157
|
|
158 def parse_grammar(self):
|
|
159 """ Entry parse function into recursive descent parser """
|
|
160 # parse header
|
|
161 headers = []
|
|
162 terminals = []
|
|
163 while self.Peak in ['HEADER', '%tokens']:
|
|
164 if self.Peak == '%tokens':
|
|
165 self.consume('%tokens')
|
|
166 while self.Peak == 'ID':
|
|
167 terminals.append(self.consume('ID')[1])
|
|
168 else:
|
|
169 headers.append(self.consume('HEADER')[1])
|
|
170 self.consume('%%')
|
319
|
171 self.headers = headers
|
318
|
172 self.grammar = Grammar(terminals)
|
|
173 while self.Peak != 'eof':
|
|
174 self.parse_rule()
|
|
175 return self.grammar
|
|
176
|
|
177 def parse_symbol(self):
|
|
178 return self.consume('ID')[1]
|
|
179
|
|
180 def parse_rhs(self):
|
319
|
181 """ Parse the right hand side of a rule definition """
|
318
|
182 symbols = []
|
|
183 while self.Peak not in [';', 'BRACEDCODE', '|']:
|
|
184 symbols.append(self.parse_symbol())
|
|
185 if self.Peak == 'BRACEDCODE':
|
|
186 action = self.consume('BRACEDCODE')[1]
|
|
187 action = action[1:-1].strip()
|
|
188 else:
|
|
189 action = None
|
|
190 return symbols, action
|
|
191
|
|
192 def parse_rule(self):
|
319
|
193 """ Parse a rule definition """
|
318
|
194 p = self.parse_symbol()
|
|
195 self.consume(':')
|
|
196 symbols, action = self.parse_rhs()
|
|
197 self.grammar.add_production(p, symbols, action)
|
|
198 while self.has_consumed('|'):
|
|
199 symbols, action = self.parse_rhs()
|
|
200 self.grammar.add_production(p, symbols, action)
|
|
201 self.consume(';')
|
|
202
|
|
203
|
|
204 class XaccGenerator:
|
|
205 """ Generator that writes generated parser to file """
|
|
206 def __init__(self):
|
323
|
207 self.logger = logging.getLogger('yacc')
|
318
|
208
|
319
|
209 def generate(self, grammar, headers, output_file):
|
321
|
210 self.output_file = output_file
|
318
|
211 self.grammar = grammar
|
319
|
212 self.headers = headers
|
323
|
213 self.logger.info('Generating parser for grammar {}'.format(grammar))
|
340
|
214 self.action_table, self.goto_table = grammar.generate_tables()
|
321
|
215 self.generate_python_script()
|
318
|
216
|
321
|
217 def print(self, *args):
|
|
218 """ Print helper function that prints to output file """
|
|
219 print(*args, file=self.output_file)
|
|
220
|
|
221 def generate_python_script(self):
|
318
|
222 """ Generate python script with the parser table """
|
321
|
223 self.print('#!/usr/bin/python')
|
318
|
224 stamp = datetime.datetime.now().ctime()
|
321
|
225 self.print('""" Automatically generated by xacc on {} """'.format(stamp))
|
|
226 self.print('from pyyacc import LRParser, Reduce, Shift, Accept, Production, Grammar')
|
|
227 self.print('from ppci import Token')
|
|
228 self.print('')
|
319
|
229 for h in self.headers:
|
|
230 print(h, file=output_file)
|
321
|
231 self.print('')
|
|
232 self.print('class Parser(LRParser):')
|
|
233 self.print(' def __init__(self):')
|
318
|
234 # Generate rules:
|
321
|
235 self.print(' self.start_symbol = "{}"'.format(self.grammar.start_symbol))
|
|
236 self.print(' self.grammar = Grammar({})'.format(self.grammar.terminals))
|
318
|
237 for rule_number, rule in enumerate(self.grammar.productions):
|
|
238 rule.f_name = 'action_{}_{}'.format(rule.name, rule_number)
|
321
|
239 self.print(' self.grammar.add_production("{}", {}, self.{})'.format(rule.name, rule.symbols, rule.f_name))
|
318
|
240 # Fill action table:
|
321
|
241 self.print(' self.action_table = {}')
|
318
|
242 for state in self.action_table:
|
|
243 action = self.action_table[state]
|
321
|
244 self.print(' self.action_table[{}] = {}'.format(state, action))
|
|
245 self.print('')
|
318
|
246
|
|
247 # Fill goto table:
|
321
|
248 self.print(' self.goto_table = {}')
|
334
|
249 for state_number in self.goto_table:
|
|
250 to = self.goto_table[state_number]
|
|
251 self.print(' self.goto_table[{}] = {}'.format(state_number, to))
|
321
|
252 self.print('')
|
318
|
253
|
|
254 # Generate a function for each action:
|
|
255 for rule in self.grammar.productions:
|
334
|
256 num_symbols = len(rule.symbols)
|
|
257 args = ', '.join('arg{}'.format(n + 1) for n in range(num_symbols))
|
321
|
258 self.print(' def {}(self, {}):'.format(rule.f_name, args))
|
318
|
259 if rule.f == None:
|
|
260 semantics = 'pass'
|
|
261 else:
|
|
262 semantics = str(rule.f)
|
|
263 if semantics.strip() == '':
|
|
264 semantics = 'pass'
|
334
|
265 for n in range(num_symbols):
|
318
|
266 semantics = semantics.replace('${}'.format(n + 1), 'arg{}'.format(n + 1))
|
321
|
267 self.print(' {}'.format(semantics))
|
322
|
268 self.print('')
|
318
|
269
|
|
270
|
321
|
271 def make_argument_parser():
|
318
|
272 # Parse arguments:
|
|
273 parser = argparse.ArgumentParser(description='xacc compiler compiler')
|
|
274 parser.add_argument('source', type=argparse.FileType('r'), \
|
|
275 help='the parser specification')
|
|
276 parser.add_argument('-o', '--output', type=argparse.FileType('w'), \
|
|
277 default=sys.stdout)
|
322
|
278 return parser
|
321
|
279
|
|
280
|
|
281 def load_as_module(filename):
|
|
282 """ Load a parser spec file, generate LR tables and create module """
|
|
283 ob = io.StringIO()
|
|
284 args = argparse.Namespace(source=open(filename), output=ob)
|
|
285 main(args)
|
|
286
|
|
287 parser_mod = types.ModuleType('generated_parser')
|
|
288 exec(ob.getvalue(), parser_mod.__dict__)
|
|
289 return parser_mod
|
|
290
|
342
|
291
|
321
|
292 def main(args):
|
318
|
293 src = args.source.read()
|
|
294 args.source.close()
|
|
295
|
|
296 # Construction of generator parts:
|
|
297 lexer = XaccLexer()
|
|
298 parser = XaccParser(lexer)
|
|
299 generator = XaccGenerator()
|
|
300
|
|
301 # Sequence source through the generator parts:
|
|
302 lexer.feed(src)
|
|
303 grammar = parser.parse_grammar()
|
319
|
304 generator.generate(grammar, parser.headers, args.output)
|
318
|
305
|
|
306
|
|
307 if __name__ == '__main__':
|
321
|
308 args = make_argument_parser().parse_args()
|
|
309 main(args)
|