request_handler.py 18 KB

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