request_handler.py 18 KB

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