home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Python / compile.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  83.4 KB  |  3,726 lines

  1.  
  2. /* Compile an expression node to intermediate code */
  3.  
  4. /* XXX TO DO:
  5.    XXX add __doc__ attribute == co_doc to code object attributes?
  6.    XXX   (it's currently the first item of the co_const tuple)
  7.    XXX Generate simple jump for break/return outside 'try...finally'
  8.    XXX Allow 'continue' inside try-finally
  9.    XXX New opcode for loading the initial index for a for loop
  10.    XXX other JAR tricks?
  11. */
  12.  
  13. #ifndef NO_PRIVATE_NAME_MANGLING
  14. #define PRIVATE_NAME_MANGLING
  15. #endif
  16.  
  17. #include "Python.h"
  18.  
  19. #include "node.h"
  20. #include "token.h"
  21. #include "graminit.h"
  22. #include "compile.h"
  23. #include "opcode.h"
  24. #include "structmember.h"
  25.  
  26. #include <ctype.h>
  27.  
  28. /* Three symbols from graminit.h are also defined in Python.h, with
  29.    Py_ prefixes to their names.  Python.h can't include graminit.h
  30.    (which defines too many confusing symbols), but we can check here
  31.    that they haven't changed (which is very unlikely, but possible). */
  32. #if Py_single_input != single_input
  33.   #error "single_input has changed -- update Py_single_input in Python.h"
  34. #endif
  35. #if Py_file_input != file_input
  36.   #error "file_input has changed -- update Py_file_input in Python.h"
  37. #endif
  38. #if Py_eval_input != eval_input
  39.   #error "eval_input has changed -- update Py_eval_input in Python.h"
  40. #endif
  41.  
  42. int Py_OptimizeFlag = 0;
  43.  
  44. #define OP_DELETE 0
  45. #define OP_ASSIGN 1
  46. #define OP_APPLY 2
  47.  
  48. #define OFF(x) offsetof(PyCodeObject, x)
  49.  
  50. static struct memberlist code_memberlist[] = {
  51.     {"co_argcount",    T_INT,        OFF(co_argcount),    READONLY},
  52.     {"co_nlocals",    T_INT,        OFF(co_nlocals),    READONLY},
  53.     {"co_stacksize",T_INT,        OFF(co_stacksize),    READONLY},
  54.     {"co_flags",    T_INT,        OFF(co_flags),        READONLY},
  55.     {"co_code",    T_OBJECT,    OFF(co_code),        READONLY},
  56.     {"co_consts",    T_OBJECT,    OFF(co_consts),        READONLY},
  57.     {"co_names",    T_OBJECT,    OFF(co_names),        READONLY},
  58.     {"co_varnames",    T_OBJECT,    OFF(co_varnames),    READONLY},
  59.     {"co_filename",    T_OBJECT,    OFF(co_filename),    READONLY},
  60.     {"co_name",    T_OBJECT,    OFF(co_name),        READONLY},
  61.     {"co_firstlineno", T_INT,    OFF(co_firstlineno),    READONLY},
  62.     {"co_lnotab",    T_OBJECT,    OFF(co_lnotab),        READONLY},
  63.     {NULL}    /* Sentinel */
  64. };
  65.  
  66. static PyObject *
  67. code_getattr(PyCodeObject *co, char *name)
  68. {
  69.     return PyMember_Get((char *)co, code_memberlist, name);
  70. }
  71.  
  72. static void
  73. code_dealloc(PyCodeObject *co)
  74. {
  75.     Py_XDECREF(co->co_code);
  76.     Py_XDECREF(co->co_consts);
  77.     Py_XDECREF(co->co_names);
  78.     Py_XDECREF(co->co_varnames);
  79.     Py_XDECREF(co->co_filename);
  80.     Py_XDECREF(co->co_name);
  81.     Py_XDECREF(co->co_lnotab);
  82.     PyObject_DEL(co);
  83. }
  84.  
  85. static PyObject *
  86. code_repr(PyCodeObject *co)
  87. {
  88.     char buf[500];
  89.     int lineno = -1;
  90.     char *filename = "???";
  91.     char *name = "???";
  92.  
  93.     if (co->co_firstlineno != 0)
  94.         lineno = co->co_firstlineno;
  95.     if (co->co_filename && PyString_Check(co->co_filename))
  96.         filename = PyString_AsString(co->co_filename);
  97.     if (co->co_name && PyString_Check(co->co_name))
  98.         name = PyString_AsString(co->co_name);
  99.     sprintf(buf, "<code object %.100s at %p, file \"%.300s\", line %d>",
  100.         name, co, filename, lineno);
  101.     return PyString_FromString(buf);
  102. }
  103.  
  104. static int
  105. code_compare(PyCodeObject *co, PyCodeObject *cp)
  106. {
  107.     int cmp;
  108.     cmp = PyObject_Compare(co->co_name, cp->co_name);
  109.     if (cmp) return cmp;
  110.     cmp = co->co_argcount - cp->co_argcount;
  111.     if (cmp) return cmp;
  112.     cmp = co->co_nlocals - cp->co_nlocals;
  113.     if (cmp) return cmp;
  114.     cmp = co->co_flags - cp->co_flags;
  115.     if (cmp) return cmp;
  116.     cmp = PyObject_Compare(co->co_code, cp->co_code);
  117.     if (cmp) return cmp;
  118.     cmp = PyObject_Compare(co->co_consts, cp->co_consts);
  119.     if (cmp) return cmp;
  120.     cmp = PyObject_Compare(co->co_names, cp->co_names);
  121.     if (cmp) return cmp;
  122.     cmp = PyObject_Compare(co->co_varnames, cp->co_varnames);
  123.     return cmp;
  124. }
  125.  
  126. static long
  127. code_hash(PyCodeObject *co)
  128. {
  129.     long h, h0, h1, h2, h3, h4;
  130.     h0 = PyObject_Hash(co->co_name);
  131.     if (h0 == -1) return -1;
  132.     h1 = PyObject_Hash(co->co_code);
  133.     if (h1 == -1) return -1;
  134.     h2 = PyObject_Hash(co->co_consts);
  135.     if (h2 == -1) return -1;
  136.     h3 = PyObject_Hash(co->co_names);
  137.     if (h3 == -1) return -1;
  138.     h4 = PyObject_Hash(co->co_varnames);
  139.     if (h4 == -1) return -1;
  140.     h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^
  141.         co->co_argcount ^ co->co_nlocals ^ co->co_flags;
  142.     if (h == -1) h = -2;
  143.     return h;
  144. }
  145.  
  146. PyTypeObject PyCode_Type = {
  147.     PyObject_HEAD_INIT(&PyType_Type)
  148.     0,
  149.     "code",
  150.     sizeof(PyCodeObject),
  151.     0,
  152.     (destructor)code_dealloc, /*tp_dealloc*/
  153.     0,        /*tp_print*/
  154.     (getattrfunc)code_getattr, /*tp_getattr*/
  155.     0,        /*tp_setattr*/
  156.     (cmpfunc)code_compare, /*tp_compare*/
  157.     (reprfunc)code_repr, /*tp_repr*/
  158.     0,        /*tp_as_number*/
  159.     0,        /*tp_as_sequence*/
  160.     0,        /*tp_as_mapping*/
  161.     (hashfunc)code_hash, /*tp_hash*/
  162. };
  163.  
  164. #define NAME_CHARS \
  165.     "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
  166.  
  167. PyCodeObject *
  168. PyCode_New(int argcount, int nlocals, int stacksize, int flags,
  169.        PyObject *code, PyObject *consts, PyObject *names,
  170.        PyObject *varnames, PyObject *filename, PyObject *name,
  171.        int firstlineno, PyObject *lnotab)
  172. {
  173.     PyCodeObject *co;
  174.     int i;
  175.     PyBufferProcs *pb;
  176.     /* Check argument types */
  177.     if (argcount < 0 || nlocals < 0 ||
  178.         code == NULL ||
  179.         consts == NULL || !PyTuple_Check(consts) ||
  180.         names == NULL || !PyTuple_Check(names) ||
  181.         varnames == NULL || !PyTuple_Check(varnames) ||
  182.         name == NULL || !PyString_Check(name) ||
  183.         filename == NULL || !PyString_Check(filename) ||
  184.         lnotab == NULL || !PyString_Check(lnotab)) {
  185.         PyErr_BadInternalCall();
  186.         return NULL;
  187.     }
  188.     pb = code->ob_type->tp_as_buffer;
  189.     if (pb == NULL ||
  190.         pb->bf_getreadbuffer == NULL ||
  191.         pb->bf_getsegcount == NULL ||
  192.         (*pb->bf_getsegcount)(code, NULL) != 1)
  193.     {
  194.         PyErr_BadInternalCall();
  195.         return NULL;
  196.     }
  197.     /* Make sure names and varnames are all strings, & intern them */
  198.     for (i = PyTuple_Size(names); --i >= 0; ) {
  199.         PyObject *v = PyTuple_GetItem(names, i);
  200.         if (v == NULL || !PyString_Check(v)) {
  201.             PyErr_BadInternalCall();
  202.             return NULL;
  203.         }
  204.         PyString_InternInPlace(&PyTuple_GET_ITEM(names, i));
  205.     }
  206.     for (i = PyTuple_Size(varnames); --i >= 0; ) {
  207.         PyObject *v = PyTuple_GetItem(varnames, i);
  208.         if (v == NULL || !PyString_Check(v)) {
  209.             PyErr_BadInternalCall();
  210.             return NULL;
  211.         }
  212.         PyString_InternInPlace(&PyTuple_GET_ITEM(varnames, i));
  213.     }
  214.     /* Intern selected string constants */
  215.     for (i = PyTuple_Size(consts); --i >= 0; ) {
  216.         PyObject *v = PyTuple_GetItem(consts, i);
  217.         char *p;
  218.         if (!PyString_Check(v))
  219.             continue;
  220.         p = PyString_AsString(v);
  221.         if (strspn(p, NAME_CHARS)
  222.             != (size_t)PyString_Size(v))
  223.             continue;
  224.         PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i));
  225.     }
  226.     co = PyObject_NEW(PyCodeObject, &PyCode_Type);
  227.     if (co != NULL) {
  228.         co->co_argcount = argcount;
  229.         co->co_nlocals = nlocals;
  230.         co->co_stacksize = stacksize;
  231.         co->co_flags = flags;
  232.         Py_INCREF(code);
  233.         co->co_code = code;
  234.         Py_INCREF(consts);
  235.         co->co_consts = consts;
  236.         Py_INCREF(names);
  237.         co->co_names = names;
  238.         Py_INCREF(varnames);
  239.         co->co_varnames = varnames;
  240.         Py_INCREF(filename);
  241.         co->co_filename = filename;
  242.         Py_INCREF(name);
  243.         co->co_name = name;
  244.         co->co_firstlineno = firstlineno;
  245.         Py_INCREF(lnotab);
  246.         co->co_lnotab = lnotab;
  247.     }
  248.     return co;
  249. }
  250.  
  251.  
  252. /* Data structure used internally */
  253.  
  254. struct compiling {
  255.     PyObject *c_code;    /* string */
  256.     PyObject *c_consts;    /* list of objects */
  257.     PyObject *c_const_dict; /* inverse of c_consts */
  258.     PyObject *c_names;    /* list of strings (names) */
  259.     PyObject *c_name_dict;  /* inverse of c_names */
  260.     PyObject *c_globals;    /* dictionary (value=None) */
  261.     PyObject *c_locals;    /* dictionary (value=localID) */
  262.     PyObject *c_varnames;    /* list (inverse of c_locals) */
  263.     int c_nlocals;        /* index of next local */
  264.     int c_argcount;        /* number of top-level arguments */
  265.     int c_flags;        /* same as co_flags */
  266.     int c_nexti;        /* index into c_code */
  267.     int c_errors;        /* counts errors occurred */
  268.     int c_infunction;    /* set when compiling a function */
  269.     int c_interactive;    /* generating code for interactive command */
  270.     int c_loops;        /* counts nested loops */
  271.     int c_begin;        /* begin of current loop, for 'continue' */
  272.     int c_block[CO_MAXBLOCKS]; /* stack of block types */
  273.     int c_nblocks;        /* current block stack level */
  274.     char *c_filename;    /* filename of current node */
  275.     char *c_name;        /* name of object (e.g. function) */
  276.     int c_lineno;        /* Current line number */
  277.     int c_stacklevel;    /* Current stack level */
  278.     int c_maxstacklevel;    /* Maximum stack level */
  279.     int c_firstlineno;
  280.     PyObject *c_lnotab;    /* Table mapping address to line number */
  281.     int c_last_addr, c_last_line, c_lnotab_next;
  282. #ifdef PRIVATE_NAME_MANGLING
  283.     char *c_private;    /* for private name mangling */
  284. #endif
  285.     int c_tmpname;        /* temporary local name counter */
  286. };
  287.  
  288.  
  289. /* Error message including line number */
  290.  
  291. static void
  292. com_error(struct compiling *c, PyObject *exc, char *msg)
  293. {
  294.     PyObject *v, *tb, *tmp;
  295.     c->c_errors++;
  296.     if (c->c_lineno <= 1) {
  297.         /* Unknown line number or single interactive command */
  298.         PyErr_SetString(exc, msg);
  299.         return;
  300.     }
  301.     v = PyString_FromString(msg);
  302.     if (v == NULL)
  303.         return; /* MemoryError, too bad */
  304.     PyErr_SetObject(exc, v);
  305.     Py_DECREF(v);
  306.  
  307.     /* add attributes for the line number and filename for the error */
  308.     PyErr_Fetch(&exc, &v, &tb);
  309.     PyErr_NormalizeException(&exc, &v, &tb);
  310.     tmp = PyInt_FromLong(c->c_lineno);
  311.     if (tmp == NULL)
  312.         PyErr_Clear();
  313.     else {
  314.         if (PyObject_SetAttrString(v, "lineno", tmp))
  315.             PyErr_Clear();
  316.         Py_DECREF(tmp);
  317.     }
  318.     if (c->c_filename != NULL) {
  319.         tmp = PyString_FromString(c->c_filename);
  320.         if (tmp == NULL)
  321.             PyErr_Clear();
  322.         else {
  323.             if (PyObject_SetAttrString(v, "filename", tmp))
  324.                 PyErr_Clear();
  325.             Py_DECREF(tmp);
  326.         }
  327.     }
  328.     PyErr_Restore(exc, v, tb);
  329. }
  330.  
  331.  
  332. /* Interface to the block stack */
  333.  
  334. static void
  335. block_push(struct compiling *c, int type)
  336. {
  337.     if (c->c_nblocks >= CO_MAXBLOCKS) {
  338.         com_error(c, PyExc_SystemError,
  339.               "too many statically nested blocks");
  340.     }
  341.     else {
  342.         c->c_block[c->c_nblocks++] = type;
  343.     }
  344. }
  345.  
  346. static void
  347. block_pop(struct compiling *c, int type)
  348. {
  349.     if (c->c_nblocks > 0)
  350.         c->c_nblocks--;
  351.     if (c->c_block[c->c_nblocks] != type && c->c_errors == 0) {
  352.         com_error(c, PyExc_SystemError, "bad block pop");
  353.     }
  354. }
  355.  
  356.  
  357. /* Prototype forward declarations */
  358.  
  359. static int com_init(struct compiling *, char *);
  360. static void com_free(struct compiling *);
  361. static void com_push(struct compiling *, int);
  362. static void com_pop(struct compiling *, int);
  363. static void com_done(struct compiling *);
  364. static void com_node(struct compiling *, struct _node *);
  365. static void com_factor(struct compiling *, struct _node *);
  366. static void com_addbyte(struct compiling *, int);
  367. static void com_addint(struct compiling *, int);
  368. static void com_addoparg(struct compiling *, int, int);
  369. static void com_addfwref(struct compiling *, int, int *);
  370. static void com_backpatch(struct compiling *, int);
  371. static int com_add(struct compiling *, PyObject *, PyObject *, PyObject *);
  372. static int com_addconst(struct compiling *, PyObject *);
  373. static int com_addname(struct compiling *, PyObject *);
  374. static void com_addopname(struct compiling *, int, node *);
  375. static void com_list(struct compiling *, node *, int);
  376. static void com_list_iter(struct compiling *, node *, node *, char *);
  377. static int com_argdefs(struct compiling *, node *);
  378. static int com_newlocal(struct compiling *, char *);
  379. static void com_assign(struct compiling *, node *, int, node *);
  380. static void com_assign_name(struct compiling *, node *, int);
  381. static PyCodeObject *icompile(struct _node *, struct compiling *);
  382. static PyCodeObject *jcompile(struct _node *, char *,
  383.                   struct compiling *);
  384. static PyObject *parsestrplus(node *);
  385. static PyObject *parsestr(char *);
  386. static node *get_rawdocstring(node *);
  387.  
  388. static int
  389. com_init(struct compiling *c, char *filename)
  390. {
  391.     memset((void *)c, '\0', sizeof(struct compiling));
  392.     if ((c->c_code = PyString_FromStringAndSize((char *)NULL,
  393.                             1000)) == NULL)
  394.         goto fail;
  395.     if ((c->c_consts = PyList_New(0)) == NULL)
  396.         goto fail;
  397.     if ((c->c_const_dict = PyDict_New()) == NULL)
  398.         goto fail;
  399.     if ((c->c_names = PyList_New(0)) == NULL)
  400.         goto fail;
  401.     if ((c->c_name_dict = PyDict_New()) == NULL)
  402.         goto fail;
  403.     if ((c->c_globals = PyDict_New()) == NULL)
  404.         goto fail;
  405.     if ((c->c_locals = PyDict_New()) == NULL)
  406.         goto fail;
  407.     if ((c->c_varnames = PyList_New(0)) == NULL)
  408.         goto fail;
  409.     if ((c->c_lnotab = PyString_FromStringAndSize((char *)NULL,
  410.                               1000)) == NULL)
  411.         goto fail;
  412.     c->c_nlocals = 0;
  413.     c->c_argcount = 0;
  414.     c->c_flags = 0;
  415.     c->c_nexti = 0;
  416.     c->c_errors = 0;
  417.     c->c_infunction = 0;
  418.     c->c_interactive = 0;
  419.     c->c_loops = 0;
  420.     c->c_begin = 0;
  421.     c->c_nblocks = 0;
  422.     c->c_filename = filename;
  423.     c->c_name = "?";
  424.     c->c_lineno = 0;
  425.     c->c_stacklevel = 0;
  426.     c->c_maxstacklevel = 0;
  427.     c->c_firstlineno = 0;
  428.     c->c_last_addr = 0;
  429.     c->c_last_line = 0;
  430.     c-> c_lnotab_next = 0;
  431.     c->c_tmpname = 0;
  432.     return 1;
  433.     
  434.   fail:
  435.     com_free(c);
  436.      return 0;
  437. }
  438.  
  439. static void
  440. com_free(struct compiling *c)
  441. {
  442.     Py_XDECREF(c->c_code);
  443.     Py_XDECREF(c->c_consts);
  444.     Py_XDECREF(c->c_const_dict);
  445.     Py_XDECREF(c->c_names);
  446.     Py_XDECREF(c->c_name_dict);
  447.     Py_XDECREF(c->c_globals);
  448.     Py_XDECREF(c->c_locals);
  449.     Py_XDECREF(c->c_varnames);
  450.     Py_XDECREF(c->c_lnotab);
  451. }
  452.  
  453. static void
  454. com_push(struct compiling *c, int n)
  455. {
  456.     c->c_stacklevel += n;
  457.     if (c->c_stacklevel > c->c_maxstacklevel)
  458.         c->c_maxstacklevel = c->c_stacklevel;
  459. }
  460.  
  461. static void
  462. com_pop(struct compiling *c, int n)
  463. {
  464.     if (c->c_stacklevel < n) {
  465.         /* fprintf(stderr,
  466.             "%s:%d: underflow! nexti=%d, level=%d, n=%d\n",
  467.             c->c_filename, c->c_lineno,
  468.             c->c_nexti, c->c_stacklevel, n); */
  469.         c->c_stacklevel = 0;
  470.     }
  471.     else
  472.         c->c_stacklevel -= n;
  473. }
  474.  
  475. static void
  476. com_done(struct compiling *c)
  477. {
  478.     if (c->c_code != NULL)
  479.         _PyString_Resize(&c->c_code, c->c_nexti);
  480.     if (c->c_lnotab != NULL)
  481.         _PyString_Resize(&c->c_lnotab, c->c_lnotab_next);
  482. }
  483.  
  484. static void
  485. com_addbyte(struct compiling *c, int byte)
  486. {
  487.     int len;
  488.     /*fprintf(stderr, "%3d: %3d\n", c->c_nexti, byte);*/
  489.     if (byte < 0 || byte > 255) {
  490.         /*
  491.         fprintf(stderr, "XXX compiling bad byte: %d\n", byte);
  492.         fatal("com_addbyte: byte out of range");
  493.         */
  494.         com_error(c, PyExc_SystemError,
  495.               "com_addbyte: byte out of range");
  496.     }
  497.     if (c->c_code == NULL)
  498.         return;
  499.     len = PyString_Size(c->c_code);
  500.     if (c->c_nexti >= len) {
  501.         if (_PyString_Resize(&c->c_code, len+1000) != 0) {
  502.             c->c_errors++;
  503.             return;
  504.         }
  505.     }
  506.     PyString_AsString(c->c_code)[c->c_nexti++] = byte;
  507. }
  508.  
  509. static void
  510. com_addint(struct compiling *c, int x)
  511. {
  512.     com_addbyte(c, x & 0xff);
  513.     com_addbyte(c, x >> 8); /* XXX x should be positive */
  514. }
  515.  
  516. static void
  517. com_add_lnotab(struct compiling *c, int addr, int line)
  518. {
  519.     int size;
  520.     char *p;
  521.     if (c->c_lnotab == NULL)
  522.         return;
  523.     size = PyString_Size(c->c_lnotab);
  524.     if (c->c_lnotab_next+2 > size) {
  525.         if (_PyString_Resize(&c->c_lnotab, size + 1000) < 0) {
  526.             c->c_errors++;
  527.             return;
  528.         }
  529.     }
  530.     p = PyString_AsString(c->c_lnotab) + c->c_lnotab_next;
  531.     *p++ = addr;
  532.     *p++ = line;
  533.     c->c_lnotab_next += 2;
  534. }
  535.  
  536. static void
  537. com_set_lineno(struct compiling *c, int lineno)
  538. {
  539.     c->c_lineno = lineno;
  540.     if (c->c_firstlineno == 0) {
  541.         c->c_firstlineno = c->c_last_line = lineno;
  542.     }
  543.     else {
  544.         int incr_addr = c->c_nexti - c->c_last_addr;
  545.         int incr_line = lineno - c->c_last_line;
  546.         while (incr_addr > 0 || incr_line > 0) {
  547.             int trunc_addr = incr_addr;
  548.             int trunc_line = incr_line;
  549.             if (trunc_addr > 255)
  550.                 trunc_addr = 255;
  551.             if (trunc_line > 255)
  552.                 trunc_line = 255;
  553.             com_add_lnotab(c, trunc_addr, trunc_line);
  554.             incr_addr -= trunc_addr;
  555.             incr_line -= trunc_line;
  556.         }
  557.         c->c_last_addr = c->c_nexti;
  558.         c->c_last_line = lineno;
  559.     }
  560. }
  561.  
  562. static void
  563. com_addoparg(struct compiling *c, int op, int arg)
  564. {
  565.     int extended_arg = arg >> 16;
  566.     if (op == SET_LINENO) {
  567.         com_set_lineno(c, arg);
  568.         if (Py_OptimizeFlag)
  569.             return;
  570.     }
  571.     if (extended_arg){
  572.         com_addbyte(c, EXTENDED_ARG);
  573.         com_addint(c, extended_arg);
  574.         arg &= 0xffff;
  575.     }
  576.     com_addbyte(c, op);
  577.     com_addint(c, arg);
  578. }
  579.  
  580. static void
  581. com_addfwref(struct compiling *c, int op, int *p_anchor)
  582. {
  583.     /* Compile a forward reference for backpatching */
  584.     int here;
  585.     int anchor;
  586.     com_addbyte(c, op);
  587.     here = c->c_nexti;
  588.     anchor = *p_anchor;
  589.     *p_anchor = here;
  590.     com_addint(c, anchor == 0 ? 0 : here - anchor);
  591. }
  592.  
  593. static void
  594. com_backpatch(struct compiling *c, int anchor)
  595. {
  596.     unsigned char *code = (unsigned char *) PyString_AsString(c->c_code);
  597.     int target = c->c_nexti;
  598.     int dist;
  599.     int prev;
  600.     for (;;) {
  601.         /* Make the JUMP instruction at anchor point to target */
  602.         prev = code[anchor] + (code[anchor+1] << 8);
  603.         dist = target - (anchor+2);
  604.         code[anchor] = dist & 0xff;
  605.         dist >>= 8;
  606.         code[anchor+1] = dist;
  607.         dist >>= 8;
  608.         if (dist) {
  609.             com_error(c, PyExc_SystemError,
  610.                   "com_backpatch: offset too large");
  611.             break;
  612.         }
  613.         if (!prev)
  614.             break;
  615.         anchor -= prev;
  616.     }
  617. }
  618.  
  619. /* Handle literals and names uniformly */
  620.  
  621. static int
  622. com_add(struct compiling *c, PyObject *list, PyObject *dict, PyObject *v)
  623. {
  624.     PyObject *w, *t, *np=NULL;
  625.     long n;
  626.  
  627.     t = Py_BuildValue("(OO)", v, v->ob_type);
  628.     if (t == NULL)
  629.         goto fail;
  630.     w = PyDict_GetItem(dict, t);
  631.     if (w != NULL) {
  632.         n = PyInt_AsLong(w);
  633.     } else {
  634.         n = PyList_Size(list);
  635.         np = PyInt_FromLong(n);
  636.         if (np == NULL)
  637.             goto fail;
  638.         if (PyList_Append(list, v) != 0)
  639.             goto fail;
  640.         if (PyDict_SetItem(dict, t, np) != 0)
  641.             goto fail;
  642.         Py_DECREF(np);
  643.     }
  644.     Py_DECREF(t);
  645.     return n;
  646.   fail:
  647.     Py_XDECREF(np);
  648.     Py_XDECREF(t);
  649.     c->c_errors++;
  650.     return 0;
  651. }
  652.  
  653. static int
  654. com_addconst(struct compiling *c, PyObject *v)
  655. {
  656.     return com_add(c, c->c_consts, c->c_const_dict, v);
  657. }
  658.  
  659. static int
  660. com_addname(struct compiling *c, PyObject *v)
  661. {
  662.     return com_add(c, c->c_names, c->c_name_dict, v);
  663. }
  664.  
  665. #ifdef PRIVATE_NAME_MANGLING
  666. static int
  667. com_mangle(struct compiling *c, char *name, char *buffer, size_t maxlen)
  668. {
  669.     /* Name mangling: __private becomes _classname__private.
  670.        This is independent from how the name is used. */
  671.     char *p;
  672.     size_t nlen, plen;
  673.     nlen = strlen(name);
  674.     if (nlen+2 >= maxlen)
  675.         return 0; /* Don't mangle __extremely_long_names */
  676.     if (name[nlen-1] == '_' && name[nlen-2] == '_')
  677.         return 0; /* Don't mangle __whatever__ */
  678.     p = c->c_private;
  679.     /* Strip leading underscores from class name */
  680.     while (*p == '_')
  681.         p++;
  682.     if (*p == '\0')
  683.         return 0; /* Don't mangle if class is just underscores */
  684.     plen = strlen(p);
  685.     if (plen + nlen >= maxlen)
  686.         plen = maxlen-nlen-2; /* Truncate class name if too long */
  687.     /* buffer = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
  688.     buffer[0] = '_';
  689.     strncpy(buffer+1, p, plen);
  690.     strcpy(buffer+1+plen, name);
  691.     /* fprintf(stderr, "mangle %s -> %s\n", name, buffer); */
  692.     return 1;
  693. }
  694. #endif
  695.  
  696. static void
  697. com_addopnamestr(struct compiling *c, int op, char *name)
  698. {
  699.     PyObject *v;
  700.     int i;
  701. #ifdef PRIVATE_NAME_MANGLING
  702.     char buffer[256];
  703.     if (name != NULL && name[0] == '_' && name[1] == '_' &&
  704.         c->c_private != NULL &&
  705.         com_mangle(c, name, buffer, sizeof(buffer)))
  706.         name = buffer;
  707. #endif
  708.     if (name == NULL || (v = PyString_InternFromString(name)) == NULL) {
  709.         c->c_errors++;
  710.         i = 255;
  711.     }
  712.     else {
  713.         i = com_addname(c, v);
  714.         Py_DECREF(v);
  715.     }
  716.     /* Hack to replace *_NAME opcodes by *_GLOBAL if necessary */
  717.     switch (op) {
  718.     case LOAD_NAME:
  719.     case STORE_NAME:
  720.     case DELETE_NAME:
  721.         if (PyDict_GetItemString(c->c_globals, name) != NULL) {
  722.             switch (op) {
  723.             case LOAD_NAME:   op = LOAD_GLOBAL;   break;
  724.             case STORE_NAME:  op = STORE_GLOBAL;  break;
  725.             case DELETE_NAME: op = DELETE_GLOBAL; break;
  726.             }
  727.         }
  728.     }
  729.     com_addoparg(c, op, i);
  730. }
  731.  
  732. static void
  733. com_addopname(struct compiling *c, int op, node *n)
  734. {
  735.     char *name;
  736.     char buffer[1000];
  737.     /* XXX it is possible to write this code without the 1000
  738.        chars on the total length of dotted names, I just can't be
  739.        bothered right now */
  740.     if (TYPE(n) == STAR)
  741.         name = "*";
  742.     else if (TYPE(n) == dotted_name) {
  743.         char *p = buffer;
  744.         int i;
  745.         name = buffer;
  746.         for (i = 0; i < NCH(n); i += 2) {
  747.             char *s = STR(CHILD(n, i));
  748.             if (p + strlen(s) > buffer + (sizeof buffer) - 2) {
  749.                 com_error(c, PyExc_MemoryError,
  750.                       "dotted_name too long");
  751.                 name = NULL;
  752.                 break;
  753.             }
  754.             if (p != buffer)
  755.                 *p++ = '.';
  756.             strcpy(p, s);
  757.             p = strchr(p, '\0');
  758.         }
  759.     }
  760.     else {
  761.         REQ(n, NAME);
  762.         name = STR(n);
  763.     }
  764.     com_addopnamestr(c, op, name);
  765. }
  766.  
  767. static PyObject *
  768. parsenumber(struct compiling *co, char *s)
  769. {
  770.     extern double atof(const char *);
  771.     char *end;
  772.     long x;
  773.     double dx;
  774. #ifndef WITHOUT_COMPLEX
  775.     Py_complex c;
  776.     int imflag;
  777. #endif
  778.  
  779.     errno = 0;
  780.     end = s + strlen(s) - 1;
  781. #ifndef WITHOUT_COMPLEX
  782.     imflag = *end == 'j' || *end == 'J';
  783. #endif
  784.     if (*end == 'l' || *end == 'L')
  785.         return PyLong_FromString(s, (char **)0, 0);
  786.     if (s[0] == '0')
  787.         x = (long) PyOS_strtoul(s, &end, 0);
  788.     else
  789.         x = PyOS_strtol(s, &end, 0);
  790.     if (*end == '\0') {
  791.         if (errno != 0) {
  792.             com_error(co, PyExc_OverflowError,
  793.                   "integer literal too large");
  794.             return NULL;
  795.         }
  796.         return PyInt_FromLong(x);
  797.     }
  798.     /* XXX Huge floats may silently fail */
  799. #ifndef WITHOUT_COMPLEX
  800.     if (imflag) {
  801.         c.real = 0.;
  802.         PyFPE_START_PROTECT("atof", return 0)
  803.         c.imag = atof(s);
  804.         PyFPE_END_PROTECT(c)
  805.         return PyComplex_FromCComplex(c);
  806.     }
  807.     else
  808. #endif
  809.     {
  810.         PyFPE_START_PROTECT("atof", return 0)
  811.         dx = atof(s);
  812.         PyFPE_END_PROTECT(dx)
  813.         return PyFloat_FromDouble(dx);
  814.     }
  815. }
  816.  
  817. static PyObject *
  818. parsestr(char *s)
  819. {
  820.     PyObject *v;
  821.     size_t len;
  822.     char *buf;
  823.     char *p;
  824.     char *end;
  825.     int c;
  826.     int first = *s;
  827.     int quote = first;
  828.     int rawmode = 0;
  829.     int unicode = 0;
  830.     if (isalpha(quote) || quote == '_') {
  831.         if (quote == 'u' || quote == 'U') {
  832.             quote = *++s;
  833.             unicode = 1;
  834.         }
  835.         if (quote == 'r' || quote == 'R') {
  836.             quote = *++s;
  837.             rawmode = 1;
  838.         }
  839.     }
  840.     if (quote != '\'' && quote != '\"') {
  841.         PyErr_BadInternalCall();
  842.         return NULL;
  843.     }
  844.     s++;
  845.     len = strlen(s);
  846.     if (len > INT_MAX) {
  847.         PyErr_SetString(PyExc_OverflowError, "string to parse is too long");
  848.         return NULL;
  849.     }
  850.     if (s[--len] != quote) {
  851.         PyErr_BadInternalCall();
  852.         return NULL;
  853.     }
  854.     if (len >= 4 && s[0] == quote && s[1] == quote) {
  855.         s += 2;
  856.         len -= 2;
  857.         if (s[--len] != quote || s[--len] != quote) {
  858.             PyErr_BadInternalCall();
  859.             return NULL;
  860.         }
  861.     }
  862.     if (unicode || Py_UnicodeFlag) {
  863.         if (rawmode)
  864.             return PyUnicode_DecodeRawUnicodeEscape(
  865.                 s, len, NULL);
  866.         else
  867.             return PyUnicode_DecodeUnicodeEscape(
  868.                 s, len, NULL);
  869.     }
  870.     if (rawmode || strchr(s, '\\') == NULL)
  871.         return PyString_FromStringAndSize(s, len);
  872.     v = PyString_FromStringAndSize((char *)NULL, len);
  873.     if (v == NULL)
  874.         return NULL;
  875.     p = buf = PyString_AsString(v);
  876.     end = s + len;
  877.     while (s < end) {
  878.         if (*s != '\\') {
  879.             *p++ = *s++;
  880.             continue;
  881.         }
  882.         s++;
  883.         switch (*s++) {
  884.         /* XXX This assumes ASCII! */
  885.         case '\n': break;
  886.         case '\\': *p++ = '\\'; break;
  887.         case '\'': *p++ = '\''; break;
  888.         case '\"': *p++ = '\"'; break;
  889.         case 'b': *p++ = '\b'; break;
  890.         case 'f': *p++ = '\014'; break; /* FF */
  891.         case 't': *p++ = '\t'; break;
  892.         case 'n': *p++ = '\n'; break;
  893.         case 'r': *p++ = '\r'; break;
  894.         case 'v': *p++ = '\013'; break; /* VT */
  895.         case 'a': *p++ = '\007'; break; /* BEL, not classic C */
  896.         case '0': case '1': case '2': case '3':
  897.         case '4': case '5': case '6': case '7':
  898.             c = s[-1] - '0';
  899.             if ('0' <= *s && *s <= '7') {
  900.                 c = (c<<3) + *s++ - '0';
  901.                 if ('0' <= *s && *s <= '7')
  902.                     c = (c<<3) + *s++ - '0';
  903.             }
  904.             *p++ = c;
  905.             break;
  906.         case 'x':
  907.             if (isxdigit(Py_CHARMASK(s[0])) && isxdigit(Py_CHARMASK(s[1]))) {
  908.                 unsigned int x = 0;
  909.                 c = Py_CHARMASK(*s);
  910.                 s++;
  911.                 if (isdigit(c))
  912.                     x = c - '0';
  913.                 else if (islower(c))
  914.                     x = 10 + c - 'a';
  915.                 else
  916.                     x = 10 + c - 'A';
  917.                 x = x << 4;
  918.                 c = Py_CHARMASK(*s);
  919.                 s++;
  920.                 if (isdigit(c))
  921.                     x += c - '0';
  922.                 else if (islower(c))
  923.                     x += 10 + c - 'a';
  924.                 else
  925.                     x += 10 + c - 'A';
  926.                 *p++ = x;
  927.                 break;
  928.             }
  929.             PyErr_SetString(PyExc_ValueError, "invalid \\x escape");
  930.             Py_DECREF(v);
  931.             return NULL;
  932.         default:
  933.             *p++ = '\\';
  934.             *p++ = s[-1];
  935.             break;
  936.         }
  937.     }
  938.     _PyString_Resize(&v, (int)(p - buf));
  939.     return v;
  940. }
  941.  
  942. static PyObject *
  943. parsestrplus(node *n)
  944. {
  945.     PyObject *v;
  946.     int i;
  947.     REQ(CHILD(n, 0), STRING);
  948.     if ((v = parsestr(STR(CHILD(n, 0)))) != NULL) {
  949.         /* String literal concatenation */
  950.         for (i = 1; i < NCH(n); i++) {
  951.             PyObject *s;
  952.             s = parsestr(STR(CHILD(n, i)));
  953.             if (s == NULL)
  954.             goto onError;
  955.             if (PyString_Check(v) && PyString_Check(s)) {
  956.             PyString_ConcatAndDel(&v, s);
  957.             if (v == NULL)
  958.                 goto onError;
  959.             }
  960.             else {
  961.             PyObject *temp;
  962.             temp = PyUnicode_Concat(v, s);
  963.             Py_DECREF(s);
  964.             if (temp == NULL)
  965.                 goto onError;
  966.             Py_DECREF(v);
  967.             v = temp;
  968.             }
  969.         }
  970.     }
  971.     return v;
  972.  
  973.  onError:
  974.     Py_XDECREF(v);
  975.     return NULL;
  976. }
  977.  
  978. static void
  979. com_list_for(struct compiling *c, node *n, node *e, char *t)
  980. {
  981.     PyObject *v;
  982.     int anchor = 0;
  983.     int save_begin = c->c_begin;
  984.  
  985.     /* list_iter: for v in expr [list_iter] */
  986.     com_node(c, CHILD(n, 3)); /* expr */
  987.     v = PyInt_FromLong(0L);
  988.     if (v == NULL)
  989.         c->c_errors++;
  990.     com_addoparg(c, LOAD_CONST, com_addconst(c, v));
  991.     com_push(c, 1);
  992.     Py_XDECREF(v);
  993.     c->c_begin = c->c_nexti;
  994.     com_addoparg(c, SET_LINENO, n->n_lineno);
  995.     com_addfwref(c, FOR_LOOP, &anchor);
  996.     com_push(c, 1);
  997.     com_assign(c, CHILD(n, 1), OP_ASSIGN, NULL);
  998.     c->c_loops++;
  999.     com_list_iter(c, n, e, t);
  1000.     c->c_loops--;
  1001.     com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  1002.     c->c_begin = save_begin;
  1003.     com_backpatch(c, anchor);
  1004.     com_pop(c, 2); /* FOR_LOOP has popped these */
  1005. }  
  1006.  
  1007. static void
  1008. com_list_if(struct compiling *c, node *n, node *e, char *t)
  1009. {
  1010.     int anchor = 0;
  1011.     int a = 0;
  1012.     /* list_iter: 'if' test [list_iter] */
  1013.     com_addoparg(c, SET_LINENO, n->n_lineno);
  1014.     com_node(c, CHILD(n, 1));
  1015.     com_addfwref(c, JUMP_IF_FALSE, &a);
  1016.     com_addbyte(c, POP_TOP);
  1017.     com_pop(c, 1);
  1018.     com_list_iter(c, n, e, t);
  1019.     com_addfwref(c, JUMP_FORWARD, &anchor);
  1020.     com_backpatch(c, a);
  1021.     /* We jump here with an extra entry which we now pop */
  1022.     com_addbyte(c, POP_TOP);
  1023.     com_backpatch(c, anchor);
  1024. }
  1025.  
  1026. static void
  1027. com_list_iter(struct compiling *c,
  1028.           node *p,        /* parent of list_iter node */
  1029.           node *e,        /* element expression node */
  1030.           char *t        /* name of result list temp local */)
  1031. {
  1032.     /* list_iter is the last child in a listmaker, list_for, or list_if */
  1033.     node *n = CHILD(p, NCH(p)-1);
  1034.     if (TYPE(n) == list_iter) {
  1035.         n = CHILD(n, 0);
  1036.         switch (TYPE(n)) {
  1037.         case list_for: 
  1038.             com_list_for(c, n, e, t);
  1039.             break;
  1040.         case list_if:
  1041.             com_list_if(c, n, e, t);
  1042.             break;
  1043.         default:
  1044.             com_error(c, PyExc_SystemError,
  1045.                   "invalid list_iter node type");
  1046.         }
  1047.     }
  1048.     else {
  1049.         com_addopnamestr(c, LOAD_NAME, t);
  1050.         com_push(c, 1);
  1051.         com_node(c, e);
  1052.         com_addoparg(c, CALL_FUNCTION, 1);
  1053.         com_addbyte(c, POP_TOP);
  1054.         com_pop(c, 2);
  1055.     }
  1056. }
  1057.  
  1058. static void
  1059. com_list_comprehension(struct compiling *c, node *n)
  1060. {
  1061.     /* listmaker: test list_for */
  1062.     char tmpname[12];
  1063.     sprintf(tmpname, "__%d__", ++c->c_tmpname);
  1064.     com_addoparg(c, BUILD_LIST, 0);
  1065.     com_addbyte(c, DUP_TOP); /* leave the result on the stack */
  1066.     com_push(c, 2);
  1067.     com_addopnamestr(c, LOAD_ATTR, "append");
  1068.     com_addopnamestr(c, STORE_NAME, tmpname);
  1069.     com_pop(c, 1);
  1070.     com_list_for(c, CHILD(n, 1), CHILD(n, 0), tmpname);
  1071.     com_addopnamestr(c, DELETE_NAME, tmpname);
  1072.     --c->c_tmpname;
  1073. }
  1074.  
  1075. static void
  1076. com_listmaker(struct compiling *c, node *n)
  1077. {
  1078.     /* listmaker: test ( list_for | (',' test)* [','] ) */
  1079.     if (NCH(n) > 1 && TYPE(CHILD(n, 1)) == list_for)
  1080.         com_list_comprehension(c, n);
  1081.     else {
  1082.         int len = 0;
  1083.         int i;
  1084.         for (i = 0; i < NCH(n); i += 2, len++)
  1085.             com_node(c, CHILD(n, i));
  1086.         com_addoparg(c, BUILD_LIST, len);
  1087.         com_pop(c, len-1);
  1088.     }
  1089. }
  1090.  
  1091. static void
  1092. com_dictmaker(struct compiling *c, node *n)
  1093. {
  1094.     int i;
  1095.     /* dictmaker: test ':' test (',' test ':' value)* [','] */
  1096.     for (i = 0; i+2 < NCH(n); i += 4) {
  1097.         /* We must arrange things just right for STORE_SUBSCR.
  1098.            It wants the stack to look like (value) (dict) (key) */
  1099.         com_addbyte(c, DUP_TOP);
  1100.         com_push(c, 1);
  1101.         com_node(c, CHILD(n, i+2)); /* value */
  1102.         com_addbyte(c, ROT_TWO);
  1103.         com_node(c, CHILD(n, i)); /* key */
  1104.         com_addbyte(c, STORE_SUBSCR);
  1105.         com_pop(c, 3);
  1106.     }
  1107. }
  1108.  
  1109. static void
  1110. com_atom(struct compiling *c, node *n)
  1111. {
  1112.     node *ch;
  1113.     PyObject *v;
  1114.     int i;
  1115.     REQ(n, atom);
  1116.     ch = CHILD(n, 0);
  1117.     switch (TYPE(ch)) {
  1118.     case LPAR:
  1119.         if (TYPE(CHILD(n, 1)) == RPAR) {
  1120.             com_addoparg(c, BUILD_TUPLE, 0);
  1121.             com_push(c, 1);
  1122.         }
  1123.         else
  1124.             com_node(c, CHILD(n, 1));
  1125.         break;
  1126.     case LSQB: /* '[' [listmaker] ']' */
  1127.         if (TYPE(CHILD(n, 1)) == RSQB) {
  1128.             com_addoparg(c, BUILD_LIST, 0);
  1129.             com_push(c, 1);
  1130.         }
  1131.         else
  1132.             com_listmaker(c, CHILD(n, 1));
  1133.         break;
  1134.     case LBRACE: /* '{' [dictmaker] '}' */
  1135.         com_addoparg(c, BUILD_MAP, 0);
  1136.         com_push(c, 1);
  1137.         if (TYPE(CHILD(n, 1)) == dictmaker)
  1138.             com_dictmaker(c, CHILD(n, 1));
  1139.         break;
  1140.     case BACKQUOTE:
  1141.         com_node(c, CHILD(n, 1));
  1142.         com_addbyte(c, UNARY_CONVERT);
  1143.         break;
  1144.     case NUMBER:
  1145.         if ((v = parsenumber(c, STR(ch))) == NULL) {
  1146.             i = 255;
  1147.         }
  1148.         else {
  1149.             i = com_addconst(c, v);
  1150.             Py_DECREF(v);
  1151.         }
  1152.         com_addoparg(c, LOAD_CONST, i);
  1153.         com_push(c, 1);
  1154.         break;
  1155.     case STRING:
  1156.         v = parsestrplus(n);
  1157.         if (v == NULL) {
  1158.             c->c_errors++;
  1159.             i = 255;
  1160.         }
  1161.         else {
  1162.             i = com_addconst(c, v);
  1163.             Py_DECREF(v);
  1164.         }
  1165.         com_addoparg(c, LOAD_CONST, i);
  1166.         com_push(c, 1);
  1167.         break;
  1168.     case NAME:
  1169.         com_addopname(c, LOAD_NAME, ch);
  1170.         com_push(c, 1);
  1171.         break;
  1172.     default:
  1173.         /* XXX fprintf(stderr, "node type %d\n", TYPE(ch)); */
  1174.         com_error(c, PyExc_SystemError,
  1175.               "com_atom: unexpected node type");
  1176.     }
  1177. }
  1178.  
  1179. static void
  1180. com_slice(struct compiling *c, node *n, int op)
  1181. {
  1182.     if (NCH(n) == 1) {
  1183.         com_addbyte(c, op);
  1184.     }
  1185.     else if (NCH(n) == 2) {
  1186.         if (TYPE(CHILD(n, 0)) != COLON) {
  1187.             com_node(c, CHILD(n, 0));
  1188.             com_addbyte(c, op+1);
  1189.         }
  1190.         else {
  1191.             com_node(c, CHILD(n, 1));
  1192.             com_addbyte(c, op+2);
  1193.         }
  1194.         com_pop(c, 1);
  1195.     }
  1196.     else {
  1197.         com_node(c, CHILD(n, 0));
  1198.         com_node(c, CHILD(n, 2));
  1199.         com_addbyte(c, op+3);
  1200.         com_pop(c, 2);
  1201.     }
  1202. }
  1203.  
  1204. static void
  1205. com_augassign_slice(struct compiling *c, node *n, int opcode, node *augn)
  1206. {
  1207.     if (NCH(n) == 1) {
  1208.         com_addbyte(c, DUP_TOP);
  1209.         com_push(c, 1);
  1210.         com_addbyte(c, SLICE);
  1211.         com_node(c, augn);
  1212.         com_addbyte(c, opcode);
  1213.         com_pop(c, 1);
  1214.         com_addbyte(c, ROT_TWO);
  1215.         com_addbyte(c, STORE_SLICE);
  1216.         com_pop(c, 2);
  1217.     } else if (NCH(n) == 2 && TYPE(CHILD(n, 0)) != COLON) {
  1218.         com_node(c, CHILD(n, 0));
  1219.         com_addoparg(c, DUP_TOPX, 2);
  1220.         com_push(c, 2);
  1221.         com_addbyte(c, SLICE+1);
  1222.         com_pop(c, 1);
  1223.         com_node(c, augn);
  1224.         com_addbyte(c, opcode);
  1225.         com_pop(c, 1);
  1226.         com_addbyte(c, ROT_THREE);
  1227.         com_addbyte(c, STORE_SLICE+1);
  1228.         com_pop(c, 3);
  1229.     } else if (NCH(n) == 2) {
  1230.         com_node(c, CHILD(n, 1));
  1231.         com_addoparg(c, DUP_TOPX, 2);
  1232.         com_push(c, 2);
  1233.         com_addbyte(c, SLICE+2);
  1234.         com_pop(c, 1);
  1235.         com_node(c, augn);
  1236.         com_addbyte(c, opcode);
  1237.         com_pop(c, 1);
  1238.         com_addbyte(c, ROT_THREE);
  1239.         com_addbyte(c, STORE_SLICE+2);
  1240.         com_pop(c, 3);
  1241.     } else {
  1242.         com_node(c, CHILD(n, 0));
  1243.         com_node(c, CHILD(n, 2));
  1244.         com_addoparg(c, DUP_TOPX, 3);
  1245.         com_push(c, 3);
  1246.         com_addbyte(c, SLICE+3);
  1247.         com_pop(c, 2);
  1248.         com_node(c, augn);
  1249.         com_addbyte(c, opcode);
  1250.         com_pop(c, 1);
  1251.         com_addbyte(c, ROT_FOUR);
  1252.         com_addbyte(c, STORE_SLICE+3);
  1253.         com_pop(c, 4);
  1254.     }
  1255. }
  1256.  
  1257. static void
  1258. com_argument(struct compiling *c, node *n, PyObject **pkeywords)
  1259. {
  1260.     node *m;
  1261.     REQ(n, argument); /* [test '='] test; really [keyword '='] test */
  1262.     if (NCH(n) == 1) {
  1263.         if (*pkeywords != NULL) {
  1264.             com_error(c, PyExc_SyntaxError,
  1265.                   "non-keyword arg after keyword arg");
  1266.         }
  1267.         else {
  1268.             com_node(c, CHILD(n, 0));
  1269.         }
  1270.         return;
  1271.     }
  1272.     m = n;
  1273.     do {
  1274.         m = CHILD(m, 0);
  1275.     } while (NCH(m) == 1);
  1276.     if (TYPE(m) != NAME) {
  1277.         com_error(c, PyExc_SyntaxError,
  1278.               "keyword can't be an expression");
  1279.     }
  1280.     else {
  1281.         PyObject *v = PyString_InternFromString(STR(m));
  1282.         if (v != NULL && *pkeywords == NULL)
  1283.             *pkeywords = PyDict_New();
  1284.         if (v == NULL || *pkeywords == NULL)
  1285.             c->c_errors++;
  1286.         else {
  1287.             if (PyDict_GetItem(*pkeywords, v) != NULL)
  1288.                 com_error(c, PyExc_SyntaxError,
  1289.                       "duplicate keyword argument");
  1290.             else
  1291.                 if (PyDict_SetItem(*pkeywords, v, v) != 0)
  1292.                     c->c_errors++;
  1293.             com_addoparg(c, LOAD_CONST, com_addconst(c, v));
  1294.             com_push(c, 1);
  1295.             Py_DECREF(v);
  1296.         }
  1297.     }
  1298.     com_node(c, CHILD(n, 2));
  1299. }
  1300.  
  1301. static void
  1302. com_call_function(struct compiling *c, node *n)
  1303. {
  1304.     if (TYPE(n) == RPAR) {
  1305.         com_addoparg(c, CALL_FUNCTION, 0);
  1306.     }
  1307.     else {
  1308.         PyObject *keywords = NULL;
  1309.         int i, na, nk;
  1310.         int lineno = n->n_lineno;
  1311.         int star_flag = 0;
  1312.         int starstar_flag = 0;
  1313.         int opcode;
  1314.         REQ(n, arglist);
  1315.         na = 0;
  1316.         nk = 0;
  1317.         for (i = 0; i < NCH(n); i += 2) {
  1318.             node *ch = CHILD(n, i);
  1319.             if (TYPE(ch) == STAR ||
  1320.                 TYPE(ch) == DOUBLESTAR)
  1321.               break;
  1322.             if (ch->n_lineno != lineno) {
  1323.                 lineno = ch->n_lineno;
  1324.                 com_addoparg(c, SET_LINENO, lineno);
  1325.             }
  1326.             com_argument(c, ch, &keywords);
  1327.             if (keywords == NULL)
  1328.                 na++;
  1329.             else
  1330.                 nk++;
  1331.         }
  1332.         Py_XDECREF(keywords);
  1333.         while (i < NCH(n)) {
  1334.             node *tok = CHILD(n, i);
  1335.             node *ch = CHILD(n, i+1);
  1336.             i += 3;
  1337.             switch (TYPE(tok)) {
  1338.             case STAR:       star_flag = 1;     break;
  1339.             case DOUBLESTAR: starstar_flag = 1;    break;
  1340.             }
  1341.             com_node(c, ch);
  1342.         }
  1343.         if (na > 255 || nk > 255) {
  1344.             com_error(c, PyExc_SyntaxError,
  1345.                   "more than 255 arguments");
  1346.         }
  1347.         if (star_flag || starstar_flag)
  1348.             opcode = CALL_FUNCTION_VAR - 1 + 
  1349.             star_flag + (starstar_flag << 1);
  1350.         else
  1351.             opcode = CALL_FUNCTION;
  1352.         com_addoparg(c, opcode, na | (nk << 8));
  1353.         com_pop(c, na + 2*nk + star_flag + starstar_flag);
  1354.     }
  1355. }
  1356.  
  1357. static void
  1358. com_select_member(struct compiling *c, node *n)
  1359. {
  1360.     com_addopname(c, LOAD_ATTR, n);
  1361. }
  1362.  
  1363. static void
  1364. com_sliceobj(struct compiling *c, node *n)
  1365. {
  1366.     int i=0;
  1367.     int ns=2; /* number of slice arguments */
  1368.     node *ch;
  1369.  
  1370.     /* first argument */
  1371.     if (TYPE(CHILD(n,i)) == COLON) {
  1372.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  1373.         com_push(c, 1);
  1374.         i++;
  1375.     }
  1376.     else {
  1377.         com_node(c, CHILD(n,i));
  1378.         i++;
  1379.         REQ(CHILD(n,i),COLON);
  1380.         i++;
  1381.     }
  1382.     /* second argument */
  1383.     if (i < NCH(n) && TYPE(CHILD(n,i)) == test) {
  1384.         com_node(c, CHILD(n,i));
  1385.         i++;
  1386.     }
  1387.     else {
  1388.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  1389.         com_push(c, 1);
  1390.     }
  1391.     /* remaining arguments */
  1392.     for (; i < NCH(n); i++) {
  1393.         ns++;
  1394.         ch=CHILD(n,i);
  1395.         REQ(ch, sliceop);
  1396.         if (NCH(ch) == 1) {
  1397.             /* right argument of ':' missing */
  1398.             com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  1399.             com_push(c, 1);
  1400.         }
  1401.         else
  1402.             com_node(c, CHILD(ch,1));
  1403.     }
  1404.     com_addoparg(c, BUILD_SLICE, ns);
  1405.     com_pop(c, 1 + (ns == 3));
  1406. }
  1407.  
  1408. static void
  1409. com_subscript(struct compiling *c, node *n)
  1410. {
  1411.     node *ch;
  1412.     REQ(n, subscript);
  1413.     ch = CHILD(n,0);
  1414.     /* check for rubber index */
  1415.     if (TYPE(ch) == DOT && TYPE(CHILD(n,1)) == DOT) {
  1416.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_Ellipsis));
  1417.         com_push(c, 1);
  1418.     }
  1419.     else {
  1420.         /* check for slice */
  1421.         if ((TYPE(ch) == COLON || NCH(n) > 1))
  1422.             com_sliceobj(c, n);
  1423.         else {
  1424.             REQ(ch, test);
  1425.             com_node(c, ch);
  1426.         }
  1427.     }
  1428. }
  1429.  
  1430. static void
  1431. com_subscriptlist(struct compiling *c, node *n, int assigning, node *augn)
  1432. {
  1433.     int i, op;
  1434.     REQ(n, subscriptlist);
  1435.     /* Check to make backward compatible slice behavior for '[i:j]' */
  1436.     if (NCH(n) == 1) {
  1437.         node *sub = CHILD(n, 0); /* subscript */
  1438.         /* 'Basic' slice, should have exactly one colon. */
  1439.         if ((TYPE(CHILD(sub, 0)) == COLON
  1440.              || (NCH(sub) > 1 && TYPE(CHILD(sub, 1)) == COLON))
  1441.             && (TYPE(CHILD(sub,NCH(sub)-1)) != sliceop))
  1442.         {
  1443.             switch (assigning) {
  1444.             case OP_DELETE:
  1445.                 op = DELETE_SLICE;
  1446.                 break;
  1447.             case OP_ASSIGN:
  1448.                 op = STORE_SLICE;
  1449.                 break;
  1450.             case OP_APPLY:
  1451.                 op = SLICE;
  1452.                 break;
  1453.             default:
  1454.                 com_augassign_slice(c, sub, assigning, augn);
  1455.                 return;
  1456.             }
  1457.             com_slice(c, sub, op);
  1458.             if (op == STORE_SLICE)
  1459.                 com_pop(c, 2);
  1460.             else if (op == DELETE_SLICE)
  1461.                 com_pop(c, 1);
  1462.             return;
  1463.         }
  1464.     }
  1465.     /* Else normal subscriptlist.  Compile each subscript. */
  1466.     for (i = 0; i < NCH(n); i += 2)
  1467.         com_subscript(c, CHILD(n, i));
  1468.     /* Put multiple subscripts into a tuple */
  1469.     if (NCH(n) > 1) {
  1470.         i = (NCH(n)+1) / 2;
  1471.         com_addoparg(c, BUILD_TUPLE, i);
  1472.         com_pop(c, i-1);
  1473.     }
  1474.     switch (assigning) {
  1475.     case OP_DELETE:
  1476.         op = DELETE_SUBSCR;
  1477.         i = 2;
  1478.         break;
  1479.     default:
  1480.     case OP_ASSIGN:
  1481.         op = STORE_SUBSCR;
  1482.         i = 3;
  1483.         break;
  1484.     case OP_APPLY:
  1485.         op = BINARY_SUBSCR;
  1486.         i = 1;
  1487.         break;
  1488.     }
  1489.     if (assigning > OP_APPLY) {
  1490.         com_addoparg(c, DUP_TOPX, 2);
  1491.         com_push(c, 2);
  1492.         com_addbyte(c, BINARY_SUBSCR);
  1493.         com_pop(c, 1);
  1494.         com_node(c, augn);
  1495.         com_addbyte(c, assigning);
  1496.         com_pop(c, 1);
  1497.         com_addbyte(c, ROT_THREE);
  1498.     }
  1499.     com_addbyte(c, op);
  1500.     com_pop(c, i);
  1501. }
  1502.  
  1503. static void
  1504. com_apply_trailer(struct compiling *c, node *n)
  1505. {
  1506.     REQ(n, trailer);
  1507.     switch (TYPE(CHILD(n, 0))) {
  1508.     case LPAR:
  1509.         com_call_function(c, CHILD(n, 1));
  1510.         break;
  1511.     case DOT:
  1512.         com_select_member(c, CHILD(n, 1));
  1513.         break;
  1514.     case LSQB:
  1515.         com_subscriptlist(c, CHILD(n, 1), OP_APPLY, NULL);
  1516.         break;
  1517.     default:
  1518.         com_error(c, PyExc_SystemError,
  1519.               "com_apply_trailer: unknown trailer type");
  1520.     }
  1521. }
  1522.  
  1523. static void
  1524. com_power(struct compiling *c, node *n)
  1525. {
  1526.     int i;
  1527.     REQ(n, power);
  1528.     com_atom(c, CHILD(n, 0));
  1529.     for (i = 1; i < NCH(n); i++) {
  1530.         if (TYPE(CHILD(n, i)) == DOUBLESTAR) {
  1531.             com_factor(c, CHILD(n, i+1));
  1532.             com_addbyte(c, BINARY_POWER);
  1533.             com_pop(c, 1);
  1534.             break;
  1535.         }
  1536.         else
  1537.             com_apply_trailer(c, CHILD(n, i));
  1538.     }
  1539. }
  1540.  
  1541. static void
  1542. com_factor(struct compiling *c, node *n)
  1543. {
  1544.     REQ(n, factor);
  1545.     if (TYPE(CHILD(n, 0)) == PLUS) {
  1546.         com_factor(c, CHILD(n, 1));
  1547.         com_addbyte(c, UNARY_POSITIVE);
  1548.     }
  1549.     else if (TYPE(CHILD(n, 0)) == MINUS) {
  1550.         com_factor(c, CHILD(n, 1));
  1551.         com_addbyte(c, UNARY_NEGATIVE);
  1552.     }
  1553.     else if (TYPE(CHILD(n, 0)) == TILDE) {
  1554.         com_factor(c, CHILD(n, 1));
  1555.         com_addbyte(c, UNARY_INVERT);
  1556.     }
  1557.     else {
  1558.         com_power(c, CHILD(n, 0));
  1559.     }
  1560. }
  1561.  
  1562. static void
  1563. com_term(struct compiling *c, node *n)
  1564. {
  1565.     int i;
  1566.     int op;
  1567.     REQ(n, term);
  1568.     com_factor(c, CHILD(n, 0));
  1569.     for (i = 2; i < NCH(n); i += 2) {
  1570.         com_factor(c, CHILD(n, i));
  1571.         switch (TYPE(CHILD(n, i-1))) {
  1572.         case STAR:
  1573.             op = BINARY_MULTIPLY;
  1574.             break;
  1575.         case SLASH:
  1576.             op = BINARY_DIVIDE;
  1577.             break;
  1578.         case PERCENT:
  1579.             op = BINARY_MODULO;
  1580.             break;
  1581.         default:
  1582.             com_error(c, PyExc_SystemError,
  1583.                   "com_term: operator not *, / or %");
  1584.             op = 255;
  1585.         }
  1586.         com_addbyte(c, op);
  1587.         com_pop(c, 1);
  1588.     }
  1589. }
  1590.  
  1591. static void
  1592. com_arith_expr(struct compiling *c, node *n)
  1593. {
  1594.     int i;
  1595.     int op;
  1596.     REQ(n, arith_expr);
  1597.     com_term(c, CHILD(n, 0));
  1598.     for (i = 2; i < NCH(n); i += 2) {
  1599.         com_term(c, CHILD(n, i));
  1600.         switch (TYPE(CHILD(n, i-1))) {
  1601.         case PLUS:
  1602.             op = BINARY_ADD;
  1603.             break;
  1604.         case MINUS:
  1605.             op = BINARY_SUBTRACT;
  1606.             break;
  1607.         default:
  1608.             com_error(c, PyExc_SystemError,
  1609.                   "com_arith_expr: operator not + or -");
  1610.             op = 255;
  1611.         }
  1612.         com_addbyte(c, op);
  1613.         com_pop(c, 1);
  1614.     }
  1615. }
  1616.  
  1617. static void
  1618. com_shift_expr(struct compiling *c, node *n)
  1619. {
  1620.     int i;
  1621.     int op;
  1622.     REQ(n, shift_expr);
  1623.     com_arith_expr(c, CHILD(n, 0));
  1624.     for (i = 2; i < NCH(n); i += 2) {
  1625.         com_arith_expr(c, CHILD(n, i));
  1626.         switch (TYPE(CHILD(n, i-1))) {
  1627.         case LEFTSHIFT:
  1628.             op = BINARY_LSHIFT;
  1629.             break;
  1630.         case RIGHTSHIFT:
  1631.             op = BINARY_RSHIFT;
  1632.             break;
  1633.         default:
  1634.             com_error(c, PyExc_SystemError,
  1635.                   "com_shift_expr: operator not << or >>");
  1636.             op = 255;
  1637.         }
  1638.         com_addbyte(c, op);
  1639.         com_pop(c, 1);
  1640.     }
  1641. }
  1642.  
  1643. static void
  1644. com_and_expr(struct compiling *c, node *n)
  1645. {
  1646.     int i;
  1647.     int op;
  1648.     REQ(n, and_expr);
  1649.     com_shift_expr(c, CHILD(n, 0));
  1650.     for (i = 2; i < NCH(n); i += 2) {
  1651.         com_shift_expr(c, CHILD(n, i));
  1652.         if (TYPE(CHILD(n, i-1)) == AMPER) {
  1653.             op = BINARY_AND;
  1654.         }
  1655.         else {
  1656.             com_error(c, PyExc_SystemError,
  1657.                   "com_and_expr: operator not &");
  1658.             op = 255;
  1659.         }
  1660.         com_addbyte(c, op);
  1661.         com_pop(c, 1);
  1662.     }
  1663. }
  1664.  
  1665. static void
  1666. com_xor_expr(struct compiling *c, node *n)
  1667. {
  1668.     int i;
  1669.     int op;
  1670.     REQ(n, xor_expr);
  1671.     com_and_expr(c, CHILD(n, 0));
  1672.     for (i = 2; i < NCH(n); i += 2) {
  1673.         com_and_expr(c, CHILD(n, i));
  1674.         if (TYPE(CHILD(n, i-1)) == CIRCUMFLEX) {
  1675.             op = BINARY_XOR;
  1676.         }
  1677.         else {
  1678.             com_error(c, PyExc_SystemError,
  1679.                   "com_xor_expr: operator not ^");
  1680.             op = 255;
  1681.         }
  1682.         com_addbyte(c, op);
  1683.         com_pop(c, 1);
  1684.     }
  1685. }
  1686.  
  1687. static void
  1688. com_expr(struct compiling *c, node *n)
  1689. {
  1690.     int i;
  1691.     int op;
  1692.     REQ(n, expr);
  1693.     com_xor_expr(c, CHILD(n, 0));
  1694.     for (i = 2; i < NCH(n); i += 2) {
  1695.         com_xor_expr(c, CHILD(n, i));
  1696.         if (TYPE(CHILD(n, i-1)) == VBAR) {
  1697.             op = BINARY_OR;
  1698.         }
  1699.         else {
  1700.             com_error(c, PyExc_SystemError,
  1701.                   "com_expr: expr operator not |");
  1702.             op = 255;
  1703.         }
  1704.         com_addbyte(c, op);
  1705.         com_pop(c, 1);
  1706.     }
  1707. }
  1708.  
  1709. static enum cmp_op
  1710. cmp_type(node *n)
  1711. {
  1712.     REQ(n, comp_op);
  1713.     /* comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '=='
  1714.               | 'in' | 'not' 'in' | 'is' | 'is' not' */
  1715.     if (NCH(n) == 1) {
  1716.         n = CHILD(n, 0);
  1717.         switch (TYPE(n)) {
  1718.         case LESS:    return LT;
  1719.         case GREATER:    return GT;
  1720.         case EQEQUAL:            /* == */
  1721.         case EQUAL:    return EQ;
  1722.         case LESSEQUAL:    return LE;
  1723.         case GREATEREQUAL: return GE;
  1724.         case NOTEQUAL:    return NE;    /* <> or != */
  1725.         case NAME:    if (strcmp(STR(n), "in") == 0) return IN;
  1726.                 if (strcmp(STR(n), "is") == 0) return IS;
  1727.         }
  1728.     }
  1729.     else if (NCH(n) == 2) {
  1730.         switch (TYPE(CHILD(n, 0))) {
  1731.         case NAME:    if (strcmp(STR(CHILD(n, 1)), "in") == 0)
  1732.                     return NOT_IN;
  1733.                 if (strcmp(STR(CHILD(n, 0)), "is") == 0)
  1734.                     return IS_NOT;
  1735.         }
  1736.     }
  1737.     return BAD;
  1738. }
  1739.  
  1740. static void
  1741. com_comparison(struct compiling *c, node *n)
  1742. {
  1743.     int i;
  1744.     enum cmp_op op;
  1745.     int anchor;
  1746.     REQ(n, comparison); /* comparison: expr (comp_op expr)* */
  1747.     com_expr(c, CHILD(n, 0));
  1748.     if (NCH(n) == 1)
  1749.         return;
  1750.     
  1751.     /****************************************************************
  1752.        The following code is generated for all but the last
  1753.        comparison in a chain:
  1754.        
  1755.        label:    on stack:    opcode:        jump to:
  1756.        
  1757.             a        <code to load b>
  1758.             a, b        DUP_TOP
  1759.             a, b, b        ROT_THREE
  1760.             b, a, b        COMPARE_OP
  1761.             b, 0-or-1    JUMP_IF_FALSE    L1
  1762.             b, 1        POP_TOP
  1763.             b        
  1764.     
  1765.        We are now ready to repeat this sequence for the next
  1766.        comparison in the chain.
  1767.        
  1768.        For the last we generate:
  1769.        
  1770.                b        <code to load c>
  1771.                b, c        COMPARE_OP
  1772.                0-or-1        
  1773.        
  1774.        If there were any jumps to L1 (i.e., there was more than one
  1775.        comparison), we generate:
  1776.        
  1777.                0-or-1        JUMP_FORWARD    L2
  1778.        L1:        b, 0        ROT_TWO
  1779.                0, b        POP_TOP
  1780.                0
  1781.        L2:        0-or-1
  1782.     ****************************************************************/
  1783.     
  1784.     anchor = 0;
  1785.     
  1786.     for (i = 2; i < NCH(n); i += 2) {
  1787.         com_expr(c, CHILD(n, i));
  1788.         if (i+2 < NCH(n)) {
  1789.             com_addbyte(c, DUP_TOP);
  1790.             com_push(c, 1);
  1791.             com_addbyte(c, ROT_THREE);
  1792.         }
  1793.         op = cmp_type(CHILD(n, i-1));
  1794.         if (op == BAD) {
  1795.             com_error(c, PyExc_SystemError,
  1796.                   "com_comparison: unknown comparison op");
  1797.         }
  1798.         com_addoparg(c, COMPARE_OP, op);
  1799.         com_pop(c, 1);
  1800.         if (i+2 < NCH(n)) {
  1801.             com_addfwref(c, JUMP_IF_FALSE, &anchor);
  1802.             com_addbyte(c, POP_TOP);
  1803.             com_pop(c, 1);
  1804.         }
  1805.     }
  1806.     
  1807.     if (anchor) {
  1808.         int anchor2 = 0;
  1809.         com_addfwref(c, JUMP_FORWARD, &anchor2);
  1810.         com_backpatch(c, anchor);
  1811.         com_addbyte(c, ROT_TWO);
  1812.         com_addbyte(c, POP_TOP);
  1813.         com_backpatch(c, anchor2);
  1814.     }
  1815. }
  1816.  
  1817. static void
  1818. com_not_test(struct compiling *c, node *n)
  1819. {
  1820.     REQ(n, not_test); /* 'not' not_test | comparison */
  1821.     if (NCH(n) == 1) {
  1822.         com_comparison(c, CHILD(n, 0));
  1823.     }
  1824.     else {
  1825.         com_not_test(c, CHILD(n, 1));
  1826.         com_addbyte(c, UNARY_NOT);
  1827.     }
  1828. }
  1829.  
  1830. static void
  1831. com_and_test(struct compiling *c, node *n)
  1832. {
  1833.     int i;
  1834.     int anchor;
  1835.     REQ(n, and_test); /* not_test ('and' not_test)* */
  1836.     anchor = 0;
  1837.     i = 0;
  1838.     for (;;) {
  1839.         com_not_test(c, CHILD(n, i));
  1840.         if ((i += 2) >= NCH(n))
  1841.             break;
  1842.         com_addfwref(c, JUMP_IF_FALSE, &anchor);
  1843.         com_addbyte(c, POP_TOP);
  1844.         com_pop(c, 1);
  1845.     }
  1846.     if (anchor)
  1847.         com_backpatch(c, anchor);
  1848. }
  1849.  
  1850. static void
  1851. com_test(struct compiling *c, node *n)
  1852. {
  1853.     REQ(n, test); /* and_test ('or' and_test)* | lambdef */
  1854.     if (NCH(n) == 1 && TYPE(CHILD(n, 0)) == lambdef) {
  1855.         PyObject *v;
  1856.         int i;
  1857.         int ndefs = com_argdefs(c, CHILD(n, 0));
  1858.         v = (PyObject *) icompile(CHILD(n, 0), c);
  1859.         if (v == NULL) {
  1860.             c->c_errors++;
  1861.             i = 255;
  1862.         }
  1863.         else {
  1864.             i = com_addconst(c, v);
  1865.             Py_DECREF(v);
  1866.         }
  1867.         com_addoparg(c, LOAD_CONST, i);
  1868.         com_push(c, 1);
  1869.         com_addoparg(c, MAKE_FUNCTION, ndefs);
  1870.         com_pop(c, ndefs);
  1871.     }
  1872.     else {
  1873.         int anchor = 0;
  1874.         int i = 0;
  1875.         for (;;) {
  1876.             com_and_test(c, CHILD(n, i));
  1877.             if ((i += 2) >= NCH(n))
  1878.                 break;
  1879.             com_addfwref(c, JUMP_IF_TRUE, &anchor);
  1880.             com_addbyte(c, POP_TOP);
  1881.             com_pop(c, 1);
  1882.         }
  1883.         if (anchor)
  1884.             com_backpatch(c, anchor);
  1885.     }
  1886. }
  1887.  
  1888. static void
  1889. com_list(struct compiling *c, node *n, int toplevel)
  1890. {
  1891.     /* exprlist: expr (',' expr)* [',']; likewise for testlist */
  1892.     if (NCH(n) == 1 && !toplevel) {
  1893.         com_node(c, CHILD(n, 0));
  1894.     }
  1895.     else {
  1896.         int i;
  1897.         int len;
  1898.         len = (NCH(n) + 1) / 2;
  1899.         for (i = 0; i < NCH(n); i += 2)
  1900.             com_node(c, CHILD(n, i));
  1901.         com_addoparg(c, BUILD_TUPLE, len);
  1902.         com_pop(c, len-1);
  1903.     }
  1904. }
  1905.  
  1906.  
  1907. /* Begin of assignment compilation */
  1908.  
  1909.  
  1910. static void
  1911. com_augassign_attr(struct compiling *c, node *n, int opcode, node *augn)
  1912. {
  1913.     com_addbyte(c, DUP_TOP);
  1914.     com_push(c, 1);
  1915.     com_addopname(c, LOAD_ATTR, n);
  1916.     com_node(c, augn);
  1917.     com_addbyte(c, opcode);
  1918.     com_pop(c, 1);
  1919.     com_addbyte(c, ROT_TWO);
  1920.     com_addopname(c, STORE_ATTR, n);
  1921.     com_pop(c, 2);
  1922. }
  1923.  
  1924. static void
  1925. com_assign_attr(struct compiling *c, node *n, int assigning)
  1926. {
  1927.     com_addopname(c, assigning ? STORE_ATTR : DELETE_ATTR, n);
  1928.     com_pop(c, assigning ? 2 : 1);
  1929. }
  1930.  
  1931. static void
  1932. com_assign_trailer(struct compiling *c, node *n, int assigning, node *augn)
  1933. {
  1934.     REQ(n, trailer);
  1935.     switch (TYPE(CHILD(n, 0))) {
  1936.     case LPAR: /* '(' [exprlist] ')' */
  1937.         com_error(c, PyExc_SyntaxError,
  1938.               "can't assign to function call");
  1939.         break;
  1940.     case DOT: /* '.' NAME */
  1941.         if (assigning > OP_APPLY)
  1942.             com_augassign_attr(c, CHILD(n, 1), assigning, augn);
  1943.         else
  1944.             com_assign_attr(c, CHILD(n, 1), assigning);
  1945.         break;
  1946.     case LSQB: /* '[' subscriptlist ']' */
  1947.         com_subscriptlist(c, CHILD(n, 1), assigning, augn);
  1948.         break;
  1949.     default:
  1950.         com_error(c, PyExc_SystemError, "unknown trailer type");
  1951.     }
  1952. }
  1953.  
  1954. static void
  1955. com_assign_sequence(struct compiling *c, node *n, int assigning)
  1956. {
  1957.     int i;
  1958.     if (TYPE(n) != testlist && TYPE(n) != listmaker)
  1959.         REQ(n, exprlist);
  1960.     if (assigning) {
  1961.         i = (NCH(n)+1)/2;
  1962.         com_addoparg(c, UNPACK_SEQUENCE, i);
  1963.         com_push(c, i-1);
  1964.     }
  1965.     for (i = 0; i < NCH(n); i += 2)
  1966.         com_assign(c, CHILD(n, i), assigning, NULL);
  1967. }
  1968.  
  1969. static void
  1970. com_augassign_name(struct compiling *c, node *n, int opcode, node *augn)
  1971. {
  1972.     REQ(n, NAME);
  1973.     com_addopname(c, LOAD_NAME, n);
  1974.     com_push(c, 1);
  1975.     com_node(c, augn);
  1976.     com_addbyte(c, opcode);
  1977.     com_pop(c, 1);
  1978.     com_assign_name(c, n, OP_ASSIGN);
  1979. }
  1980.  
  1981. static void
  1982. com_assign_name(struct compiling *c, node *n, int assigning)
  1983. {
  1984.     REQ(n, NAME);
  1985.     com_addopname(c, assigning ? STORE_NAME : DELETE_NAME, n);
  1986.     if (assigning)
  1987.         com_pop(c, 1);
  1988. }
  1989.  
  1990. static void
  1991. com_assign(struct compiling *c, node *n, int assigning, node *augn)
  1992. {
  1993.     /* Loop to avoid trivial recursion */
  1994.     for (;;) {
  1995.         switch (TYPE(n)) {
  1996.         
  1997.         case exprlist:
  1998.         case testlist:
  1999.             if (NCH(n) > 1) {
  2000.                 if (assigning > OP_APPLY) {
  2001.                     com_error(c, PyExc_SyntaxError,
  2002.                           "augmented assign to tuple not possible");
  2003.                     return;
  2004.                 }
  2005.                 com_assign_sequence(c, n, assigning);
  2006.                 return;
  2007.             }
  2008.             n = CHILD(n, 0);
  2009.             break;
  2010.         
  2011.         case test:
  2012.         case and_test:
  2013.         case not_test:
  2014.         case comparison:
  2015.         case expr:
  2016.         case xor_expr:
  2017.         case and_expr:
  2018.         case shift_expr:
  2019.         case arith_expr:
  2020.         case term:
  2021.         case factor:
  2022.             if (NCH(n) > 1) {
  2023.                 com_error(c, PyExc_SyntaxError,
  2024.                       "can't assign to operator");
  2025.                 return;
  2026.             }
  2027.             n = CHILD(n, 0);
  2028.             break;
  2029.         
  2030.         case power: /* atom trailer* ('**' power)* */
  2031. /* ('+'|'-'|'~') factor | atom trailer* */
  2032.             if (TYPE(CHILD(n, 0)) != atom) {
  2033.                 com_error(c, PyExc_SyntaxError,
  2034.                       "can't assign to operator");
  2035.                 return;
  2036.             }
  2037.             if (NCH(n) > 1) { /* trailer or exponent present */
  2038.                 int i;
  2039.                 com_node(c, CHILD(n, 0));
  2040.                 for (i = 1; i+1 < NCH(n); i++) {
  2041.                     if (TYPE(CHILD(n, i)) == DOUBLESTAR) {
  2042.                         com_error(c, PyExc_SyntaxError,
  2043.                           "can't assign to operator");
  2044.                         return;
  2045.                     }
  2046.                     com_apply_trailer(c, CHILD(n, i));
  2047.                 } /* NB i is still alive */
  2048.                 com_assign_trailer(c,
  2049.                         CHILD(n, i), assigning, augn);
  2050.                 return;
  2051.             }
  2052.             n = CHILD(n, 0);
  2053.             break;
  2054.         
  2055.         case atom:
  2056.             switch (TYPE(CHILD(n, 0))) {
  2057.             case LPAR:
  2058.                 n = CHILD(n, 1);
  2059.                 if (TYPE(n) == RPAR) {
  2060.                     /* XXX Should allow () = () ??? */
  2061.                     com_error(c, PyExc_SyntaxError,
  2062.                           "can't assign to ()");
  2063.                     return;
  2064.                 }
  2065.                 if (assigning > OP_APPLY) {
  2066.                     com_error(c, PyExc_SyntaxError,
  2067.                           "augmented assign to tuple not possible");
  2068.                     return;
  2069.                 }
  2070.                 break;
  2071.             case LSQB:
  2072.                 n = CHILD(n, 1);
  2073.                 if (TYPE(n) == RSQB) {
  2074.                     com_error(c, PyExc_SyntaxError,
  2075.                           "can't assign to []");
  2076.                     return;
  2077.                 }
  2078.                 if (assigning > OP_APPLY) {
  2079.                     com_error(c, PyExc_SyntaxError,
  2080.                           "augmented assign to list not possible");
  2081.                     return;
  2082.                 }
  2083.                 com_assign_sequence(c, n, assigning);
  2084.                 return;
  2085.             case NAME:
  2086.                 if (assigning > OP_APPLY)
  2087.                     com_augassign_name(c, CHILD(n, 0),
  2088.                                assigning, augn);
  2089.                 else
  2090.                     com_assign_name(c, CHILD(n, 0),
  2091.                             assigning);
  2092.                 return;
  2093.             default:
  2094.                 com_error(c, PyExc_SyntaxError,
  2095.                       "can't assign to literal");
  2096.                 return;
  2097.             }
  2098.             break;
  2099.  
  2100.         case lambdef:
  2101.             com_error(c, PyExc_SyntaxError,
  2102.                   "can't assign to lambda");
  2103.             return;
  2104.         
  2105.         default:
  2106.             /* XXX fprintf(stderr, "node type %d\n", TYPE(n)); */
  2107.             com_error(c, PyExc_SystemError,
  2108.                   "com_assign: bad node");
  2109.             return;
  2110.         
  2111.         }
  2112.     }
  2113. }
  2114.  
  2115. static void
  2116. com_augassign(struct compiling *c, node *n)
  2117. {
  2118.     int opcode;
  2119.  
  2120.     switch (STR(CHILD(CHILD(n, 1), 0))[0]) {
  2121.     case '+': opcode = INPLACE_ADD; break;
  2122.     case '-': opcode = INPLACE_SUBTRACT; break;
  2123.     case '/': opcode = INPLACE_DIVIDE; break;
  2124.     case '%': opcode = INPLACE_MODULO; break;
  2125.     case '<': opcode = INPLACE_LSHIFT; break;
  2126.     case '>': opcode = INPLACE_RSHIFT; break;
  2127.     case '&': opcode = INPLACE_AND; break;
  2128.     case '^': opcode = INPLACE_XOR; break;
  2129.     case '|': opcode = INPLACE_OR; break;
  2130.     case '*':
  2131.         if (STR(CHILD(CHILD(n, 1), 0))[1] == '*')
  2132.             opcode = INPLACE_POWER;
  2133.         else
  2134.             opcode = INPLACE_MULTIPLY;
  2135.         break;
  2136.     default:
  2137.         com_error(c, PyExc_SystemError, "com_augassign: bad operator");
  2138.         return;
  2139.     }
  2140.     com_assign(c, CHILD(n, 0), opcode, CHILD(n, 2));
  2141. }
  2142.  
  2143. static void
  2144. com_expr_stmt(struct compiling *c, node *n)
  2145. {
  2146.     REQ(n, expr_stmt);
  2147.     /* testlist (('=' testlist)* | augassign testlist) */
  2148.     /* Forget it if we have just a doc string here */
  2149.     if (!c->c_interactive && NCH(n) == 1 && get_rawdocstring(n) != NULL)
  2150.         return;
  2151.      if (NCH(n) == 1) {
  2152.         com_node(c, CHILD(n, NCH(n)-1));
  2153.         if (c->c_interactive)
  2154.             com_addbyte(c, PRINT_EXPR);
  2155.         else
  2156.             com_addbyte(c, POP_TOP);
  2157.         com_pop(c, 1);
  2158.     }
  2159.     else if (TYPE(CHILD(n,1)) == augassign)
  2160.         com_augassign(c, n);
  2161.     else {
  2162.         int i;
  2163.         com_node(c, CHILD(n, NCH(n)-1));
  2164.         for (i = 0; i < NCH(n)-2; i+=2) {
  2165.             if (i+2 < NCH(n)-2) {
  2166.                 com_addbyte(c, DUP_TOP);
  2167.                 com_push(c, 1);
  2168.             }
  2169.             com_assign(c, CHILD(n, i), OP_ASSIGN, NULL);
  2170.         }
  2171.     }
  2172. }
  2173.  
  2174. static void
  2175. com_assert_stmt(struct compiling *c, node *n)
  2176. {
  2177.     int a = 0, b = 0;
  2178.     int i;
  2179.     REQ(n, assert_stmt); /* 'assert' test [',' test] */
  2180.     /* Generate code like for
  2181.        
  2182.        if __debug__:
  2183.           if not <test>:
  2184.              raise AssertionError [, <message>]
  2185.  
  2186.        where <message> is the second test, if present.
  2187.     */
  2188.     if (Py_OptimizeFlag)
  2189.         return;
  2190.     com_addopnamestr(c, LOAD_GLOBAL, "__debug__");
  2191.     com_push(c, 1);
  2192.     com_addfwref(c, JUMP_IF_FALSE, &a);
  2193.     com_addbyte(c, POP_TOP);
  2194.     com_pop(c, 1);
  2195.     com_node(c, CHILD(n, 1));
  2196.     com_addfwref(c, JUMP_IF_TRUE, &b);
  2197.     com_addbyte(c, POP_TOP);
  2198.     com_pop(c, 1);
  2199.     /* Raise that exception! */
  2200.     com_addopnamestr(c, LOAD_GLOBAL, "AssertionError");
  2201.     com_push(c, 1);
  2202.     i = NCH(n)/2; /* Either 2 or 4 */
  2203.     if (i > 1)
  2204.         com_node(c, CHILD(n, 3));
  2205.     com_addoparg(c, RAISE_VARARGS, i);
  2206.     com_pop(c, i);
  2207.     /* The interpreter does not fall through */
  2208.     /* All jumps converge here */
  2209.     com_backpatch(c, a);
  2210.     com_backpatch(c, b);
  2211.     com_addbyte(c, POP_TOP);
  2212. }
  2213.  
  2214. static void
  2215. com_print_stmt(struct compiling *c, node *n)
  2216. {
  2217.     int i = 1;
  2218.     node* stream = NULL;
  2219.  
  2220.     REQ(n, print_stmt); /* 'print' (test ',')* [test] */
  2221.  
  2222.     /* are we using the extended print form? */
  2223.     if (NCH(n) >= 2 && TYPE(CHILD(n, 1)) == RIGHTSHIFT) {
  2224.         stream = CHILD(n, 2);
  2225.         com_node(c, stream);
  2226.         /* stack: [...] => [... stream] */
  2227.         com_push(c, 1);
  2228.         if (NCH(n) > 3 && TYPE(CHILD(n, 3)) == COMMA)
  2229.             i = 4;
  2230.         else
  2231.             i = 3;
  2232.     }
  2233.     for (; i < NCH(n); i += 2) {
  2234.         if (stream != NULL) {
  2235.             com_addbyte(c, DUP_TOP);
  2236.             /* stack: [stream] => [stream stream] */
  2237.             com_push(c, 1);
  2238.             com_node(c, CHILD(n, i));
  2239.             /* stack: [stream stream] => [stream stream obj] */
  2240.             com_addbyte(c, ROT_TWO);
  2241.             /* stack: [stream stream obj] => [stream obj stream] */
  2242.             com_addbyte(c, PRINT_ITEM_TO);
  2243.             /* stack: [stream obj stream] => [stream] */
  2244.             com_pop(c, 2);
  2245.         }
  2246.         else {
  2247.             com_node(c, CHILD(n, i));
  2248.             /* stack: [...] => [... obj] */
  2249.             com_addbyte(c, PRINT_ITEM);
  2250.             com_pop(c, 1);
  2251.         }
  2252.     }
  2253.     /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */
  2254.     if (TYPE(CHILD(n, NCH(n)-1)) == COMMA) {
  2255.         if (stream != NULL) {
  2256.             /* must pop the extra stream object off the stack */
  2257.             com_addbyte(c, POP_TOP);
  2258.             /* stack: [... stream] => [...] */
  2259.             com_pop(c, 1);
  2260.         }
  2261.     }
  2262.     else {
  2263.         if (stream != NULL) {
  2264.             /* this consumes the last stream object on stack */
  2265.             com_addbyte(c, PRINT_NEWLINE_TO);
  2266.             /* stack: [... stream] => [...] */
  2267.             com_pop(c, 1);
  2268.         }
  2269.         else
  2270.             com_addbyte(c, PRINT_NEWLINE);
  2271.     }
  2272. }
  2273.  
  2274. static void
  2275. com_return_stmt(struct compiling *c, node *n)
  2276. {
  2277.     REQ(n, return_stmt); /* 'return' [testlist] */
  2278.     if (!c->c_infunction) {
  2279.         com_error(c, PyExc_SyntaxError, "'return' outside function");
  2280.     }
  2281.     if (NCH(n) < 2) {
  2282.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  2283.         com_push(c, 1);
  2284.     }
  2285.     else
  2286.         com_node(c, CHILD(n, 1));
  2287.     com_addbyte(c, RETURN_VALUE);
  2288.     com_pop(c, 1);
  2289. }
  2290.  
  2291. static void
  2292. com_raise_stmt(struct compiling *c, node *n)
  2293. {
  2294.     int i;
  2295.     REQ(n, raise_stmt); /* 'raise' [test [',' test [',' test]]] */
  2296.     if (NCH(n) > 1) {
  2297.         com_node(c, CHILD(n, 1));
  2298.         if (NCH(n) > 3) {
  2299.             com_node(c, CHILD(n, 3));
  2300.             if (NCH(n) > 5)
  2301.                 com_node(c, CHILD(n, 5));
  2302.         }
  2303.     }
  2304.     i = NCH(n)/2;
  2305.     com_addoparg(c, RAISE_VARARGS, i);
  2306.     com_pop(c, i);
  2307. }
  2308.  
  2309. static void
  2310. com_from_import(struct compiling *c, node *n)
  2311. {
  2312.     com_addopname(c, IMPORT_FROM, CHILD(n, 0));
  2313.     com_push(c, 1);
  2314.     if (NCH(n) > 1) {
  2315.         if (strcmp(STR(CHILD(n, 1)), "as") != 0) {
  2316.             com_error(c, PyExc_SyntaxError, "invalid syntax");
  2317.             return;
  2318.         }
  2319.         com_addopname(c, STORE_NAME, CHILD(n, 2));
  2320.     } else
  2321.         com_addopname(c, STORE_NAME, CHILD(n, 0));
  2322.     com_pop(c, 1);
  2323. }
  2324.  
  2325. static void
  2326. com_import_stmt(struct compiling *c, node *n)
  2327. {
  2328.     int i;
  2329.     PyObject *tup;
  2330.     REQ(n, import_stmt);
  2331.     /* 'import' dotted_name (',' dotted_name)* |
  2332.        'from' dotted_name 'import' ('*' | NAME (',' NAME)*) */
  2333.     if (STR(CHILD(n, 0))[0] == 'f') {
  2334.         /* 'from' dotted_name 'import' ... */
  2335.         REQ(CHILD(n, 1), dotted_name);
  2336.         
  2337.         if (TYPE(CHILD(n, 3)) == STAR) {
  2338.             tup = Py_BuildValue("(s)", "*");
  2339.         } else {
  2340.             tup = PyTuple_New((NCH(n) - 2)/2);
  2341.             for (i = 3; i < NCH(n); i += 2) {
  2342.                 PyTuple_SET_ITEM(tup, (i-3)/2, 
  2343.                     PyString_FromString(STR(
  2344.                             CHILD(CHILD(n, i), 0))));
  2345.             }
  2346.         }
  2347.         com_addoparg(c, LOAD_CONST, com_addconst(c, tup));
  2348.         com_push(c, 1);
  2349.         com_addopname(c, IMPORT_NAME, CHILD(n, 1));
  2350.         if (TYPE(CHILD(n, 3)) == STAR) 
  2351.             com_addbyte(c, IMPORT_STAR);
  2352.         else {
  2353.             for (i = 3; i < NCH(n); i += 2) 
  2354.                 com_from_import(c, CHILD(n, i));
  2355.             com_addbyte(c, POP_TOP);
  2356.         }
  2357.         com_pop(c, 1);
  2358.     }
  2359.     else {
  2360.         /* 'import' ... */
  2361.         for (i = 1; i < NCH(n); i += 2) {
  2362.             node *subn = CHILD(n, i);
  2363.             REQ(subn, dotted_as_name);
  2364.             com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  2365.             com_push(c, 1);
  2366.             com_addopname(c, IMPORT_NAME, CHILD(subn, 0));
  2367.             if (NCH(subn) > 1) {
  2368.                 int j;
  2369.                 if (strcmp(STR(CHILD(subn, 1)), "as") != 0) {
  2370.                     com_error(c, PyExc_SyntaxError,
  2371.                           "invalid syntax");
  2372.                     return;
  2373.                 }
  2374.                 for (j=2 ; j < NCH(CHILD(subn, 0)); j += 2)
  2375.                     com_addopname(c, LOAD_ATTR,
  2376.                               CHILD(CHILD(subn, 0), j));
  2377.                 com_addopname(c, STORE_NAME, CHILD(subn, 2));
  2378.             } else
  2379.                 com_addopname(c, STORE_NAME,
  2380.                           CHILD(CHILD(subn, 0),0));
  2381.             com_pop(c, 1);
  2382.         }
  2383.     }
  2384. }
  2385.  
  2386. static void
  2387. com_global_stmt(struct compiling *c, node *n)
  2388. {
  2389.     int i;
  2390.     REQ(n, global_stmt);
  2391.     /* 'global' NAME (',' NAME)* */
  2392.     for (i = 1; i < NCH(n); i += 2) {
  2393.         char *s = STR(CHILD(n, i));
  2394. #ifdef PRIVATE_NAME_MANGLING
  2395.         char buffer[256];
  2396.         if (s != NULL && s[0] == '_' && s[1] == '_' &&
  2397.             c->c_private != NULL &&
  2398.             com_mangle(c, s, buffer, sizeof(buffer)))
  2399.             s = buffer;
  2400. #endif
  2401.         if (PyDict_GetItemString(c->c_locals, s) != NULL) {
  2402.             com_error(c, PyExc_SyntaxError,
  2403.                   "name is local and global");
  2404.         }
  2405.         else if (PyDict_SetItemString(c->c_globals, s, Py_None) != 0)
  2406.             c->c_errors++;
  2407.     }
  2408. }
  2409.  
  2410. static int
  2411. com_newlocal_o(struct compiling *c, PyObject *nameval)
  2412. {
  2413.     int i;
  2414.     PyObject *ival;
  2415.     if (PyList_Size(c->c_varnames) != c->c_nlocals) {
  2416.         /* This is usually caused by an error on a previous call */
  2417.         if (c->c_errors == 0) {
  2418.             com_error(c, PyExc_SystemError,
  2419.                   "mixed up var name/index");
  2420.         }
  2421.         return 0;
  2422.     }
  2423.     ival = PyInt_FromLong(i = c->c_nlocals++);
  2424.     if (ival == NULL)
  2425.         c->c_errors++;
  2426.     else if (PyDict_SetItem(c->c_locals, nameval, ival) != 0)
  2427.         c->c_errors++;
  2428.     else if (PyList_Append(c->c_varnames, nameval) != 0)
  2429.         c->c_errors++;
  2430.     Py_XDECREF(ival);
  2431.     return i;
  2432. }
  2433.  
  2434. static int
  2435. com_addlocal_o(struct compiling *c, PyObject *nameval)
  2436. {
  2437.     PyObject *ival =  PyDict_GetItem(c->c_locals, nameval);
  2438.     if (ival != NULL)
  2439.         return PyInt_AsLong(ival);
  2440.     return com_newlocal_o(c, nameval);
  2441. }
  2442.  
  2443. static int
  2444. com_newlocal(struct compiling *c, char *name)
  2445. {
  2446.     PyObject *nameval = PyString_InternFromString(name);
  2447.     int i;
  2448.     if (nameval == NULL) {
  2449.         c->c_errors++;
  2450.         return 0;
  2451.     }
  2452.     i = com_newlocal_o(c, nameval);
  2453.     Py_DECREF(nameval);
  2454.     return i;
  2455. }
  2456.  
  2457. static void
  2458. com_exec_stmt(struct compiling *c, node *n)
  2459. {
  2460.     REQ(n, exec_stmt);
  2461.     /* exec_stmt: 'exec' expr ['in' expr [',' expr]] */
  2462.     com_node(c, CHILD(n, 1));
  2463.     if (NCH(n) >= 4)
  2464.         com_node(c, CHILD(n, 3));
  2465.     else {
  2466.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  2467.         com_push(c, 1);
  2468.     }
  2469.     if (NCH(n) >= 6)
  2470.         com_node(c, CHILD(n, 5));
  2471.     else {
  2472.         com_addbyte(c, DUP_TOP);
  2473.         com_push(c, 1);
  2474.     }
  2475.     com_addbyte(c, EXEC_STMT);
  2476.     com_pop(c, 3);
  2477. }
  2478.  
  2479. static int
  2480. is_constant_false(struct compiling *c, node *n)
  2481. {
  2482.     PyObject *v;
  2483.     int i;
  2484.  
  2485.   /* Label to avoid tail recursion */
  2486.   next:
  2487.     switch (TYPE(n)) {
  2488.  
  2489.     case suite:
  2490.         if (NCH(n) == 1) {
  2491.             n = CHILD(n, 0);
  2492.             goto next;
  2493.         }
  2494.         /* Fall through */
  2495.     case file_input:
  2496.         for (i = 0; i < NCH(n); i++) {
  2497.             node *ch = CHILD(n, i);
  2498.             if (TYPE(ch) == stmt) {
  2499.                 n = ch;
  2500.                 goto next;
  2501.             }
  2502.         }
  2503.         break;
  2504.  
  2505.     case stmt:
  2506.     case simple_stmt:
  2507.     case small_stmt:
  2508.         n = CHILD(n, 0);
  2509.         goto next;
  2510.  
  2511.     case expr_stmt:
  2512.     case testlist:
  2513.     case test:
  2514.     case and_test:
  2515.     case not_test:
  2516.     case comparison:
  2517.     case expr:
  2518.     case xor_expr:
  2519.     case and_expr:
  2520.     case shift_expr:
  2521.     case arith_expr:
  2522.     case term:
  2523.     case factor:
  2524.     case power:
  2525.     case atom:
  2526.         if (NCH(n) == 1) {
  2527.             n = CHILD(n, 0);
  2528.             goto next;
  2529.         }
  2530.         break;
  2531.  
  2532.     case NAME:
  2533.         if (Py_OptimizeFlag && strcmp(STR(n), "__debug__") == 0)
  2534.             return 1;
  2535.         break;
  2536.  
  2537.     case NUMBER:
  2538.         v = parsenumber(c, STR(n));
  2539.         if (v == NULL) {
  2540.             PyErr_Clear();
  2541.             break;
  2542.         }
  2543.         i = PyObject_IsTrue(v);
  2544.         Py_DECREF(v);
  2545.         return i == 0;
  2546.  
  2547.     case STRING:
  2548.         v = parsestr(STR(n));
  2549.         if (v == NULL) {
  2550.             PyErr_Clear();
  2551.             break;
  2552.         }
  2553.         i = PyObject_IsTrue(v);
  2554.         Py_DECREF(v);
  2555.         return i == 0;
  2556.  
  2557.     }
  2558.     return 0;
  2559. }
  2560.  
  2561. static void
  2562. com_if_stmt(struct compiling *c, node *n)
  2563. {
  2564.     int i;
  2565.     int anchor = 0;
  2566.     REQ(n, if_stmt);
  2567.     /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */
  2568.     for (i = 0; i+3 < NCH(n); i+=4) {
  2569.         int a = 0;
  2570.         node *ch = CHILD(n, i+1);
  2571.         if (is_constant_false(c, ch))
  2572.             continue;
  2573.         if (i > 0)
  2574.             com_addoparg(c, SET_LINENO, ch->n_lineno);
  2575.         com_node(c, ch);
  2576.         com_addfwref(c, JUMP_IF_FALSE, &a);
  2577.         com_addbyte(c, POP_TOP);
  2578.         com_pop(c, 1);
  2579.         com_node(c, CHILD(n, i+3));
  2580.         com_addfwref(c, JUMP_FORWARD, &anchor);
  2581.         com_backpatch(c, a);
  2582.         /* We jump here with an extra entry which we now pop */
  2583.         com_addbyte(c, POP_TOP);
  2584.     }
  2585.     if (i+2 < NCH(n))
  2586.         com_node(c, CHILD(n, i+2));
  2587.     if (anchor)
  2588.         com_backpatch(c, anchor);
  2589. }
  2590.  
  2591. static void
  2592. com_while_stmt(struct compiling *c, node *n)
  2593. {
  2594.     int break_anchor = 0;
  2595.     int anchor = 0;
  2596.     int save_begin = c->c_begin;
  2597.     REQ(n, while_stmt); /* 'while' test ':' suite ['else' ':' suite] */
  2598.     com_addfwref(c, SETUP_LOOP, &break_anchor);
  2599.     block_push(c, SETUP_LOOP);
  2600.     c->c_begin = c->c_nexti;
  2601.     com_addoparg(c, SET_LINENO, n->n_lineno);
  2602.     com_node(c, CHILD(n, 1));
  2603.     com_addfwref(c, JUMP_IF_FALSE, &anchor);
  2604.     com_addbyte(c, POP_TOP);
  2605.     com_pop(c, 1);
  2606.     c->c_loops++;
  2607.     com_node(c, CHILD(n, 3));
  2608.     c->c_loops--;
  2609.     com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  2610.     c->c_begin = save_begin;
  2611.     com_backpatch(c, anchor);
  2612.     /* We jump here with one entry more on the stack */
  2613.     com_addbyte(c, POP_TOP);
  2614.     com_addbyte(c, POP_BLOCK);
  2615.     block_pop(c, SETUP_LOOP);
  2616.     if (NCH(n) > 4)
  2617.         com_node(c, CHILD(n, 6));
  2618.     com_backpatch(c, break_anchor);
  2619. }
  2620.  
  2621. static void
  2622. com_for_stmt(struct compiling *c, node *n)
  2623. {
  2624.     PyObject *v;
  2625.     int break_anchor = 0;
  2626.     int anchor = 0;
  2627.     int save_begin = c->c_begin;
  2628.     REQ(n, for_stmt);
  2629.     /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */
  2630.     com_addfwref(c, SETUP_LOOP, &break_anchor);
  2631.     block_push(c, SETUP_LOOP);
  2632.     com_node(c, CHILD(n, 3));
  2633.     v = PyInt_FromLong(0L);
  2634.     if (v == NULL)
  2635.         c->c_errors++;
  2636.     com_addoparg(c, LOAD_CONST, com_addconst(c, v));
  2637.     com_push(c, 1);
  2638.     Py_XDECREF(v);
  2639.     c->c_begin = c->c_nexti;
  2640.     com_addoparg(c, SET_LINENO, n->n_lineno);
  2641.     com_addfwref(c, FOR_LOOP, &anchor);
  2642.     com_push(c, 1);
  2643.     com_assign(c, CHILD(n, 1), OP_ASSIGN, NULL);
  2644.     c->c_loops++;
  2645.     com_node(c, CHILD(n, 5));
  2646.     c->c_loops--;
  2647.     com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  2648.     c->c_begin = save_begin;
  2649.     com_backpatch(c, anchor);
  2650.     com_pop(c, 2); /* FOR_LOOP has popped these */
  2651.     com_addbyte(c, POP_BLOCK);
  2652.     block_pop(c, SETUP_LOOP);
  2653.     if (NCH(n) > 8)
  2654.         com_node(c, CHILD(n, 8));
  2655.     com_backpatch(c, break_anchor);
  2656. }
  2657.  
  2658. /* Code generated for "try: S finally: Sf" is as follows:
  2659.    
  2660.         SETUP_FINALLY    L
  2661.         <code for S>
  2662.         POP_BLOCK
  2663.         LOAD_CONST    <nil>
  2664.     L:    <code for Sf>
  2665.         END_FINALLY
  2666.    
  2667.    The special instructions use the block stack.  Each block
  2668.    stack entry contains the instruction that created it (here
  2669.    SETUP_FINALLY), the level of the value stack at the time the
  2670.    block stack entry was created, and a label (here L).
  2671.    
  2672.    SETUP_FINALLY:
  2673.     Pushes the current value stack level and the label
  2674.     onto the block stack.
  2675.    POP_BLOCK:
  2676.     Pops en entry from the block stack, and pops the value
  2677.     stack until its level is the same as indicated on the
  2678.     block stack.  (The label is ignored.)
  2679.    END_FINALLY:
  2680.     Pops a variable number of entries from the *value* stack
  2681.     and re-raises the exception they specify.  The number of
  2682.     entries popped depends on the (pseudo) exception type.
  2683.    
  2684.    The block stack is unwound when an exception is raised:
  2685.    when a SETUP_FINALLY entry is found, the exception is pushed
  2686.    onto the value stack (and the exception condition is cleared),
  2687.    and the interpreter jumps to the label gotten from the block
  2688.    stack.
  2689.    
  2690.    Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
  2691.    (The contents of the value stack is shown in [], with the top
  2692.    at the right; 'tb' is trace-back info, 'val' the exception's
  2693.    associated value, and 'exc' the exception.)
  2694.    
  2695.    Value stack        Label    Instruction    Argument
  2696.    []                SETUP_EXCEPT    L1
  2697.    []                <code for S>
  2698.    []                POP_BLOCK
  2699.    []                JUMP_FORWARD    L0
  2700.    
  2701.    [tb, val, exc]    L1:    DUP                )
  2702.    [tb, val, exc, exc]        <evaluate E1>            )
  2703.    [tb, val, exc, exc, E1]    COMPARE_OP    EXC_MATCH    ) only if E1
  2704.    [tb, val, exc, 1-or-0]    JUMP_IF_FALSE    L2        )
  2705.    [tb, val, exc, 1]        POP                )
  2706.    [tb, val, exc]        POP
  2707.    [tb, val]            <assign to V1>    (or POP if no V1)
  2708.    [tb]                POP
  2709.    []                <code for S1>
  2710.                    JUMP_FORWARD    L0
  2711.    
  2712.    [tb, val, exc, 0]    L2:    POP
  2713.    [tb, val, exc]        DUP
  2714.    .............................etc.......................
  2715.  
  2716.    [tb, val, exc, 0]    Ln+1:    POP
  2717.    [tb, val, exc]           END_FINALLY    # re-raise exception
  2718.    
  2719.    []            L0:    <next statement>
  2720.    
  2721.    Of course, parts are not generated if Vi or Ei is not present.
  2722. */
  2723.  
  2724. static void
  2725. com_try_except(struct compiling *c, node *n)
  2726. {
  2727.     int except_anchor = 0;
  2728.     int end_anchor = 0;
  2729.     int else_anchor = 0;
  2730.     int i;
  2731.     node *ch;
  2732.  
  2733.     com_addfwref(c, SETUP_EXCEPT, &except_anchor);
  2734.     block_push(c, SETUP_EXCEPT);
  2735.     com_node(c, CHILD(n, 2));
  2736.     com_addbyte(c, POP_BLOCK);
  2737.     block_pop(c, SETUP_EXCEPT);
  2738.     com_addfwref(c, JUMP_FORWARD, &else_anchor);
  2739.     com_backpatch(c, except_anchor);
  2740.     for (i = 3;
  2741.          i < NCH(n) && TYPE(ch = CHILD(n, i)) == except_clause;
  2742.          i += 3) {
  2743.         /* except_clause: 'except' [expr [',' var]] */
  2744.         if (except_anchor == 0) {
  2745.             com_error(c, PyExc_SyntaxError,
  2746.                   "default 'except:' must be last");
  2747.             break;
  2748.         }
  2749.         except_anchor = 0;
  2750.         com_push(c, 3); /* tb, val, exc pushed by exception */
  2751.         com_addoparg(c, SET_LINENO, ch->n_lineno);
  2752.         if (NCH(ch) > 1) {
  2753.             com_addbyte(c, DUP_TOP);
  2754.             com_push(c, 1);
  2755.             com_node(c, CHILD(ch, 1));
  2756.             com_addoparg(c, COMPARE_OP, EXC_MATCH);
  2757.             com_pop(c, 1);
  2758.             com_addfwref(c, JUMP_IF_FALSE, &except_anchor);
  2759.             com_addbyte(c, POP_TOP);
  2760.             com_pop(c, 1);
  2761.         }
  2762.         com_addbyte(c, POP_TOP);
  2763.         com_pop(c, 1);
  2764.         if (NCH(ch) > 3)
  2765.             com_assign(c, CHILD(ch, 3), OP_ASSIGN, NULL);
  2766.         else {
  2767.             com_addbyte(c, POP_TOP);
  2768.             com_pop(c, 1);
  2769.         }
  2770.         com_addbyte(c, POP_TOP);
  2771.         com_pop(c, 1);
  2772.         com_node(c, CHILD(n, i+2));
  2773.         com_addfwref(c, JUMP_FORWARD, &end_anchor);
  2774.         if (except_anchor) {
  2775.             com_backpatch(c, except_anchor);
  2776.             /* We come in with [tb, val, exc, 0] on the
  2777.                stack; one pop and it's the same as
  2778.                expected at the start of the loop */
  2779.             com_addbyte(c, POP_TOP);
  2780.         }
  2781.     }
  2782.     /* We actually come in here with [tb, val, exc] but the
  2783.        END_FINALLY will zap those and jump around.
  2784.        The c_stacklevel does not reflect them so we need not pop
  2785.        anything. */
  2786.     com_addbyte(c, END_FINALLY);
  2787.     com_backpatch(c, else_anchor);
  2788.     if (i < NCH(n))
  2789.         com_node(c, CHILD(n, i+2));
  2790.     com_backpatch(c, end_anchor);
  2791. }
  2792.  
  2793. static void
  2794. com_try_finally(struct compiling *c, node *n)
  2795. {
  2796.     int finally_anchor = 0;
  2797.     node *ch;
  2798.  
  2799.     com_addfwref(c, SETUP_FINALLY, &finally_anchor);
  2800.     block_push(c, SETUP_FINALLY);
  2801.     com_node(c, CHILD(n, 2));
  2802.     com_addbyte(c, POP_BLOCK);
  2803.     block_pop(c, SETUP_FINALLY);
  2804.     block_push(c, END_FINALLY);
  2805.     com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  2806.     /* While the generated code pushes only one item,
  2807.        the try-finally handling can enter here with
  2808.        up to three items.  OK, here are the details:
  2809.        3 for an exception, 2 for RETURN, 1 for BREAK. */
  2810.     com_push(c, 3);
  2811.     com_backpatch(c, finally_anchor);
  2812.     ch = CHILD(n, NCH(n)-1);
  2813.     com_addoparg(c, SET_LINENO, ch->n_lineno);
  2814.     com_node(c, ch);
  2815.     com_addbyte(c, END_FINALLY);
  2816.     block_pop(c, END_FINALLY);
  2817.     com_pop(c, 3); /* Matches the com_push above */
  2818. }
  2819.  
  2820. static void
  2821. com_try_stmt(struct compiling *c, node *n)
  2822. {
  2823.     REQ(n, try_stmt);
  2824.     /* 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
  2825.      | 'try' ':' suite 'finally' ':' suite */
  2826.     if (TYPE(CHILD(n, 3)) != except_clause)
  2827.         com_try_finally(c, n);
  2828.     else
  2829.         com_try_except(c, n);
  2830. }
  2831.  
  2832. static node *
  2833. get_rawdocstring(node *n)
  2834. {
  2835.     int i;
  2836.  
  2837.   /* Label to avoid tail recursion */
  2838.   next:
  2839.     switch (TYPE(n)) {
  2840.  
  2841.     case suite:
  2842.         if (NCH(n) == 1) {
  2843.             n = CHILD(n, 0);
  2844.             goto next;
  2845.         }
  2846.         /* Fall through */
  2847.     case file_input:
  2848.         for (i = 0; i < NCH(n); i++) {
  2849.             node *ch = CHILD(n, i);
  2850.             if (TYPE(ch) == stmt) {
  2851.                 n = ch;
  2852.                 goto next;
  2853.             }
  2854.         }
  2855.         break;
  2856.  
  2857.     case stmt:
  2858.     case simple_stmt:
  2859.     case small_stmt:
  2860.         n = CHILD(n, 0);
  2861.         goto next;
  2862.  
  2863.     case expr_stmt:
  2864.     case testlist:
  2865.     case test:
  2866.     case and_test:
  2867.     case not_test:
  2868.     case comparison:
  2869.     case expr:
  2870.     case xor_expr:
  2871.     case and_expr:
  2872.     case shift_expr:
  2873.     case arith_expr:
  2874.     case term:
  2875.     case factor:
  2876.     case power:
  2877.         if (NCH(n) == 1) {
  2878.             n = CHILD(n, 0);
  2879.             goto next;
  2880.         }
  2881.         break;
  2882.  
  2883.     case atom:
  2884.         if (TYPE(CHILD(n, 0)) == STRING)
  2885.             return n;
  2886.         break;
  2887.  
  2888.     }
  2889.     return NULL;
  2890. }
  2891.  
  2892. static PyObject *
  2893. get_docstring(node *n)
  2894. {
  2895.     /* Don't generate doc-strings if run with -OO */
  2896.     if (Py_OptimizeFlag > 1)
  2897.         return NULL;
  2898.     n = get_rawdocstring(n);
  2899.     if (n == NULL)
  2900.         return NULL;
  2901.     return parsestrplus(n);
  2902. }
  2903.  
  2904. static void
  2905. com_suite(struct compiling *c, node *n)
  2906. {
  2907.     REQ(n, suite);
  2908.     /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */
  2909.     if (NCH(n) == 1) {
  2910.         com_node(c, CHILD(n, 0));
  2911.     }
  2912.     else {
  2913.         int i;
  2914.         for (i = 0; i < NCH(n); i++) {
  2915.             node *ch = CHILD(n, i);
  2916.             if (TYPE(ch) == stmt)
  2917.                 com_node(c, ch);
  2918.         }
  2919.     }
  2920. }
  2921.  
  2922. /* ARGSUSED */
  2923. static void
  2924. com_continue_stmt(struct compiling *c, node *n)
  2925. {
  2926.     int i = c->c_nblocks;
  2927.     if (i-- > 0 && c->c_block[i] == SETUP_LOOP) {
  2928.         com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  2929.     }
  2930.     else if (i <= 0) {
  2931.         /* at the outer level */
  2932.         com_error(c, PyExc_SyntaxError,
  2933.               "'continue' not properly in loop");
  2934.     }
  2935.     else {
  2936.         int j;
  2937.         for (j = 0; j <= i; ++j) {
  2938.             if (c->c_block[j] == SETUP_LOOP)
  2939.                 break;
  2940.         }
  2941.         if (j < i+1) {
  2942.             /* there is a loop, but something interferes */
  2943.             for (++j; j <= i; ++j) {
  2944.                 if (c->c_block[i] == SETUP_EXCEPT
  2945.                     || c->c_block[i] == SETUP_FINALLY) {
  2946.                     com_error(c, PyExc_SyntaxError,
  2947.                    "'continue' not supported inside 'try' clause");
  2948.                     return;
  2949.                 }
  2950.             }
  2951.         }
  2952.         com_error(c, PyExc_SyntaxError,
  2953.               "'continue' not properly in loop");
  2954.     }
  2955.     /* XXX Could allow it inside a 'finally' clause
  2956.        XXX if we could pop the exception still on the stack */
  2957. }
  2958.  
  2959. static int
  2960. com_argdefs(struct compiling *c, node *n)
  2961. {
  2962.     int i, nch, nargs, ndefs;
  2963.     if (TYPE(n) == lambdef) {
  2964.         /* lambdef: 'lambda' [varargslist] ':' test */
  2965.         n = CHILD(n, 1);
  2966.     }
  2967.     else {
  2968.         REQ(n, funcdef); /* funcdef: 'def' NAME parameters ... */
  2969.         n = CHILD(n, 2);
  2970.         REQ(n, parameters); /* parameters: '(' [varargslist] ')' */
  2971.         n = CHILD(n, 1);
  2972.     }
  2973.     if (TYPE(n) != varargslist)
  2974.             return 0;
  2975.     /* varargslist:
  2976.         (fpdef ['=' test] ',')* '*' ....... |
  2977.         fpdef ['=' test] (',' fpdef ['=' test])* [','] */
  2978.     nch = NCH(n);
  2979.     nargs = 0;
  2980.     ndefs = 0;
  2981.     for (i = 0; i < nch; i++) {
  2982.         int t;
  2983.         if (TYPE(CHILD(n, i)) == STAR ||
  2984.             TYPE(CHILD(n, i)) == DOUBLESTAR)
  2985.             break;
  2986.         nargs++;
  2987.         i++;
  2988.         if (i >= nch)
  2989.             t = RPAR; /* Anything except EQUAL or COMMA */
  2990.         else
  2991.             t = TYPE(CHILD(n, i));
  2992.         if (t == EQUAL) {
  2993.             i++;
  2994.             ndefs++;
  2995.             com_node(c, CHILD(n, i));
  2996.             i++;
  2997.             if (i >= nch)
  2998.                 break;
  2999.             t = TYPE(CHILD(n, i));
  3000.         }
  3001.         else {
  3002.             /* Treat "(a=1, b)" as an error */
  3003.             if (ndefs)
  3004.                 com_error(c, PyExc_SyntaxError,
  3005.                 "non-default argument follows default argument");
  3006.         }
  3007.         if (t != COMMA)
  3008.             break;
  3009.     }
  3010.     return ndefs;
  3011. }
  3012.  
  3013. static void
  3014. com_funcdef(struct compiling *c, node *n)
  3015. {
  3016.     PyObject *v;
  3017.     REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */
  3018.     v = (PyObject *)icompile(n, c);
  3019.     if (v == NULL)
  3020.         c->c_errors++;
  3021.     else {
  3022.         int i = com_addconst(c, v);
  3023.         int ndefs = com_argdefs(c, n);
  3024.         com_addoparg(c, LOAD_CONST, i);
  3025.         com_push(c, 1);
  3026.         com_addoparg(c, MAKE_FUNCTION, ndefs);
  3027.         com_pop(c, ndefs);
  3028.         com_addopname(c, STORE_NAME, CHILD(n, 1));
  3029.         com_pop(c, 1);
  3030.         Py_DECREF(v);
  3031.     }
  3032. }
  3033.  
  3034. static void
  3035. com_bases(struct compiling *c, node *n)
  3036. {
  3037.     int i;
  3038.     REQ(n, testlist);
  3039.     /* testlist: test (',' test)* [','] */
  3040.     for (i = 0; i < NCH(n); i += 2)
  3041.         com_node(c, CHILD(n, i));
  3042.     i = (NCH(n)+1) / 2;
  3043.     com_addoparg(c, BUILD_TUPLE, i);
  3044.     com_pop(c, i-1);
  3045. }
  3046.  
  3047. static void
  3048. com_classdef(struct compiling *c, node *n)
  3049. {
  3050.     int i;
  3051.     PyObject *v;
  3052.     REQ(n, classdef);
  3053.     /* classdef: class NAME ['(' testlist ')'] ':' suite */
  3054.     if ((v = PyString_InternFromString(STR(CHILD(n, 1)))) == NULL) {
  3055.         c->c_errors++;
  3056.         return;
  3057.     }
  3058.     /* Push the class name on the stack */
  3059.     i = com_addconst(c, v);
  3060.     com_addoparg(c, LOAD_CONST, i);
  3061.     com_push(c, 1);
  3062.     Py_DECREF(v);
  3063.     /* Push the tuple of base classes on the stack */
  3064.     if (TYPE(CHILD(n, 2)) != LPAR) {
  3065.         com_addoparg(c, BUILD_TUPLE, 0);
  3066.         com_push(c, 1);
  3067.     }
  3068.     else
  3069.         com_bases(c, CHILD(n, 3));
  3070.     v = (PyObject *)icompile(n, c);
  3071.     if (v == NULL)
  3072.         c->c_errors++;
  3073.     else {
  3074.         i = com_addconst(c, v);
  3075.         com_addoparg(c, LOAD_CONST, i);
  3076.         com_push(c, 1);
  3077.         com_addoparg(c, MAKE_FUNCTION, 0);
  3078.         com_addoparg(c, CALL_FUNCTION, 0);
  3079.         com_addbyte(c, BUILD_CLASS);
  3080.         com_pop(c, 2);
  3081.         com_addopname(c, STORE_NAME, CHILD(n, 1));
  3082.         Py_DECREF(v);
  3083.     }
  3084. }
  3085.  
  3086. static void
  3087. com_node(struct compiling *c, node *n)
  3088. {
  3089.     switch (TYPE(n)) {
  3090.     
  3091.     /* Definition nodes */
  3092.     
  3093.     case funcdef:
  3094.         com_funcdef(c, n);
  3095.         break;
  3096.     case classdef:
  3097.         com_classdef(c, n);
  3098.         break;
  3099.     
  3100.     /* Trivial parse tree nodes */
  3101.     
  3102.     case stmt:
  3103.     case small_stmt:
  3104.     case flow_stmt:
  3105.         com_node(c, CHILD(n, 0));
  3106.         break;
  3107.  
  3108.     case simple_stmt:
  3109.         /* small_stmt (';' small_stmt)* [';'] NEWLINE */
  3110.         com_addoparg(c, SET_LINENO, n->n_lineno);
  3111.         {
  3112.             int i;
  3113.             for (i = 0; i < NCH(n)-1; i += 2)
  3114.                 com_node(c, CHILD(n, i));
  3115.         }
  3116.         break;
  3117.     
  3118.     case compound_stmt:
  3119.         com_addoparg(c, SET_LINENO, n->n_lineno);
  3120.         com_node(c, CHILD(n, 0));
  3121.         break;
  3122.  
  3123.     /* Statement nodes */
  3124.     
  3125.     case expr_stmt:
  3126.         com_expr_stmt(c, n);
  3127.         break;
  3128.     case print_stmt:
  3129.         com_print_stmt(c, n);
  3130.         break;
  3131.     case del_stmt: /* 'del' exprlist */
  3132.         com_assign(c, CHILD(n, 1), OP_DELETE, NULL);
  3133.         break;
  3134.     case pass_stmt:
  3135.         break;
  3136.     case break_stmt:
  3137.         if (c->c_loops == 0) {
  3138.             com_error(c, PyExc_SyntaxError,
  3139.                   "'break' outside loop");
  3140.         }
  3141.         com_addbyte(c, BREAK_LOOP);
  3142.         break;
  3143.     case continue_stmt:
  3144.         com_continue_stmt(c, n);
  3145.         break;
  3146.     case return_stmt:
  3147.         com_return_stmt(c, n);
  3148.         break;
  3149.     case raise_stmt:
  3150.         com_raise_stmt(c, n);
  3151.         break;
  3152.     case import_stmt:
  3153.         com_import_stmt(c, n);
  3154.         break;
  3155.     case global_stmt:
  3156.         com_global_stmt(c, n);
  3157.         break;
  3158.     case exec_stmt:
  3159.         com_exec_stmt(c, n);
  3160.         break;
  3161.     case assert_stmt:
  3162.         com_assert_stmt(c, n);
  3163.         break;
  3164.     case if_stmt:
  3165.         com_if_stmt(c, n);
  3166.         break;
  3167.     case while_stmt:
  3168.         com_while_stmt(c, n);
  3169.         break;
  3170.     case for_stmt:
  3171.         com_for_stmt(c, n);
  3172.         break;
  3173.     case try_stmt:
  3174.         com_try_stmt(c, n);
  3175.         break;
  3176.     case suite:
  3177.         com_suite(c, n);
  3178.         break;
  3179.     
  3180.     /* Expression nodes */
  3181.     
  3182.     case testlist:
  3183.         com_list(c, n, 0);
  3184.         break;
  3185.     case test:
  3186.         com_test(c, n);
  3187.         break;
  3188.     case and_test:
  3189.         com_and_test(c, n);
  3190.         break;
  3191.     case not_test:
  3192.         com_not_test(c, n);
  3193.         break;
  3194.     case comparison:
  3195.         com_comparison(c, n);
  3196.         break;
  3197.     case exprlist:
  3198.         com_list(c, n, 0);
  3199.         break;
  3200.     case expr:
  3201.         com_expr(c, n);
  3202.         break;
  3203.     case xor_expr:
  3204.         com_xor_expr(c, n);
  3205.         break;
  3206.     case and_expr:
  3207.         com_and_expr(c, n);
  3208.         break;
  3209.     case shift_expr:
  3210.         com_shift_expr(c, n);
  3211.         break;
  3212.     case arith_expr:
  3213.         com_arith_expr(c, n);
  3214.         break;
  3215.     case term:
  3216.         com_term(c, n);
  3217.         break;
  3218.     case factor:
  3219.         com_factor(c, n);
  3220.         break;
  3221.     case power:
  3222.         com_power(c, n);
  3223.         break;
  3224.     case atom:
  3225.         com_atom(c, n);
  3226.         break;
  3227.     
  3228.     default:
  3229.         /* XXX fprintf(stderr, "node type %d\n", TYPE(n)); */
  3230.         com_error(c, PyExc_SystemError,
  3231.               "com_node: unexpected node type");
  3232.     }
  3233. }
  3234.  
  3235. static void com_fplist(struct compiling *, node *);
  3236.  
  3237. static void
  3238. com_fpdef(struct compiling *c, node *n)
  3239. {
  3240.     REQ(n, fpdef); /* fpdef: NAME | '(' fplist ')' */
  3241.     if (TYPE(CHILD(n, 0)) == LPAR)
  3242.         com_fplist(c, CHILD(n, 1));
  3243.     else {
  3244.         com_addoparg(c, STORE_FAST, com_newlocal(c, STR(CHILD(n, 0))));
  3245.         com_pop(c, 1);
  3246.     }
  3247. }
  3248.  
  3249. static void
  3250. com_fplist(struct compiling *c, node *n)
  3251. {
  3252.     REQ(n, fplist); /* fplist: fpdef (',' fpdef)* [','] */
  3253.     if (NCH(n) == 1) {
  3254.         com_fpdef(c, CHILD(n, 0));
  3255.     }
  3256.     else {
  3257.         int i = (NCH(n)+1)/2;
  3258.         com_addoparg(c, UNPACK_SEQUENCE, i);
  3259.         com_push(c, i-1);
  3260.         for (i = 0; i < NCH(n); i += 2)
  3261.             com_fpdef(c, CHILD(n, i));
  3262.     }
  3263. }
  3264.  
  3265. static void
  3266. com_arglist(struct compiling *c, node *n)
  3267. {
  3268.     int nch, i;
  3269.     int complex = 0;
  3270.     char nbuf[10];
  3271.     REQ(n, varargslist);
  3272.     /* varargslist:
  3273.         (fpdef ['=' test] ',')* (fpdef ['=' test] | '*' .....) */
  3274.     nch = NCH(n);
  3275.     /* Enter all arguments in table of locals */
  3276.     for (i = 0; i < nch; i++) {
  3277.         node *ch = CHILD(n, i);
  3278.         node *fp;
  3279.         char *name;
  3280.         PyObject *nameval;
  3281.         if (TYPE(ch) == STAR || TYPE(ch) == DOUBLESTAR)
  3282.             break;
  3283.         REQ(ch, fpdef); /* fpdef: NAME | '(' fplist ')' */
  3284.         fp = CHILD(ch, 0);
  3285.         if (TYPE(fp) == NAME)
  3286.             name = STR(fp);
  3287.         else {
  3288.             name = nbuf;
  3289.             sprintf(nbuf, ".%d", i);
  3290.             complex = 1;
  3291.         }
  3292.         nameval = PyString_InternFromString(name);
  3293.         if (nameval == NULL) {
  3294.             c->c_errors++;
  3295.         }
  3296.         if (PyDict_GetItem(c->c_locals, nameval)) {
  3297.             com_error(c, PyExc_SyntaxError,
  3298.                   "duplicate argument in function definition");
  3299.         }
  3300.         com_newlocal_o(c, nameval);
  3301.         Py_DECREF(nameval);
  3302.         c->c_argcount++;
  3303.         if (++i >= nch)
  3304.             break;
  3305.         ch = CHILD(n, i);
  3306.         if (TYPE(ch) == EQUAL)
  3307.             i += 2;
  3308.         else
  3309.             REQ(ch, COMMA);
  3310.     }
  3311.     /* Handle *arguments */
  3312.     if (i < nch) {
  3313.         node *ch;
  3314.         ch = CHILD(n, i);
  3315.         if (TYPE(ch) != DOUBLESTAR) {
  3316.             REQ(ch, STAR);
  3317.             ch = CHILD(n, i+1);
  3318.             if (TYPE(ch) == NAME) {
  3319.                 c->c_flags |= CO_VARARGS;
  3320.                 i += 3;
  3321.                 com_newlocal(c, STR(ch));
  3322.             }
  3323.         }
  3324.     }
  3325.     /* Handle **keywords */
  3326.     if (i < nch) {
  3327.         node *ch;
  3328.         ch = CHILD(n, i);
  3329.         if (TYPE(ch) != DOUBLESTAR) {
  3330.             REQ(ch, STAR);
  3331.             ch = CHILD(n, i+1);
  3332.             REQ(ch, STAR);
  3333.             ch = CHILD(n, i+2);
  3334.         }
  3335.         else
  3336.             ch = CHILD(n, i+1);
  3337.         REQ(ch, NAME);
  3338.         c->c_flags |= CO_VARKEYWORDS;
  3339.         com_newlocal(c, STR(ch));
  3340.     }
  3341.     if (complex) {
  3342.         /* Generate code for complex arguments only after
  3343.            having counted the simple arguments */
  3344.         int ilocal = 0;
  3345.         for (i = 0; i < nch; i++) {
  3346.             node *ch = CHILD(n, i);
  3347.             node *fp;
  3348.             if (TYPE(ch) == STAR || TYPE(ch) == DOUBLESTAR)
  3349.                 break;
  3350.             REQ(ch, fpdef); /* fpdef: NAME | '(' fplist ')' */
  3351.             fp = CHILD(ch, 0);
  3352.             if (TYPE(fp) != NAME) {
  3353.                 com_addoparg(c, LOAD_FAST, ilocal);
  3354.                 com_push(c, 1);
  3355.                 com_fpdef(c, ch);
  3356.             }
  3357.             ilocal++;
  3358.             if (++i >= nch)
  3359.                 break;
  3360.             ch = CHILD(n, i);
  3361.             if (TYPE(ch) == EQUAL)
  3362.                 i += 2;
  3363.             else
  3364.                 REQ(ch, COMMA);
  3365.         }
  3366.     }
  3367. }
  3368.  
  3369. static void
  3370. com_file_input(struct compiling *c, node *n)
  3371. {
  3372.     int i;
  3373.     PyObject *doc;
  3374.     REQ(n, file_input); /* (NEWLINE | stmt)* ENDMARKER */
  3375.     doc = get_docstring(n);
  3376.     if (doc != NULL) {
  3377.         int i = com_addconst(c, doc);
  3378.         Py_DECREF(doc);
  3379.         com_addoparg(c, LOAD_CONST, i);
  3380.         com_push(c, 1);
  3381.         com_addopnamestr(c, STORE_NAME, "__doc__");
  3382.         com_pop(c, 1);
  3383.     }
  3384.     for (i = 0; i < NCH(n); i++) {
  3385.         node *ch = CHILD(n, i);
  3386.         if (TYPE(ch) != ENDMARKER && TYPE(ch) != NEWLINE)
  3387.             com_node(c, ch);
  3388.     }
  3389. }
  3390.  
  3391. /* Top-level compile-node interface */
  3392.  
  3393. static void
  3394. compile_funcdef(struct compiling *c, node *n)
  3395. {
  3396.     PyObject *doc;
  3397.     node *ch;
  3398.     REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */
  3399.     c->c_name = STR(CHILD(n, 1));
  3400.     doc = get_docstring(CHILD(n, 4));
  3401.     if (doc != NULL) {
  3402.         (void) com_addconst(c, doc);
  3403.         Py_DECREF(doc);
  3404.     }
  3405.     else
  3406.         (void) com_addconst(c, Py_None); /* No docstring */
  3407.     ch = CHILD(n, 2); /* parameters: '(' [varargslist] ')' */
  3408.     ch = CHILD(ch, 1); /* ')' | varargslist */
  3409.     if (TYPE(ch) == varargslist)
  3410.         com_arglist(c, ch);
  3411.     c->c_infunction = 1;
  3412.     com_node(c, CHILD(n, 4));
  3413.     c->c_infunction = 0;
  3414.     com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  3415.     com_push(c, 1);
  3416.     com_addbyte(c, RETURN_VALUE);
  3417.     com_pop(c, 1);
  3418. }
  3419.  
  3420. static void
  3421. compile_lambdef(struct compiling *c, node *n)
  3422. {
  3423.     node *ch;
  3424.     REQ(n, lambdef); /* lambdef: 'lambda' [varargslist] ':' test */
  3425.     c->c_name = "<lambda>";
  3426.  
  3427.     ch = CHILD(n, 1);
  3428.     (void) com_addconst(c, Py_None); /* No docstring */
  3429.     if (TYPE(ch) == varargslist) {
  3430.         com_arglist(c, ch);
  3431.         ch = CHILD(n, 3);
  3432.     }
  3433.     else
  3434.         ch = CHILD(n, 2);
  3435.     com_node(c, ch);
  3436.     com_addbyte(c, RETURN_VALUE);
  3437.     com_pop(c, 1);
  3438. }
  3439.  
  3440. static void
  3441. compile_classdef(struct compiling *c, node *n)
  3442. {
  3443.     node *ch;
  3444.     PyObject *doc;
  3445.     REQ(n, classdef);
  3446.     /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */
  3447.     c->c_name = STR(CHILD(n, 1));
  3448. #ifdef PRIVATE_NAME_MANGLING
  3449.     c->c_private = c->c_name;
  3450. #endif
  3451.     ch = CHILD(n, NCH(n)-1); /* The suite */
  3452.     doc = get_docstring(ch);
  3453.     if (doc != NULL) {
  3454.         int i = com_addconst(c, doc);
  3455.         Py_DECREF(doc);
  3456.         com_addoparg(c, LOAD_CONST, i);
  3457.         com_push(c, 1);
  3458.         com_addopnamestr(c, STORE_NAME, "__doc__");
  3459.         com_pop(c, 1);
  3460.     }
  3461.     else
  3462.         (void) com_addconst(c, Py_None);
  3463.     com_node(c, ch);
  3464.     com_addbyte(c, LOAD_LOCALS);
  3465.     com_push(c, 1);
  3466.     com_addbyte(c, RETURN_VALUE);
  3467.     com_pop(c, 1);
  3468. }
  3469.  
  3470. static void
  3471. compile_node(struct compiling *c, node *n)
  3472. {
  3473.     com_addoparg(c, SET_LINENO, n->n_lineno);
  3474.     
  3475.     switch (TYPE(n)) {
  3476.     
  3477.     case single_input: /* One interactive command */
  3478.         /* NEWLINE | simple_stmt | compound_stmt NEWLINE */
  3479.         c->c_interactive++;
  3480.         n = CHILD(n, 0);
  3481.         if (TYPE(n) != NEWLINE)
  3482.             com_node(c, n);
  3483.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  3484.         com_push(c, 1);
  3485.         com_addbyte(c, RETURN_VALUE);
  3486.         com_pop(c, 1);
  3487.         c->c_interactive--;
  3488.         break;
  3489.     
  3490.     case file_input: /* A whole file, or built-in function exec() */
  3491.         com_file_input(c, n);
  3492.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  3493.         com_push(c, 1);
  3494.         com_addbyte(c, RETURN_VALUE);
  3495.         com_pop(c, 1);
  3496.         break;
  3497.     
  3498.     case eval_input: /* Built-in function input() */
  3499.         com_node(c, CHILD(n, 0));
  3500.         com_addbyte(c, RETURN_VALUE);
  3501.         com_pop(c, 1);
  3502.         break;
  3503.     
  3504.     case lambdef: /* anonymous function definition */
  3505.         compile_lambdef(c, n);
  3506.         break;
  3507.  
  3508.     case funcdef: /* A function definition */
  3509.         compile_funcdef(c, n);
  3510.         break;
  3511.     
  3512.     case classdef: /* A class definition */
  3513.         compile_classdef(c, n);
  3514.         break;
  3515.     
  3516.     default:
  3517.         /* XXX fprintf(stderr, "node type %d\n", TYPE(n)); */
  3518.         com_error(c, PyExc_SystemError,
  3519.               "compile_node: unexpected node type");
  3520.     }
  3521. }
  3522.  
  3523. /* Optimization for local variables in functions (and *only* functions).
  3524.  
  3525.    This replaces all LOAD_NAME, STORE_NAME and DELETE_NAME
  3526.    instructions that refer to local variables with LOAD_FAST etc.
  3527.    The latter instructions are much faster because they don't need to
  3528.    look up the variable name in a dictionary.
  3529.  
  3530.    To find all local variables, we check all STORE_NAME, IMPORT_FROM
  3531.    and DELETE_NAME instructions.  This yields all local variables,
  3532.    function definitions, class definitions and import statements.
  3533.    Argument names have already been entered into the list by the
  3534.    special processing for the argument list.
  3535.  
  3536.    All remaining LOAD_NAME instructions must refer to non-local (global
  3537.    or builtin) variables, so are replaced by LOAD_GLOBAL.
  3538.  
  3539.    There are two problems:  'from foo import *' and 'exec' may introduce
  3540.    local variables that we can't know while compiling.  If this is the
  3541.    case, we can still optimize bona fide locals (since those
  3542.    statements will be surrounded by fast_2_locals() and
  3543.    locals_2_fast()), but we can't change LOAD_NAME to LOAD_GLOBAL.
  3544.  
  3545.    NB: this modifies the string object c->c_code!  */
  3546.  
  3547. static void
  3548. optimize(struct compiling *c)
  3549. {
  3550.     unsigned char *next_instr, *cur_instr;
  3551.     int opcode;
  3552.     int oparg = 0;
  3553.     PyObject *name;
  3554.     PyObject *error_type, *error_value, *error_traceback;
  3555.     
  3556. #define NEXTOP()    (*next_instr++)
  3557. #define NEXTARG()    (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
  3558. #define GETITEM(v, i)    (PyList_GetItem((v), (i)))
  3559. #define GETNAMEOBJ(i)    (GETITEM(c->c_names, (i)))
  3560.     
  3561.     PyErr_Fetch(&error_type, &error_value, &error_traceback);
  3562.  
  3563.     c->c_flags |= CO_OPTIMIZED;
  3564.     
  3565.     next_instr = (unsigned char *) PyString_AsString(c->c_code);
  3566.     for (;;) {
  3567.         opcode = NEXTOP();
  3568.         if (opcode == STOP_CODE)
  3569.             break;
  3570.         if (HAS_ARG(opcode))
  3571.             oparg = NEXTARG();
  3572.       dispatch_opcode1:
  3573.         switch (opcode) {
  3574.         case STORE_NAME:
  3575.         case DELETE_NAME:
  3576.         case IMPORT_FROM:
  3577.             com_addlocal_o(c, GETNAMEOBJ(oparg));
  3578.             break;
  3579.         case IMPORT_STAR:
  3580.         case EXEC_STMT:
  3581.             c->c_flags &= ~CO_OPTIMIZED;
  3582.             break;
  3583.         case EXTENDED_ARG:
  3584.             opcode = NEXTOP();
  3585.             oparg = oparg<<16 | NEXTARG();
  3586.             goto dispatch_opcode1;
  3587.             break;
  3588.         }
  3589.     }
  3590.     
  3591.     /* TBD: Is this still necessary ? */
  3592.     if (PyDict_GetItemString(c->c_locals, "*") != NULL)
  3593.         c->c_flags &= ~CO_OPTIMIZED;
  3594.     
  3595.     next_instr = (unsigned char *) PyString_AsString(c->c_code);
  3596.     for (;;) {
  3597.         cur_instr = next_instr;
  3598.         opcode = NEXTOP();
  3599.         if (opcode == STOP_CODE)
  3600.             break;
  3601.         if (HAS_ARG(opcode))
  3602.             oparg = NEXTARG();
  3603.       dispatch_opcode2:
  3604.         if (opcode == LOAD_NAME ||
  3605.             opcode == STORE_NAME ||
  3606.             opcode == DELETE_NAME) {
  3607.             PyObject *v;
  3608.             int i;
  3609.             name = GETNAMEOBJ(oparg);
  3610.             v = PyDict_GetItem(c->c_locals, name);
  3611.             if (v == NULL) {
  3612.                 if (opcode == LOAD_NAME &&
  3613.                     (c->c_flags&CO_OPTIMIZED))
  3614.                     cur_instr[0] = LOAD_GLOBAL;
  3615.                 continue;
  3616.             }
  3617.             i = PyInt_AsLong(v);
  3618.             if (i >> 16) /* too big for 2 bytes */
  3619.                 continue;
  3620.             switch (opcode) {
  3621.             case LOAD_NAME: cur_instr[0] = LOAD_FAST; break;
  3622.             case STORE_NAME: cur_instr[0] = STORE_FAST; break;
  3623.             case DELETE_NAME: cur_instr[0] = DELETE_FAST; break;
  3624.             }
  3625.             cur_instr[1] = i & 0xff;
  3626.             cur_instr[2] = i >> 8;
  3627.         }
  3628.         if (opcode == EXTENDED_ARG) {
  3629.             opcode = NEXTOP();
  3630.             oparg = oparg<<16 | NEXTARG();
  3631.             goto dispatch_opcode2;
  3632.         }
  3633.     }
  3634.  
  3635.     if (c->c_errors == 0)
  3636.         PyErr_Restore(error_type, error_value, error_traceback);
  3637. }
  3638.  
  3639. PyCodeObject *
  3640. PyNode_Compile(node *n, char *filename)
  3641. {
  3642.     return jcompile(n, filename, NULL);
  3643. }
  3644.  
  3645. static PyCodeObject *
  3646. icompile(node *n, struct compiling *base)
  3647. {
  3648.     return jcompile(n, base->c_filename, base);
  3649. }
  3650.  
  3651. static PyCodeObject *
  3652. jcompile(node *n, char *filename, struct compiling *base)
  3653. {
  3654.     struct compiling sc;
  3655.     PyCodeObject *co;
  3656.     if (!com_init(&sc, filename))
  3657.         return NULL;
  3658. #ifdef PRIVATE_NAME_MANGLING
  3659.     if (base)
  3660.         sc.c_private = base->c_private;
  3661.     else
  3662.         sc.c_private = NULL;
  3663. #endif
  3664.     compile_node(&sc, n);
  3665.     com_done(&sc);
  3666.     if ((TYPE(n) == funcdef || TYPE(n) == lambdef) && sc.c_errors == 0) {
  3667.         optimize(&sc);
  3668.         sc.c_flags |= CO_NEWLOCALS;
  3669.     }
  3670.     else if (TYPE(n) == classdef)
  3671.         sc.c_flags |= CO_NEWLOCALS;
  3672.     co = NULL;
  3673.     if (sc.c_errors == 0) {
  3674.         PyObject *consts, *names, *varnames, *filename, *name;
  3675.         consts = PyList_AsTuple(sc.c_consts);
  3676.         names = PyList_AsTuple(sc.c_names);
  3677.         varnames = PyList_AsTuple(sc.c_varnames);
  3678.         filename = PyString_InternFromString(sc.c_filename);
  3679.         name = PyString_InternFromString(sc.c_name);
  3680.         if (!PyErr_Occurred())
  3681.             co = PyCode_New(sc.c_argcount,
  3682.                        sc.c_nlocals,
  3683.                        sc.c_maxstacklevel,
  3684.                        sc.c_flags,
  3685.                        sc.c_code,
  3686.                        consts,
  3687.                        names,
  3688.                        varnames,
  3689.                        filename,
  3690.                        name,
  3691.                        sc.c_firstlineno,
  3692.                        sc.c_lnotab);
  3693.         Py_XDECREF(consts);
  3694.         Py_XDECREF(names);
  3695.         Py_XDECREF(varnames);
  3696.         Py_XDECREF(filename);
  3697.         Py_XDECREF(name);
  3698.     }
  3699.     else if (!PyErr_Occurred()) {
  3700.         /* This could happen if someone called PyErr_Clear() after an
  3701.            error was reported above.  That's not supposed to happen,
  3702.            but I just plugged one case and I'm not sure there can't be
  3703.            others.  In that case, raise SystemError so that at least
  3704.            it gets reported instead dumping core. */
  3705.         PyErr_SetString(PyExc_SystemError, "lost syntax error");
  3706.     }
  3707.     com_free(&sc);
  3708.     return co;
  3709. }
  3710.  
  3711. int
  3712. PyCode_Addr2Line(PyCodeObject *co, int addrq)
  3713. {
  3714.     int size = PyString_Size(co->co_lnotab) / 2;
  3715.     unsigned char *p = (unsigned char*)PyString_AsString(co->co_lnotab);
  3716.     int line = co->co_firstlineno;
  3717.     int addr = 0;
  3718.     while (--size >= 0) {
  3719.         addr += *p++;
  3720.         if (addr > addrq)
  3721.             break;
  3722.         line += *p++;
  3723.     }
  3724.     return line;
  3725. }
  3726.