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

/Python/compile.c

http://unladen-swallow.googlecode.com/
C | 4071 lines | 3303 code | 365 blank | 403 comment | 693 complexity | 90a995028856bda463af1ecde267e58a MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. /*
  2. * This file compiles an abstract syntax tree (AST) into Python bytecode.
  3. *
  4. * The primary entry point is PyAST_Compile(), which returns a
  5. * PyCodeObject. The compiler makes several passes to build the code
  6. * object:
  7. * 1. Checks for future statements. See future.c
  8. * 2. Builds a symbol table. See symtable.c.
  9. * 3. Generate code for basic blocks. See compiler_mod() in this file.
  10. * 4. Assemble the basic blocks into final code. See assemble() in
  11. * this file.
  12. * 5. Optimize the byte code (peephole optimizations). See peephole.c
  13. *
  14. * Note that compiler_mod() suggests module, but the module ast type
  15. * (mod_ty) has cases for expressions and interactive statements.
  16. *
  17. * CAUTION: The VISIT_* macros abort the current function when they
  18. * encounter a problem. So don't invoke them when there is memory
  19. * which needs to be released. Code blocks are OK, as the compiler
  20. * structure takes care of releasing those. Use the arena to manage
  21. * objects.
  22. */
  23. #include "Python.h"
  24. #include "Python-ast.h"
  25. #include "node.h"
  26. #include "pyarena.h"
  27. #include "ast.h"
  28. #include "code.h"
  29. #include "compile.h"
  30. #include "symtable.h"
  31. #include "opcode.h"
  32. #define DEFAULT_BLOCK_SIZE 16
  33. #define DEFAULT_BLOCKS 8
  34. #define DEFAULT_CODE_SIZE 128
  35. #define DEFAULT_LNOTAB_SIZE 16
  36. struct instr {
  37. unsigned i_jabs : 1;
  38. unsigned i_jrel : 1;
  39. unsigned i_hasarg : 1;
  40. unsigned char i_opcode;
  41. int i_oparg;
  42. struct basicblock_ *i_target; /* target block (if jump instruction) */
  43. int i_lineno;
  44. };
  45. typedef struct basicblock_ {
  46. /* Each basicblock in a compilation unit is linked via b_list in the
  47. reverse order that the block are allocated. b_list points to the next
  48. block, not to be confused with b_next, which is next by control flow. */
  49. struct basicblock_ *b_list;
  50. /* number of instructions used */
  51. int b_iused;
  52. /* length of instruction array (b_instr) */
  53. int b_ialloc;
  54. /* pointer to an array of instructions, initially NULL */
  55. struct instr *b_instr;
  56. /* If b_next is non-NULL, it is a pointer to the next
  57. block reached by normal control flow. */
  58. struct basicblock_ *b_next;
  59. /* b_seen is used to perform a DFS of basicblocks. */
  60. unsigned b_seen : 1;
  61. /* b_return is true if a RETURN_VALUE opcode is inserted. */
  62. unsigned b_return : 1;
  63. /* depth of stack upon entry of block, computed by stackdepth() */
  64. int b_startdepth;
  65. /* instruction offset for block, computed by assemble_jump_offsets() */
  66. int b_offset;
  67. } basicblock;
  68. /* fblockinfo tracks the current frame block.
  69. A frame block is used to handle loops, try/except, and try/finally.
  70. It's called a frame block to distinguish it from a basic block in the
  71. compiler IR.
  72. */
  73. enum fblocktype { FOR_LOOP, WHILE_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
  74. struct fblockinfo {
  75. enum fblocktype fb_type;
  76. basicblock *fb_block;
  77. basicblock *fb_target;
  78. };
  79. /* The following items change on entry and exit of code blocks.
  80. They must be saved and restored when returning to a block.
  81. */
  82. struct compiler_unit {
  83. PySTEntryObject *u_ste;
  84. PyObject *u_name;
  85. /* The following fields are dicts that map objects to
  86. the index of them in co_XXX. The index is used as
  87. the argument for opcodes that refer to those collections.
  88. */
  89. PyObject *u_consts; /* all constants */
  90. PyObject *u_names; /* all names */
  91. PyObject *u_varnames; /* local variables */
  92. PyObject *u_cellvars; /* cell variables */
  93. PyObject *u_freevars; /* free variables */
  94. PyObject *u_private; /* for private name mangling */
  95. int u_argcount; /* number of arguments for block */
  96. /* Pointer to the most recently allocated block. By following b_list
  97. members, you can reach all early allocated blocks. */
  98. basicblock *u_blocks;
  99. basicblock *u_curblock; /* pointer to current block */
  100. int u_tmpname; /* temporary variables for list comps */
  101. int u_nfblocks;
  102. struct fblockinfo u_fblock[CO_MAXBLOCKS];
  103. int u_firstlineno; /* the first lineno of the block */
  104. int u_lineno; /* the lineno for the current stmt */
  105. bool u_lineno_set; /* boolean to indicate whether instr
  106. has been generated with current lineno */
  107. bool u_uses_exec; /* Whether this code object uses exec */
  108. };
  109. /* This struct captures the global state of a compilation.
  110. The u pointer points to the current compilation unit, while units
  111. for enclosing blocks are stored in c_stack. The u and c_stack are
  112. managed by compiler_enter_scope() and compiler_exit_scope().
  113. */
  114. struct compiler {
  115. const char *c_filename;
  116. struct symtable *c_st;
  117. PyFutureFeatures *c_future; /* pointer to module's __future__ */
  118. PyCompilerFlags *c_flags;
  119. int c_interactive; /* true if in interactive mode */
  120. int c_nestlevel;
  121. struct compiler_unit *u; /* compiler state for current block */
  122. PyObject *c_stack; /* Python list holding compiler_unit ptrs */
  123. char *c_encoding; /* source encoding (a borrowed reference) */
  124. PyArena *c_arena; /* pointer to memory allocation arena */
  125. };
  126. static int compiler_enter_scope(struct compiler *, identifier, void *, int);
  127. static void compiler_free(struct compiler *);
  128. static basicblock *compiler_new_block(struct compiler *);
  129. static int compiler_next_instr(struct compiler *, basicblock *);
  130. static int compiler_addop(struct compiler *, int);
  131. static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
  132. static int compiler_addop_i(struct compiler *, int, int);
  133. static int compiler_addop_j(struct compiler *, int, basicblock *, int);
  134. static basicblock *compiler_use_new_block(struct compiler *);
  135. static int compiler_error(struct compiler *, const char *);
  136. static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
  137. static int compiler_load_global(struct compiler *, const char *);
  138. static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
  139. static int compiler_visit_stmt(struct compiler *, stmt_ty);
  140. static int compiler_visit_keyword(struct compiler *, keyword_ty);
  141. static int compiler_visit_expr(struct compiler *, expr_ty);
  142. static int compiler_augassign(struct compiler *, stmt_ty);
  143. static int compiler_visit_slice(struct compiler *, slice_ty,
  144. expr_context_ty);
  145. /* top is the basic block representing the top of the loop or try. target
  146. is really only relevant for loops, and indicates where a break instruction
  147. should jump to. */
  148. static int compiler_push_fblock(struct compiler *, enum fblocktype,
  149. basicblock *top, basicblock *target);
  150. static void compiler_pop_fblock(struct compiler *, enum fblocktype,
  151. basicblock *top, basicblock *target);
  152. /* Returns true if there is a loop on the fblock stack. */
  153. static int compiler_in_loop(struct compiler *);
  154. static int inplace_binop(struct compiler *, operator_ty);
  155. static int expr_constant(expr_ty e);
  156. static int compiler_with(struct compiler *, stmt_ty);
  157. static PyCodeObject *assemble(struct compiler *, int addNone);
  158. static PyObject *__doc__;
  159. PyObject *
  160. _Py_Mangle(PyObject *privateobj, PyObject *ident)
  161. {
  162. /* Name mangling: __private becomes _classname__private.
  163. This is independent from how the name is used. */
  164. const char *p, *name = PyString_AsString(ident);
  165. char *buffer;
  166. size_t nlen, plen;
  167. if (privateobj == NULL || !PyString_Check(privateobj) ||
  168. name == NULL || name[0] != '_' || name[1] != '_') {
  169. Py_INCREF(ident);
  170. return ident;
  171. }
  172. p = PyString_AsString(privateobj);
  173. nlen = strlen(name);
  174. /* Don't mangle __id__ or names with dots.
  175. The only time a name with a dot can occur is when
  176. we are compiling an import statement that has a
  177. package name.
  178. TODO(jhylton): Decide whether we want to support
  179. mangling of the module name, e.g. __M.X.
  180. */
  181. if ((name[nlen-1] == '_' && name[nlen-2] == '_')
  182. || strchr(name, '.')) {
  183. Py_INCREF(ident);
  184. return ident; /* Don't mangle __whatever__ */
  185. }
  186. /* Strip leading underscores from class name */
  187. while (*p == '_')
  188. p++;
  189. if (*p == '\0') {
  190. Py_INCREF(ident);
  191. return ident; /* Don't mangle if class is just underscores */
  192. }
  193. plen = strlen(p);
  194. assert(1 <= PY_SSIZE_T_MAX - nlen);
  195. assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
  196. ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
  197. if (!ident)
  198. return 0;
  199. /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
  200. buffer = PyString_AS_STRING(ident);
  201. buffer[0] = '_';
  202. strncpy(buffer+1, p, plen);
  203. strcpy(buffer+1+plen, name);
  204. return ident;
  205. }
  206. static int
  207. compiler_init(struct compiler *c)
  208. {
  209. memset(c, 0, sizeof(struct compiler));
  210. c->c_stack = PyList_New(0);
  211. if (!c->c_stack)
  212. return 0;
  213. return 1;
  214. }
  215. PyCodeObject *
  216. PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
  217. PyArena *arena)
  218. {
  219. struct compiler c;
  220. PyCodeObject *co = NULL;
  221. PyCompilerFlags local_flags;
  222. int merged;
  223. if (!__doc__) {
  224. __doc__ = PyString_InternFromString("__doc__");
  225. if (!__doc__)
  226. return NULL;
  227. }
  228. if (!compiler_init(&c))
  229. return NULL;
  230. c.c_filename = filename;
  231. c.c_arena = arena;
  232. c.c_future = PyFuture_FromAST(mod, filename);
  233. if (c.c_future == NULL)
  234. goto finally;
  235. if (!flags) {
  236. local_flags.cf_flags = 0;
  237. flags = &local_flags;
  238. }
  239. merged = c.c_future->ff_features | flags->cf_flags;
  240. c.c_future->ff_features = merged;
  241. flags->cf_flags = merged;
  242. c.c_flags = flags;
  243. c.c_nestlevel = 0;
  244. c.c_st = PySymtable_Build(mod, filename, c.c_future);
  245. if (c.c_st == NULL) {
  246. if (!PyErr_Occurred())
  247. PyErr_SetString(PyExc_SystemError, "no symtable");
  248. goto finally;
  249. }
  250. /* XXX initialize to NULL for now, need to handle */
  251. c.c_encoding = NULL;
  252. co = compiler_mod(&c, mod);
  253. finally:
  254. compiler_free(&c);
  255. assert(co || PyErr_Occurred());
  256. return co;
  257. }
  258. PyCodeObject *
  259. PyNode_Compile(struct _node *n, const char *filename)
  260. {
  261. PyCodeObject *co = NULL;
  262. mod_ty mod;
  263. PyArena *arena = PyArena_New();
  264. if (!arena)
  265. return NULL;
  266. mod = PyAST_FromNode(n, NULL, filename, arena);
  267. if (mod)
  268. co = PyAST_Compile(mod, filename, NULL, arena);
  269. PyArena_Free(arena);
  270. return co;
  271. }
  272. static void
  273. compiler_free(struct compiler *c)
  274. {
  275. if (c->c_st)
  276. PySymtable_Free(c->c_st);
  277. if (c->c_future)
  278. PyObject_Free(c->c_future);
  279. Py_DECREF(c->c_stack);
  280. }
  281. static PyObject *
  282. list2dict(PyObject *list)
  283. {
  284. Py_ssize_t i, n;
  285. PyObject *v, *k;
  286. PyObject *dict = PyDict_New();
  287. if (!dict) return NULL;
  288. n = PyList_Size(list);
  289. for (i = 0; i < n; i++) {
  290. v = PyInt_FromLong(i);
  291. if (!v) {
  292. Py_DECREF(dict);
  293. return NULL;
  294. }
  295. k = PyList_GET_ITEM(list, i);
  296. k = PyTuple_Pack(2, k, k->ob_type);
  297. if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
  298. Py_XDECREF(k);
  299. Py_DECREF(v);
  300. Py_DECREF(dict);
  301. return NULL;
  302. }
  303. Py_DECREF(k);
  304. Py_DECREF(v);
  305. }
  306. return dict;
  307. }
  308. /* Return new dict containing names from src that match scope(s).
  309. src is a symbol table dictionary. If the scope of a name matches
  310. either scope_type or flag is set, insert it into the new dict. The
  311. values are integers, starting at offset and increasing by one for
  312. each key.
  313. */
  314. static PyObject *
  315. dictbytype(PyObject *src, int scope_type, int flag, int offset)
  316. {
  317. Py_ssize_t pos = 0, i = offset, scope;
  318. PyObject *k, *v, *dest = PyDict_New();
  319. assert(offset >= 0);
  320. if (dest == NULL)
  321. return NULL;
  322. while (PyDict_Next(src, &pos, &k, &v)) {
  323. /* XXX this should probably be a macro in symtable.h */
  324. assert(PyInt_Check(v));
  325. scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
  326. if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
  327. PyObject *tuple, *item = PyInt_FromLong(i);
  328. if (item == NULL) {
  329. Py_DECREF(dest);
  330. return NULL;
  331. }
  332. i++;
  333. tuple = PyTuple_Pack(2, k, k->ob_type);
  334. if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
  335. Py_DECREF(item);
  336. Py_DECREF(dest);
  337. Py_XDECREF(tuple);
  338. return NULL;
  339. }
  340. Py_DECREF(item);
  341. Py_DECREF(tuple);
  342. }
  343. }
  344. return dest;
  345. }
  346. static void
  347. compiler_unit_check(struct compiler_unit *u)
  348. {
  349. basicblock *block;
  350. for (block = u->u_blocks; block != NULL; block = block->b_list) {
  351. assert((void *)block != (void *)0xcbcbcbcb);
  352. assert((void *)block != (void *)0xfbfbfbfb);
  353. assert((void *)block != (void *)0xdbdbdbdb);
  354. if (block->b_instr != NULL) {
  355. assert(block->b_ialloc > 0);
  356. assert(block->b_iused > 0);
  357. assert(block->b_ialloc >= block->b_iused);
  358. }
  359. else {
  360. assert (block->b_iused == 0);
  361. assert (block->b_ialloc == 0);
  362. }
  363. }
  364. }
  365. static void
  366. compiler_unit_free(struct compiler_unit *u)
  367. {
  368. basicblock *b, *next;
  369. compiler_unit_check(u);
  370. b = u->u_blocks;
  371. while (b != NULL) {
  372. if (b->b_instr)
  373. PyObject_Free((void *)b->b_instr);
  374. next = b->b_list;
  375. PyObject_Free((void *)b);
  376. b = next;
  377. }
  378. Py_CLEAR(u->u_ste);
  379. Py_CLEAR(u->u_name);
  380. Py_CLEAR(u->u_consts);
  381. Py_CLEAR(u->u_names);
  382. Py_CLEAR(u->u_varnames);
  383. Py_CLEAR(u->u_freevars);
  384. Py_CLEAR(u->u_cellvars);
  385. Py_CLEAR(u->u_private);
  386. PyObject_Free(u);
  387. }
  388. static int
  389. compiler_enter_scope(struct compiler *c, identifier name, void *key,
  390. int lineno)
  391. {
  392. struct compiler_unit *u;
  393. u = (struct compiler_unit *)PyObject_Malloc(sizeof(
  394. struct compiler_unit));
  395. if (!u) {
  396. PyErr_NoMemory();
  397. return 0;
  398. }
  399. memset(u, 0, sizeof(struct compiler_unit));
  400. u->u_argcount = 0;
  401. u->u_ste = PySymtable_Lookup(c->c_st, key);
  402. if (!u->u_ste) {
  403. compiler_unit_free(u);
  404. return 0;
  405. }
  406. Py_INCREF(name);
  407. u->u_name = name;
  408. u->u_varnames = list2dict(u->u_ste->ste_varnames);
  409. u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
  410. if (!u->u_varnames || !u->u_cellvars) {
  411. compiler_unit_free(u);
  412. return 0;
  413. }
  414. u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
  415. PyDict_Size(u->u_cellvars));
  416. if (!u->u_freevars) {
  417. compiler_unit_free(u);
  418. return 0;
  419. }
  420. u->u_blocks = NULL;
  421. u->u_tmpname = 0;
  422. u->u_nfblocks = 0;
  423. u->u_firstlineno = lineno;
  424. u->u_lineno = 0;
  425. u->u_lineno_set = false;
  426. u->u_uses_exec = false;
  427. u->u_consts = PyDict_New();
  428. if (!u->u_consts) {
  429. compiler_unit_free(u);
  430. return 0;
  431. }
  432. u->u_names = PyDict_New();
  433. if (!u->u_names) {
  434. compiler_unit_free(u);
  435. return 0;
  436. }
  437. u->u_private = NULL;
  438. /* Push the old compiler_unit on the stack. */
  439. if (c->u) {
  440. PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
  441. if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
  442. Py_XDECREF(wrapper);
  443. compiler_unit_free(u);
  444. return 0;
  445. }
  446. Py_DECREF(wrapper);
  447. u->u_private = c->u->u_private;
  448. Py_XINCREF(u->u_private);
  449. }
  450. c->u = u;
  451. c->c_nestlevel++;
  452. if (compiler_use_new_block(c) == NULL)
  453. return 0;
  454. return 1;
  455. }
  456. static void
  457. compiler_exit_scope(struct compiler *c)
  458. {
  459. int n;
  460. PyObject *wrapper;
  461. c->c_nestlevel--;
  462. compiler_unit_free(c->u);
  463. /* Restore c->u to the parent unit. */
  464. n = PyList_GET_SIZE(c->c_stack) - 1;
  465. if (n >= 0) {
  466. wrapper = PyList_GET_ITEM(c->c_stack, n);
  467. c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
  468. assert(c->u);
  469. /* we are deleting from a list so this really shouldn't fail */
  470. if (PySequence_DelItem(c->c_stack, n) < 0)
  471. Py_FatalError("compiler_exit_scope()");
  472. compiler_unit_check(c->u);
  473. }
  474. else
  475. c->u = NULL;
  476. }
  477. /* Allocate a new "anonymous" local variable.
  478. Used by list comprehensions and with statements.
  479. */
  480. static PyObject *
  481. compiler_new_tmpname(struct compiler *c)
  482. {
  483. char tmpname[256];
  484. PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
  485. return PyString_FromString(tmpname);
  486. }
  487. /* Allocate a new block and return a pointer to it.
  488. Returns NULL on error.
  489. */
  490. static basicblock *
  491. compiler_new_block(struct compiler *c)
  492. {
  493. basicblock *b;
  494. struct compiler_unit *u;
  495. u = c->u;
  496. b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
  497. if (b == NULL) {
  498. PyErr_NoMemory();
  499. return NULL;
  500. }
  501. memset((void *)b, 0, sizeof(basicblock));
  502. /* Extend the singly linked list of blocks with new block. */
  503. b->b_list = u->u_blocks;
  504. u->u_blocks = b;
  505. return b;
  506. }
  507. static basicblock *
  508. compiler_use_new_block(struct compiler *c)
  509. {
  510. basicblock *block = compiler_new_block(c);
  511. if (block == NULL)
  512. return NULL;
  513. c->u->u_curblock = block;
  514. return block;
  515. }
  516. static basicblock *
  517. compiler_use_next_block(struct compiler *c, basicblock *block)
  518. {
  519. assert(block != NULL);
  520. c->u->u_curblock->b_next = block;
  521. c->u->u_curblock = block;
  522. return block;
  523. }
  524. static basicblock *
  525. compiler_next_block(struct compiler *c)
  526. {
  527. basicblock *block = compiler_new_block(c);
  528. if (block == NULL)
  529. return NULL;
  530. return compiler_use_next_block(c, block);
  531. }
  532. /* Returns the offset of the next instruction in the current block's
  533. b_instr array. Resizes the b_instr as necessary.
  534. Returns -1 on failure.
  535. */
  536. static int
  537. compiler_next_instr(struct compiler *c, basicblock *b)
  538. {
  539. assert(b != NULL);
  540. if (b->b_instr == NULL) {
  541. b->b_instr = (struct instr *)PyObject_Malloc(
  542. sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
  543. if (b->b_instr == NULL) {
  544. PyErr_NoMemory();
  545. return -1;
  546. }
  547. b->b_ialloc = DEFAULT_BLOCK_SIZE;
  548. memset((char *)b->b_instr, 0,
  549. sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
  550. }
  551. else if (b->b_iused == b->b_ialloc) {
  552. struct instr *tmp;
  553. size_t oldsize, newsize;
  554. oldsize = b->b_ialloc * sizeof(struct instr);
  555. newsize = oldsize << 1;
  556. if (oldsize > (PY_SIZE_MAX >> 1)) {
  557. PyErr_NoMemory();
  558. return -1;
  559. }
  560. if (newsize == 0) {
  561. PyErr_NoMemory();
  562. return -1;
  563. }
  564. b->b_ialloc <<= 1;
  565. tmp = (struct instr *)PyObject_Realloc(
  566. (void *)b->b_instr, newsize);
  567. if (tmp == NULL) {
  568. PyErr_NoMemory();
  569. return -1;
  570. }
  571. b->b_instr = tmp;
  572. memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
  573. }
  574. return b->b_iused++;
  575. }
  576. /* Set the i_lineno member of the instruction at offset off if the
  577. line number for the current expression/statement has not
  578. already been set. If it has been set, the call has no effect.
  579. The line number is reset in the following cases:
  580. - when entering a new scope
  581. - on each statement
  582. - on each expression that start a new line
  583. - before the "except" clause
  584. - before the "for" and "while" expressions
  585. */
  586. static void
  587. compiler_set_lineno(struct compiler *c, int off)
  588. {
  589. basicblock *b;
  590. if (c->u->u_lineno_set)
  591. return;
  592. c->u->u_lineno_set = true;
  593. b = c->u->u_curblock;
  594. b->b_instr[off].i_lineno = c->u->u_lineno;
  595. }
  596. int
  597. _Py_OpcodeStackEffect(int opcode, int oparg)
  598. {
  599. switch (opcode) {
  600. case POP_TOP:
  601. return -1;
  602. case ROT_TWO:
  603. case ROT_THREE:
  604. return 0;
  605. case DUP_TOP:
  606. return 1;
  607. case ROT_FOUR:
  608. return 0;
  609. case UNARY_POSITIVE:
  610. case UNARY_NEGATIVE:
  611. case UNARY_NOT:
  612. case UNARY_CONVERT:
  613. case UNARY_INVERT:
  614. return 0;
  615. case LIST_APPEND:
  616. return -2;
  617. case BINARY_POWER:
  618. case BINARY_MULTIPLY:
  619. case BINARY_DIVIDE:
  620. case BINARY_MODULO:
  621. case BINARY_ADD:
  622. case BINARY_SUBTRACT:
  623. case BINARY_SUBSCR:
  624. case BINARY_FLOOR_DIVIDE:
  625. case BINARY_TRUE_DIVIDE:
  626. return -1;
  627. case INPLACE_FLOOR_DIVIDE:
  628. case INPLACE_TRUE_DIVIDE:
  629. return -1;
  630. case SLICE_NONE:
  631. return 0;
  632. case SLICE_LEFT:
  633. return -1;
  634. case SLICE_RIGHT:
  635. return -1;
  636. case SLICE_BOTH:
  637. return -2;
  638. case STORE_SLICE_NONE:
  639. return -2;
  640. case STORE_SLICE_LEFT:
  641. return -3;
  642. case STORE_SLICE_RIGHT:
  643. return -3;
  644. case STORE_SLICE_BOTH:
  645. return -4;
  646. case DELETE_SLICE_NONE:
  647. return -1;
  648. case DELETE_SLICE_LEFT:
  649. return -2;
  650. case DELETE_SLICE_RIGHT:
  651. return -2;
  652. case DELETE_SLICE_BOTH:
  653. return -3;
  654. case INPLACE_ADD:
  655. case INPLACE_SUBTRACT:
  656. case INPLACE_MULTIPLY:
  657. case INPLACE_DIVIDE:
  658. case INPLACE_MODULO:
  659. return -1;
  660. case STORE_SUBSCR:
  661. return -3;
  662. case STORE_MAP:
  663. return -2;
  664. case DELETE_SUBSCR:
  665. return -2;
  666. case BINARY_LSHIFT:
  667. case BINARY_RSHIFT:
  668. case BINARY_AND:
  669. case BINARY_XOR:
  670. case BINARY_OR:
  671. return -1;
  672. case INPLACE_POWER:
  673. return -1;
  674. case GET_ITER:
  675. return 0;
  676. case INPLACE_LSHIFT:
  677. case INPLACE_RSHIFT:
  678. case INPLACE_AND:
  679. case INPLACE_XOR:
  680. case INPLACE_OR:
  681. return -1;
  682. case BREAK_LOOP:
  683. return 0;
  684. case WITH_CLEANUP:
  685. return -1;
  686. case RETURN_VALUE:
  687. return -1;
  688. case YIELD_VALUE:
  689. return 0;
  690. case POP_BLOCK:
  691. return 0;
  692. case END_FINALLY:
  693. return -3;
  694. case STORE_NAME:
  695. return -1;
  696. case DELETE_NAME:
  697. return 0;
  698. case UNPACK_SEQUENCE:
  699. return oparg-1;
  700. case FOR_ITER:
  701. return 1;
  702. case STORE_ATTR:
  703. return -2;
  704. case DELETE_ATTR:
  705. return -1;
  706. case STORE_GLOBAL:
  707. return -1;
  708. case DELETE_GLOBAL:
  709. return 0;
  710. case DUP_TOP_TWO:
  711. return 2;
  712. case DUP_TOP_THREE:
  713. return 3;
  714. case LOAD_CONST:
  715. return 1;
  716. case LOAD_NAME:
  717. return 1;
  718. case BUILD_TUPLE:
  719. case BUILD_LIST:
  720. return 1-oparg;
  721. case BUILD_MAP:
  722. return 1;
  723. case LOAD_ATTR:
  724. return 0;
  725. case LOAD_METHOD:
  726. return 1; /* Maybe set top, push one. */
  727. case COMPARE_OP:
  728. return -1;
  729. case IMPORT_NAME:
  730. return -2; /* Pop three, push one. */
  731. case JUMP_FORWARD:
  732. case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
  733. case JUMP_IF_FALSE_OR_POP: /* "" */
  734. case JUMP_ABSOLUTE:
  735. return 0;
  736. case POP_JUMP_IF_FALSE:
  737. case POP_JUMP_IF_TRUE:
  738. return -1;
  739. case LOAD_GLOBAL:
  740. return 1;
  741. case CONTINUE_LOOP:
  742. return 0;
  743. case SETUP_LOOP:
  744. return 0;
  745. case SETUP_EXCEPT:
  746. case SETUP_FINALLY:
  747. return 3; /* actually pushed by an exception */
  748. case LOAD_FAST:
  749. return 1;
  750. case STORE_FAST:
  751. return -1;
  752. case DELETE_FAST:
  753. return 0;
  754. case RAISE_VARARGS_ZERO:
  755. return 0;
  756. case RAISE_VARARGS_ONE:
  757. return -1;
  758. case RAISE_VARARGS_TWO:
  759. return -2;
  760. case RAISE_VARARGS_THREE:
  761. return -3;
  762. #define NARGS(o) (((o) % 256) + 2*((o) / 256))
  763. case CALL_FUNCTION:
  764. return -NARGS(oparg);
  765. case CALL_METHOD:
  766. return -NARGS(oparg)-1;
  767. case CALL_FUNCTION_VAR:
  768. case CALL_FUNCTION_KW:
  769. return -NARGS(oparg)-1;
  770. case CALL_FUNCTION_VAR_KW:
  771. return -NARGS(oparg)-2;
  772. #undef NARGS
  773. case BUILD_SLICE_TWO:
  774. return -1;
  775. case BUILD_SLICE_THREE:
  776. return -2;
  777. case MAKE_CLOSURE:
  778. return -(oparg + 1);
  779. case LOAD_CLOSURE:
  780. return 1;
  781. case LOAD_DEREF:
  782. return 1;
  783. case STORE_DEREF:
  784. return -1;
  785. default:
  786. fprintf(stderr, "opcode = %d\n", opcode);
  787. Py_FatalError("_Py_OpcodeStackEffect()");
  788. }
  789. return 0; /* not reachable */
  790. }
  791. /* Add an opcode with no argument.
  792. Returns 0 on failure, 1 on success.
  793. */
  794. static int
  795. compiler_addop(struct compiler *c, int opcode)
  796. {
  797. basicblock *b;
  798. struct instr *i;
  799. int off;
  800. off = compiler_next_instr(c, c->u->u_curblock);
  801. if (off < 0)
  802. return 0;
  803. b = c->u->u_curblock;
  804. i = &b->b_instr[off];
  805. i->i_opcode = opcode;
  806. i->i_hasarg = 0;
  807. if (opcode == RETURN_VALUE)
  808. b->b_return = 1;
  809. compiler_set_lineno(c, off);
  810. return 1;
  811. }
  812. /* Adds 'o' to the mapping stored in 'dict' (if it wasn't already
  813. * there) so it can be looked up by opcodes like LOAD_CONST and
  814. * LOAD_NAME. This function derives a tuple from o to avoid pairs of
  815. * values like 0.0 and -0.0 or 0 and 0.0 that compare equal but need
  816. * to be kept separate. 'o' is mapped to a small integer, and its
  817. * mapping is returned. */
  818. static int
  819. compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
  820. {
  821. PyObject *t, *v;
  822. Py_ssize_t arg;
  823. unsigned char *p, *q;
  824. Py_complex z;
  825. double d;
  826. int real_part_zero, imag_part_zero;
  827. /* necessary to make sure types aren't coerced (e.g., int and long) */
  828. /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
  829. if (PyFloat_Check(o)) {
  830. d = PyFloat_AS_DOUBLE(o);
  831. p = (unsigned char*) &d;
  832. /* all we need is to make the tuple different in either the 0.0
  833. * or -0.0 case from all others, just to avoid the "coercion".
  834. */
  835. if (*p==0 && p[sizeof(double)-1]==0)
  836. t = PyTuple_Pack(3, o, o->ob_type, Py_None);
  837. else
  838. t = PyTuple_Pack(2, o, o->ob_type);
  839. }
  840. else if (PyComplex_Check(o)) {
  841. /* complex case is even messier: we need to make complex(x,
  842. 0.) different from complex(x, -0.) and complex(0., y)
  843. different from complex(-0., y), for any x and y. In
  844. particular, all four complex zeros should be
  845. distinguished.*/
  846. z = PyComplex_AsCComplex(o);
  847. p = (unsigned char*) &(z.real);
  848. q = (unsigned char*) &(z.imag);
  849. /* all that matters here is that on IEEE platforms
  850. real_part_zero will be true if z.real == 0., and false if
  851. z.real == -0. In fact, real_part_zero will also be true
  852. for some other rarely occurring nonzero floats, but this
  853. doesn't matter. Similar comments apply to
  854. imag_part_zero. */
  855. real_part_zero = *p==0 && p[sizeof(double)-1]==0;
  856. imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
  857. if (real_part_zero && imag_part_zero) {
  858. t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
  859. }
  860. else if (real_part_zero && !imag_part_zero) {
  861. t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
  862. }
  863. else if (!real_part_zero && imag_part_zero) {
  864. t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
  865. }
  866. else {
  867. t = PyTuple_Pack(2, o, o->ob_type);
  868. }
  869. }
  870. else {
  871. t = PyTuple_Pack(2, o, o->ob_type);
  872. }
  873. if (t == NULL)
  874. return -1;
  875. v = PyDict_GetItem(dict, t);
  876. if (!v) {
  877. arg = PyDict_Size(dict);
  878. v = PyInt_FromLong(arg);
  879. if (!v) {
  880. Py_DECREF(t);
  881. return -1;
  882. }
  883. if (PyDict_SetItem(dict, t, v) < 0) {
  884. Py_DECREF(t);
  885. Py_DECREF(v);
  886. return -1;
  887. }
  888. Py_DECREF(v);
  889. }
  890. else
  891. arg = PyInt_AsLong(v);
  892. Py_DECREF(t);
  893. return arg;
  894. }
  895. /* Adds opcode(o) as the next instruction in the current basic block.
  896. Because opcodes only take integer arguments, we give 'o' a number
  897. unique within 'dict' and store the mapping in 'dict'. 'dict' is one
  898. of c->u->u_{consts,names,varnames} and must match the code::co_list
  899. that 'opcode' looks in.
  900. */
  901. static int
  902. compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
  903. PyObject *o)
  904. {
  905. int arg = compiler_add_o(c, dict, o);
  906. if (arg < 0)
  907. return 0;
  908. return compiler_addop_i(c, opcode, arg);
  909. }
  910. /* Like compiler_addop_o, but name-mangles 'o' if appropriate. */
  911. static int
  912. compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
  913. PyObject *o)
  914. {
  915. int arg;
  916. PyObject *mangled = _Py_Mangle(c->u->u_private, o);
  917. if (!mangled)
  918. return 0;
  919. arg = compiler_add_o(c, dict, mangled);
  920. Py_DECREF(mangled);
  921. if (arg < 0)
  922. return 0;
  923. return compiler_addop_i(c, opcode, arg);
  924. }
  925. /* Add an opcode with an integer argument.
  926. Returns 0 on failure, 1 on success.
  927. */
  928. static int
  929. compiler_addop_i(struct compiler *c, int opcode, int oparg)
  930. {
  931. struct instr *i;
  932. int off;
  933. off = compiler_next_instr(c, c->u->u_curblock);
  934. if (off < 0)
  935. return 0;
  936. i = &c->u->u_curblock->b_instr[off];
  937. i->i_opcode = opcode;
  938. i->i_oparg = oparg;
  939. i->i_hasarg = 1;
  940. compiler_set_lineno(c, off);
  941. return 1;
  942. }
  943. /* Adds a jump opcode whose target is 'b'. This works for both
  944. conditional and unconditional jumps.
  945. */
  946. static int
  947. compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
  948. {
  949. struct instr *i;
  950. int off;
  951. assert(b != NULL);
  952. off = compiler_next_instr(c, c->u->u_curblock);
  953. if (off < 0)
  954. return 0;
  955. i = &c->u->u_curblock->b_instr[off];
  956. i->i_opcode = opcode;
  957. i->i_target = b;
  958. i->i_hasarg = 1;
  959. if (absolute)
  960. i->i_jabs = 1;
  961. else
  962. i->i_jrel = 1;
  963. compiler_set_lineno(c, off);
  964. return 1;
  965. }
  966. /* NEXT_BLOCK() creates a new block, creates an implicit jump from the
  967. current block to the new block, and sets the new block as the
  968. current block.
  969. */
  970. /* The returns inside these macros make it impossible to decref objects
  971. created in the local function. Local objects should use the arena.
  972. */
  973. #define NEXT_BLOCK(C) { \
  974. if (compiler_next_block((C)) == NULL) \
  975. return 0; \
  976. }
  977. #define ADDOP(C, OP) { \
  978. if (!compiler_addop((C), (OP))) \
  979. return 0; \
  980. }
  981. #define ADDOP_IN_SCOPE(C, OP) { \
  982. if (!compiler_addop((C), (OP))) { \
  983. compiler_exit_scope(c); \
  984. return 0; \
  985. } \
  986. }
  987. #define ADDOP_O(C, OP, O, TYPE) { \
  988. if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
  989. return 0; \
  990. }
  991. #define ADDOP_NAME(C, OP, O, TYPE) { \
  992. if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
  993. return 0; \
  994. }
  995. #define ADDOP_I(C, OP, O) { \
  996. if (!compiler_addop_i((C), (OP), (O))) \
  997. return 0; \
  998. }
  999. #define ADDOP_JABS(C, OP, O) { \
  1000. if (!compiler_addop_j((C), (OP), (O), 1)) \
  1001. return 0; \
  1002. }
  1003. #define ADDOP_JREL(C, OP, O) { \
  1004. if (!compiler_addop_j((C), (OP), (O), 0)) \
  1005. return 0; \
  1006. }
  1007. /* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
  1008. the ASDL name to synthesize the name of the C type and the visit function.
  1009. */
  1010. #define VISIT(C, TYPE, V) {\
  1011. if (!compiler_visit_ ## TYPE((C), (V))) \
  1012. return 0; \
  1013. }
  1014. #define VISIT_IN_SCOPE(C, TYPE, V) {\
  1015. if (!compiler_visit_ ## TYPE((C), (V))) { \
  1016. compiler_exit_scope(c); \
  1017. return 0; \
  1018. } \
  1019. }
  1020. #define VISIT_SLICE(C, V, CTX) {\
  1021. if (!compiler_visit_slice((C), (V), (CTX))) \
  1022. return 0; \
  1023. }
  1024. #define VISIT_SEQ(C, TYPE, SEQ) { \
  1025. int _i; \
  1026. asdl_seq *seq = (SEQ); /* avoid variable capture */ \
  1027. for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
  1028. TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
  1029. if (!compiler_visit_ ## TYPE((C), elt)) \
  1030. return 0; \
  1031. } \
  1032. }
  1033. #define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
  1034. int _i; \
  1035. asdl_seq *seq = (SEQ); /* avoid variable capture */ \
  1036. for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
  1037. TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
  1038. if (!compiler_visit_ ## TYPE((C), elt)) { \
  1039. compiler_exit_scope(c); \
  1040. return 0; \
  1041. } \
  1042. } \
  1043. }
  1044. static int
  1045. compiler_isdocstring(stmt_ty s)
  1046. {
  1047. if (s->kind != Expr_kind)
  1048. return 0;
  1049. return s->v.Expr.value->kind == Str_kind;
  1050. }
  1051. /* Compile a sequence of statements, checking for a docstring. */
  1052. static int
  1053. compiler_body(struct compiler *c, asdl_seq *stmts)
  1054. {
  1055. int i = 0;
  1056. stmt_ty st;
  1057. if (!asdl_seq_LEN(stmts))
  1058. return 1;
  1059. st = (stmt_ty)asdl_seq_GET(stmts, 0);
  1060. if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
  1061. /* don't generate docstrings if -OO */
  1062. i = 1;
  1063. VISIT(c, expr, st->v.Expr.value);
  1064. if (!compiler_nameop(c, __doc__, Store))
  1065. return 0;
  1066. }
  1067. for (; i < asdl_seq_LEN(stmts); i++)
  1068. VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
  1069. return 1;
  1070. }
  1071. static PyCodeObject *
  1072. compiler_mod(struct compiler *c, mod_ty mod)
  1073. {
  1074. PyCodeObject *co;
  1075. int addNone = 1;
  1076. static PyObject *module;
  1077. if (!module) {
  1078. module = PyString_InternFromString("<module>");
  1079. if (!module)
  1080. return NULL;
  1081. }
  1082. /* Use 0 for firstlineno initially, will fixup in assemble(). */
  1083. if (!compiler_enter_scope(c, module, mod, 0))
  1084. return NULL;
  1085. switch (mod->kind) {
  1086. case Module_kind:
  1087. if (!compiler_body(c, mod->v.Module.body)) {
  1088. compiler_exit_scope(c);
  1089. return 0;
  1090. }
  1091. break;
  1092. case Interactive_kind:
  1093. c->c_interactive = 1;
  1094. VISIT_SEQ_IN_SCOPE(c, stmt,
  1095. mod->v.Interactive.body);
  1096. break;
  1097. case Expression_kind:
  1098. VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
  1099. addNone = 0;
  1100. break;
  1101. case Suite_kind:
  1102. PyErr_SetString(PyExc_SystemError,
  1103. "suite should not be possible");
  1104. return 0;
  1105. default:
  1106. PyErr_Format(PyExc_SystemError,
  1107. "module kind %d should not be possible",
  1108. mod->kind);
  1109. return 0;
  1110. }
  1111. co = assemble(c, addNone);
  1112. compiler_exit_scope(c);
  1113. return co;
  1114. }
  1115. /* The test for LOCAL must come before the test for FREE in order to
  1116. handle classes where name is both local and free. The local var is
  1117. a method and the free var is a free var referenced within a method.
  1118. */
  1119. static int
  1120. get_ref_type(struct compiler *c, PyObject *name)
  1121. {
  1122. int scope = PyST_GetScope(c->u->u_ste, name);
  1123. if (scope == 0) {
  1124. char buf[350];
  1125. PyOS_snprintf(buf, sizeof(buf),
  1126. "unknown scope for %.100s in %.100s(%s) in %s\n"
  1127. "symbols: %s\nlocals: %s\nglobals: %s\n",
  1128. PyString_AS_STRING(name),
  1129. PyString_AS_STRING(c->u->u_name),
  1130. PyObject_REPR(c->u->u_ste->ste_id),
  1131. c->c_filename,
  1132. PyObject_REPR(c->u->u_ste->ste_symbols),
  1133. PyObject_REPR(c->u->u_varnames),
  1134. PyObject_REPR(c->u->u_names)
  1135. );
  1136. Py_FatalError(buf);
  1137. }
  1138. return scope;
  1139. }
  1140. static int
  1141. compiler_lookup_arg(PyObject *dict, PyObject *name)
  1142. {
  1143. PyObject *k, *v;
  1144. k = PyTuple_Pack(2, name, name->ob_type);
  1145. if (k == NULL)
  1146. return -1;
  1147. v = PyDict_GetItem(dict, k);
  1148. Py_DECREF(k);
  1149. if (v == NULL)
  1150. return -1;
  1151. return PyInt_AS_LONG(v);
  1152. }
  1153. static int
  1154. compiler_make_closure(struct compiler *c, PyCodeObject *co, asdl_seq *defaults)
  1155. {
  1156. int i, free = PyCode_GetNumFree(co), ndefaults = 0;
  1157. if (free == 0) {
  1158. if (!compiler_load_global(c, "#@make_function"))
  1159. return 0;
  1160. ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
  1161. if (defaults)
  1162. VISIT_SEQ(c, expr, defaults);
  1163. ADDOP_I(c, CALL_FUNCTION, asdl_seq_LEN(defaults) + 1);
  1164. return 1;
  1165. }
  1166. if (defaults) {
  1167. ndefaults = asdl_seq_LEN(defaults);
  1168. VISIT_SEQ(c, expr, defaults);
  1169. }
  1170. for (i = 0; i < free; ++i) {
  1171. /* Bypass com_addop_varname because it will generate
  1172. LOAD_DEREF but LOAD_CLOSURE is needed.
  1173. */
  1174. PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
  1175. int arg, reftype;
  1176. /* Special case: If a class contains a method with a
  1177. free variable that has the same name as a method,
  1178. the name will be considered free *and* local in the
  1179. class. It should be handled by the closure, as
  1180. well as by the normal name loookup logic.
  1181. */
  1182. reftype = get_ref_type(c, name);
  1183. if (reftype == CELL)
  1184. arg = compiler_lookup_arg(c->u->u_cellvars, name);
  1185. else /* (reftype == FREE) */
  1186. arg = compiler_lookup_arg(c->u->u_freevars, name);
  1187. if (arg == -1) {
  1188. printf("lookup %s in %s %d %d\n"
  1189. "freevars of %s: %s\n",
  1190. PyObject_REPR(name),
  1191. PyString_AS_STRING(c->u->u_name),
  1192. reftype, arg,
  1193. PyString_AS_STRING(co->co_name),
  1194. PyObject_REPR(co->co_freevars));
  1195. Py_FatalError("compiler_make_closure()");
  1196. }
  1197. ADDOP_I(c, LOAD_CLOSURE, arg);
  1198. }
  1199. ADDOP_I(c, BUILD_TUPLE, free);
  1200. ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
  1201. ADDOP_I(c, MAKE_CLOSURE, ndefaults);
  1202. return 1;
  1203. }
  1204. static int
  1205. compiler_decorators(struct compiler *c, asdl_seq* decos)
  1206. {
  1207. int i;
  1208. if (!decos)
  1209. return 1;
  1210. for (i = 0; i < asdl_seq_LEN(decos); i++) {
  1211. VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
  1212. }
  1213. return 1;
  1214. }
  1215. static int
  1216. compiler_arguments(struct compiler *c, arguments_ty args)
  1217. {
  1218. int i;
  1219. int n = asdl_seq_LEN(args->args);
  1220. /* Correctly handle nested argument lists */
  1221. for (i = 0; i < n; i++) {
  1222. expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
  1223. if (arg->kind == Tuple_kind) {
  1224. PyObject *id = PyString_FromFormat(".%d", i);
  1225. if (id == NULL) {
  1226. return 0;
  1227. }
  1228. if (!compiler_nameop(c, id, Load)) {
  1229. Py_DECREF(id);
  1230. return 0;
  1231. }
  1232. Py_DECREF(id);
  1233. VISIT(c, expr, arg);
  1234. }
  1235. }
  1236. return 1;
  1237. }
  1238. static int
  1239. compiler_function(struct compiler *c, stmt_ty s)
  1240. {
  1241. PyCodeObject *co;
  1242. PyObject *first_const = Py_None;
  1243. arguments_ty args = s->v.FunctionDef.args;
  1244. asdl_seq* decos = s->v.FunctionDef.decorator_list;
  1245. stmt_ty st;
  1246. int i, n, docstring;
  1247. assert(s->kind == FunctionDef_kind);
  1248. if (!compiler_decorators(c, decos))
  1249. return 0;
  1250. if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
  1251. s->lineno))
  1252. return 0;
  1253. st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
  1254. docstring = compiler_isdocstring(st);
  1255. if (docstring && Py_OptimizeFlag < 2)
  1256. first_const = st->v.Expr.value->v.Str.s;
  1257. if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
  1258. compiler_exit_scope(c);
  1259. return 0;
  1260. }
  1261. /* unpack nested arguments */
  1262. compiler_arguments(c, args);
  1263. c->u->u_argcount = asdl_seq_LEN(args->args);
  1264. n = asdl_seq_LEN(s->v.FunctionDef.body);
  1265. /* if there was a docstring, we need to skip the first statement */
  1266. for (i = docstring; i < n; i++) {
  1267. st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
  1268. VISIT_IN_SCOPE(c, stmt, st);
  1269. }
  1270. co = assemble(c, 1);
  1271. compiler_exit_scope(c);
  1272. if (co == NULL)
  1273. return 0;
  1274. compiler_make_closure(c, co, args->defaults);
  1275. Py_DECREF(co);
  1276. for (i = 0; i < asdl_seq_LEN(decos); i++) {
  1277. ADDOP_I(c, CALL_FUNCTION, 1);
  1278. }
  1279. return compiler_nameop(c, s->v.FunctionDef.name, Store);
  1280. }
  1281. static int
  1282. compiler_class(struct compiler *c, stmt_ty s)
  1283. {
  1284. int n, i;
  1285. PyCodeObject *co;
  1286. PyObject *str;
  1287. asdl_seq* decos = s->v.ClassDef.decorator_list;
  1288. if (!compiler_decorators(c, decos))
  1289. return 0;
  1290. if (!compiler_load_global(c, "#@buildclass"))
  1291. return 0;
  1292. /* push class name on stack, needed by #@buildclass */
  1293. ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
  1294. /* push the tuple of base classes on the stack */
  1295. n = asdl_seq_LEN(s->v.ClassDef.bases);
  1296. if (n > 0)
  1297. VISIT_SEQ(c, expr, s->v.ClassDef.bases);
  1298. ADDOP_I(c, BUILD_TUPLE, n);
  1299. if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
  1300. s->lineno))
  1301. return 0;
  1302. Py_XDECREF(c->u->u_private);
  1303. c->u->u_private = s->v.ClassDef.name;
  1304. Py_INCREF(c->u->u_private);
  1305. str = PyString_InternFromString("__name__");
  1306. if (!str || !compiler_nameop(c, str, Load)) {
  1307. Py_XDECREF(str);
  1308. compiler_exit_scope(c);
  1309. return 0;
  1310. }
  1311. Py_DECREF(str);
  1312. str = PyString_InternFromString("__module__");
  1313. if (!str || !compiler_nameop(c, str, Store)) {
  1314. Py_XDECREF(str);
  1315. compiler_exit_scope(c);
  1316. return 0;
  1317. }
  1318. Py_DECREF(str);
  1319. if (!compiler_body(c, s->v.ClassDef.body)) {
  1320. compiler_exit_scope(c);
  1321. return 0;
  1322. }
  1323. if (!compiler_load_global(c, "#@locals"))
  1324. return 0;
  1325. ADDOP_I(c, CALL_FUNCTION, 0);
  1326. ADDOP_IN_SCOPE(c, RETURN_VALUE);
  1327. co = assemble(c, 1);
  1328. compiler_exit_scope(c);
  1329. if (co == NULL)
  1330. return 0;
  1331. compiler_make_closure(c, co, NULL);
  1332. Py_DECREF(co);
  1333. ADDOP_I(c, CALL_FUNCTION, 0);
  1334. /* Call #@buildclass */
  1335. ADDOP_I(c, CALL_FUNCTION, 3);
  1336. /* apply decorators */
  1337. for (i = 0; i < asdl_seq_LEN(decos); i++) {
  1338. ADDOP_I(c, CALL_FUNCTION, 1);
  1339. }
  1340. if (!compiler_nameop(c, s->v.ClassDef.name, Store))
  1341. return 0;
  1342. return 1;
  1343. }
  1344. static int
  1345. compiler_exec(struct compiler *c, stmt_ty s)
  1346. {
  1347. if (!compiler_load_global(c, "#@exec"))
  1348. return 0;
  1349. VISIT(c, expr, s->v.Exec.body);
  1350. if (s->v.Exec.globals) {
  1351. VISIT(c, expr, s->v.Exec.globals);
  1352. if (s->v.Exec.locals) {
  1353. VISIT(c, expr, s->v.Exec.locals);
  1354. } else {
  1355. ADDOP(c, DUP_TOP);
  1356. }
  1357. } else {
  1358. ADDOP_O(c, LOAD_CONST, Py_None, consts);
  1359. ADDOP(c, DUP_TOP);
  1360. }
  1361. ADDOP_I(c, CALL_FUNCTION, 3);
  1362. ADDOP(c, POP_TOP);
  1363. c->u->u_uses_exec = true;
  1364. return 1;
  1365. }
  1366. static int
  1367. compiler_ifexp(struct compiler *c, expr_ty e)
  1368. {
  1369. basicblock *end, *next;
  1370. assert(e->kind == IfExp_kind);
  1371. end = compiler_new_block(c);
  1372. if (end == NULL)
  1373. return 0;
  1374. next = compiler_new_block(c);
  1375. if (next == NULL)
  1376. return 0;
  1377. VISIT(c, expr, e->v.IfExp.test);
  1378. ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
  1379. VISIT(c, expr, e->v.IfExp.body);
  1380. ADDOP_JREL(c, JUMP_FORWARD, end);
  1381. compiler_use_next_block(c, next);
  1382. VISIT(c, expr, e->v.IfExp.orelse);
  1383. compiler_use_next_block(c, end);
  1384. return 1;
  1385. }
  1386. static int
  1387. compiler_lambda(struct compiler *c, expr_ty e)
  1388. {
  1389. PyCodeObject *co;
  1390. static identifier name;
  1391. arguments_ty args = e->v.Lambda.args;
  1392. assert(e->kind == Lambda_kind);
  1393. if (!name) {
  1394. name = PyString_InternFromString("<lambda>");
  1395. if (!name)
  1396. return 0;
  1397. }
  1398. if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
  1399. return 0;
  1400. /* unpack nested arguments */
  1401. compiler_arguments(c, args);
  1402. c->u->u_argcount = asdl_seq_LEN(args->args);
  1403. VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
  1404. ADDOP_IN_SCOPE(c, RETURN_VALUE);
  1405. co = assemble(c, 1);
  1406. compiler_exit_scope(c);
  1407. if (co == NULL)
  1408. return 0;
  1409. compiler_make_closure(c, co, args->defaults);
  1410. Py_DECREF(co);
  1411. return 1;
  1412. }
  1413. static int
  1414. compiler_print(struct compiler *c, stmt_ty s)
  1415. {
  1416. int i, n, kwargs = 0;
  1417. PyObject *str;
  1418. assert(s->kind == Print_kind);
  1419. n = asdl_seq_LEN(s->v.Print.values);
  1420. if (!compiler_load_global(c, "#@print_stmt"))
  1421. return 0;
  1422. for (i = 0; i < n; i++) {
  1423. expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
  1424. VISIT(c, expr, e);
  1425. }
  1426. if (!s->v.Print.nl) {
  1427. str = PyString_InternFromString("end");
  1428. if (!str)
  1429. return 0;
  1430. ADDOP_O(c, LOAD_CONST, str, consts);
  1431. Py_DECREF(str);
  1432. str = PyString_FromString("");
  1433. if (!str)
  1434. return 0;
  1435. ADDOP_O(c, LOAD_CONST, str, consts);
  1436. Py_DECREF(str);
  1437. kwargs++;
  1438. }
  1439. if (s->v.Print.dest) {
  1440. str = PyString_InternFromString("file");
  1441. if (!str)
  1442. return 0;
  1443. ADDOP_O(c, LOAD_CONST, str, consts);
  1444. Py_DECREF(str);
  1445. VISIT(c, expr, s->v.Print.dest);
  1446. kwargs++;
  1447. }
  1448. ADDOP_I(c, CALL_FUNCTION, n | (kwargs << 8));
  1449. ADDOP(c, POP_TOP);
  1450. return 1;
  1451. }
  1452. static int
  1453. compiler_if(struct compiler *c, stmt_ty s)
  1454. {
  1455. basicblock *end, *next;
  1456. int constant;
  1457. assert(s->kind == If_kind);
  1458. end = compiler_new_block(c);
  1459. if (end == NULL)
  1460. return 0;
  1461. constant = expr_constant(s->v.If.test);
  1462. /* constant = 0: "if 0"
  1463. * constant = 1: "if 1", "if 2", ...
  1464. * constant = -1: rest */
  1465. if (constant == 0) {
  1466. if (s->v.If.orelse)
  1467. VISIT_SEQ(c, stmt, s->v.If.orelse);
  1468. } else if (constant == 1) {
  1469. VISIT_SEQ(c, stmt, s->v.If.body);
  1470. } else {
  1471. if (s->v.If.orelse) {
  1472. next = compiler_new_block(c);
  1473. if (next == NULL)
  1474. return 0;
  1475. }
  1476. else
  1477. next = end;
  1478. VISIT(c, expr, s->v.If.test);
  1479. ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
  1480. VISIT_SEQ(c, stmt, s->v.If.body);
  1481. ADDOP_JREL(c, JUMP_FORWARD, end);
  1482. if (s->v.If.orelse) {
  1483. compiler_use_next_block(c, next);
  1484. VISIT_SEQ(c, stmt, s->v.If.orelse);
  1485. }
  1486. }
  1487. compiler_use_next_block(c, end);
  1488. return 1;
  1489. }
  1490. static int
  1491. compiler_for(struct compiler *c, stmt_ty s)
  1492. {
  1493. basicblock *start, *cleanup, *end;
  1494. start = compiler_new_block(c);
  1495. cleanup = compiler_new_block(c);
  1496. end = compiler_new_block(c);
  1497. if (start == NULL || end == NULL || cleanup == NULL)
  1498. return 0;
  1499. if (c->u->u_ste->ste_blockstack)
  1500. ADDOP_JREL(c, SETUP_LOOP, end);
  1501. if (!compiler_push_fblock(c, FOR_LOOP, start, end))
  1502. return 0;
  1503. VISIT(c, expr, s->v.For.iter);
  1504. ADDOP(c, GET_ITER);
  1505. compiler_use_next_block(c, start);
  1506. ADDOP_JREL(c, FOR_ITER, cleanup);
  1507. VISIT(c, expr, s->v.For.target);
  1508. VISIT_SEQ(c, stmt, s->v.For.body);
  1509. ADDOP_JABS(c, JUMP_ABSOLUTE, start);
  1510. compiler_use_next_block(c, cleanup);
  1511. if (c->u->u_ste->ste_blockstack)
  1512. ADDOP(c, POP_BLOCK);
  1513. compiler_pop_fblock(c, FOR_LOOP, start, end);
  1514. VISIT_SEQ(c, stmt, s->v.For.orelse);
  1515. compiler_use_next_block(c, end);
  1516. return 1;
  1517. }
  1518. static int
  1519. compiler_while(struct compiler *c, stmt_ty s)
  1520. {
  1521. basicblock *loop, *orelse, *end, *anchor = NULL;
  1522. int constant = expr_constant(s->v.While.test);
  1523. if (constant == 0) {
  1524. if (s->v.While.orelse)
  1525. VISIT_SEQ(c, stmt, s->v.While.orelse);
  1526. return 1;
  1527. }
  1528. loop = compiler_new_block(c);
  1529. end = compiler_new_block(c);
  1530. if (constant == -1) {
  1531. anchor = compiler_new_block(c);
  1532. if (anchor == NULL)
  1533. return 0;
  1534. }
  1535. if (loop == NULL || end == NULL)
  1536. return 0;
  1537. if (s->v.While.orelse) {
  1538. orelse = compiler_new_block(c);
  1539. if (orelse == NULL)
  1540. return 0;
  1541. }
  1542. else
  1543. orelse = NULL;
  1544. if (c->u->u_ste->ste_blockstack)
  1545. ADDOP_JREL(c, SETUP_LOOP, end);
  1546. compiler_use_next_block(c, loop);
  1547. if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
  1548. return 0;
  1549. if (constant == -1) {
  1550. VISIT(c, expr, s->v.While.test);
  1551. ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
  1552. }
  1553. VISIT_SEQ(c, stmt, s->v.While.body);
  1554. ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
  1555. /* XXX should the two POP instructions be in a separate block
  1556. if there is no else clause ?
  1557. */
  1558. if (constant == -1) {
  1559. compiler_use_next_block(c, anchor);
  1560. if (c->u->u_ste->ste_blockstack)
  1561. ADDOP(c, POP_BLOCK);
  1562. }
  1563. compiler_pop_fblock(c, WHILE_LOOP, loop, end);
  1564. if (orelse != NULL) { /* what if orelse is just pass? */
  1565. compiler_use_next_block(c, orelse);
  1566. VISIT_SEQ(c, stmt, s->v.While.orelse);
  1567. }
  1568. compiler_use_next_block(c, end);
  1569. return 1;
  1570. }
  1571. static int
  1572. compiler_break(struct compiler *c)
  1573. {
  1574. if (!compiler_in_loop(c))
  1575. return compiler_error(c, "'break' outside loop");
  1576. if (c->u->u_ste->ste_blockstack) {
  1577. ADDOP(c, BREAK_LOOP);
  1578. } else {
  1579. int top = c->u->u_nfblocks - 1;
  1580. assert(c->u->u_fblock[top].fb_target);
  1581. if (c->u->u_fblock[top].fb_type == FOR_LOOP) {
  1582. ADDOP(c, POP_TOP);
  1583. } else {
  1584. assert(c->u->u_fblock[top].fb_type == WHILE_LOOP);
  1585. }
  1586. ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[top].fb_target);
  1587. }
  1588. return 1;
  1589. }
  1590. static int
  1591. compiler_continue(struct compiler *c)
  1592. {
  1593. static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
  1594. static const char IN_FINALLY_ERROR_MSG[] =
  1595. "'continue' not supported inside 'finally' clause";
  1596. int i;
  1597. if (!c->u->u_nfblocks)
  1598. return compiler_error(c, LOOP_ERROR_MSG);
  1599. i = c->u->u_nfblocks - 1;
  1600. switch (c->u->u_fblock[i].fb_type) {
  1601. case FOR_LOOP:
  1602. case WHILE_LOOP:
  1603. ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
  1604. break;
  1605. case EXCEPT:
  1606. case FINALLY_TRY:
  1607. while (--i >= 0 && !(c->u->u_fblock[i].fb_type == FOR_LOOP ||
  1608. c->u->u_fblock[i].fb_type == WHILE_LOOP)) {
  1609. /* Prevent continue anywhere under a finally
  1610. even if hidden in a sub-try or except. */
  1611. if (c->u->u_fblock[i].fb_type == FINALLY_END)
  1612. return compiler_error(c, IN_FINALLY_ERROR_MSG);
  1613. }
  1614. if (i == -1)
  1615. return compiler_error(c, LOOP_ERROR_MSG);
  1616. ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
  1617. break;
  1618. case FINALLY_END:
  1619. return compiler_error(c, IN_FINALLY_ERROR_MSG);
  1620. }
  1621. return 1;
  1622. }
  1623. /* Code generated for "try: <body> finally: <finalbody>" is as follows:
  1624. SETUP_FINALLY L
  1625. <code for body>
  1626. POP_BLOCK
  1627. LOAD_CONST <None>
  1628. L: <code for finalbody>
  1629. END_FINALLY
  1630. The special instructions use the block stack. Each block
  1631. stack entry contains the instruction that created it (here
  1632. SETUP_FINALLY), the level of the value stack at the time the
  1633. block stack entry was created, and a label (here L).
  1634. SETUP_FINALLY:
  1635. Pushes the current value stack level and the label
  1636. onto the block stack.
  1637. POP_BLOCK:
  1638. Pops en entry from the block stack, and pops the value
  1639. stack until its level is the same as indicated on the
  1640. block stack. (The label is ignored.)
  1641. END_FINALLY:
  1642. Pops a variable number of entries from the *value* stack
  1643. and re-raises the exception they specify. The number of
  1644. entries popped depends on the (pseudo) exception type.
  1645. The block stack is unwound when an exception is raised:
  1646. when a SETUP_FINALLY entry is found, the exception is pushed
  1647. onto the value stack (and the exception condition is cleared),
  1648. and the interpreter jumps to the label gotten from the block
  1649. stack.
  1650. */
  1651. static int
  1652. compiler_try_finally(struct compiler *c, stmt_ty s)
  1653. {
  1654. basicblock *body, *end;
  1655. body = compiler_new_block(c);
  1656. end = compiler_new_block(c);
  1657. if (body == NULL || end == NULL)
  1658. return 0;
  1659. ADDOP_JREL(c, SETUP_FINALLY, end);
  1660. compiler_use_next_block(c, body);
  1661. if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
  1662. return 0;
  1663. VISIT_SEQ(c, stmt, s->v.TryFinally.body);
  1664. ADDOP(c, POP_BLOCK);
  1665. compiler_pop_fblock(c, FINALLY_TRY, body, end);
  1666. ADDOP_O(c, LOAD_CONST, Py_None, consts);
  1667. ADDOP(c, DUP_TOP);
  1668. ADDOP(c, DUP_TOP);
  1669. compiler_use_next_block(c, end);
  1670. if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
  1671. return 0;
  1672. VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
  1673. ADDOP(c, END_FINALLY);
  1674. compiler_pop_fblock(c, FINALLY_END, end, NULL);
  1675. return 1;
  1676. }
  1677. /*
  1678. Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
  1679. (The contents of the value stack is shown in [], with the top
  1680. at the right; 'tb' is trace-back info, 'val' the exception's
  1681. associated value, and 'exc' the exception.)
  1682. Value stack Label Instruction Argument
  1683. [] SETUP_EXCEPT L1
  1684. [] <code for S>
  1685. [] POP_BLOCK
  1686. [] JUMP_FORWARD L0
  1687. [tb, val, exc] L1: DUP )
  1688. [tb, val, exc, exc] <evaluate E1> )
  1689. [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
  1690. [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
  1691. [tb, val, exc] POP
  1692. [tb, val] <assign to V1> (or POP if no V1)
  1693. [tb] POP
  1694. [] <code for S1>
  1695. JUMP_FORWARD L0
  1696. [tb, val, exc] L2: DUP
  1697. .............................etc.......................
  1698. [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
  1699. [] L0: <next statement>
  1700. Of course, parts are not generated if Vi or Ei is not present.
  1701. */
  1702. static int
  1703. compiler_try_except(struct compiler *c, stmt_ty s)
  1704. {
  1705. basicblock *body, *orelse, *except, *end;
  1706. int i, n;
  1707. body = compiler_new_block(c);
  1708. except = compiler_new_block(c);
  1709. orelse = compiler_new_block(c);
  1710. end = compiler_new_block(c);
  1711. if (body == NULL || except == NULL || orelse == NULL || end == NULL)
  1712. return 0;
  1713. ADDOP_JREL(c, SETUP_EXCEPT, except);
  1714. compiler_use_next_block(c, body);
  1715. if (!compiler_push_fblock(c, EXCEPT, body, except))
  1716. return 0;
  1717. VISIT_SEQ(c, stmt, s->v.TryExcept.body);
  1718. ADDOP(c, POP_BLOCK);
  1719. compiler_pop_fblock(c, EXCEPT, body, except);
  1720. ADDOP_JREL(c, JUMP_FORWARD, orelse);
  1721. n = asdl_seq_LEN(s->v.TryExcept.handlers);
  1722. compiler_use_next_block(c, except);
  1723. for (i = 0; i < n; i++) {
  1724. excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
  1725. s->v.TryExcept.handlers, i);
  1726. if (!handler->v.ExceptHandler.type && i < n-1)
  1727. return compiler_error(c, "default 'except:' must be last");
  1728. c->u->u_lineno_set = false;
  1729. c->u->u_lineno = handler->lineno;
  1730. except = compiler_new_block(c);
  1731. if (except == NULL)
  1732. return 0;
  1733. if (handler->v.ExceptHandler.type) {
  1734. ADDOP(c, DUP_TOP);
  1735. VISIT(c, expr, handler->v.ExceptHandler.type);
  1736. ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
  1737. ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
  1738. }
  1739. ADDOP(c, POP_TOP);
  1740. if (handler->v.ExceptHandler.name) {
  1741. VISIT(c, expr, handler->v.ExceptHandler.name);
  1742. }
  1743. else {
  1744. ADDOP(c, POP_TOP);
  1745. }
  1746. ADDOP(c, POP_TOP);
  1747. VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
  1748. ADDOP_JREL(c, JUMP_FORWARD, end);
  1749. compiler_use_next_block(c, except);
  1750. }
  1751. ADDOP(c, END_FINALLY);
  1752. compiler_use_next_block(c, orelse);
  1753. VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
  1754. compiler_use_next_block(c, end);
  1755. return 1;
  1756. }
  1757. static int
  1758. compiler_import_as(struct compiler *c, identifier name, identifier asname)
  1759. {
  1760. /* The IMPORT_NAME opcode was already generated. This function
  1761. merely needs to bind the result to a name.
  1762. If there is a dot in name, we need to split it and emit a
  1763. LOAD_ATTR for each name.
  1764. */
  1765. const char *src = PyString_AS_STRING(name);
  1766. const char *dot = strchr(src, '.');
  1767. if (dot) {
  1768. /* Consume the base module name to get the first attribute */
  1769. src = dot + 1;
  1770. while (dot) {
  1771. /* NB src is only defined when dot != NULL */
  1772. PyObject *attr;
  1773. dot = strchr(src, '.');
  1774. attr = PyString_FromStringAndSize(src,
  1775. dot ? dot - src : strlen(src));
  1776. if (!attr)
  1777. return -1;
  1778. ADDOP_O(c, LOAD_ATTR, attr, names);
  1779. Py_DECREF(attr);
  1780. src = dot + 1;
  1781. }
  1782. }
  1783. return compiler_nameop(c, asname, Store);
  1784. }
  1785. static int
  1786. compiler_import(struct compiler *c, stmt_ty s)
  1787. {
  1788. /* The Import node stores a module name like a.b.c as a single
  1789. string. This is convenient for all cases except
  1790. import a.b.c as d
  1791. where we need to parse that string to extract the individual
  1792. module names.
  1793. XXX Perhaps change the representation to make this case simpler?
  1794. */
  1795. int i, n = asdl_seq_LEN(s->v.Import.names);
  1796. for (i = 0; i < n; i++) {
  1797. alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
  1798. int r;
  1799. PyObject *level;
  1800. if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
  1801. level = PyInt_FromLong(0);
  1802. else
  1803. level = PyInt_FromLong(-1);
  1804. if (level == NULL)
  1805. return 0;
  1806. ADDOP_O(c, LOAD_CONST, level, consts);
  1807. Py_DECREF(level);
  1808. ADDOP_O(c, LOAD_CONST, Py_None, consts);
  1809. ADDOP_O(c, LOAD_CONST, alias->name, consts);
  1810. ADDOP(c, IMPORT_NAME);
  1811. if (alias->asname) {
  1812. r = compiler_import_as(c, alias->name, alias->asname);
  1813. if (!r)
  1814. return r;
  1815. }
  1816. else {
  1817. identifier tmp = alias->name;
  1818. const char *base = PyString_AS_STRING(alias->name);
  1819. const char *dot = strchr(base, '.');
  1820. if (dot)
  1821. tmp = PyString_FromStringAndSize(base,
  1822. dot - base);
  1823. r = compiler_nameop(c, tmp, Store);
  1824. if (dot) {
  1825. Py_DECREF(tmp);
  1826. }
  1827. if (!r)
  1828. return r;
  1829. }
  1830. }
  1831. return 1;
  1832. }
  1833. static int
  1834. compiler_from_import(struct compiler *c, stmt_ty s)
  1835. {
  1836. int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
  1837. PyObject *names = PyTuple_New(n);
  1838. PyObject *level;
  1839. alias_ty alias;
  1840. if (!names)
  1841. return 0;
  1842. if (s->v.ImportFrom.level == 0 && c->c_flags &&
  1843. !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
  1844. level = PyInt_FromLong(-1);
  1845. else
  1846. level = PyInt_FromLong(s->v.ImportFrom.level);
  1847. if (!level) {
  1848. Py_DECREF(names);
  1849. return 0;
  1850. }
  1851. /* build up the names */
  1852. for (i = 0; i < n; i++) {
  1853. alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
  1854. Py_INCREF(alias->name);
  1855. PyTuple_SET_ITEM(names, i, alias->name);
  1856. }
  1857. if (s->lineno > c->c_future->ff_lineno) {
  1858. if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
  1859. "__future__")) {
  1860. Py_DECREF(level);
  1861. Py_DECREF(names);
  1862. return compiler_error(c,
  1863. "from __future__ imports must occur "
  1864. "at the beginning of the file");
  1865. }
  1866. }
  1867. /* Handle 'from x import *' */
  1868. alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, 0);
  1869. if (PyString_AS_STRING(alias->name)[0] == '*') {
  1870. assert(n == 1);
  1871. if (!compiler_load_global(c, "#@import_star"))
  1872. return 0;
  1873. ADDOP_O(c, LOAD_CONST, level, consts);
  1874. Py_DECREF(level);
  1875. ADDOP_O(c, LOAD_CONST, names, consts);
  1876. Py_DECREF(names);
  1877. ADDOP_O(c, LOAD_CONST, s->v.ImportFrom.module, consts);
  1878. ADDOP(c, IMPORT_NAME);
  1879. ADDOP_I(c, CALL_FUNCTION, 1);
  1880. ADDOP(c, POP_TOP);
  1881. return 1;
  1882. }
  1883. /* Handle all other imports. */
  1884. if (!compiler_load_global(c, "#@import_from"))
  1885. return 0;
  1886. ADDOP_O(c, LOAD_CONST, level, consts);
  1887. Py_DECREF(level);
  1888. ADDOP_O(c, LOAD_CONST, names, consts);
  1889. Py_DECREF(names);
  1890. ADDOP_O(c, LOAD_CONST, s->v.ImportFrom.module, consts);
  1891. ADDOP(c, IMPORT_NAME);
  1892. for (i = 0; i < n; i++) {
  1893. identifier store_name;
  1894. alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
  1895. /* The DUP_TOP_TWO ends up duplicating [#@import_from, module],
  1896. where module is the return value from IMPORT_NAME. */
  1897. ADDOP(c, DUP_TOP_TWO);
  1898. ADDOP_O(c, LOAD_CONST, alias->name, consts);
  1899. ADDOP_I(c, CALL_FUNCTION, 2);
  1900. store_name = alias->name;
  1901. if (alias->asname)
  1902. store_name = alias->asname;
  1903. if (!compiler_nameop(c, store_name, Store)) {
  1904. Py_DECREF(names);
  1905. return 0;
  1906. }
  1907. }
  1908. ADDOP(c, POP_TOP); /* remove imported module */
  1909. ADDOP(c, POP_TOP); /* remove #@import_from function */
  1910. return 1;
  1911. }
  1912. static int
  1913. compiler_assert(struct compiler *c, stmt_ty s)
  1914. {
  1915. static PyObject *assertion_error = NULL;
  1916. basicblock *end;
  1917. if (Py_OptimizeFlag)
  1918. return 1;
  1919. if (assertion_error == NULL) {
  1920. assertion_error = PyString_InternFromString("AssertionError");
  1921. if (assertion_error == NULL)
  1922. return 0;
  1923. }
  1924. if (s->v.Assert.test->kind == Tuple_kind &&
  1925. asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
  1926. const char* msg =
  1927. "assertion is always true, perhaps remove parentheses?";
  1928. if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
  1929. c->u->u_lineno, NULL, NULL) == -1)
  1930. return 0;
  1931. }
  1932. VISIT(c, expr, s->v.Assert.test);
  1933. end = compiler_new_block(c);
  1934. if (end == NULL)
  1935. return 0;
  1936. ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
  1937. ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
  1938. if (s->v.Assert.msg) {
  1939. VISIT(c, expr, s->v.Assert.msg);
  1940. ADDOP(c, RAISE_VARARGS_TWO);
  1941. }
  1942. else {
  1943. ADDOP(c, RAISE_VARARGS_ONE);
  1944. }
  1945. compiler_use_next_block(c, end);
  1946. return 1;
  1947. }
  1948. static int
  1949. compiler_visit_stmt(struct compiler *c, stmt_ty s)
  1950. {
  1951. int i, n;
  1952. const int raise_varargs[] = { RAISE_VARARGS_ZERO, RAISE_VARARGS_ONE,
  1953. RAISE_VARARGS_TWO, RAISE_VARARGS_THREE };
  1954. /* Always assign a lineno to the next instruction for a stmt. */
  1955. c->u->u_lineno = s->lineno;
  1956. c->u->u_lineno_set = false;
  1957. switch (s->kind) {
  1958. case FunctionDef_kind:
  1959. return compiler_function(c, s);
  1960. case ClassDef_kind:
  1961. return compiler_class(c, s);
  1962. case Return_kind:
  1963. if (c->u->u_ste->ste_type != FunctionBlock)
  1964. return compiler_error(c, "'return' outside function");
  1965. if (s->v.Return.value) {
  1966. VISIT(c, expr, s->v.Return.value);
  1967. }
  1968. else
  1969. ADDOP_O(c, LOAD_CONST, Py_None, consts);
  1970. ADDOP(c, RETURN_VALUE);
  1971. break;
  1972. case Delete_kind:
  1973. VISIT_SEQ(c, expr, s->v.Delete.targets)
  1974. break;
  1975. case Assign_kind:
  1976. n = asdl_seq_LEN(s->v.Assign.targets);
  1977. VISIT(c, expr, s->v.Assign.value);
  1978. for (i = 0; i < n; i++) {
  1979. if (i < n - 1)
  1980. ADDOP(c, DUP_TOP);
  1981. VISIT(c, expr,
  1982. (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
  1983. }
  1984. break;
  1985. case AugAssign_kind:
  1986. return compiler_augassign(c, s);
  1987. case Print_kind:
  1988. return compiler_print(c, s);
  1989. case For_kind:
  1990. return compiler_for(c, s);
  1991. case While_kind:
  1992. return compiler_while(c, s);
  1993. case If_kind:
  1994. return compiler_if(c, s);
  1995. case Raise_kind:
  1996. n = 0;
  1997. if (s->v.Raise.type) {
  1998. VISIT(c, expr, s->v.Raise.type);
  1999. n++;
  2000. if (s->v.Raise.inst) {
  2001. VISIT(c, expr, s->v.Raise.inst);
  2002. n++;
  2003. if (s->v.Raise.tback) {
  2004. VISIT(c, expr, s->v.Raise.tback);
  2005. n++;
  2006. }
  2007. }
  2008. }
  2009. ADDOP(c, raise_varargs[n]);
  2010. break;
  2011. case TryExcept_kind:
  2012. return compiler_try_except(c, s);
  2013. case TryFinally_kind:
  2014. return compiler_try_finally(c, s);
  2015. case Assert_kind:
  2016. return compiler_assert(c, s);
  2017. case Import_kind:
  2018. return compiler_import(c, s);
  2019. case ImportFrom_kind:
  2020. return compiler_from_import(c, s);
  2021. case Exec_kind:
  2022. return compiler_exec(c, s);
  2023. case Global_kind:
  2024. break;
  2025. case Expr_kind:
  2026. if (c->c_interactive && c->c_nestlevel <= 1) {
  2027. if (!compiler_load_global(c, "#@displayhook"))
  2028. return 0;
  2029. VISIT(c, expr, s->v.Expr.value);
  2030. ADDOP_I(c, CALL_FUNCTION, 1);
  2031. ADDOP(c, POP_TOP);
  2032. }
  2033. else if (s->v.Expr.value->kind != Str_kind &&
  2034. s->v.Expr.value->kind != Num_kind) {
  2035. VISIT(c, expr, s->v.Expr.value);
  2036. ADDOP(c, POP_TOP);
  2037. }
  2038. break;
  2039. case Pass_kind:
  2040. break;
  2041. case Break_kind:
  2042. return compiler_break(c);
  2043. case Continue_kind:
  2044. return compiler_continue(c);
  2045. case With_kind:
  2046. return compiler_with(c, s);
  2047. }
  2048. return 1;
  2049. }
  2050. static int
  2051. unaryop(unaryop_ty op)
  2052. {
  2053. switch (op) {
  2054. case Invert:
  2055. return UNARY_INVERT;
  2056. case Not:
  2057. return UNARY_NOT;
  2058. case UAdd:
  2059. return UNARY_POSITIVE;
  2060. case USub:
  2061. return UNARY_NEGATIVE;
  2062. default:
  2063. PyErr_Format(PyExc_SystemError,
  2064. "unary op %d should not be possible", op);
  2065. return 0;
  2066. }
  2067. }
  2068. static int
  2069. binop(struct compiler *c, operator_ty op)
  2070. {
  2071. switch (op) {
  2072. case Add:
  2073. return BINARY_ADD;
  2074. case Sub:
  2075. return BINARY_SUBTRACT;
  2076. case Mult:
  2077. return BINARY_MULTIPLY;
  2078. case Div:
  2079. if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
  2080. return BINARY_TRUE_DIVIDE;
  2081. else
  2082. return BINARY_DIVIDE;
  2083. case Mod:
  2084. return BINARY_MODULO;
  2085. case Pow:
  2086. return BINARY_POWER;
  2087. case LShift:
  2088. return BINARY_LSHIFT;
  2089. case RShift:
  2090. return BINARY_RSHIFT;
  2091. case BitOr:
  2092. return BINARY_OR;
  2093. case BitXor:
  2094. return BINARY_XOR;
  2095. case BitAnd:
  2096. return BINARY_AND;
  2097. case FloorDiv:
  2098. return BINARY_FLOOR_DIVIDE;
  2099. default:
  2100. PyErr_Format(PyExc_SystemError,
  2101. "binary op %d should not be possible", op);
  2102. return 0;
  2103. }
  2104. }
  2105. static int
  2106. cmpop(cmpop_ty op)
  2107. {
  2108. switch (op) {
  2109. case Eq:
  2110. return PyCmp_EQ;
  2111. case NotEq:
  2112. return PyCmp_NE;
  2113. case Lt:
  2114. return PyCmp_LT;
  2115. case LtE:
  2116. return PyCmp_LE;
  2117. case Gt:
  2118. return PyCmp_GT;
  2119. case GtE:
  2120. return PyCmp_GE;
  2121. case Is:
  2122. return PyCmp_IS;
  2123. case IsNot:
  2124. return PyCmp_IS_NOT;
  2125. case In:
  2126. return PyCmp_IN;
  2127. case NotIn:
  2128. return PyCmp_NOT_IN;
  2129. default:
  2130. return PyCmp_BAD;
  2131. }
  2132. }
  2133. static int
  2134. inplace_binop(struct compiler *c, operator_ty op)
  2135. {
  2136. switch (op) {
  2137. case Add:
  2138. return INPLACE_ADD;
  2139. case Sub:
  2140. return INPLACE_SUBTRACT;
  2141. case Mult:
  2142. return INPLACE_MULTIPLY;
  2143. case Div:
  2144. if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
  2145. return INPLACE_TRUE_DIVIDE;
  2146. else
  2147. return INPLACE_DIVIDE;
  2148. case Mod:
  2149. return INPLACE_MODULO;
  2150. case Pow:
  2151. return INPLACE_POWER;
  2152. case LShift:
  2153. return INPLACE_LSHIFT;
  2154. case RShift:
  2155. return INPLACE_RSHIFT;
  2156. case BitOr:
  2157. return INPLACE_OR;
  2158. case BitXor:
  2159. return INPLACE_XOR;
  2160. case BitAnd:
  2161. return INPLACE_AND;
  2162. case FloorDiv:
  2163. return INPLACE_FLOOR_DIVIDE;
  2164. default:
  2165. PyErr_Format(PyExc_SystemError,
  2166. "inplace binary op %d should not be possible", op);
  2167. return 0;
  2168. }
  2169. }
  2170. static int
  2171. compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
  2172. {
  2173. int op, scope, arg;
  2174. enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
  2175. PyObject *dict = c->u->u_names;
  2176. PyObject *mangled;
  2177. /* XXX AugStore isn't used anywhere! */
  2178. /* First check for assignment to __debug__. Param? */
  2179. if ((ctx == Store || ctx == AugStore || ctx == Del)
  2180. && !strcmp(PyString_AS_STRING(name), "__debug__")) {
  2181. return compiler_error(c, "can not assign to __debug__");
  2182. }
  2183. mangled = _Py_Mangle(c->u->u_private, name);
  2184. if (!mangled)
  2185. return 0;
  2186. op = 0;
  2187. optype = OP_NAME;
  2188. scope = PyST_GetScope(c->u->u_ste, mangled);
  2189. switch (scope) {
  2190. case FREE:
  2191. dict = c->u->u_freevars;
  2192. optype = OP_DEREF;
  2193. break;
  2194. case CELL:
  2195. dict = c->u->u_cellvars;
  2196. optype = OP_DEREF;
  2197. break;
  2198. case LOCAL:
  2199. if (c->u->u_ste->ste_type == FunctionBlock)
  2200. optype = OP_FAST;
  2201. break;
  2202. case GLOBAL_IMPLICIT:
  2203. if (c->u->u_ste->ste_type == FunctionBlock &&
  2204. !c->u->u_ste->ste_unoptimized)
  2205. optype = OP_GLOBAL;
  2206. break;
  2207. case GLOBAL_EXPLICIT:
  2208. optype = OP_GLOBAL;
  2209. break;
  2210. default:
  2211. /* scope can be 0 */
  2212. break;
  2213. }
  2214. /* XXX Leave assert here, but handle __doc__ and the like better */
  2215. assert(scope || PyString_AS_STRING(name)[0] == '_');
  2216. switch (optype) {
  2217. case OP_DEREF:
  2218. switch (ctx) {
  2219. case Load: op = LOAD_DEREF; break;
  2220. case Store: op = STORE_DEREF; break;
  2221. case AugLoad:
  2222. case AugStore:
  2223. break;
  2224. case Del:
  2225. PyErr_Format(PyExc_SyntaxError,
  2226. "can not delete variable '%s' referenced "
  2227. "in nested scope",
  2228. PyString_AS_STRING(name));
  2229. Py_DECREF(mangled);
  2230. return 0;
  2231. case Param:
  2232. default:
  2233. PyErr_SetString(PyExc_SystemError,
  2234. "param invalid for deref variable");
  2235. return 0;
  2236. }
  2237. break;
  2238. case OP_FAST:
  2239. switch (ctx) {
  2240. case Load: op = LOAD_FAST; break;
  2241. case Store: op = STORE_FAST; break;
  2242. case Del: op = DELETE_FAST; break;
  2243. case AugLoad:
  2244. case AugStore:
  2245. break;
  2246. case Param:
  2247. default:
  2248. PyErr_SetString(PyExc_SystemError,
  2249. "param invalid for local variable");
  2250. return 0;
  2251. }
  2252. ADDOP_O(c, op, mangled, varnames);
  2253. Py_DECREF(mangled);
  2254. return 1;
  2255. case OP_GLOBAL:
  2256. switch (ctx) {
  2257. case Load: op = LOAD_GLOBAL; break;
  2258. case Store: op = STORE_GLOBAL; break;
  2259. case Del: op = DELETE_GLOBAL; break;
  2260. case AugLoad:
  2261. case AugStore:
  2262. break;
  2263. case Param:
  2264. default:
  2265. PyErr_SetString(PyExc_SystemError,
  2266. "param invalid for global variable");
  2267. return 0;
  2268. }
  2269. break;
  2270. case OP_NAME:
  2271. switch (ctx) {
  2272. case Load: op = LOAD_NAME; break;
  2273. case Store: op = STORE_NAME; break;
  2274. case Del: op = DELETE_NAME; break;
  2275. case AugLoad:
  2276. case AugStore:
  2277. break;
  2278. case Param:
  2279. default:
  2280. PyErr_SetString(PyExc_SystemError,
  2281. "param invalid for name variable");
  2282. return 0;
  2283. }
  2284. break;
  2285. }
  2286. assert(op);
  2287. arg = compiler_add_o(c, dict, mangled);
  2288. Py_DECREF(mangled);
  2289. if (arg < 0)
  2290. return 0;
  2291. return compiler_addop_i(c, op, arg);
  2292. }
  2293. static int
  2294. compiler_load_global(struct compiler *c, const char *global_name)
  2295. {
  2296. int arg;
  2297. PyObject *str = PyString_InternFromString(global_name);
  2298. if (!str) {
  2299. compiler_exit_scope(c);
  2300. return 0;
  2301. }
  2302. arg = compiler_add_o(c, c->u->u_names, str);
  2303. Py_DECREF(str);
  2304. if (arg < 0) {
  2305. compiler_exit_scope(c);
  2306. return 0;
  2307. }
  2308. if (!compiler_addop_i(c, LOAD_GLOBAL, arg)) {
  2309. compiler_exit_scope(c);
  2310. return 0;
  2311. }
  2312. return 1;
  2313. }
  2314. static int
  2315. compiler_boolop(struct compiler *c, expr_ty e)
  2316. {
  2317. basicblock *end;
  2318. int i, n;
  2319. asdl_seq *s;
  2320. assert(e->kind == BoolOp_kind);
  2321. end = compiler_new_block(c);
  2322. if (end == NULL)
  2323. return 0;
  2324. s = e->v.BoolOp.values;
  2325. n = asdl_seq_LEN(s) - 1;
  2326. assert(n >= 0);
  2327. for (i = 0; i < n; ++i) {
  2328. VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
  2329. if (e->v.BoolOp.op == And) {
  2330. ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, end);
  2331. }
  2332. else {
  2333. ADDOP_JABS(c, JUMP_IF_TRUE_OR_POP, end);
  2334. }
  2335. }
  2336. VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
  2337. compiler_use_next_block(c, end);
  2338. return 1;
  2339. }
  2340. static int
  2341. compiler_list(struct compiler *c, expr_ty e)
  2342. {
  2343. int n = asdl_seq_LEN(e->v.List.elts);
  2344. if (e->v.List.ctx == Store) {
  2345. ADDOP_I(c, UNPACK_SEQUENCE, n);
  2346. }
  2347. VISIT_SEQ(c, expr, e->v.List.elts);
  2348. if (e->v.List.ctx == Load) {
  2349. ADDOP_I(c, BUILD_LIST, n);
  2350. }
  2351. return 1;
  2352. }
  2353. static int
  2354. compiler_tuple(struct compiler *c, expr_ty e)
  2355. {
  2356. int n = asdl_seq_LEN(e->v.Tuple.elts);
  2357. if (e->v.Tuple.ctx == Store) {
  2358. ADDOP_I(c, UNPACK_SEQUENCE, n);
  2359. }
  2360. VISIT_SEQ(c, expr, e->v.Tuple.elts);
  2361. if (e->v.Tuple.ctx == Load) {
  2362. ADDOP_I(c, BUILD_TUPLE, n);
  2363. }
  2364. return 1;
  2365. }
  2366. static int
  2367. compiler_compare(struct compiler *c, expr_ty e)
  2368. {
  2369. int i, n;
  2370. basicblock *cleanup = NULL;
  2371. /* XXX the logic can be cleaned up for 1 or multiple comparisons */
  2372. VISIT(c, expr, e->v.Compare.left);
  2373. n = asdl_seq_LEN(e->v.Compare.ops);
  2374. assert(n > 0);
  2375. if (n > 1) {
  2376. cleanup = compiler_new_block(c);
  2377. if (cleanup == NULL)
  2378. return 0;
  2379. VISIT(c, expr,
  2380. (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
  2381. }
  2382. for (i = 1; i < n; i++) {
  2383. ADDOP(c, DUP_TOP);
  2384. ADDOP(c, ROT_THREE);
  2385. ADDOP_I(c, COMPARE_OP,
  2386. cmpop((cmpop_ty)(asdl_seq_GET(
  2387. e->v.Compare.ops, i - 1))));
  2388. ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
  2389. NEXT_BLOCK(c);
  2390. if (i < (n - 1))
  2391. VISIT(c, expr,
  2392. (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
  2393. }
  2394. VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
  2395. ADDOP_I(c, COMPARE_OP,
  2396. cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
  2397. if (n > 1) {
  2398. basicblock *end = compiler_new_block(c);
  2399. if (end == NULL)
  2400. return 0;
  2401. ADDOP_JREL(c, JUMP_FORWARD, end);
  2402. compiler_use_next_block(c, cleanup);
  2403. ADDOP(c, ROT_TWO);
  2404. ADDOP(c, POP_TOP);
  2405. compiler_use_next_block(c, end);
  2406. }
  2407. return 1;
  2408. }
  2409. static int
  2410. compiler_call(struct compiler *c, expr_ty e)
  2411. {
  2412. int n, code = 0;
  2413. int n_positional_args, n_keyword_args = 0;
  2414. expr_ty func = e->v.Call.func;
  2415. /* If this looks like a method call, emit specialized opcodes that
  2416. * avoid bound method allocation. */
  2417. if (!e->v.Call.starargs && !e->v.Call.kwargs &&
  2418. func->kind == Attribute_kind &&
  2419. func->v.Attribute.ctx == Load) {
  2420. VISIT(c, expr, func->v.Attribute.value);
  2421. ADDOP_NAME(c, LOAD_METHOD, func->v.Attribute.attr, names);
  2422. code = -1;
  2423. } else {
  2424. VISIT(c, expr, func);
  2425. }
  2426. n_positional_args = asdl_seq_LEN(e->v.Call.args);
  2427. VISIT_SEQ(c, expr, e->v.Call.args);
  2428. if (e->v.Call.keywords) {
  2429. VISIT_SEQ(c, keyword, e->v.Call.keywords);
  2430. n_keyword_args = asdl_seq_LEN(e->v.Call.keywords);
  2431. }
  2432. n = n_positional_args | (n_keyword_args << 8);
  2433. if (e->v.Call.starargs) {
  2434. VISIT(c, expr, e->v.Call.starargs);
  2435. code |= 1;
  2436. }
  2437. if (e->v.Call.kwargs) {
  2438. VISIT(c, expr, e->v.Call.kwargs);
  2439. code |= 2;
  2440. }
  2441. switch (code) {
  2442. case -1:
  2443. ADDOP_I(c, CALL_METHOD, n);
  2444. break;
  2445. case 0:
  2446. ADDOP_I(c, CALL_FUNCTION, n);
  2447. break;
  2448. case 1:
  2449. ADDOP_I(c, CALL_FUNCTION_VAR, n);
  2450. break;
  2451. case 2:
  2452. ADDOP_I(c, CALL_FUNCTION_KW, n);
  2453. break;
  2454. case 3:
  2455. ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
  2456. break;
  2457. }
  2458. return 1;
  2459. }
  2460. static int
  2461. compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
  2462. asdl_seq *generators, int gen_index,
  2463. expr_ty elt)
  2464. {
  2465. /* generate code for the iterator, then each of the ifs,
  2466. and then write to the element */
  2467. comprehension_ty l;
  2468. basicblock *start, *anchor, *if_cleanup;
  2469. int i, n;
  2470. start = compiler_new_block(c);
  2471. if_cleanup = compiler_new_block(c);
  2472. anchor = compiler_new_block(c);
  2473. if (start == NULL || if_cleanup == NULL || anchor == NULL)
  2474. return 0;
  2475. l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
  2476. VISIT(c, expr, l->iter);
  2477. ADDOP(c, GET_ITER);
  2478. compiler_use_next_block(c, start);
  2479. ADDOP_JREL(c, FOR_ITER, anchor);
  2480. NEXT_BLOCK(c);
  2481. VISIT(c, expr, l->target);
  2482. /* XXX this needs to be cleaned up...a lot! */
  2483. n = asdl_seq_LEN(l->ifs);
  2484. for (i = 0; i < n; i++) {
  2485. expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
  2486. VISIT(c, expr, e);
  2487. ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
  2488. NEXT_BLOCK(c);
  2489. }
  2490. if (++gen_index < asdl_seq_LEN(generators))
  2491. if (!compiler_listcomp_generator(c, tmpname,
  2492. generators, gen_index, elt))
  2493. return 0;
  2494. /* only append after the last for generator */
  2495. if (gen_index >= asdl_seq_LEN(generators)) {
  2496. if (!compiler_nameop(c, tmpname, Load))
  2497. return 0;
  2498. VISIT(c, expr, elt);
  2499. ADDOP(c, LIST_APPEND);
  2500. }
  2501. compiler_use_next_block(c, if_cleanup);
  2502. ADDOP_JABS(c, JUMP_ABSOLUTE, start);
  2503. compiler_use_next_block(c, anchor);
  2504. /* delete the temporary list name added to locals */
  2505. if (gen_index == 1)
  2506. if (!compiler_nameop(c, tmpname, Del))
  2507. return 0;
  2508. return 1;
  2509. }
  2510. static int
  2511. compiler_listcomp(struct compiler *c, expr_ty e)
  2512. {
  2513. identifier tmp;
  2514. int rc = 0;
  2515. asdl_seq *generators = e->v.ListComp.generators;
  2516. assert(e->kind == ListComp_kind);
  2517. tmp = compiler_new_tmpname(c);
  2518. if (!tmp)
  2519. return 0;
  2520. ADDOP_I(c, BUILD_LIST, 0);
  2521. ADDOP(c, DUP_TOP);
  2522. if (compiler_nameop(c, tmp, Store))
  2523. rc = compiler_listcomp_generator(c, tmp, generators, 0,
  2524. e->v.ListComp.elt);
  2525. Py_DECREF(tmp);
  2526. return rc;
  2527. }
  2528. static int
  2529. compiler_genexp_generator(struct compiler *c,
  2530. asdl_seq *generators, int gen_index,
  2531. expr_ty elt)
  2532. {
  2533. /* generate code for the iterator, then each of the ifs,
  2534. and then write to the element */
  2535. comprehension_ty ge;
  2536. basicblock *start, *anchor, *if_cleanup, *end;
  2537. int i, n;
  2538. start = compiler_new_block(c);
  2539. if_cleanup = compiler_new_block(c);
  2540. anchor = compiler_new_block(c);
  2541. end = compiler_new_block(c);
  2542. if (start == NULL || if_cleanup == NULL ||
  2543. anchor == NULL || end == NULL)
  2544. return 0;
  2545. ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
  2546. if (c->u->u_ste->ste_blockstack)
  2547. ADDOP_JREL(c, SETUP_LOOP, end);
  2548. if (!compiler_push_fblock(c, FOR_LOOP, start, end))
  2549. return 0;
  2550. if (gen_index == 0) {
  2551. /* Receive outermost iter as an implicit argument */
  2552. c->u->u_argcount = 1;
  2553. ADDOP_I(c, LOAD_FAST, 0);
  2554. }
  2555. else {
  2556. /* Sub-iter - calculate on the fly */
  2557. VISIT(c, expr, ge->iter);
  2558. ADDOP(c, GET_ITER);
  2559. }
  2560. compiler_use_next_block(c, start);
  2561. ADDOP_JREL(c, FOR_ITER, anchor);
  2562. NEXT_BLOCK(c);
  2563. VISIT(c, expr, ge->target);
  2564. /* XXX this needs to be cleaned up...a lot! */
  2565. n = asdl_seq_LEN(ge->ifs);
  2566. for (i = 0; i < n; i++) {
  2567. expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
  2568. VISIT(c, expr, e);
  2569. ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
  2570. NEXT_BLOCK(c);
  2571. }
  2572. if (++gen_index < asdl_seq_LEN(generators))
  2573. if (!compiler_genexp_generator(c, generators, gen_index, elt))
  2574. return 0;
  2575. /* only append after the last 'for' generator */
  2576. if (gen_index >= asdl_seq_LEN(generators)) {
  2577. VISIT(c, expr, elt);
  2578. ADDOP(c, YIELD_VALUE);
  2579. ADDOP(c, POP_TOP);
  2580. }
  2581. compiler_use_next_block(c, if_cleanup);
  2582. ADDOP_JABS(c, JUMP_ABSOLUTE, start);
  2583. compiler_use_next_block(c, anchor);
  2584. if (c->u->u_ste->ste_blockstack)
  2585. ADDOP(c, POP_BLOCK);
  2586. compiler_pop_fblock(c, FOR_LOOP, start, end);
  2587. compiler_use_next_block(c, end);
  2588. return 1;
  2589. }
  2590. static int
  2591. compiler_genexp(struct compiler *c, expr_ty e)
  2592. {
  2593. static identifier name;
  2594. PyCodeObject *co;
  2595. expr_ty outermost_iter = ((comprehension_ty)
  2596. (asdl_seq_GET(e->v.GeneratorExp.generators,
  2597. 0)))->iter;
  2598. if (!name) {
  2599. name = PyString_FromString("<genexpr>");
  2600. if (!name)
  2601. return 0;
  2602. }
  2603. if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
  2604. return 0;
  2605. compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
  2606. e->v.GeneratorExp.elt);
  2607. co = assemble(c, 1);
  2608. compiler_exit_scope(c);
  2609. if (co == NULL)
  2610. return 0;
  2611. compiler_make_closure(c, co, NULL);
  2612. Py_DECREF(co);
  2613. VISIT(c, expr, outermost_iter);
  2614. ADDOP(c, GET_ITER);
  2615. ADDOP_I(c, CALL_FUNCTION, 1);
  2616. return 1;
  2617. }
  2618. static int
  2619. compiler_visit_keyword(struct compiler *c, keyword_ty k)
  2620. {
  2621. ADDOP_O(c, LOAD_CONST, k->arg, consts);
  2622. VISIT(c, expr, k->value);
  2623. return 1;
  2624. }
  2625. /* Test whether expression is constant. For constants, report
  2626. whether they are true or false.
  2627. Return values: 1 for true, 0 for false, -1 for non-constant.
  2628. */
  2629. static int
  2630. expr_constant(expr_ty e)
  2631. {
  2632. switch (e->kind) {
  2633. case Num_kind:
  2634. return PyObject_IsTrue(e->v.Num.n);
  2635. case Str_kind:
  2636. return PyObject_IsTrue(e->v.Str.s);
  2637. case Name_kind:
  2638. /* __debug__ is not assignable, so we can optimize
  2639. * it away in if and while statements */
  2640. if (strcmp(PyString_AS_STRING(e->v.Name.id),
  2641. "__debug__") == 0)
  2642. return ! Py_OptimizeFlag;
  2643. /* fall through */
  2644. default:
  2645. return -1;
  2646. }
  2647. }
  2648. /*
  2649. Implements the with statement from PEP 343.
  2650. The semantics outlined in that PEP are as follows:
  2651. with EXPR as VAR:
  2652. BLOCK
  2653. It is implemented roughly as:
  2654. context = EXPR
  2655. exit = context.__exit__ # not calling it
  2656. value = context.__enter__()
  2657. try:
  2658. VAR = value # if VAR present in the syntax
  2659. BLOCK
  2660. finally:
  2661. if an exception was raised:
  2662. exc = copy of (exception, instance, traceback)
  2663. else:
  2664. exc = (None, None, None)
  2665. exit(*exc)
  2666. */
  2667. static int
  2668. compiler_with(struct compiler *c, stmt_ty s)
  2669. {
  2670. static identifier enter_attr, exit_attr;
  2671. basicblock *block, *finally;
  2672. identifier tmpvalue = NULL;
  2673. assert(s->kind == With_kind);
  2674. if (!enter_attr) {
  2675. enter_attr = PyString_InternFromString("__enter__");
  2676. if (!enter_attr)
  2677. return 0;
  2678. }
  2679. if (!exit_attr) {
  2680. exit_attr = PyString_InternFromString("__exit__");
  2681. if (!exit_attr)
  2682. return 0;
  2683. }
  2684. block = compiler_new_block(c);
  2685. finally = compiler_new_block(c);
  2686. if (!block || !finally)
  2687. return 0;
  2688. if (s->v.With.optional_vars) {
  2689. /* Create a temporary variable to hold context.__enter__().
  2690. We need to do this rather than preserving it on the stack
  2691. because SETUP_FINALLY remembers the stack level.
  2692. We need to do the assignment *inside* the try/finally
  2693. so that context.__exit__() is called when the assignment
  2694. fails. But we need to call context.__enter__() *before*
  2695. the try/finally so that if it fails we won't call
  2696. context.__exit__().
  2697. */
  2698. tmpvalue = compiler_new_tmpname(c);
  2699. if (tmpvalue == NULL)
  2700. return 0;
  2701. PyArena_AddPyObject(c->c_arena, tmpvalue);
  2702. }
  2703. /* Evaluate EXPR */
  2704. VISIT(c, expr, s->v.With.context_expr);
  2705. /* Squirrel away context.__exit__ by stuffing it under context */
  2706. ADDOP(c, DUP_TOP);
  2707. ADDOP_O(c, LOAD_ATTR, exit_attr, names);
  2708. ADDOP(c, ROT_TWO);
  2709. /* Call context.__enter__() */
  2710. ADDOP_O(c, LOAD_ATTR, enter_attr, names);
  2711. ADDOP_I(c, CALL_FUNCTION, 0);
  2712. if (s->v.With.optional_vars) {
  2713. /* Store it in tmpvalue */
  2714. if (!compiler_nameop(c, tmpvalue, Store))
  2715. return 0;
  2716. }
  2717. else {
  2718. /* Discard result from context.__enter__() */
  2719. ADDOP(c, POP_TOP);
  2720. }
  2721. /* Start the try block */
  2722. ADDOP_JREL(c, SETUP_FINALLY, finally);
  2723. compiler_use_next_block(c, block);
  2724. if (!compiler_push_fblock(c, FINALLY_TRY, block, finally)) {
  2725. return 0;
  2726. }
  2727. if (s->v.With.optional_vars) {
  2728. /* Bind saved result of context.__enter__() to VAR */
  2729. if (!compiler_nameop(c, tmpvalue, Load) ||
  2730. !compiler_nameop(c, tmpvalue, Del))
  2731. return 0;
  2732. VISIT(c, expr, s->v.With.optional_vars);
  2733. }
  2734. /* BLOCK code */
  2735. VISIT_SEQ(c, stmt, s->v.With.body);
  2736. /* End of try block; start the finally block */
  2737. ADDOP(c, POP_BLOCK);
  2738. compiler_pop_fblock(c, FINALLY_TRY, block, finally);
  2739. ADDOP_O(c, LOAD_CONST, Py_None, consts);
  2740. ADDOP(c, DUP_TOP);
  2741. ADDOP(c, DUP_TOP);
  2742. compiler_use_next_block(c, finally);
  2743. if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
  2744. return 0;
  2745. /* Finally block starts; context.__exit__ is on the stack under
  2746. the exception or return information. Just issue our magic
  2747. opcode. */
  2748. ADDOP(c, WITH_CLEANUP);
  2749. /* Finally block ends. */
  2750. ADDOP(c, END_FINALLY);
  2751. compiler_pop_fblock(c, FINALLY_END, finally, NULL);
  2752. return 1;
  2753. }
  2754. static int
  2755. compiler_visit_expr(struct compiler *c, expr_ty e)
  2756. {
  2757. int i, n;
  2758. /* If expr e has a different line number than the last expr/stmt,
  2759. set a new line number for the next instruction.
  2760. */
  2761. if (e->lineno > c->u->u_lineno) {
  2762. c->u->u_lineno = e->lineno;
  2763. c->u->u_lineno_set = false;
  2764. }
  2765. switch (e->kind) {
  2766. case BoolOp_kind:
  2767. return compiler_boolop(c, e);
  2768. case BinOp_kind:
  2769. VISIT(c, expr, e->v.BinOp.left);
  2770. VISIT(c, expr, e->v.BinOp.right);
  2771. ADDOP(c, binop(c, e->v.BinOp.op));
  2772. break;
  2773. case UnaryOp_kind:
  2774. VISIT(c, expr, e->v.UnaryOp.operand);
  2775. ADDOP(c, unaryop(e->v.UnaryOp.op));
  2776. break;
  2777. case Lambda_kind:
  2778. return compiler_lambda(c, e);
  2779. case IfExp_kind:
  2780. return compiler_ifexp(c, e);
  2781. case Dict_kind:
  2782. n = asdl_seq_LEN(e->v.Dict.values);
  2783. ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
  2784. for (i = 0; i < n; i++) {
  2785. VISIT(c, expr,
  2786. (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
  2787. VISIT(c, expr,
  2788. (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
  2789. ADDOP(c, STORE_MAP);
  2790. }
  2791. break;
  2792. case ListComp_kind:
  2793. return compiler_listcomp(c, e);
  2794. case GeneratorExp_kind:
  2795. return compiler_genexp(c, e);
  2796. case Yield_kind:
  2797. if (c->u->u_ste->ste_type != FunctionBlock)
  2798. return compiler_error(c, "'yield' outside function");
  2799. if (e->v.Yield.value) {
  2800. VISIT(c, expr, e->v.Yield.value);
  2801. }
  2802. else {
  2803. ADDOP_O(c, LOAD_CONST, Py_None, consts);
  2804. }
  2805. ADDOP(c, YIELD_VALUE);
  2806. break;
  2807. case Compare_kind:
  2808. return compiler_compare(c, e);
  2809. case Call_kind:
  2810. return compiler_call(c, e);
  2811. case Repr_kind:
  2812. VISIT(c, expr, e->v.Repr.value);
  2813. ADDOP(c, UNARY_CONVERT);
  2814. break;
  2815. case Num_kind:
  2816. ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
  2817. break;
  2818. case Str_kind:
  2819. ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
  2820. break;
  2821. /* The following exprs can be assignment targets. */
  2822. case Attribute_kind:
  2823. if (e->v.Attribute.ctx != AugStore)
  2824. VISIT(c, expr, e->v.Attribute.value);
  2825. switch (e->v.Attribute.ctx) {
  2826. case AugLoad:
  2827. ADDOP(c, DUP_TOP);
  2828. /* Fall through to load */
  2829. case Load:
  2830. ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
  2831. break;
  2832. case AugStore:
  2833. ADDOP(c, ROT_TWO);
  2834. /* Fall through to save */
  2835. case Store:
  2836. ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
  2837. break;
  2838. case Del:
  2839. ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
  2840. break;
  2841. case Param:
  2842. default:
  2843. PyErr_SetString(PyExc_SystemError,
  2844. "param invalid in attribute expression");
  2845. return 0;
  2846. }
  2847. break;
  2848. case Subscript_kind:
  2849. switch (e->v.Subscript.ctx) {
  2850. case AugLoad:
  2851. VISIT(c, expr, e->v.Subscript.value);
  2852. VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
  2853. break;
  2854. case Load:
  2855. VISIT(c, expr, e->v.Subscript.value);
  2856. VISIT_SLICE(c, e->v.Subscript.slice, Load);
  2857. break;
  2858. case AugStore:
  2859. VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
  2860. break;
  2861. case Store:
  2862. VISIT(c, expr, e->v.Subscript.value);
  2863. VISIT_SLICE(c, e->v.Subscript.slice, Store);
  2864. break;
  2865. case Del:
  2866. VISIT(c, expr, e->v.Subscript.value);
  2867. VISIT_SLICE(c, e->v.Subscript.slice, Del);
  2868. break;
  2869. case Param:
  2870. default:
  2871. PyErr_SetString(PyExc_SystemError,
  2872. "param invalid in subscript expression");
  2873. return 0;
  2874. }
  2875. break;
  2876. case Name_kind:
  2877. return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
  2878. /* child nodes of List and Tuple will have expr_context set */
  2879. case List_kind:
  2880. return compiler_list(c, e);
  2881. case Tuple_kind:
  2882. return compiler_tuple(c, e);
  2883. }
  2884. return 1;
  2885. }
  2886. static int
  2887. compiler_augassign(struct compiler *c, stmt_ty s)
  2888. {
  2889. expr_ty e = s->v.AugAssign.target;
  2890. expr_ty auge;
  2891. assert(s->kind == AugAssign_kind);
  2892. switch (e->kind) {
  2893. case Attribute_kind:
  2894. auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
  2895. AugLoad, e->lineno, e->col_offset, c->c_arena);
  2896. if (auge == NULL)
  2897. return 0;
  2898. VISIT(c, expr, auge);
  2899. VISIT(c, expr, s->v.AugAssign.value);
  2900. ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
  2901. auge->v.Attribute.ctx = AugStore;
  2902. VISIT(c, expr, auge);
  2903. break;
  2904. case Subscript_kind:
  2905. auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
  2906. AugLoad, e->lineno, e->col_offset, c->c_arena);
  2907. if (auge == NULL)
  2908. return 0;
  2909. VISIT(c, expr, auge);
  2910. VISIT(c, expr, s->v.AugAssign.value);
  2911. ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
  2912. auge->v.Subscript.ctx = AugStore;
  2913. VISIT(c, expr, auge);
  2914. break;
  2915. case Name_kind:
  2916. if (!compiler_nameop(c, e->v.Name.id, Load))
  2917. return 0;
  2918. VISIT(c, expr, s->v.AugAssign.value);
  2919. ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
  2920. return compiler_nameop(c, e->v.Name.id, Store);
  2921. default:
  2922. PyErr_Format(PyExc_SystemError,
  2923. "invalid node type (%d) for augmented assignment",
  2924. e->kind);
  2925. return 0;
  2926. }
  2927. return 1;
  2928. }
  2929. static int
  2930. compiler_push_fblock(struct compiler *c, enum fblocktype t,
  2931. basicblock *b, basicblock *target)
  2932. {
  2933. struct fblockinfo *f;
  2934. if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
  2935. PyErr_SetString(PyExc_SystemError,
  2936. "too many statically nested blocks");
  2937. return 0;
  2938. }
  2939. f = &c->u->u_fblock[c->u->u_nfblocks++];
  2940. f->fb_type = t;
  2941. f->fb_block = b;
  2942. f->fb_target = target;
  2943. return 1;
  2944. }
  2945. static void
  2946. compiler_pop_fblock(struct compiler *c, enum fblocktype t,
  2947. basicblock *b, basicblock *target)
  2948. {
  2949. struct compiler_unit *u = c->u;
  2950. assert(u->u_nfblocks > 0);
  2951. u->u_nfblocks--;
  2952. assert(u->u_fblock[u->u_nfblocks].fb_type == t);
  2953. assert(u->u_fblock[u->u_nfblocks].fb_block == b);
  2954. assert(u->u_fblock[u->u_nfblocks].fb_target == target);
  2955. }
  2956. static int
  2957. compiler_in_loop(struct compiler *c)
  2958. {
  2959. int i;
  2960. struct compiler_unit *u = c->u;
  2961. for (i = 0; i < u->u_nfblocks; ++i) {
  2962. enum fblocktype block_type = u->u_fblock[i].fb_type;
  2963. if (block_type == FOR_LOOP || block_type == WHILE_LOOP)
  2964. return 1;
  2965. }
  2966. return 0;
  2967. }
  2968. /* Raises a SyntaxError and returns 0.
  2969. If something goes wrong, a different exception may be raised.
  2970. */
  2971. static int
  2972. compiler_error(struct compiler *c, const char *errstr)
  2973. {
  2974. PyObject *loc;
  2975. PyObject *u = NULL, *v = NULL;
  2976. loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
  2977. if (!loc) {
  2978. Py_INCREF(Py_None);
  2979. loc = Py_None;
  2980. }
  2981. u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
  2982. Py_None, loc);
  2983. if (!u)
  2984. goto exit;
  2985. v = Py_BuildValue("(zO)", errstr, u);
  2986. if (!v)
  2987. goto exit;
  2988. PyErr_SetObject(PyExc_SyntaxError, v);
  2989. exit:
  2990. Py_DECREF(loc);
  2991. Py_XDECREF(u);
  2992. Py_XDECREF(v);
  2993. return 0;
  2994. }
  2995. static int
  2996. compiler_handle_subscr(struct compiler *c, const char *kind,
  2997. expr_context_ty ctx)
  2998. {
  2999. int op = 0;
  3000. /* XXX this code is duplicated */
  3001. switch (ctx) {
  3002. case AugLoad: /* fall through to Load */
  3003. case Load: op = BINARY_SUBSCR; break;
  3004. case AugStore:/* fall through to Store */
  3005. case Store: op = STORE_SUBSCR; break;
  3006. case Del: op = DELETE_SUBSCR; break;
  3007. case Param:
  3008. PyErr_Format(PyExc_SystemError,
  3009. "invalid %s kind %d in subscript\n",
  3010. kind, ctx);
  3011. return 0;
  3012. }
  3013. if (ctx == AugLoad) {
  3014. ADDOP(c, DUP_TOP_TWO);
  3015. }
  3016. else if (ctx == AugStore) {
  3017. ADDOP(c, ROT_THREE);
  3018. }
  3019. ADDOP(c, op);
  3020. return 1;
  3021. }
  3022. static int
  3023. compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
  3024. {
  3025. int slice_has_three_args = 0;
  3026. assert(s->kind == Slice_kind);
  3027. /* only handles the cases where BUILD_SLICE is emitted */
  3028. if (s->v.Slice.lower) {
  3029. VISIT(c, expr, s->v.Slice.lower);
  3030. }
  3031. else {
  3032. ADDOP_O(c, LOAD_CONST, Py_None, consts);
  3033. }
  3034. if (s->v.Slice.upper) {
  3035. VISIT(c, expr, s->v.Slice.upper);
  3036. }
  3037. else {
  3038. ADDOP_O(c, LOAD_CONST, Py_None, consts);
  3039. }
  3040. if (s->v.Slice.step) {
  3041. slice_has_three_args = 1;
  3042. VISIT(c, expr, s->v.Slice.step);
  3043. }
  3044. ADDOP(c, slice_has_three_args ? BUILD_SLICE_THREE : BUILD_SLICE_TWO);
  3045. return 1;
  3046. }
  3047. static int
  3048. compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
  3049. {
  3050. const int slice[] = { SLICE_NONE, SLICE_LEFT, SLICE_RIGHT, SLICE_BOTH };
  3051. const int store_slice[] = { STORE_SLICE_NONE, STORE_SLICE_LEFT,
  3052. STORE_SLICE_RIGHT, STORE_SLICE_BOTH };
  3053. const int delete_slice[] = { DELETE_SLICE_NONE, DELETE_SLICE_LEFT,
  3054. DELETE_SLICE_RIGHT, DELETE_SLICE_BOTH };
  3055. const int *op_array = NULL;
  3056. int slice_offset = 0, stack_count = 0;
  3057. assert(s->v.Slice.step == NULL);
  3058. if (s->v.Slice.lower) {
  3059. slice_offset++;
  3060. stack_count++;
  3061. if (ctx != AugStore)
  3062. VISIT(c, expr, s->v.Slice.lower);
  3063. }
  3064. if (s->v.Slice.upper) {
  3065. slice_offset += 2;
  3066. stack_count++;
  3067. if (ctx != AugStore)
  3068. VISIT(c, expr, s->v.Slice.upper);
  3069. }
  3070. if (ctx == AugLoad) {
  3071. switch (stack_count) {
  3072. case 0: ADDOP(c, DUP_TOP); break;
  3073. case 1: ADDOP(c, DUP_TOP_TWO); break;
  3074. case 2: ADDOP(c, DUP_TOP_THREE); break;
  3075. }
  3076. }
  3077. else if (ctx == AugStore) {
  3078. switch (stack_count) {
  3079. case 0: ADDOP(c, ROT_TWO); break;
  3080. case 1: ADDOP(c, ROT_THREE); break;
  3081. case 2: ADDOP(c, ROT_FOUR); break;
  3082. }
  3083. }
  3084. switch (ctx) {
  3085. case AugLoad: /* fall through to Load */
  3086. case Load: op_array = slice; break;
  3087. case AugStore:/* fall through to Store */
  3088. case Store: op_array = store_slice; break;
  3089. case Del: op_array = delete_slice; break;
  3090. case Param:
  3091. default:
  3092. PyErr_SetString(PyExc_SystemError,
  3093. "param invalid in simple slice");
  3094. return 0;
  3095. }
  3096. ADDOP(c, op_array[slice_offset]);
  3097. return 1;
  3098. }
  3099. static int
  3100. compiler_visit_nested_slice(struct compiler *c, slice_ty s,
  3101. expr_context_ty ctx)
  3102. {
  3103. switch (s->kind) {
  3104. case Ellipsis_kind:
  3105. ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
  3106. break;
  3107. case Slice_kind:
  3108. return compiler_slice(c, s, ctx);
  3109. case Index_kind:
  3110. VISIT(c, expr, s->v.Index.value);
  3111. break;
  3112. case ExtSlice_kind:
  3113. default:
  3114. PyErr_SetString(PyExc_SystemError,
  3115. "extended slice invalid in nested slice");
  3116. return 0;
  3117. }
  3118. return 1;
  3119. }
  3120. static int
  3121. compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
  3122. {
  3123. char * kindname = NULL;
  3124. switch (s->kind) {
  3125. case Index_kind:
  3126. kindname = "index";
  3127. if (ctx != AugStore) {
  3128. VISIT(c, expr, s->v.Index.value);
  3129. }
  3130. break;
  3131. case Ellipsis_kind:
  3132. kindname = "ellipsis";
  3133. if (ctx != AugStore) {
  3134. ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
  3135. }
  3136. break;
  3137. case Slice_kind:
  3138. kindname = "slice";
  3139. if (!s->v.Slice.step)
  3140. return compiler_simple_slice(c, s, ctx);
  3141. if (ctx != AugStore) {
  3142. if (!compiler_slice(c, s, ctx))
  3143. return 0;
  3144. }
  3145. break;
  3146. case ExtSlice_kind:
  3147. kindname = "extended slice";
  3148. if (ctx != AugStore) {
  3149. int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
  3150. for (i = 0; i < n; i++) {
  3151. slice_ty sub = (slice_ty)asdl_seq_GET(
  3152. s->v.ExtSlice.dims, i);
  3153. if (!compiler_visit_nested_slice(c, sub, ctx))
  3154. return 0;
  3155. }
  3156. ADDOP_I(c, BUILD_TUPLE, n);
  3157. }
  3158. break;
  3159. default:
  3160. PyErr_Format(PyExc_SystemError,
  3161. "invalid subscript kind %d", s->kind);
  3162. return 0;
  3163. }
  3164. return compiler_handle_subscr(c, kindname, ctx);
  3165. }
  3166. /* End of the compiler section, beginning of the assembler section */
  3167. /* do depth-first search of basic block graph, starting with block.
  3168. post records the block indices in post-order.
  3169. XXX must handle implicit jumps from one block to next
  3170. */
  3171. struct assembler {
  3172. PyObject *a_bytecode; /* string containing bytecode */
  3173. int a_offset; /* offset into bytecode */
  3174. int a_nblocks; /* number of reachable blocks */
  3175. basicblock **a_postorder; /* list of blocks in dfs postorder */
  3176. PyObject *a_lnotab; /* string containing lnotab */
  3177. int a_lnotab_off; /* offset into lnotab */
  3178. int a_lineno; /* last lineno of emitted instruction */
  3179. int a_lineno_off; /* bytecode offset of last lineno */
  3180. };
  3181. static void
  3182. dfs(struct compiler *c, basicblock *b, struct assembler *a)
  3183. {
  3184. int i;
  3185. struct instr *instr = NULL;
  3186. if (b->b_seen)
  3187. return;
  3188. b->b_seen = 1;
  3189. if (b->b_next != NULL)
  3190. dfs(c, b->b_next, a);
  3191. for (i = 0; i < b->b_iused; i++) {
  3192. instr = &b->b_instr[i];
  3193. if (instr->i_jrel || instr->i_jabs)
  3194. dfs(c, instr->i_target, a);
  3195. }
  3196. a->a_postorder[a->a_nblocks++] = b;
  3197. }
  3198. static int
  3199. stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
  3200. {
  3201. int i;
  3202. struct instr *instr;
  3203. if (b->b_seen || b->b_startdepth >= depth)
  3204. return maxdepth;
  3205. b->b_seen = 1;
  3206. b->b_startdepth = depth;
  3207. for (i = 0; i < b->b_iused; i++) {
  3208. instr = &b->b_instr[i];
  3209. depth += _Py_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
  3210. if (depth > maxdepth)
  3211. maxdepth = depth;
  3212. assert(depth >= 0); /* invalid code or bug in stackdepth() */
  3213. if (instr->i_jrel || instr->i_jabs) {
  3214. maxdepth = stackdepth_walk(c, instr->i_target,
  3215. depth, maxdepth);
  3216. if (instr->i_opcode == JUMP_ABSOLUTE ||
  3217. instr->i_opcode == JUMP_FORWARD) {
  3218. goto out; /* remaining code is dead */
  3219. }
  3220. }
  3221. }
  3222. if (b->b_next)
  3223. maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
  3224. out:
  3225. b->b_seen = 0;
  3226. return maxdepth;
  3227. }
  3228. /* Find the flow path that needs the largest stack. We assume that
  3229. * cycles in the flow graph have no net effect on the stack depth.
  3230. */
  3231. static int
  3232. stackdepth(struct compiler *c)
  3233. {
  3234. basicblock *b, *entryblock;
  3235. entryblock = NULL;
  3236. for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
  3237. b->b_seen = 0;
  3238. b->b_startdepth = INT_MIN;
  3239. entryblock = b;
  3240. }
  3241. if (!entryblock)
  3242. return 0;
  3243. return stackdepth_walk(c, entryblock, 0, 0);
  3244. }
  3245. static int
  3246. assemble_init(struct assembler *a, int nblocks, int firstlineno)
  3247. {
  3248. memset(a, 0, sizeof(struct assembler));
  3249. a->a_lineno = firstlineno;
  3250. a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
  3251. if (!a->a_bytecode)
  3252. return 0;
  3253. a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
  3254. if (!a->a_lnotab)
  3255. return 0;
  3256. if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
  3257. PyErr_NoMemory();
  3258. return 0;
  3259. }
  3260. a->a_postorder = (basicblock **)PyObject_Malloc(
  3261. sizeof(basicblock *) * nblocks);
  3262. if (!a->a_postorder) {
  3263. PyErr_NoMemory();
  3264. return 0;
  3265. }
  3266. return 1;
  3267. }
  3268. static void
  3269. assemble_free(struct assembler *a)
  3270. {
  3271. Py_XDECREF(a->a_bytecode);
  3272. Py_XDECREF(a->a_lnotab);
  3273. if (a->a_postorder)
  3274. PyObject_Free(a->a_postorder);
  3275. }
  3276. /* Return the size of a basic block in bytes. */
  3277. static int
  3278. instrsize(struct instr *instr)
  3279. {
  3280. if (!instr->i_hasarg)
  3281. return 1; /* 1 byte for the opcode*/
  3282. if (instr->i_oparg > 0xffff)
  3283. return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
  3284. return 3; /* 1 (opcode) + 2 (oparg) */
  3285. }
  3286. static int
  3287. blocksize(basicblock *b)
  3288. {
  3289. int i;
  3290. int size = 0;
  3291. for (i = 0; i < b->b_iused; i++)
  3292. size += instrsize(&b->b_instr[i]);
  3293. return size;
  3294. }
  3295. /* Appends a pair to the end of the line number table, a_lnotab, representing
  3296. the instruction's bytecode offset and line number. See
  3297. Objects/lnotab_notes.txt for the description of the line number table. */
  3298. static int
  3299. assemble_lnotab(struct assembler *a, struct instr *i)
  3300. {
  3301. int d_bytecode, d_lineno;
  3302. int len;
  3303. unsigned char *lnotab;
  3304. d_bytecode = a->a_offset - a->a_lineno_off;
  3305. d_lineno = i->i_lineno - a->a_lineno;
  3306. assert(d_bytecode >= 0);
  3307. assert(d_lineno >= 0);
  3308. if(d_bytecode == 0 && d_lineno == 0)
  3309. return 1;
  3310. if (d_bytecode > 255) {
  3311. int j, nbytes, ncodes = d_bytecode / 255;
  3312. nbytes = a->a_lnotab_off + 2 * ncodes;
  3313. len = PyString_GET_SIZE(a->a_lnotab);
  3314. if (nbytes >= len) {
  3315. if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
  3316. len = nbytes;
  3317. else if (len <= INT_MAX / 2)
  3318. len *= 2;
  3319. else {
  3320. PyErr_NoMemory();
  3321. return 0;
  3322. }
  3323. if (_PyString_Resize(&a->a_lnotab, len) < 0)
  3324. return 0;
  3325. }
  3326. lnotab = (unsigned char *)
  3327. PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
  3328. for (j = 0; j < ncodes; j++) {
  3329. *lnotab++ = 255;
  3330. *lnotab++ = 0;
  3331. }
  3332. d_bytecode -= ncodes * 255;
  3333. a->a_lnotab_off += ncodes * 2;
  3334. }
  3335. assert(d_bytecode <= 255);
  3336. if (d_lineno > 255) {
  3337. int j, nbytes, ncodes = d_lineno / 255;
  3338. nbytes = a->a_lnotab_off + 2 * ncodes;
  3339. len = PyString_GET_SIZE(a->a_lnotab);
  3340. if (nbytes >= len) {
  3341. if ((len <= INT_MAX / 2) && len * 2 < nbytes)
  3342. len = nbytes;
  3343. else if (len <= INT_MAX / 2)
  3344. len *= 2;
  3345. else {
  3346. PyErr_NoMemory();
  3347. return 0;
  3348. }
  3349. if (_PyString_Resize(&a->a_lnotab, len) < 0)
  3350. return 0;
  3351. }
  3352. lnotab = (unsigned char *)
  3353. PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
  3354. *lnotab++ = d_bytecode;
  3355. *lnotab++ = 255;
  3356. d_bytecode = 0;
  3357. for (j = 1; j < ncodes; j++) {
  3358. *lnotab++ = 0;
  3359. *lnotab++ = 255;
  3360. }
  3361. d_lineno -= ncodes * 255;
  3362. a->a_lnotab_off += ncodes * 2;
  3363. }
  3364. len = PyString_GET_SIZE(a->a_lnotab);
  3365. if (a->a_lnotab_off + 2 >= len) {
  3366. if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
  3367. return 0;
  3368. }
  3369. lnotab = (unsigned char *)
  3370. PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
  3371. a->a_lnotab_off += 2;
  3372. if (d_bytecode) {
  3373. *lnotab++ = d_bytecode;
  3374. *lnotab++ = d_lineno;
  3375. }
  3376. else { /* First line of a block; def stmt, etc. */
  3377. *lnotab++ = 0;
  3378. *lnotab++ = d_lineno;
  3379. }
  3380. a->a_lineno = i->i_lineno;
  3381. a->a_lineno_off = a->a_offset;
  3382. return 1;
  3383. }
  3384. /* assemble_emit()
  3385. Extend the bytecode with a new instruction.
  3386. Update lnotab if necessary.
  3387. */
  3388. static int
  3389. assemble_emit(struct assembler *a, struct instr *i)
  3390. {
  3391. int size, arg = 0, ext = 0;
  3392. Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
  3393. char *code;
  3394. size = instrsize(i);
  3395. if (i->i_hasarg) {
  3396. arg = i->i_oparg;
  3397. ext = arg >> 16;
  3398. }
  3399. if (i->i_lineno && !assemble_lnotab(a, i))
  3400. return 0;
  3401. if (a->a_offset + size >= len) {
  3402. if (len > PY_SSIZE_T_MAX / 2)
  3403. return 0;
  3404. if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
  3405. return 0;
  3406. }
  3407. code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
  3408. a->a_offset += size;
  3409. if (size == 6) {
  3410. assert(i->i_hasarg);
  3411. *code++ = (char)EXTENDED_ARG;
  3412. *code++ = ext & 0xff;
  3413. *code++ = ext >> 8;
  3414. arg &= 0xffff;
  3415. }
  3416. *code++ = i->i_opcode;
  3417. if (i->i_hasarg) {
  3418. assert(size == 3 || size == 6);
  3419. *code++ = arg & 0xff;
  3420. *code++ = arg >> 8;
  3421. }
  3422. return 1;
  3423. }
  3424. static void
  3425. assemble_jump_offsets(struct assembler *a, struct compiler *c)
  3426. {
  3427. basicblock *b;
  3428. int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
  3429. int i;
  3430. /* Compute the size of each block and fixup jump args.
  3431. Replace block pointer with position in bytecode. */
  3432. start:
  3433. totsize = 0;
  3434. for (i = a->a_nblocks - 1; i >= 0; i--) {
  3435. b = a->a_postorder[i];
  3436. bsize = blocksize(b);
  3437. b->b_offset = totsize;
  3438. totsize += bsize;
  3439. }
  3440. extended_arg_count = 0;
  3441. for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
  3442. bsize = b->b_offset;
  3443. for (i = 0; i < b->b_iused; i++) {
  3444. struct instr *instr = &b->b_instr[i];
  3445. /* Relative jumps are computed relative to
  3446. the instruction pointer after fetching
  3447. the jump instruction.
  3448. */
  3449. bsize += instrsize(instr);
  3450. if (instr->i_jabs)
  3451. instr->i_oparg = instr->i_target->b_offset;
  3452. else if (instr->i_jrel) {
  3453. int delta = instr->i_target->b_offset - bsize;
  3454. instr->i_oparg = delta;
  3455. }
  3456. else
  3457. continue;
  3458. if (instr->i_oparg > 0xffff)
  3459. extended_arg_count++;
  3460. }
  3461. }
  3462. /* XXX: This is an awful hack that could hurt performance, but
  3463. on the bright side it should work until we come up
  3464. with a better solution.
  3465. In the meantime, should the goto be dropped in favor
  3466. of a loop?
  3467. The issue is that in the first loop blocksize() is called
  3468. which calls instrsize() which requires i_oparg be set
  3469. appropriately. There is a bootstrap problem because
  3470. i_oparg is calculated in the second loop above.
  3471. So we loop until we stop seeing new EXTENDED_ARGs.
  3472. The only EXTENDED_ARGs that could be popping up are
  3473. ones in jump instructions. So this should converge
  3474. fairly quickly.
  3475. */
  3476. if (last_extended_arg_count != extended_arg_count) {
  3477. last_extended_arg_count = extended_arg_count;
  3478. goto start;
  3479. }
  3480. }
  3481. static PyObject *
  3482. dict_keys_inorder(PyObject *dict, int offset)
  3483. {
  3484. PyObject *tuple, *k, *v;
  3485. Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
  3486. tuple = PyTuple_New(size);
  3487. if (tuple == NULL)
  3488. return NULL;
  3489. while (PyDict_Next(dict, &pos, &k, &v)) {
  3490. i = PyInt_AS_LONG(v);
  3491. k = PyTuple_GET_ITEM(k, 0);
  3492. Py_INCREF(k);
  3493. assert((i - offset) < size);
  3494. assert((i - offset) >= 0);
  3495. PyTuple_SET_ITEM(tuple, i - offset, k);
  3496. }
  3497. return tuple;
  3498. }
  3499. static int
  3500. compute_code_flags(struct compiler *c)
  3501. {
  3502. PySTEntryObject *ste = c->u->u_ste;
  3503. int flags = 0, n;
  3504. if (ste->ste_type != ModuleBlock)
  3505. flags |= CO_NEWLOCALS;
  3506. if (ste->ste_type == FunctionBlock) {
  3507. if (!ste->ste_unoptimized)
  3508. flags |= CO_OPTIMIZED;
  3509. if (ste->ste_nested)
  3510. flags |= CO_NESTED;
  3511. if (ste->ste_generator)
  3512. flags |= CO_GENERATOR;
  3513. }
  3514. if (ste->ste_varargs)
  3515. flags |= CO_VARARGS;
  3516. if (ste->ste_varkeywords)
  3517. flags |= CO_VARKEYWORDS;
  3518. if (ste->ste_generator)
  3519. flags |= CO_GENERATOR;
  3520. if (ste->ste_blockstack)
  3521. flags |= CO_BLOCKSTACK;
  3522. if (c->u->u_uses_exec)
  3523. flags |= CO_USES_EXEC;
  3524. /* (Only) inherit compilerflags in PyCF_MASK */
  3525. flags |= (c->c_flags->cf_flags & PyCF_MASK);
  3526. n = PyDict_Size(c->u->u_freevars);
  3527. if (n < 0)
  3528. return -1;
  3529. if (n == 0) {
  3530. n = PyDict_Size(c->u->u_cellvars);
  3531. if (n < 0)
  3532. return -1;
  3533. if (n == 0) {
  3534. flags |= CO_NOFREE;
  3535. }
  3536. }
  3537. return flags;
  3538. }
  3539. static PyCodeObject *
  3540. makecode(struct compiler *c, struct assembler *a)
  3541. {
  3542. PyObject *tmp;
  3543. PyCodeObject *co = NULL;
  3544. PyObject *consts = NULL;
  3545. PyObject *names = NULL;
  3546. PyObject *varnames = NULL;
  3547. PyObject *filename = NULL;
  3548. PyObject *name = NULL;
  3549. PyObject *freevars = NULL;
  3550. PyObject *cellvars = NULL;
  3551. PyObject *bytecode = NULL;
  3552. int nlocals, flags;
  3553. tmp = dict_keys_inorder(c->u->u_consts, 0);
  3554. if (!tmp)
  3555. goto error;
  3556. consts = PySequence_List(tmp); /* optimize_code requires a list */
  3557. Py_DECREF(tmp);
  3558. names = dict_keys_inorder(c->u->u_names, 0);
  3559. varnames = dict_keys_inorder(c->u->u_varnames, 0);
  3560. if (!consts || !names || !varnames)
  3561. goto error;
  3562. cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
  3563. if (!cellvars)
  3564. goto error;
  3565. freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
  3566. if (!freevars)
  3567. goto error;
  3568. filename = PyString_FromString(c->c_filename);
  3569. if (!filename)
  3570. goto error;
  3571. nlocals = PyDict_Size(c->u->u_varnames);
  3572. flags = compute_code_flags(c);
  3573. if (flags < 0)
  3574. goto error;
  3575. bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
  3576. if (!bytecode)
  3577. goto error;
  3578. tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
  3579. if (!tmp)
  3580. goto error;
  3581. Py_DECREF(consts);
  3582. consts = tmp;
  3583. co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
  3584. bytecode, consts, names, varnames,
  3585. freevars, cellvars,
  3586. filename, c->u->u_name,
  3587. c->u->u_firstlineno,
  3588. a->a_lnotab);
  3589. error:
  3590. Py_XDECREF(consts);
  3591. Py_XDECREF(names);
  3592. Py_XDECREF(varnames);
  3593. Py_XDECREF(filename);
  3594. Py_XDECREF(name);
  3595. Py_XDECREF(freevars);
  3596. Py_XDECREF(cellvars);
  3597. Py_XDECREF(bytecode);
  3598. return co;
  3599. }
  3600. /* For debugging purposes only */
  3601. #if 0
  3602. static void
  3603. dump_instr(const struct instr *i)
  3604. {
  3605. const char *jrel = i->i_jrel ? "jrel " : "";
  3606. const char *jabs = i->i_jabs ? "jabs " : "";
  3607. char arg[128];
  3608. *arg = '\0';
  3609. if (i->i_hasarg)
  3610. sprintf(arg, "arg: %d ", i->i_oparg);
  3611. fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
  3612. i->i_lineno, i->i_opcode, arg, jabs, jrel);
  3613. }
  3614. static void
  3615. dump_basicblock(const basicblock *b)
  3616. {
  3617. const char *seen = b->b_seen ? "seen " : "";
  3618. const char *b_return = b->b_return ? "return " : "";
  3619. fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
  3620. b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
  3621. if (b->b_instr) {
  3622. int i;
  3623. for (i = 0; i < b->b_iused; i++) {
  3624. fprintf(stderr, " [%02d] ", i);
  3625. dump_instr(b->b_instr + i);
  3626. }
  3627. }
  3628. }
  3629. #endif
  3630. static PyCodeObject *
  3631. assemble(struct compiler *c, int addNone)
  3632. {
  3633. basicblock *b, *entryblock;
  3634. struct assembler a;
  3635. int i, j, nblocks;
  3636. PyCodeObject *co = NULL;
  3637. /* Make sure every block that falls off the end returns None.
  3638. XXX NEXT_BLOCK() isn't quite right, because if the last
  3639. block ends with a jump or return b_next shouldn't set.
  3640. */
  3641. if (!c->u->u_curblock->b_return) {
  3642. NEXT_BLOCK(c);
  3643. if (addNone)
  3644. ADDOP_O(c, LOAD_CONST, Py_None, consts);
  3645. ADDOP(c, RETURN_VALUE);
  3646. }
  3647. nblocks = 0;
  3648. entryblock = NULL;
  3649. for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
  3650. nblocks++;
  3651. entryblock = b;
  3652. }
  3653. /* Set firstlineno if it wasn't explicitly set. */
  3654. if (!c->u->u_firstlineno) {
  3655. if (entryblock && entryblock->b_instr)
  3656. c->u->u_firstlineno = entryblock->b_instr->i_lineno;
  3657. else
  3658. c->u->u_firstlineno = 1;
  3659. }
  3660. if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
  3661. goto error;
  3662. dfs(c, entryblock, &a);
  3663. /* Can't modify the bytecode after computing jump offsets. */
  3664. assemble_jump_offsets(&a, c);
  3665. /* Emit code in reverse postorder from dfs. */
  3666. for (i = a.a_nblocks - 1; i >= 0; i--) {
  3667. b = a.a_postorder[i];
  3668. for (j = 0; j < b->b_iused; j++)
  3669. if (!assemble_emit(&a, &b->b_instr[j]))
  3670. goto error;
  3671. }
  3672. if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
  3673. goto error;
  3674. if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
  3675. goto error;
  3676. co = makecode(c, &a);
  3677. error:
  3678. assemble_free(&a);
  3679. return co;
  3680. }