runtime.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import modelverse_kernel.primitives as primitive_functions
  2. class JitCompilationFailedException(Exception):
  3. """A type of exception that is raised when the jit fails to compile a function."""
  4. pass
  5. MUTABLE_FUNCTION_KEY = "mutable"
  6. """A dictionary key for functions that are mutable."""
  7. FUNCTION_BODY_KEY = "body"
  8. """A dictionary key for function bodies."""
  9. KWARGS_PARAMETER_NAME = "kwargs"
  10. """The name of the kwargs parameter in jitted functions."""
  11. CALL_FUNCTION_NAME = "__call_function"
  12. """The name of the '__call_function' function, in the jitted function scope."""
  13. GET_INPUT_FUNCTION_NAME = "__get_input"
  14. """The name of the '__get_input' function, in the jitted function scope."""
  15. LOCALS_NODE_NAME = "jit_locals"
  16. """The name of the node that is connected to all JIT locals in a given function call."""
  17. LOCALS_EDGE_NAME = "jit_locals_edge"
  18. """The name of the edge that connects the LOCALS_NODE_NAME node to a user root."""
  19. def call_function(function_id, named_arguments, **kwargs):
  20. """Runs the function with the given id, passing it the specified argument dictionary."""
  21. user_root = kwargs['user_root']
  22. kernel = kwargs['mvk']
  23. body_id, is_mutable = yield [
  24. ("RD", [function_id, FUNCTION_BODY_KEY]),
  25. ("RD", [function_id, MUTABLE_FUNCTION_KEY])]
  26. # Try to jit the function here. We might be able to avoid building the stack
  27. # frame.
  28. def handle_jit_failed(_):
  29. """Interprets the function."""
  30. interpreter_args = {'function_id' : function_id, 'named_arguments' : named_arguments}
  31. interpreter_args.update(kwargs)
  32. yield [("TAIL_CALL_KWARGS", [interpret_function, interpreter_args])]
  33. if is_mutable is not None:
  34. kernel.jit.mark_no_jit(body_id)
  35. yield [("TAIL_CALL_ARGS", [handle_jit_failed, ()])]
  36. else:
  37. kernel.jit.mark_entry_point(body_id)
  38. yield [("TRY", [])]
  39. yield [("CATCH", [JitCompilationFailedException, handle_jit_failed])]
  40. # Try to compile.
  41. compiled_func, = yield [("CALL_ARGS", [kernel.jit_compile, (user_root, body_id)])]
  42. yield [("END_TRY", [])]
  43. # Add the keyword arguments to the argument dictionary.
  44. named_arguments.update(kwargs)
  45. # Run the function.
  46. yield [("TAIL_CALL_KWARGS", [compiled_func, named_arguments])]
  47. def interpret_function(function_id, named_arguments, **kwargs):
  48. """Makes the interpreter run the function with the given id for the specified
  49. argument dictionary."""
  50. user_root = kwargs['user_root']
  51. kernel = kwargs['mvk']
  52. user_frame, = yield [("RD", [user_root, "frame"])]
  53. inst, body_id = yield [("RD", [user_frame, "IP"]), ("RD", [function_id, FUNCTION_BODY_KEY])]
  54. kernel.jit.mark_entry_point(body_id)
  55. # Create a new stack frame.
  56. frame_link, new_phase, new_frame, new_evalstack, new_symbols, \
  57. new_returnvalue, intrinsic_return = \
  58. yield [("RDE", [user_root, "frame"]),
  59. ("CNV", ["init"]),
  60. ("CN", []),
  61. ("CN", []),
  62. ("CN", []),
  63. ("CN", []),
  64. ("CN", [])
  65. ]
  66. _, _, _, _, _, _, _, _, _, _ = \
  67. yield [("CD", [user_root, "frame", new_frame]),
  68. ("CD", [new_frame, "evalstack", new_evalstack]),
  69. ("CD", [new_frame, "symbols", new_symbols]),
  70. ("CD", [new_frame, "returnvalue", new_returnvalue]),
  71. ("CD", [new_frame, "caller", inst]),
  72. ("CD", [new_frame, "phase", new_phase]),
  73. ("CD", [new_frame, "IP", body_id]),
  74. ("CD", [new_frame, "prev", user_frame]),
  75. ("CD", [
  76. new_frame,
  77. primitive_functions.EXCEPTION_RETURN_KEY,
  78. intrinsic_return]),
  79. ("DE", [frame_link])
  80. ]
  81. # Put the parameters in the new stack frame's symbol table.
  82. (parameter_vars, parameter_names, _), = yield [
  83. ("CALL_ARGS", [kernel.jit.jit_signature, (body_id,)])]
  84. parameter_dict = dict(zip(parameter_names, parameter_vars))
  85. for (key, value) in named_arguments.items():
  86. param_var = parameter_dict[key]
  87. variable, = yield [("CN", [])]
  88. yield [("CD", [variable, "value", value])]
  89. symbol_edge, = yield [("CE", [new_symbols, variable])]
  90. yield [("CE", [symbol_edge, param_var])]
  91. username = kwargs['username']
  92. def exception_handler(ex):
  93. # print('Returning from interpreted function. Result: %s' % ex.result)
  94. raise primitive_functions.PrimitiveFinished(ex.result)
  95. # Create an exception handler to catch and translate InterpretedFunctionFinished.
  96. yield [("TRY", [])]
  97. yield [("CATCH", [primitive_functions.InterpretedFunctionFinished, exception_handler])]
  98. while 1:
  99. result, = yield [("CALL_ARGS", [kernel.execute_rule, (username,)])]
  100. # An instruction has completed. Forward it.
  101. yield result
  102. def get_input(**parameters):
  103. """Retrieves input."""
  104. mvk = parameters["mvk"]
  105. user_root = parameters["user_root"]
  106. while 1:
  107. yield [("CALL_ARGS", [mvk.input_init, (user_root,)])]
  108. # Finished
  109. if mvk.success:
  110. # Got some input, so we can access it
  111. raise primitive_functions.PrimitiveFinished(mvk.input_value)
  112. else:
  113. # No input, so yield None but don't stop
  114. yield None