Debian Codegraph @

src/yapps3/parsetree.py

raw symbols SCIP
1 #!/usr/bin/python2
2 #
3 # parsetree.py, part of Yapps 2 - yet another python parser system
4 # Copyright 1999-2003 by Amit J. Patel <[email protected]>
5 #
6 # This version of the Yapps 2 Runtime can be distributed under the
7 # terms of the MIT open source license, either found in the LICENSE file
8 # included with the Yapps distribution
9 # <http://theory.stanford.edu/~amitp/yapps/> or at
10 # <http://www.opensource.org/licenses/mit-license.php>
11 #
12 from __future__ import print_function
13
14 """Classes used to represent parse trees and generate output.
15
16 This module defines the Generator class, which drives the generation
17 of Python output from a grammar parse tree. It also defines nodes
18 used to represent the parse tree; they are derived from class Node.
19
20 The main logic of Yapps is in this module.
21 """
22
23 import sys, re
24
25 ######################################################################
26 INDENT = ' '*4
27 class Generator:
28
29 # TODO: many of the methods here should be class methods, not instance methods
30
31 def __init__(self, name, options, tokens, rules):
32 self.change_count = 0
33 self.name = name
34 self.options = options
35 self.preparser = ''
36 self.postparser = None
37
38 self.tokens = {} # Map from tokens to regexps
39 self.ignore = [] # List of token names to ignore in parsing
40 self.terminals = [] # List of token names (to maintain ordering)
41 for n, t in tokens:
42 if n == '#ignore':
43 n = t
44 self.ignore.append(n)
45 if n in self.tokens.keys() and self.tokens[n] != t:
46 print('Warning: token %s defined more than once.' % n, file=sys.stderr)
47 self.tokens[n] = t
48 self.terminals.append(n)
49
50 self.rules = {} # Map from rule names to parser nodes
51 self.params = {} # Map from rule names to parameters
52 self.goals = [] # List of rule names (to maintain ordering)
53 for n,p,r in rules:
54 self.params[n] = p
55 self.rules[n] = r
56 self.goals.append(n)
57
58 self.output = sys.stdout
59
60 def has_option(self, name):
61 return self.options.get(name, 0)
62
63 def non_ignored_tokens(self):
64 return [x for x in self.terminals if x not in self.ignore]
65
66 def changed(self):
67 """Increments the change count.
68
69 >>> t = Generator('', [], [], [])
70 >>> old_count = t.change_count
71 >>> t.changed()
72 >>> assert t.change_count == old_count + 1
73 """
74 self.change_count = 1+self.change_count
75
76 def set_subtract(self, a, b):
77 """Returns the elements of a that are not in b.
78
79 >>> t = Generator('', [], [], [])
80 >>> t.set_subtract([], [])
81 []
82 >>> t.set_subtract([1, 2], [1, 2])
83 []
84 >>> t.set_subtract([1, 2, 3], [2])
85 [1, 3]
86 >>> t.set_subtract([1], [2, 3, 4])
87 [1]
88 """
89 result = []
90 for x in a:
91 if x not in b:
92 result.append(x)
93 return result
94
95 def subset(self, a, b):
96 """True iff all elements of sequence a are inside sequence b
97
98 >>> t = Generator('', [], [], [])
99 >>> t.subset([], [1, 2, 3])
100 1
101 >>> t.subset([1, 2, 3], [])
102 0
103 >>> t.subset([1], [1, 2, 3])
104 1
105 >>> t.subset([3, 2, 1], [1, 2, 3])
106 1
107 >>> t.subset([1, 1, 1], [1, 2, 3])
108 1
109 >>> t.subset([1, 2, 3], [1, 1, 1])
110 0
111 """
112 for x in a:
113 if x not in b:
114 return 0
115 return 1
116
117 def equal_set(self, a, b):
118 """True iff subset(a, b) and subset(b, a)
119
120 >>> t = Generator('', [], [], [])
121 >>> a_set = [1, 2, 3]
122 >>> t.equal_set(a_set, a_set)
123 1
124 >>> t.equal_set(a_set, a_set[:])
125 1
126 >>> t.equal_set([], a_set)
127 0
128 >>> t.equal_set([1, 2, 3], [3, 2, 1])
129 1
130 """
131 if len(a) != len(b): return 0
132 if a == b: return 1
133 return self.subset(a, b) and self.subset(b, a)
134
135 def add_to(self, parent, additions):
136 "Modify _parent_ to include all elements in _additions_"
137 for x in additions:
138 if x not in parent:
139 parent.append(x)
140 self.changed()
141
142 def equate(self, a, b):
143 """Extend (a) and (b) so that they contain each others' elements.
144
145 >>> t = Generator('', [], [], [])
146 >>> a = [1, 2]
147 >>> b = [2, 3]
148 >>> t.equate(a, b)
149 >>> a
150 [1, 2, 3]
151 >>> b
152 [2, 3, 1]
153 """
154 self.add_to(a, b)
155 self.add_to(b, a)
156
157 def write(self, *args):
158 for a in args:
159 self.output.write(a)
160
161 def in_test(self, expr, full, set):
162 """Generate a test of (expr) being in (set), where (set) is a subset of (full)
163
164 expr is a string (Python expression)
165 set is a list of values (which will be converted with repr)
166 full is the list of all values expr could possibly evaluate to
167
168 >>> t = Generator('', [], [], [])
169 >>> t.in_test('x', [1,2,3,4], [])
170 '0'
171 >>> t.in_test('x', [1,2,3,4], [1,2,3,4])
172 '1'
173 >>> t.in_test('x', [1,2,3,4], [1])
174 'x == 1'
175 >>> t.in_test('a+b', [1,2,3,4], [1,2])
176 'a+b in [1, 2]'
177 >>> t.in_test('x', [1,2,3,4,5], [1,2,3])
178 'x not in [4, 5]'
179 >>> t.in_test('x', [1,2,3,4,5], [1,2,3,4])
180 'x != 5'
181 """
182
183 if not set: return '0'
184 if len(set) == 1: return '%s == %s' % (expr, repr(set[0]))
185 if full and len(set) > len(full)/2:
186 # Reverse the sense of the test.
187 not_set = [x for x in full if x not in set]
188 return self.not_in_test(expr, full, not_set)
189 return '%s in %s' % (expr, repr(set))
190
191 def not_in_test(self, expr, full, set):
192 """Like in_test, but the reverse test."""
193 if not set: return '1'
194 if len(set) == 1: return '%s != %s' % (expr, repr(set[0]))
195 return '%s not in %s' % (expr, repr(set))
196
197 def peek_call(self, a):
198 """Generate a call to scan for a token in the set 'a'"""
199 assert type(a) == type([])
200 a_set = (repr(a)[1:-1])
201 if self.equal_set(a, self.non_ignored_tokens()): a_set = ''
202 if self.has_option('context-insensitive-scanner'): a_set = ''
203 return 'self._peek(%s)' % a_set
204
205 def peek_test(self, a, b):
206 """Generate a call to test whether the next token (which could be any of
207 the elements in a) is in the set b."""
208 if self.subset(a, b): return '1'
209 if self.has_option('context-insensitive-scanner'): a = self.non_ignored_tokens()
210 return self.in_test(self.peek_call(a), a, b)
211
212 def not_peek_test(self, a, b):
213 """Like peek_test, but the opposite sense."""
214 if self.subset(a, b): return '0'
215 return self.not_in_test(self.peek_call(a), a, b)
216
217 def calculate(self):
218 """The main loop to compute the epsilon, first, follow sets.
219 The loop continues until the sets converge. This works because
220 each set can only get larger, so when they stop getting larger,
221 we're done."""
222 # First we determine whether a rule accepts epsilon (the empty sequence)
223 while 1:
224 for r in self.goals:
225 self.rules[r].setup(self)
226 if self.change_count == 0: break
227 self.change_count = 0
228
229 # Now we compute the first/follow sets
230 while 1:
231 for r in self.goals:
232 self.rules[r].update(self)
233 if self.change_count == 0: break
234 self.change_count = 0
235
236 def dump_information(self):
237 """Display the grammar in somewhat human-readable form."""
238 self.calculate()
239 for r in self.goals:
240 print(' _____' + '_'*len(r))
241 print(('___/Rule '+r+'\\' + '_'*80)[:79])
242 queue = [self.rules[r]]
243 while queue:
244 top = queue[0]
245 del queue[0]
246
247 print('Rule', repr(top), 'of class', top.__class__.__name__)
248 top.first.sort()
249 top.follow.sort()
250 eps = []
251 if top.accepts_epsilon: eps = ['(null)']
252 print(' FIRST:', ', '.join(top.first+eps))
253 print(' FOLLOW:', ', '.join(top.follow))
254 for x in top.get_children(): queue.append(x)
255
256 def generate_output(self):
257 self.calculate()
258 self.write(self.preparser)
259 self.write("# Begin -- grammar generated by Yapps\n")
260 self.write("import sys, re\n")
261 self.write("from . import yapps3_compiled_rt as yappsrt\n")
262 self.write("\n")
263 self.write("class ", self.name, "Scanner(yappsrt.Scanner):\n")
264 self.write(" def __init__(self, *args,**kwargs):\n")
265 self.write(" patterns = [\n")
266 for p in self.terminals:
267 self.write(" (%s, %s),\n" % (
268 repr(p), repr(self.tokens[p])))
269 self.write(" ]\n")
270 self.write(" yappsrt.Scanner.__init__(self,patterns,%s,*args,**kwargs)\n" %
271 repr(self.ignore))
272 self.write("\n")
273
274 self.write("class ", self.name, "(yappsrt.Parser):\n")
275 self.write(INDENT, "Context = yappsrt.Context\n")
276 for r in self.goals:
277 self.write(INDENT, "def ", r, "(self")
278 if self.params[r]: self.write(", ", self.params[r])
279 self.write(", _parent=None):\n")
280 self.write(INDENT+INDENT, "_context = self.Context(_parent, self._scanner, self._pos, %s, [%s])\n" %
281 (repr(r), self.params.get(r, '')))
282 self.rules[r].output(self, INDENT+INDENT)
283 self.write("\n")
284
285 self.write("\n")
286 self.write("def parse(rule, text):\n")
287 self.write(" P = ", self.name, "(", self.name, "Scanner(text))\n")
288 self.write(" return yappsrt.wrap_error_reporter(P, rule)\n")
289 self.write("\n")
290 if self.postparser is not None:
291 self.write("# End -- grammar generated by Yapps\n")
292 self.write(self.postparser)
293 else:
294 self.write("if __name__ == '__main__':\n")
295 self.write(INDENT, "from sys import argv, stdin\n")
296 self.write(INDENT, "if len(argv) >= 2:\n")
297 self.write(INDENT*2, "if len(argv) >= 3:\n")
298 self.write(INDENT*3, "f = open(argv[2],'r')\n")
299 self.write(INDENT*2, "else:\n")
300 self.write(INDENT*3, "f = stdin\n")
301 self.write(INDENT*2, "print(parse(argv[1], f.read()))\n")
302 self.write(INDENT, "else: print('Args: <rule> [<filename>]', file=sys.stderr)\n")
303 self.write("# End -- grammar generated by Yapps\n")
304
305 ######################################################################
306 class Node:
307 """This is the base class for all components of a grammar."""
308 def __init__(self, rule):
309 self.rule = rule # name of the rule containing this node
310 self.first = []
311 self.follow = []
312 self.accepts_epsilon = 0
313
314 def setup(self, gen):
315 # Setup will change accepts_epsilon,
316 # sometimes from 0 to 1 but never 1 to 0.
317 # It will take a finite number of steps to set things up
318 pass
319
320 def used(self, vars):
321 "Return two lists: one of vars used, and the other of vars assigned"
322 return vars, []
323
324 def get_children(self):
325 "Return a list of sub-nodes"
326 return []
327
328 def __repr__(self):
329 return str(self)
330
331 def update(self, gen):
332 if self.accepts_epsilon:
333 gen.add_to(self.first, self.follow)
334
335 def output(self, gen, indent):
336 "Write out code to _gen_ with _indent_:string indentation"
337 gen.write(indent, "assert 0 # Invalid parser node\n")
338
339 class Terminal(Node):
340 """This class stores terminal nodes, which are tokens."""
341 def __init__(self, rule, token):
342 Node.__init__(self, rule)
343 self.token = token
344 self.accepts_epsilon = 0
345
346 def __str__(self):
347 return self.token
348
349 def update(self, gen):
350 Node.update(self, gen)
351 if self.first != [self.token]:
352 self.first = [self.token]
353 gen.changed()
354
355 def output(self, gen, indent):
356 gen.write(indent)
357 if re.match('[a-zA-Z_][a-zA-Z_0-9]*$', self.token):
358 gen.write(self.token, " = ")
359 gen.write("self._scan(%s)\n" % repr(self.token))
360
361 class Eval(Node):
362 """This class stores evaluation nodes, from {{ ... }} clauses."""
363 def __init__(self, rule, expr):
364 Node.__init__(self, rule)
365 self.expr = expr
366
367 def setup(self, gen):
368 Node.setup(self, gen)
369 if not self.accepts_epsilon:
370 self.accepts_epsilon = 1
371 gen.changed()
372
373 def __str__(self):
374 return '{{ %s }}' % self.expr.strip()
375
376 def output(self, gen, indent):
377 gen.write(indent, self.expr.strip(), '\n')
378
379 class NonTerminal(Node):
380 """This class stores nonterminal nodes, which are rules with arguments."""
381 def __init__(self, rule, name, args):
382 Node.__init__(self, rule)
383 self.name = name
384 self.args = args
385
386 def setup(self, gen):
387 Node.setup(self, gen)
388 try:
389 self.target = gen.rules[self.name]
390 if self.accepts_epsilon != self.target.accepts_epsilon:
391 self.accepts_epsilon = self.target.accepts_epsilon
392 gen.changed()
393 except KeyError: # Oops, it's nonexistent
394 print('Error: no rule <%s>' % self.name, file=sys.stderr)
395 self.target = self
396
397 def __str__(self):
398 return '%s' % self.name
399
400 def update(self, gen):
401 Node.update(self, gen)
402 gen.equate(self.first, self.target.first)
403 gen.equate(self.follow, self.target.follow)
404
405 def output(self, gen, indent):
406 gen.write(indent)
407 gen.write(self.name, " = ")
408 args = self.args
409 if args: args += ', '
410 args += '_context'
411 gen.write("self.", self.name, "(", args, ")\n")
412
413 class Sequence(Node):
414 """This class stores a sequence of nodes (A B C ...)"""
415 def __init__(self, rule, *children):
416 Node.__init__(self, rule)
417 self.children = children
418
419 def setup(self, gen):
420 Node.setup(self, gen)
421 for c in self.children: c.setup(gen)
422
423 if not self.accepts_epsilon:
424 # If it's not already accepting epsilon, it might now do so.
425 for c in self.children:
426 # any non-epsilon means all is non-epsilon
427 if not c.accepts_epsilon: break
428 else:
429 self.accepts_epsilon = 1
430 gen.changed()
431
432 def get_children(self):
433 return self.children
434
435 def __str__(self):
436 return '( %s )' % ' '.join(map(str, self.children))
437
438 def update(self, gen):
439 Node.update(self, gen)
440 for g in self.children:
441 g.update(gen)
442
443 empty = 1
444 for g_i in range(len(self.children)):
445 g = self.children[g_i]
446
447 if empty: gen.add_to(self.first, g.first)
448 if not g.accepts_epsilon: empty = 0
449
450 if g_i == len(self.children)-1:
451 next = self.follow
452 else:
453 next = self.children[1+g_i].first
454 gen.add_to(g.follow, next)
455
456 if self.children:
457 gen.add_to(self.follow, self.children[-1].follow)
458
459 def output(self, gen, indent):
460 if self.children:
461 for c in self.children:
462 c.output(gen, indent)
463 else:
464 # Placeholder for empty sequences, just in case
465 gen.write(indent, 'pass\n')
466
467 class Choice(Node):
468 """This class stores a choice between nodes (A | B | C | ...)"""
469 def __init__(self, rule, *children):
470 Node.__init__(self, rule)
471 self.children = children
472
473 def setup(self, gen):
474 Node.setup(self, gen)
475 for c in self.children: c.setup(gen)
476
477 if not self.accepts_epsilon:
478 for c in self.children:
479 if c.accepts_epsilon:
480 self.accepts_epsilon = 1
481 gen.changed()
482
483 def get_children(self):
484 return self.children
485
486 def __str__(self):
487 return '( %s )' % ' | '.join(map(str, self.children))
488
489 def update(self, gen):
490 Node.update(self, gen)
491 for g in self.children:
492 g.update(gen)
493
494 for g in self.children:
495 gen.add_to(self.first, g.first)
496 gen.add_to(self.follow, g.follow)
497 for g in self.children:
498 gen.add_to(g.follow, self.follow)
499 if self.accepts_epsilon:
500 gen.add_to(self.first, self.follow)
501
502 def output(self, gen, indent):
503 test = "if"
504 gen.write(indent, "_token = ", gen.peek_call(self.first), "\n")
505 tokens_seen = []
506 tokens_unseen = self.first[:]
507 if gen.has_option('context-insensitive-scanner'):
508 # Context insensitive scanners can return ANY token,
509 # not only the ones in first.
510 tokens_unseen = gen.non_ignored_tokens()
511 for c in self.children:
512 testset = c.first[:]
513 removed = []
514 for x in testset:
515 if x in tokens_seen:
516 testset.remove(x)
517 removed.append(x)
518 if x in tokens_unseen: tokens_unseen.remove(x)
519 tokens_seen = tokens_seen + testset
520 if removed:
521 if not testset:
522 print('Error in rule', self.rule+':', file=sys.stderr)
523 else:
524 print('Warning in rule', self.rule+':', file=sys.stderr)
525 print(' *', self, file=sys.stderr)
526 print(' * These tokens could be matched by more than one clause:', file=sys.stderr)
527 print(' *', ' '.join(removed), file=sys.stderr)
528
529 if testset:
530 if not tokens_unseen: # context sensitive scanners only!
531 if test == 'if':
532 # if it's the first AND last test, then
533 # we can simply put the code without an if/else
534 c.output(gen, indent)
535 else:
536 gen.write(indent, "else:")
537 t = gen.in_test('', [], testset)
538 if len(t) < 70-len(indent):
539 gen.write(' #', t)
540 gen.write("\n")
541 c.output(gen, indent+INDENT)
542 else:
543 gen.write(indent, test, " ",
544 gen.in_test('_token', tokens_unseen, testset),
545 ":\n")
546 c.output(gen, indent+INDENT)
547 test = "elif"
548
549 if tokens_unseen:
550 gen.write(indent, "else:\n")
551 gen.write(indent, INDENT, "raise yappsrt.YappsSyntaxError(_token[0], ")
552 gen.write("'Could not match ", self.rule, "')\n")
553
554 class Wrapper(Node):
555 """This is a base class for nodes that modify a single child."""
556 def __init__(self, rule, child):
557 Node.__init__(self, rule)
558 self.child = child
559
560 def setup(self, gen):
561 Node.setup(self, gen)
562 self.child.setup(gen)
563
564 def get_children(self):
565 return [self.child]
566
567 def update(self, gen):
568 Node.update(self, gen)
569 self.child.update(gen)
570 gen.add_to(self.first, self.child.first)
571 gen.equate(self.follow, self.child.follow)
572
573 class Option(Wrapper):
574 """This class represents an optional clause of the form [A]"""
575 def setup(self, gen):
576 Wrapper.setup(self, gen)
577 if not self.accepts_epsilon:
578 self.accepts_epsilon = 1
579 gen.changed()
580
581 def __str__(self):
582 return '[ %s ]' % str(self.child)
583
584 def output(self, gen, indent):
585 if self.child.accepts_epsilon:
586 print('Warning in rule', self.rule+': contents may be empty.', file=sys.stderr)
587 gen.write(indent, "if %s:\n" %
588 gen.peek_test(self.first, self.child.first))
589 self.child.output(gen, indent+INDENT)
590
591 class Plus(Wrapper):
592 """This class represents a 1-or-more repetition clause of the form A+"""
593 def setup(self, gen):
594 Wrapper.setup(self, gen)
595 if self.accepts_epsilon != self.child.accepts_epsilon:
596 self.accepts_epsilon = self.child.accepts_epsilon
597 gen.changed()
598
599 def __str__(self):
600 return '%s+' % str(self.child)
601
602 def update(self, gen):
603 Wrapper.update(self, gen)
604 gen.add_to(self.child.follow, self.child.first)
605
606 def output(self, gen, indent):
607 if self.child.accepts_epsilon:
608 print('Warning in rule', self.rule+':', file=sys.stderr)
609 print(' * The repeated pattern could be empty. The resulting parser may not work properly.', file=sys.stderr)
610 gen.write(indent, "while 1:\n")
611 self.child.output(gen, indent+INDENT)
612 union = self.first[:]
613 gen.add_to(union, self.follow)
614 gen.write(indent+INDENT, "if %s: break\n" %
615 gen.not_peek_test(union, self.child.first))
616
617 class Star(Wrapper):
618 """This class represents a 0-or-more repetition clause of the form A*"""
619 def setup(self, gen):
620 Wrapper.setup(self, gen)
621 if not self.accepts_epsilon:
622 self.accepts_epsilon = 1
623 gen.changed()
624
625 def __str__(self):
626 return '%s*' % str(self.child)
627
628 def update(self, gen):
629 Wrapper.update(self, gen)
630 gen.add_to(self.child.follow, self.child.first)
631
632 def output(self, gen, indent):
633 if self.child.accepts_epsilon:
634 print('Warning in rule', self.rule+':', file=sys.stderr)
635 print(' * The repeated pattern could be empty. The resulting parser probably will not work properly.', file=sys.stderr)
636 gen.write(indent, "while %s:\n" %
637 gen.peek_test(self.follow, self.child.first))
638 self.child.output(gen, indent+INDENT)
639
640 # TODO: need to generate tests like this in lots of rules
641 # TODO: do we need to do this only when it's a context-insensitive scanner?
642 gen.write(indent, "if %s:\n" %
643 gen.not_peek_test(gen.non_ignored_tokens(), self.follow))
644 gen.write(indent+INDENT, "raise yappsrt.YappsSyntaxError(charpos=self._scanner.get_prev_char_pos(), context=_context, msg='Need one of ' + ', '.join(%s))\n" %
645 repr(self.first))