home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / p / python / pytexdoc / ext / source / !Python / Monty / c / compile < prev    next >
Encoding:
Text File  |  1996-11-06  |  64.2 KB  |  3,013 lines

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