PageRenderTime 56ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/pypy/interpreter/pyopcode.py

https://bitbucket.org/vanl/pypy
Python | 1669 lines | 1412 code | 164 blank | 93 comment | 260 complexity | 85f0088a596cbfcdd892a317c8f9a6bb MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, AGPL-3.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, operr:
  57. next_instr = self.handle_operation_error(ec, operr)
  58. except RaiseWithExplicitTraceback, 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, 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, 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. @jit.unroll_safe
  663. def RAISE_VARARGS(self, nbargs, next_instr):
  664. space = self.space
  665. if nbargs == 0:
  666. frame = self
  667. while frame:
  668. if frame.last_exception is not None:
  669. operror = frame.last_exception
  670. break
  671. frame = frame.f_backref()
  672. else:
  673. raise OperationError(space.w_TypeError,
  674. space.wrap("raise: no active exception to re-raise"))
  675. if operror.w_type is space.w_None:
  676. raise OperationError(space.w_TypeError,
  677. space.wrap("raise: the exception to re-raise was cleared"))
  678. # re-raise, no new traceback obj will be attached
  679. self.last_exception = operror
  680. raise RaiseWithExplicitTraceback(operror)
  681. w_value = w_traceback = space.w_None
  682. if nbargs >= 3:
  683. w_traceback = self.popvalue()
  684. if nbargs >= 2:
  685. w_value = self.popvalue()
  686. if 1:
  687. w_type = self.popvalue()
  688. operror = OperationError(w_type, w_value)
  689. operror.normalize_exception(space)
  690. if space.is_w(w_traceback, space.w_None):
  691. # common case
  692. raise operror
  693. else:
  694. msg = "raise: arg 3 must be a traceback or None"
  695. tb = pytraceback.check_traceback(space, w_traceback, msg)
  696. operror.set_traceback(tb)
  697. # special 3-arguments raise, no new traceback obj will be attached
  698. raise RaiseWithExplicitTraceback(operror)
  699. def LOAD_LOCALS(self, oparg, next_instr):
  700. self.pushvalue(self.getorcreatedebug().w_locals)
  701. def EXEC_STMT(self, oparg, next_instr):
  702. w_locals = self.popvalue()
  703. w_globals = self.popvalue()
  704. w_prog = self.popvalue()
  705. ec = self.space.getexecutioncontext()
  706. flags = ec.compiler.getcodeflags(self.pycode)
  707. w_compile_flags = self.space.wrap(flags)
  708. w_resulttuple = prepare_exec(self.space, self.space.wrap(self), w_prog,
  709. w_globals, w_locals,
  710. w_compile_flags,
  711. self.space.wrap(self.get_builtin()),
  712. self.space.gettypeobject(PyCode.typedef))
  713. w_prog, w_globals, w_locals = self.space.fixedview(w_resulttuple, 3)
  714. plain = (self.get_w_locals() is not None and
  715. self.space.is_w(w_locals, self.get_w_locals()))
  716. if plain:
  717. w_locals = self.getdictscope()
  718. co = self.space.interp_w(eval.Code, w_prog)
  719. co.exec_code(self.space, w_globals, w_locals)
  720. if plain:
  721. self.setdictscope(w_locals)
  722. def POP_BLOCK(self, oparg, next_instr):
  723. block = self.pop_block()
  724. block.cleanup(self) # the block knows how to clean up the value stack
  725. def end_finally(self):
  726. # unlike CPython, there are two statically distinct cases: the
  727. # END_FINALLY might be closing an 'except' block or a 'finally'
  728. # block. In the first case, the stack contains three items:
  729. # [exception type we are now handling]
  730. # [exception value we are now handling]
  731. # [wrapped SApplicationException]
  732. # In the case of a finally: block, the stack contains only one
  733. # item (unlike CPython which can have 1, 2 or 3 items):
  734. # [wrapped subclass of SuspendedUnroller]
  735. w_top = self.popvalue()
  736. if self.space.is_w(w_top, self.space.w_None):
  737. # case of a finally: block with no exception
  738. return None
  739. if isinstance(w_top, SuspendedUnroller):
  740. # case of a finally: block with a suspended unroller
  741. return w_top
  742. else:
  743. # case of an except: block. We popped the exception type
  744. self.popvalue() # Now we pop the exception value
  745. w_unroller = self.popvalue()
  746. assert w_unroller is not None
  747. return w_unroller
  748. def BUILD_CLASS(self, oparg, next_instr):
  749. w_methodsdict = self.popvalue()
  750. w_bases = self.popvalue()
  751. w_name = self.popvalue()
  752. w_metaclass = find_metaclass(self.space, w_bases,
  753. w_methodsdict, self.w_globals,
  754. self.space.wrap(self.get_builtin()))
  755. w_newclass = self.space.call_function(w_metaclass, w_name,
  756. w_bases, w_methodsdict)
  757. self.pushvalue(w_newclass)
  758. def STORE_NAME(self, varindex, next_instr):
  759. varname = self.getname_u(varindex)
  760. w_newvalue = self.popvalue()
  761. self.space.setitem_str(self.getorcreatedebug().w_locals, varname,
  762. w_newvalue)
  763. def DELETE_NAME(self, varindex, next_instr):
  764. w_varname = self.getname_w(varindex)
  765. try:
  766. self.space.delitem(self.getorcreatedebug().w_locals, w_varname)
  767. except OperationError, e:
  768. # catch KeyErrors and turn them into NameErrors
  769. if not e.match(self.space, self.space.w_KeyError):
  770. raise
  771. raise oefmt(self.space.w_NameError, "name '%s' is not defined",
  772. self.space.str_w(w_varname))
  773. def UNPACK_SEQUENCE(self, itemcount, next_instr):
  774. w_iterable = self.popvalue()
  775. items = self.space.fixedview_unroll(w_iterable, itemcount)
  776. self.pushrevvalues(itemcount, items)
  777. def STORE_ATTR(self, nameindex, next_instr):
  778. "obj.attributename = newvalue"
  779. w_attributename = self.getname_w(nameindex)
  780. w_obj = self.popvalue()
  781. w_newvalue = self.popvalue()
  782. self.space.setattr(w_obj, w_attributename, w_newvalue)
  783. def DELETE_ATTR(self, nameindex, next_instr):
  784. "del obj.attributename"
  785. w_attributename = self.getname_w(nameindex)
  786. w_obj = self.popvalue()
  787. self.space.delattr(w_obj, w_attributename)
  788. def STORE_GLOBAL(self, nameindex, next_instr):
  789. varname = self.getname_u(nameindex)
  790. w_newvalue = self.popvalue()
  791. self.space.setitem_str(self.w_globals, varname, w_newvalue)
  792. def DELETE_GLOBAL(self, nameindex, next_instr):
  793. w_varname = self.getname_w(nameindex)
  794. self.space.delitem(self.w_globals, w_varname)
  795. def LOAD_NAME(self, nameindex, next_instr):
  796. if self.getorcreatedebug().w_locals is not self.w_globals:
  797. varname = self.getname_u(nameindex)
  798. w_value = self.space.finditem_str(self.getorcreatedebug().w_locals,
  799. varname)
  800. if w_value is not None:
  801. self.pushvalue(w_value)
  802. return
  803. self.LOAD_GLOBAL(nameindex, next_instr) # fall-back
  804. def _load_global(self, varname):
  805. w_value = self.space.finditem_str(self.w_globals, varname)
  806. if w_value is None:
  807. # not in the globals, now look in the built-ins
  808. w_value = self.get_builtin().getdictvalue(self.space, varname)
  809. if w_value is None:
  810. self._load_global_failed(varname)
  811. return w_value
  812. _load_global._always_inline_ = True
  813. def _load_global_failed(self, varname):
  814. raise oefmt(self.space.w_NameError,
  815. "global name '%s' is not defined", varname)
  816. _load_global_failed._dont_inline_ = True
  817. def LOAD_GLOBAL(self, nameindex, next_instr):
  818. self.pushvalue(self._load_global(self.getname_u(nameindex)))
  819. LOAD_GLOBAL._always_inline_ = True
  820. def DELETE_FAST(self, varindex, next_instr):
  821. if self.locals_cells_stack_w[varindex] is None:
  822. varname = self.getlocalvarname(varindex)
  823. raise oefmt(self.space.w_UnboundLocalError,
  824. "local variable '%s' referenced before assignment",
  825. varname)
  826. self.locals_cells_stack_w[varindex] = None
  827. def BUILD_TUPLE(self, itemcount, next_instr):
  828. items = self.popvalues(itemcount)
  829. w_tuple = self.space.newtuple(items)
  830. self.pushvalue(w_tuple)
  831. def BUILD_LIST(self, itemcount, next_instr):
  832. items = self.popvalues_mutable(itemcount)
  833. w_list = self.space.newlist(items)
  834. self.pushvalue(w_list)
  835. def BUILD_LIST_FROM_ARG(self, _, next_instr):
  836. space = self.space
  837. # this is a little dance, because list has to be before the
  838. # value
  839. last_val = self.popvalue()
  840. length_hint = 0
  841. try:
  842. length_hint = space.length_hint(last_val, length_hint)
  843. except OperationError as e:
  844. if e.async(space):
  845. raise
  846. self.pushvalue(space.newlist([], sizehint=length_hint))
  847. self.pushvalue(last_val)
  848. def LOAD_ATTR(self, nameindex, next_instr):
  849. "obj.attributename"
  850. w_obj = self.popvalue()
  851. if (self.space.config.objspace.std.withmapdict
  852. and not jit.we_are_jitted()):
  853. from pypy.objspace.std.mapdict import LOAD_ATTR_caching
  854. w_value = LOAD_ATTR_caching(self.getcode(), w_obj, nameindex)
  855. else:
  856. w_attributename = self.getname_w(nameindex)
  857. w_value = self.space.getattr(w_obj, w_attributename)
  858. self.pushvalue(w_value)
  859. LOAD_ATTR._always_inline_ = True
  860. @jit.unroll_safe
  861. def cmp_exc_match(self, w_1, w_2):
  862. space = self.space
  863. if space.isinstance_w(w_2, space.w_tuple):
  864. for w_t in space.fixedview(w_2):
  865. if space.isinstance_w(w_t, space.w_str):
  866. msg = "catching of string exceptions is deprecated"
  867. space.warn(space.wrap(msg), space.w_DeprecationWarning)
  868. elif space.isinstance_w(w_2, space.w_str):
  869. msg = "catching of string exceptions is deprecated"
  870. space.warn(space.wrap(msg), space.w_DeprecationWarning)
  871. return space.newbool(space.exception_match(w_1, w_2))
  872. def COMPARE_OP(self, testnum, next_instr):
  873. w_2 = self.popvalue()
  874. w_1 = self.popvalue()
  875. if testnum == 0:
  876. w_result = self.space.lt(w_1, w_2)
  877. elif testnum == 1:
  878. w_result = self.space.le(w_1, w_2)
  879. elif testnum == 2:
  880. w_result = self.space.eq(w_1, w_2)
  881. elif testnum == 3:
  882. w_result = self.space.ne(w_1, w_2)
  883. elif testnum == 4:
  884. w_result = self.space.gt(w_1, w_2)
  885. elif testnum == 5:
  886. w_result = self.space.ge(w_1, w_2)
  887. elif testnum == 6:
  888. w_result = self.space.contains(w_2, w_1)
  889. elif testnum == 7:
  890. w_result = self.space.not_(self.space.contains(w_2, w_1))
  891. elif testnum == 8:
  892. w_result = self.space.is_(w_1, w_2)
  893. elif testnum == 9:
  894. w_result = self.space.not_(self.space.is_(w_1, w_2))
  895. elif testnum == 10:
  896. w_result = self.cmp_exc_match(w_1, w_2)
  897. else:
  898. raise BytecodeCorruption("bad COMPARE_OP oparg")
  899. self.pushvalue(w_result)
  900. def IMPORT_NAME(self, nameindex, next_instr):
  901. space = self.space
  902. w_modulename = self.getname_w(nameindex)
  903. modulename = self.space.str_w(w_modulename)
  904. w_fromlist = self.popvalue()
  905. w_flag = self.popvalue()
  906. try:
  907. if space.int_w(w_flag) == -1:
  908. w_flag = None
  909. except OperationError, e:
  910. if e.async(space):
  911. raise
  912. w_import = self.get_builtin().getdictvalue(space, '__import__')
  913. if w_import is None:
  914. raise OperationError(space.w_ImportError,
  915. space.wrap("__import__ not found"))
  916. d = self.getdebug()
  917. if d is None:
  918. w_locals = None
  919. else:
  920. w_locals = d.w_locals
  921. if w_locals is None: # CPython does this
  922. w_locals = space.w_None
  923. w_modulename = space.wrap(modulename)
  924. w_globals = self.w_globals
  925. if w_flag is None:
  926. w_obj = space.call_function(w_import, w_modulename, w_globals,
  927. w_locals, w_fromlist)
  928. else:
  929. w_obj = space.call_function(w_import, w_modulename, w_globals,
  930. w_locals, w_fromlist, w_flag)
  931. self.pushvalue(w_obj)
  932. def IMPORT_STAR(self, oparg, next_instr):
  933. w_module = self.popvalue()
  934. w_locals = self.getdictscope()
  935. import_all_from(self.space, w_module, w_locals)
  936. self.setdictscope(w_locals)
  937. def IMPORT_FROM(self, nameindex, next_instr):
  938. w_name = self.getname_w(nameindex)
  939. w_module = self.peekvalue()
  940. try:
  941. w_obj = self.space.getattr(w_module, w_name)
  942. except OperationError, e:
  943. if not e.match(self.space, self.space.w_AttributeError):
  944. raise
  945. raise oefmt(self.space.w_ImportError,
  946. "cannot import name '%s'", self.space.str_w(w_name))
  947. self.pushvalue(w_obj)
  948. def YIELD_VALUE(self, oparg, next_instr):
  949. raise Yield
  950. def jump_absolute(self, jumpto, ec):
  951. # this function is overridden by pypy.module.pypyjit.interp_jit
  952. check_nonneg(jumpto)
  953. return jumpto
  954. def JUMP_FORWARD(self, jumpby, next_instr):
  955. next_instr += jumpby
  956. return next_instr
  957. def POP_JUMP_IF_FALSE(self, target, next_instr):
  958. w_value = self.popvalue()
  959. if not self.space.is_true(w_value):
  960. return target
  961. return next_instr
  962. def POP_JUMP_IF_TRUE(self, target, next_instr):
  963. w_value = self.popvalue()
  964. if self.space.is_true(w_value):
  965. return target
  966. return next_instr
  967. def JUMP_IF_FALSE_OR_POP(self, target, next_instr):
  968. w_value = self.peekvalue()
  969. if not self.space.is_true(w_value):
  970. return target
  971. self.popvalue()
  972. return next_instr
  973. def JUMP_IF_TRUE_OR_POP(self, target, next_instr):
  974. w_value = self.peekvalue()
  975. if self.space.is_true(w_value):
  976. return target
  977. self.popvalue()
  978. return next_instr
  979. def JUMP_IF_NOT_DEBUG(self, jumpby, next_instr):
  980. if not self.space.sys.debug:
  981. next_instr += jumpby
  982. return next_instr
  983. def GET_ITER(self, oparg, next_instr):
  984. w_iterable = self.popvalue()
  985. w_iterator = self.space.iter(w_iterable)
  986. self.pushvalue(w_iterator)
  987. def FOR_ITER(self, jumpby, next_instr):
  988. w_iterator = self.peekvalue()
  989. try:
  990. w_nextitem = self.space.next(w_iterator)
  991. except OperationError, e:
  992. if not e.match(self.space, self.space.w_StopIteration):
  993. raise
  994. # iterator exhausted
  995. self.popvalue()
  996. next_instr += jumpby
  997. else:
  998. self.pushvalue(w_nextitem)
  999. return next_instr
  1000. def FOR_LOOP(self, oparg, next_instr):
  1001. raise BytecodeCorruption, "old opcode, no longer in use"
  1002. def SETUP_LOOP(self, offsettoend, next_instr):
  1003. block = LoopBlock(self, next_instr + offsettoend, self.lastblock)
  1004. self.lastblock = block
  1005. def SETUP_EXCEPT(self, offsettoend, next_instr):
  1006. block = ExceptBlock(self, next_instr + offsettoend, self.lastblock)
  1007. self.lastblock = block
  1008. def SETUP_FINALLY(self, offsettoend, next_instr):
  1009. block = FinallyBlock(self, next_instr + offsettoend, self.lastblock)
  1010. self.lastblock = block
  1011. def SETUP_WITH(self, offsettoend, next_instr):
  1012. w_manager = self.peekvalue()
  1013. w_enter = self.space.lookup(w_manager, "__enter__")
  1014. w_descr = self.space.lookup(w_manager, "__exit__")
  1015. if w_enter is None or w_descr is None:
  1016. raise oefmt(self.space.w_AttributeError,
  1017. "'%T' object is not a context manager (no __enter__/"
  1018. "__exit__ method)", w_manager)
  1019. w_exit = self.space.get(w_descr, w_manager)
  1020. self.settopvalue(w_exit)
  1021. w_result = self.space.get_and_call_function(w_enter, w_manager)
  1022. block = WithBlock(self, next_instr + offsettoend, self.lastblock)
  1023. self.lastblock = block
  1024. self.pushvalue(w_result)
  1025. def WITH_CLEANUP(self, oparg, next_instr):
  1026. # see comment in END_FINALLY for stack state
  1027. w_unroller = self.popvalue()
  1028. w_exitfunc = self.popvalue()
  1029. self.pushvalue(w_unroller)
  1030. if isinstance(w_unroller, SApplicationException):
  1031. # app-level exception
  1032. operr = w_unroller.operr
  1033. self.last_exception = operr
  1034. w_traceback = self.space.wrap(operr.get_traceback())
  1035. w_suppress = self.call_contextmanager_exit_function(
  1036. w_exitfunc,
  1037. operr.w_type,
  1038. operr.get_w_value(self.space),
  1039. w_traceback)
  1040. if self.space.is_true(w_suppress):
  1041. # __exit__() returned True -> Swallow the exception.
  1042. self.settopvalue(self.space.w_None)
  1043. else:
  1044. self.call_contextmanager_exit_function(
  1045. w_exitfunc,
  1046. self.space.w_None,
  1047. self.space.w_None,
  1048. self.space.w_None)
  1049. @jit.unroll_safe
  1050. def call_function(self, oparg, w_star=None, w_starstar=None):
  1051. n_arguments = oparg & 0xff
  1052. n_keywords = (oparg>>8) & 0xff
  1053. if n_keywords:
  1054. keywords = [None] * n_keywords
  1055. keywords_w = [None] * n_keywords
  1056. while True:
  1057. n_keywords -= 1
  1058. if n_keywords < 0:
  1059. break
  1060. w_value = self.popvalue()
  1061. w_key = self.popvalue()
  1062. key = self.space.str_w(w_key)
  1063. keywords[n_keywords] = key
  1064. keywords_w[n_keywords] = w_value
  1065. else:
  1066. keywords = None
  1067. keywords_w = None
  1068. arguments = self.popvalues(n_arguments)
  1069. args = self.argument_factory(arguments, keywords, keywords_w, w_star,
  1070. w_starstar)
  1071. w_function = self.popvalue()
  1072. if self.get_is_being_profiled() and function.is_builtin_code(w_function):
  1073. w_result = self.space.call_args_and_c_profile(self, w_function,
  1074. args)
  1075. else:
  1076. w_result = self.space.call_args(w_function, args)
  1077. self.pushvalue(w_result)
  1078. def CALL_FUNCTION(self, oparg, next_instr):
  1079. # XXX start of hack for performance
  1080. if (oparg >> 8) & 0xff == 0:
  1081. # Only positional arguments
  1082. nargs = oparg & 0xff
  1083. w_function = self.peekvalue(nargs)
  1084. try:
  1085. w_result = self.space.call_valuestack(w_function, nargs, self)
  1086. finally:
  1087. self.dropvalues(nargs + 1)
  1088. self.pushvalue(w_result)
  1089. # XXX end of hack for performance
  1090. else:
  1091. # general case
  1092. self.call_function(oparg)
  1093. def CALL_FUNCTION_VAR(self, oparg, next_instr):
  1094. w_varargs = self.popvalue()
  1095. self.call_function(oparg, w_varargs)
  1096. def CALL_FUNCTION_KW(self, oparg, next_instr):
  1097. w_varkw = self.popvalue()
  1098. self.call_function(oparg, None, w_varkw)
  1099. def CALL_FUNCTION_VAR_KW(self, oparg, next_instr):
  1100. w_varkw = self.popvalue()
  1101. w_varargs = self.popvalue()
  1102. self.call_function(oparg, w_varargs, w_varkw)
  1103. def MAKE_FUNCTION(self, numdefaults, next_instr):
  1104. w_codeobj = self.popvalue()
  1105. codeobj = self.space.interp_w(PyCode, w_codeobj)
  1106. defaultarguments = self.popvalues(numdefaults)
  1107. fn = function.Function(self.space, codeobj, self.w_globals,
  1108. defaultarguments)
  1109. self.pushvalue(self.space.wrap(fn))
  1110. @jit.unroll_safe
  1111. def MAKE_CLOSURE(self, numdefaults, next_instr):
  1112. w_codeobj = self.popvalue()
  1113. codeobj = self.space.interp_w(pycode.PyCode, w_codeobj)
  1114. w_freevarstuple = self.popvalue()
  1115. freevars = [self.space.interp_w(Cell, cell)
  1116. for cell in self.space.fixedview(w_freevarstuple)]
  1117. defaultarguments = self.popvalues(numdefaults)
  1118. fn = function.Function(self.space, codeobj, self.w_globals,
  1119. defaultarguments, freevars)
  1120. self.pushvalue(self.space.wrap(fn))
  1121. def BUILD_SLICE(self, numargs, next_instr):
  1122. if numargs == 3:
  1123. w_step = self.popvalue()
  1124. elif numargs == 2:
  1125. w_step = self.space.w_None
  1126. else:
  1127. raise BytecodeCorruption
  1128. w_end = self.popvalue()
  1129. w_start = self.popvalue()
  1130. w_slice = self.space.newslice(w_start, w_end, w_step)
  1131. self.pushvalue(w_slice)
  1132. def LIST_APPEND(self, oparg, next_instr):
  1133. w = self.popvalue()
  1134. v = self.peekvalue(oparg - 1)
  1135. self.space.call_method(v, 'append', w)
  1136. def SET_ADD(self, oparg, next_instr):
  1137. w_value = self.popvalue()
  1138. w_set = self.peekvalue(oparg - 1)
  1139. self.space.call_method(w_set, 'add', w_value)
  1140. def MAP_ADD(self, oparg, next_instr):
  1141. w_key = self.popvalue()
  1142. w_value = self.popvalue()
  1143. w_dict = self.peekvalue(oparg - 1)
  1144. self.space.setitem(w_dict, w_key, w_value)
  1145. def SET_LINENO(self, lineno, next_instr):
  1146. pass
  1147. # overridden by faster version in the standard object space.
  1148. LOOKUP_METHOD = LOAD_ATTR
  1149. CALL_METHOD = CALL_FUNCTION
  1150. def MISSING_OPCODE(self, oparg, next_instr):
  1151. ofs = self.last_instr
  1152. c = self.pycode.co_code[ofs]
  1153. name = self.pycode.co_name
  1154. raise BytecodeCorruption("unknown opcode, ofs=%d, code=%d, name=%s" %
  1155. (ofs, ord(c), name) )
  1156. STOP_CODE = MISSING_OPCODE
  1157. def BUILD_MAP(self, itemcount, next_instr):
  1158. w_dict = self.space.newdict()
  1159. self.pushvalue(w_dict)
  1160. @jit.unroll_safe
  1161. def BUILD_SET(self, itemcount, next_instr):
  1162. w_set = self.space.newset()
  1163. for i in range(itemcount):
  1164. w_item = self.popvalue()
  1165. self.space.call_method(w_set, 'add', w_item)
  1166. self.pushvalue(w_set)
  1167. def STORE_MAP(self, oparg, next_instr):
  1168. w_key = self.popvalue()
  1169. w_value = self.popvalue()
  1170. w_dict = self.peekvalue()
  1171. self.space.setitem(w_dict, w_key, w_value)
  1172. ### ____________________________________________________________ ###
  1173. class ExitFrame(Exception):
  1174. pass
  1175. class Return(ExitFrame):
  1176. """Raised when exiting a frame via a 'return' statement."""
  1177. class Yield(ExitFrame):
  1178. """Raised when exiting a frame via a 'yield' statement."""
  1179. class RaiseWithExplicitTraceback(Exception):
  1180. """Raised at interp-level by a 0- or 3-arguments 'raise' statement."""
  1181. def __init__(self, operr):
  1182. self.operr = operr
  1183. ### Frame Blocks ###
  1184. class SuspendedUnroller(W_Root):
  1185. """Abstract base class for interpreter-level objects that
  1186. instruct the interpreter to change the control flow and the
  1187. block stack.
  1188. The concrete subclasses correspond to the various values WHY_XXX
  1189. values of the why_code enumeration in ceval.c:
  1190. WHY_NOT, OK, not this one :-)
  1191. WHY_EXCEPTION, SApplicationException
  1192. WHY_RERAISE, implemented differently, see Reraise
  1193. WHY_RETURN, SReturnValue
  1194. WHY_BREAK, SBreakLoop
  1195. WHY_CONTINUE, SContinueLoop
  1196. WHY_YIELD not needed
  1197. """
  1198. _immutable_ = True
  1199. def nomoreblocks(self):
  1200. raise BytecodeCorruption("misplaced bytecode - should not return")
  1201. class SReturnValue(SuspendedUnroller):
  1202. """Signals a 'return' statement.
  1203. Argument is the wrapped object to return."""
  1204. _immutable_ = True
  1205. kind = 0x01
  1206. def __init__(self, w_returnvalue):
  1207. self.w_returnvalue = w_returnvalue
  1208. def nomoreblocks(self):
  1209. return self.w_returnvalue
  1210. class SApplicationException(SuspendedUnroller):
  1211. """Signals an application-level exception
  1212. (i.e. an OperationException)."""
  1213. _immutable_ = True
  1214. kind = 0x02
  1215. def __init__(self, operr):
  1216. self.operr = operr
  1217. def nomoreblocks(self):
  1218. raise RaiseWithExplicitTraceback(self.operr)
  1219. class SBreakLoop(SuspendedUnroller):
  1220. """Signals a 'break' statement."""
  1221. _immutable_ = True
  1222. kind = 0x04
  1223. SBreakLoop.singleton = SBreakLoop()
  1224. class SContinueLoop(SuspendedUnroller):
  1225. """Signals a 'continue' statement.
  1226. Argument is the bytecode position of the beginning of the loop."""
  1227. _immutable_ = True
  1228. kind = 0x08
  1229. def __init__(self, jump_to):
  1230. self.jump_to = jump_to
  1231. class FrameBlock(object):
  1232. """Abstract base class for frame blocks from the blockstack,
  1233. used by the SETUP_XXX and POP_BLOCK opcodes."""
  1234. _immutable_ = True
  1235. def __init__(self, frame, handlerposition, previous):
  1236. self.handlerposition = handlerposition
  1237. self.valuestackdepth = frame.valuestackdepth
  1238. self.previous = previous # this makes a linked list of blocks
  1239. def __eq__(self, other):
  1240. return (self.__class__ is other.__class__ and
  1241. self.handlerposition == other.handlerposition and
  1242. self.valuestackdepth == other.valuestackdepth)
  1243. def __ne__(self, other):
  1244. return not (self == other)
  1245. def __hash__(self):
  1246. return hash((self.handlerposition, self.valuestackdepth))
  1247. def cleanupstack(self, frame):
  1248. frame.dropvaluesuntil(self.valuestackdepth)
  1249. def cleanup(self, frame):
  1250. "Clean up a frame when we normally exit the block."
  1251. self.cleanupstack(frame)
  1252. # internal pickling interface, not using the standard protocol
  1253. def _get_state_(self, space):
  1254. w = space.wrap
  1255. return space.newtuple([w(self._opname), w(self.handlerposition),
  1256. w(self.valuestackdepth)])
  1257. def handle(self, frame, unroller):
  1258. """ Purely abstract method
  1259. """
  1260. raise NotImplementedError
  1261. class LoopBlock(FrameBlock):
  1262. """A loop block. Stores the end-of-loop pointer in case of 'break'."""
  1263. _immutable_ = True
  1264. _opname = 'SETUP_LOOP'
  1265. handling_mask = SBreakLoop.kind | SContinueLoop.kind
  1266. def handle(self, frame, unroller):
  1267. if isinstance(unroller, SContinueLoop):
  1268. # re-push the loop block without cleaning up the value stack,
  1269. # and jump to the beginning of the loop, stored in the
  1270. # exception's argument
  1271. frame.append_block(self)
  1272. jumpto = unroller.jump_to
  1273. ec = frame.space.getexecutioncontext()
  1274. return r_uint(frame.jump_absolute(jumpto, ec))
  1275. else:
  1276. # jump to the end of the loop
  1277. self.cleanupstack(frame)
  1278. return r_uint(self.handlerposition)
  1279. class ExceptBlock(FrameBlock):
  1280. """An try:except: block. Stores the position of the exception handler."""
  1281. _immutable_ = True
  1282. _opname = 'SETUP_EXCEPT'
  1283. handling_mask = SApplicationException.kind
  1284. def handle(self, frame, unroller):
  1285. # push the exception to the value stack for inspection by the
  1286. # exception handler (the code after the except:)
  1287. self.cleanupstack(frame)
  1288. assert isinstance(unroller, SApplicationException)
  1289. operationerr = unroller.operr
  1290. operationerr.normalize_exception(frame.space)
  1291. # the stack setup is slightly different than in CPython:
  1292. # instead of the traceback, we store the unroller object,
  1293. # wrapped.
  1294. frame.pushvalue(frame.space.wrap(unroller))
  1295. frame.pushvalue(operationerr.get_w_value(frame.space))
  1296. frame.pushvalue(operationerr.w_type)
  1297. frame.last_exception = operationerr
  1298. return r_uint(self.handlerposition) # jump to the handler
  1299. class FinallyBlock(FrameBlock):
  1300. """A try:finally: block. Stores the position of the exception handler."""
  1301. _immutable_ = True
  1302. _opname = 'SETUP_FINALLY'
  1303. handling_mask = -1 # handles every kind of SuspendedUnroller
  1304. def handle(self, frame, unroller):
  1305. # any abnormal reason for unrolling a finally: triggers the end of
  1306. # the block unrolling and the entering the finally: handler.
  1307. # see comments in cleanup().
  1308. self.cleanupstack(frame)
  1309. frame.pushvalue(frame.space.wrap(unroller))
  1310. return r_uint(self.handlerposition) # jump to the handler
  1311. class WithBlock(FinallyBlock):
  1312. _immutable_ = True
  1313. def handle(self, frame, unroller):
  1314. if isinstance(unroller, SApplicationException):
  1315. unroller.operr.normalize_exception(frame.space)
  1316. return FinallyBlock.handle(self, frame, unroller)
  1317. block_classes = {'SETUP_LOOP': LoopBlock,
  1318. 'SETUP_EXCEPT': ExceptBlock,
  1319. 'SETUP_FINALLY': FinallyBlock,
  1320. 'SETUP_WITH': WithBlock,
  1321. }
  1322. ### helpers written at the application-level ###
  1323. # Some of these functions are expected to be generally useful if other
  1324. # parts of the code need to do the same thing as a non-trivial opcode,
  1325. # like finding out which metaclass a new class should have.
  1326. # This is why they are not methods of PyFrame.
  1327. # There are also a couple of helpers that are methods, defined in the
  1328. # class above.
  1329. app = gateway.applevel(r'''
  1330. """ applevel implementation of certain system properties, imports
  1331. and other helpers"""
  1332. import sys
  1333. def sys_stdout():
  1334. try:
  1335. return sys.stdout
  1336. except AttributeError:
  1337. raise RuntimeError("lost sys.stdout")
  1338. def print_expr(obj):
  1339. try:
  1340. displayhook = sys.displayhook
  1341. except AttributeError:
  1342. raise RuntimeError("lost sys.displayhook")
  1343. displayhook(obj)
  1344. def print_item_to(x, stream):
  1345. if file_softspace(stream, False):
  1346. stream.write(" ")
  1347. # give to write() an argument which is either a string or a unicode
  1348. # (and let it deals itself with unicode handling). The check "is
  1349. # unicode" should not use isinstance() at app-level, because that
  1350. # could be fooled by strange objects, so it is done at interp-level.
  1351. stream.write(x)
  1352. # add a softspace unless we just printed a string which ends in a '\t'
  1353. # or '\n' -- or more generally any whitespace character but ' '
  1354. if x:
  1355. lastchar = x[-1]
  1356. if lastchar.isspace() and lastchar != ' ':
  1357. return
  1358. file_softspace(stream, True)
  1359. def print_item(x):
  1360. print_item_to(x, sys_stdout())
  1361. def print_newline_to(stream):
  1362. stream.write("\n")
  1363. file_softspace(stream, False)
  1364. def print_newline():
  1365. print_newline_to(sys_stdout())
  1366. def file_softspace(file, newflag):
  1367. try:
  1368. softspace = file.softspace
  1369. except AttributeError:
  1370. softspace = 0
  1371. try:
  1372. file.softspace = newflag
  1373. except AttributeError:
  1374. pass
  1375. return softspace
  1376. ''', filename=__file__)
  1377. sys_stdout = app.interphook('sys_stdout')
  1378. print_expr = app.interphook('print_expr')
  1379. print_item = app.interphook('print_item')
  1380. print_item_to = app.interphook('print_item_to')
  1381. print_newline = app.interphook('print_newline')
  1382. print_newline_to= app.interphook('print_newline_to')
  1383. file_softspace = app.interphook('file_softspace')
  1384. app = gateway.applevel(r'''
  1385. def find_metaclass(bases, namespace, globals, builtin):
  1386. if '__metaclass__' in namespace:
  1387. return namespace['__metaclass__']
  1388. elif len(bases) > 0:
  1389. base = bases[0]
  1390. if hasattr(base, '__class__'):
  1391. return base.__class__
  1392. else:
  1393. return type(base)
  1394. elif '__metaclass__' in globals:
  1395. return globals['__metaclass__']
  1396. else:
  1397. try:
  1398. return builtin.__metaclass__
  1399. except AttributeError:
  1400. return type
  1401. ''', filename=__file__)
  1402. find_metaclass = app.interphook('find_metaclass')
  1403. app = gateway.applevel(r'''
  1404. def import_all_from(module, into_locals):
  1405. try:
  1406. all = module.__all__
  1407. except AttributeError:
  1408. try:
  1409. dict = module.__dict__
  1410. except AttributeError:
  1411. raise ImportError("from-import-* object has no __dict__ "
  1412. "and no __all__")
  1413. all = dict.keys()
  1414. skip_leading_underscores = True
  1415. else:
  1416. skip_leading_underscores = False
  1417. for name in all:
  1418. if skip_leading_underscores and name[0]=='_':
  1419. continue
  1420. into_locals[name] = getattr(module, name)
  1421. ''', filename=__file__)
  1422. import_all_from = app.interphook('import_all_from')
  1423. app = gateway.applevel(r'''
  1424. def prepare_exec(f, prog, globals, locals, compile_flags, builtin, codetype):
  1425. """Manipulate parameters to exec statement to (codeobject, dict, dict).
  1426. """
  1427. if (globals is None and locals is None and
  1428. isinstance(prog, tuple) and
  1429. (len(prog) == 2 or len(prog) == 3)):
  1430. globals = prog[1]
  1431. if len(prog) == 3:
  1432. locals = prog[2]
  1433. prog = prog[0]
  1434. if globals is None:
  1435. globals = f.f_globals
  1436. if locals is None:
  1437. locals = f.f_locals
  1438. if locals is None:
  1439. locals = globals
  1440. if not isinstance(globals, dict):
  1441. if not hasattr(globals, '__getitem__'):
  1442. raise TypeError("exec: arg 2 must be a dictionary or None")
  1443. globals.setdefault('__builtins__', builtin)
  1444. if not isinstance(locals, dict):
  1445. if not hasattr(locals, '__getitem__'):
  1446. raise TypeError("exec: arg 3 must be a dictionary or None")
  1447. if not isinstance(prog, codetype):
  1448. filename = '<string>'
  1449. if not isinstance(prog, basestring):
  1450. if isinstance(prog, file):
  1451. filename = prog.name
  1452. prog = prog.read()
  1453. else:
  1454. raise TypeError("exec: arg 1 must be a string, file, "
  1455. "or code object")
  1456. prog = compile(prog, filename, 'exec', compile_flags, 1)
  1457. return (prog, globals, locals)
  1458. ''', filename=__file__)
  1459. prepare_exec = app.interphook('prepare_exec')