home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyth_os2.zip / python-1.0.2 / Python / compile.c < prev    next >
C/C++ Source or Header  |  1994-05-04  |  54KB  |  2,500 lines

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