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
|
383
|
46 from baselex import BaseLexer
|
|
47 from ppci import Token
|
318
|
48
|
|
49
|
383
|
50 class XaccLexer(BaseLexer):
|
318
|
51 def __init__(self):
|
|
52 tok_spec = [
|
383
|
53 ('ID', r'[A-Za-z][A-Za-z\d_]*', lambda typ, val: (typ, val)),
|
|
54 ('STRING', r"'[^']*'", lambda typ, val: ('ID', val[1:-1])),
|
|
55 ('BRACEDCODE', r"\{[^\}]*\}", lambda typ, val: (typ, val)),
|
|
56 ('OTHER', r'[:;\|]', lambda typ, val: (val, val)),
|
|
57 ('SKIP', r'[ ]', None)
|
318
|
58 ]
|
383
|
59 super().__init__(tok_spec)
|
318
|
60
|
383
|
61 def tokenize(self, txt):
|
|
62 lines = txt.split('\n')
|
|
63 section = 0
|
|
64 for line in lines:
|
|
65 line = line.strip()
|
|
66 if not line:
|
|
67 continue # Skip empty lines
|
|
68 if line == '%%':
|
|
69 section += 1
|
|
70 yield Token('%%', '%%')
|
|
71 continue
|
|
72 if section == 0:
|
|
73 if line.startswith('%tokens'):
|
|
74 yield Token('%tokens', '%tokens')
|
|
75 for tk in super().tokenize(line[7:]):
|
|
76 yield tk
|
318
|
77 else:
|
383
|
78 yield Token('HEADER', line)
|
|
79 elif section == 1:
|
|
80 for tk in super().tokenize(line):
|
|
81 yield tk
|
318
|
82
|
|
83
|
|
84 class ParseError(Exception):
|
|
85 pass
|
|
86
|
|
87
|
|
88 class XaccParser:
|
|
89 """ Implements a recursive descent parser to parse grammar rules.
|
|
90 We could have made an generated parser, but that would yield a chicken
|
|
91 egg issue.
|
|
92 """
|
383
|
93 def __init__(self):
|
|
94 pass
|
|
95
|
|
96 def prepare_peak(self, lexer):
|
318
|
97 self.lexer = lexer
|
383
|
98 self.look_ahead = self.lexer.next_token()
|
318
|
99
|
|
100 @property
|
|
101 def Peak(self):
|
|
102 """ Sneak peak to the next token in line """
|
383
|
103 return self.look_ahead.typ
|
318
|
104
|
|
105 def next_token(self):
|
|
106 """ Take the next token """
|
383
|
107 token = self.look_ahead
|
|
108 self.look_ahead = self.lexer.next_token()
|
|
109 return token
|
318
|
110
|
|
111 def consume(self, typ):
|
|
112 """ Eat next token of type typ or raise an exception """
|
|
113 if self.Peak == typ:
|
|
114 return self.next_token()
|
|
115 else:
|
|
116 raise ParseError('Expected {}, but got {}'.format(typ, self.Peak))
|
|
117
|
|
118 def has_consumed(self, typ):
|
|
119 """ Consume typ if possible and return true if so """
|
|
120 if self.Peak == typ:
|
|
121 self.consume(typ)
|
|
122 return True
|
|
123 return False
|
|
124
|
383
|
125 def parse_grammar(self, lexer):
|
318
|
126 """ Entry parse function into recursive descent parser """
|
383
|
127 self.prepare_peak(lexer)
|
318
|
128 # parse header
|
383
|
129 self.headers = []
|
318
|
130 terminals = []
|
|
131 while self.Peak in ['HEADER', '%tokens']:
|
|
132 if self.Peak == '%tokens':
|
|
133 self.consume('%tokens')
|
|
134 while self.Peak == 'ID':
|
383
|
135 terminals.append(self.consume('ID').val)
|
318
|
136 else:
|
383
|
137 self.headers.append(self.consume('HEADER').val)
|
318
|
138 self.consume('%%')
|
|
139 self.grammar = Grammar(terminals)
|
383
|
140 while self.Peak != 'EOF':
|
318
|
141 self.parse_rule()
|
|
142 return self.grammar
|
|
143
|
|
144 def parse_symbol(self):
|
383
|
145 return self.consume('ID').val
|
318
|
146
|
|
147 def parse_rhs(self):
|
319
|
148 """ Parse the right hand side of a rule definition """
|
318
|
149 symbols = []
|
|
150 while self.Peak not in [';', 'BRACEDCODE', '|']:
|
|
151 symbols.append(self.parse_symbol())
|
|
152 if self.Peak == 'BRACEDCODE':
|
383
|
153 action = self.consume('BRACEDCODE').val
|
318
|
154 action = action[1:-1].strip()
|
|
155 else:
|
|
156 action = None
|
|
157 return symbols, action
|
|
158
|
|
159 def parse_rule(self):
|
319
|
160 """ Parse a rule definition """
|
318
|
161 p = self.parse_symbol()
|
|
162 self.consume(':')
|
|
163 symbols, action = self.parse_rhs()
|
|
164 self.grammar.add_production(p, symbols, action)
|
|
165 while self.has_consumed('|'):
|
|
166 symbols, action = self.parse_rhs()
|
|
167 self.grammar.add_production(p, symbols, action)
|
|
168 self.consume(';')
|
|
169
|
|
170
|
|
171 class XaccGenerator:
|
|
172 """ Generator that writes generated parser to file """
|
|
173 def __init__(self):
|
323
|
174 self.logger = logging.getLogger('yacc')
|
318
|
175
|
319
|
176 def generate(self, grammar, headers, output_file):
|
321
|
177 self.output_file = output_file
|
318
|
178 self.grammar = grammar
|
319
|
179 self.headers = headers
|
323
|
180 self.logger.info('Generating parser for grammar {}'.format(grammar))
|
340
|
181 self.action_table, self.goto_table = grammar.generate_tables()
|
321
|
182 self.generate_python_script()
|
318
|
183
|
321
|
184 def print(self, *args):
|
|
185 """ Print helper function that prints to output file """
|
|
186 print(*args, file=self.output_file)
|
|
187
|
|
188 def generate_python_script(self):
|
318
|
189 """ Generate python script with the parser table """
|
321
|
190 self.print('#!/usr/bin/python')
|
318
|
191 stamp = datetime.datetime.now().ctime()
|
321
|
192 self.print('""" Automatically generated by xacc on {} """'.format(stamp))
|
|
193 self.print('from pyyacc import LRParser, Reduce, Shift, Accept, Production, Grammar')
|
|
194 self.print('from ppci import Token')
|
|
195 self.print('')
|
319
|
196 for h in self.headers:
|
|
197 print(h, file=output_file)
|
321
|
198 self.print('')
|
|
199 self.print('class Parser(LRParser):')
|
|
200 self.print(' def __init__(self):')
|
318
|
201 # Generate rules:
|
321
|
202 self.print(' self.start_symbol = "{}"'.format(self.grammar.start_symbol))
|
|
203 self.print(' self.grammar = Grammar({})'.format(self.grammar.terminals))
|
318
|
204 for rule_number, rule in enumerate(self.grammar.productions):
|
|
205 rule.f_name = 'action_{}_{}'.format(rule.name, rule_number)
|
321
|
206 self.print(' self.grammar.add_production("{}", {}, self.{})'.format(rule.name, rule.symbols, rule.f_name))
|
318
|
207 # Fill action table:
|
321
|
208 self.print(' self.action_table = {}')
|
318
|
209 for state in self.action_table:
|
|
210 action = self.action_table[state]
|
321
|
211 self.print(' self.action_table[{}] = {}'.format(state, action))
|
|
212 self.print('')
|
318
|
213
|
|
214 # Fill goto table:
|
321
|
215 self.print(' self.goto_table = {}')
|
334
|
216 for state_number in self.goto_table:
|
|
217 to = self.goto_table[state_number]
|
|
218 self.print(' self.goto_table[{}] = {}'.format(state_number, to))
|
321
|
219 self.print('')
|
318
|
220
|
|
221 # Generate a function for each action:
|
|
222 for rule in self.grammar.productions:
|
334
|
223 num_symbols = len(rule.symbols)
|
|
224 args = ', '.join('arg{}'.format(n + 1) for n in range(num_symbols))
|
321
|
225 self.print(' def {}(self, {}):'.format(rule.f_name, args))
|
318
|
226 if rule.f == None:
|
|
227 semantics = 'pass'
|
|
228 else:
|
|
229 semantics = str(rule.f)
|
|
230 if semantics.strip() == '':
|
|
231 semantics = 'pass'
|
334
|
232 for n in range(num_symbols):
|
318
|
233 semantics = semantics.replace('${}'.format(n + 1), 'arg{}'.format(n + 1))
|
321
|
234 self.print(' {}'.format(semantics))
|
322
|
235 self.print('')
|
318
|
236
|
|
237
|
321
|
238 def make_argument_parser():
|
318
|
239 # Parse arguments:
|
|
240 parser = argparse.ArgumentParser(description='xacc compiler compiler')
|
|
241 parser.add_argument('source', type=argparse.FileType('r'), \
|
|
242 help='the parser specification')
|
|
243 parser.add_argument('-o', '--output', type=argparse.FileType('w'), \
|
|
244 default=sys.stdout)
|
322
|
245 return parser
|
321
|
246
|
|
247
|
|
248 def load_as_module(filename):
|
|
249 """ Load a parser spec file, generate LR tables and create module """
|
|
250 ob = io.StringIO()
|
|
251 args = argparse.Namespace(source=open(filename), output=ob)
|
|
252 main(args)
|
|
253
|
|
254 parser_mod = types.ModuleType('generated_parser')
|
|
255 exec(ob.getvalue(), parser_mod.__dict__)
|
|
256 return parser_mod
|
|
257
|
342
|
258
|
321
|
259 def main(args):
|
318
|
260 src = args.source.read()
|
|
261 args.source.close()
|
|
262
|
|
263 # Construction of generator parts:
|
|
264 lexer = XaccLexer()
|
383
|
265 parser = XaccParser()
|
318
|
266 generator = XaccGenerator()
|
|
267
|
|
268 # Sequence source through the generator parts:
|
|
269 lexer.feed(src)
|
383
|
270 grammar = parser.parse_grammar(lexer)
|
319
|
271 generator.generate(grammar, parser.headers, args.output)
|
318
|
272
|
|
273
|
|
274 if __name__ == '__main__':
|
321
|
275 args = make_argument_parser().parse_args()
|
|
276 main(args)
|