This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.4 KiB

  1. #
  2. # This example shows how to write a basic calculator with variables.
  3. #
  4. from lark import Lark, Transformer, v_args
  5. try:
  6. input = raw_input # For Python2 compatibility
  7. except NameError:
  8. pass
  9. calc_grammar = """
  10. ?start: sum
  11. | NAME "=" sum -> assign_var
  12. ?sum: product
  13. | sum "+" product -> add
  14. | sum "-" product -> sub
  15. ?product: atom
  16. | product "*" atom -> mul
  17. | product "/" atom -> div
  18. ?atom: NUMBER -> number
  19. | "-" atom -> neg
  20. | NAME -> var
  21. | "(" sum ")"
  22. %import common.CNAME -> NAME
  23. %import common.NUMBER
  24. %import common.WS_INLINE
  25. %ignore WS_INLINE
  26. """
  27. @v_args(inline=True) # Affects the signatures of the methods
  28. class CalculateTree(Transformer):
  29. from operator import add, sub, mul, truediv as div, neg
  30. number = float
  31. def __init__(self):
  32. self.vars = {}
  33. def assign_var(self, name, value):
  34. self.vars[name] = value
  35. return value
  36. def var(self, name):
  37. return self.vars[name]
  38. calc_parser = Lark(calc_grammar, parser='lalr', transformer=CalculateTree())
  39. calc = calc_parser.parse
  40. def main():
  41. while True:
  42. try:
  43. s = input('> ')
  44. except EOFError:
  45. break
  46. print(calc(s))
  47. def test():
  48. print(calc("a = 1+2"))
  49. print(calc("1+a*-3"))
  50. if __name__ == '__main__':
  51. # test()
  52. main()