Source

ppparse / demo / demo_arith.py

Full commit

from ppparse import make_scan, make_parse

LEX = """
SPACE:  [\s]+
        !skip
NUMBER: [\d]+
SYMBOL: [()*/+-]
        !symbol
"""

SYN = """
expr    : term
        | expr `+` term
        | expr `-` term
term    : factor
        | term `*` factor
        | term `/` factor
factor  : atom
        | `+` factor
        | `-` factor
atom    : NUMBER
        | `(` expr `)`
"""

EXAMPLES = [
        "2+2",
        "-34",
        "(-3+7)*4-1"
]

scan = make_scan(LEX)
parse = make_parse(SYN)

for text in EXAMPLES:
    print "="*79
    print "INPUT:", text
    print
    print "TOKENS:"
    tokens = scan(text)
    for token in tokens:
        print token
    print
    print "SYNTAX:"
    syntax = parse(tokens)
    print syntax
    print