lark/examples/calc.py

72 lines
1.3 KiB
Python
Raw Normal View History

#
# This example shows how to write a basic calculator with variables.
#
2017-02-11 09:12:15 +00:00
from lark import Lark, InlineTransformer
2017-02-05 11:40:19 +00:00
2017-02-15 08:00:01 +00:00
try:
input = raw_input
except NameError:
pass
2017-02-05 11:40:19 +00:00
calc_grammar = """
?start: sum
| NAME "=" sum -> assign_var
?sum: product
| sum "+" product -> add
| sum "-" product -> sub
?product: atom
| product "*" atom -> mul
| product "/" atom -> div
2017-02-23 17:08:23 +00:00
?atom: DECIMAL -> number
2017-02-05 11:40:19 +00:00
| "-" atom -> neg
| NAME -> var
| "(" sum ")"
2017-02-23 17:08:23 +00:00
%import common.CNAME -> NAME
%import common.DECIMAL
%import common.WS_INLINE
2017-02-23 17:08:23 +00:00
%ignore WS_INLINE
2017-02-05 11:40:19 +00:00
"""
class CalculateTree(InlineTransformer):
from operator import add, sub, mul, truediv as div, neg
2017-02-05 11:40:19 +00:00
number = float
def __init__(self):
self.vars = {}
def assign_var(self, name, value):
self.vars[name] = value
return value
def var(self, name):
return self.vars[name]
calc_parser = Lark(calc_grammar, parser='lalr', transformer=CalculateTree())
calc = calc_parser.parse
def main():
while True:
try:
2017-02-15 08:00:01 +00:00
s = input('> ')
2017-02-05 11:40:19 +00:00
except EOFError:
break
print(calc(s))
def test():
print(calc("a = 1+2"))
print(calc("1+a*-3"))
2017-02-05 11:40:19 +00:00
if __name__ == '__main__':
2017-02-15 08:00:01 +00:00
# test()
main()
2017-02-05 11:40:19 +00:00