Skip to content

Instantly share code, notes, and snippets.

@darius
Last active July 14, 2018 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darius/d8928685d4ba642b94a6b4a8d4fc1abe to your computer and use it in GitHub Desktop.
Save darius/d8928685d4ba642b94a6b4a8d4fc1abe to your computer and use it in GitHub Desktop.
another parson example
from parson import Grammar
g = r"""
_: /\s*/.
ns: /[0-9]+/.
num: {ns ('.' ns | '.') | '.' ns | ns} _ .
e: num {'**'} _ num :to_prefix | num.
m: e {'/'|'*'} _ m :to_prefix | e.
a: m {'+'|'-'} _ a :to_prefix | m.
"""
parsers = Grammar(g)(to_prefix=lambda left,op,right: (op,left,right))
parser = parsers.a
## parser('13 + 4 * 5 + 4 ** 3 * 1')
#. (('+', '13', ('+', ('*', '4', '5'), ('*', ('**', '4', '3'), '1'))),)
# This has the 'wrong' associativity:
## parser('5-4-3')
#. (('-', '5', ('-', '4', '3')),)
# So let's fix that, in the m: and a: rules.
# (BTW this isn't quite how I'd write it, e.g. I'd left-factor it more. I'm just sticking close to the original.)
g2 = r"""
_: /\s*/.
ns: /[0-9]+/.
num: {ns ('.' ns | '.') | '.' ns | ns} _ .
e: num {'**'} _ num :to_prefix | num.
m: e ({'/'|'*'} _ e :to_prefix)*.
a: m ({'+'|'-'} _ m :to_prefix)*.
"""
parsers2 = Grammar(g2)(to_prefix=lambda left,op,right: (op,left,right))
parser2 = parsers2.a
## parser2('13 + 4 * 5 + 4 ** 3 * 1')
#. (('+', ('+', '13', ('*', '4', '5')), ('*', ('**', '4', '3'), '1')),)
## parser2('5-4-3')
#. (('-', ('-', '5', '4'), '3'),)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment