prompt.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import readline
  2. import termcolor
  3. from sccd.action_lang.dynamic.memory import *
  4. from sccd.action_lang.parser.text import *
  5. from lark.exceptions import *
  6. if __name__ == "__main__":
  7. scope = Scope("interactive", parent=None) # "global" scope
  8. memory = Memory()
  9. memory.push_frame(scope)
  10. readline.set_history_length(1000)
  11. print("Enter statements or expressions. Most statements end with ';'. Statements will be executed, expressions will be evaluated. Either can have side effects.")
  12. print("Examples:")
  13. print(" basic stuff:")
  14. print(" greeting = \"hello\";")
  15. print(" to_whom = \" world\";")
  16. print(" greeting + to_whom")
  17. print(" more interesting: higher order functions:")
  18. print(" apply = func(i: int, f: func(int) -> int) { return f(i); } ;")
  19. print(" apply(10, func(i: int) { return i+1; })")
  20. print()
  21. parser = ActionLangParser()
  22. while True:
  23. try:
  24. line = input("> ")
  25. try:
  26. # Attempt to parse as a statement
  27. stmt = parser.parse_stmt(line) # may raise LarkError
  28. stmt.init_stmt(scope)
  29. # Grow current stack frame if necessary
  30. diff = scope.size() - len(memory.current_frame().storage)
  31. if diff > 0:
  32. memory.current_frame().storage.extend([None]*diff)
  33. stmt.exec(memory)
  34. except LarkError as e:
  35. try:
  36. # Attempt to parse as an expression
  37. expr = parser.parse_expr(line)
  38. expr_type = expr.init_expr(scope)
  39. val = expr.eval(memory)
  40. print("%s: %s" % (str(val), str(expr_type)))
  41. except LarkError:
  42. raise e
  43. except (UnexpectedToken, UnexpectedCharacters) as e:
  44. print(" " + " "*e.column + "^")
  45. print(type(e).__name__+":", e)
  46. except (LarkError, ModelStaticError, ModelRuntimeError) as e:
  47. print(type(e).__name__+":", e)
  48. except (KeyboardInterrupt, EOFError):
  49. print()
  50. exit()