request_handler.py 18 KB

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