Debian Codegraph @

rpython/jit/metainterp/ruleopt/parse.py

raw symbols SCIP
1 import sys
2 from rply import LexerGenerator, LexingError, ParserGenerator, ParsingError
3 from rply.token import BaseBox
4 from rpython.jit.metainterp.optimizeopt.intutils import IntBound
5
6
7 # ____________________________________________________________
8 # lexer
9
10 lg = LexerGenerator()
11
12 alltokens = []
13
14
15 def addtok(name, regex):
16 alltokens.append(name)
17 lg.add(name, regex)
18
19
20 def addkeyword(kw):
21 addtok(kw.upper(), r"\b" + kw + r"\b")
22
23
24 addkeyword("check")
25 addkeyword("and")
26 addkeyword("or")
27 addkeyword("SORRY_Z3")
28
29 addtok("NUMBER", r"[+-]?([1-9]\d*)|0")
30 addtok("NAME", r"[a-zA-Z_][a-zA-Z_0-9]*")
31 addtok("LSHIFT", r"[<][<]")
32 addtok("URSHIFT", r"[>][>]u")
33 addtok("ARSHIFT", r"[>][>]")
34 addtok("ARROW", r"=>")
35 addtok("LPAREN", r"[(]")
36 addtok("RPAREN", r"[)]")
37 addtok("COMMA", r"[,]")
38 addtok("EQUALEQUAL", r"[=][=]")
39 addtok("NE", r"[!][=]")
40 addtok("EQUAL", r"[=]")
41 addtok("COLON", r"[:]")
42 addtok("DOT", r"[.]")
43 addtok("GE", r"[>][=]")
44 addtok("GT", r"[>]")
45 addtok("LE", r"[<][=]")
46 addtok("LT", r"[<]")
47
48 addtok("PLUS", r"[+]")
49 addtok("MINUS", r"[-]")
50 addtok("MUL", r"[*]")
51 addtok("DIV", r"[/][/]")
52 addtok("OP_AND", r"[&]")
53 addtok("OP_OR", r"[|]")
54 addtok("OP_XOR", r"\^")
55 addtok("INVERT", r"~")
56
57 addtok("NEWLINE", r" *([#].*)?\n")
58
59 lg.ignore(r"[ ]")
60
61 lexer = lg.build()
62
63
64 # ____________________________________________________________
65 # AST classes
66
67
68 class Visitor(object):
69 def visit(self, ast, *args, **kwargs):
70 for typ in type(ast).mro():
71 meth = getattr(self, "visit_%s" % typ.__name__, None)
72 if meth is not None:
73 return meth(ast, *args, **kwargs)
74 return self.default_visit(ast, **kwargs)
75
76 def default_visit(self, ast, **kwargs):
77 pass
78
79
80 class BaseAst(BaseBox):
81 # __metaclass__ = extendabletype
82 sourcepos = None
83 endsourcepos = None
84
85 def getsourcepos(self):
86 return self.sourcepos
87
88 def __eq__(self, other):
89 if type(self) != type(other):
90 return NotImplemented
91 return self.__dict__ == other.__dict__
92
93 def __ne__(self, other):
94 return not self == other
95
96 def __repr__(self):
97 args = ["%s=%r" % (key, value) for key, value in self.__dict__.items()]
98 if len(args) == 1:
99 args = [repr(self.__dict__.values()[0])]
100 return "%s(%s)" % (
101 type(self).__name__,
102 ", ".join(args),
103 )
104
105 def view(self):
106 from rpython.translator.tool.make_dot import DotGen
107 from dotviewer import graphclient
108 import pytest
109
110 dotgen = DotGen("G")
111 self._dot(dotgen)
112 p = pytest.ensuretemp("pyparser").join("temp.dot")
113 p.write(dotgen.generate(target=None))
114 graphclient.display_dot_file(str(p))
115
116 def _dot(self, dotgen):
117 arcs = []
118 label = [type(self).__name__]
119 for key, value in self.__dict__.items():
120 if isinstance(value, BaseAst):
121 arcs.append((value, key))
122 value._dot(dotgen)
123 elif isinstance(value, list) and value and isinstance(value[0], BaseAst):
124 for index, item in enumerate(value):
125 arcs.append((item, "%s[%s]" % (key, index)))
126 item._dot(dotgen)
127 else:
128 label.append("%s = %r" % (key, value))
129 dotgen.emit_node(str(id(self)), shape="box", label="\n".join(label))
130 for target, label in arcs:
131 dotgen.emit_edge(str(id(self)), str(id(target)), label)
132
133
134 class File(BaseAst):
135 def __init__(self, rules):
136 self.rules = rules
137
138
139 class Rule(BaseAst):
140 def __init__(self, name, pattern, cantproof, elements, target):
141 self.name = name
142 self.pattern = pattern
143 self.cantproof = cantproof
144 self.elements = elements
145 self.target = target
146
147 def newpattern(self, pattern):
148 res = Rule(self.name, pattern, self.cantproof, self.elements, self.target)
149 res.sourcepos = self.sourcepos
150 res.endsourcepos = self.endsourcepos
151 return res
152
153 def __str__(self):
154 lines = [self.name + ": " + str(self.pattern)]
155 for el in self.elements:
156 lines.append(" " + str(el))
157 lines.append(" => " + str(self.target))
158 return "\n".join(lines)
159
160
161 class Pattern(BaseAst):
162 pass
163
164
165 class PatternVar(Pattern):
166 def __init__(self, name, typ=None):
167 self.name = name
168 self.typ = typ
169
170 def sort_key(self):
171 return (2, self.name)
172
173 def matches_constant(self):
174 return self.name.startswith("C")
175
176 def __str__(self):
177 return self.name
178
179
180 class PatternConst(BaseAst):
181 typ = int
182 def __init__(self, const):
183 self.const = const
184
185 def sort_key(self):
186 return (0, self.const)
187
188 def matches_constant(self):
189 return True
190
191 def __str__(self):
192 return str(self.const)
193
194
195 class PatternOp(BaseAst):
196 def __init__(self, opname, args):
197 self.opname = opname
198 self.args = args
199
200 def newargs(self, args):
201 return PatternOp(self.opname, args)
202
203 def matches_constant(self):
204 return False
205
206 def sort_key(self):
207 return (1, self.opname) + tuple(sorted(arg.sort_key() for arg in self.args))
208
209 def __str__(self):
210 return "%s(%s)" % (self.opname, ", ".join([str(arg) for arg in self.args]))
211
212
213 class Compute(BaseAst):
214 def __init__(self, name, expr):
215 self.name = name
216 self.expr = expr
217
218 def __str__(self):
219 return "compute %s = %s" % (self.name, self.expr)
220
221
222 class Check(BaseAst):
223 def __init__(self, expr):
224 self.expr = expr
225
226 def __str__(self):
227 return "check %s" % (self.expr,)
228
229
230 class Expression(BaseAst):
231 typ = None # can be None, int, bool, IntBound
232
233
234 class Name(Expression):
235 def __init__(self, name, typ=None):
236 self.name = name
237 if typ is None:
238 if self.name.startswith('C'):
239 self.typ = int
240 else:
241 self.typ = IntBound
242 else:
243 self.typ = typ
244
245
246 class Number(Expression):
247 typ = int
248 def __init__(self, value):
249 self.value = value
250
251
252 class BinOp(Expression):
253 def __init__(self, left, right):
254 self.left = left
255 self.right = right
256
257
258 class IntBinOp(BinOp):
259 typ = int
260 need_ruint = False
261
262 class BoolBinOp(BinOp):
263 typ = bool
264
265
266 class Add(IntBinOp):
267 opname = "int_add"
268 pysymbol = "+"
269 need_ruint = True
270
271
272 class Sub(IntBinOp):
273 opname = "int_sub"
274 pysymbol = "-"
275 need_ruint = True
276
277
278 class Mul(IntBinOp):
279 opname = "int_mul"
280 pysymbol = "*"
281 need_ruint = True
282
283
284 class Div(IntBinOp):
285 opname = None
286 pysymbol = "//"
287
288
289 class LShift(IntBinOp):
290 opname = "int_lshift"
291 pysymbol = "<<"
292
293
294 class URShift(IntBinOp):
295 opname = "uint_rshift"
296 pysymbol = ">>"
297 need_ruint = True
298
299
300 class ARShift(IntBinOp):
301 opname = "int_rshift"
302 pysymbol = ">>"
303 need_ruint = False
304
305
306 class OpAnd(IntBinOp):
307 opname = "int_and"
308 pysymbol = "&"
309
310
311 class OpOr(IntBinOp):
312 opname = "int_or"
313 pysymbol = "|"
314
315
316 class OpXor(IntBinOp):
317 opname = "int_xor"
318 pysymbol = "^"
319
320
321 class Eq(BoolBinOp):
322 opname = "int_eq"
323 pysymbol = "=="
324
325
326 class Ge(BoolBinOp):
327 opname = "int_ge"
328 pysymbol = ">="
329
330
331 class Gt(BoolBinOp):
332 opname = "int_gt"
333 pysymbol = ">"
334
335
336 class Le(BoolBinOp):
337 opname = "int_le"
338 pysymbol = "<="
339
340
341 class Lt(BoolBinOp):
342 opname = "int_lt"
343 pysymbol = "<"
344
345
346 class Ne(BoolBinOp):
347 opname = "int_ne"
348 pysymbol = "!="
349
350
351 class ShortcutAnd(BinOp):
352 typ = bool
353 pysymbol = "and"
354
355
356 class ShortcutOr(BinOp):
357 typ = bool
358 pysymbol = "or"
359
360
361 class UnaryOp(Expression):
362 def __init__(self, left):
363 self.left = left
364
365
366 class IntUnaryOp(UnaryOp):
367 typ = int
368
369
370 class Invert(IntUnaryOp):
371 opname = "int_invert"
372 pysymbol = "~"
373
374
375
376 class Attribute(BaseAst):
377 typ = int
378 def __init__(self, varname, attrname):
379 self.varname = varname
380 self.attrname = attrname
381
382
383 class MethodCall(Expression):
384 def __init__(self, value, methname, args):
385 self.value = value
386 self.methname = methname
387 self.args = args
388
389
390 class FuncCall(Expression):
391 def __init__(self, funcname, args):
392 self.funcname = funcname
393 self.args = args
394
395
396 precedence_classes = [
397 ShortcutOr,
398 ShortcutAnd,
399 # NOT,
400 (Eq, Ge, Gt, Le, Lt, Ne),
401 OpOr,
402 OpXor,
403 OpAnd,
404 (LShift, ARShift, URShift),
405 (Add, Sub),
406 (Mul, Div),
407 Invert,
408 (MethodCall, Attribute),
409 (Name, Number),
410 ]
411
412 for i, tup in enumerate(precedence_classes):
413 if not isinstance(tup, tuple):
414 tup = (tup, )
415 for cls in tup:
416 cls.precedence = i
417
418 # ____________________________________________________________
419 # parser
420
421 def production(s):
422 def wrapper(func):
423 def newfunc(p):
424 res = func(p)
425 if isinstance(res, BaseAst) and res.sourcepos is None:
426 sourcepositions = [a.getsourcepos() for a in p if hasattr(a, 'getsourcepos')]
427 if sourcepositions:
428 res.sourcepos = sourcepositions[0]
429 res.endsourcepos = sourcepositions[-1]
430 return res
431 return pg.production(s)(newfunc)
432 return wrapper
433
434
435 pg = ParserGenerator(
436 alltokens,
437 precedence=[
438 ("left", ["OR"]),
439 ("left", ["AND"]),
440 ("left", ["NOT"]),
441 ("left", ["EQUALEQUAL", "GE", "GT", "LE", "LT", "NE"]),
442 ("left", ["OP_OR"]),
443 ("left", ["OP_XOR"]),
444 ("left", ["OP_AND"]),
445 ("left", ["LSHIFT", "ARSHIFT", "URSHIFT"]),
446 ("left", ["PLUS", "MINUS"]),
447 ("left", ["MUL", "DIV"]),
448 ("left", ["INVERT"]),
449 ("left", ["DOT"]),
450 ],
451 )
452
453
454 @production("file : rule | file rule")
455 def file(p):
456 if len(p) == 1:
457 return File(p)
458 return File(p[0].rules + [p[1]])
459
460
461 @production("newlines : NEWLINE | NEWLINE newlines")
462 def newlines(p):
463 return None
464
465
466 @production("rule : NAME COLON pattern newlines maybesorry elements ARROW pattern newlines")
467 def rule(p):
468 return Rule(p[0].value, p[2], p[4], p[5], p[7])
469
470 @production("maybesorry : | SORRY_Z3 newlines")
471 def maybesorry(p):
472 return bool(p)
473
474
475 @production("pattern : NAME")
476 def pattern_var(p):
477 if p[0].value in ("LONG_BIT", "MININT", "MAXINT"):
478 return PatternConst(p[0].value)
479 return PatternVar(p[0].value)
480
481
482 @production("pattern : NUMBER")
483 def pattern_const(p):
484 return PatternConst(p[0].value)
485
486
487 @production("pattern : NAME LPAREN patternargs RPAREN")
488 def pattern_op(p):
489 return PatternOp(p[0].value, p[2])
490
491
492 @production("patternargs : pattern | pattern COMMA patternargs")
493 def patternargs(p):
494 if len(p) == 1:
495 return p
496 return [p[0]] + p[2]
497
498
499 @production("elements : | element newlines elements")
500 def elements(p):
501 if len(p) == 0:
502 return []
503 return [p[0]] + p[2]
504
505
506 @production("element : NAME EQUAL expression")
507 def compute_element(p):
508 return Compute(p[0].value, p[2])
509
510
511 @production("element : CHECK expression")
512 def check(p):
513 return Check(p[1])
514
515
516 @production("expression : NUMBER")
517 def expression_number(p):
518 return Number(int(p[0].getstr()))
519
520
521 @production("expression : NAME")
522 def expression_name(p):
523 return Name(p[0].getstr())
524
525
526 @production("expression : LPAREN expression RPAREN")
527 def expression_parens(p):
528 return p[1]
529
530
531 @production("expression : INVERT expression")
532 def expression_unary(p):
533 return Invert(p[1])
534
535
536 @production("expression : expression PLUS expression")
537 @production("expression : expression MINUS expression")
538 @production("expression : expression MUL expression")
539 @production("expression : expression DIV expression")
540 @production("expression : expression LSHIFT expression")
541 @production("expression : expression URSHIFT expression")
542 @production("expression : expression ARSHIFT expression")
543 @production("expression : expression AND expression")
544 @production("expression : expression OR expression")
545 @production("expression : expression OP_AND expression")
546 @production("expression : expression OP_OR expression")
547 @production("expression : expression OP_XOR expression")
548 @production("expression : expression EQUALEQUAL expression")
549 @production("expression : expression GE expression")
550 @production("expression : expression GT expression")
551 @production("expression : expression LE expression")
552 @production("expression : expression LT expression")
553 @production("expression : expression NE expression")
554 def expression_binop(p):
555 left = p[0]
556 right = p[2]
557 if p[1].gettokentype() == "PLUS":
558 return Add(left, right)
559 elif p[1].gettokentype() == "MINUS":
560 return Sub(left, right)
561 elif p[1].gettokentype() == "MUL":
562 return Mul(left, right)
563 elif p[1].gettokentype() == "DIV":
564 return Div(left, right)
565 elif p[1].gettokentype() == "LSHIFT":
566 return LShift(left, right)
567 elif p[1].gettokentype() == "URSHIFT":
568 return URShift(left, right)
569 elif p[1].gettokentype() == "ARSHIFT":
570 return ARShift(left, right)
571 elif p[1].gettokentype() == "AND":
572 return ShortcutAnd(left, right)
573 elif p[1].gettokentype() == "OR":
574 return ShortcutOr(left, right)
575 elif p[1].gettokentype() == "OP_AND":
576 return OpAnd(left, right)
577 elif p[1].gettokentype() == "OP_OR":
578 return OpOr(left, right)
579 elif p[1].gettokentype() == "OP_XOR":
580 return OpXor(left, right)
581 elif p[1].gettokentype() == "EQUALEQUAL":
582 return Eq(left, right)
583 elif p[1].gettokentype() == "GE":
584 return Ge(left, right)
585 elif p[1].gettokentype() == "GT":
586 return Gt(left, right)
587 elif p[1].gettokentype() == "LE":
588 return Le(left, right)
589 elif p[1].gettokentype() == "LT":
590 return Lt(left, right)
591 elif p[1].gettokentype() == "NE":
592 return Ne(left, right)
593 else:
594 raise AssertionError("Oops, this should not be possible!")
595
596
597 @production("expression : expression DOT NAME maybecall")
598 def attr_or_method(p):
599 assert p[1].gettokentype() == "DOT"
600 if p[3] is not None:
601 return MethodCall(p[0], p[2].value, p[3])
602 return Attribute(p[0].name, p[2].value)
603
604
605 @production("expression : NAME LPAREN args RPAREN")
606 def funccall(p):
607 return FuncCall(p[0].value, p[2])
608
609
610 @production("maybecall : | LPAREN args RPAREN")
611 def methodcall(p):
612 if not p:
613 return None
614 return p[1]
615
616
617 @production("args : | expression | expression COMMA args ")
618 def args(p):
619 if len(p) <= 1:
620 return p
621 return [p[0]] + p[2]
622
623
624 parser = pg.build()
625
626
627 def print_conflicts():
628 if parser.lr_table.rr_conflicts:
629 print("rr conflicts")
630 for rule_num, token, conflict in parser.lr_table.rr_conflicts:
631 print(rule_num, token, conflict)
632
633 if parser.lr_table.sr_conflicts:
634 print("sr conflicts")
635 for rule_num, token, conflict in parser.lr_table.sr_conflicts:
636 print(rule_num, token, conflict)
637
638
639 parser = pg.build()
640 print_conflicts()
641
642
643 def parse(s):
644 ast = parser.parse(lexer.lex(s))
645 t = TypingVisitor()
646 for rule in ast.rules:
647 t.visit(rule)
648 return ast
649
650
651 # ___________________________________________________________________________
652 # attach types
653
654 INTBOUND_METHODTYPES = {
655 "known_eq_const": (IntBound, [int], bool),
656 "known_le_const": (IntBound, [int], bool),
657 "known_lt_const": (IntBound, [int], bool),
658 "known_ge_const": (IntBound, [int], bool),
659 "known_gt_const": (IntBound, [int], bool),
660 "known_ne": (IntBound, [IntBound], bool),
661 "known_nonnegative": (IntBound, [], bool),
662 "is_constant": (IntBound, [], bool),
663 "is_bool": (IntBound, [], bool),
664 "get_constant_int": (IntBound, [], int),
665 "lshift_bound_cannot_overflow": (IntBound, [IntBound], bool),
666 "and_bound": (IntBound, [IntBound], IntBound),
667 "or_bound": (IntBound, [IntBound], IntBound),
668 "sub_bound": (IntBound, [IntBound], IntBound),
669 "sub_bound_cannot_overflow": (IntBound, [IntBound], bool),
670 "lshift_bound": (IntBound, [IntBound], IntBound),
671 "rshift_bound": (IntBound, [IntBound], IntBound),
672 "urshift_bound": (IntBound, [IntBound], IntBound),
673 "known_le": (IntBound, [IntBound], bool),
674 "known_gt": (IntBound, [IntBound], bool),
675 }
676
677 FUNCTYPES = {
678 "highest_bit": ([int], int),
679 "min": ([int, int], int),
680 }
681
682 class TypeCheckError(Exception):
683 def __init__(self, msg, ast):
684 self.msg = msg
685 self.ast = ast
686
687 def __str__(self):
688 return self.msg
689
690 def format(self, sourcelines=None):
691 res = ["Type error: %s" % self.msg]
692 if self.ast.sourcepos:
693 pos = self.ast.sourcepos
694 res.append("in line %s" % pos.lineno)
695 if sourcelines:
696 line = sourcelines.splitlines()[pos.lineno - 1]
697 res.append(" " + line)
698 res.append(" " + " " * (pos.colno - 1) + "^")
699 return "\n".join(res)
700
701
702 class TypingVisitor(Visitor):
703 def _must_be_same_typ(self, ast, typ, targettyp):
704 if targettyp is not typ:
705 raise TypeCheckError("%s must have type %s, got %s" % (ast, targettyp, typ), ast)
706
707 def _error(self, msg, ast):
708 raise TypeCheckError(msg, ast)
709
710 def visit_Rule(self, rule):
711 self.bindings = {}
712 self.visit(rule.pattern, patterndefine=True)
713 for el in rule.elements:
714 self.visit(el)
715 self.visit(rule.target, patterndefine=False)
716
717 def visit_PatternVar(self, ast, patterndefine):
718 if patterndefine:
719 if ast.name.startswith('C'):
720 typ = int
721 else:
722 typ = IntBound
723 if ast.name in self.bindings:
724 self._must_be_same_typ(ast, self.bindings[ast.name], typ)
725 else:
726 self.bindings[ast.name] = typ
727 ast.typ = typ
728 else:
729 if ast.name not in self.bindings:
730 self._error("variable %s is not defined" % (repr(ast.name), ), ast)
731 typ = self.bindings[ast.name]
732 ast.typ = typ
733 return typ
734
735 def visit_PatternConst(self, ast, patterndefine):
736 return ast.typ
737
738 def visit_PatternOp(self, ast, patterndefine):
739 # XXX check that name exists
740 for arg in ast.args:
741 self.visit(arg, patterndefine=patterndefine)
742
743 def visit_Compute(self, ast):
744 if ast.name in self.bindings:
745 self._error("%r is already defined" % ast.name, ast)
746 self.bindings[ast.name] = self.visit(ast.expr)
747
748 def visit_Check(self, ast):
749 typ = self.visit(ast.expr)
750 if typ is not bool:
751 self._error("expected check expression to return a bool, got %s" % typ.__name__, ast.expr)
752
753 def visit_Expression(self, ast):
754 assert 0, "should be unreachable"
755
756 def visit_Name(self, ast):
757 if ast.name == "LONG_BIT":
758 return int
759 if ast.name not in self.bindings:
760 self._error("variable %s is not defined" % (repr(ast.name), ), ast)
761 typ = self.bindings[ast.name]
762 ast.typ = typ
763 return typ
764
765 def visit_Number(self, ast):
766 return ast.typ
767
768 def visit_IntBinOp(self, ast):
769 self._must_be_same_typ(ast.left, int, self.visit(ast.left))
770 self._must_be_same_typ(ast.right, int, self.visit(ast.right))
771 return int
772
773 def visit_IntUnaryOp(self, ast):
774 self._must_be_same_typ(ast.left, int, self.visit(ast.left))
775 return int
776
777 def visit_BoolBinOp(self, ast):
778 self._must_be_same_typ(ast.left, int, self.visit(ast.left))
779 self._must_be_same_typ(ast.right, int, self.visit(ast.right))
780 return bool
781
782 def visit_ShortcutAnd(self, ast):
783 self._must_be_same_typ(ast.left, bool, self.visit(ast.left))
784 self._must_be_same_typ(ast.right, bool, self.visit(ast.right))
785 return bool
786
787 def visit_ShortcutOr(self, ast):
788 self._must_be_same_typ(ast.left, bool, self.visit(ast.left))
789 self._must_be_same_typ(ast.right, bool, self.visit(ast.right))
790 return bool
791
792 def visit_MethodCall(self, ast):
793 if ast.methname in INTBOUND_METHODTYPES:
794 _, argtyps, restyp = INTBOUND_METHODTYPES[ast.methname]
795 for arg, typ in zip(ast.args, argtyps):
796 hastyp = self.visit(arg)
797 self._must_be_same_typ(arg, hastyp, typ)
798 ast.typ = restyp
799 return restyp
800 self._error("unknown method %r" % ast.methname, ast)
801
802 def visit_FuncCall(self, ast):
803 if ast.funcname in FUNCTYPES:
804 argtyps, restyp = FUNCTYPES[ast.funcname]
805 for arg, typ in zip(ast.args, argtyps):
806 hastyp = self.visit(arg)
807 self._must_be_same_typ(arg, hastyp, typ)
808 self.typ = restyp
809 return restyp
810
811 def default_visit(self, ast):
812 assert ast.typ is not None
813 return ast.typ