request_handler.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. import sys
  2. import modelverse_kernel.primitives as primitive_functions
  3. import modelverse_jit.runtime as jit_runtime
  4. class KnownRequestHandled(Exception):
  5. """An exception that signifies that a known request was handled."""
  6. pass
  7. class GeneratorStackEntry(object):
  8. """An entry in the generator stack of a request handles."""
  9. __slots__ = ["generator", "function_name", "source_map", "function_origin", "pending_requests", "finished_requests", "replies"]
  10. def __init__(self, generator):
  11. self.generator = generator
  12. self.function_name = None
  13. self.source_map = None
  14. self.function_origin = None
  15. self.pending_requests = None
  16. self.finished_requests = True
  17. self.replies = None
  18. def __getattr__(self, varname):
  19. return None
  20. def format_stack_trace(stack_trace):
  21. """Formats a list of (function name, debug info, origin) triples."""
  22. return '\n'.join([jit_runtime.format_stack_frame(*triple) for triple in stack_trace])
  23. class UnhandledRequestHandlerException(Exception):
  24. """The type of exception that is thrown when the request handler encounters an
  25. unhandled exception."""
  26. def __init__(self, inner_exception, stack_trace):
  27. Exception.__init__(
  28. self,
  29. """The request handler encountered an unknown exception.\n
  30. Inner exception: %s\n
  31. Stack trace:\n%s\n""" % (inner_exception, format_stack_trace(stack_trace)))
  32. self.inner_exception = inner_exception
  33. self.stack_trace = stack_trace
  34. class RequestHandler(object):
  35. """A type of object that intercepts logic-related Modelverse requests, and
  36. forwards Modelverse state requests."""
  37. def __init__(self):
  38. # generator_stack is a stack of GeneratorStackEntry values.
  39. self.generator_stack = []
  40. # exception_handlers is a stack of
  41. # (generator_stack index, [(exception type, handler function)])
  42. # tuples.
  43. self.exception_handlers = []
  44. self.produce_stack_trace = True
  45. self.handlers = {
  46. 'CALL' : self.execute_call,
  47. 'CALL_ARGS' : self.execute_call_args,
  48. 'CALL_KWARGS' : self.execute_call_kwargs,
  49. 'TAIL_CALL' : self.execute_tail_call,
  50. 'TAIL_CALL_ARGS' : self.execute_tail_call_args,
  51. 'TAIL_CALL_KWARGS' : self.execute_tail_call_kwargs,
  52. 'TRY' : self.execute_try,
  53. 'CATCH' : self.execute_catch,
  54. 'END_TRY' : self.execute_end_try,
  55. 'DEBUG_INFO' : self.execute_debug_info
  56. }
  57. def is_active(self):
  58. """Tests if this request handler has a top-of-stack generator."""
  59. return len(self.generator_stack) > 0
  60. def handle_request(self, reply):
  61. """Replies to a request from the top-of-stack generator, and returns a new request."""
  62. if not self.is_active():
  63. raise ValueError('handle_request cannot be called with an empty generator stack.')
  64. # Append the server's replies to the list of replies.
  65. if reply is not None:
  66. if self.generator_stack[-1].replies is None:
  67. self.generator_stack[-1].replies = reply
  68. else:
  69. self.generator_stack[-1].replies.extend(reply)
  70. while 1:
  71. # Silence pylint's warning about catching Exception.
  72. # pylint: disable=I0011,W0703
  73. try:
  74. while self.generator_stack[-1].finished_requests:
  75. gen = self.generator_stack[-1]
  76. gen.pending_requests = gen.generator.send(gen.replies)
  77. gen.finished_requests = False
  78. gen.replies = None
  79. else:
  80. return self.pop_requests()
  81. except KnownRequestHandled:
  82. pass
  83. except StopIteration:
  84. # Done, so remove the generator
  85. self.pop_generator()
  86. if self.is_active():
  87. # This generator was called from another generator.
  88. # Append 'None' to the caller's list of replies.
  89. self.append_reply(None)
  90. else:
  91. # Looks like we're done here.
  92. return None
  93. except primitive_functions.PrimitiveFinished as ex:
  94. # Done, so remove the generator
  95. self.pop_generator()
  96. if self.is_active():
  97. # This generator was called from another generator.
  98. # Append the callee's result to the caller's list of replies.
  99. self.append_reply(ex.result)
  100. else:
  101. # Looks like we're done here.
  102. return None
  103. except Exception as ex:
  104. # Maybe get an exception handler to do this.
  105. stack_trace = self.handle_exception(ex)
  106. if stack_trace is not None:
  107. if self.produce_stack_trace:
  108. raise UnhandledRequestHandlerException(ex, stack_trace)
  109. else:
  110. raise
  111. def set_finished_requests_flag(self):
  112. """Sets the finished_requests flag in the top-of-stack tuple."""
  113. self.generator_stack[-1].finished_requests = True
  114. def has_pending_requests(self):
  115. """Tests if the top-of-stack generator has pending requests."""
  116. return not self.generator_stack[-1].finished_requests
  117. def push_generator(self, gen):
  118. """Pushes a new generator onto the stack."""
  119. self.generator_stack.append(GeneratorStackEntry(gen))
  120. # print('Pushed generator %s. Generator count: %d' % (gen, len(self.generator_stack)))
  121. def pop_generator(self):
  122. """Removes the top-of-stack generator from the generator stack."""
  123. # Pop the generator itself.
  124. self.generator_stack.pop()
  125. # print('Popped generator %s. Generator count: %d' % (gen, len(self.generator_stack)))
  126. # Pop any exception handlers defined by the generator.
  127. top_of_stack_index = len(self.generator_stack)
  128. while len(self.exception_handlers) > 0:
  129. stack_index, _ = self.exception_handlers[-1]
  130. if stack_index == top_of_stack_index:
  131. # Pop exception handlers until exception_handlers is empty or until
  132. # we find an exception handler that is not associated with the popped
  133. # generator.
  134. self.exception_handlers.pop()
  135. else:
  136. # We're done here.
  137. break
  138. def append_reply(self, new_reply):
  139. """Appends a reply to the top-of-stack generator's list of pending replies."""
  140. if self.generator_stack[-1].replies is None:
  141. self.generator_stack[-1].replies = [new_reply]
  142. else:
  143. self.generator_stack[-1].replies.append(new_reply)
  144. def handle_exception(self, exception):
  145. """Handles the given exception. A Boolean is returned that tells if
  146. the exception was handled."""
  147. # print('Exception thrown from %s: %s' % (str(self.generator_stack[-1]), str(exception)))
  148. while len(self.exception_handlers) > 0:
  149. # Pop the top-of-stack exception handler.
  150. stack_index, handlers = self.exception_handlers.pop()
  151. # Try to find an applicable handler.
  152. applicable_handler = None
  153. for handled_type, handler in handlers:
  154. if isinstance(exception, handled_type):
  155. applicable_handler = handler
  156. if applicable_handler is not None:
  157. # We handle exceptions by first clearing the current stack frame and
  158. # all of its children. Then, we place a dummy frame on the stack with
  159. # a single 'TAIL_CALL_ARGS' request. The next iteration will replace
  160. # the dummy frame by an actual frame.
  161. del self.generator_stack[stack_index:]
  162. stack_entry = GeneratorStackEntry(None)
  163. stack_entry.pending_requests = [
  164. ('TAIL_CALL_ARGS', [applicable_handler, (exception,)])]
  165. stack_entry.finished_requests = False
  166. self.generator_stack.append(stack_entry)
  167. return None
  168. # We couldn't find an applicable exception handler, even after exhausting the
  169. # entire exception handler stack. All is lost.
  170. # Also, clean up after ourselves by unwinding the stack.
  171. return self.unwind_stack()
  172. def unwind_stack(self):
  173. """Unwinds the entirety of the stack. All generators and exception handlers are
  174. discarded. A list of (function name, debug information, source) statements is
  175. returned."""
  176. class UnwindStackException(Exception):
  177. """A hard-to-catch exception that is used to make generators crash.
  178. The exceptions they produce can then be analyzed for line numbers."""
  179. pass
  180. # First throw away all exception handlers. We won't be needing them any more.
  181. self.exception_handlers = []
  182. # Then pop every generator from the stack and make it crash.
  183. stack_trace = []
  184. while len(self.generator_stack) > 0:
  185. top_entry = self.generator_stack.pop()
  186. if top_entry.function_origin is None:
  187. # Skip this function.
  188. continue
  189. try:
  190. # Crash the generator.
  191. top_entry.generator.throw(UnwindStackException())
  192. except UnwindStackException:
  193. # Find out where the exception was thrown.
  194. _, _, exc_traceback = sys.exc_info()
  195. line_number = exc_traceback.tb_lineno
  196. source_map = top_entry.source_map
  197. if source_map is not None:
  198. debug_info = source_map.get_debug_info(line_number)
  199. else:
  200. debug_info = None
  201. function_name = top_entry.function_name
  202. stack_trace.append((function_name, debug_info, top_entry.function_origin))
  203. return stack_trace[::-1]
  204. def pop_requests(self):
  205. """Tries to pop a batch of Modelverse _state_ requests from the
  206. current list of requests. Known requests are executed immediately.
  207. A list of requests and a Boolean are returned. The latter is True
  208. if there are no more requests to process, and false otherwise."""
  209. requests = self.generator_stack[-1].pending_requests
  210. if requests is None or len(requests) == 0:
  211. # Couldn't find a request for the state to handle.
  212. self.set_finished_requests_flag()
  213. return requests
  214. for i, elem in enumerate(requests):
  215. if elem[0] in self.handlers:
  216. # The kernel should handle known requests.
  217. if i > 0:
  218. # Handle any requests that precede the known request first.
  219. pre_requests = requests[:i]
  220. del requests[:i]
  221. return pre_requests
  222. # The known request must be the first element in the list. Pop it.
  223. requests.pop(0)
  224. # The list of requests might be empty now. If so, then flag this
  225. # batch of requests as finished.
  226. if len(requests) == 0:
  227. self.set_finished_requests_flag()
  228. # Handle the request.
  229. _, request_args = elem
  230. self.handlers[elem[0]](request_args)
  231. raise KnownRequestHandled()
  232. # We couldn't find a known request in the batch of requests, so we might as well
  233. # handle them all at once then.
  234. self.set_finished_requests_flag()
  235. return requests
  236. def execute_call(self, request_args):
  237. """Executes a CALL-request with the given argument list."""
  238. # Format: ("CALL", [gen])
  239. gen, = request_args
  240. self.push_generator(gen)
  241. def execute_call_kwargs(self, request_args):
  242. """Executes a CALL_KWARGS-request with the given argument list."""
  243. # Format: ("CALL_KWARGS", [func, kwargs])
  244. # This format is useful because it also works for functions that
  245. # throw an exception but never yield.
  246. func, kwargs = request_args
  247. # We need to be extra careful here, because func(**kwargs) might
  248. # not be a generator at all: it might simply be a method that
  249. # raises an exception. To cope with this we need to push a dummy
  250. # entry onto the stack if a StopIteration or PrimtiveFinished
  251. # exception is thrown. The logic in execute_yields will then pop
  252. # that dummy entry.
  253. try:
  254. self.push_generator(func(**kwargs))
  255. except StopIteration:
  256. self.push_generator(None)
  257. raise
  258. except primitive_functions.PrimitiveFinished:
  259. self.push_generator(None)
  260. raise
  261. def execute_call_args(self, request_args):
  262. """Executes a CALL_ARGS-request with the given argument list."""
  263. # Format: ("CALL_ARGS", [gen, args])
  264. func, args = request_args
  265. # We need to be extra careful here, because func(*args) might
  266. # not be a generator at all: it might simply be a method that
  267. # raises an exception. To cope with this we need to push a dummy
  268. # entry onto the stack if a StopIteration or PrimtiveFinished
  269. # exception is thrown. The logic in execute_yields will then pop
  270. # that dummy entry.
  271. try:
  272. self.push_generator(func(*args))
  273. except StopIteration:
  274. self.push_generator(None)
  275. raise
  276. except primitive_functions.PrimitiveFinished:
  277. self.push_generator(None)
  278. raise
  279. def execute_tail_call(self, request_args):
  280. """Executes a TAIL_CALL-request with the given argument list."""
  281. # Format: ("TAIL_CALL", [gen])
  282. self.pop_generator()
  283. self.execute_call(request_args)
  284. def execute_tail_call_args(self, request_args):
  285. """Executes a TAIL_CALL_ARGS-request with the given argument list."""
  286. # Format: ("TAIL_CALL_ARGS", [gen, args])
  287. self.pop_generator()
  288. self.execute_call_args(request_args)
  289. def execute_tail_call_kwargs(self, request_args):
  290. """Executes a TAIL_CALL_KWARGS-request with the given argument list."""
  291. # Format: ("TAIL_CALL_KWARGS", [gen, kwargs])
  292. self.pop_generator()
  293. self.execute_call_kwargs(request_args)
  294. def execute_try(self, request_args):
  295. """Executes a TRY-request with the given argument list."""
  296. # TRY pushes an exception handler onto the exception handler stack.
  297. # Format: ("TRY", [])
  298. if len(request_args) != 0:
  299. raise ValueError(
  300. ("TRY was given argument list '%s', " +
  301. "expected exactly zero arguments.") % repr(request_args))
  302. self.exception_handlers.append((len(self.generator_stack) - 1, []))
  303. self.append_reply(None)
  304. def execute_catch(self, request_args):
  305. """Executes a CATCH-request with the given argument list."""
  306. if len(request_args) != 2:
  307. raise ValueError(
  308. ("CATCH was given argument list '%s', "
  309. "expected exactly two arguments: an exception "
  310. "type and an exception handler.") % repr(request_args))
  311. exception_type, handler = request_args
  312. stack_index, handlers = self.exception_handlers[-1]
  313. if stack_index != len(self.generator_stack) - 1:
  314. raise ValueError(
  315. 'Cannot comply with CATCH because there is no exception handler for the '
  316. 'current generator.')
  317. handlers.append((exception_type, handler))
  318. self.append_reply(None)
  319. def execute_end_try(self, request_args):
  320. """Executes an END_TRY-request with the given argument list."""
  321. # END_TRY pops a value from the exception handler stack. The
  322. # popped value must reference the top-of-stack element in the
  323. # generator stack. END_TRY takes no arguments.
  324. # Format: ("END_TRY", [])
  325. if len(request_args) != 0:
  326. raise ValueError(
  327. "END_TRY was given argument list '%s', expected '%s'." % (
  328. repr(request_args), repr([])))
  329. if len(self.exception_handlers) == 0:
  330. raise ValueError(
  331. 'Cannot comply with END_TRY because the exception handler stack is empty.')
  332. stack_index, _ = self.exception_handlers[-1]
  333. if stack_index != len(self.generator_stack) - 1:
  334. raise ValueError(
  335. 'Cannot comply with END_TRY because there is no exception handler for the '
  336. 'current generator.')
  337. # Everything seems to be in order. Pop the exception handler.
  338. self.exception_handlers.pop()
  339. self.append_reply(None)
  340. def execute_debug_info(self, request_args):
  341. """Executes a DEBUG_INFO-request with the given argument list."""
  342. # DEBUG_INFO updates the function name and source map for the top-of-stack generator.
  343. # These two things allow us to unwind the stack neatly if an unhandled exception is
  344. # encountered.
  345. # Format: ("DEBUG_INFO", [function_name, source_map])
  346. top_entry = self.generator_stack[-1]
  347. top_entry.function_name, top_entry.source_map, top_entry.function_origin = request_args
  348. self.append_reply(None)