/Python/compile.c

http://unladen-swallow.googlecode.com/ · C · 4071 lines · 3303 code · 365 blank · 403 comment · 693 complexity · 90a995028856bda463af1ecde267e58a MD5 · raw file

Large files are truncated click here to view the full file

  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…