runtime.py 6.1 KB

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