home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Source Code / C / Applications / Python 1.3 / source code / Python / compile.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-12-17  |  59.1 KB  |  2,798 lines  |  [TEXT/R*ch]

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its 
  8. documentation for any purpose and without fee is hereby granted, 
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in 
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI not be used in advertising or publicity pertaining to
  13. distribution of the software without specific, written prior permission.
  14.  
  15. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  16. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  18. FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  21. OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22.  
  23. ******************************************************************/
  24.  
  25. /* Compile an expression node to intermediate code */
  26.  
  27. /* XXX TO DO:
  28.    XXX Compute maximum needed stack sizes while compiling;
  29.    XXX   then frame object can be one malloc and no stack checks are needed
  30.    XXX add __doc__ attribute == co_doc to code object attributes
  31.    XXX don't execute doc string
  32.    XXX Generate simple jump for break/return outside 'try...finally'
  33.    XXX get rid of SET_LINENO instructions, use JAR's table trick
  34.    XXX   (need an option to put them back in, for debugger!)
  35.    XXX other JAR tricks?
  36. */
  37.  
  38. #include "allobjects.h"
  39.  
  40. #include "node.h"
  41. #include "token.h"
  42. #include "graminit.h"
  43. #include "compile.h"
  44. #include "opcode.h"
  45. #include "structmember.h"
  46.  
  47. #include <ctype.h>
  48. #include <errno.h>
  49.  
  50. #define OFF(x) offsetof(codeobject, x)
  51.  
  52. static struct memberlist code_memberlist[] = {
  53.     {"co_argcount",    T_INT,        OFF(co_argcount),    READONLY},
  54.     {"co_nlocals",    T_INT,        OFF(co_nlocals),    READONLY},
  55.     {"co_flags",    T_INT,        OFF(co_flags),        READONLY},
  56.     {"co_code",    T_OBJECT,    OFF(co_code),        READONLY},
  57.     {"co_consts",    T_OBJECT,    OFF(co_consts),        READONLY},
  58.     {"co_names",    T_OBJECT,    OFF(co_names),        READONLY},
  59.     {"co_varnames",    T_OBJECT,    OFF(co_varnames),    READONLY},
  60.     {"co_filename",    T_OBJECT,    OFF(co_filename),    READONLY},
  61.     {"co_name",    T_OBJECT,    OFF(co_name),        READONLY},
  62.     {NULL}    /* Sentinel */
  63. };
  64.  
  65. static object *
  66. code_getattr(co, name)
  67.     codeobject *co;
  68.     char *name;
  69. {
  70.     return getmember((char *)co, code_memberlist, name);
  71. }
  72.  
  73. static void
  74. code_dealloc(co)
  75.     codeobject *co;
  76. {
  77.     XDECREF(co->co_code);
  78.     XDECREF(co->co_consts);
  79.     XDECREF(co->co_names);
  80.     XDECREF(co->co_filename);
  81.     XDECREF(co->co_name);
  82.     XDECREF(co->co_varnames);
  83.     DEL(co);
  84. }
  85.  
  86. static object *
  87. code_repr(co)
  88.     codeobject *co;
  89. {
  90.     char buf[500];
  91.     int lineno = -1;
  92.     char *p = GETSTRINGVALUE(co->co_code);
  93.     char *filename = "???";
  94.     char *name = "???";
  95.     if (*p == SET_LINENO)
  96.         lineno = (p[1] & 0xff) | ((p[2] & 0xff) << 8);
  97.     if (co->co_filename && is_stringobject(co->co_filename))
  98.         filename = getstringvalue(co->co_filename);
  99.     if (co->co_name && is_stringobject(co->co_name))
  100.         name = getstringvalue(co->co_name);
  101.     sprintf(buf, "<code object %.100s at %lx, file \"%.300s\", line %d>",
  102.         name, (long)co, filename, lineno);
  103.     return newstringobject(buf);
  104. }
  105.  
  106. static int
  107. code_compare(co, cp)
  108.     codeobject *co, *cp;
  109. {
  110.     int cmp;
  111.     cmp = cp->co_argcount - cp->co_argcount;
  112.     if (cmp) return cmp;
  113.     cmp = cp->co_nlocals - cp->co_nlocals;
  114.     if (cmp) return cmp;
  115.     cmp = cp->co_flags - cp->co_flags;
  116.     if (cmp) return cmp;
  117.     cmp = cmpobject((object *)co->co_code, (object *)cp->co_code);
  118.     if (cmp) return cmp;
  119.     cmp = cmpobject(co->co_consts, cp->co_consts);
  120.     if (cmp) return cmp;
  121.     cmp = cmpobject(co->co_names, cp->co_names);
  122.     if (cmp) return cmp;
  123.     cmp = cmpobject(co->co_varnames, cp->co_varnames);
  124.     return cmp;
  125. }
  126.  
  127. static long
  128. code_hash(co)
  129.     codeobject *co;
  130. {
  131.     long h, h1, h2, h3, h4;
  132.     h1 = hashobject((object *)co->co_code);
  133.     if (h1 == -1) return -1;
  134.     h2 = hashobject(co->co_consts);
  135.     if (h2 == -1) return -1;
  136.     h3 = hashobject(co->co_names);
  137.     if (h3 == -1) return -1;
  138.     h4 = hashobject(co->co_varnames);
  139.     if (h4 == -1) return -1;
  140.     h = 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. typeobject Codetype = {
  147.     OB_HEAD_INIT(&Typetype)
  148.     0,
  149.     "code",
  150.     sizeof(codeobject),
  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. codeobject *
  165. newcodeobject(argcount, nlocals, flags,
  166.           code, consts, names, varnames, filename, name)
  167.     int argcount;
  168.     int nlocals;
  169.     int flags;
  170.     object *code;
  171.     object *consts;
  172.     object *names;
  173.     object *varnames;
  174.     object *filename;
  175.     object *name;
  176. {
  177.     codeobject *co;
  178.     int i;
  179.     /* Check argument types */
  180.     if (argcount < 0 || nlocals < 0 ||
  181.         code == NULL || !is_stringobject(code) ||
  182.         consts == NULL || !is_tupleobject(consts) ||
  183.         names == NULL || !is_tupleobject(names) ||
  184.         varnames == NULL || !is_tupleobject(varnames) ||
  185.         name == NULL || !is_stringobject(name) ||
  186.         filename == NULL || !is_stringobject(filename)) {
  187.         err_badcall();
  188.         return NULL;
  189.     }
  190.     /* Make sure names and varnames are all strings */
  191.     for (i = gettuplesize(names); --i >= 0; ) {
  192.         object *v = gettupleitem(names, i);
  193.         if (v == NULL || !is_stringobject(v)) {
  194.             err_badcall();
  195.             return NULL;
  196.         }
  197.     }
  198.     for (i = gettuplesize(varnames); --i >= 0; ) {
  199.         object *v = gettupleitem(varnames, i);
  200.         if (v == NULL || !is_stringobject(v)) {
  201.             err_badcall();
  202.             return NULL;
  203.         }
  204.     }
  205.     co = NEWOBJ(codeobject, &Codetype);
  206.     if (co != NULL) {
  207.         co->co_argcount = argcount;
  208.         co->co_nlocals = nlocals;
  209.         co->co_flags = flags;
  210.         INCREF(code);
  211.         co->co_code = (stringobject *)code;
  212.         INCREF(consts);
  213.         co->co_consts = consts;
  214.         INCREF(names);
  215.         co->co_names = names;
  216.         INCREF(varnames);
  217.         co->co_varnames = varnames;
  218.         INCREF(filename);
  219.         co->co_filename = filename;
  220.         INCREF(name);
  221.         co->co_name = name;
  222.     }
  223.     return co;
  224. }
  225.  
  226.  
  227. /* Data structure used internally */
  228.  
  229. #define MAXBLOCKS 20 /* Max static block nesting within a function */
  230.  
  231. struct compiling {
  232.     object *c_code;        /* string */
  233.     object *c_consts;    /* list of objects */
  234.     object *c_names;    /* list of strings (names) */
  235.     object *c_globals;    /* dictionary (value=None) */
  236.     object *c_locals;    /* dictionary (value=localID) */
  237.     object *c_varnames;    /* list (inverse of c_locals) */
  238.     int c_nlocals;        /* index of next local */
  239.     int c_argcount;        /* number of top-level arguments */
  240.     int c_flags;        /* same as co_flags */
  241.     int c_nexti;        /* index into c_code */
  242.     int c_errors;        /* counts errors occurred */
  243.     int c_infunction;    /* set when compiling a function */
  244.     int c_interactive;    /* generating code for interactive command */
  245.     int c_loops;        /* counts nested loops */
  246.     int c_begin;        /* begin of current loop, for 'continue' */
  247.     int c_block[MAXBLOCKS];    /* stack of block types */
  248.     int c_nblocks;        /* current block stack level */
  249.     char *c_filename;    /* filename of current node */
  250.     char *c_name;        /* name of object (e.g. function) */
  251. };
  252.  
  253.  
  254. /* Interface to the block stack */
  255.  
  256. static void
  257. block_push(c, type)
  258.     struct compiling *c;
  259.     int type;
  260. {
  261.     if (c->c_nblocks >= MAXBLOCKS) {
  262.         err_setstr(SystemError, "too many statically nested blocks");
  263.         c->c_errors++;
  264.     }
  265.     else {
  266.         c->c_block[c->c_nblocks++] = type;
  267.     }
  268. }
  269.  
  270. static void
  271. block_pop(c, type)
  272.     struct compiling *c;
  273.     int type;
  274. {
  275.     if (c->c_nblocks > 0)
  276.         c->c_nblocks--;
  277.     if (c->c_block[c->c_nblocks] != type && c->c_errors == 0) {
  278.         err_setstr(SystemError, "bad block pop");
  279.         c->c_errors++;
  280.     }
  281. }
  282.  
  283.  
  284. /* Prototype forward declarations */
  285.  
  286. static int com_init PROTO((struct compiling *, char *));
  287. static void com_free PROTO((struct compiling *));
  288. static void com_done PROTO((struct compiling *));
  289. static void com_node PROTO((struct compiling *, struct _node *));
  290. static void com_addbyte PROTO((struct compiling *, int));
  291. static void com_addint PROTO((struct compiling *, int));
  292. static void com_addoparg PROTO((struct compiling *, int, int));
  293. static void com_addfwref PROTO((struct compiling *, int, int *));
  294. static void com_backpatch PROTO((struct compiling *, int));
  295. static int com_add PROTO((struct compiling *, object *, object *));
  296. static int com_addconst PROTO((struct compiling *, object *));
  297. static int com_addname PROTO((struct compiling *, object *));
  298. static void com_addopname PROTO((struct compiling *, int, node *));
  299. static void com_list PROTO((struct compiling *, node *, int));
  300. static int com_argdefs PROTO((struct compiling *, node *));
  301. static int com_newlocal PROTO((struct compiling *, char *));
  302.  
  303. static int
  304. com_init(c, filename)
  305.     struct compiling *c;
  306.     char *filename;
  307. {
  308.     if ((c->c_code = newsizedstringobject((char *)NULL, 1000)) == NULL)
  309.         goto fail_3;
  310.     if ((c->c_consts = newlistobject(0)) == NULL)
  311.         goto fail_2;
  312.     if ((c->c_names = newlistobject(0)) == NULL)
  313.         goto fail_1;
  314.     if ((c->c_globals = newdictobject()) == NULL)
  315.         goto fail_0;
  316.     if ((c->c_locals = newdictobject()) == NULL)
  317.         goto fail_00;
  318.     if ((c->c_varnames = newlistobject(0)) == NULL)
  319.         goto fail_000;
  320.     c->c_nlocals = 0;
  321.     c->c_argcount = 0;
  322.     c->c_flags = 0;
  323.     c->c_nexti = 0;
  324.     c->c_errors = 0;
  325.     c->c_infunction = 0;
  326.     c->c_interactive = 0;
  327.     c->c_loops = 0;
  328.     c->c_begin = 0;
  329.     c->c_nblocks = 0;
  330.     c->c_filename = filename;
  331.     c->c_name = "?";
  332.     return 1;
  333.     
  334.   fail_000:
  335.       DECREF(c->c_locals);
  336.   fail_00:
  337.       DECREF(c->c_globals);
  338.   fail_0:
  339.       DECREF(c->c_names);
  340.   fail_1:
  341.     DECREF(c->c_consts);
  342.   fail_2:
  343.     DECREF(c->c_code);
  344.   fail_3:
  345.      return 0;
  346. }
  347.  
  348. static void
  349. com_free(c)
  350.     struct compiling *c;
  351. {
  352.     XDECREF(c->c_code);
  353.     XDECREF(c->c_consts);
  354.     XDECREF(c->c_names);
  355.     XDECREF(c->c_globals);
  356.     XDECREF(c->c_locals);
  357.     XDECREF(c->c_varnames);
  358. }
  359.  
  360. static void
  361. com_done(c)
  362.     struct compiling *c;
  363. {
  364.     if (c->c_code != NULL)
  365.         resizestring(&c->c_code, c->c_nexti);
  366. }
  367.  
  368. static void
  369. com_addbyte(c, byte)
  370.     struct compiling *c;
  371.     int byte;
  372. {
  373.     int len;
  374.     /*fprintf(stderr, "%3d: %3d\n", c->c_nexti, byte);*/
  375.     if (byte < 0 || byte > 255) {
  376.         /*
  377.         fprintf(stderr, "XXX compiling bad byte: %d\n", byte);
  378.         fatal("com_addbyte: byte out of range");
  379.         */
  380.         err_setstr(SystemError, "com_addbyte: byte out of range");
  381.         c->c_errors++;
  382.     }
  383.     if (c->c_code == NULL)
  384.         return;
  385.     len = getstringsize(c->c_code);
  386.     if (c->c_nexti >= len) {
  387.         if (resizestring(&c->c_code, len+1000) != 0) {
  388.             c->c_errors++;
  389.             return;
  390.         }
  391.     }
  392.     getstringvalue(c->c_code)[c->c_nexti++] = byte;
  393. }
  394.  
  395. static void
  396. com_addint(c, x)
  397.     struct compiling *c;
  398.     int x;
  399. {
  400.     com_addbyte(c, x & 0xff);
  401.     com_addbyte(c, x >> 8); /* XXX x should be positive */
  402. }
  403.  
  404. static void
  405. com_addoparg(c, op, arg)
  406.     struct compiling *c;
  407.     int op;
  408.     int arg;
  409. {
  410.     com_addbyte(c, op);
  411.     com_addint(c, arg);
  412. }
  413.  
  414. static void
  415. com_addfwref(c, op, p_anchor)
  416.     struct compiling *c;
  417.     int op;
  418.     int *p_anchor;
  419. {
  420.     /* Compile a forward reference for backpatching */
  421.     int here;
  422.     int anchor;
  423.     com_addbyte(c, op);
  424.     here = c->c_nexti;
  425.     anchor = *p_anchor;
  426.     *p_anchor = here;
  427.     com_addint(c, anchor == 0 ? 0 : here - anchor);
  428. }
  429.  
  430. static void
  431. com_backpatch(c, anchor)
  432.     struct compiling *c;
  433.     int anchor; /* Must be nonzero */
  434. {
  435.     unsigned char *code = (unsigned char *) getstringvalue(c->c_code);
  436.     int target = c->c_nexti;
  437.     int dist;
  438.     int prev;
  439.     for (;;) {
  440.         /* Make the JUMP instruction at anchor point to target */
  441.         prev = code[anchor] + (code[anchor+1] << 8);
  442.         dist = target - (anchor+2);
  443.         code[anchor] = dist & 0xff;
  444.         code[anchor+1] = dist >> 8;
  445.         if (!prev)
  446.             break;
  447.         anchor -= prev;
  448.     }
  449. }
  450.  
  451. /* Handle literals and names uniformly */
  452.  
  453. static int
  454. com_add(c, list, v)
  455.     struct compiling *c;
  456.     object *list;
  457.     object *v;
  458. {
  459.     int n = getlistsize(list);
  460.     int i;
  461.     for (i = n; --i >= 0; ) {
  462.         object *w = getlistitem(list, i);
  463.         if (v->ob_type == w->ob_type && cmpobject(v, w) == 0)
  464.             return i;
  465.     }
  466.     if (addlistitem(list, v) != 0)
  467.         c->c_errors++;
  468.     return n;
  469. }
  470.  
  471. static int
  472. com_addconst(c, v)
  473.     struct compiling *c;
  474.     object *v;
  475. {
  476.     return com_add(c, c->c_consts, v);
  477. }
  478.  
  479. static int
  480. com_addname(c, v)
  481.     struct compiling *c;
  482.     object *v;
  483. {
  484.     return com_add(c, c->c_names, v);
  485. }
  486.  
  487. static void
  488. com_addopnamestr(c, op, name)
  489.     struct compiling *c;
  490.     int op;
  491.     char *name;
  492. {
  493.     object *v;
  494.     int i;
  495.     if (name == NULL || (v = newstringobject(name)) == NULL) {
  496.         c->c_errors++;
  497.         i = 255;
  498.     }
  499.     else {
  500.         i = com_addname(c, v);
  501.         DECREF(v);
  502.     }
  503.     /* Hack to replace *_NAME opcodes by *_GLOBAL if necessary */
  504.     switch (op) {
  505.     case LOAD_NAME:
  506.     case STORE_NAME:
  507.     case DELETE_NAME:
  508.         if (dictlookup(c->c_globals, name) != NULL) {
  509.             switch (op) {
  510.             case LOAD_NAME:   op = LOAD_GLOBAL;   break;
  511.             case STORE_NAME:  op = STORE_GLOBAL;  break;
  512.             case DELETE_NAME: op = DELETE_GLOBAL; break;
  513.             }
  514.         }
  515.     }
  516.     com_addoparg(c, op, i);
  517. }
  518.  
  519. static void
  520. com_addopname(c, op, n)
  521.     struct compiling *c;
  522.     int op;
  523.     node *n;
  524. {
  525.     char *name;
  526.     char buffer[1000];
  527.     /* XXX it is possible to write this code without the 1000
  528.        chars on the total length of dotted names, I just can't be
  529.        bothered right now */
  530.     if (TYPE(n) == STAR)
  531.         name = "*";
  532.     else if (TYPE(n) == dotted_name) {
  533.         char *p = buffer;
  534.         int i;
  535.         name = buffer;
  536.         for (i = 0; i < NCH(n); i += 2) {
  537.             char *s = STR(CHILD(n, i));
  538.             if (p + strlen(s) > buffer + (sizeof buffer) - 2) {
  539.                 err_setstr(MemoryError,
  540.                        "dotted_name too long");
  541.                 name = NULL;
  542.                 break;
  543.             }
  544.             if (p != buffer)
  545.                 *p++ = '.';
  546.             strcpy(p, s);
  547.             p = strchr(p, '\0');
  548.         }
  549.     }
  550.     else {
  551.         REQ(n, NAME);
  552.         name = STR(n);
  553.     }
  554.     com_addopnamestr(c, op, name);
  555. }
  556.  
  557. static object *
  558. parsenumber(s)
  559.     char *s;
  560. {
  561.     extern long mystrtol PROTO((const char *, char **, int));
  562.     extern unsigned long mystrtoul PROTO((const char *, char **, int));
  563.     extern double atof PROTO((const char *));
  564.     char *end;
  565.     long x;
  566.     errno = 0;
  567.     end = s + strlen(s) - 1;
  568.     if (*end == 'l' || *end == 'L')
  569.         return long_scan(s, 0);
  570.     if (s[0] == '0')
  571.         x = (long) mystrtoul(s, &end, 0);
  572.     else
  573.         x = mystrtol(s, &end, 0);
  574.     if (*end == '\0') {
  575.         if (errno != 0) {
  576.             err_setstr(OverflowError,
  577.                    "integer literal too large");
  578.             return NULL;
  579.         }
  580.         return newintobject(x);
  581.     }
  582.     /* XXX Huge floats may silently fail */
  583.     return newfloatobject(atof(s));
  584. }
  585.  
  586. static object *
  587. parsestr(s)
  588.     char *s;
  589. {
  590.     object *v;
  591.     int len;
  592.     char *buf;
  593.     char *p;
  594.     char *end;
  595.     int c;
  596.     int quote = *s;
  597.     if (quote != '\'' && quote != '\"') {
  598.         err_badcall();
  599.         return NULL;
  600.     }
  601.     s++;
  602.     len = strlen(s);
  603.     if (s[--len] != quote) {
  604.         err_badcall();
  605.         return NULL;
  606.     }
  607.     if (len >= 4 && s[0] == quote && s[1] == quote) {
  608.         s += 2;
  609.         len -= 2;
  610.         if (s[--len] != quote || s[--len] != quote) {
  611.             err_badcall();
  612.             return NULL;
  613.         }
  614.     }
  615.     if (strchr(s, '\\') == NULL)
  616.         return newsizedstringobject(s, len);
  617.     v = newsizedstringobject((char *)NULL, len);
  618.     p = buf = getstringvalue(v);
  619.     end = s + len;
  620.     while (s < end) {
  621.         if (*s != '\\') {
  622.             *p++ = *s++;
  623.             continue;
  624.         }
  625.         s++;
  626.         switch (*s++) {
  627.         /* XXX This assumes ASCII! */
  628.         case '\n': break;
  629.         case '\\': *p++ = '\\'; break;
  630.         case '\'': *p++ = '\''; break;
  631.         case '\"': *p++ = '\"'; break;
  632.         case 'b': *p++ = '\b'; break;
  633.         case 'f': *p++ = '\014'; break; /* FF */
  634.         case 't': *p++ = '\t'; break;
  635.         case 'n': *p++ = '\n'; break;
  636.         case 'r': *p++ = '\r'; break;
  637.         case 'v': *p++ = '\013'; break; /* VT */
  638.         case 'a': *p++ = '\007'; break; /* BEL, not classic C */
  639.         case '0': case '1': case '2': case '3':
  640.         case '4': case '5': case '6': case '7':
  641.             c = s[-1] - '0';
  642.             if ('0' <= *s && *s <= '7') {
  643.                 c = (c<<3) + *s++ - '0';
  644.                 if ('0' <= *s && *s <= '7')
  645.                     c = (c<<3) + *s++ - '0';
  646.             }
  647.             *p++ = c;
  648.             break;
  649.         case 'x':
  650.             if (isxdigit(Py_CHARMASK(*s))) {
  651.                 sscanf(s, "%x", &c);
  652.                 *p++ = c;
  653.                 do {
  654.                     s++;
  655.                 } while (isxdigit(Py_CHARMASK(*s)));
  656.                 break;
  657.             }
  658.         /* FALLTHROUGH */
  659.         default: *p++ = '\\'; *p++ = s[-1]; break;
  660.         }
  661.     }
  662.     resizestring(&v, (int)(p - buf));
  663.     return v;
  664. }
  665.  
  666. static object *
  667. parsestrplus(n)
  668.     node *n;
  669. {
  670.     object *v;
  671.     int i;
  672.     REQ(CHILD(n, 0), STRING);
  673.     if ((v = parsestr(STR(CHILD(n, 0)))) != NULL) {
  674.         /* String literal concatenation */
  675.         for (i = 1; i < NCH(n) && v != NULL; i++) {
  676.             joinstring_decref(&v, parsestr(STR(CHILD(n, i))));
  677.         }
  678.     }
  679.     return v;
  680. }
  681.  
  682. static void
  683. com_list_constructor(c, n)
  684.     struct compiling *c;
  685.     node *n;
  686. {
  687.     int len;
  688.     int i;
  689.     if (TYPE(n) != testlist)
  690.         REQ(n, exprlist);
  691.     /* exprlist: expr (',' expr)* [',']; likewise for testlist */
  692.     len = (NCH(n) + 1) / 2;
  693.     for (i = 0; i < NCH(n); i += 2)
  694.         com_node(c, CHILD(n, i));
  695.     com_addoparg(c, BUILD_LIST, len);
  696. }
  697.  
  698. static void
  699. com_dictmaker(c, n)
  700.     struct compiling *c;
  701.     node *n;
  702. {
  703.     int i;
  704.     /* dictmaker: test ':' test (',' test ':' value)* [','] */
  705.     for (i = 0; i+2 < NCH(n); i += 4) {
  706.         /* We must arrange things just right for STORE_SUBSCR.
  707.            It wants the stack to look like (value) (dict) (key) */
  708.         com_addbyte(c, DUP_TOP);
  709.         com_node(c, CHILD(n, i+2)); /* value */
  710.         com_addbyte(c, ROT_TWO);
  711.         com_node(c, CHILD(n, i)); /* key */
  712.         com_addbyte(c, STORE_SUBSCR);
  713.     }
  714. }
  715.  
  716. static void
  717. com_atom(c, n)
  718.     struct compiling *c;
  719.     node *n;
  720. {
  721.     node *ch;
  722.     object *v;
  723.     int i;
  724.     REQ(n, atom);
  725.     ch = CHILD(n, 0);
  726.     switch (TYPE(ch)) {
  727.     case LPAR:
  728.         if (TYPE(CHILD(n, 1)) == RPAR)
  729.             com_addoparg(c, BUILD_TUPLE, 0);
  730.         else
  731.             com_node(c, CHILD(n, 1));
  732.         break;
  733.     case LSQB:
  734.         if (TYPE(CHILD(n, 1)) == RSQB)
  735.             com_addoparg(c, BUILD_LIST, 0);
  736.         else
  737.             com_list_constructor(c, CHILD(n, 1));
  738.         break;
  739.     case LBRACE: /* '{' [dictmaker] '}' */
  740.         com_addoparg(c, BUILD_MAP, 0);
  741.         if (TYPE(CHILD(n, 1)) != RBRACE)
  742.             com_dictmaker(c, CHILD(n, 1));
  743.         break;
  744.     case BACKQUOTE:
  745.         com_node(c, CHILD(n, 1));
  746.         com_addbyte(c, UNARY_CONVERT);
  747.         break;
  748.     case NUMBER:
  749.         if ((v = parsenumber(STR(ch))) == NULL) {
  750.             c->c_errors++;
  751.             i = 255;
  752.         }
  753.         else {
  754.             i = com_addconst(c, v);
  755.             DECREF(v);
  756.         }
  757.         com_addoparg(c, LOAD_CONST, i);
  758.         break;
  759.     case STRING:
  760.         v = parsestrplus(n);
  761.         if (v == NULL) {
  762.             c->c_errors++;
  763.             i = 255;
  764.         }
  765.         else {
  766.             i = com_addconst(c, v);
  767.             DECREF(v);
  768.         }
  769.         com_addoparg(c, LOAD_CONST, i);
  770.         break;
  771.     case NAME:
  772.         com_addopname(c, LOAD_NAME, ch);
  773.         break;
  774.     default:
  775.         fprintf(stderr, "node type %d\n", TYPE(ch));
  776.         err_setstr(SystemError, "com_atom: unexpected node type");
  777.         c->c_errors++;
  778.     }
  779. }
  780.  
  781. static void
  782. com_slice(c, n, op)
  783.     struct compiling *c;
  784.     node *n;
  785.     int op;
  786. {
  787.     if (NCH(n) == 1) {
  788.         com_addbyte(c, op);
  789.     }
  790.     else if (NCH(n) == 2) {
  791.         if (TYPE(CHILD(n, 0)) != COLON) {
  792.             com_node(c, CHILD(n, 0));
  793.             com_addbyte(c, op+1);
  794.         }
  795.         else {
  796.             com_node(c, CHILD(n, 1));
  797.             com_addbyte(c, op+2);
  798.         }
  799.     }
  800.     else {
  801.         com_node(c, CHILD(n, 0));
  802.         com_node(c, CHILD(n, 2));
  803.         com_addbyte(c, op+3);
  804.     }
  805. }
  806.  
  807. static void
  808. com_apply_subscript(c, n)
  809.     struct compiling *c;
  810.     node *n;
  811. {
  812.     REQ(n, subscript);
  813.     if (NCH(n) == 1 && TYPE(CHILD(n, 0)) != COLON) {
  814.         /* It's a single subscript */
  815.         com_node(c, CHILD(n, 0));
  816.         com_addbyte(c, BINARY_SUBSCR);
  817.     }
  818.     else {
  819.         /* It's a slice: [expr] ':' [expr] */
  820.         com_slice(c, n, SLICE);
  821.     }
  822. }
  823.  
  824. static int
  825. com_argument(c, n, inkeywords)
  826.     struct compiling *c;
  827.     node *n; /* argument */
  828.     int inkeywords;
  829. {
  830.     node *m;
  831.     REQ(n, argument); /* [test '='] test; really [ keyword '='] keyword */
  832.     if (NCH(n) == 1) {
  833.         if (inkeywords) {
  834.             err_setstr(SyntaxError,
  835.                    "non-keyword arg after keyword arg");
  836.             c->c_errors++;
  837.         }
  838.         else {
  839.             com_node(c, CHILD(n, 0));
  840.         }
  841.         return 0;
  842.     }
  843.     m = n;
  844.     do {
  845.         m = CHILD(m, 0);
  846.     } while (NCH(m) == 1);
  847.     if (TYPE(m) != NAME) {
  848.         err_setstr(SyntaxError, "keyword can't be an expression");
  849.         c->c_errors++;
  850.     }
  851.     else {
  852.         object *v = newstringobject(STR(m));
  853.         if (v == NULL)
  854.             c->c_errors++;
  855.         else {
  856.             com_addoparg(c, LOAD_CONST, com_addconst(c, v));
  857.             DECREF(v);
  858.         }
  859.     }
  860.     com_node(c, CHILD(n, 2));
  861.     return 1;
  862. }
  863.  
  864. static void
  865. com_call_function(c, n)
  866.     struct compiling *c;
  867.     node *n; /* EITHER arglist OR ')' */
  868. {
  869.     if (TYPE(n) == RPAR) {
  870.         com_addoparg(c, CALL_FUNCTION, 0);
  871.     }
  872.     else {
  873.         int inkeywords, i, na, nk;
  874.         REQ(n, arglist);
  875.         inkeywords = 0;
  876.         na = 0;
  877.         nk = 0;
  878.         for (i = 0; i < NCH(n); i += 2) {
  879.             inkeywords = com_argument(c, CHILD(n, i), inkeywords);
  880.             if (!inkeywords)
  881.                 na++;
  882.             else
  883.                 nk++;
  884.         }
  885.         if (na > 255 || nk > 255) {
  886.             err_setstr(SyntaxError, "more than 255 arguments");
  887.             c->c_errors++;
  888.         }
  889.         com_addoparg(c, CALL_FUNCTION, na | (nk << 8));
  890.     }
  891. }
  892.  
  893. static void
  894. com_select_member(c, n)
  895.     struct compiling *c;
  896.     node *n;
  897. {
  898.     com_addopname(c, LOAD_ATTR, n);
  899. }
  900.  
  901. static void
  902. com_apply_trailer(c, n)
  903.     struct compiling *c;
  904.     node *n;
  905. {
  906.     REQ(n, trailer);
  907.     switch (TYPE(CHILD(n, 0))) {
  908.     case LPAR:
  909.         com_call_function(c, CHILD(n, 1));
  910.         break;
  911.     case DOT:
  912.         com_select_member(c, CHILD(n, 1));
  913.         break;
  914.     case LSQB:
  915.         com_apply_subscript(c, CHILD(n, 1));
  916.         break;
  917.     default:
  918.         err_setstr(SystemError,
  919.             "com_apply_trailer: unknown trailer type");
  920.         c->c_errors++;
  921.     }
  922. }
  923.  
  924. static void
  925. com_factor(c, n)
  926.     struct compiling *c;
  927.     node *n;
  928. {
  929.     int i;
  930.     REQ(n, factor);
  931.     if (TYPE(CHILD(n, 0)) == PLUS) {
  932.         com_factor(c, CHILD(n, 1));
  933.         com_addbyte(c, UNARY_POSITIVE);
  934.     }
  935.     else if (TYPE(CHILD(n, 0)) == MINUS) {
  936.         com_factor(c, CHILD(n, 1));
  937.         com_addbyte(c, UNARY_NEGATIVE);
  938.     }
  939.     else if (TYPE(CHILD(n, 0)) == TILDE) {
  940.         com_factor(c, CHILD(n, 1));
  941.         com_addbyte(c, UNARY_INVERT);
  942.     }
  943.     else {
  944.         com_atom(c, CHILD(n, 0));
  945.         for (i = 1; i < NCH(n); i++)
  946.             com_apply_trailer(c, CHILD(n, i));
  947.     }
  948. }
  949.  
  950. static void
  951. com_term(c, n)
  952.     struct compiling *c;
  953.     node *n;
  954. {
  955.     int i;
  956.     int op;
  957.     REQ(n, term);
  958.     com_factor(c, CHILD(n, 0));
  959.     for (i = 2; i < NCH(n); i += 2) {
  960.         com_factor(c, CHILD(n, i));
  961.         switch (TYPE(CHILD(n, i-1))) {
  962.         case STAR:
  963.             op = BINARY_MULTIPLY;
  964.             break;
  965.         case SLASH:
  966.             op = BINARY_DIVIDE;
  967.             break;
  968.         case PERCENT:
  969.             op = BINARY_MODULO;
  970.             break;
  971.         default:
  972.             err_setstr(SystemError,
  973.                 "com_term: operator not *, / or %");
  974.             c->c_errors++;
  975.             op = 255;
  976.         }
  977.         com_addbyte(c, op);
  978.     }
  979. }
  980.  
  981. static void
  982. com_arith_expr(c, n)
  983.     struct compiling *c;
  984.     node *n;
  985. {
  986.     int i;
  987.     int op;
  988.     REQ(n, arith_expr);
  989.     com_term(c, CHILD(n, 0));
  990.     for (i = 2; i < NCH(n); i += 2) {
  991.         com_term(c, CHILD(n, i));
  992.         switch (TYPE(CHILD(n, i-1))) {
  993.         case PLUS:
  994.             op = BINARY_ADD;
  995.             break;
  996.         case MINUS:
  997.             op = BINARY_SUBTRACT;
  998.             break;
  999.         default:
  1000.             err_setstr(SystemError,
  1001.                 "com_arith_expr: operator not + or -");
  1002.             c->c_errors++;
  1003.             op = 255;
  1004.         }
  1005.         com_addbyte(c, op);
  1006.     }
  1007. }
  1008.  
  1009. static void
  1010. com_shift_expr(c, n)
  1011.     struct compiling *c;
  1012.     node *n;
  1013. {
  1014.     int i;
  1015.     int op;
  1016.     REQ(n, shift_expr);
  1017.     com_arith_expr(c, CHILD(n, 0));
  1018.     for (i = 2; i < NCH(n); i += 2) {
  1019.         com_arith_expr(c, CHILD(n, i));
  1020.         switch (TYPE(CHILD(n, i-1))) {
  1021.         case LEFTSHIFT:
  1022.             op = BINARY_LSHIFT;
  1023.             break;
  1024.         case RIGHTSHIFT:
  1025.             op = BINARY_RSHIFT;
  1026.             break;
  1027.         default:
  1028.             err_setstr(SystemError,
  1029.                 "com_shift_expr: operator not << or >>");
  1030.             c->c_errors++;
  1031.             op = 255;
  1032.         }
  1033.         com_addbyte(c, op);
  1034.     }
  1035. }
  1036.  
  1037. static void
  1038. com_and_expr(c, n)
  1039.     struct compiling *c;
  1040.     node *n;
  1041. {
  1042.     int i;
  1043.     int op;
  1044.     REQ(n, and_expr);
  1045.     com_shift_expr(c, CHILD(n, 0));
  1046.     for (i = 2; i < NCH(n); i += 2) {
  1047.         com_shift_expr(c, CHILD(n, i));
  1048.         if (TYPE(CHILD(n, i-1)) == AMPER) {
  1049.             op = BINARY_AND;
  1050.         }
  1051.         else {
  1052.             err_setstr(SystemError,
  1053.                 "com_and_expr: operator not &");
  1054.             c->c_errors++;
  1055.             op = 255;
  1056.         }
  1057.         com_addbyte(c, op);
  1058.     }
  1059. }
  1060.  
  1061. static void
  1062. com_xor_expr(c, n)
  1063.     struct compiling *c;
  1064.     node *n;
  1065. {
  1066.     int i;
  1067.     int op;
  1068.     REQ(n, xor_expr);
  1069.     com_and_expr(c, CHILD(n, 0));
  1070.     for (i = 2; i < NCH(n); i += 2) {
  1071.         com_and_expr(c, CHILD(n, i));
  1072.         if (TYPE(CHILD(n, i-1)) == CIRCUMFLEX) {
  1073.             op = BINARY_XOR;
  1074.         }
  1075.         else {
  1076.             err_setstr(SystemError,
  1077.                 "com_xor_expr: operator not ^");
  1078.             c->c_errors++;
  1079.             op = 255;
  1080.         }
  1081.         com_addbyte(c, op);
  1082.     }
  1083. }
  1084.  
  1085. static void
  1086. com_expr(c, n)
  1087.     struct compiling *c;
  1088.     node *n;
  1089. {
  1090.     int i;
  1091.     int op;
  1092.     REQ(n, expr);
  1093.     com_xor_expr(c, CHILD(n, 0));
  1094.     for (i = 2; i < NCH(n); i += 2) {
  1095.         com_xor_expr(c, CHILD(n, i));
  1096.         if (TYPE(CHILD(n, i-1)) == VBAR) {
  1097.             op = BINARY_OR;
  1098.         }
  1099.         else {
  1100.             err_setstr(SystemError,
  1101.                 "com_expr: expr operator not |");
  1102.             c->c_errors++;
  1103.             op = 255;
  1104.         }
  1105.         com_addbyte(c, op);
  1106.     }
  1107. }
  1108.  
  1109. static enum cmp_op
  1110. cmp_type(n)
  1111.     node *n;
  1112. {
  1113.     REQ(n, comp_op);
  1114.     /* comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '=='
  1115.               | 'in' | 'not' 'in' | 'is' | 'is' not' */
  1116.     if (NCH(n) == 1) {
  1117.         n = CHILD(n, 0);
  1118.         switch (TYPE(n)) {
  1119.         case LESS:    return LT;
  1120.         case GREATER:    return GT;
  1121.         case EQEQUAL:            /* == */
  1122.         case EQUAL:    return EQ;
  1123.         case LESSEQUAL:    return LE;
  1124.         case GREATEREQUAL: return GE;
  1125.         case NOTEQUAL:    return NE;    /* <> or != */
  1126.         case NAME:    if (strcmp(STR(n), "in") == 0) return IN;
  1127.                 if (strcmp(STR(n), "is") == 0) return IS;
  1128.         }
  1129.     }
  1130.     else if (NCH(n) == 2) {
  1131.         switch (TYPE(CHILD(n, 0))) {
  1132.         case NAME:    if (strcmp(STR(CHILD(n, 1)), "in") == 0)
  1133.                     return NOT_IN;
  1134.                 if (strcmp(STR(CHILD(n, 0)), "is") == 0)
  1135.                     return IS_NOT;
  1136.         }
  1137.     }
  1138.     return BAD;
  1139. }
  1140.  
  1141. static void
  1142. com_comparison(c, n)
  1143.     struct compiling *c;
  1144.     node *n;
  1145. {
  1146.     int i;
  1147.     enum cmp_op op;
  1148.     int anchor;
  1149.     REQ(n, comparison); /* comparison: expr (comp_op expr)* */
  1150.     com_expr(c, CHILD(n, 0));
  1151.     if (NCH(n) == 1)
  1152.         return;
  1153.     
  1154.     /****************************************************************
  1155.        The following code is generated for all but the last
  1156.        comparison in a chain:
  1157.        
  1158.        label:    on stack:    opcode:        jump to:
  1159.        
  1160.             a        <code to load b>
  1161.             a, b        DUP_TOP
  1162.             a, b, b        ROT_THREE
  1163.             b, a, b        COMPARE_OP
  1164.             b, 0-or-1    JUMP_IF_FALSE    L1
  1165.             b, 1        POP_TOP
  1166.             b        
  1167.     
  1168.        We are now ready to repeat this sequence for the next
  1169.        comparison in the chain.
  1170.        
  1171.        For the last we generate:
  1172.        
  1173.                b        <code to load c>
  1174.                b, c        COMPARE_OP
  1175.                0-or-1        
  1176.        
  1177.        If there were any jumps to L1 (i.e., there was more than one
  1178.        comparison), we generate:
  1179.        
  1180.                0-or-1        JUMP_FORWARD    L2
  1181.        L1:        b, 0        ROT_TWO
  1182.                0, b        POP_TOP
  1183.                0
  1184.        L2:
  1185.     ****************************************************************/
  1186.     
  1187.     anchor = 0;
  1188.     
  1189.     for (i = 2; i < NCH(n); i += 2) {
  1190.         com_expr(c, CHILD(n, i));
  1191.         if (i+2 < NCH(n)) {
  1192.             com_addbyte(c, DUP_TOP);
  1193.             com_addbyte(c, ROT_THREE);
  1194.         }
  1195.         op = cmp_type(CHILD(n, i-1));
  1196.         if (op == BAD) {
  1197.             err_setstr(SystemError,
  1198.                 "com_comparison: unknown comparison op");
  1199.             c->c_errors++;
  1200.         }
  1201.         com_addoparg(c, COMPARE_OP, op);
  1202.         if (i+2 < NCH(n)) {
  1203.             com_addfwref(c, JUMP_IF_FALSE, &anchor);
  1204.             com_addbyte(c, POP_TOP);
  1205.         }
  1206.     }
  1207.     
  1208.     if (anchor) {
  1209.         int anchor2 = 0;
  1210.         com_addfwref(c, JUMP_FORWARD, &anchor2);
  1211.         com_backpatch(c, anchor);
  1212.         com_addbyte(c, ROT_TWO);
  1213.         com_addbyte(c, POP_TOP);
  1214.         com_backpatch(c, anchor2);
  1215.     }
  1216. }
  1217.  
  1218. static void
  1219. com_not_test(c, n)
  1220.     struct compiling *c;
  1221.     node *n;
  1222. {
  1223.     REQ(n, not_test); /* 'not' not_test | comparison */
  1224.     if (NCH(n) == 1) {
  1225.         com_comparison(c, CHILD(n, 0));
  1226.     }
  1227.     else {
  1228.         com_not_test(c, CHILD(n, 1));
  1229.         com_addbyte(c, UNARY_NOT);
  1230.     }
  1231. }
  1232.  
  1233. static void
  1234. com_and_test(c, n)
  1235.     struct compiling *c;
  1236.     node *n;
  1237. {
  1238.     int i;
  1239.     int anchor;
  1240.     REQ(n, and_test); /* not_test ('and' not_test)* */
  1241.     anchor = 0;
  1242.     i = 0;
  1243.     for (;;) {
  1244.         com_not_test(c, CHILD(n, i));
  1245.         if ((i += 2) >= NCH(n))
  1246.             break;
  1247.         com_addfwref(c, JUMP_IF_FALSE, &anchor);
  1248.         com_addbyte(c, POP_TOP);
  1249.     }
  1250.     if (anchor)
  1251.         com_backpatch(c, anchor);
  1252. }
  1253.  
  1254. static void
  1255. com_test(c, n)
  1256.     struct compiling *c;
  1257.     node *n;
  1258. {
  1259.     REQ(n, test); /* and_test ('and' and_test)* | lambdef */
  1260.     if (NCH(n) == 1 && TYPE(CHILD(n, 0)) == lambdef) {
  1261.         object *v;
  1262.         int i;
  1263.         int ndefs = com_argdefs(c, CHILD(n, 0));
  1264.         v = (object *) compile(CHILD(n, 0), c->c_filename);
  1265.         if (v == NULL) {
  1266.             c->c_errors++;
  1267.             i = 255;
  1268.         }
  1269.         else {
  1270.             i = com_addconst(c, v);
  1271.             DECREF(v);
  1272.         }
  1273.         com_addoparg(c, LOAD_CONST, i);
  1274.         com_addoparg(c, MAKE_FUNCTION, ndefs);
  1275.     }
  1276.     else {
  1277.         int anchor = 0;
  1278.         int i = 0;
  1279.         for (;;) {
  1280.             com_and_test(c, CHILD(n, i));
  1281.             if ((i += 2) >= NCH(n))
  1282.                 break;
  1283.             com_addfwref(c, JUMP_IF_TRUE, &anchor);
  1284.             com_addbyte(c, POP_TOP);
  1285.         }
  1286.         if (anchor)
  1287.             com_backpatch(c, anchor);
  1288.     }
  1289. }
  1290.  
  1291. static void
  1292. com_list(c, n, toplevel)
  1293.     struct compiling *c;
  1294.     node *n;
  1295.     int toplevel; /* If nonzero, *always* build a tuple */
  1296. {
  1297.     /* exprlist: expr (',' expr)* [',']; likewise for testlist */
  1298.     if (NCH(n) == 1 && !toplevel) {
  1299.         com_node(c, CHILD(n, 0));
  1300.     }
  1301.     else {
  1302.         int i;
  1303.         int len;
  1304.         len = (NCH(n) + 1) / 2;
  1305.         for (i = 0; i < NCH(n); i += 2)
  1306.             com_node(c, CHILD(n, i));
  1307.         com_addoparg(c, BUILD_TUPLE, len);
  1308.     }
  1309. }
  1310.  
  1311.  
  1312. /* Begin of assignment compilation */
  1313.  
  1314. static void com_assign_name PROTO((struct compiling *, node *, int));
  1315. static void com_assign PROTO((struct compiling *, node *, int));
  1316.  
  1317. static void
  1318. com_assign_attr(c, n, assigning)
  1319.     struct compiling *c;
  1320.     node *n;
  1321.     int assigning;
  1322. {
  1323.     com_addopname(c, assigning ? STORE_ATTR : DELETE_ATTR, n);
  1324. }
  1325.  
  1326. static void
  1327. com_assign_slice(c, n, assigning)
  1328.     struct compiling *c;
  1329.     node *n;
  1330.     int assigning;
  1331. {
  1332.     com_slice(c, n, assigning ? STORE_SLICE : DELETE_SLICE);
  1333. }
  1334.  
  1335. static void
  1336. com_assign_subscript(c, n, assigning)
  1337.     struct compiling *c;
  1338.     node *n;
  1339.     int assigning;
  1340. {
  1341.     com_node(c, n);
  1342.     com_addbyte(c, assigning ? STORE_SUBSCR : DELETE_SUBSCR);
  1343. }
  1344.  
  1345. static void
  1346. com_assign_trailer(c, n, assigning)
  1347.     struct compiling *c;
  1348.     node *n;
  1349.     int assigning;
  1350. {
  1351.     REQ(n, trailer);
  1352.     switch (TYPE(CHILD(n, 0))) {
  1353.     case LPAR: /* '(' [exprlist] ')' */
  1354.         err_setstr(SyntaxError, "can't assign to function call");
  1355.         c->c_errors++;
  1356.         break;
  1357.     case DOT: /* '.' NAME */
  1358.         com_assign_attr(c, CHILD(n, 1), assigning);
  1359.         break;
  1360.     case LSQB: /* '[' subscript ']' */
  1361.         n = CHILD(n, 1);
  1362.         REQ(n, subscript); /* subscript: expr | [expr] ':' [expr] */
  1363.         if (NCH(n) > 1 || TYPE(CHILD(n, 0)) == COLON)
  1364.             com_assign_slice(c, n, assigning);
  1365.         else
  1366.             com_assign_subscript(c, CHILD(n, 0), assigning);
  1367.         break;
  1368.     default:
  1369.         err_setstr(SystemError, "unknown trailer type");
  1370.         c->c_errors++;
  1371.     }
  1372. }
  1373.  
  1374. static void
  1375. com_assign_tuple(c, n, assigning)
  1376.     struct compiling *c;
  1377.     node *n;
  1378.     int assigning;
  1379. {
  1380.     int i;
  1381.     if (TYPE(n) != testlist)
  1382.         REQ(n, exprlist);
  1383.     if (assigning)
  1384.         com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2);
  1385.     for (i = 0; i < NCH(n); i += 2)
  1386.         com_assign(c, CHILD(n, i), assigning);
  1387. }
  1388.  
  1389. static void
  1390. com_assign_list(c, n, assigning)
  1391.     struct compiling *c;
  1392.     node *n;
  1393.     int assigning;
  1394. {
  1395.     int i;
  1396.     if (assigning)
  1397.         com_addoparg(c, UNPACK_LIST, (NCH(n)+1)/2);
  1398.     for (i = 0; i < NCH(n); i += 2)
  1399.         com_assign(c, CHILD(n, i), assigning);
  1400. }
  1401.  
  1402. static void
  1403. com_assign_name(c, n, assigning)
  1404.     struct compiling *c;
  1405.     node *n;
  1406.     int assigning;
  1407. {
  1408.     REQ(n, NAME);
  1409.     com_addopname(c, assigning ? STORE_NAME : DELETE_NAME, n);
  1410. }
  1411.  
  1412. static void
  1413. com_assign(c, n, assigning)
  1414.     struct compiling *c;
  1415.     node *n;
  1416.     int assigning;
  1417. {
  1418.     /* Loop to avoid trivial recursion */
  1419.     for (;;) {
  1420.         switch (TYPE(n)) {
  1421.         
  1422.         case exprlist:
  1423.         case testlist:
  1424.             if (NCH(n) > 1) {
  1425.                 com_assign_tuple(c, n, assigning);
  1426.                 return;
  1427.             }
  1428.             n = CHILD(n, 0);
  1429.             break;
  1430.         
  1431.         case test:
  1432.         case and_test:
  1433.         case not_test:
  1434.         case comparison:
  1435.         case expr:
  1436.         case xor_expr:
  1437.         case and_expr:
  1438.         case shift_expr:
  1439.         case arith_expr:
  1440.         case term:
  1441.             if (NCH(n) > 1) {
  1442.                 err_setstr(SyntaxError,
  1443.                     "can't assign to operator");
  1444.                 c->c_errors++;
  1445.                 return;
  1446.             }
  1447.             n = CHILD(n, 0);
  1448.             break;
  1449.         
  1450.         case factor: /* ('+'|'-'|'~') factor | atom trailer* */
  1451.             if (TYPE(CHILD(n, 0)) != atom) { /* '+'|'-'|'~' */
  1452.                 err_setstr(SyntaxError,
  1453.                     "can't assign to operator");
  1454.                 c->c_errors++;
  1455.                 return;
  1456.             }
  1457.             if (NCH(n) > 1) { /* trailer present */
  1458.                 int i;
  1459.                 com_node(c, CHILD(n, 0));
  1460.                 for (i = 1; i+1 < NCH(n); i++) {
  1461.                     com_apply_trailer(c, CHILD(n, i));
  1462.                 } /* NB i is still alive */
  1463.                 com_assign_trailer(c,
  1464.                         CHILD(n, i), assigning);
  1465.                 return;
  1466.             }
  1467.             n = CHILD(n, 0);
  1468.             break;
  1469.         
  1470.         case atom:
  1471.             switch (TYPE(CHILD(n, 0))) {
  1472.             case LPAR:
  1473.                 n = CHILD(n, 1);
  1474.                 if (TYPE(n) == RPAR) {
  1475.                     /* XXX Should allow () = () ??? */
  1476.                     err_setstr(SyntaxError,
  1477.                         "can't assign to ()");
  1478.                     c->c_errors++;
  1479.                     return;
  1480.                 }
  1481.                 break;
  1482.             case LSQB:
  1483.                 n = CHILD(n, 1);
  1484.                 if (TYPE(n) == RSQB) {
  1485.                     err_setstr(SyntaxError,
  1486.                         "can't assign to []");
  1487.                     c->c_errors++;
  1488.                     return;
  1489.                 }
  1490.                 com_assign_list(c, n, assigning);
  1491.                 return;
  1492.             case NAME:
  1493.                 com_assign_name(c, CHILD(n, 0), assigning);
  1494.                 return;
  1495.             default:
  1496.                 err_setstr(SyntaxError,
  1497.                         "can't assign to literal");
  1498.                 c->c_errors++;
  1499.                 return;
  1500.             }
  1501.             break;
  1502.         
  1503.         default:
  1504.             fprintf(stderr, "node type %d\n", TYPE(n));
  1505.             err_setstr(SystemError, "com_assign: bad node");
  1506.             c->c_errors++;
  1507.             return;
  1508.         
  1509.         }
  1510.     }
  1511. }
  1512.  
  1513. static void
  1514. com_expr_stmt(c, n)
  1515.     struct compiling *c;
  1516.     node *n;
  1517. {
  1518.     REQ(n, expr_stmt); /* testlist ('=' testlist)* */
  1519.     com_node(c, CHILD(n, NCH(n)-1));
  1520.     if (NCH(n) == 1) {
  1521.         if (c->c_interactive)
  1522.             com_addbyte(c, PRINT_EXPR);
  1523.         else
  1524.             com_addbyte(c, POP_TOP);
  1525.     }
  1526.     else {
  1527.         int i;
  1528.         for (i = 0; i < NCH(n)-2; i+=2) {
  1529.             if (i+2 < NCH(n)-2)
  1530.                 com_addbyte(c, DUP_TOP);
  1531.             com_assign(c, CHILD(n, i), 1/*assign*/);
  1532.         }
  1533.     }
  1534. }
  1535.  
  1536. static void
  1537. com_print_stmt(c, n)
  1538.     struct compiling *c;
  1539.     node *n;
  1540. {
  1541.     int i;
  1542.     REQ(n, print_stmt); /* 'print' (test ',')* [test] */
  1543.     for (i = 1; i < NCH(n); i += 2) {
  1544.         com_node(c, CHILD(n, i));
  1545.         com_addbyte(c, PRINT_ITEM);
  1546.     }
  1547.     if (TYPE(CHILD(n, NCH(n)-1)) != COMMA)
  1548.         com_addbyte(c, PRINT_NEWLINE);
  1549.         /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */
  1550. }
  1551.  
  1552. static void
  1553. com_return_stmt(c, n)
  1554.     struct compiling *c;
  1555.     node *n;
  1556. {
  1557.     REQ(n, return_stmt); /* 'return' [testlist] */
  1558.     if (!c->c_infunction) {
  1559.         err_setstr(SyntaxError, "'return' outside function");
  1560.         c->c_errors++;
  1561.     }
  1562.     if (NCH(n) < 2)
  1563.         com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  1564.     else
  1565.         com_node(c, CHILD(n, 1));
  1566.     com_addbyte(c, RETURN_VALUE);
  1567. }
  1568.  
  1569. static void
  1570. com_raise_stmt(c, n)
  1571.     struct compiling *c;
  1572.     node *n;
  1573. {
  1574.     REQ(n, raise_stmt); /* 'raise' test [',' test [',' test]] */
  1575.     com_node(c, CHILD(n, 1));
  1576.     if (NCH(n) > 3) {
  1577.         com_node(c, CHILD(n, 3));
  1578.         if (NCH(n) > 5)
  1579.             com_node(c, CHILD(n, 5));
  1580.     }
  1581.     com_addoparg(c, RAISE_VARARGS, NCH(n)/2);
  1582. }
  1583.  
  1584. static void
  1585. com_import_stmt(c, n)
  1586.     struct compiling *c;
  1587.     node *n;
  1588. {
  1589.     int i;
  1590.     REQ(n, import_stmt);
  1591.     /* 'import' dotted_name (',' dotted_name)* |
  1592.        'from' dotted_name 'import' ('*' | NAME (',' NAME)*) */
  1593.     if (STR(CHILD(n, 0))[0] == 'f') {
  1594.         /* 'from' dotted_name 'import' ... */
  1595.         REQ(CHILD(n, 1), dotted_name);
  1596.         com_addopname(c, IMPORT_NAME, CHILD(n, 1));
  1597.         for (i = 3; i < NCH(n); i += 2)
  1598.             com_addopname(c, IMPORT_FROM, CHILD(n, i));
  1599.         com_addbyte(c, POP_TOP);
  1600.     }
  1601.     else {
  1602.         /* 'import' ... */
  1603.         for (i = 1; i < NCH(n); i += 2) {
  1604.             REQ(CHILD(n, i), dotted_name);
  1605.             com_addopname(c, IMPORT_NAME, CHILD(n, i));
  1606.             com_addopname(c, STORE_NAME, CHILD(CHILD(n, i), 0));
  1607.         }
  1608.     }
  1609. }
  1610.  
  1611. static void
  1612. com_global_stmt(c, n)
  1613.     struct compiling *c;
  1614.     node *n;
  1615. {
  1616.     int i;
  1617.     REQ(n, global_stmt);
  1618.     /* 'global' NAME (',' NAME)* */
  1619.     for (i = 1; i < NCH(n); i += 2) {
  1620.         char *s = STR(CHILD(n, i));
  1621.         if (dictlookup(c->c_locals, s) != NULL) {
  1622.             err_setstr(SyntaxError, "name is local and global");
  1623.             c->c_errors++;
  1624.         }
  1625.         else if (dictinsert(c->c_globals, s, None) != 0)
  1626.             c->c_errors++;
  1627.     }
  1628. }
  1629.  
  1630. static int
  1631. com_newlocal_o(c, nameval)
  1632.     struct compiling *c;
  1633.     object *nameval;
  1634. {
  1635.     int i;
  1636.     object *ival;
  1637.     if (getlistsize(c->c_varnames) != c->c_nlocals) {
  1638.         /* This is usually caused by an error on a previous call */
  1639.         if (c->c_errors == 0) {
  1640.             err_setstr(SystemError, "mixed up var name/index");
  1641.             c->c_errors++;
  1642.         }
  1643.         return 0;
  1644.     }
  1645.     ival = newintobject(i = c->c_nlocals++);
  1646.     if (ival == NULL)
  1647.         c->c_errors++;
  1648.     else if (mappinginsert(c->c_locals, nameval, ival) != 0)
  1649.         c->c_errors++;
  1650.     else if (addlistitem(c->c_varnames, nameval) != 0)
  1651.         c->c_errors++;
  1652.     XDECREF(ival);
  1653.     return i;
  1654. }
  1655.  
  1656. static int
  1657. com_addlocal_o(c, nameval)
  1658.     struct compiling *c;
  1659.     object *nameval;
  1660. {
  1661.     object *ival =  mappinglookup(c->c_locals, nameval);
  1662.     if (ival != NULL)
  1663.         return getintvalue(ival);
  1664.     return com_newlocal_o(c, nameval);
  1665. }
  1666.  
  1667. static int
  1668. com_newlocal(c, name)
  1669.     struct compiling *c;
  1670.     char *name;
  1671. {
  1672.     object *nameval = newstringobject(name);
  1673.     int i;
  1674.     if (nameval == NULL) {
  1675.         c->c_errors++;
  1676.         return 0;
  1677.     }
  1678.     i = com_newlocal_o(c, nameval);
  1679.     DECREF(nameval);
  1680.     return i;
  1681. }
  1682.  
  1683. #define strequ(a, b) (strcmp((a), (b)) == 0)
  1684.  
  1685. static void
  1686. com_access_stmt(c, n)
  1687.     struct compiling *c;
  1688.     node *n;
  1689. {
  1690. #if 0
  1691.     int i, j, k, mode, imode;
  1692.     object *vmode;
  1693.     REQ(n, access_stmt);
  1694.     /* 'access' NAME (',' NAME)* ':' accesstype (',' accesstype)*
  1695.        accesstype: NAME+ */
  1696.  
  1697.     /* Find where the colon is */
  1698.     i = 1;
  1699.     while (TYPE(CHILD(n,i-1)) != COLON)
  1700.         i += 1;
  1701.  
  1702.     /* Calculate the mode mask */
  1703.     mode = 0;
  1704.     for (j = i; j < NCH(n); j += 2) {
  1705.         int r = 0, w = 0, p = 0;
  1706.         for (k = 0; k < NCH(CHILD(n,j)); k++) {
  1707.             if (strequ(STR(CHILD(CHILD(n,j),k)), "public"))
  1708.                 p = 0;
  1709.             else if (strequ(STR(CHILD(CHILD(n,j),k)), "protected"))
  1710.                 p = 1;
  1711.             else if (strequ(STR(CHILD(CHILD(n,j),k)), "private"))
  1712.                 p = 2;
  1713.             else if (strequ(STR(CHILD(CHILD(n,j),k)), "read"))
  1714.                 r = 1;
  1715.             else if (strequ(STR(CHILD(CHILD(n,j),k)), "write"))
  1716.                 w = 1;
  1717.             else /* XXX should make this an exception */
  1718.                 fprintf(stderr, "bad access type %s\n",
  1719.                     STR(CHILD(CHILD(n,j),k)));
  1720.         }
  1721.         if (r == 0 && w == 0)
  1722.             r = w = 1;
  1723.         if (p == 0) {
  1724.             if (r == 1) mode |= AC_R_PUBLIC;
  1725.             if (w == 1) mode |= AC_W_PUBLIC;
  1726.         } else if (p == 1) {
  1727.             if (r == 1) mode |= AC_R_PROTECTED;
  1728.             if (w == 1) mode |= AC_W_PROTECTED;
  1729.         } else {
  1730.             if (r == 1) mode |= AC_R_PRIVATE;
  1731.             if (w == 1) mode |= AC_W_PRIVATE;
  1732.         }
  1733.     }
  1734.     vmode = newintobject((long)mode);
  1735.     imode = com_addconst(c, vmode);
  1736.     XDECREF(vmode);
  1737.     for (i = 1; TYPE(CHILD(n,i-1)) != COLON; i+=2) {
  1738.         com_addoparg(c, LOAD_CONST, imode);
  1739.         com_addopname(c, ACCESS_MODE, CHILD(n, i));
  1740.     }
  1741. #endif
  1742. }
  1743.  
  1744. static void
  1745. com_exec_stmt(c, n)
  1746.     struct compiling *c;
  1747.     node *n;
  1748. {
  1749.     REQ(n, exec_stmt);
  1750.     /* exec_stmt: 'exec' expr ['in' expr [',' expr]] */
  1751.     com_node(c, CHILD(n, 1));
  1752.     if (NCH(n) >= 4)
  1753.         com_node(c, CHILD(n, 3));
  1754.     else
  1755.         com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  1756.     if (NCH(n) >= 6)
  1757.         com_node(c, CHILD(n, 5));
  1758.     else
  1759.         com_addbyte(c, DUP_TOP);
  1760.     com_addbyte(c, EXEC_STMT);
  1761. }
  1762.  
  1763. static void
  1764. com_if_stmt(c, n)
  1765.     struct compiling *c;
  1766.     node *n;
  1767. {
  1768.     int i;
  1769.     int anchor = 0;
  1770.     REQ(n, if_stmt);
  1771.     /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */
  1772.     for (i = 0; i+3 < NCH(n); i+=4) {
  1773.         int a = 0;
  1774.         node *ch = CHILD(n, i+1);
  1775.         if (i > 0)
  1776.             com_addoparg(c, SET_LINENO, ch->n_lineno);
  1777.         com_node(c, CHILD(n, i+1));
  1778.         com_addfwref(c, JUMP_IF_FALSE, &a);
  1779.         com_addbyte(c, POP_TOP);
  1780.         com_node(c, CHILD(n, i+3));
  1781.         com_addfwref(c, JUMP_FORWARD, &anchor);
  1782.         com_backpatch(c, a);
  1783.         com_addbyte(c, POP_TOP);
  1784.     }
  1785.     if (i+2 < NCH(n))
  1786.         com_node(c, CHILD(n, i+2));
  1787.     com_backpatch(c, anchor);
  1788. }
  1789.  
  1790. static void
  1791. com_while_stmt(c, n)
  1792.     struct compiling *c;
  1793.     node *n;
  1794. {
  1795.     int break_anchor = 0;
  1796.     int anchor = 0;
  1797.     int save_begin = c->c_begin;
  1798.     REQ(n, while_stmt); /* 'while' test ':' suite ['else' ':' suite] */
  1799.     com_addfwref(c, SETUP_LOOP, &break_anchor);
  1800.     block_push(c, SETUP_LOOP);
  1801.     c->c_begin = c->c_nexti;
  1802.     com_addoparg(c, SET_LINENO, n->n_lineno);
  1803.     com_node(c, CHILD(n, 1));
  1804.     com_addfwref(c, JUMP_IF_FALSE, &anchor);
  1805.     com_addbyte(c, POP_TOP);
  1806.     c->c_loops++;
  1807.     com_node(c, CHILD(n, 3));
  1808.     c->c_loops--;
  1809.     com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  1810.     c->c_begin = save_begin;
  1811.     com_backpatch(c, anchor);
  1812.     com_addbyte(c, POP_TOP);
  1813.     com_addbyte(c, POP_BLOCK);
  1814.     block_pop(c, SETUP_LOOP);
  1815.     if (NCH(n) > 4)
  1816.         com_node(c, CHILD(n, 6));
  1817.     com_backpatch(c, break_anchor);
  1818. }
  1819.  
  1820. static void
  1821. com_for_stmt(c, n)
  1822.     struct compiling *c;
  1823.     node *n;
  1824. {
  1825.     object *v;
  1826.     int break_anchor = 0;
  1827.     int anchor = 0;
  1828.     int save_begin = c->c_begin;
  1829.     REQ(n, for_stmt);
  1830.     /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */
  1831.     com_addfwref(c, SETUP_LOOP, &break_anchor);
  1832.     block_push(c, SETUP_LOOP);
  1833.     com_node(c, CHILD(n, 3));
  1834.     v = newintobject(0L);
  1835.     if (v == NULL)
  1836.         c->c_errors++;
  1837.     com_addoparg(c, LOAD_CONST, com_addconst(c, v));
  1838.     XDECREF(v);
  1839.     c->c_begin = c->c_nexti;
  1840.     com_addoparg(c, SET_LINENO, n->n_lineno);
  1841.     com_addfwref(c, FOR_LOOP, &anchor);
  1842.     com_assign(c, CHILD(n, 1), 1/*assigning*/);
  1843.     c->c_loops++;
  1844.     com_node(c, CHILD(n, 5));
  1845.     c->c_loops--;
  1846.     com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  1847.     c->c_begin = save_begin;
  1848.     com_backpatch(c, anchor);
  1849.     com_addbyte(c, POP_BLOCK);
  1850.     block_pop(c, SETUP_LOOP);
  1851.     if (NCH(n) > 8)
  1852.         com_node(c, CHILD(n, 8));
  1853.     com_backpatch(c, break_anchor);
  1854. }
  1855.  
  1856. /* Code generated for "try: S finally: Sf" is as follows:
  1857.    
  1858.         SETUP_FINALLY    L
  1859.         <code for S>
  1860.         POP_BLOCK
  1861.         LOAD_CONST    <nil>
  1862.     L:    <code for Sf>
  1863.         END_FINALLY
  1864.    
  1865.    The special instructions use the block stack.  Each block
  1866.    stack entry contains the instruction that created it (here
  1867.    SETUP_FINALLY), the level of the value stack at the time the
  1868.    block stack entry was created, and a label (here L).
  1869.    
  1870.    SETUP_FINALLY:
  1871.     Pushes the current value stack level and the label
  1872.     onto the block stack.
  1873.    POP_BLOCK:
  1874.     Pops en entry from the block stack, and pops the value
  1875.     stack until its level is the same as indicated on the
  1876.     block stack.  (The label is ignored.)
  1877.    END_FINALLY:
  1878.     Pops a variable number of entries from the *value* stack
  1879.     and re-raises the exception they specify.  The number of
  1880.     entries popped depends on the (pseudo) exception type.
  1881.    
  1882.    The block stack is unwound when an exception is raised:
  1883.    when a SETUP_FINALLY entry is found, the exception is pushed
  1884.    onto the value stack (and the exception condition is cleared),
  1885.    and the interpreter jumps to the label gotten from the block
  1886.    stack.
  1887.    
  1888.    Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
  1889.    (The contents of the value stack is shown in [], with the top
  1890.    at the right; 'tb' is trace-back info, 'val' the exception's
  1891.    associated value, and 'exc' the exception.)
  1892.    
  1893.    Value stack        Label    Instruction    Argument
  1894.    []                SETUP_EXCEPT    L1
  1895.    []                <code for S>
  1896.    []                POP_BLOCK
  1897.    []                JUMP_FORWARD    L0
  1898.    
  1899.    [tb, val, exc]    L1:    DUP                )
  1900.    [tb, val, exc, exc]        <evaluate E1>            )
  1901.    [tb, val, exc, exc, E1]    COMPARE_OP    EXC_MATCH    ) only if E1
  1902.    [tb, val, exc, 1-or-0]    JUMP_IF_FALSE    L2        )
  1903.    [tb, val, exc, 1]        POP                )
  1904.    [tb, val, exc]        POP
  1905.    [tb, val]            <assign to V1>    (or POP if no V1)
  1906.    [tb]                POP
  1907.    []                <code for S1>
  1908.                    JUMP_FORWARD    L0
  1909.    
  1910.    [tb, val, exc, 0]    L2:    POP
  1911.    [tb, val, exc]        DUP
  1912.    .............................etc.......................
  1913.  
  1914.    [tb, val, exc, 0]    Ln+1:    POP
  1915.    [tb, val, exc]           END_FINALLY    # re-raise exception
  1916.    
  1917.    []            L0:    <next statement>
  1918.    
  1919.    Of course, parts are not generated if Vi or Ei is not present.
  1920. */
  1921.  
  1922. static void
  1923. com_try_except(c, n)
  1924.     struct compiling *c;
  1925.     node *n;
  1926. {
  1927.     int except_anchor = 0;
  1928.     int end_anchor = 0;
  1929.     int else_anchor = 0;
  1930.     int i;
  1931.     node *ch;
  1932.  
  1933.     com_addfwref(c, SETUP_EXCEPT, &except_anchor);
  1934.     block_push(c, SETUP_EXCEPT);
  1935.     com_node(c, CHILD(n, 2));
  1936.     com_addbyte(c, POP_BLOCK);
  1937.     block_pop(c, SETUP_EXCEPT);
  1938.     com_addfwref(c, JUMP_FORWARD, &else_anchor);
  1939.     com_backpatch(c, except_anchor);
  1940.     for (i = 3;
  1941.          i < NCH(n) && TYPE(ch = CHILD(n, i)) == except_clause;
  1942.          i += 3) {
  1943.         /* except_clause: 'except' [expr [',' expr]] */
  1944.         if (except_anchor == 0) {
  1945.             err_setstr(SyntaxError,
  1946.                 "default 'except:' must be last");
  1947.             c->c_errors++;
  1948.             break;
  1949.         }
  1950.         except_anchor = 0;
  1951.         com_addoparg(c, SET_LINENO, ch->n_lineno);
  1952.         if (NCH(ch) > 1) {
  1953.             com_addbyte(c, DUP_TOP);
  1954.             com_node(c, CHILD(ch, 1));
  1955.             com_addoparg(c, COMPARE_OP, EXC_MATCH);
  1956.             com_addfwref(c, JUMP_IF_FALSE, &except_anchor);
  1957.             com_addbyte(c, POP_TOP);
  1958.         }
  1959.         com_addbyte(c, POP_TOP);
  1960.         if (NCH(ch) > 3)
  1961.             com_assign(c, CHILD(ch, 3), 1/*assigning*/);
  1962.         else
  1963.             com_addbyte(c, POP_TOP);
  1964.         com_addbyte(c, POP_TOP);
  1965.         com_node(c, CHILD(n, i+2));
  1966.         com_addfwref(c, JUMP_FORWARD, &end_anchor);
  1967.         if (except_anchor) {
  1968.             com_backpatch(c, except_anchor);
  1969.             com_addbyte(c, POP_TOP);
  1970.         }
  1971.     }
  1972.     com_addbyte(c, END_FINALLY);
  1973.     com_backpatch(c, else_anchor);
  1974.     if (i < NCH(n))
  1975.         com_node(c, CHILD(n, i+2));
  1976.     com_backpatch(c, end_anchor);
  1977. }
  1978.  
  1979. static void
  1980. com_try_finally(c, n)
  1981.     struct compiling *c;
  1982.     node *n;
  1983. {
  1984.     int finally_anchor = 0;
  1985.     node *ch;
  1986.  
  1987.     com_addfwref(c, SETUP_FINALLY, &finally_anchor);
  1988.     block_push(c, SETUP_FINALLY);
  1989.     com_node(c, CHILD(n, 2));
  1990.     com_addbyte(c, POP_BLOCK);
  1991.     block_pop(c, SETUP_FINALLY);
  1992.     block_push(c, END_FINALLY);
  1993.     com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  1994.     com_backpatch(c, finally_anchor);
  1995.     ch = CHILD(n, NCH(n)-1);
  1996.     com_addoparg(c, SET_LINENO, ch->n_lineno);
  1997.     com_node(c, ch);
  1998.     com_addbyte(c, END_FINALLY);
  1999.     block_pop(c, END_FINALLY);
  2000. }
  2001.  
  2002. static void
  2003. com_try_stmt(c, n)
  2004.     struct compiling *c;
  2005.     node *n;
  2006. {
  2007.     REQ(n, try_stmt);
  2008.     /* 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
  2009.      | 'try' ':' suite 'finally' ':' suite */
  2010.     if (TYPE(CHILD(n, 3)) != except_clause)
  2011.         com_try_finally(c, n);
  2012.     else
  2013.         com_try_except(c, n);
  2014. }
  2015.  
  2016. static object *
  2017. get_docstring(n)
  2018.     node *n;
  2019. {
  2020.     int i;
  2021.  
  2022.     switch (TYPE(n)) {
  2023.  
  2024.     case suite:
  2025.         if (NCH(n) == 1)
  2026.             return get_docstring(CHILD(n, 0));
  2027.         else {
  2028.             for (i = 0; i < NCH(n); i++) {
  2029.                 node *ch = CHILD(n, i);
  2030.                 if (TYPE(ch) == stmt)
  2031.                     return get_docstring(ch);
  2032.             }
  2033.         }
  2034.         break;
  2035.  
  2036.     case file_input:
  2037.         for (i = 0; i < NCH(n); i++) {
  2038.             node *ch = CHILD(n, i);
  2039.             if (TYPE(ch) == stmt)
  2040.                 return get_docstring(ch);
  2041.         }
  2042.         break;
  2043.  
  2044.     case stmt:
  2045.     case simple_stmt:
  2046.     case small_stmt:
  2047.         return get_docstring(CHILD(n, 0));
  2048.  
  2049.     case expr_stmt:
  2050.     case testlist:
  2051.     case test:
  2052.     case and_test:
  2053.     case not_test:
  2054.     case comparison:
  2055.     case expr:
  2056.     case xor_expr:
  2057.     case and_expr:
  2058.     case shift_expr:
  2059.     case arith_expr:
  2060.     case term:
  2061.     case factor:
  2062.         if (NCH(n) == 1)
  2063.             return get_docstring(CHILD(n, 0));
  2064.         break;
  2065.  
  2066.     case atom:
  2067.         if (TYPE(CHILD(n, 0)) == STRING)
  2068.             return parsestrplus(n);
  2069.         break;
  2070.  
  2071.     }
  2072.     return NULL;
  2073. }
  2074.  
  2075. static void
  2076. com_suite(c, n)
  2077.     struct compiling *c;
  2078.     node *n;
  2079. {
  2080.     REQ(n, suite);
  2081.     /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */
  2082.     if (NCH(n) == 1) {
  2083.         com_node(c, CHILD(n, 0));
  2084.     }
  2085.     else {
  2086.         int i;
  2087.         for (i = 0; i < NCH(n); i++) {
  2088.             node *ch = CHILD(n, i);
  2089.             if (TYPE(ch) == stmt)
  2090.                 com_node(c, ch);
  2091.         }
  2092.     }
  2093. }
  2094.  
  2095. /* ARGSUSED */
  2096. static void
  2097. com_continue_stmt(c, n)
  2098.     struct compiling *c;
  2099.     node *n; /* Not used, but passed for consistency */
  2100. {
  2101.     int i = c->c_nblocks;
  2102.     if (i-- > 0 && c->c_block[i] == SETUP_LOOP) {
  2103.         com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  2104.     }
  2105.     else {
  2106.         err_setstr(SyntaxError, "'continue' not properly in loop");
  2107.         c->c_errors++;
  2108.     }
  2109.     /* XXX Could allow it inside a 'finally' clause
  2110.        XXX if we could pop the exception still on the stack */
  2111. }
  2112.  
  2113. static int
  2114. com_argdefs(c, n)
  2115.     struct compiling *c;
  2116.     node *n;
  2117. {
  2118.     int i, nch, nargs, ndefs;
  2119.     if (TYPE(n) == lambdef) {
  2120.         /* lambdef: 'lambda' [varargslist] ':' test */
  2121.         n = CHILD(n, 1);
  2122.     }
  2123.     else {
  2124.         REQ(n, funcdef); /* funcdef: 'def' NAME parameters ... */
  2125.         n = CHILD(n, 2);
  2126.         REQ(n, parameters); /* parameters: '(' [varargslist] ')' */
  2127.         n = CHILD(n, 1);
  2128.     }
  2129.     if (TYPE(n) != varargslist)
  2130.             return 0;
  2131.     /* varargslist:
  2132.         (fpdef ['=' test] ',')* '*' ....... |
  2133.         fpdef ['=' test] (',' fpdef ['=' test])* [','] */
  2134.     nch = NCH(n);
  2135.     nargs = 0;
  2136.     ndefs = 0;
  2137.     for (i = 0; i < nch; i++) {
  2138.         int t;
  2139.         if (TYPE(CHILD(n, i)) == STAR)
  2140.             break;
  2141.         nargs++;
  2142.         i++;
  2143.         if (i >= nch)
  2144.             t = RPAR; /* Anything except EQUAL or COMMA */
  2145.         else
  2146.             t = TYPE(CHILD(n, i));
  2147.         if (t == EQUAL) {
  2148.             i++;
  2149.             ndefs++;
  2150.             com_node(c, CHILD(n, i));
  2151.             i++;
  2152.             if (i >= nch)
  2153.                 break;
  2154.             t = TYPE(CHILD(n, i));
  2155.         }
  2156.         else {
  2157.             /* Treat "(a=1, b)" as "(a=1, b=None)" */
  2158.             if (ndefs) {
  2159.                 com_addoparg(c, LOAD_CONST,
  2160.                          com_addconst(c, None));
  2161.                 ndefs++;
  2162.             }
  2163.         }
  2164.         if (t != COMMA)
  2165.             break;
  2166.     }
  2167.     return ndefs;
  2168. }
  2169.  
  2170. static void
  2171. com_funcdef(c, n)
  2172.     struct compiling *c;
  2173.     node *n;
  2174. {
  2175.     object *v;
  2176.     REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */
  2177.     v = (object *)compile(n, c->c_filename);
  2178.     if (v == NULL)
  2179.         c->c_errors++;
  2180.     else {
  2181.         int i = com_addconst(c, v);
  2182.         int ndefs = com_argdefs(c, n);
  2183.         com_addoparg(c, LOAD_CONST, i);
  2184.         com_addoparg(c, MAKE_FUNCTION, ndefs);
  2185.         com_addopname(c, STORE_NAME, CHILD(n, 1));
  2186.         DECREF(v);
  2187.     }
  2188. }
  2189.  
  2190. static void
  2191. com_bases(c, n)
  2192.     struct compiling *c;
  2193.     node *n;
  2194. {
  2195.     int i;
  2196.     REQ(n, testlist);
  2197.     /* testlist: test (',' test)* [','] */
  2198.     for (i = 0; i < NCH(n); i += 2)
  2199.         com_node(c, CHILD(n, i));
  2200.     com_addoparg(c, BUILD_TUPLE, (NCH(n)+1) / 2);
  2201. }
  2202.  
  2203. static void
  2204. com_classdef(c, n)
  2205.     struct compiling *c;
  2206.     node *n;
  2207. {
  2208.     int i;
  2209.     object *v;
  2210.     REQ(n, classdef);
  2211.     /* classdef: class NAME ['(' testlist ')'] ':' suite */
  2212.     if ((v = newstringobject(STR(CHILD(n, 1)))) == NULL) {
  2213.         c->c_errors++;
  2214.         return;
  2215.     }
  2216.     /* Push the class name on the stack */
  2217.     i = com_addconst(c, v);
  2218.     com_addoparg(c, LOAD_CONST, i);
  2219.     DECREF(v);
  2220.     /* Push the tuple of base classes on the stack */
  2221.     if (TYPE(CHILD(n, 2)) != LPAR)
  2222.         com_addoparg(c, BUILD_TUPLE, 0);
  2223.     else
  2224.         com_bases(c, CHILD(n, 3));
  2225.     v = (object *)compile(n, c->c_filename);
  2226.     if (v == NULL)
  2227.         c->c_errors++;
  2228.     else {
  2229.         i = com_addconst(c, v);
  2230.         com_addoparg(c, LOAD_CONST, i);
  2231.         com_addoparg(c, MAKE_FUNCTION, 0);
  2232.         com_addoparg(c, CALL_FUNCTION, 0);
  2233.         com_addbyte(c, BUILD_CLASS);
  2234.         com_addopname(c, STORE_NAME, CHILD(n, 1));
  2235.         DECREF(v);
  2236.     }
  2237. }
  2238.  
  2239. static void
  2240. com_node(c, n)
  2241.     struct compiling *c;
  2242.     node *n;
  2243. {
  2244.     switch (TYPE(n)) {
  2245.     
  2246.     /* Definition nodes */
  2247.     
  2248.     case funcdef:
  2249.         com_funcdef(c, n);
  2250.         break;
  2251.     case classdef:
  2252.         com_classdef(c, n);
  2253.         break;
  2254.     
  2255.     /* Trivial parse tree nodes */
  2256.     
  2257.     case stmt:
  2258.     case small_stmt:
  2259.     case flow_stmt:
  2260.         com_node(c, CHILD(n, 0));
  2261.         break;
  2262.  
  2263.     case simple_stmt:
  2264.         /* small_stmt (';' small_stmt)* [';'] NEWLINE */
  2265.         com_addoparg(c, SET_LINENO, n->n_lineno);
  2266.         {
  2267.             int i;
  2268.             for (i = 0; i < NCH(n)-1; i += 2)
  2269.                 com_node(c, CHILD(n, i));
  2270.         }
  2271.         break;
  2272.     
  2273.     case compound_stmt:
  2274.         com_addoparg(c, SET_LINENO, n->n_lineno);
  2275.         com_node(c, CHILD(n, 0));
  2276.         break;
  2277.  
  2278.     /* Statement nodes */
  2279.     
  2280.     case expr_stmt:
  2281.         com_expr_stmt(c, n);
  2282.         break;
  2283.     case print_stmt:
  2284.         com_print_stmt(c, n);
  2285.         break;
  2286.     case del_stmt: /* 'del' exprlist */
  2287.         com_assign(c, CHILD(n, 1), 0/*delete*/);
  2288.         break;
  2289.     case pass_stmt:
  2290.         break;
  2291.     case break_stmt:
  2292.         if (c->c_loops == 0) {
  2293.             err_setstr(SyntaxError, "'break' outside loop");
  2294.             c->c_errors++;
  2295.         }
  2296.         com_addbyte(c, BREAK_LOOP);
  2297.         break;
  2298.     case continue_stmt:
  2299.         com_continue_stmt(c, n);
  2300.         break;
  2301.     case return_stmt:
  2302.         com_return_stmt(c, n);
  2303.         break;
  2304.     case raise_stmt:
  2305.         com_raise_stmt(c, n);
  2306.         break;
  2307.     case import_stmt:
  2308.         com_import_stmt(c, n);
  2309.         break;
  2310.     case global_stmt:
  2311.         com_global_stmt(c, n);
  2312.         break;
  2313.     case access_stmt:
  2314.         com_access_stmt(c, n);
  2315.         break;
  2316.     case exec_stmt:
  2317.         com_exec_stmt(c, n);
  2318.         break;
  2319.     case if_stmt:
  2320.         com_if_stmt(c, n);
  2321.         break;
  2322.     case while_stmt:
  2323.         com_while_stmt(c, n);
  2324.         break;
  2325.     case for_stmt:
  2326.         com_for_stmt(c, n);
  2327.         break;
  2328.     case try_stmt:
  2329.         com_try_stmt(c, n);
  2330.         break;
  2331.     case suite:
  2332.         com_suite(c, n);
  2333.         break;
  2334.     
  2335.     /* Expression nodes */
  2336.     
  2337.     case testlist:
  2338.         com_list(c, n, 0);
  2339.         break;
  2340.     case test:
  2341.         com_test(c, n);
  2342.         break;
  2343.     case and_test:
  2344.         com_and_test(c, n);
  2345.         break;
  2346.     case not_test:
  2347.         com_not_test(c, n);
  2348.         break;
  2349.     case comparison:
  2350.         com_comparison(c, n);
  2351.         break;
  2352.     case exprlist:
  2353.         com_list(c, n, 0);
  2354.         break;
  2355.     case expr:
  2356.         com_expr(c, n);
  2357.         break;
  2358.     case xor_expr:
  2359.         com_xor_expr(c, n);
  2360.         break;
  2361.     case and_expr:
  2362.         com_and_expr(c, n);
  2363.         break;
  2364.     case shift_expr:
  2365.         com_shift_expr(c, n);
  2366.         break;
  2367.     case arith_expr:
  2368.         com_arith_expr(c, n);
  2369.         break;
  2370.     case term:
  2371.         com_term(c, n);
  2372.         break;
  2373.     case factor:
  2374.         com_factor(c, n);
  2375.         break;
  2376.     case atom:
  2377.         com_atom(c, n);
  2378.         break;
  2379.     
  2380.     default:
  2381.         fprintf(stderr, "node type %d\n", TYPE(n));
  2382.         err_setstr(SystemError, "com_node: unexpected node type");
  2383.         c->c_errors++;
  2384.     }
  2385. }
  2386.  
  2387. static void com_fplist PROTO((struct compiling *, node *));
  2388.  
  2389. static void
  2390. com_fpdef(c, n)
  2391.     struct compiling *c;
  2392.     node *n;
  2393. {
  2394.     REQ(n, fpdef); /* fpdef: NAME | '(' fplist ')' */
  2395.     if (TYPE(CHILD(n, 0)) == LPAR)
  2396.         com_fplist(c, CHILD(n, 1));
  2397.     else
  2398.         com_addoparg(c, STORE_FAST, com_newlocal(c, STR(CHILD(n, 0))));
  2399. }
  2400.  
  2401. static void
  2402. com_fplist(c, n)
  2403.     struct compiling *c;
  2404.     node *n;
  2405. {
  2406.     REQ(n, fplist); /* fplist: fpdef (',' fpdef)* [','] */
  2407.     if (NCH(n) == 1) {
  2408.         com_fpdef(c, CHILD(n, 0));
  2409.     }
  2410.     else {
  2411.         int i;
  2412.         com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2);
  2413.         for (i = 0; i < NCH(n); i += 2)
  2414.             com_fpdef(c, CHILD(n, i));
  2415.     }
  2416. }
  2417.  
  2418. static void
  2419. com_arglist(c, n)
  2420.     struct compiling *c;
  2421.     node *n;
  2422. {
  2423.     int nch, i;
  2424.     int complex = 0;
  2425.     REQ(n, varargslist);
  2426.     /* varargslist:
  2427.         (fpdef ['=' test] ',')* (fpdef ['=' test] | '*' .....) */
  2428.     nch = NCH(n);
  2429.     /* Enter all arguments in table of locals */
  2430.     for (i = 0; i < nch; i++) {
  2431.         node *ch = CHILD(n, i);
  2432.         node *fp;
  2433.         char *name;
  2434.         if (TYPE(ch) == STAR)
  2435.             break;
  2436.         REQ(ch, fpdef); /* fpdef: NAME | '(' fplist ')' */
  2437.         fp = CHILD(ch, 0);
  2438.         if (TYPE(fp) == NAME)
  2439.             name = STR(fp);
  2440.         else {
  2441.             name = "";
  2442.             complex= 1;
  2443.         }
  2444.         com_newlocal(c, name);
  2445.         c->c_argcount++;
  2446.         if (++i >= nch)
  2447.             break;
  2448.         ch = CHILD(n, i);
  2449.         if (TYPE(ch) == EQUAL)
  2450.             i += 2;
  2451.         else
  2452.             REQ(ch, COMMA);
  2453.     }
  2454.     /* Handle *arguments */
  2455.     if (i < nch) {
  2456.         node *ch;
  2457.         ch = CHILD(n, i);
  2458.         REQ(ch, STAR);
  2459.         ch = CHILD(n, i+1);
  2460.         if (TYPE(ch) == NAME) {
  2461.             c->c_flags |= CO_VARARGS;
  2462.             i += 3;
  2463.             com_newlocal(c, STR(ch));
  2464.         }
  2465.     }
  2466.     /* Handle **keywords */
  2467.     if (i < nch) {
  2468.         node *ch;
  2469.         ch = CHILD(n, i);
  2470.         REQ(ch, STAR);
  2471.         ch = CHILD(n, i+1);
  2472.         REQ(ch, STAR);
  2473.         ch = CHILD(n, i+2);
  2474.         REQ(ch, NAME);
  2475.         c->c_flags |= CO_VARKEYWORDS;
  2476.         com_newlocal(c, STR(ch));
  2477.     }
  2478.     if (complex) {
  2479.         /* Generate code for complex arguments only after
  2480.            having counted the simple arguments */
  2481.         int ilocal = 0;
  2482.         for (i = 0; i < nch; i++) {
  2483.             node *ch = CHILD(n, i);
  2484.             node *fp;
  2485.             if (TYPE(ch) == STAR)
  2486.                 break;
  2487.             REQ(ch, fpdef); /* fpdef: NAME | '(' fplist ')' */
  2488.             fp = CHILD(ch, 0);
  2489.             if (TYPE(fp) != NAME) {
  2490.                 com_addoparg(c, LOAD_FAST, ilocal);
  2491.                 com_fpdef(c, ch);
  2492.             }
  2493.             ilocal++;
  2494.             if (++i >= nch)
  2495.                 break;
  2496.             ch = CHILD(n, i);
  2497.             if (TYPE(ch) == EQUAL)
  2498.                 i += 2;
  2499.             else
  2500.                 REQ(ch, COMMA);
  2501.         }
  2502.     }
  2503. }
  2504.  
  2505. static void
  2506. com_file_input(c, n)
  2507.     struct compiling *c;
  2508.     node *n;
  2509. {
  2510.     int i;
  2511.     object *doc;
  2512.     REQ(n, file_input); /* (NEWLINE | stmt)* ENDMARKER */
  2513.     doc = get_docstring(n);
  2514.     if (doc != NULL) {
  2515.         int i = com_addconst(c, doc);
  2516.         DECREF(doc);
  2517.         com_addoparg(c, LOAD_CONST, i);
  2518.         com_addopnamestr(c, STORE_NAME, "__doc__");
  2519.     }
  2520.     for (i = 0; i < NCH(n); i++) {
  2521.         node *ch = CHILD(n, i);
  2522.         if (TYPE(ch) != ENDMARKER && TYPE(ch) != NEWLINE)
  2523.             com_node(c, ch);
  2524.     }
  2525. }
  2526.  
  2527. /* Top-level compile-node interface */
  2528.  
  2529. static void
  2530. compile_funcdef(c, n)
  2531.     struct compiling *c;
  2532.     node *n;
  2533. {
  2534.     object *doc;
  2535.     node *ch;
  2536.     REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */
  2537.     c->c_name = STR(CHILD(n, 1));
  2538.     doc = get_docstring(CHILD(n, 4));
  2539.     if (doc != NULL) {
  2540.         (void) com_addconst(c, doc);
  2541.         DECREF(doc);
  2542.     }
  2543.     else
  2544.         (void) com_addconst(c, None); /* No docstring */
  2545.     ch = CHILD(n, 2); /* parameters: '(' [varargslist] ')' */
  2546.     ch = CHILD(ch, 1); /* ')' | varargslist */
  2547.     if (TYPE(ch) == varargslist)
  2548.         com_arglist(c, ch);
  2549.     c->c_infunction = 1;
  2550.     com_node(c, CHILD(n, 4));
  2551.     c->c_infunction = 0;
  2552.     com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  2553.     com_addbyte(c, RETURN_VALUE);
  2554. }
  2555.  
  2556. static void
  2557. compile_lambdef(c, n)
  2558.     struct compiling *c;
  2559.     node *n;
  2560. {
  2561.     node *ch;
  2562.     REQ(n, lambdef); /* lambdef: 'lambda' [varargslist] ':' test */
  2563.     c->c_name = "<lambda>";
  2564.  
  2565.     ch = CHILD(n, 1);
  2566.     (void) com_addconst(c, None); /* No docstring */
  2567.     if (TYPE(ch) == varargslist) {
  2568.         com_arglist(c, ch);
  2569.         ch = CHILD(n, 3);
  2570.     }
  2571.     else
  2572.         ch = CHILD(n, 2);
  2573.     com_node(c, ch);
  2574.     com_addbyte(c, RETURN_VALUE);
  2575. }
  2576.  
  2577. static void
  2578. compile_classdef(c, n)
  2579.     struct compiling *c;
  2580.     node *n;
  2581. {
  2582.     node *ch;
  2583.     object *doc;
  2584.     REQ(n, classdef);
  2585.     /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */
  2586.     c->c_name = STR(CHILD(n, 1));
  2587.     ch = CHILD(n, NCH(n)-1); /* The suite */
  2588.     doc = get_docstring(ch);
  2589.     if (doc != NULL) {
  2590.         int i = com_addconst(c, doc);
  2591.         DECREF(doc);
  2592.         com_addoparg(c, LOAD_CONST, i);
  2593.         com_addopnamestr(c, STORE_NAME, "__doc__");
  2594.     }
  2595.     else
  2596.         (void) com_addconst(c, None);
  2597.     com_node(c, ch);
  2598.     com_addbyte(c, LOAD_LOCALS);
  2599.     com_addbyte(c, RETURN_VALUE);
  2600. }
  2601.  
  2602. static void
  2603. compile_node(c, n)
  2604.     struct compiling *c;
  2605.     node *n;
  2606. {
  2607.     com_addoparg(c, SET_LINENO, n->n_lineno);
  2608.     
  2609.     switch (TYPE(n)) {
  2610.     
  2611.     case single_input: /* One interactive command */
  2612.         /* NEWLINE | simple_stmt | compound_stmt NEWLINE */
  2613.         c->c_interactive++;
  2614.         n = CHILD(n, 0);
  2615.         if (TYPE(n) != NEWLINE)
  2616.             com_node(c, n);
  2617.         com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  2618.         com_addbyte(c, RETURN_VALUE);
  2619.         c->c_interactive--;
  2620.         break;
  2621.     
  2622.     case file_input: /* A whole file, or built-in function exec() */
  2623.         com_file_input(c, n);
  2624.         com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  2625.         com_addbyte(c, RETURN_VALUE);
  2626.         break;
  2627.     
  2628.     case eval_input: /* Built-in function input() */
  2629.         com_node(c, CHILD(n, 0));
  2630.         com_addbyte(c, RETURN_VALUE);
  2631.         break;
  2632.     
  2633.     case lambdef: /* anonymous function definition */
  2634.         compile_lambdef(c, n);
  2635.         break;
  2636.  
  2637.     case funcdef: /* A function definition */
  2638.         compile_funcdef(c, n);
  2639.         break;
  2640.     
  2641.     case classdef: /* A class definition */
  2642.         compile_classdef(c, n);
  2643.         break;
  2644.     
  2645.     default:
  2646.         fprintf(stderr, "node type %d\n", TYPE(n));
  2647.         err_setstr(SystemError, "compile_node: unexpected node type");
  2648.         c->c_errors++;
  2649.     }
  2650. }
  2651.  
  2652. /* Optimization for local variables in functions (and *only* functions).
  2653.  
  2654.    This replaces all LOAD_NAME, STORE_NAME and DELETE_NAME
  2655.    instructions that refer to local variables with LOAD_FAST etc.
  2656.    The latter instructions are much faster because they don't need to
  2657.    look up the variable name in a dictionary.
  2658.  
  2659.    To find all local variables, we check all STORE_NAME, IMPORT_FROM
  2660.    and DELETE_NAME instructions.  This yields all local variables,
  2661.    function definitions, class definitions and import statements.
  2662.    Argument names have already been entered into the list by the
  2663.    special processing for the argument list.
  2664.  
  2665.    All remaining LOAD_NAME instructions must refer to non-local (global
  2666.    or builtin) variables, so are replaced by LOAD_GLOBAL.
  2667.  
  2668.    There are two problems:  'from foo import *' and 'exec' may introduce
  2669.    local variables that we can't know while compiling.  If this is the
  2670.    case, we can still optimize bona fide locals (since those
  2671.    statements will be surrounded by fast_2_locals() and
  2672.    locals_2_fast()), but we can't change LOAD_NAME to LOAD_GLOBAL.
  2673.  
  2674.    NB: this modifies the string object c->c_code!  */
  2675.  
  2676. static void
  2677. optimize(c)
  2678.     struct compiling *c;
  2679. {
  2680.     unsigned char *next_instr, *cur_instr;
  2681.     int opcode;
  2682.     int oparg;
  2683.     object *name;
  2684.     object *error_type, *error_value, *error_traceback;
  2685.     
  2686. #define NEXTOP()    (*next_instr++)
  2687. #define NEXTARG()    (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
  2688. #define GETITEM(v, i)    (getlistitem((v), (i)))
  2689. #define GETNAMEOBJ(i)    (GETITEM(c->c_names, (i)))
  2690.     
  2691.     err_fetch(&error_type, &error_value, &error_traceback);
  2692.  
  2693.     c->c_flags |= CO_OPTIMIZED;
  2694.     
  2695.     next_instr = (unsigned char *) getstringvalue(c->c_code);
  2696.     for (;;) {
  2697.         opcode = NEXTOP();
  2698.         if (opcode == STOP_CODE)
  2699.             break;
  2700.         if (HAS_ARG(opcode))
  2701.             oparg = NEXTARG();
  2702.         switch (opcode) {
  2703.         case STORE_NAME:
  2704.         case DELETE_NAME:
  2705.         case IMPORT_FROM:
  2706.             com_addlocal_o(c, GETNAMEOBJ(oparg));
  2707.             break;
  2708.         case EXEC_STMT:
  2709.             c->c_flags &= ~CO_OPTIMIZED;
  2710.             break;
  2711.         }
  2712.     }
  2713.     
  2714.     if (dictlookup(c->c_locals, "*") != NULL)
  2715.         c->c_flags &= ~CO_OPTIMIZED;
  2716.     
  2717.     next_instr = (unsigned char *) getstringvalue(c->c_code);
  2718.     for (;;) {
  2719.         cur_instr = next_instr;
  2720.         opcode = NEXTOP();
  2721.         if (opcode == STOP_CODE)
  2722.             break;
  2723.         if (HAS_ARG(opcode))
  2724.             oparg = NEXTARG();
  2725.         if (opcode == LOAD_NAME ||
  2726.             opcode == STORE_NAME ||
  2727.             opcode == DELETE_NAME) {
  2728.             object *v;
  2729.             int i;
  2730.             name = GETNAMEOBJ(oparg);
  2731.             v = dict2lookup(c->c_locals, name);
  2732.             if (v == NULL) {
  2733.                 err_clear();
  2734.                 if (opcode == LOAD_NAME &&
  2735.                     (c->c_flags&CO_OPTIMIZED))
  2736.                     cur_instr[0] = LOAD_GLOBAL;
  2737.                 continue;
  2738.             }
  2739.             i = getintvalue(v);
  2740.             switch (opcode) {
  2741.             case LOAD_NAME: cur_instr[0] = LOAD_FAST; break;
  2742.             case STORE_NAME: cur_instr[0] = STORE_FAST; break;
  2743.             case DELETE_NAME: cur_instr[0] = DELETE_FAST; break;
  2744.             }
  2745.             cur_instr[1] = i & 0xff;
  2746.             cur_instr[2] = (i>>8) & 0xff;
  2747.         }
  2748.     }
  2749.  
  2750.     if (c->c_errors == 0)
  2751.         err_restore(error_type, error_value, error_traceback);
  2752. }
  2753.  
  2754. codeobject *
  2755. compile(n, filename)
  2756.     node *n;
  2757.     char *filename;
  2758. {
  2759.     struct compiling sc;
  2760.     codeobject *co;
  2761.     if (!com_init(&sc, filename))
  2762.         return NULL;
  2763.     compile_node(&sc, n);
  2764.     com_done(&sc);
  2765.     if ((TYPE(n) == funcdef || TYPE(n) == lambdef) && sc.c_errors == 0) {
  2766.         optimize(&sc);
  2767.         sc.c_flags |= CO_NEWLOCALS;
  2768.     }
  2769.     else if (TYPE(n) == classdef)
  2770.         sc.c_flags |= CO_NEWLOCALS;
  2771.     co = NULL;
  2772.     if (sc.c_errors == 0) {
  2773.         object *consts, *names, *varnames, *filename, *name;
  2774.         consts = listtuple(sc.c_consts);
  2775.         names = listtuple(sc.c_names);
  2776.         varnames = listtuple(sc.c_varnames);
  2777.         filename = newstringobject(sc.c_filename);
  2778.         name = newstringobject(sc.c_name);
  2779.         if (!err_occurred())
  2780.             co = newcodeobject(sc.c_argcount,
  2781.                        sc.c_nlocals,
  2782.                        sc.c_flags,
  2783.                        sc.c_code,
  2784.                        consts,
  2785.                        names,
  2786.                        varnames,
  2787.                        filename,
  2788.                        name);
  2789.         XDECREF(consts);
  2790.         XDECREF(names);
  2791.         XDECREF(varnames);
  2792.         XDECREF(filename);
  2793.         XDECREF(name);
  2794.     }
  2795.     com_free(&sc);
  2796.     return co;
  2797. }
  2798.