PageRenderTime 32ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/interpreter/pyopcode.py

https://bitbucket.org/pypy/pypy/
Python | 1659 lines | 1402 code | 164 blank | 93 comment | 256 complexity | 8cdce73f5fbfb12e4c8fe85eb6638347 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. """
  2. Implementation of a part of the standard Python opcodes.
  3. The rest, dealing with variables in optimized ways, is in nestedscope.py.
  4. """
  5. from rpython.rlib import jit, rstackovf
  6. from rpython.rlib.debug import check_nonneg
  7. from rpython.rlib.objectmodel import we_are_translated
  8. from rpython.rlib.rarithmetic import r_uint, intmask
  9. from rpython.tool.sourcetools import func_with_new_name
  10. from pypy.interpreter import (
  11. gateway, function, eval, pyframe, pytraceback, pycode
  12. )
  13. from pypy.interpreter.baseobjspace import W_Root
  14. from pypy.interpreter.error import OperationError, oefmt
  15. from pypy.interpreter.nestedscope import Cell
  16. from pypy.interpreter.pycode import PyCode, BytecodeCorruption
  17. from pypy.tool.stdlib_opcode import bytecode_spec
  18. def unaryoperation(operationname):
  19. """NOT_RPYTHON"""
  20. def opimpl(self, *ignored):
  21. operation = getattr(self.space, operationname)
  22. w_1 = self.popvalue()
  23. w_result = operation(w_1)
  24. self.pushvalue(w_result)
  25. opimpl.unaryop = operationname
  26. return func_with_new_name(opimpl, "opcode_impl_for_%s" % operationname)
  27. def binaryoperation(operationname):
  28. """NOT_RPYTHON"""
  29. def opimpl(self, *ignored):
  30. operation = getattr(self.space, operationname)
  31. w_2 = self.popvalue()
  32. w_1 = self.popvalue()
  33. w_result = operation(w_1, w_2)
  34. self.pushvalue(w_result)
  35. opimpl.binop = operationname
  36. return func_with_new_name(opimpl, "opcode_impl_for_%s" % operationname)
  37. opcodedesc = bytecode_spec.opcodedesc
  38. HAVE_ARGUMENT = bytecode_spec.HAVE_ARGUMENT
  39. class __extend__(pyframe.PyFrame):
  40. """A PyFrame that knows about interpretation of standard Python opcodes
  41. minus the ones related to nested scopes."""
  42. ### opcode dispatch ###
  43. def dispatch(self, pycode, next_instr, ec):
  44. # For the sequel, force 'next_instr' to be unsigned for performance
  45. next_instr = r_uint(next_instr)
  46. co_code = pycode.co_code
  47. try:
  48. while True:
  49. next_instr = self.handle_bytecode(co_code, next_instr, ec)
  50. except ExitFrame:
  51. self.last_exception = None
  52. return self.popvalue()
  53. def handle_bytecode(self, co_code, next_instr, ec):
  54. try:
  55. next_instr = self.dispatch_bytecode(co_code, next_instr, ec)
  56. except OperationError as operr:
  57. next_instr = self.handle_operation_error(ec, operr)
  58. except RaiseWithExplicitTraceback as e:
  59. next_instr = self.handle_operation_error(ec, e.operr,
  60. attach_tb=False)
  61. except KeyboardInterrupt:
  62. next_instr = self.handle_asynchronous_error(ec,
  63. self.space.w_KeyboardInterrupt)
  64. except MemoryError:
  65. next_instr = self.handle_asynchronous_error(ec,
  66. self.space.w_MemoryError)
  67. except rstackovf.StackOverflow as e:
  68. # Note that this case catches AttributeError!
  69. rstackovf.check_stack_overflow()
  70. next_instr = self.handle_asynchronous_error(ec,
  71. self.space.w_RuntimeError,
  72. self.space.wrap("maximum recursion depth exceeded"))
  73. return next_instr
  74. def handle_asynchronous_error(self, ec, w_type, w_value=None):
  75. # catch asynchronous exceptions and turn them
  76. # into OperationErrors
  77. if w_value is None:
  78. w_value = self.space.w_None
  79. operr = OperationError(w_type, w_value)
  80. return self.handle_operation_error(ec, operr)
  81. def handle_operation_error(self, ec, operr, attach_tb=True):
  82. if attach_tb:
  83. if 1:
  84. # xxx this is a hack. It allows bytecode_trace() to
  85. # call a signal handler which raises, and catch the
  86. # raised exception immediately. See test_alarm_raise in
  87. # pypy/module/signal/test/test_signal.py. Without the
  88. # next four lines, if an external call (like
  89. # socket.accept()) is interrupted by a signal, it raises
  90. # an exception carrying EINTR which arrives here,
  91. # entering the next "except" block -- but the signal
  92. # handler is then called on the next call to
  93. # dispatch_bytecode(), causing the real exception to be
  94. # raised after the exception handler block was popped.
  95. try:
  96. trace = self.get_w_f_trace()
  97. if trace is not None:
  98. self.getorcreatedebug().w_f_trace = None
  99. try:
  100. ec.bytecode_trace_after_exception(self)
  101. finally:
  102. if trace is not None:
  103. self.getorcreatedebug().w_f_trace = trace
  104. except OperationError as e:
  105. operr = e
  106. pytraceback.record_application_traceback(
  107. self.space, operr, self, self.last_instr)
  108. ec.exception_trace(self, operr)
  109. block = self.unrollstack(SApplicationException.kind)
  110. if block is None:
  111. # no handler found for the OperationError
  112. if we_are_translated():
  113. raise operr
  114. else:
  115. # try to preserve the CPython-level traceback
  116. import sys
  117. tb = sys.exc_info()[2]
  118. raise OperationError, operr, tb
  119. else:
  120. unroller = SApplicationException(operr)
  121. next_instr = block.handle(self, unroller)
  122. return next_instr
  123. def call_contextmanager_exit_function(self, w_func, w_typ, w_val, w_tb):
  124. return self.space.call_function(w_func, w_typ, w_val, w_tb)
  125. @jit.unroll_safe
  126. def dispatch_bytecode(self, co_code, next_instr, ec):
  127. while True:
  128. self.last_instr = intmask(next_instr)
  129. if jit.we_are_jitted():
  130. ec.bytecode_only_trace(self)
  131. else:
  132. ec.bytecode_trace(self)
  133. next_instr = r_uint(self.last_instr)
  134. opcode = ord(co_code[next_instr])
  135. next_instr += 1
  136. if opcode >= HAVE_ARGUMENT:
  137. lo = ord(co_code[next_instr])
  138. hi = ord(co_code[next_instr+1])
  139. next_instr += 2
  140. oparg = (hi * 256) | lo
  141. else:
  142. oparg = 0
  143. # note: the structure of the code here is such that it makes
  144. # (after translation) a big "if/elif" chain, which is then
  145. # turned into a switch().
  146. while opcode == opcodedesc.EXTENDED_ARG.index:
  147. opcode = ord(co_code[next_instr])
  148. if opcode < HAVE_ARGUMENT:
  149. raise BytecodeCorruption
  150. lo = ord(co_code[next_instr+1])
  151. hi = ord(co_code[next_instr+2])
  152. next_instr += 3
  153. oparg = (oparg * 65536) | (hi * 256) | lo
  154. if opcode == opcodedesc.RETURN_VALUE.index:
  155. w_returnvalue = self.popvalue()
  156. block = self.unrollstack(SReturnValue.kind)
  157. if block is None:
  158. self.pushvalue(w_returnvalue) # XXX ping pong
  159. raise Return
  160. else:
  161. unroller = SReturnValue(w_returnvalue)
  162. next_instr = block.handle(self, unroller)
  163. return next_instr # now inside a 'finally' block
  164. elif opcode == opcodedesc.END_FINALLY.index:
  165. unroller = self.end_finally()
  166. if isinstance(unroller, SuspendedUnroller):
  167. # go on unrolling the stack
  168. block = self.unrollstack(unroller.kind)
  169. if block is None:
  170. w_result = unroller.nomoreblocks()
  171. self.pushvalue(w_result)
  172. raise Return
  173. else:
  174. next_instr = block.handle(self, unroller)
  175. return next_instr
  176. elif opcode == opcodedesc.JUMP_ABSOLUTE.index:
  177. return self.jump_absolute(oparg, ec)
  178. elif opcode == opcodedesc.BREAK_LOOP.index:
  179. next_instr = self.BREAK_LOOP(oparg, next_instr)
  180. elif opcode == opcodedesc.CONTINUE_LOOP.index:
  181. return self.CONTINUE_LOOP(oparg, next_instr)
  182. elif opcode == opcodedesc.FOR_ITER.index:
  183. next_instr = self.FOR_ITER(oparg, next_instr)
  184. elif opcode == opcodedesc.JUMP_FORWARD.index:
  185. next_instr = self.JUMP_FORWARD(oparg, next_instr)
  186. elif opcode == opcodedesc.JUMP_IF_FALSE_OR_POP.index:
  187. next_instr = self.JUMP_IF_FALSE_OR_POP(oparg, next_instr)
  188. elif opcode == opcodedesc.JUMP_IF_NOT_DEBUG.index:
  189. next_instr = self.JUMP_IF_NOT_DEBUG(oparg, next_instr)
  190. elif opcode == opcodedesc.JUMP_IF_TRUE_OR_POP.index:
  191. next_instr = self.JUMP_IF_TRUE_OR_POP(oparg, next_instr)
  192. elif opcode == opcodedesc.POP_JUMP_IF_FALSE.index:
  193. next_instr = self.POP_JUMP_IF_FALSE(oparg, next_instr)
  194. elif opcode == opcodedesc.POP_JUMP_IF_TRUE.index:
  195. next_instr = self.POP_JUMP_IF_TRUE(oparg, next_instr)
  196. elif opcode == opcodedesc.BINARY_ADD.index:
  197. self.BINARY_ADD(oparg, next_instr)
  198. elif opcode == opcodedesc.BINARY_AND.index:
  199. self.BINARY_AND(oparg, next_instr)
  200. elif opcode == opcodedesc.BINARY_DIVIDE.index:
  201. self.BINARY_DIVIDE(oparg, next_instr)
  202. elif opcode == opcodedesc.BINARY_FLOOR_DIVIDE.index:
  203. self.BINARY_FLOOR_DIVIDE(oparg, next_instr)
  204. elif opcode == opcodedesc.BINARY_LSHIFT.index:
  205. self.BINARY_LSHIFT(oparg, next_instr)
  206. elif opcode == opcodedesc.BINARY_MODULO.index:
  207. self.BINARY_MODULO(oparg, next_instr)
  208. elif opcode == opcodedesc.BINARY_MULTIPLY.index:
  209. self.BINARY_MULTIPLY(oparg, next_instr)
  210. elif opcode == opcodedesc.BINARY_OR.index:
  211. self.BINARY_OR(oparg, next_instr)
  212. elif opcode == opcodedesc.BINARY_POWER.index:
  213. self.BINARY_POWER(oparg, next_instr)
  214. elif opcode == opcodedesc.BINARY_RSHIFT.index:
  215. self.BINARY_RSHIFT(oparg, next_instr)
  216. elif opcode == opcodedesc.BINARY_SUBSCR.index:
  217. self.BINARY_SUBSCR(oparg, next_instr)
  218. elif opcode == opcodedesc.BINARY_SUBTRACT.index:
  219. self.BINARY_SUBTRACT(oparg, next_instr)
  220. elif opcode == opcodedesc.BINARY_TRUE_DIVIDE.index:
  221. self.BINARY_TRUE_DIVIDE(oparg, next_instr)
  222. elif opcode == opcodedesc.BINARY_XOR.index:
  223. self.BINARY_XOR(oparg, next_instr)
  224. elif opcode == opcodedesc.BUILD_CLASS.index:
  225. self.BUILD_CLASS(oparg, next_instr)
  226. elif opcode == opcodedesc.BUILD_LIST.index:
  227. self.BUILD_LIST(oparg, next_instr)
  228. elif opcode == opcodedesc.BUILD_LIST_FROM_ARG.index:
  229. self.BUILD_LIST_FROM_ARG(oparg, next_instr)
  230. elif opcode == opcodedesc.BUILD_MAP.index:
  231. self.BUILD_MAP(oparg, next_instr)
  232. elif opcode == opcodedesc.BUILD_SET.index:
  233. self.BUILD_SET(oparg, next_instr)
  234. elif opcode == opcodedesc.BUILD_SLICE.index:
  235. self.BUILD_SLICE(oparg, next_instr)
  236. elif opcode == opcodedesc.BUILD_TUPLE.index:
  237. self.BUILD_TUPLE(oparg, next_instr)
  238. elif opcode == opcodedesc.CALL_FUNCTION.index:
  239. self.CALL_FUNCTION(oparg, next_instr)
  240. elif opcode == opcodedesc.CALL_FUNCTION_KW.index:
  241. self.CALL_FUNCTION_KW(oparg, next_instr)
  242. elif opcode == opcodedesc.CALL_FUNCTION_VAR.index:
  243. self.CALL_FUNCTION_VAR(oparg, next_instr)
  244. elif opcode == opcodedesc.CALL_FUNCTION_VAR_KW.index:
  245. self.CALL_FUNCTION_VAR_KW(oparg, next_instr)
  246. elif opcode == opcodedesc.CALL_METHOD.index:
  247. self.CALL_METHOD(oparg, next_instr)
  248. elif opcode == opcodedesc.COMPARE_OP.index:
  249. self.COMPARE_OP(oparg, next_instr)
  250. elif opcode == opcodedesc.DELETE_ATTR.index:
  251. self.DELETE_ATTR(oparg, next_instr)
  252. elif opcode == opcodedesc.DELETE_FAST.index:
  253. self.DELETE_FAST(oparg, next_instr)
  254. elif opcode == opcodedesc.DELETE_GLOBAL.index:
  255. self.DELETE_GLOBAL(oparg, next_instr)
  256. elif opcode == opcodedesc.DELETE_NAME.index:
  257. self.DELETE_NAME(oparg, next_instr)
  258. elif opcode == opcodedesc.DELETE_SLICE_0.index:
  259. self.DELETE_SLICE_0(oparg, next_instr)
  260. elif opcode == opcodedesc.DELETE_SLICE_1.index:
  261. self.DELETE_SLICE_1(oparg, next_instr)
  262. elif opcode == opcodedesc.DELETE_SLICE_2.index:
  263. self.DELETE_SLICE_2(oparg, next_instr)
  264. elif opcode == opcodedesc.DELETE_SLICE_3.index:
  265. self.DELETE_SLICE_3(oparg, next_instr)
  266. elif opcode == opcodedesc.DELETE_SUBSCR.index:
  267. self.DELETE_SUBSCR(oparg, next_instr)
  268. elif opcode == opcodedesc.DUP_TOP.index:
  269. self.DUP_TOP(oparg, next_instr)
  270. elif opcode == opcodedesc.DUP_TOPX.index:
  271. self.DUP_TOPX(oparg, next_instr)
  272. elif opcode == opcodedesc.EXEC_STMT.index:
  273. self.EXEC_STMT(oparg, next_instr)
  274. elif opcode == opcodedesc.GET_ITER.index:
  275. self.GET_ITER(oparg, next_instr)
  276. elif opcode == opcodedesc.IMPORT_FROM.index:
  277. self.IMPORT_FROM(oparg, next_instr)
  278. elif opcode == opcodedesc.IMPORT_NAME.index:
  279. self.IMPORT_NAME(oparg, next_instr)
  280. elif opcode == opcodedesc.IMPORT_STAR.index:
  281. self.IMPORT_STAR(oparg, next_instr)
  282. elif opcode == opcodedesc.INPLACE_ADD.index:
  283. self.INPLACE_ADD(oparg, next_instr)
  284. elif opcode == opcodedesc.INPLACE_AND.index:
  285. self.INPLACE_AND(oparg, next_instr)
  286. elif opcode == opcodedesc.INPLACE_DIVIDE.index:
  287. self.INPLACE_DIVIDE(oparg, next_instr)
  288. elif opcode == opcodedesc.INPLACE_FLOOR_DIVIDE.index:
  289. self.INPLACE_FLOOR_DIVIDE(oparg, next_instr)
  290. elif opcode == opcodedesc.INPLACE_LSHIFT.index:
  291. self.INPLACE_LSHIFT(oparg, next_instr)
  292. elif opcode == opcodedesc.INPLACE_MODULO.index:
  293. self.INPLACE_MODULO(oparg, next_instr)
  294. elif opcode == opcodedesc.INPLACE_MULTIPLY.index:
  295. self.INPLACE_MULTIPLY(oparg, next_instr)
  296. elif opcode == opcodedesc.INPLACE_OR.index:
  297. self.INPLACE_OR(oparg, next_instr)
  298. elif opcode == opcodedesc.INPLACE_POWER.index:
  299. self.INPLACE_POWER(oparg, next_instr)
  300. elif opcode == opcodedesc.INPLACE_RSHIFT.index:
  301. self.INPLACE_RSHIFT(oparg, next_instr)
  302. elif opcode == opcodedesc.INPLACE_SUBTRACT.index:
  303. self.INPLACE_SUBTRACT(oparg, next_instr)
  304. elif opcode == opcodedesc.INPLACE_TRUE_DIVIDE.index:
  305. self.INPLACE_TRUE_DIVIDE(oparg, next_instr)
  306. elif opcode == opcodedesc.INPLACE_XOR.index:
  307. self.INPLACE_XOR(oparg, next_instr)
  308. elif opcode == opcodedesc.LIST_APPEND.index:
  309. self.LIST_APPEND(oparg, next_instr)
  310. elif opcode == opcodedesc.LOAD_ATTR.index:
  311. self.LOAD_ATTR(oparg, next_instr)
  312. elif opcode == opcodedesc.LOAD_CLOSURE.index:
  313. self.LOAD_CLOSURE(oparg, next_instr)
  314. elif opcode == opcodedesc.LOAD_CONST.index:
  315. self.LOAD_CONST(oparg, next_instr)
  316. elif opcode == opcodedesc.LOAD_DEREF.index:
  317. self.LOAD_DEREF(oparg, next_instr)
  318. elif opcode == opcodedesc.LOAD_FAST.index:
  319. self.LOAD_FAST(oparg, next_instr)
  320. elif opcode == opcodedesc.LOAD_GLOBAL.index:
  321. self.LOAD_GLOBAL(oparg, next_instr)
  322. elif opcode == opcodedesc.LOAD_LOCALS.index:
  323. self.LOAD_LOCALS(oparg, next_instr)
  324. elif opcode == opcodedesc.LOAD_NAME.index:
  325. self.LOAD_NAME(oparg, next_instr)
  326. elif opcode == opcodedesc.LOOKUP_METHOD.index:
  327. self.LOOKUP_METHOD(oparg, next_instr)
  328. elif opcode == opcodedesc.MAKE_CLOSURE.index:
  329. self.MAKE_CLOSURE(oparg, next_instr)
  330. elif opcode == opcodedesc.MAKE_FUNCTION.index:
  331. self.MAKE_FUNCTION(oparg, next_instr)
  332. elif opcode == opcodedesc.MAP_ADD.index:
  333. self.MAP_ADD(oparg, next_instr)
  334. elif opcode == opcodedesc.NOP.index:
  335. self.NOP(oparg, next_instr)
  336. elif opcode == opcodedesc.POP_BLOCK.index:
  337. self.POP_BLOCK(oparg, next_instr)
  338. elif opcode == opcodedesc.POP_TOP.index:
  339. self.POP_TOP(oparg, next_instr)
  340. elif opcode == opcodedesc.PRINT_EXPR.index:
  341. self.PRINT_EXPR(oparg, next_instr)
  342. elif opcode == opcodedesc.PRINT_ITEM.index:
  343. self.PRINT_ITEM(oparg, next_instr)
  344. elif opcode == opcodedesc.PRINT_ITEM_TO.index:
  345. self.PRINT_ITEM_TO(oparg, next_instr)
  346. elif opcode == opcodedesc.PRINT_NEWLINE.index:
  347. self.PRINT_NEWLINE(oparg, next_instr)
  348. elif opcode == opcodedesc.PRINT_NEWLINE_TO.index:
  349. self.PRINT_NEWLINE_TO(oparg, next_instr)
  350. elif opcode == opcodedesc.RAISE_VARARGS.index:
  351. self.RAISE_VARARGS(oparg, next_instr)
  352. elif opcode == opcodedesc.ROT_FOUR.index:
  353. self.ROT_FOUR(oparg, next_instr)
  354. elif opcode == opcodedesc.ROT_THREE.index:
  355. self.ROT_THREE(oparg, next_instr)
  356. elif opcode == opcodedesc.ROT_TWO.index:
  357. self.ROT_TWO(oparg, next_instr)
  358. elif opcode == opcodedesc.SETUP_EXCEPT.index:
  359. self.SETUP_EXCEPT(oparg, next_instr)
  360. elif opcode == opcodedesc.SETUP_FINALLY.index:
  361. self.SETUP_FINALLY(oparg, next_instr)
  362. elif opcode == opcodedesc.SETUP_LOOP.index:
  363. self.SETUP_LOOP(oparg, next_instr)
  364. elif opcode == opcodedesc.SETUP_WITH.index:
  365. self.SETUP_WITH(oparg, next_instr)
  366. elif opcode == opcodedesc.SET_ADD.index:
  367. self.SET_ADD(oparg, next_instr)
  368. elif opcode == opcodedesc.SLICE_0.index:
  369. self.SLICE_0(oparg, next_instr)
  370. elif opcode == opcodedesc.SLICE_1.index:
  371. self.SLICE_1(oparg, next_instr)
  372. elif opcode == opcodedesc.SLICE_2.index:
  373. self.SLICE_2(oparg, next_instr)
  374. elif opcode == opcodedesc.SLICE_3.index:
  375. self.SLICE_3(oparg, next_instr)
  376. elif opcode == opcodedesc.STOP_CODE.index:
  377. self.STOP_CODE(oparg, next_instr)
  378. elif opcode == opcodedesc.STORE_ATTR.index:
  379. self.STORE_ATTR(oparg, next_instr)
  380. elif opcode == opcodedesc.STORE_DEREF.index:
  381. self.STORE_DEREF(oparg, next_instr)
  382. elif opcode == opcodedesc.STORE_FAST.index:
  383. self.STORE_FAST(oparg, next_instr)
  384. elif opcode == opcodedesc.STORE_GLOBAL.index:
  385. self.STORE_GLOBAL(oparg, next_instr)
  386. elif opcode == opcodedesc.STORE_MAP.index:
  387. self.STORE_MAP(oparg, next_instr)
  388. elif opcode == opcodedesc.STORE_NAME.index:
  389. self.STORE_NAME(oparg, next_instr)
  390. elif opcode == opcodedesc.STORE_SLICE_0.index:
  391. self.STORE_SLICE_0(oparg, next_instr)
  392. elif opcode == opcodedesc.STORE_SLICE_1.index:
  393. self.STORE_SLICE_1(oparg, next_instr)
  394. elif opcode == opcodedesc.STORE_SLICE_2.index:
  395. self.STORE_SLICE_2(oparg, next_instr)
  396. elif opcode == opcodedesc.STORE_SLICE_3.index:
  397. self.STORE_SLICE_3(oparg, next_instr)
  398. elif opcode == opcodedesc.STORE_SUBSCR.index:
  399. self.STORE_SUBSCR(oparg, next_instr)
  400. elif opcode == opcodedesc.UNARY_CONVERT.index:
  401. self.UNARY_CONVERT(oparg, next_instr)
  402. elif opcode == opcodedesc.UNARY_INVERT.index:
  403. self.UNARY_INVERT(oparg, next_instr)
  404. elif opcode == opcodedesc.UNARY_NEGATIVE.index:
  405. self.UNARY_NEGATIVE(oparg, next_instr)
  406. elif opcode == opcodedesc.UNARY_NOT.index:
  407. self.UNARY_NOT(oparg, next_instr)
  408. elif opcode == opcodedesc.UNARY_POSITIVE.index:
  409. self.UNARY_POSITIVE(oparg, next_instr)
  410. elif opcode == opcodedesc.UNPACK_SEQUENCE.index:
  411. self.UNPACK_SEQUENCE(oparg, next_instr)
  412. elif opcode == opcodedesc.WITH_CLEANUP.index:
  413. self.WITH_CLEANUP(oparg, next_instr)
  414. elif opcode == opcodedesc.YIELD_VALUE.index:
  415. self.YIELD_VALUE(oparg, next_instr)
  416. else:
  417. self.MISSING_OPCODE(oparg, next_instr)
  418. if jit.we_are_jitted():
  419. return next_instr
  420. @jit.unroll_safe
  421. def unrollstack(self, unroller_kind):
  422. while self.blockstack_non_empty():
  423. block = self.pop_block()
  424. if (block.handling_mask & unroller_kind) != 0:
  425. return block
  426. block.cleanupstack(self)
  427. self.frame_finished_execution = True # for generators
  428. return None
  429. def unrollstack_and_jump(self, unroller):
  430. block = self.unrollstack(unroller.kind)
  431. if block is None:
  432. raise BytecodeCorruption("misplaced bytecode - should not return")
  433. return block.handle(self, unroller)
  434. ### accessor functions ###
  435. def getlocalvarname(self, index):
  436. return self.getcode().co_varnames[index]
  437. def getconstant_w(self, index):
  438. return self.getcode().co_consts_w[index]
  439. def getname_u(self, index):
  440. return self.space.str_w(self.getcode().co_names_w[index])
  441. def getname_w(self, index):
  442. return self.getcode().co_names_w[index]
  443. ################################################################
  444. ## Implementation of the "operational" opcodes
  445. ## See also nestedscope.py for the rest.
  446. ##
  447. def NOP(self, oparg, next_instr):
  448. # annotation-time check: if it fails, it means that the decoding
  449. # of oparg failed to produce an integer which is annotated as non-neg
  450. check_nonneg(oparg)
  451. def LOAD_FAST(self, varindex, next_instr):
  452. # access a local variable directly
  453. w_value = self.locals_cells_stack_w[varindex]
  454. if w_value is None:
  455. self._load_fast_failed(varindex)
  456. self.pushvalue(w_value)
  457. LOAD_FAST._always_inline_ = True
  458. def _load_fast_failed(self, varindex):
  459. varname = self.getlocalvarname(varindex)
  460. raise oefmt(self.space.w_UnboundLocalError,
  461. "local variable '%s' referenced before assignment",
  462. varname)
  463. _load_fast_failed._dont_inline_ = True
  464. def LOAD_CONST(self, constindex, next_instr):
  465. w_const = self.getconstant_w(constindex)
  466. self.pushvalue(w_const)
  467. def STORE_FAST(self, varindex, next_instr):
  468. w_newvalue = self.popvalue()
  469. assert w_newvalue is not None
  470. self.locals_cells_stack_w[varindex] = w_newvalue
  471. def getfreevarname(self, index):
  472. freevarnames = self.pycode.co_cellvars + self.pycode.co_freevars
  473. return freevarnames[index]
  474. def iscellvar(self, index):
  475. # is the variable given by index a cell or a free var?
  476. return index < len(self.pycode.co_cellvars)
  477. def LOAD_DEREF(self, varindex, next_instr):
  478. # nested scopes: access a variable through its cell object
  479. cell = self._getcell(varindex)
  480. try:
  481. w_value = cell.get()
  482. except ValueError:
  483. varname = self.getfreevarname(varindex)
  484. if self.iscellvar(varindex):
  485. message = "local variable '%s' referenced before assignment" % varname
  486. w_exc_type = self.space.w_UnboundLocalError
  487. else:
  488. message = ("free variable '%s' referenced before assignment"
  489. " in enclosing scope" % varname)
  490. w_exc_type = self.space.w_NameError
  491. raise OperationError(w_exc_type, self.space.wrap(message))
  492. else:
  493. self.pushvalue(w_value)
  494. def STORE_DEREF(self, varindex, next_instr):
  495. # nested scopes: access a variable through its cell object
  496. w_newvalue = self.popvalue()
  497. cell = self._getcell(varindex)
  498. cell.set(w_newvalue)
  499. def LOAD_CLOSURE(self, varindex, next_instr):
  500. # nested scopes: access the cell object
  501. cell = self._getcell(varindex)
  502. w_value = self.space.wrap(cell)
  503. self.pushvalue(w_value)
  504. def POP_TOP(self, oparg, next_instr):
  505. self.popvalue()
  506. def ROT_TWO(self, oparg, next_instr):
  507. w_1 = self.popvalue()
  508. w_2 = self.popvalue()
  509. self.pushvalue(w_1)
  510. self.pushvalue(w_2)
  511. def ROT_THREE(self, oparg, next_instr):
  512. w_1 = self.popvalue()
  513. w_2 = self.popvalue()
  514. w_3 = self.popvalue()
  515. self.pushvalue(w_1)
  516. self.pushvalue(w_3)
  517. self.pushvalue(w_2)
  518. def ROT_FOUR(self, oparg, next_instr):
  519. w_1 = self.popvalue()
  520. w_2 = self.popvalue()
  521. w_3 = self.popvalue()
  522. w_4 = self.popvalue()
  523. self.pushvalue(w_1)
  524. self.pushvalue(w_4)
  525. self.pushvalue(w_3)
  526. self.pushvalue(w_2)
  527. def DUP_TOP(self, oparg, next_instr):
  528. w_1 = self.peekvalue()
  529. self.pushvalue(w_1)
  530. def DUP_TOPX(self, itemcount, next_instr):
  531. assert 1 <= itemcount <= 5, "limitation of the current interpreter"
  532. self.dupvalues(itemcount)
  533. UNARY_POSITIVE = unaryoperation("pos")
  534. UNARY_NEGATIVE = unaryoperation("neg")
  535. UNARY_NOT = unaryoperation("not_")
  536. UNARY_CONVERT = unaryoperation("repr")
  537. UNARY_INVERT = unaryoperation("invert")
  538. def BINARY_POWER(self, oparg, next_instr):
  539. w_2 = self.popvalue()
  540. w_1 = self.popvalue()
  541. w_result = self.space.pow(w_1, w_2, self.space.w_None)
  542. self.pushvalue(w_result)
  543. BINARY_MULTIPLY = binaryoperation("mul")
  544. BINARY_TRUE_DIVIDE = binaryoperation("truediv")
  545. BINARY_FLOOR_DIVIDE = binaryoperation("floordiv")
  546. BINARY_DIVIDE = binaryoperation("div")
  547. # XXX BINARY_DIVIDE must fall back to BINARY_TRUE_DIVIDE with -Qnew
  548. BINARY_MODULO = binaryoperation("mod")
  549. BINARY_ADD = binaryoperation("add")
  550. BINARY_SUBTRACT = binaryoperation("sub")
  551. BINARY_SUBSCR = binaryoperation("getitem")
  552. BINARY_LSHIFT = binaryoperation("lshift")
  553. BINARY_RSHIFT = binaryoperation("rshift")
  554. BINARY_AND = binaryoperation("and_")
  555. BINARY_XOR = binaryoperation("xor")
  556. BINARY_OR = binaryoperation("or_")
  557. def INPLACE_POWER(self, oparg, next_instr):
  558. w_2 = self.popvalue()
  559. w_1 = self.popvalue()
  560. w_result = self.space.inplace_pow(w_1, w_2)
  561. self.pushvalue(w_result)
  562. INPLACE_MULTIPLY = binaryoperation("inplace_mul")
  563. INPLACE_TRUE_DIVIDE = binaryoperation("inplace_truediv")
  564. INPLACE_FLOOR_DIVIDE = binaryoperation("inplace_floordiv")
  565. INPLACE_DIVIDE = binaryoperation("inplace_div")
  566. # XXX INPLACE_DIVIDE must fall back to INPLACE_TRUE_DIVIDE with -Qnew
  567. INPLACE_MODULO = binaryoperation("inplace_mod")
  568. INPLACE_ADD = binaryoperation("inplace_add")
  569. INPLACE_SUBTRACT = binaryoperation("inplace_sub")
  570. INPLACE_LSHIFT = binaryoperation("inplace_lshift")
  571. INPLACE_RSHIFT = binaryoperation("inplace_rshift")
  572. INPLACE_AND = binaryoperation("inplace_and")
  573. INPLACE_XOR = binaryoperation("inplace_xor")
  574. INPLACE_OR = binaryoperation("inplace_or")
  575. def slice(self, w_start, w_end):
  576. w_obj = self.popvalue()
  577. w_result = self.space.getslice(w_obj, w_start, w_end)
  578. self.pushvalue(w_result)
  579. def SLICE_0(self, oparg, next_instr):
  580. self.slice(self.space.w_None, self.space.w_None)
  581. def SLICE_1(self, oparg, next_instr):
  582. w_start = self.popvalue()
  583. self.slice(w_start, self.space.w_None)
  584. def SLICE_2(self, oparg, next_instr):
  585. w_end = self.popvalue()
  586. self.slice(self.space.w_None, w_end)
  587. def SLICE_3(self, oparg, next_instr):
  588. w_end = self.popvalue()
  589. w_start = self.popvalue()
  590. self.slice(w_start, w_end)
  591. def storeslice(self, w_start, w_end):
  592. w_obj = self.popvalue()
  593. w_newvalue = self.popvalue()
  594. self.space.setslice(w_obj, w_start, w_end, w_newvalue)
  595. def STORE_SLICE_0(self, oparg, next_instr):
  596. self.storeslice(self.space.w_None, self.space.w_None)
  597. def STORE_SLICE_1(self, oparg, next_instr):
  598. w_start = self.popvalue()
  599. self.storeslice(w_start, self.space.w_None)
  600. def STORE_SLICE_2(self, oparg, next_instr):
  601. w_end = self.popvalue()
  602. self.storeslice(self.space.w_None, w_end)
  603. def STORE_SLICE_3(self, oparg, next_instr):
  604. w_end = self.popvalue()
  605. w_start = self.popvalue()
  606. self.storeslice(w_start, w_end)
  607. def deleteslice(self, w_start, w_end):
  608. w_obj = self.popvalue()
  609. self.space.delslice(w_obj, w_start, w_end)
  610. def DELETE_SLICE_0(self, oparg, next_instr):
  611. self.deleteslice(self.space.w_None, self.space.w_None)
  612. def DELETE_SLICE_1(self, oparg, next_instr):
  613. w_start = self.popvalue()
  614. self.deleteslice(w_start, self.space.w_None)
  615. def DELETE_SLICE_2(self, oparg, next_instr):
  616. w_end = self.popvalue()
  617. self.deleteslice(self.space.w_None, w_end)
  618. def DELETE_SLICE_3(self, oparg, next_instr):
  619. w_end = self.popvalue()
  620. w_start = self.popvalue()
  621. self.deleteslice(w_start, w_end)
  622. def STORE_SUBSCR(self, oparg, next_instr):
  623. "obj[subscr] = newvalue"
  624. w_subscr = self.popvalue()
  625. w_obj = self.popvalue()
  626. w_newvalue = self.popvalue()
  627. self.space.setitem(w_obj, w_subscr, w_newvalue)
  628. def DELETE_SUBSCR(self, oparg, next_instr):
  629. "del obj[subscr]"
  630. w_subscr = self.popvalue()
  631. w_obj = self.popvalue()
  632. self.space.delitem(w_obj, w_subscr)
  633. def PRINT_EXPR(self, oparg, next_instr):
  634. w_expr = self.popvalue()
  635. print_expr(self.space, w_expr)
  636. def PRINT_ITEM_TO(self, oparg, next_instr):
  637. w_stream = self.popvalue()
  638. w_item = self.popvalue()
  639. if self.space.is_w(w_stream, self.space.w_None):
  640. w_stream = sys_stdout(self.space) # grumble grumble special cases
  641. print_item_to(self.space, self._printable_object(w_item), w_stream)
  642. def PRINT_ITEM(self, oparg, next_instr):
  643. w_item = self.popvalue()
  644. print_item(self.space, self._printable_object(w_item))
  645. def _printable_object(self, w_obj):
  646. space = self.space
  647. if not space.isinstance_w(w_obj, space.w_unicode):
  648. w_obj = space.str(w_obj)
  649. return w_obj
  650. def PRINT_NEWLINE_TO(self, oparg, next_instr):
  651. w_stream = self.popvalue()
  652. if self.space.is_w(w_stream, self.space.w_None):
  653. w_stream = sys_stdout(self.space) # grumble grumble special cases
  654. print_newline_to(self.space, w_stream)
  655. def PRINT_NEWLINE(self, oparg, next_instr):
  656. print_newline(self.space)
  657. def BREAK_LOOP(self, oparg, next_instr):
  658. return self.unrollstack_and_jump(SBreakLoop.singleton)
  659. def CONTINUE_LOOP(self, startofloop, next_instr):
  660. unroller = SContinueLoop(startofloop)
  661. return self.unrollstack_and_jump(unroller)
  662. def RAISE_VARARGS(self, nbargs, next_instr):
  663. space = self.space
  664. if nbargs == 0:
  665. last_operr = self._exc_info_unroll(space, for_hidden=True)
  666. if last_operr is None:
  667. raise oefmt(space.w_TypeError,
  668. "No active exception to reraise")
  669. # re-raise, no new traceback obj will be attached
  670. self.last_exception = last_operr
  671. raise RaiseWithExplicitTraceback(last_operr)
  672. w_value = w_traceback = space.w_None
  673. if nbargs >= 3:
  674. w_traceback = self.popvalue()
  675. if nbargs >= 2:
  676. w_value = self.popvalue()
  677. if 1:
  678. w_type = self.popvalue()
  679. operror = OperationError(w_type, w_value)
  680. operror.normalize_exception(space)
  681. if space.is_w(w_traceback, space.w_None):
  682. # common case
  683. raise operror
  684. else:
  685. msg = "raise: arg 3 must be a traceback or None"
  686. tb = pytraceback.check_traceback(space, w_traceback, msg)
  687. operror.set_traceback(tb)
  688. # special 3-arguments raise, no new traceback obj will be attached
  689. raise RaiseWithExplicitTraceback(operror)
  690. def LOAD_LOCALS(self, oparg, next_instr):
  691. self.pushvalue(self.getorcreatedebug().w_locals)
  692. def EXEC_STMT(self, oparg, next_instr):
  693. w_locals = self.popvalue()
  694. w_globals = self.popvalue()
  695. w_prog = self.popvalue()
  696. ec = self.space.getexecutioncontext()
  697. flags = ec.compiler.getcodeflags(self.pycode)
  698. w_compile_flags = self.space.wrap(flags)
  699. w_resulttuple = prepare_exec(self.space, self.space.wrap(self), w_prog,
  700. w_globals, w_locals,
  701. w_compile_flags,
  702. self.space.wrap(self.get_builtin()),
  703. self.space.gettypeobject(PyCode.typedef))
  704. w_prog, w_globals, w_locals = self.space.fixedview(w_resulttuple, 3)
  705. plain = (self.get_w_locals() is not None and
  706. self.space.is_w(w_locals, self.get_w_locals()))
  707. if plain:
  708. w_locals = self.getdictscope()
  709. co = self.space.interp_w(eval.Code, w_prog)
  710. co.exec_code(self.space, w_globals, w_locals)
  711. if plain:
  712. self.setdictscope(w_locals)
  713. def POP_BLOCK(self, oparg, next_instr):
  714. block = self.pop_block()
  715. block.cleanup(self) # the block knows how to clean up the value stack
  716. def end_finally(self):
  717. # unlike CPython, there are two statically distinct cases: the
  718. # END_FINALLY might be closing an 'except' block or a 'finally'
  719. # block. In the first case, the stack contains three items:
  720. # [exception type we are now handling]
  721. # [exception value we are now handling]
  722. # [wrapped SApplicationException]
  723. # In the case of a finally: block, the stack contains only one
  724. # item (unlike CPython which can have 1, 2 or 3 items):
  725. # [wrapped subclass of SuspendedUnroller]
  726. w_top = self.popvalue()
  727. if self.space.is_w(w_top, self.space.w_None):
  728. # case of a finally: block with no exception
  729. return None
  730. if isinstance(w_top, SuspendedUnroller):
  731. # case of a finally: block with a suspended unroller
  732. return w_top
  733. else:
  734. # case of an except: block. We popped the exception type
  735. self.popvalue() # Now we pop the exception value
  736. w_unroller = self.popvalue()
  737. assert w_unroller is not None
  738. return w_unroller
  739. def BUILD_CLASS(self, oparg, next_instr):
  740. w_methodsdict = self.popvalue()
  741. w_bases = self.popvalue()
  742. w_name = self.popvalue()
  743. w_metaclass = find_metaclass(self.space, w_bases,
  744. w_methodsdict, self.get_w_globals(),
  745. self.space.wrap(self.get_builtin()))
  746. w_newclass = self.space.call_function(w_metaclass, w_name,
  747. w_bases, w_methodsdict)
  748. self.pushvalue(w_newclass)
  749. def STORE_NAME(self, varindex, next_instr):
  750. varname = self.getname_u(varindex)
  751. w_newvalue = self.popvalue()
  752. self.space.setitem_str(self.getorcreatedebug().w_locals, varname,
  753. w_newvalue)
  754. def DELETE_NAME(self, varindex, next_instr):
  755. w_varname = self.getname_w(varindex)
  756. try:
  757. self.space.delitem(self.getorcreatedebug().w_locals, w_varname)
  758. except OperationError as e:
  759. # catch KeyErrors and turn them into NameErrors
  760. if not e.match(self.space, self.space.w_KeyError):
  761. raise
  762. raise oefmt(self.space.w_NameError, "name '%s' is not defined",
  763. self.space.str_w(w_varname))
  764. def UNPACK_SEQUENCE(self, itemcount, next_instr):
  765. w_iterable = self.popvalue()
  766. items = self.space.fixedview_unroll(w_iterable, itemcount)
  767. self.pushrevvalues(itemcount, items)
  768. def STORE_ATTR(self, nameindex, next_instr):
  769. "obj.attributename = newvalue"
  770. w_attributename = self.getname_w(nameindex)
  771. w_obj = self.popvalue()
  772. w_newvalue = self.popvalue()
  773. self.space.setattr(w_obj, w_attributename, w_newvalue)
  774. def DELETE_ATTR(self, nameindex, next_instr):
  775. "del obj.attributename"
  776. w_attributename = self.getname_w(nameindex)
  777. w_obj = self.popvalue()
  778. self.space.delattr(w_obj, w_attributename)
  779. def STORE_GLOBAL(self, nameindex, next_instr):
  780. varname = self.getname_u(nameindex)
  781. w_newvalue = self.popvalue()
  782. self.space.setitem_str(self.get_w_globals(), varname, w_newvalue)
  783. def DELETE_GLOBAL(self, nameindex, next_instr):
  784. w_varname = self.getname_w(nameindex)
  785. self.space.delitem(self.get_w_globals(), w_varname)
  786. def LOAD_NAME(self, nameindex, next_instr):
  787. if self.getorcreatedebug().w_locals is not self.get_w_globals():
  788. varname = self.getname_u(nameindex)
  789. w_value = self.space.finditem_str(self.getorcreatedebug().w_locals,
  790. varname)
  791. if w_value is not None:
  792. self.pushvalue(w_value)
  793. return
  794. self.LOAD_GLOBAL(nameindex, next_instr) # fall-back
  795. def _load_global(self, varname):
  796. w_value = self.space.finditem_str(self.get_w_globals(), varname)
  797. if w_value is None:
  798. # not in the globals, now look in the built-ins
  799. w_value = self.get_builtin().getdictvalue(self.space, varname)
  800. if w_value is None:
  801. self._load_global_failed(varname)
  802. return w_value
  803. _load_global._always_inline_ = True
  804. def _load_global_failed(self, varname):
  805. raise oefmt(self.space.w_NameError,
  806. "global name '%s' is not defined", varname)
  807. _load_global_failed._dont_inline_ = True
  808. def LOAD_GLOBAL(self, nameindex, next_instr):
  809. self.pushvalue(self._load_global(self.getname_u(nameindex)))
  810. LOAD_GLOBAL._always_inline_ = True
  811. def DELETE_FAST(self, varindex, next_instr):
  812. if self.locals_cells_stack_w[varindex] is None:
  813. varname = self.getlocalvarname(varindex)
  814. raise oefmt(self.space.w_UnboundLocalError,
  815. "local variable '%s' referenced before assignment",
  816. varname)
  817. self.locals_cells_stack_w[varindex] = None
  818. def BUILD_TUPLE(self, itemcount, next_instr):
  819. items = self.popvalues(itemcount)
  820. w_tuple = self.space.newtuple(items)
  821. self.pushvalue(w_tuple)
  822. def BUILD_LIST(self, itemcount, next_instr):
  823. items = self.popvalues_mutable(itemcount)
  824. w_list = self.space.newlist(items)
  825. self.pushvalue(w_list)
  826. def BUILD_LIST_FROM_ARG(self, _, next_instr):
  827. space = self.space
  828. # this is a little dance, because list has to be before the
  829. # value
  830. last_val = self.popvalue()
  831. length_hint = 0
  832. try:
  833. length_hint = space.length_hint(last_val, length_hint)
  834. except OperationError as e:
  835. if e.async(space):
  836. raise
  837. self.pushvalue(space.newlist([], sizehint=length_hint))
  838. self.pushvalue(last_val)
  839. def LOAD_ATTR(self, nameindex, next_instr):
  840. "obj.attributename"
  841. w_obj = self.popvalue()
  842. if not jit.we_are_jitted():
  843. from pypy.objspace.std.mapdict import LOAD_ATTR_caching
  844. w_value = LOAD_ATTR_caching(self.getcode(), w_obj, nameindex)
  845. else:
  846. w_attributename = self.getname_w(nameindex)
  847. w_value = self.space.getattr(w_obj, w_attributename)
  848. self.pushvalue(w_value)
  849. LOAD_ATTR._always_inline_ = True
  850. @jit.unroll_safe
  851. def cmp_exc_match(self, w_1, w_2):
  852. space = self.space
  853. if space.isinstance_w(w_2, space.w_tuple):
  854. for w_t in space.fixedview(w_2):
  855. if space.isinstance_w(w_t, space.w_str):
  856. msg = "catching of string exceptions is deprecated"
  857. space.warn(space.wrap(msg), space.w_DeprecationWarning)
  858. elif space.isinstance_w(w_2, space.w_str):
  859. msg = "catching of string exceptions is deprecated"
  860. space.warn(space.wrap(msg), space.w_DeprecationWarning)
  861. return space.newbool(space.exception_match(w_1, w_2))
  862. def COMPARE_OP(self, testnum, next_instr):
  863. w_2 = self.popvalue()
  864. w_1 = self.popvalue()
  865. if testnum == 0:
  866. w_result = self.space.lt(w_1, w_2)
  867. elif testnum == 1:
  868. w_result = self.space.le(w_1, w_2)
  869. elif testnum == 2:
  870. w_result = self.space.eq(w_1, w_2)
  871. elif testnum == 3:
  872. w_result = self.space.ne(w_1, w_2)
  873. elif testnum == 4:
  874. w_result = self.space.gt(w_1, w_2)
  875. elif testnum == 5:
  876. w_result = self.space.ge(w_1, w_2)
  877. elif testnum == 6:
  878. w_result = self.space.contains(w_2, w_1)
  879. elif testnum == 7:
  880. w_result = self.space.not_(self.space.contains(w_2, w_1))
  881. elif testnum == 8:
  882. w_result = self.space.is_(w_1, w_2)
  883. elif testnum == 9:
  884. w_result = self.space.not_(self.space.is_(w_1, w_2))
  885. elif testnum == 10:
  886. w_result = self.cmp_exc_match(w_1, w_2)
  887. else:
  888. raise BytecodeCorruption("bad COMPARE_OP oparg")
  889. self.pushvalue(w_result)
  890. def IMPORT_NAME(self, nameindex, next_instr):
  891. space = self.space
  892. w_modulename = self.getname_w(nameindex)
  893. modulename = self.space.str_w(w_modulename)
  894. w_fromlist = self.popvalue()
  895. w_flag = self.popvalue()
  896. try:
  897. if space.int_w(w_flag) == -1:
  898. w_flag = None
  899. except OperationError as e:
  900. if e.async(space):
  901. raise
  902. w_import = self.get_builtin().getdictvalue(space, '__import__')
  903. if w_import is None:
  904. raise OperationError(space.w_ImportError,
  905. space.wrap("__import__ not found"))
  906. d = self.getdebug()
  907. if d is None:
  908. w_locals = None
  909. else:
  910. w_locals = d.w_locals
  911. if w_locals is None: # CPython does this
  912. w_locals = space.w_None
  913. w_modulename = space.wrap(modulename)
  914. w_globals = self.get_w_globals()
  915. if w_flag is None:
  916. w_obj = space.call_function(w_import, w_modulename, w_globals,
  917. w_locals, w_fromlist)
  918. else:
  919. w_obj = space.call_function(w_import, w_modulename, w_globals,
  920. w_locals, w_fromlist, w_flag)
  921. self.pushvalue(w_obj)
  922. def IMPORT_STAR(self, oparg, next_instr):
  923. w_module = self.popvalue()
  924. w_locals = self.getdictscope()
  925. import_all_from(self.space, w_module, w_locals)
  926. self.setdictscope(w_locals)
  927. def IMPORT_FROM(self, nameindex, next_instr):
  928. w_name = self.getname_w(nameindex)
  929. w_module = self.peekvalue()
  930. try:
  931. w_obj = self.space.getattr(w_module, w_name)
  932. except OperationError as e:
  933. if not e.match(self.space, self.space.w_AttributeError):
  934. raise
  935. raise oefmt(self.space.w_ImportError,
  936. "cannot import name '%s'", self.space.str_w(w_name))
  937. self.pushvalue(w_obj)
  938. def YIELD_VALUE(self, oparg, next_instr):
  939. raise Yield
  940. def jump_absolute(self, jumpto, ec):
  941. # this function is overridden by pypy.module.pypyjit.interp_jit
  942. check_nonneg(jumpto)
  943. return jumpto
  944. def JUMP_FORWARD(self, jumpby, next_instr):
  945. next_instr += jumpby
  946. return next_instr
  947. def POP_JUMP_IF_FALSE(self, target, next_instr):
  948. w_value = self.popvalue()
  949. if not self.space.is_true(w_value):
  950. return target
  951. return next_instr
  952. def POP_JUMP_IF_TRUE(self, target, next_instr):
  953. w_value = self.popvalue()
  954. if self.space.is_true(w_value):
  955. return target
  956. return next_instr
  957. def JUMP_IF_FALSE_OR_POP(self, target, next_instr):
  958. w_value = self.peekvalue()
  959. if not self.space.is_true(w_value):
  960. return target
  961. self.popvalue()
  962. return next_instr
  963. def JUMP_IF_TRUE_OR_POP(self, target, next_instr):
  964. w_value = self.peekvalue()
  965. if self.space.is_true(w_value):
  966. return target
  967. self.popvalue()
  968. return next_instr
  969. def JUMP_IF_NOT_DEBUG(self, jumpby, next_instr):
  970. if not self.space.sys.debug:
  971. next_instr += jumpby
  972. return next_instr
  973. def GET_ITER(self, oparg, next_instr):
  974. w_iterable = self.popvalue()
  975. w_iterator = self.space.iter(w_iterable)
  976. self.pushvalue(w_iterator)
  977. def FOR_ITER(self, jumpby, next_instr):
  978. w_iterator = self.peekvalue()
  979. try:
  980. w_nextitem = self.space.next(w_iterator)
  981. except OperationError as e:
  982. if not e.match(self.space, self.space.w_StopIteration):
  983. raise
  984. # iterator exhausted
  985. self.popvalue()
  986. next_instr += jumpby
  987. else:
  988. self.pushvalue(w_nextitem)
  989. return next_instr
  990. def FOR_LOOP(self, oparg, next_instr):
  991. raise BytecodeCorruption("old opcode, no longer in use")
  992. def SETUP_LOOP(self, offsettoend, next_instr):
  993. block = LoopBlock(self, next_instr + offsettoend, self.lastblock)
  994. self.lastblock = block
  995. def SETUP_EXCEPT(self, offsettoend, next_instr):
  996. block = ExceptBlock(self, next_instr + offsettoend, self.lastblock)
  997. self.lastblock = block
  998. def SETUP_FINALLY(self, offsettoend, next_instr):
  999. block = FinallyBlock(self, next_instr + offsettoend, self.lastblock)
  1000. self.lastblock = block
  1001. def SETUP_WITH(self, offsettoend, next_instr):
  1002. w_manager = self.peekvalue()
  1003. w_enter = self.space.lookup(w_manager, "__enter__")
  1004. w_descr = self.space.lookup(w_manager, "__exit__")
  1005. if w_enter is None or w_descr is None:
  1006. raise oefmt(self.space.w_AttributeError,
  1007. "'%T' object is not a context manager (no __enter__/"
  1008. "__exit__ method)", w_manager)
  1009. w_exit = self.space.get(w_descr, w_manager)
  1010. self.settopvalue(w_exit)
  1011. w_result = self.space.get_and_call_function(w_enter, w_manager)
  1012. block = WithBlock(self, next_instr + offsettoend, self.lastblock)
  1013. self.lastblock = block
  1014. self.pushvalue(w_result)
  1015. def WITH_CLEANUP(self, oparg, next_instr):
  1016. # see comment in END_FINALLY for stack state
  1017. w_unroller = self.popvalue()
  1018. w_exitfunc = self.popvalue()
  1019. self.pushvalue(w_unroller)
  1020. if isinstance(w_unroller, SApplicationException):
  1021. # app-level exception
  1022. operr = w_unroller.operr
  1023. self.last_exception = operr
  1024. w_traceback = self.space.wrap(operr.get_traceback())
  1025. w_suppress = self.call_contextmanager_exit_function(
  1026. w_exitfunc,
  1027. operr.w_type,
  1028. operr.get_w_value(self.space),
  1029. w_traceback)
  1030. if self.space.is_true(w_suppress):
  1031. # __exit__() returned True -> Swallow the exception.
  1032. self.settopvalue(self.space.w_None)
  1033. else:
  1034. self.call_contextmanager_exit_function(
  1035. w_exitfunc,
  1036. self.space.w_None,
  1037. self.space.w_None,
  1038. self.space.w_None)
  1039. @jit.unroll_safe
  1040. def call_function(self, oparg, w_star=None, w_starstar=None):
  1041. n_arguments = oparg & 0xff
  1042. n_keywords = (oparg>>8) & 0xff
  1043. if n_keywords:
  1044. keywords = [None] * n_keywords
  1045. keywords_w = [None] * n_keywords
  1046. while True:
  1047. n_keywords -= 1
  1048. if n_keywords < 0:
  1049. break
  1050. w_value = self.popvalue()
  1051. w_key = self.popvalue()
  1052. key = self.space.str_w(w_key)
  1053. keywords[n_keywords] = key
  1054. keywords_w[n_keywords] = w_value
  1055. else:
  1056. keywords = None
  1057. keywords_w = None
  1058. arguments = self.popvalues(n_arguments)
  1059. args = self.argument_factory(arguments, keywords, keywords_w, w_star,
  1060. w_starstar)
  1061. w_function = self.popvalue()
  1062. if self.get_is_being_profiled() and function.is_builtin_code(w_function):
  1063. w_result = self.space.call_args_and_c_profile(self, w_function,
  1064. args)
  1065. else:
  1066. w_result = self.space.call_args(w_function, args)
  1067. self.pushvalue(w_result)
  1068. def CALL_FUNCTION(self, oparg, next_instr):
  1069. # XXX start of hack for performance
  1070. if (oparg >> 8) & 0xff == 0:
  1071. # Only positional arguments
  1072. nargs = oparg & 0xff
  1073. w_function = self.peekvalue(nargs)
  1074. try:
  1075. w_result = self.space.call_valuestack(w_function, nargs, self)
  1076. finally:
  1077. self.dropvalues(nargs + 1)
  1078. self.pushvalue(w_result)
  1079. # XXX end of hack for performance
  1080. else:
  1081. # general case
  1082. self.call_function(oparg)
  1083. def CALL_FUNCTION_VAR(self, oparg, next_instr):
  1084. w_varargs = self.popvalue()
  1085. self.call_function(oparg, w_varargs)
  1086. def CALL_FUNCTION_KW(self, oparg, next_instr):
  1087. w_varkw = self.popvalue()
  1088. self.call_function(oparg, None, w_varkw)
  1089. def CALL_FUNCTION_VAR_KW(self, oparg, next_instr):
  1090. w_varkw = self.popvalue()
  1091. w_varargs = self.popvalue()
  1092. self.call_function(oparg, w_varargs, w_varkw)
  1093. def MAKE_FUNCTION(self, numdefaults, next_instr):
  1094. w_codeobj = self.popvalue()
  1095. codeobj = self.space.interp_w(PyCode, w_codeobj)
  1096. defaultarguments = self.popvalues(numdefaults)
  1097. fn = function.Function(self.space, codeobj, self.get_w_globals(),
  1098. defaultarguments)
  1099. self.pushvalue(self.space.wrap(fn))
  1100. @jit.unroll_safe
  1101. def MAKE_CLOSURE(self, numdefaults, next_instr):
  1102. w_codeobj = self.popvalue()
  1103. codeobj = self.space.interp_w(pycode.PyCode, w_codeobj)
  1104. w_freevarstuple = self.popvalue()
  1105. freevars = [self.space.interp_w(Cell, cell)
  1106. for cell in self.space.fixedview(w_freevarstuple)]
  1107. defaultarguments = self.popvalues(numdefaults)
  1108. fn = function.Function(self.space, codeobj, self.get_w_globals(),
  1109. defaultarguments, freevars)
  1110. self.pushvalue(self.space.wrap(fn))
  1111. def BUILD_SLICE(self, numargs, next_instr):
  1112. if numargs == 3:
  1113. w_step = self.popvalue()
  1114. elif numargs == 2:
  1115. w_step = self.space.w_None
  1116. else:
  1117. raise BytecodeCorruption
  1118. w_end = self.popvalue()
  1119. w_start = self.popvalue()
  1120. w_slice = self.space.newslice(w_start, w_end, w_step)
  1121. self.pushvalue(w_slice)
  1122. def LIST_APPEND(self, oparg, next_instr):
  1123. w = self.popvalue()
  1124. v = self.peekvalue(oparg - 1)
  1125. self.space.call_method(v, 'append', w)
  1126. def SET_ADD(self, oparg, next_instr):
  1127. w_value = self.popvalue()
  1128. w_set = self.peekvalue(oparg - 1)
  1129. self.space.call_method(w_set, 'add', w_value)
  1130. def MAP_ADD(self, oparg, next_instr):
  1131. w_key = self.popvalue()
  1132. w_value = self.popvalue()
  1133. w_dict = self.peekvalue(oparg - 1)
  1134. self.space.setitem(w_dict, w_key, w_value)
  1135. def SET_LINENO(self, lineno, next_instr):
  1136. pass
  1137. # overridden by faster version in the standard object space.
  1138. LOOKUP_METHOD = LOAD_ATTR
  1139. CALL_METHOD = CALL_FUNCTION
  1140. def MISSING_OPCODE(self, oparg, next_instr):
  1141. ofs = self.last_instr
  1142. c = self.pycode.co_code[ofs]
  1143. name = self.pycode.co_name
  1144. raise BytecodeCorruption("unknown opcode, ofs=%d, code=%d, name=%s" %
  1145. (ofs, ord(c), name) )
  1146. STOP_CODE = MISSING_OPCODE
  1147. def BUILD_MAP(self, itemcount, next_instr):
  1148. w_dict = self.space.newdict()
  1149. self.pushvalue(w_dict)
  1150. @jit.unroll_safe
  1151. def BUILD_SET(self, itemcount, next_instr):
  1152. w_set = self.space.newset()
  1153. for i in range(itemcount):
  1154. w_item = self.popvalue()
  1155. self.space.call_method(w_set, 'add', w_item)
  1156. self.pushvalue(w_set)
  1157. def STORE_MAP(self, oparg, next_instr):
  1158. w_key = self.popvalue()
  1159. w_value = self.popvalue()
  1160. w_dict = self.peekvalue()
  1161. self.space.setitem(w_dict, w_key, w_value)
  1162. ### ____________________________________________________________ ###
  1163. class ExitFrame(Exception):
  1164. pass
  1165. class Return(ExitFrame):
  1166. """Raised when exiting a frame via a 'return' statement."""
  1167. class Yield(ExitFrame):
  1168. """Raised when exiting a frame via a 'yield' statement."""
  1169. class RaiseWithExplicitTraceback(Exception):
  1170. """Raised at interp-level by a 0- or 3-arguments 'raise' statement."""
  1171. def __init__(self, operr):
  1172. self.operr = operr
  1173. ### Frame Blocks ###
  1174. class SuspendedUnroller(W_Root):
  1175. """Abstract base class for interpreter-level objects that
  1176. instruct the interpreter to change the control flow and the
  1177. block stack.
  1178. The concrete subclasses correspond to the various values WHY_XXX
  1179. values of the why_code enumeration in ceval.c:
  1180. WHY_NOT, OK, not this one :-)
  1181. WHY_EXCEPTION, SApplicationException
  1182. WHY_RERAISE, implemented differently, see Reraise
  1183. WHY_RETURN, SReturnValue
  1184. WHY_BREAK, SBreakLoop
  1185. WHY_CONTINUE, SContinueLoop
  1186. WHY_YIELD not needed
  1187. """
  1188. _immutable_ = True
  1189. def nomoreblocks(self):
  1190. raise BytecodeCorruption("misplaced bytecode - should not return")
  1191. class SReturnValue(SuspendedUnroller):
  1192. """Signals a 'return' statement.
  1193. Argument is the wrapped object to return."""
  1194. _immutable_ = True
  1195. kind = 0x01
  1196. def __init__(self, w_returnvalue):
  1197. self.w_returnvalue = w_returnvalue
  1198. def nomoreblocks(self):
  1199. return self.w_returnvalue
  1200. class SApplicationException(SuspendedUnroller):
  1201. """Signals an application-level exception
  1202. (i.e. an OperationException)."""
  1203. _immutable_ = True
  1204. kind = 0x02
  1205. def __init__(self, operr):
  1206. self.operr = operr
  1207. def nomoreblocks(self):
  1208. raise RaiseWithExplicitTraceback(self.operr)
  1209. class SBreakLoop(SuspendedUnroller):
  1210. """Signals a 'break' statement."""
  1211. _immutable_ = True
  1212. kind = 0x04
  1213. SBreakLoop.singleton = SBreakLoop()
  1214. class SContinueLoop(SuspendedUnroller):
  1215. """Signals a 'continue' statement.
  1216. Argument is the bytecode position of the beginning of the loop."""
  1217. _immutable_ = True
  1218. kind = 0x08
  1219. def __init__(self, jump_to):
  1220. self.jump_to = jump_to
  1221. class FrameBlock(object):
  1222. """Abstract base class for frame blocks from the blockstack,
  1223. used by the SETUP_XXX and POP_BLOCK opcodes."""
  1224. _immutable_ = True
  1225. def __init__(self, frame, handlerposition, previous):
  1226. self.handlerposition = handlerposition
  1227. self.valuestackdepth = frame.valuestackdepth
  1228. self.previous = previous # this makes a linked list of blocks
  1229. def __eq__(self, other):
  1230. return (self.__class__ is other.__class__ and
  1231. self.handlerposition == other.handlerposition and
  1232. self.valuestackdepth == other.valuestackdepth)
  1233. def __ne__(self, other):
  1234. return not (self == other)
  1235. def __hash__(self):
  1236. return hash((self.handlerposition, self.valuestackdepth))
  1237. def cleanupstack(self, frame):
  1238. frame.dropvaluesuntil(self.valuestackdepth)
  1239. def cleanup(self, frame):
  1240. "Clean up a frame when we normally exit the block."
  1241. self.cleanupstack(frame)
  1242. # internal pickling interface, not using the standard protocol
  1243. def _get_state_(self, space):
  1244. w = space.wrap
  1245. return space.newtuple([w(self._opname), w(self.handlerposition),
  1246. w(self.valuestackdepth)])
  1247. def handle(self, frame, unroller):
  1248. """ Purely abstract method
  1249. """
  1250. raise NotImplementedError
  1251. class LoopBlock(FrameBlock):
  1252. """A loop block. Stores the end-of-loop pointer in case of 'break'."""
  1253. _immutable_ = True
  1254. _opname = 'SETUP_LOOP'
  1255. handling_mask = SBreakLoop.kind | SContinueLoop.kind
  1256. def handle(self, frame, unroller):
  1257. if isinstance(unroller, SContinueLoop):
  1258. # re-push the loop block without cleaning up the value stack,
  1259. # and jump to the beginning of the loop, stored in the
  1260. # exception's argument
  1261. frame.append_block(self)
  1262. jumpto = unroller.jump_to
  1263. ec = frame.space.getexecutioncontext()
  1264. return r_uint(frame.jump_absolute(jumpto, ec))
  1265. else:
  1266. # jump to the end of the loop
  1267. self.cleanupstack(frame)
  1268. return r_uint(self.handlerposition)
  1269. class ExceptBlock(FrameBlock):
  1270. """An try:except: block. Stores the position of the exception handler."""
  1271. _immutable_ = True
  1272. _opname = 'SETUP_EXCEPT'
  1273. handling_mask = SApplicationException.kind
  1274. def handle(self, frame, unroller):
  1275. # push the exception to the value stack for inspection by the
  1276. # exception handler (the code after the except:)
  1277. self.cleanupstack(frame)
  1278. assert isinstance(unroller, SApplicationException)
  1279. operationerr = unroller.operr
  1280. operationerr.normalize_exception(frame.space)
  1281. # the stack setup is slightly different than in CPython:
  1282. # instead of the traceback, we store the unroller object,
  1283. # wrapped.
  1284. frame.pushvalue(frame.space.wrap(unroller))
  1285. frame.pushvalue(operationerr.get_w_value(frame.space))
  1286. frame.pushvalue(operationerr.w_type)
  1287. frame.last_exception = operationerr
  1288. return r_uint(self.handlerposition) # jump to the handler
  1289. class FinallyBlock(FrameBlock):
  1290. """A try:finally: block. Stores the position of the exception handler."""
  1291. _immutable_ = True
  1292. _opname = 'SETUP_FINALLY'
  1293. handling_mask = -1 # handles every kind of SuspendedUnroller
  1294. def handle(self, frame, unroller):
  1295. # any abnormal reason for unrolling a finally: triggers the end of
  1296. # the block unrolling and the entering the finally: handler.
  1297. # see comments in cleanup().
  1298. self.cleanupstack(frame)
  1299. frame.pushvalue(frame.space.wrap(unroller))
  1300. return r_uint(self.handlerposition) # jump to the handler
  1301. class WithBlock(FinallyBlock):
  1302. _immutable_ = True
  1303. def handle(self, frame, unroller):
  1304. if isinstance(unroller, SApplicationException):
  1305. unroller.operr.normalize_exception(frame.space)
  1306. return FinallyBlock.handle(self, frame, unroller)
  1307. block_classes = {'SETUP_LOOP': LoopBlock,
  1308. 'SETUP_EXCEPT': ExceptBlock,
  1309. 'SETUP_FINALLY': FinallyBlock,
  1310. 'SETUP_WITH': WithBlock,
  1311. }
  1312. ### helpers written at the application-level ###
  1313. # Some of these functions are expected to be generally useful if other
  1314. # parts of the code need to do the same thing as a non-trivial opcode,
  1315. # like finding out which metaclass a new class should have.
  1316. # This is why they are not methods of PyFrame.
  1317. # There are also a couple of helpers that are methods, defined in the
  1318. # class above.
  1319. app = gateway.applevel(r'''
  1320. """ applevel implementation of certain system properties, imports
  1321. and other helpers"""
  1322. import sys
  1323. def sys_stdout():
  1324. try:
  1325. return sys.stdout
  1326. except AttributeError:
  1327. raise RuntimeError("lost sys.stdout")
  1328. def print_expr(obj):
  1329. try:
  1330. displayhook = sys.displayhook
  1331. except AttributeError:
  1332. raise RuntimeError("lost sys.displayhook")
  1333. displayhook(obj)
  1334. def print_item_to(x, stream):
  1335. if file_softspace(stream, False):
  1336. stream.write(" ")
  1337. # give to write() an argument which is either a string or a unicode
  1338. # (and let it deals itself with unicode handling). The check "is
  1339. # unicode" should not use isinstance() at app-level, because that
  1340. # could be fooled by strange objects, so it is done at interp-level.
  1341. stream.write(x)
  1342. # add a softspace unless we just printed a string which ends in a '\t'
  1343. # or '\n' -- or more generally any whitespace character but ' '
  1344. if x:
  1345. lastchar = x[-1]
  1346. if lastchar.isspace() and lastchar != ' ':
  1347. return
  1348. file_softspace(stream, True)
  1349. def print_item(x):
  1350. print_item_to(x, sys_stdout())
  1351. def print_newline_to(stream):
  1352. stream.write("\n")
  1353. file_softspace(stream, False)
  1354. def print_newline():
  1355. print_newline_to(sys_stdout())
  1356. def file_softspace(file, newflag):
  1357. try:
  1358. softspace = file.softspace
  1359. except AttributeError:
  1360. softspace = 0
  1361. try:
  1362. file.softspace = newflag
  1363. except AttributeError:
  1364. pass
  1365. return softspace
  1366. ''', filename=__file__)
  1367. sys_stdout = app.interphook('sys_stdout')
  1368. print_expr = app.interphook('print_expr')
  1369. print_item = app.interphook('print_item')
  1370. print_item_to = app.interphook('print_item_to')
  1371. print_newline = app.interphook('print_newline')
  1372. print_newline_to= app.interphook('print_newline_to')
  1373. file_softspace = app.interphook('file_softspace')
  1374. app = gateway.applevel(r'''
  1375. def find_metaclass(bases, namespace, globals, builtin):
  1376. if '__metaclass__' in namespace:
  1377. return namespace['__metaclass__']
  1378. elif len(bases) > 0:
  1379. base = bases[0]
  1380. if hasattr(base, '__class__'):
  1381. return base.__class__
  1382. else:
  1383. return type(base)
  1384. elif '__metaclass__' in globals:
  1385. return globals['__metaclass__']
  1386. else:
  1387. try:
  1388. return builtin.__metaclass__
  1389. except AttributeError:
  1390. return type
  1391. ''', filename=__file__)
  1392. find_metaclass = app.interphook('find_metaclass')
  1393. app = gateway.applevel(r'''
  1394. def import_all_from(module, into_locals):
  1395. try:
  1396. all = module.__all__
  1397. except AttributeError:
  1398. try:
  1399. dict = module.__dict__
  1400. except AttributeError:
  1401. raise ImportError("from-import-* object has no __dict__ "
  1402. "and no __all__")
  1403. all = dict.keys()
  1404. skip_leading_underscores = True
  1405. else:
  1406. skip_leading_underscores = False
  1407. for name in all:
  1408. if skip_leading_underscores and name[0]=='_':
  1409. continue
  1410. into_locals[name] = getattr(module, name)
  1411. ''', filename=__file__)
  1412. import_all_from = app.interphook('import_all_from')
  1413. app = gateway.applevel(r'''
  1414. def prepare_exec(f, prog, globals, locals, compile_flags, builtin, codetype):
  1415. """Manipulate parameters to exec statement to (codeobject, dict, dict).
  1416. """
  1417. if (globals is None and locals is None and
  1418. isinstance(prog, tuple) and
  1419. (len(prog) == 2 or len(prog) == 3)):
  1420. globals = prog[1]
  1421. if len(prog) == 3:
  1422. locals = prog[2]
  1423. prog = prog[0]
  1424. if globals is None:
  1425. globals = f.f_globals
  1426. if locals is None:
  1427. locals = f.f_locals
  1428. if locals is None:
  1429. locals = globals
  1430. if not isinstance(globals, dict):
  1431. if not hasattr(globals, '__getitem__'):
  1432. raise TypeError("exec: arg 2 must be a dictionary or None")
  1433. globals.setdefault('__builtins__', builtin)
  1434. if not isinstance(locals, dict):
  1435. if not hasattr(locals, '__getitem__'):
  1436. raise TypeError("exec: arg 3 must be a dictionary or None")
  1437. if not isinstance(prog, codetype):
  1438. filename = '<string>'
  1439. if not isinstance(prog, basestring):
  1440. if isinstance(prog, file):
  1441. filename = prog.name
  1442. prog = prog.read()
  1443. else:
  1444. raise TypeError("exec: arg 1 must be a string, file, "
  1445. "or code object")
  1446. prog = compile(prog, filename, 'exec', compile_flags, 1)
  1447. return (prog, globals, locals)
  1448. ''', filename=__file__)
  1449. prepare_exec = app.interphook('prepare_exec')