def __getattr__(self, name): try: return self._rules[name] except KeyError: pass try: return self._stubs[name] except KeyError: pass self._stubs[name] = result = P.delay(lambda: self._rules[name], "<%s>", name) return result
def alt(pegs): return foldr(either, fail, pegs) def foldr(f, z, xs): for x in reversed(xs): z = f(x, z) return z # eg_calc.py example from operator import * from parson import delay _ = delay(lambda: g._) exp3 = delay(lambda: g.exp3) exp1 = PrececedenceParser(exp3, [ LeftAssoc(('*'+_, mul), ('//'+_, div), ('/'+_, truediv), ('%'+_, mod)), RightAssoc(('^'+_, pow)), ]) exps = PrececedenceParser(exp1, [ LeftAssoc(('+'+_, add), ('-'+_, sub)), ]) g = Grammar(r""" top = _ :exps !/./. exp3 : '('_ :exps ')'_
from operator import add, sub from parson import anyone, capture, delay, nest, one_of, one_that end = ~anyone def match(p, x): return (p + end)([x]) def an_instance(type_): return one_that(lambda x: isinstance(x, type_)) def capture1(p): return capture(p) >> (lambda x: x[0]) # Ouch var = capture1(anyone) ## (var + var)(eg) #. ('+', 2) calc = delay(lambda: nest(one_of('+') + calc + calc + end) >> add | nest(one_of('-') + calc + calc + end) >> sub | capture1(an_instance(int))) eg = ['+', 2, 3] ## match(calc, eg) #. (5,) eg2 = ['+', ['-', 2, 4], 3] ## match(calc, eg2) #. (1,) # Exercise: transforming trees with generic walks flatten1 = delay(lambda: nest(one_of('+') + flatten1.star() + end)
def an_instance(type_): return one_that(lambda x: isinstance(x, type_)) def capture1(p): return capture(p) >> (lambda x: x[0]) # Ouch var = capture1(anyone) ## (var + var)(eg) #. ('+', 2) calc = delay(lambda: nest(one_of('+') + calc + calc + end) >> add | nest(one_of('-') + calc + calc + end) >> sub | capture1(an_instance(int))) eg = ['+', 2, 3] ## match(calc, eg) #. (5,) eg2 = ['+', ['-', 2, 4], 3] ## match(calc, eg2) #. (1,) # Exercise: transforming trees with generic walks flatten1 = delay(lambda: nest(one_of('+') + flatten1.star() + end) | capture1(an_instance(int)))
def alt(pegs): return foldr(either, fail, pegs) def foldr(f, z, xs): for x in reversed(xs): z = f(x, z) return z # eg_calc.py example from operator import * from parson import delay _ = delay(lambda: g.FNORD) exp3 = delay(lambda: g.exp3) exp1 = PrececedenceParser(exp3, [ LeftAssoc(('*'+_, mul), ('//'+_, div), ('/'+_, truediv), ('%'+_, mod)), RightAssoc(('^'+_, pow)), ]) exps = PrececedenceParser(exp1, [ LeftAssoc(('+'+_, add), ('-'+_, sub)), ]) g = Grammar(r""" :exps :end. exp3 : '(' :exps ')'
def RuleRef(name): return delay((lambda: rules[name]), name) grammar = Grammar(g)(**globals())