1 /* Compile an expression node to intermediate code */
4 XXX add __doc__ attribute == co_doc to code object attributes?
5 XXX (it's currently the first item of the co_const tuple)
6 XXX Generate simple jump for break/return outside 'try...finally'
7 XXX Allow 'continue' inside finally clause of try-finally
8 XXX New opcode for loading the initial index for a for loop
20 #include "structmember.h"
24 /* Three symbols from graminit.h are also defined in Python.h, with
25 Py_ prefixes to their names. Python.h can't include graminit.h
26 (which defines too many confusing symbols), but we can check here
27 that they haven't changed (which is very unlikely, but possible). */
28 #if Py_single_input != single_input
29 #error "single_input has changed -- update Py_single_input in Python.h"
31 #if Py_file_input != file_input
32 #error "file_input has changed -- update Py_file_input in Python.h"
34 #if Py_eval_input != eval_input
35 #error "eval_input has changed -- update Py_eval_input in Python.h"
38 int Py_OptimizeFlag
= 0;
48 #define DEL_CLOSURE_ERROR \
49 "can not delete variable '%.400s' referenced in nested scope"
51 #define DUPLICATE_ARGUMENT \
52 "duplicate argument '%s' in function definition"
54 #define ILLEGAL_DYNAMIC_SCOPE \
55 "%.100s: exec or 'import *' makes names ambiguous in nested scope"
57 #define GLOBAL_AFTER_ASSIGN \
58 "name '%.400s' is assigned to before global declaration"
60 #define GLOBAL_AFTER_USE \
61 "name '%.400s' is used prior to global declaration"
63 #define LOCAL_GLOBAL \
64 "name '%.400s' is a function paramter and declared global"
67 "from __future__ imports must occur at the beginning of the file"
69 #define ASSIGN_DEBUG \
70 "can not assign to __debug__"
72 #define MANGLE_LEN 256
74 #define OFF(x) offsetof(PyCodeObject, x)
76 static struct memberlist code_memberlist
[] = {
77 {"co_argcount", T_INT
, OFF(co_argcount
), READONLY
},
78 {"co_nlocals", T_INT
, OFF(co_nlocals
), READONLY
},
79 {"co_stacksize",T_INT
, OFF(co_stacksize
), READONLY
},
80 {"co_flags", T_INT
, OFF(co_flags
), READONLY
},
81 {"co_code", T_OBJECT
, OFF(co_code
), READONLY
},
82 {"co_consts", T_OBJECT
, OFF(co_consts
), READONLY
},
83 {"co_names", T_OBJECT
, OFF(co_names
), READONLY
},
84 {"co_varnames", T_OBJECT
, OFF(co_varnames
), READONLY
},
85 {"co_freevars", T_OBJECT
, OFF(co_freevars
), READONLY
},
86 {"co_cellvars", T_OBJECT
, OFF(co_cellvars
), READONLY
},
87 {"co_filename", T_OBJECT
, OFF(co_filename
), READONLY
},
88 {"co_name", T_OBJECT
, OFF(co_name
), READONLY
},
89 {"co_firstlineno", T_INT
, OFF(co_firstlineno
), READONLY
},
90 {"co_lnotab", T_OBJECT
, OFF(co_lnotab
), READONLY
},
95 code_getattr(PyCodeObject
*co
, char *name
)
97 return PyMember_Get((char *)co
, code_memberlist
, name
);
101 code_dealloc(PyCodeObject
*co
)
103 Py_XDECREF(co
->co_code
);
104 Py_XDECREF(co
->co_consts
);
105 Py_XDECREF(co
->co_names
);
106 Py_XDECREF(co
->co_varnames
);
107 Py_XDECREF(co
->co_freevars
);
108 Py_XDECREF(co
->co_cellvars
);
109 Py_XDECREF(co
->co_filename
);
110 Py_XDECREF(co
->co_name
);
111 Py_XDECREF(co
->co_lnotab
);
116 code_repr(PyCodeObject
*co
)
120 char *filename
= "???";
123 if (co
->co_firstlineno
!= 0)
124 lineno
= co
->co_firstlineno
;
125 if (co
->co_filename
&& PyString_Check(co
->co_filename
))
126 filename
= PyString_AS_STRING(co
->co_filename
);
127 if (co
->co_name
&& PyString_Check(co
->co_name
))
128 name
= PyString_AS_STRING(co
->co_name
);
129 sprintf(buf
, "<code object %.100s at %p, file \"%.300s\", line %d>",
130 name
, co
, filename
, lineno
);
131 return PyString_FromString(buf
);
135 code_compare(PyCodeObject
*co
, PyCodeObject
*cp
)
138 cmp
= PyObject_Compare(co
->co_name
, cp
->co_name
);
140 cmp
= co
->co_argcount
- cp
->co_argcount
;
142 cmp
= co
->co_nlocals
- cp
->co_nlocals
;
144 cmp
= co
->co_flags
- cp
->co_flags
;
146 cmp
= PyObject_Compare(co
->co_code
, cp
->co_code
);
148 cmp
= PyObject_Compare(co
->co_consts
, cp
->co_consts
);
150 cmp
= PyObject_Compare(co
->co_names
, cp
->co_names
);
152 cmp
= PyObject_Compare(co
->co_varnames
, cp
->co_varnames
);
154 cmp
= PyObject_Compare(co
->co_freevars
, cp
->co_freevars
);
156 cmp
= PyObject_Compare(co
->co_cellvars
, cp
->co_cellvars
);
161 code_hash(PyCodeObject
*co
)
163 long h
, h0
, h1
, h2
, h3
, h4
, h5
, h6
;
164 h0
= PyObject_Hash(co
->co_name
);
165 if (h0
== -1) return -1;
166 h1
= PyObject_Hash(co
->co_code
);
167 if (h1
== -1) return -1;
168 h2
= PyObject_Hash(co
->co_consts
);
169 if (h2
== -1) return -1;
170 h3
= PyObject_Hash(co
->co_names
);
171 if (h3
== -1) return -1;
172 h4
= PyObject_Hash(co
->co_varnames
);
173 if (h4
== -1) return -1;
174 h5
= PyObject_Hash(co
->co_freevars
);
175 if (h5
== -1) return -1;
176 h6
= PyObject_Hash(co
->co_cellvars
);
177 if (h6
== -1) return -1;
178 h
= h0
^ h1
^ h2
^ h3
^ h4
^ h5
^ h6
^
179 co
->co_argcount
^ co
->co_nlocals
^ co
->co_flags
;
184 /* XXX code objects need to participate in GC? */
186 PyTypeObject PyCode_Type
= {
187 PyObject_HEAD_INIT(&PyType_Type
)
190 sizeof(PyCodeObject
),
192 (destructor
)code_dealloc
, /*tp_dealloc*/
194 (getattrfunc
)code_getattr
, /*tp_getattr*/
196 (cmpfunc
)code_compare
, /*tp_compare*/
197 (reprfunc
)code_repr
, /*tp_repr*/
199 0, /*tp_as_sequence*/
201 (hashfunc
)code_hash
, /*tp_hash*/
205 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
207 /* all_name_chars(s): true iff all chars in s are valid NAME_CHARS */
210 all_name_chars(unsigned char *s
)
212 static char ok_name_char
[256];
213 static unsigned char *name_chars
= (unsigned char *)NAME_CHARS
;
215 if (ok_name_char
[*name_chars
] == 0) {
217 for (p
= name_chars
; *p
; p
++)
218 ok_name_char
[*p
] = 1;
221 if (ok_name_char
[*s
++] == 0)
228 intern_strings(PyObject
*tuple
)
232 for (i
= PyTuple_GET_SIZE(tuple
); --i
>= 0; ) {
233 PyObject
*v
= PyTuple_GET_ITEM(tuple
, i
);
234 if (v
== NULL
|| !PyString_Check(v
)) {
235 Py_FatalError("non-string found in code slot");
236 PyErr_BadInternalCall();
239 PyString_InternInPlace(&PyTuple_GET_ITEM(tuple
, i
));
245 PyCode_New(int argcount
, int nlocals
, int stacksize
, int flags
,
246 PyObject
*code
, PyObject
*consts
, PyObject
*names
,
247 PyObject
*varnames
, PyObject
*freevars
, PyObject
*cellvars
,
248 PyObject
*filename
, PyObject
*name
, int firstlineno
,
254 /* Check argument types */
255 if (argcount
< 0 || nlocals
< 0 ||
257 consts
== NULL
|| !PyTuple_Check(consts
) ||
258 names
== NULL
|| !PyTuple_Check(names
) ||
259 varnames
== NULL
|| !PyTuple_Check(varnames
) ||
260 freevars
== NULL
|| !PyTuple_Check(freevars
) ||
261 cellvars
== NULL
|| !PyTuple_Check(cellvars
) ||
262 name
== NULL
|| !PyString_Check(name
) ||
263 filename
== NULL
|| !PyString_Check(filename
) ||
264 lnotab
== NULL
|| !PyString_Check(lnotab
)) {
265 PyErr_BadInternalCall();
268 pb
= code
->ob_type
->tp_as_buffer
;
270 pb
->bf_getreadbuffer
== NULL
||
271 pb
->bf_getsegcount
== NULL
||
272 (*pb
->bf_getsegcount
)(code
, NULL
) != 1)
274 PyErr_BadInternalCall();
277 intern_strings(names
);
278 intern_strings(varnames
);
279 if (freevars
== NULL
)
280 freevars
= PyTuple_New(0);
281 intern_strings(freevars
);
282 if (cellvars
== NULL
)
283 cellvars
= PyTuple_New(0);
284 intern_strings(cellvars
);
285 /* Intern selected string constants */
286 for (i
= PyTuple_Size(consts
); --i
>= 0; ) {
287 PyObject
*v
= PyTuple_GetItem(consts
, i
);
288 if (!PyString_Check(v
))
290 if (!all_name_chars((unsigned char *)PyString_AS_STRING(v
)))
292 PyString_InternInPlace(&PyTuple_GET_ITEM(consts
, i
));
294 co
= PyObject_NEW(PyCodeObject
, &PyCode_Type
);
296 co
->co_argcount
= argcount
;
297 co
->co_nlocals
= nlocals
;
298 co
->co_stacksize
= stacksize
;
299 co
->co_flags
= flags
;
303 co
->co_consts
= consts
;
305 co
->co_names
= names
;
307 co
->co_varnames
= varnames
;
309 co
->co_freevars
= freevars
;
311 co
->co_cellvars
= cellvars
;
313 co
->co_filename
= filename
;
316 co
->co_firstlineno
= firstlineno
;
318 co
->co_lnotab
= lnotab
;
324 /* Data structure used internally */
326 /* The compiler uses two passes to generate bytecodes. The first pass
327 builds the symbol table. The second pass generates the bytecode.
329 The first pass uses a single symtable struct. The second pass uses
330 a compiling struct for each code block. The compiling structs
331 share a reference to the symtable.
333 The two passes communicate via symtable_load_symbols() and via
334 is_local() and is_global(). The former initializes several slots
335 in the compiling struct: c_varnames, c_locals, c_nlocals,
336 c_argcount, c_globals, and c_flags.
339 /* All about c_lnotab.
341 c_lnotab is an array of unsigned bytes disguised as a Python string. In -O
342 mode, SET_LINENO opcodes aren't generated, and bytecode offsets are mapped
343 to source code line #s (when needed for tracebacks) via c_lnotab instead.
344 The array is conceptually a list of
345 (bytecode offset increment, line number increment)
346 pairs. The details are important and delicate, best illustrated by example:
348 byte code offset source code line number
355 The first trick is that these numbers aren't stored, only the increments
356 from one row to the next (this doesn't really work, but it's a start):
358 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
360 The second trick is that an unsigned byte can't hold negative values, or
361 values larger than 255, so (a) there's a deep assumption that byte code
362 offsets and their corresponding line #s both increase monotonically, and (b)
363 if at least one column jumps by more than 255 from one row to the next, more
364 than one pair is written to the table. In case #b, there's no way to know
365 from looking at the table later how many were written. That's the delicate
366 part. A user of c_lnotab desiring to find the source line number
367 corresponding to a bytecode address A should do something like this
370 for addr_incr, line_incr in c_lnotab:
376 In order for this to work, when the addr field increments by more than 255,
377 the line # increment in each pair generated must be 0 until the remaining addr
378 increment is < 256. So, in the example above, com_set_lineno should not (as
379 was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
380 255, 0, 45, 255, 0, 45.
384 PyObject
*c_code
; /* string */
385 PyObject
*c_consts
; /* list of objects */
386 PyObject
*c_const_dict
; /* inverse of c_consts */
387 PyObject
*c_names
; /* list of strings (names) */
388 PyObject
*c_name_dict
; /* inverse of c_names */
389 PyObject
*c_globals
; /* dictionary (value=None) */
390 PyObject
*c_locals
; /* dictionary (value=localID) */
391 PyObject
*c_varnames
; /* list (inverse of c_locals) */
392 PyObject
*c_freevars
; /* dictionary (value=None) */
393 PyObject
*c_cellvars
; /* list */
394 int c_nlocals
; /* index of next local */
395 int c_argcount
; /* number of top-level arguments */
396 int c_flags
; /* same as co_flags */
397 int c_nexti
; /* index into c_code */
398 int c_errors
; /* counts errors occurred */
399 int c_infunction
; /* set when compiling a function */
400 int c_interactive
; /* generating code for interactive command */
401 int c_loops
; /* counts nested loops */
402 int c_begin
; /* begin of current loop, for 'continue' */
403 int c_block
[CO_MAXBLOCKS
]; /* stack of block types */
404 int c_nblocks
; /* current block stack level */
405 char *c_filename
; /* filename of current node */
406 char *c_name
; /* name of object (e.g. function) */
407 int c_lineno
; /* Current line number */
408 int c_stacklevel
; /* Current stack level */
409 int c_maxstacklevel
; /* Maximum stack level */
411 PyObject
*c_lnotab
; /* Table mapping address to line number */
412 int c_last_addr
, c_last_line
, c_lnotab_next
;
413 char *c_private
; /* for private name mangling */
414 int c_tmpname
; /* temporary local name counter */
415 int c_nested
; /* Is block nested funcdef or lamdef? */
416 int c_closure
; /* Is nested w/freevars? */
417 struct symtable
*c_symtable
; /* pointer to module symbol table */
418 PyFutureFeatures
*c_future
; /* pointer to module's __future__ */
424 if ((v
& (USE
| DEF_FREE
))
425 && !(v
& (DEF_LOCAL
| DEF_PARAM
| DEF_GLOBAL
)))
427 if (v
& DEF_FREE_CLASS
)
433 com_error(struct compiling
*c
, PyObject
*exc
, char *msg
)
435 PyObject
*t
= NULL
, *v
= NULL
, *w
= NULL
, *line
= NULL
;
438 /* Error occurred via symtable call to
440 PyErr_SetString(exc
, msg
);
444 if (c
->c_lineno
< 1 || c
->c_interactive
) {
445 /* Unknown line number or interactive input */
446 PyErr_SetString(exc
, msg
);
449 v
= PyString_FromString(msg
);
451 return; /* MemoryError, too bad */
453 line
= PyErr_ProgramText(c
->c_filename
, c
->c_lineno
);
458 t
= Py_BuildValue("(ziOO)", c
->c_filename
, c
->c_lineno
,
462 w
= Py_BuildValue("(OO)", v
, t
);
465 PyErr_SetObject(exc
, w
);
473 /* Interface to the block stack */
476 block_push(struct compiling
*c
, int type
)
478 if (c
->c_nblocks
>= CO_MAXBLOCKS
) {
479 com_error(c
, PyExc_SystemError
,
480 "too many statically nested blocks");
483 c
->c_block
[c
->c_nblocks
++] = type
;
488 block_pop(struct compiling
*c
, int type
)
490 if (c
->c_nblocks
> 0)
492 if (c
->c_block
[c
->c_nblocks
] != type
&& c
->c_errors
== 0) {
493 com_error(c
, PyExc_SystemError
, "bad block pop");
497 /* Prototype forward declarations */
499 static int com_init(struct compiling
*, char *);
500 static void com_free(struct compiling
*);
501 static void com_push(struct compiling
*, int);
502 static void com_pop(struct compiling
*, int);
503 static void com_done(struct compiling
*);
504 static void com_node(struct compiling
*, node
*);
505 static void com_factor(struct compiling
*, node
*);
506 static void com_addbyte(struct compiling
*, int);
507 static void com_addint(struct compiling
*, int);
508 static void com_addoparg(struct compiling
*, int, int);
509 static void com_addfwref(struct compiling
*, int, int *);
510 static void com_backpatch(struct compiling
*, int);
511 static int com_add(struct compiling
*, PyObject
*, PyObject
*, PyObject
*);
512 static int com_addconst(struct compiling
*, PyObject
*);
513 static int com_addname(struct compiling
*, PyObject
*);
514 static void com_addopname(struct compiling
*, int, node
*);
515 static void com_list(struct compiling
*, node
*, int);
516 static void com_list_iter(struct compiling
*, node
*, node
*, char *);
517 static int com_argdefs(struct compiling
*, node
*);
518 static void com_assign(struct compiling
*, node
*, int, node
*);
519 static void com_assign_name(struct compiling
*, node
*, int);
520 static PyCodeObject
*icompile(node
*, struct compiling
*);
521 static PyCodeObject
*jcompile(node
*, char *, struct compiling
*,
523 static PyObject
*parsestrplus(node
*);
524 static PyObject
*parsestr(char *);
525 static node
*get_rawdocstring(node
*);
527 static int get_ref_type(struct compiling
*, char *);
529 /* symtable operations */
530 static int symtable_build(struct compiling
*, node
*);
531 static int symtable_load_symbols(struct compiling
*);
532 static struct symtable
*symtable_init(void);
533 static void symtable_enter_scope(struct symtable
*, char *, int, int);
534 static int symtable_exit_scope(struct symtable
*);
535 static int symtable_add_def(struct symtable
*, char *, int);
536 static int symtable_add_def_o(struct symtable
*, PyObject
*, PyObject
*, int);
538 static void symtable_node(struct symtable
*, node
*);
539 static void symtable_funcdef(struct symtable
*, node
*);
540 static void symtable_default_args(struct symtable
*, node
*);
541 static void symtable_params(struct symtable
*, node
*);
542 static void symtable_params_fplist(struct symtable
*, node
*n
);
543 static void symtable_global(struct symtable
*, node
*);
544 static void symtable_import(struct symtable
*, node
*);
545 static void symtable_assign(struct symtable
*, node
*, int);
546 static void symtable_list_comprehension(struct symtable
*, node
*);
548 static int symtable_update_free_vars(struct symtable
*);
549 static int symtable_undo_free(struct symtable
*, PyObject
*, PyObject
*);
550 static int symtable_check_global(struct symtable
*, PyObject
*, PyObject
*);
557 for (i
= 0; i
< pad
; ++i
)
558 fprintf(stderr
, " ");
562 dump(node
*n
, int pad
, int depth
)
568 fprintf(stderr
, "%d: %s\n", TYPE(n
), STR(n
));
571 for (i
= 0; i
< NCH(n
); ++i
)
572 dump(CHILD(n
, i
), pad
+ 1, depth
);
575 #define DUMP(N) dump(N, 0, -1)
578 com_init(struct compiling
*c
, char *filename
)
580 memset((void *)c
, '\0', sizeof(struct compiling
));
581 if ((c
->c_code
= PyString_FromStringAndSize((char *)NULL
,
584 if ((c
->c_consts
= PyList_New(0)) == NULL
)
586 if ((c
->c_const_dict
= PyDict_New()) == NULL
)
588 if ((c
->c_names
= PyList_New(0)) == NULL
)
590 if ((c
->c_name_dict
= PyDict_New()) == NULL
)
592 if ((c
->c_locals
= PyDict_New()) == NULL
)
594 if ((c
->c_lnotab
= PyString_FromStringAndSize((char *)NULL
,
598 c
->c_varnames
= NULL
;
599 c
->c_freevars
= NULL
;
600 c
->c_cellvars
= NULL
;
607 c
->c_interactive
= 0;
611 c
->c_filename
= filename
;
615 c
->c_maxstacklevel
= 0;
616 c
->c_firstlineno
= 0;
619 c
->c_lnotab_next
= 0;
623 c
->c_symtable
= NULL
;
632 com_free(struct compiling
*c
)
634 Py_XDECREF(c
->c_code
);
635 Py_XDECREF(c
->c_consts
);
636 Py_XDECREF(c
->c_const_dict
);
637 Py_XDECREF(c
->c_names
);
638 Py_XDECREF(c
->c_name_dict
);
639 Py_XDECREF(c
->c_globals
);
640 Py_XDECREF(c
->c_locals
);
641 Py_XDECREF(c
->c_varnames
);
642 Py_XDECREF(c
->c_freevars
);
643 Py_XDECREF(c
->c_cellvars
);
644 Py_XDECREF(c
->c_lnotab
);
646 PyMem_Free((void *)c
->c_future
);
650 com_push(struct compiling
*c
, int n
)
652 c
->c_stacklevel
+= n
;
653 if (c
->c_stacklevel
> c
->c_maxstacklevel
)
654 c
->c_maxstacklevel
= c
->c_stacklevel
;
658 com_pop(struct compiling
*c
, int n
)
660 if (c
->c_stacklevel
< n
) {
662 "%s:%d: underflow! nexti=%d, level=%d, n=%d\n",
663 c->c_filename, c->c_lineno,
664 c->c_nexti, c->c_stacklevel, n); */
668 c
->c_stacklevel
-= n
;
672 com_done(struct compiling
*c
)
674 if (c
->c_code
!= NULL
)
675 _PyString_Resize(&c
->c_code
, c
->c_nexti
);
676 if (c
->c_lnotab
!= NULL
)
677 _PyString_Resize(&c
->c_lnotab
, c
->c_lnotab_next
);
681 com_addbyte(struct compiling
*c
, int byte
)
684 /*fprintf(stderr, "%3d: %3d\n", c->c_nexti, byte);*/
685 assert(byte
>= 0 && byte
<= 255);
686 if (byte
< 0 || byte
> 255) {
687 com_error(c
, PyExc_SystemError
,
688 "com_addbyte: byte out of range");
690 if (c
->c_code
== NULL
)
692 len
= PyString_Size(c
->c_code
);
693 if (c
->c_nexti
>= len
) {
694 if (_PyString_Resize(&c
->c_code
, len
+1000) != 0) {
699 PyString_AsString(c
->c_code
)[c
->c_nexti
++] = byte
;
703 com_addint(struct compiling
*c
, int x
)
705 com_addbyte(c
, x
& 0xff);
706 com_addbyte(c
, x
>> 8); /* XXX x should be positive */
710 com_add_lnotab(struct compiling
*c
, int addr
, int line
)
714 if (c
->c_lnotab
== NULL
)
716 size
= PyString_Size(c
->c_lnotab
);
717 if (c
->c_lnotab_next
+2 > size
) {
718 if (_PyString_Resize(&c
->c_lnotab
, size
+ 1000) < 0) {
723 p
= PyString_AsString(c
->c_lnotab
) + c
->c_lnotab_next
;
726 c
->c_lnotab_next
+= 2;
730 com_set_lineno(struct compiling
*c
, int lineno
)
732 c
->c_lineno
= lineno
;
733 if (c
->c_firstlineno
== 0) {
734 c
->c_firstlineno
= c
->c_last_line
= lineno
;
737 int incr_addr
= c
->c_nexti
- c
->c_last_addr
;
738 int incr_line
= lineno
- c
->c_last_line
;
739 while (incr_addr
> 255) {
740 com_add_lnotab(c
, 255, 0);
743 while (incr_line
> 255) {
744 com_add_lnotab(c
, incr_addr
, 255);
748 if (incr_addr
> 0 || incr_line
> 0)
749 com_add_lnotab(c
, incr_addr
, incr_line
);
750 c
->c_last_addr
= c
->c_nexti
;
751 c
->c_last_line
= lineno
;
756 com_addoparg(struct compiling
*c
, int op
, int arg
)
758 int extended_arg
= arg
>> 16;
759 if (op
== SET_LINENO
) {
760 com_set_lineno(c
, arg
);
765 com_addbyte(c
, EXTENDED_ARG
);
766 com_addint(c
, extended_arg
);
774 com_addfwref(struct compiling
*c
, int op
, int *p_anchor
)
776 /* Compile a forward reference for backpatching */
783 com_addint(c
, anchor
== 0 ? 0 : here
- anchor
);
787 com_backpatch(struct compiling
*c
, int anchor
)
789 unsigned char *code
= (unsigned char *) PyString_AsString(c
->c_code
);
790 int target
= c
->c_nexti
;
794 /* Make the JUMP instruction at anchor point to target */
795 prev
= code
[anchor
] + (code
[anchor
+1] << 8);
796 dist
= target
- (anchor
+2);
797 code
[anchor
] = dist
& 0xff;
799 code
[anchor
+1] = dist
;
802 com_error(c
, PyExc_SystemError
,
803 "com_backpatch: offset too large");
812 /* Handle literals and names uniformly */
815 com_add(struct compiling
*c
, PyObject
*list
, PyObject
*dict
, PyObject
*v
)
817 PyObject
*w
, *t
, *np
=NULL
;
820 t
= Py_BuildValue("(OO)", v
, v
->ob_type
);
823 w
= PyDict_GetItem(dict
, t
);
827 n
= PyList_Size(list
);
828 np
= PyInt_FromLong(n
);
831 if (PyList_Append(list
, v
) != 0)
833 if (PyDict_SetItem(dict
, t
, np
) != 0)
847 com_addconst(struct compiling
*c
, PyObject
*v
)
849 return com_add(c
, c
->c_consts
, c
->c_const_dict
, v
);
853 com_addname(struct compiling
*c
, PyObject
*v
)
855 return com_add(c
, c
->c_names
, c
->c_name_dict
, v
);
859 mangle(char *p
, char *name
, char *buffer
, size_t maxlen
)
861 /* Name mangling: __private becomes _classname__private.
862 This is independent from how the name is used. */
864 if (p
== NULL
|| name
== NULL
|| name
[0] != '_' || name
[1] != '_')
867 if (nlen
+2 >= maxlen
)
868 return 0; /* Don't mangle __extremely_long_names */
869 if (name
[nlen
-1] == '_' && name
[nlen
-2] == '_')
870 return 0; /* Don't mangle __whatever__ */
871 /* Strip leading underscores from class name */
875 return 0; /* Don't mangle if class is just underscores */
877 if (plen
+ nlen
>= maxlen
)
878 plen
= maxlen
-nlen
-2; /* Truncate class name if too long */
879 /* buffer = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
881 strncpy(buffer
+1, p
, plen
);
882 strcpy(buffer
+1+plen
, name
);
887 com_addop_name(struct compiling
*c
, int op
, char *name
)
891 char buffer
[MANGLE_LEN
];
893 if (mangle(c
->c_private
, name
, buffer
, sizeof(buffer
)))
895 if (name
== NULL
|| (v
= PyString_InternFromString(name
)) == NULL
) {
900 i
= com_addname(c
, v
);
903 com_addoparg(c
, op
, i
);
907 #define NAME_GLOBAL 1
908 #define NAME_DEFAULT 2
909 #define NAME_CLOSURE 3
912 com_lookup_arg(PyObject
*dict
, PyObject
*name
)
914 PyObject
*v
= PyDict_GetItem(dict
, name
);
918 return PyInt_AS_LONG(v
);
922 com_addop_varname(struct compiling
*c
, int kind
, char *name
)
926 int scope
= NAME_DEFAULT
;
928 char buffer
[MANGLE_LEN
];
930 if (mangle(c
->c_private
, name
, buffer
, sizeof(buffer
)))
932 if (name
== NULL
|| (v
= PyString_InternFromString(name
)) == NULL
) {
938 reftype
= get_ref_type(c
, name
);
941 if (c
->c_symtable
->st_cur
->ste_type
== TYPE_FUNCTION
)
944 case GLOBAL_EXPLICIT
:
947 case GLOBAL_IMPLICIT
:
948 if (c
->c_flags
& CO_OPTIMIZED
)
953 scope
= NAME_CLOSURE
;
957 i
= com_addname(c
, v
);
958 if (scope
== NAME_LOCAL
)
959 i
= com_lookup_arg(c
->c_locals
, v
);
960 else if (reftype
== FREE
)
961 i
= com_lookup_arg(c
->c_freevars
, v
);
962 else if (reftype
== CELL
)
963 i
= com_lookup_arg(c
->c_cellvars
, v
);
965 c
->c_errors
++; /* XXX no exception set */
1015 case NAME_CLOSURE
: {
1017 sprintf(buf
, DEL_CLOSURE_ERROR
, name
);
1018 com_error(c
, PyExc_SyntaxError
, buf
);
1026 com_addoparg(c
, op
, i
);
1030 com_addopname(struct compiling
*c
, int op
, node
*n
)
1034 /* XXX it is possible to write this code without the 1000
1035 chars on the total length of dotted names, I just can't be
1036 bothered right now */
1037 if (TYPE(n
) == STAR
)
1039 else if (TYPE(n
) == dotted_name
) {
1043 for (i
= 0; i
< NCH(n
); i
+= 2) {
1044 char *s
= STR(CHILD(n
, i
));
1045 if (p
+ strlen(s
) > buffer
+ (sizeof buffer
) - 2) {
1046 com_error(c
, PyExc_MemoryError
,
1047 "dotted_name too long");
1054 p
= strchr(p
, '\0');
1061 com_addop_name(c
, op
, name
);
1065 parsenumber(struct compiling
*co
, char *s
)
1070 #ifndef WITHOUT_COMPLEX
1076 end
= s
+ strlen(s
) - 1;
1077 #ifndef WITHOUT_COMPLEX
1078 imflag
= *end
== 'j' || *end
== 'J';
1080 if (*end
== 'l' || *end
== 'L')
1081 return PyLong_FromString(s
, (char **)0, 0);
1083 x
= (long) PyOS_strtoul(s
, &end
, 0);
1085 x
= PyOS_strtol(s
, &end
, 0);
1088 com_error(co
, PyExc_OverflowError
,
1089 "integer literal too large");
1092 return PyInt_FromLong(x
);
1094 /* XXX Huge floats may silently fail */
1095 #ifndef WITHOUT_COMPLEX
1098 PyFPE_START_PROTECT("atof", return 0)
1100 PyFPE_END_PROTECT(c
)
1101 return PyComplex_FromCComplex(c
);
1106 PyFPE_START_PROTECT("atof", return 0)
1108 PyFPE_END_PROTECT(dx
)
1109 return PyFloat_FromDouble(dx
);
1126 if (isalpha(quote
) || quote
== '_') {
1127 if (quote
== 'u' || quote
== 'U') {
1131 if (quote
== 'r' || quote
== 'R') {
1136 if (quote
!= '\'' && quote
!= '\"') {
1137 PyErr_BadInternalCall();
1142 if (len
> INT_MAX
) {
1143 PyErr_SetString(PyExc_OverflowError
, "string to parse is too long");
1146 if (s
[--len
] != quote
) {
1147 PyErr_BadInternalCall();
1150 if (len
>= 4 && s
[0] == quote
&& s
[1] == quote
) {
1153 if (s
[--len
] != quote
|| s
[--len
] != quote
) {
1154 PyErr_BadInternalCall();
1158 if (unicode
|| Py_UnicodeFlag
) {
1160 return PyUnicode_DecodeRawUnicodeEscape(
1163 return PyUnicode_DecodeUnicodeEscape(
1166 if (rawmode
|| strchr(s
, '\\') == NULL
)
1167 return PyString_FromStringAndSize(s
, len
);
1168 v
= PyString_FromStringAndSize((char *)NULL
, len
);
1171 p
= buf
= PyString_AsString(v
);
1180 /* XXX This assumes ASCII! */
1182 case '\\': *p
++ = '\\'; break;
1183 case '\'': *p
++ = '\''; break;
1184 case '\"': *p
++ = '\"'; break;
1185 case 'b': *p
++ = '\b'; break;
1186 case 'f': *p
++ = '\014'; break; /* FF */
1187 case 't': *p
++ = '\t'; break;
1188 case 'n': *p
++ = '\n'; break;
1189 case 'r': *p
++ = '\r'; break;
1190 case 'v': *p
++ = '\013'; break; /* VT */
1191 case 'a': *p
++ = '\007'; break; /* BEL, not classic C */
1192 case '0': case '1': case '2': case '3':
1193 case '4': case '5': case '6': case '7':
1195 if ('0' <= *s
&& *s
<= '7') {
1196 c
= (c
<<3) + *s
++ - '0';
1197 if ('0' <= *s
&& *s
<= '7')
1198 c
= (c
<<3) + *s
++ - '0';
1203 if (isxdigit(Py_CHARMASK(s
[0]))
1204 && isxdigit(Py_CHARMASK(s
[1]))) {
1206 c
= Py_CHARMASK(*s
);
1210 else if (islower(c
))
1215 c
= Py_CHARMASK(*s
);
1219 else if (islower(c
))
1226 PyErr_SetString(PyExc_ValueError
,
1227 "invalid \\x escape");
1236 _PyString_Resize(&v
, (int)(p
- buf
));
1241 parsestrplus(node
*n
)
1245 REQ(CHILD(n
, 0), STRING
);
1246 if ((v
= parsestr(STR(CHILD(n
, 0)))) != NULL
) {
1247 /* String literal concatenation */
1248 for (i
= 1; i
< NCH(n
); i
++) {
1250 s
= parsestr(STR(CHILD(n
, i
)));
1253 if (PyString_Check(v
) && PyString_Check(s
)) {
1254 PyString_ConcatAndDel(&v
, s
);
1260 temp
= PyUnicode_Concat(v
, s
);
1277 com_list_for(struct compiling
*c
, node
*n
, node
*e
, char *t
)
1280 int save_begin
= c
->c_begin
;
1282 /* list_iter: for v in expr [list_iter] */
1283 com_node(c
, CHILD(n
, 3)); /* expr */
1284 com_addbyte(c
, GET_ITER
);
1285 c
->c_begin
= c
->c_nexti
;
1286 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
1287 com_addfwref(c
, FOR_ITER
, &anchor
);
1289 com_assign(c
, CHILD(n
, 1), OP_ASSIGN
, NULL
);
1291 com_list_iter(c
, n
, e
, t
);
1293 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
1294 c
->c_begin
= save_begin
;
1295 com_backpatch(c
, anchor
);
1296 com_pop(c
, 1); /* FOR_ITER has popped this */
1300 com_list_if(struct compiling
*c
, node
*n
, node
*e
, char *t
)
1304 /* list_iter: 'if' test [list_iter] */
1305 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
1306 com_node(c
, CHILD(n
, 1));
1307 com_addfwref(c
, JUMP_IF_FALSE
, &a
);
1308 com_addbyte(c
, POP_TOP
);
1310 com_list_iter(c
, n
, e
, t
);
1311 com_addfwref(c
, JUMP_FORWARD
, &anchor
);
1312 com_backpatch(c
, a
);
1313 /* We jump here with an extra entry which we now pop */
1314 com_addbyte(c
, POP_TOP
);
1315 com_backpatch(c
, anchor
);
1319 com_list_iter(struct compiling
*c
,
1320 node
*p
, /* parent of list_iter node */
1321 node
*e
, /* element expression node */
1322 char *t
/* name of result list temp local */)
1324 /* list_iter is the last child in a listmaker, list_for, or list_if */
1325 node
*n
= CHILD(p
, NCH(p
)-1);
1326 if (TYPE(n
) == list_iter
) {
1330 com_list_for(c
, n
, e
, t
);
1333 com_list_if(c
, n
, e
, t
);
1336 com_error(c
, PyExc_SystemError
,
1337 "invalid list_iter node type");
1341 com_addop_varname(c
, VAR_LOAD
, t
);
1344 com_addoparg(c
, CALL_FUNCTION
, 1);
1345 com_addbyte(c
, POP_TOP
);
1351 com_list_comprehension(struct compiling
*c
, node
*n
)
1353 /* listmaker: test list_for */
1355 sprintf(tmpname
, "_[%d]", ++c
->c_tmpname
);
1356 com_addoparg(c
, BUILD_LIST
, 0);
1357 com_addbyte(c
, DUP_TOP
); /* leave the result on the stack */
1359 com_addop_name(c
, LOAD_ATTR
, "append");
1360 com_addop_varname(c
, VAR_STORE
, tmpname
);
1362 com_list_for(c
, CHILD(n
, 1), CHILD(n
, 0), tmpname
);
1363 com_addop_varname(c
, VAR_DELETE
, tmpname
);
1368 com_listmaker(struct compiling
*c
, node
*n
)
1370 /* listmaker: test ( list_for | (',' test)* [','] ) */
1371 if (NCH(n
) > 1 && TYPE(CHILD(n
, 1)) == list_for
)
1372 com_list_comprehension(c
, n
);
1376 for (i
= 0; i
< NCH(n
); i
+= 2, len
++)
1377 com_node(c
, CHILD(n
, i
));
1378 com_addoparg(c
, BUILD_LIST
, len
);
1384 com_dictmaker(struct compiling
*c
, node
*n
)
1387 /* dictmaker: test ':' test (',' test ':' value)* [','] */
1388 for (i
= 0; i
+2 < NCH(n
); i
+= 4) {
1389 /* We must arrange things just right for STORE_SUBSCR.
1390 It wants the stack to look like (value) (dict) (key) */
1391 com_addbyte(c
, DUP_TOP
);
1393 com_node(c
, CHILD(n
, i
+2)); /* value */
1394 com_addbyte(c
, ROT_TWO
);
1395 com_node(c
, CHILD(n
, i
)); /* key */
1396 com_addbyte(c
, STORE_SUBSCR
);
1402 com_atom(struct compiling
*c
, node
*n
)
1411 if (TYPE(CHILD(n
, 1)) == RPAR
) {
1412 com_addoparg(c
, BUILD_TUPLE
, 0);
1416 com_node(c
, CHILD(n
, 1));
1418 case LSQB
: /* '[' [listmaker] ']' */
1419 if (TYPE(CHILD(n
, 1)) == RSQB
) {
1420 com_addoparg(c
, BUILD_LIST
, 0);
1424 com_listmaker(c
, CHILD(n
, 1));
1426 case LBRACE
: /* '{' [dictmaker] '}' */
1427 com_addoparg(c
, BUILD_MAP
, 0);
1429 if (TYPE(CHILD(n
, 1)) == dictmaker
)
1430 com_dictmaker(c
, CHILD(n
, 1));
1433 com_node(c
, CHILD(n
, 1));
1434 com_addbyte(c
, UNARY_CONVERT
);
1437 if ((v
= parsenumber(c
, STR(ch
))) == NULL
) {
1441 i
= com_addconst(c
, v
);
1444 com_addoparg(c
, LOAD_CONST
, i
);
1448 v
= parsestrplus(n
);
1454 i
= com_addconst(c
, v
);
1457 com_addoparg(c
, LOAD_CONST
, i
);
1461 com_addop_varname(c
, VAR_LOAD
, STR(ch
));
1465 com_error(c
, PyExc_SystemError
,
1466 "com_atom: unexpected node type");
1471 com_slice(struct compiling
*c
, node
*n
, int op
)
1476 else if (NCH(n
) == 2) {
1477 if (TYPE(CHILD(n
, 0)) != COLON
) {
1478 com_node(c
, CHILD(n
, 0));
1479 com_addbyte(c
, op
+1);
1482 com_node(c
, CHILD(n
, 1));
1483 com_addbyte(c
, op
+2);
1488 com_node(c
, CHILD(n
, 0));
1489 com_node(c
, CHILD(n
, 2));
1490 com_addbyte(c
, op
+3);
1496 com_augassign_slice(struct compiling
*c
, node
*n
, int opcode
, node
*augn
)
1499 com_addbyte(c
, DUP_TOP
);
1501 com_addbyte(c
, SLICE
);
1503 com_addbyte(c
, opcode
);
1505 com_addbyte(c
, ROT_TWO
);
1506 com_addbyte(c
, STORE_SLICE
);
1508 } else if (NCH(n
) == 2 && TYPE(CHILD(n
, 0)) != COLON
) {
1509 com_node(c
, CHILD(n
, 0));
1510 com_addoparg(c
, DUP_TOPX
, 2);
1512 com_addbyte(c
, SLICE
+1);
1515 com_addbyte(c
, opcode
);
1517 com_addbyte(c
, ROT_THREE
);
1518 com_addbyte(c
, STORE_SLICE
+1);
1520 } else if (NCH(n
) == 2) {
1521 com_node(c
, CHILD(n
, 1));
1522 com_addoparg(c
, DUP_TOPX
, 2);
1524 com_addbyte(c
, SLICE
+2);
1527 com_addbyte(c
, opcode
);
1529 com_addbyte(c
, ROT_THREE
);
1530 com_addbyte(c
, STORE_SLICE
+2);
1533 com_node(c
, CHILD(n
, 0));
1534 com_node(c
, CHILD(n
, 2));
1535 com_addoparg(c
, DUP_TOPX
, 3);
1537 com_addbyte(c
, SLICE
+3);
1540 com_addbyte(c
, opcode
);
1542 com_addbyte(c
, ROT_FOUR
);
1543 com_addbyte(c
, STORE_SLICE
+3);
1549 com_argument(struct compiling
*c
, node
*n
, PyObject
**pkeywords
)
1552 REQ(n
, argument
); /* [test '='] test; really [keyword '='] test */
1554 if (*pkeywords
!= NULL
) {
1555 com_error(c
, PyExc_SyntaxError
,
1556 "non-keyword arg after keyword arg");
1559 com_node(c
, CHILD(n
, 0));
1566 } while (NCH(m
) == 1);
1567 if (TYPE(m
) != NAME
) {
1568 /* f(lambda x: x[0] = 3) ends up getting parsed with
1569 * LHS test = lambda x: x[0], and RHS test = 3.
1570 * SF bug 132313 points out that complaining about a keyword
1571 * then is very confusing.
1573 com_error(c
, PyExc_SyntaxError
,
1574 TYPE(m
) == lambdef
?
1575 "lambda cannot contain assignment" :
1576 "keyword can't be an expression");
1579 PyObject
*v
= PyString_InternFromString(STR(m
));
1580 if (v
!= NULL
&& *pkeywords
== NULL
)
1581 *pkeywords
= PyDict_New();
1584 else if (*pkeywords
== NULL
) {
1588 if (PyDict_GetItem(*pkeywords
, v
) != NULL
)
1589 com_error(c
, PyExc_SyntaxError
,
1590 "duplicate keyword argument");
1592 if (PyDict_SetItem(*pkeywords
, v
, v
) != 0)
1594 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, v
));
1599 com_node(c
, CHILD(n
, 2));
1603 com_call_function(struct compiling
*c
, node
*n
)
1605 if (TYPE(n
) == RPAR
) {
1606 com_addoparg(c
, CALL_FUNCTION
, 0);
1609 PyObject
*keywords
= NULL
;
1611 int lineno
= n
->n_lineno
;
1613 int starstar_flag
= 0;
1618 for (i
= 0; i
< NCH(n
); i
+= 2) {
1619 node
*ch
= CHILD(n
, i
);
1620 if (TYPE(ch
) == STAR
||
1621 TYPE(ch
) == DOUBLESTAR
)
1623 if (ch
->n_lineno
!= lineno
) {
1624 lineno
= ch
->n_lineno
;
1625 com_addoparg(c
, SET_LINENO
, lineno
);
1627 com_argument(c
, ch
, &keywords
);
1628 if (keywords
== NULL
)
1633 Py_XDECREF(keywords
);
1634 while (i
< NCH(n
)) {
1635 node
*tok
= CHILD(n
, i
);
1636 node
*ch
= CHILD(n
, i
+1);
1638 switch (TYPE(tok
)) {
1639 case STAR
: star_flag
= 1; break;
1640 case DOUBLESTAR
: starstar_flag
= 1; break;
1644 if (na
> 255 || nk
> 255) {
1645 com_error(c
, PyExc_SyntaxError
,
1646 "more than 255 arguments");
1648 if (star_flag
|| starstar_flag
)
1649 opcode
= CALL_FUNCTION_VAR
- 1 +
1650 star_flag
+ (starstar_flag
<< 1);
1652 opcode
= CALL_FUNCTION
;
1653 com_addoparg(c
, opcode
, na
| (nk
<< 8));
1654 com_pop(c
, na
+ 2*nk
+ star_flag
+ starstar_flag
);
1659 com_select_member(struct compiling
*c
, node
*n
)
1661 com_addopname(c
, LOAD_ATTR
, n
);
1665 com_sliceobj(struct compiling
*c
, node
*n
)
1668 int ns
=2; /* number of slice arguments */
1671 /* first argument */
1672 if (TYPE(CHILD(n
,i
)) == COLON
) {
1673 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1678 com_node(c
, CHILD(n
,i
));
1680 REQ(CHILD(n
,i
),COLON
);
1683 /* second argument */
1684 if (i
< NCH(n
) && TYPE(CHILD(n
,i
)) == test
) {
1685 com_node(c
, CHILD(n
,i
));
1689 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1692 /* remaining arguments */
1693 for (; i
< NCH(n
); i
++) {
1698 /* right argument of ':' missing */
1699 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1703 com_node(c
, CHILD(ch
,1));
1705 com_addoparg(c
, BUILD_SLICE
, ns
);
1706 com_pop(c
, 1 + (ns
== 3));
1710 com_subscript(struct compiling
*c
, node
*n
)
1715 /* check for rubber index */
1716 if (TYPE(ch
) == DOT
&& TYPE(CHILD(n
,1)) == DOT
) {
1717 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_Ellipsis
));
1721 /* check for slice */
1722 if ((TYPE(ch
) == COLON
|| NCH(n
) > 1))
1732 com_subscriptlist(struct compiling
*c
, node
*n
, int assigning
, node
*augn
)
1735 REQ(n
, subscriptlist
);
1736 /* Check to make backward compatible slice behavior for '[i:j]' */
1738 node
*sub
= CHILD(n
, 0); /* subscript */
1739 /* 'Basic' slice, should have exactly one colon. */
1740 if ((TYPE(CHILD(sub
, 0)) == COLON
1741 || (NCH(sub
) > 1 && TYPE(CHILD(sub
, 1)) == COLON
))
1742 && (TYPE(CHILD(sub
,NCH(sub
)-1)) != sliceop
))
1744 switch (assigning
) {
1755 com_augassign_slice(c
, sub
, assigning
, augn
);
1758 com_slice(c
, sub
, op
);
1759 if (op
== STORE_SLICE
)
1761 else if (op
== DELETE_SLICE
)
1766 /* Else normal subscriptlist. Compile each subscript. */
1767 for (i
= 0; i
< NCH(n
); i
+= 2)
1768 com_subscript(c
, CHILD(n
, i
));
1769 /* Put multiple subscripts into a tuple */
1772 com_addoparg(c
, BUILD_TUPLE
, i
);
1775 switch (assigning
) {
1790 if (assigning
> OP_APPLY
) {
1791 com_addoparg(c
, DUP_TOPX
, 2);
1793 com_addbyte(c
, BINARY_SUBSCR
);
1796 com_addbyte(c
, assigning
);
1798 com_addbyte(c
, ROT_THREE
);
1805 com_apply_trailer(struct compiling
*c
, node
*n
)
1808 switch (TYPE(CHILD(n
, 0))) {
1810 com_call_function(c
, CHILD(n
, 1));
1813 com_select_member(c
, CHILD(n
, 1));
1816 com_subscriptlist(c
, CHILD(n
, 1), OP_APPLY
, NULL
);
1819 com_error(c
, PyExc_SystemError
,
1820 "com_apply_trailer: unknown trailer type");
1825 com_power(struct compiling
*c
, node
*n
)
1829 com_atom(c
, CHILD(n
, 0));
1830 for (i
= 1; i
< NCH(n
); i
++) {
1831 if (TYPE(CHILD(n
, i
)) == DOUBLESTAR
) {
1832 com_factor(c
, CHILD(n
, i
+1));
1833 com_addbyte(c
, BINARY_POWER
);
1838 com_apply_trailer(c
, CHILD(n
, i
));
1843 com_factor(struct compiling
*c
, node
*n
)
1846 if (TYPE(CHILD(n
, 0)) == PLUS
) {
1847 com_factor(c
, CHILD(n
, 1));
1848 com_addbyte(c
, UNARY_POSITIVE
);
1850 else if (TYPE(CHILD(n
, 0)) == MINUS
) {
1851 com_factor(c
, CHILD(n
, 1));
1852 com_addbyte(c
, UNARY_NEGATIVE
);
1854 else if (TYPE(CHILD(n
, 0)) == TILDE
) {
1855 com_factor(c
, CHILD(n
, 1));
1856 com_addbyte(c
, UNARY_INVERT
);
1859 com_power(c
, CHILD(n
, 0));
1864 com_term(struct compiling
*c
, node
*n
)
1869 com_factor(c
, CHILD(n
, 0));
1870 for (i
= 2; i
< NCH(n
); i
+= 2) {
1871 com_factor(c
, CHILD(n
, i
));
1872 switch (TYPE(CHILD(n
, i
-1))) {
1874 op
= BINARY_MULTIPLY
;
1877 if (c
->c_flags
& CO_FUTURE_DIVISION
)
1878 op
= BINARY_TRUE_DIVIDE
;
1886 op
= BINARY_FLOOR_DIVIDE
;
1889 com_error(c
, PyExc_SystemError
,
1890 "com_term: operator not *, /, // or %");
1899 com_arith_expr(struct compiling
*c
, node
*n
)
1904 com_term(c
, CHILD(n
, 0));
1905 for (i
= 2; i
< NCH(n
); i
+= 2) {
1906 com_term(c
, CHILD(n
, i
));
1907 switch (TYPE(CHILD(n
, i
-1))) {
1912 op
= BINARY_SUBTRACT
;
1915 com_error(c
, PyExc_SystemError
,
1916 "com_arith_expr: operator not + or -");
1925 com_shift_expr(struct compiling
*c
, node
*n
)
1930 com_arith_expr(c
, CHILD(n
, 0));
1931 for (i
= 2; i
< NCH(n
); i
+= 2) {
1932 com_arith_expr(c
, CHILD(n
, i
));
1933 switch (TYPE(CHILD(n
, i
-1))) {
1941 com_error(c
, PyExc_SystemError
,
1942 "com_shift_expr: operator not << or >>");
1951 com_and_expr(struct compiling
*c
, node
*n
)
1956 com_shift_expr(c
, CHILD(n
, 0));
1957 for (i
= 2; i
< NCH(n
); i
+= 2) {
1958 com_shift_expr(c
, CHILD(n
, i
));
1959 if (TYPE(CHILD(n
, i
-1)) == AMPER
) {
1963 com_error(c
, PyExc_SystemError
,
1964 "com_and_expr: operator not &");
1973 com_xor_expr(struct compiling
*c
, node
*n
)
1978 com_and_expr(c
, CHILD(n
, 0));
1979 for (i
= 2; i
< NCH(n
); i
+= 2) {
1980 com_and_expr(c
, CHILD(n
, i
));
1981 if (TYPE(CHILD(n
, i
-1)) == CIRCUMFLEX
) {
1985 com_error(c
, PyExc_SystemError
,
1986 "com_xor_expr: operator not ^");
1995 com_expr(struct compiling
*c
, node
*n
)
2000 com_xor_expr(c
, CHILD(n
, 0));
2001 for (i
= 2; i
< NCH(n
); i
+= 2) {
2002 com_xor_expr(c
, CHILD(n
, i
));
2003 if (TYPE(CHILD(n
, i
-1)) == VBAR
) {
2007 com_error(c
, PyExc_SystemError
,
2008 "com_expr: expr operator not |");
2020 /* comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '=='
2021 | 'in' | 'not' 'in' | 'is' | 'is' not' */
2025 case LESS
: return LT
;
2026 case GREATER
: return GT
;
2027 case EQEQUAL
: /* == */
2028 case EQUAL
: return EQ
;
2029 case LESSEQUAL
: return LE
;
2030 case GREATEREQUAL
: return GE
;
2031 case NOTEQUAL
: return NE
; /* <> or != */
2032 case NAME
: if (strcmp(STR(n
), "in") == 0) return IN
;
2033 if (strcmp(STR(n
), "is") == 0) return IS
;
2036 else if (NCH(n
) == 2) {
2037 switch (TYPE(CHILD(n
, 0))) {
2038 case NAME
: if (strcmp(STR(CHILD(n
, 1)), "in") == 0)
2040 if (strcmp(STR(CHILD(n
, 0)), "is") == 0)
2048 com_comparison(struct compiling
*c
, node
*n
)
2053 REQ(n
, comparison
); /* comparison: expr (comp_op expr)* */
2054 com_expr(c
, CHILD(n
, 0));
2058 /****************************************************************
2059 The following code is generated for all but the last
2060 comparison in a chain:
2062 label: on stack: opcode: jump to:
2068 b, 0-or-1 JUMP_IF_FALSE L1
2072 We are now ready to repeat this sequence for the next
2073 comparison in the chain.
2075 For the last we generate:
2081 If there were any jumps to L1 (i.e., there was more than one
2082 comparison), we generate:
2084 0-or-1 JUMP_FORWARD L2
2089 ****************************************************************/
2093 for (i
= 2; i
< NCH(n
); i
+= 2) {
2094 com_expr(c
, CHILD(n
, i
));
2096 com_addbyte(c
, DUP_TOP
);
2098 com_addbyte(c
, ROT_THREE
);
2100 op
= cmp_type(CHILD(n
, i
-1));
2102 com_error(c
, PyExc_SystemError
,
2103 "com_comparison: unknown comparison op");
2105 com_addoparg(c
, COMPARE_OP
, op
);
2108 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
2109 com_addbyte(c
, POP_TOP
);
2116 com_addfwref(c
, JUMP_FORWARD
, &anchor2
);
2117 com_backpatch(c
, anchor
);
2118 com_addbyte(c
, ROT_TWO
);
2119 com_addbyte(c
, POP_TOP
);
2120 com_backpatch(c
, anchor2
);
2125 com_not_test(struct compiling
*c
, node
*n
)
2127 REQ(n
, not_test
); /* 'not' not_test | comparison */
2129 com_comparison(c
, CHILD(n
, 0));
2132 com_not_test(c
, CHILD(n
, 1));
2133 com_addbyte(c
, UNARY_NOT
);
2138 com_and_test(struct compiling
*c
, node
*n
)
2142 REQ(n
, and_test
); /* not_test ('and' not_test)* */
2146 com_not_test(c
, CHILD(n
, i
));
2147 if ((i
+= 2) >= NCH(n
))
2149 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
2150 com_addbyte(c
, POP_TOP
);
2154 com_backpatch(c
, anchor
);
2158 com_make_closure(struct compiling
*c
, PyCodeObject
*co
)
2160 int i
, free
= PyTuple_GET_SIZE(co
->co_freevars
);
2163 for (i
= 0; i
< free
; ++i
) {
2164 /* Bypass com_addop_varname because it will generate
2165 LOAD_DEREF but LOAD_CLOSURE is needed.
2167 PyObject
*name
= PyTuple_GET_ITEM(co
->co_freevars
, i
);
2170 /* Special case: If a class contains a method with a
2171 free variable that has the same name as a method,
2172 the name will be considered free *and* local in the
2173 class. It should be handled by the closure, as
2174 well as by the normal name loookup logic.
2176 reftype
= get_ref_type(c
, PyString_AS_STRING(name
));
2177 if (reftype
== CELL
)
2178 arg
= com_lookup_arg(c
->c_cellvars
, name
);
2179 else /* (reftype == FREE) */
2180 arg
= com_lookup_arg(c
->c_freevars
, name
);
2182 fprintf(stderr
, "lookup %s in %s %d %d\n"
2183 "freevars of %s: %s\n",
2184 PyObject_REPR(name
),
2187 PyString_AS_STRING(co
->co_name
),
2188 PyObject_REPR(co
->co_freevars
));
2189 Py_FatalError("com_make_closure()");
2191 com_addoparg(c
, LOAD_CLOSURE
, arg
);
2199 com_test(struct compiling
*c
, node
*n
)
2201 REQ(n
, test
); /* and_test ('or' and_test)* | lambdef */
2202 if (NCH(n
) == 1 && TYPE(CHILD(n
, 0)) == lambdef
) {
2205 int ndefs
= com_argdefs(c
, CHILD(n
, 0));
2206 symtable_enter_scope(c
->c_symtable
, "lambda", lambdef
,
2208 co
= (PyObject
*) icompile(CHILD(n
, 0), c
);
2213 symtable_exit_scope(c
->c_symtable
);
2214 i
= com_addconst(c
, co
);
2215 closure
= com_make_closure(c
, (PyCodeObject
*)co
);
2217 com_addoparg(c
, LOAD_CONST
, i
);
2220 com_addoparg(c
, MAKE_CLOSURE
, ndefs
);
2222 com_addoparg(c
, MAKE_FUNCTION
, ndefs
);
2229 com_and_test(c
, CHILD(n
, i
));
2230 if ((i
+= 2) >= NCH(n
))
2232 com_addfwref(c
, JUMP_IF_TRUE
, &anchor
);
2233 com_addbyte(c
, POP_TOP
);
2237 com_backpatch(c
, anchor
);
2242 com_list(struct compiling
*c
, node
*n
, int toplevel
)
2244 /* exprlist: expr (',' expr)* [',']; likewise for testlist */
2245 if (NCH(n
) == 1 && !toplevel
) {
2246 com_node(c
, CHILD(n
, 0));
2251 len
= (NCH(n
) + 1) / 2;
2252 for (i
= 0; i
< NCH(n
); i
+= 2)
2253 com_node(c
, CHILD(n
, i
));
2254 com_addoparg(c
, BUILD_TUPLE
, len
);
2260 /* Begin of assignment compilation */
2264 com_augassign_attr(struct compiling
*c
, node
*n
, int opcode
, node
*augn
)
2266 com_addbyte(c
, DUP_TOP
);
2268 com_addopname(c
, LOAD_ATTR
, n
);
2270 com_addbyte(c
, opcode
);
2272 com_addbyte(c
, ROT_TWO
);
2273 com_addopname(c
, STORE_ATTR
, n
);
2278 com_assign_attr(struct compiling
*c
, node
*n
, int assigning
)
2280 com_addopname(c
, assigning
? STORE_ATTR
: DELETE_ATTR
, n
);
2281 com_pop(c
, assigning
? 2 : 1);
2285 com_assign_trailer(struct compiling
*c
, node
*n
, int assigning
, node
*augn
)
2288 switch (TYPE(CHILD(n
, 0))) {
2289 case LPAR
: /* '(' [exprlist] ')' */
2290 com_error(c
, PyExc_SyntaxError
,
2291 "can't assign to function call");
2293 case DOT
: /* '.' NAME */
2294 if (assigning
> OP_APPLY
)
2295 com_augassign_attr(c
, CHILD(n
, 1), assigning
, augn
);
2297 com_assign_attr(c
, CHILD(n
, 1), assigning
);
2299 case LSQB
: /* '[' subscriptlist ']' */
2300 com_subscriptlist(c
, CHILD(n
, 1), assigning
, augn
);
2303 com_error(c
, PyExc_SystemError
, "unknown trailer type");
2308 com_assign_sequence(struct compiling
*c
, node
*n
, int assigning
)
2311 if (TYPE(n
) != testlist
&& TYPE(n
) != listmaker
)
2315 com_addoparg(c
, UNPACK_SEQUENCE
, i
);
2318 for (i
= 0; i
< NCH(n
); i
+= 2)
2319 com_assign(c
, CHILD(n
, i
), assigning
, NULL
);
2323 com_augassign_name(struct compiling
*c
, node
*n
, int opcode
, node
*augn
)
2326 com_addop_varname(c
, VAR_LOAD
, STR(n
));
2329 com_addbyte(c
, opcode
);
2331 com_assign_name(c
, n
, OP_ASSIGN
);
2335 com_assign_name(struct compiling
*c
, node
*n
, int assigning
)
2338 com_addop_varname(c
, assigning
? VAR_STORE
: VAR_DELETE
, STR(n
));
2344 com_assign(struct compiling
*c
, node
*n
, int assigning
, node
*augn
)
2346 /* Loop to avoid trivial recursion */
2353 if (assigning
> OP_APPLY
) {
2354 com_error(c
, PyExc_SyntaxError
,
2355 "augmented assign to tuple not possible");
2358 com_assign_sequence(c
, n
, assigning
);
2376 com_error(c
, PyExc_SyntaxError
,
2377 "can't assign to operator");
2383 case power
: /* atom trailer* ('**' power)*
2384 ('+'|'-'|'~') factor | atom trailer* */
2385 if (TYPE(CHILD(n
, 0)) != atom
) {
2386 com_error(c
, PyExc_SyntaxError
,
2387 "can't assign to operator");
2390 if (NCH(n
) > 1) { /* trailer or exponent present */
2392 com_node(c
, CHILD(n
, 0));
2393 for (i
= 1; i
+1 < NCH(n
); i
++) {
2394 if (TYPE(CHILD(n
, i
)) == DOUBLESTAR
) {
2395 com_error(c
, PyExc_SyntaxError
,
2396 "can't assign to operator");
2399 com_apply_trailer(c
, CHILD(n
, i
));
2400 } /* NB i is still alive */
2401 com_assign_trailer(c
,
2402 CHILD(n
, i
), assigning
, augn
);
2409 switch (TYPE(CHILD(n
, 0))) {
2412 if (TYPE(n
) == RPAR
) {
2413 /* XXX Should allow () = () ??? */
2414 com_error(c
, PyExc_SyntaxError
,
2415 "can't assign to ()");
2418 if (assigning
> OP_APPLY
) {
2419 com_error(c
, PyExc_SyntaxError
,
2420 "augmented assign to tuple not possible");
2426 if (TYPE(n
) == RSQB
) {
2427 com_error(c
, PyExc_SyntaxError
,
2428 "can't assign to []");
2431 if (assigning
> OP_APPLY
) {
2432 com_error(c
, PyExc_SyntaxError
,
2433 "augmented assign to list not possible");
2437 && TYPE(CHILD(n
, 1)) == list_for
) {
2438 com_error(c
, PyExc_SyntaxError
,
2439 "can't assign to list comprehension");
2442 com_assign_sequence(c
, n
, assigning
);
2445 if (assigning
> OP_APPLY
)
2446 com_augassign_name(c
, CHILD(n
, 0),
2449 com_assign_name(c
, CHILD(n
, 0),
2453 com_error(c
, PyExc_SyntaxError
,
2454 "can't assign to literal");
2460 com_error(c
, PyExc_SyntaxError
,
2461 "can't assign to lambda");
2465 com_error(c
, PyExc_SystemError
,
2466 "com_assign: bad node");
2474 com_augassign(struct compiling
*c
, node
*n
)
2478 switch (STR(CHILD(CHILD(n
, 1), 0))[0]) {
2479 case '+': opcode
= INPLACE_ADD
; break;
2480 case '-': opcode
= INPLACE_SUBTRACT
; break;
2482 if (STR(CHILD(CHILD(n
, 1), 0))[1] == '/')
2483 opcode
= INPLACE_FLOOR_DIVIDE
;
2484 else if (c
->c_flags
& CO_FUTURE_DIVISION
)
2485 opcode
= INPLACE_TRUE_DIVIDE
;
2487 opcode
= INPLACE_DIVIDE
;
2489 case '%': opcode
= INPLACE_MODULO
; break;
2490 case '<': opcode
= INPLACE_LSHIFT
; break;
2491 case '>': opcode
= INPLACE_RSHIFT
; break;
2492 case '&': opcode
= INPLACE_AND
; break;
2493 case '^': opcode
= INPLACE_XOR
; break;
2494 case '|': opcode
= INPLACE_OR
; break;
2496 if (STR(CHILD(CHILD(n
, 1), 0))[1] == '*')
2497 opcode
= INPLACE_POWER
;
2499 opcode
= INPLACE_MULTIPLY
;
2502 com_error(c
, PyExc_SystemError
, "com_augassign: bad operator");
2505 com_assign(c
, CHILD(n
, 0), opcode
, CHILD(n
, 2));
2509 com_expr_stmt(struct compiling
*c
, node
*n
)
2512 /* testlist (('=' testlist)* | augassign testlist) */
2513 /* Forget it if we have just a doc string here */
2514 if (!c
->c_interactive
&& NCH(n
) == 1 && get_rawdocstring(n
) != NULL
)
2517 com_node(c
, CHILD(n
, NCH(n
)-1));
2518 if (c
->c_interactive
)
2519 com_addbyte(c
, PRINT_EXPR
);
2521 com_addbyte(c
, POP_TOP
);
2524 else if (TYPE(CHILD(n
,1)) == augassign
)
2525 com_augassign(c
, n
);
2528 com_node(c
, CHILD(n
, NCH(n
)-1));
2529 for (i
= 0; i
< NCH(n
)-2; i
+=2) {
2530 if (i
+2 < NCH(n
)-2) {
2531 com_addbyte(c
, DUP_TOP
);
2534 com_assign(c
, CHILD(n
, i
), OP_ASSIGN
, NULL
);
2540 com_assert_stmt(struct compiling
*c
, node
*n
)
2544 REQ(n
, assert_stmt
); /* 'assert' test [',' test] */
2545 /* Generate code like for
2549 raise AssertionError [, <message>]
2551 where <message> is the second test, if present.
2554 if (Py_OptimizeFlag
)
2556 com_addop_name(c
, LOAD_GLOBAL
, "__debug__");
2558 com_addfwref(c
, JUMP_IF_FALSE
, &a
);
2559 com_addbyte(c
, POP_TOP
);
2561 com_node(c
, CHILD(n
, 1));
2562 com_addfwref(c
, JUMP_IF_TRUE
, &b
);
2563 com_addbyte(c
, POP_TOP
);
2565 /* Raise that exception! */
2566 com_addop_name(c
, LOAD_GLOBAL
, "AssertionError");
2568 i
= NCH(n
)/2; /* Either 2 or 4 */
2570 com_node(c
, CHILD(n
, 3));
2571 com_addoparg(c
, RAISE_VARARGS
, i
);
2573 /* The interpreter does not fall through */
2574 /* All jumps converge here */
2575 com_backpatch(c
, a
);
2576 com_backpatch(c
, b
);
2577 com_addbyte(c
, POP_TOP
);
2581 com_print_stmt(struct compiling
*c
, node
*n
)
2584 node
* stream
= NULL
;
2586 REQ(n
, print_stmt
); /* 'print' (test ',')* [test] */
2588 /* are we using the extended print form? */
2589 if (NCH(n
) >= 2 && TYPE(CHILD(n
, 1)) == RIGHTSHIFT
) {
2590 stream
= CHILD(n
, 2);
2591 com_node(c
, stream
);
2592 /* stack: [...] => [... stream] */
2594 if (NCH(n
) > 3 && TYPE(CHILD(n
, 3)) == COMMA
)
2599 for (; i
< NCH(n
); i
+= 2) {
2600 if (stream
!= NULL
) {
2601 com_addbyte(c
, DUP_TOP
);
2602 /* stack: [stream] => [stream stream] */
2604 com_node(c
, CHILD(n
, i
));
2605 /* stack: [stream stream] => [stream stream obj] */
2606 com_addbyte(c
, ROT_TWO
);
2607 /* stack: [stream stream obj] => [stream obj stream] */
2608 com_addbyte(c
, PRINT_ITEM_TO
);
2609 /* stack: [stream obj stream] => [stream] */
2613 com_node(c
, CHILD(n
, i
));
2614 /* stack: [...] => [... obj] */
2615 com_addbyte(c
, PRINT_ITEM
);
2619 /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */
2620 if (TYPE(CHILD(n
, NCH(n
)-1)) == COMMA
) {
2621 if (stream
!= NULL
) {
2622 /* must pop the extra stream object off the stack */
2623 com_addbyte(c
, POP_TOP
);
2624 /* stack: [... stream] => [...] */
2629 if (stream
!= NULL
) {
2630 /* this consumes the last stream object on stack */
2631 com_addbyte(c
, PRINT_NEWLINE_TO
);
2632 /* stack: [... stream] => [...] */
2636 com_addbyte(c
, PRINT_NEWLINE
);
2641 com_return_stmt(struct compiling
*c
, node
*n
)
2643 REQ(n
, return_stmt
); /* 'return' [testlist] */
2644 if (!c
->c_infunction
) {
2645 com_error(c
, PyExc_SyntaxError
, "'return' outside function");
2647 if (c
->c_flags
& CO_GENERATOR
) {
2649 com_error(c
, PyExc_SyntaxError
,
2650 "'return' with argument inside generator");
2654 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
2658 com_node(c
, CHILD(n
, 1));
2659 com_addbyte(c
, RETURN_VALUE
);
2664 com_yield_stmt(struct compiling
*c
, node
*n
)
2667 REQ(n
, yield_stmt
); /* 'yield' testlist */
2668 if (!c
->c_infunction
) {
2669 com_error(c
, PyExc_SyntaxError
, "'yield' outside function");
2672 for (i
= 0; i
< c
->c_nblocks
; ++i
) {
2673 if (c
->c_block
[i
] == SETUP_FINALLY
) {
2674 com_error(c
, PyExc_SyntaxError
,
2675 "'yield' not allowed in a 'try' block "
2676 "with a 'finally' clause");
2680 com_node(c
, CHILD(n
, 1));
2681 com_addbyte(c
, YIELD_VALUE
);
2686 com_raise_stmt(struct compiling
*c
, node
*n
)
2689 REQ(n
, raise_stmt
); /* 'raise' [test [',' test [',' test]]] */
2691 com_node(c
, CHILD(n
, 1));
2693 com_node(c
, CHILD(n
, 3));
2695 com_node(c
, CHILD(n
, 5));
2699 com_addoparg(c
, RAISE_VARARGS
, i
);
2704 com_from_import(struct compiling
*c
, node
*n
)
2706 com_addopname(c
, IMPORT_FROM
, CHILD(n
, 0));
2709 if (strcmp(STR(CHILD(n
, 1)), "as") != 0) {
2710 com_error(c
, PyExc_SyntaxError
, "invalid syntax");
2713 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 2)));
2715 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 0)));
2720 com_import_stmt(struct compiling
*c
, node
*n
)
2723 REQ(n
, import_stmt
);
2724 /* 'import' dotted_name (',' dotted_name)* |
2725 'from' dotted_name 'import' ('*' | NAME (',' NAME)*) */
2726 if (STR(CHILD(n
, 0))[0] == 'f') {
2728 /* 'from' dotted_name 'import' ... */
2729 REQ(CHILD(n
, 1), dotted_name
);
2731 if (TYPE(CHILD(n
, 3)) == STAR
) {
2732 tup
= Py_BuildValue("(s)", "*");
2734 tup
= PyTuple_New((NCH(n
) - 2)/2);
2735 for (i
= 3; i
< NCH(n
); i
+= 2) {
2736 PyTuple_SET_ITEM(tup
, (i
-3)/2,
2737 PyString_FromString(STR(
2738 CHILD(CHILD(n
, i
), 0))));
2741 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, tup
));
2744 com_addopname(c
, IMPORT_NAME
, CHILD(n
, 1));
2745 if (TYPE(CHILD(n
, 3)) == STAR
)
2746 com_addbyte(c
, IMPORT_STAR
);
2748 for (i
= 3; i
< NCH(n
); i
+= 2)
2749 com_from_import(c
, CHILD(n
, i
));
2750 com_addbyte(c
, POP_TOP
);
2756 for (i
= 1; i
< NCH(n
); i
+= 2) {
2757 node
*subn
= CHILD(n
, i
);
2758 REQ(subn
, dotted_as_name
);
2759 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
2761 com_addopname(c
, IMPORT_NAME
, CHILD(subn
, 0));
2762 if (NCH(subn
) > 1) {
2764 if (strcmp(STR(CHILD(subn
, 1)), "as") != 0) {
2765 com_error(c
, PyExc_SyntaxError
,
2769 for (j
=2 ; j
< NCH(CHILD(subn
, 0)); j
+= 2)
2770 com_addopname(c
, LOAD_ATTR
,
2771 CHILD(CHILD(subn
, 0),
2773 com_addop_varname(c
, VAR_STORE
,
2774 STR(CHILD(subn
, 2)));
2776 com_addop_varname(c
, VAR_STORE
,
2777 STR(CHILD(CHILD(subn
, 0),
2785 com_exec_stmt(struct compiling
*c
, node
*n
)
2788 /* exec_stmt: 'exec' expr ['in' expr [',' expr]] */
2789 com_node(c
, CHILD(n
, 1));
2791 com_node(c
, CHILD(n
, 3));
2793 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
2797 com_node(c
, CHILD(n
, 5));
2799 com_addbyte(c
, DUP_TOP
);
2802 com_addbyte(c
, EXEC_STMT
);
2807 is_constant_false(struct compiling
*c
, node
*n
)
2811 /* argument c will be NULL when called from symtable_node() */
2813 /* Label to avoid tail recursion */
2824 for (i
= 0; i
< NCH(n
); i
++) {
2825 node
*ch
= CHILD(n
, i
);
2826 if (TYPE(ch
) == stmt
) {
2861 if (Py_OptimizeFlag
&& strcmp(STR(n
), "__debug__") == 0)
2866 v
= parsenumber(c
, STR(n
));
2871 i
= PyObject_IsTrue(v
);
2876 v
= parsestr(STR(n
));
2881 i
= PyObject_IsTrue(v
);
2890 /* Look under n for a return stmt with an expression.
2891 * This hack is used to find illegal returns under "if 0:" blocks in
2892 * functions already known to be generators (as determined by the symtable
2894 * Return the offending return node if found, else NULL.
2897 look_for_offending_return(node
*n
)
2901 for (i
= 0; i
< NCH(n
); ++i
) {
2902 node
*kid
= CHILD(n
, i
);
2904 switch (TYPE(kid
)) {
2908 /* Stuff in nested functions & classes doesn't
2909 affect the code block we started in. */
2918 node
*bad
= look_for_offending_return(kid
);
2929 com_if_stmt(struct compiling
*c
, node
*n
)
2934 /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */
2935 for (i
= 0; i
+3 < NCH(n
); i
+=4) {
2937 node
*ch
= CHILD(n
, i
+1);
2938 if (is_constant_false(c
, ch
)) {
2939 /* We're going to skip this block. However, if this
2940 is a generator, we have to check the dead code
2941 anyway to make sure there aren't any return stmts
2942 with expressions, in the same scope. */
2943 if (c
->c_flags
& CO_GENERATOR
) {
2944 node
*p
= look_for_offending_return(n
);
2946 int savelineno
= c
->c_lineno
;
2947 c
->c_lineno
= p
->n_lineno
;
2948 com_error(c
, PyExc_SyntaxError
,
2949 "'return' with argument "
2950 "inside generator");
2951 c
->c_lineno
= savelineno
;
2957 com_addoparg(c
, SET_LINENO
, ch
->n_lineno
);
2959 com_addfwref(c
, JUMP_IF_FALSE
, &a
);
2960 com_addbyte(c
, POP_TOP
);
2962 com_node(c
, CHILD(n
, i
+3));
2963 com_addfwref(c
, JUMP_FORWARD
, &anchor
);
2964 com_backpatch(c
, a
);
2965 /* We jump here with an extra entry which we now pop */
2966 com_addbyte(c
, POP_TOP
);
2969 com_node(c
, CHILD(n
, i
+2));
2971 com_backpatch(c
, anchor
);
2975 com_while_stmt(struct compiling
*c
, node
*n
)
2977 int break_anchor
= 0;
2979 int save_begin
= c
->c_begin
;
2980 REQ(n
, while_stmt
); /* 'while' test ':' suite ['else' ':' suite] */
2981 com_addfwref(c
, SETUP_LOOP
, &break_anchor
);
2982 block_push(c
, SETUP_LOOP
);
2983 c
->c_begin
= c
->c_nexti
;
2984 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
2985 com_node(c
, CHILD(n
, 1));
2986 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
2987 com_addbyte(c
, POP_TOP
);
2990 com_node(c
, CHILD(n
, 3));
2992 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
2993 c
->c_begin
= save_begin
;
2994 com_backpatch(c
, anchor
);
2995 /* We jump here with one entry more on the stack */
2996 com_addbyte(c
, POP_TOP
);
2997 com_addbyte(c
, POP_BLOCK
);
2998 block_pop(c
, SETUP_LOOP
);
3000 com_node(c
, CHILD(n
, 6));
3001 com_backpatch(c
, break_anchor
);
3005 com_for_stmt(struct compiling
*c
, node
*n
)
3007 int break_anchor
= 0;
3009 int save_begin
= c
->c_begin
;
3011 /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */
3012 com_addfwref(c
, SETUP_LOOP
, &break_anchor
);
3013 block_push(c
, SETUP_LOOP
);
3014 com_node(c
, CHILD(n
, 3));
3015 com_addbyte(c
, GET_ITER
);
3016 c
->c_begin
= c
->c_nexti
;
3017 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3018 com_addfwref(c
, FOR_ITER
, &anchor
);
3020 com_assign(c
, CHILD(n
, 1), OP_ASSIGN
, NULL
);
3022 com_node(c
, CHILD(n
, 5));
3024 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
3025 c
->c_begin
= save_begin
;
3026 com_backpatch(c
, anchor
);
3027 com_pop(c
, 1); /* FOR_ITER has popped this */
3028 com_addbyte(c
, POP_BLOCK
);
3029 block_pop(c
, SETUP_LOOP
);
3031 com_node(c
, CHILD(n
, 8));
3032 com_backpatch(c
, break_anchor
);
3035 /* Code generated for "try: S finally: Sf" is as follows:
3044 The special instructions use the block stack. Each block
3045 stack entry contains the instruction that created it (here
3046 SETUP_FINALLY), the level of the value stack at the time the
3047 block stack entry was created, and a label (here L).
3050 Pushes the current value stack level and the label
3051 onto the block stack.
3053 Pops en entry from the block stack, and pops the value
3054 stack until its level is the same as indicated on the
3055 block stack. (The label is ignored.)
3057 Pops a variable number of entries from the *value* stack
3058 and re-raises the exception they specify. The number of
3059 entries popped depends on the (pseudo) exception type.
3061 The block stack is unwound when an exception is raised:
3062 when a SETUP_FINALLY entry is found, the exception is pushed
3063 onto the value stack (and the exception condition is cleared),
3064 and the interpreter jumps to the label gotten from the block
3067 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
3068 (The contents of the value stack is shown in [], with the top
3069 at the right; 'tb' is trace-back info, 'val' the exception's
3070 associated value, and 'exc' the exception.)
3072 Value stack Label Instruction Argument
3078 [tb, val, exc] L1: DUP )
3079 [tb, val, exc, exc] <evaluate E1> )
3080 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
3081 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
3082 [tb, val, exc, 1] POP )
3084 [tb, val] <assign to V1> (or POP if no V1)
3089 [tb, val, exc, 0] L2: POP
3091 .............................etc.......................
3093 [tb, val, exc, 0] Ln+1: POP
3094 [tb, val, exc] END_FINALLY # re-raise exception
3096 [] L0: <next statement>
3098 Of course, parts are not generated if Vi or Ei is not present.
3102 com_try_except(struct compiling
*c
, node
*n
)
3104 int except_anchor
= 0;
3106 int else_anchor
= 0;
3110 com_addfwref(c
, SETUP_EXCEPT
, &except_anchor
);
3111 block_push(c
, SETUP_EXCEPT
);
3112 com_node(c
, CHILD(n
, 2));
3113 com_addbyte(c
, POP_BLOCK
);
3114 block_pop(c
, SETUP_EXCEPT
);
3115 com_addfwref(c
, JUMP_FORWARD
, &else_anchor
);
3116 com_backpatch(c
, except_anchor
);
3118 i
< NCH(n
) && TYPE(ch
= CHILD(n
, i
)) == except_clause
;
3120 /* except_clause: 'except' [expr [',' var]] */
3121 if (except_anchor
== 0) {
3122 com_error(c
, PyExc_SyntaxError
,
3123 "default 'except:' must be last");
3127 com_push(c
, 3); /* tb, val, exc pushed by exception */
3128 com_addoparg(c
, SET_LINENO
, ch
->n_lineno
);
3130 com_addbyte(c
, DUP_TOP
);
3132 com_node(c
, CHILD(ch
, 1));
3133 com_addoparg(c
, COMPARE_OP
, EXC_MATCH
);
3135 com_addfwref(c
, JUMP_IF_FALSE
, &except_anchor
);
3136 com_addbyte(c
, POP_TOP
);
3139 com_addbyte(c
, POP_TOP
);
3142 com_assign(c
, CHILD(ch
, 3), OP_ASSIGN
, NULL
);
3144 com_addbyte(c
, POP_TOP
);
3147 com_addbyte(c
, POP_TOP
);
3149 com_node(c
, CHILD(n
, i
+2));
3150 com_addfwref(c
, JUMP_FORWARD
, &end_anchor
);
3151 if (except_anchor
) {
3152 com_backpatch(c
, except_anchor
);
3153 /* We come in with [tb, val, exc, 0] on the
3154 stack; one pop and it's the same as
3155 expected at the start of the loop */
3156 com_addbyte(c
, POP_TOP
);
3159 /* We actually come in here with [tb, val, exc] but the
3160 END_FINALLY will zap those and jump around.
3161 The c_stacklevel does not reflect them so we need not pop
3163 com_addbyte(c
, END_FINALLY
);
3164 com_backpatch(c
, else_anchor
);
3166 com_node(c
, CHILD(n
, i
+2));
3167 com_backpatch(c
, end_anchor
);
3171 com_try_finally(struct compiling
*c
, node
*n
)
3173 int finally_anchor
= 0;
3176 com_addfwref(c
, SETUP_FINALLY
, &finally_anchor
);
3177 block_push(c
, SETUP_FINALLY
);
3178 com_node(c
, CHILD(n
, 2));
3179 com_addbyte(c
, POP_BLOCK
);
3180 block_pop(c
, SETUP_FINALLY
);
3181 block_push(c
, END_FINALLY
);
3182 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3183 /* While the generated code pushes only one item,
3184 the try-finally handling can enter here with
3185 up to three items. OK, here are the details:
3186 3 for an exception, 2 for RETURN, 1 for BREAK. */
3188 com_backpatch(c
, finally_anchor
);
3189 ch
= CHILD(n
, NCH(n
)-1);
3190 com_addoparg(c
, SET_LINENO
, ch
->n_lineno
);
3192 com_addbyte(c
, END_FINALLY
);
3193 block_pop(c
, END_FINALLY
);
3194 com_pop(c
, 3); /* Matches the com_push above */
3198 com_try_stmt(struct compiling
*c
, node
*n
)
3201 /* 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
3202 | 'try' ':' suite 'finally' ':' suite */
3203 if (TYPE(CHILD(n
, 3)) != except_clause
)
3204 com_try_finally(c
, n
);
3206 com_try_except(c
, n
);
3210 get_rawdocstring(node
*n
)
3214 /* Label to avoid tail recursion */
3225 for (i
= 0; i
< NCH(n
); i
++) {
3226 node
*ch
= CHILD(n
, i
);
3227 if (TYPE(ch
) == stmt
) {
3261 if (TYPE(CHILD(n
, 0)) == STRING
)
3270 get_docstring(node
*n
)
3272 /* Don't generate doc-strings if run with -OO */
3273 if (Py_OptimizeFlag
> 1)
3275 n
= get_rawdocstring(n
);
3278 return parsestrplus(n
);
3282 com_suite(struct compiling
*c
, node
*n
)
3285 /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */
3287 com_node(c
, CHILD(n
, 0));
3291 for (i
= 0; i
< NCH(n
) && c
->c_errors
== 0; i
++) {
3292 node
*ch
= CHILD(n
, i
);
3293 if (TYPE(ch
) == stmt
)
3301 com_continue_stmt(struct compiling
*c
, node
*n
)
3303 int i
= c
->c_nblocks
;
3304 if (i
-- > 0 && c
->c_block
[i
] == SETUP_LOOP
) {
3305 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
3308 /* at the outer level */
3309 com_error(c
, PyExc_SyntaxError
,
3310 "'continue' not properly in loop");
3314 for (j
= i
-1; j
>= 0; --j
) {
3315 if (c
->c_block
[j
] == SETUP_LOOP
)
3319 /* there is a loop, but something interferes */
3320 for (; i
> j
; --i
) {
3321 if (c
->c_block
[i
] == SETUP_EXCEPT
||
3322 c
->c_block
[i
] == SETUP_FINALLY
) {
3323 com_addoparg(c
, CONTINUE_LOOP
,
3327 if (c
->c_block
[i
] == END_FINALLY
) {
3328 com_error(c
, PyExc_SyntaxError
,
3329 "'continue' not supported inside 'finally' clause");
3334 com_error(c
, PyExc_SyntaxError
,
3335 "'continue' not properly in loop");
3337 /* XXX Could allow it inside a 'finally' clause
3338 XXX if we could pop the exception still on the stack */
3342 com_argdefs(struct compiling
*c
, node
*n
)
3344 int i
, nch
, nargs
, ndefs
;
3345 if (TYPE(n
) == lambdef
) {
3346 /* lambdef: 'lambda' [varargslist] ':' test */
3350 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ... */
3352 REQ(n
, parameters
); /* parameters: '(' [varargslist] ')' */
3355 if (TYPE(n
) != varargslist
)
3358 (fpdef ['=' test] ',')* '*' ....... |
3359 fpdef ['=' test] (',' fpdef ['=' test])* [','] */
3363 for (i
= 0; i
< nch
; i
++) {
3365 if (TYPE(CHILD(n
, i
)) == STAR
||
3366 TYPE(CHILD(n
, i
)) == DOUBLESTAR
)
3371 t
= RPAR
; /* Anything except EQUAL or COMMA */
3373 t
= TYPE(CHILD(n
, i
));
3377 com_node(c
, CHILD(n
, i
));
3381 t
= TYPE(CHILD(n
, i
));
3384 /* Treat "(a=1, b)" as an error */
3386 com_error(c
, PyExc_SyntaxError
,
3387 "non-default argument follows default argument");
3396 com_funcdef(struct compiling
*c
, node
*n
)
3400 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ':' suite */
3401 ndefs
= com_argdefs(c
, n
);
3402 symtable_enter_scope(c
->c_symtable
, STR(CHILD(n
, 1)), TYPE(n
),
3404 co
= (PyObject
*)icompile(n
, c
);
3405 symtable_exit_scope(c
->c_symtable
);
3409 int closure
= com_make_closure(c
, (PyCodeObject
*)co
);
3410 int i
= com_addconst(c
, co
);
3411 com_addoparg(c
, LOAD_CONST
, i
);
3414 com_addoparg(c
, MAKE_CLOSURE
, ndefs
);
3416 com_addoparg(c
, MAKE_FUNCTION
, ndefs
);
3418 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 1)));
3425 com_bases(struct compiling
*c
, node
*n
)
3429 /* testlist: test (',' test)* [','] */
3430 for (i
= 0; i
< NCH(n
); i
+= 2)
3431 com_node(c
, CHILD(n
, i
));
3433 com_addoparg(c
, BUILD_TUPLE
, i
);
3438 com_classdef(struct compiling
*c
, node
*n
)
3445 /* classdef: class NAME ['(' testlist ')'] ':' suite */
3446 if ((v
= PyString_InternFromString(STR(CHILD(n
, 1)))) == NULL
) {
3450 /* Push the class name on the stack */
3451 i
= com_addconst(c
, v
);
3452 com_addoparg(c
, LOAD_CONST
, i
);
3455 /* Push the tuple of base classes on the stack */
3456 if (TYPE(CHILD(n
, 2)) != LPAR
) {
3457 com_addoparg(c
, BUILD_TUPLE
, 0);
3461 com_bases(c
, CHILD(n
, 3));
3462 name
= STR(CHILD(n
, 1));
3463 symtable_enter_scope(c
->c_symtable
, name
, TYPE(n
), n
->n_lineno
);
3464 co
= (PyObject
*)icompile(n
, c
);
3465 symtable_exit_scope(c
->c_symtable
);
3469 int closure
= com_make_closure(c
, (PyCodeObject
*)co
);
3470 i
= com_addconst(c
, co
);
3471 com_addoparg(c
, LOAD_CONST
, i
);
3474 com_addoparg(c
, MAKE_CLOSURE
, 0);
3476 com_addoparg(c
, MAKE_FUNCTION
, 0);
3477 com_addoparg(c
, CALL_FUNCTION
, 0);
3478 com_addbyte(c
, BUILD_CLASS
);
3480 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 1)));
3486 com_node(struct compiling
*c
, node
*n
)
3493 /* Definition nodes */
3502 /* Trivial parse tree nodes */
3511 /* small_stmt (';' small_stmt)* [';'] NEWLINE */
3512 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3515 for (i
= 0; i
< NCH(n
)-1; i
+= 2)
3516 com_node(c
, CHILD(n
, i
));
3521 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3525 /* Statement nodes */
3528 com_expr_stmt(c
, n
);
3531 com_print_stmt(c
, n
);
3533 case del_stmt
: /* 'del' exprlist */
3534 com_assign(c
, CHILD(n
, 1), OP_DELETE
, NULL
);
3539 if (c
->c_loops
== 0) {
3540 com_error(c
, PyExc_SyntaxError
,
3541 "'break' outside loop");
3543 com_addbyte(c
, BREAK_LOOP
);
3546 com_continue_stmt(c
, n
);
3549 com_return_stmt(c
, n
);
3552 com_yield_stmt(c
, n
);
3555 com_raise_stmt(c
, n
);
3558 com_import_stmt(c
, n
);
3563 com_exec_stmt(c
, n
);
3566 com_assert_stmt(c
, n
);
3572 com_while_stmt(c
, n
);
3584 /* Expression nodes */
3599 com_comparison(c
, n
);
3614 com_shift_expr(c
, n
);
3617 com_arith_expr(c
, n
);
3633 com_error(c
, PyExc_SystemError
,
3634 "com_node: unexpected node type");
3638 static void com_fplist(struct compiling
*, node
*);
3641 com_fpdef(struct compiling
*c
, node
*n
)
3643 REQ(n
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
3644 if (TYPE(CHILD(n
, 0)) == LPAR
)
3645 com_fplist(c
, CHILD(n
, 1));
3647 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 0)));
3653 com_fplist(struct compiling
*c
, node
*n
)
3655 REQ(n
, fplist
); /* fplist: fpdef (',' fpdef)* [','] */
3657 com_fpdef(c
, CHILD(n
, 0));
3660 int i
= (NCH(n
)+1)/2;
3661 com_addoparg(c
, UNPACK_SEQUENCE
, i
);
3663 for (i
= 0; i
< NCH(n
); i
+= 2)
3664 com_fpdef(c
, CHILD(n
, i
));
3669 com_arglist(struct compiling
*c
, node
*n
)
3674 REQ(n
, varargslist
);
3676 (fpdef ['=' test] ',')* (fpdef ['=' test] | '*' .....) */
3678 /* Enter all arguments in table of locals */
3679 for (i
= 0, narg
= 0; i
< nch
; i
++) {
3680 node
*ch
= CHILD(n
, i
);
3682 if (TYPE(ch
) == STAR
|| TYPE(ch
) == DOUBLESTAR
)
3684 REQ(ch
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
3686 if (TYPE(fp
) != NAME
) {
3687 sprintf(nbuf
, ".%d", i
);
3691 /* all name updates handled by symtable */
3695 if (TYPE(ch
) == EQUAL
)
3701 /* Generate code for complex arguments only after
3702 having counted the simple arguments */
3704 for (i
= 0; i
< nch
; i
++) {
3705 node
*ch
= CHILD(n
, i
);
3707 if (TYPE(ch
) == STAR
|| TYPE(ch
) == DOUBLESTAR
)
3709 REQ(ch
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
3711 if (TYPE(fp
) != NAME
) {
3712 com_addoparg(c
, LOAD_FAST
, ilocal
);
3720 if (TYPE(ch
) == EQUAL
)
3729 com_file_input(struct compiling
*c
, node
*n
)
3733 REQ(n
, file_input
); /* (NEWLINE | stmt)* ENDMARKER */
3734 doc
= get_docstring(n
);
3736 int i
= com_addconst(c
, doc
);
3738 com_addoparg(c
, LOAD_CONST
, i
);
3740 com_addop_name(c
, STORE_NAME
, "__doc__");
3743 for (i
= 0; i
< NCH(n
); i
++) {
3744 node
*ch
= CHILD(n
, i
);
3745 if (TYPE(ch
) != ENDMARKER
&& TYPE(ch
) != NEWLINE
)
3750 /* Top-level compile-node interface */
3753 compile_funcdef(struct compiling
*c
, node
*n
)
3757 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ':' suite */
3758 c
->c_name
= STR(CHILD(n
, 1));
3759 doc
= get_docstring(CHILD(n
, 4));
3761 (void) com_addconst(c
, doc
);
3765 (void) com_addconst(c
, Py_None
); /* No docstring */
3766 ch
= CHILD(n
, 2); /* parameters: '(' [varargslist] ')' */
3767 ch
= CHILD(ch
, 1); /* ')' | varargslist */
3768 if (TYPE(ch
) == varargslist
)
3770 c
->c_infunction
= 1;
3771 com_node(c
, CHILD(n
, 4));
3772 c
->c_infunction
= 0;
3773 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3775 com_addbyte(c
, RETURN_VALUE
);
3780 compile_lambdef(struct compiling
*c
, node
*n
)
3783 REQ(n
, lambdef
); /* lambdef: 'lambda' [varargslist] ':' test */
3784 c
->c_name
= "<lambda>";
3787 (void) com_addconst(c
, Py_None
); /* No docstring */
3788 if (TYPE(ch
) == varargslist
) {
3795 com_addbyte(c
, RETURN_VALUE
);
3800 compile_classdef(struct compiling
*c
, node
*n
)
3805 /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */
3806 c
->c_name
= STR(CHILD(n
, 1));
3807 c
->c_private
= c
->c_name
;
3808 ch
= CHILD(n
, NCH(n
)-1); /* The suite */
3809 doc
= get_docstring(ch
);
3811 int i
= com_addconst(c
, doc
);
3813 com_addoparg(c
, LOAD_CONST
, i
);
3815 com_addop_name(c
, STORE_NAME
, "__doc__");
3819 (void) com_addconst(c
, Py_None
);
3821 com_addbyte(c
, LOAD_LOCALS
);
3823 com_addbyte(c
, RETURN_VALUE
);
3828 compile_node(struct compiling
*c
, node
*n
)
3830 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3834 case single_input
: /* One interactive command */
3835 /* NEWLINE | simple_stmt | compound_stmt NEWLINE */
3838 if (TYPE(n
) != NEWLINE
)
3840 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3842 com_addbyte(c
, RETURN_VALUE
);
3847 case file_input
: /* A whole file, or built-in function exec() */
3848 com_file_input(c
, n
);
3849 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3851 com_addbyte(c
, RETURN_VALUE
);
3855 case eval_input
: /* Built-in function input() */
3856 com_node(c
, CHILD(n
, 0));
3857 com_addbyte(c
, RETURN_VALUE
);
3861 case lambdef
: /* anonymous function definition */
3862 compile_lambdef(c
, n
);
3865 case funcdef
: /* A function definition */
3866 compile_funcdef(c
, n
);
3869 case classdef
: /* A class definition */
3870 compile_classdef(c
, n
);
3874 com_error(c
, PyExc_SystemError
,
3875 "compile_node: unexpected node type");
3880 dict_keys_inorder(PyObject
*dict
, int offset
)
3882 PyObject
*tuple
, *k
, *v
;
3883 int i
, pos
= 0, size
= PyDict_Size(dict
);
3885 tuple
= PyTuple_New(size
);
3888 while (PyDict_Next(dict
, &pos
, &k
, &v
)) {
3889 i
= PyInt_AS_LONG(v
);
3891 assert((i
- offset
) < size
);
3892 PyTuple_SET_ITEM(tuple
, i
- offset
, k
);
3898 PyNode_Compile(node
*n
, char *filename
)
3900 return PyNode_CompileFlags(n
, filename
, NULL
);
3904 PyNode_CompileFlags(node
*n
, char *filename
, PyCompilerFlags
*flags
)
3906 return jcompile(n
, filename
, NULL
, flags
);
3910 PyNode_CompileSymtable(node
*n
, char *filename
)
3912 struct symtable
*st
;
3913 PyFutureFeatures
*ff
;
3915 ff
= PyNode_Future(n
, filename
);
3918 st
= symtable_init();
3922 symtable_enter_scope(st
, TOP
, TYPE(n
), n
->n_lineno
);
3923 if (st
->st_errors
> 0)
3925 symtable_node(st
, n
);
3926 if (st
->st_errors
> 0)
3931 PyMem_Free((void *)ff
);
3932 st
->st_future
= NULL
;
3933 PySymtable_Free(st
);
3937 static PyCodeObject
*
3938 icompile(node
*n
, struct compiling
*base
)
3940 return jcompile(n
, base
->c_filename
, base
, NULL
);
3943 static PyCodeObject
*
3944 jcompile(node
*n
, char *filename
, struct compiling
*base
,
3945 PyCompilerFlags
*flags
)
3947 struct compiling sc
;
3949 if (!com_init(&sc
, filename
))
3952 sc
.c_private
= base
->c_private
;
3953 sc
.c_symtable
= base
->c_symtable
;
3954 /* c_symtable still points to parent's symbols */
3956 || (sc
.c_symtable
->st_cur
->ste_type
== TYPE_FUNCTION
))
3958 sc
.c_flags
|= base
->c_flags
& (CO_GENERATOR_ALLOWED
|
3959 CO_FUTURE_DIVISION
);
3961 sc
.c_private
= NULL
;
3962 sc
.c_future
= PyNode_Future(n
, filename
);
3963 if (sc
.c_future
== NULL
) {
3968 sc
.c_future
->ff_features
|= flags
->cf_flags
;
3969 if (symtable_build(&sc
, n
) < 0) {
3975 if (symtable_load_symbols(&sc
) < 0) {
3979 compile_node(&sc
, n
);
3981 if (sc
.c_errors
== 0) {
3982 PyObject
*consts
, *names
, *varnames
, *filename
, *name
,
3983 *freevars
, *cellvars
;
3984 consts
= PyList_AsTuple(sc
.c_consts
);
3985 names
= PyList_AsTuple(sc
.c_names
);
3986 varnames
= PyList_AsTuple(sc
.c_varnames
);
3987 cellvars
= dict_keys_inorder(sc
.c_cellvars
, 0);
3988 freevars
= dict_keys_inorder(sc
.c_freevars
,
3989 PyTuple_GET_SIZE(cellvars
));
3990 filename
= PyString_InternFromString(sc
.c_filename
);
3991 name
= PyString_InternFromString(sc
.c_name
);
3992 if (!PyErr_Occurred())
3993 co
= PyCode_New(sc
.c_argcount
,
4009 Py_XDECREF(varnames
);
4010 Py_XDECREF(freevars
);
4011 Py_XDECREF(cellvars
);
4012 Py_XDECREF(filename
);
4015 else if (!PyErr_Occurred()) {
4016 /* This could happen if someone called PyErr_Clear() after an
4017 error was reported above. That's not supposed to happen,
4018 but I just plugged one case and I'm not sure there can't be
4019 others. In that case, raise SystemError so that at least
4020 it gets reported instead dumping core. */
4021 PyErr_SetString(PyExc_SystemError
, "lost syntax error");
4025 PySymtable_Free(sc
.c_symtable
);
4026 sc
.c_symtable
= NULL
;
4033 PyCode_Addr2Line(PyCodeObject
*co
, int addrq
)
4035 int size
= PyString_Size(co
->co_lnotab
) / 2;
4036 unsigned char *p
= (unsigned char*)PyString_AsString(co
->co_lnotab
);
4037 int line
= co
->co_firstlineno
;
4039 while (--size
>= 0) {
4048 /* The test for LOCAL must come before the test for FREE in order to
4049 handle classes where name is both local and free. The local var is
4050 a method and the free var is a free var referenced within a method.
4054 get_ref_type(struct compiling
*c
, char *name
)
4059 if (PyDict_GetItemString(c
->c_cellvars
, name
) != NULL
)
4061 if (PyDict_GetItemString(c
->c_locals
, name
) != NULL
)
4063 if (PyDict_GetItemString(c
->c_freevars
, name
) != NULL
)
4065 v
= PyDict_GetItemString(c
->c_globals
, name
);
4068 return GLOBAL_EXPLICIT
;
4070 return GLOBAL_IMPLICIT
;
4074 "unknown scope for %.100s in %.100s(%s) "
4075 "in %s\nsymbols: %s\nlocals: %s\nglobals: %s\n",
4077 PyObject_REPR(c
->c_symtable
->st_cur
->ste_id
),
4079 PyObject_REPR(c
->c_symtable
->st_cur
->ste_symbols
),
4080 PyObject_REPR(c
->c_locals
),
4081 PyObject_REPR(c
->c_globals
)
4088 /* Helper functions to issue warnings */
4091 issue_warning(char *msg
, char *filename
, int lineno
)
4093 if (PyErr_WarnExplicit(PyExc_SyntaxWarning
, msg
, filename
,
4094 lineno
, NULL
, NULL
) < 0) {
4095 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning
)) {
4096 PyErr_SetString(PyExc_SyntaxError
, msg
);
4097 PyErr_SyntaxLocation(filename
, lineno
);
4105 symtable_warn(struct symtable
*st
, char *msg
)
4107 if (issue_warning(msg
, st
->st_filename
, st
->st_cur
->ste_lineno
) < 0) {
4114 /* Helper function for setting lineno and filename */
4117 symtable_build(struct compiling
*c
, node
*n
)
4119 if ((c
->c_symtable
= symtable_init()) == NULL
)
4121 c
->c_symtable
->st_future
= c
->c_future
;
4122 c
->c_symtable
->st_filename
= c
->c_filename
;
4123 symtable_enter_scope(c
->c_symtable
, TOP
, TYPE(n
), n
->n_lineno
);
4124 if (c
->c_symtable
->st_errors
> 0)
4126 symtable_node(c
->c_symtable
, n
);
4127 if (c
->c_symtable
->st_errors
> 0)
4129 /* reset for second pass */
4130 c
->c_symtable
->st_nscopes
= 1;
4131 c
->c_symtable
->st_pass
= 2;
4136 symtable_init_compiling_symbols(struct compiling
*c
)
4140 varnames
= c
->c_symtable
->st_cur
->ste_varnames
;
4141 if (varnames
== NULL
) {
4142 varnames
= PyList_New(0);
4143 if (varnames
== NULL
)
4145 c
->c_symtable
->st_cur
->ste_varnames
= varnames
;
4146 Py_INCREF(varnames
);
4148 Py_INCREF(varnames
);
4149 c
->c_varnames
= varnames
;
4151 c
->c_globals
= PyDict_New();
4152 if (c
->c_globals
== NULL
)
4154 c
->c_freevars
= PyDict_New();
4155 if (c
->c_freevars
== NULL
)
4157 c
->c_cellvars
= PyDict_New();
4158 if (c
->c_cellvars
== NULL
)
4163 struct symbol_info
{
4171 symtable_init_info(struct symbol_info
*si
)
4176 si
->si_nimplicit
= 0;
4180 symtable_resolve_free(struct compiling
*c
, PyObject
*name
, int flags
,
4181 struct symbol_info
*si
)
4185 /* Seperate logic for DEF_FREE. If it occurs in a function,
4186 it indicates a local that we must allocate storage for (a
4187 cell var). If it occurs in a class, then the class has a
4188 method and a free variable with the same name.
4190 if (c
->c_symtable
->st_cur
->ste_type
== TYPE_FUNCTION
) {
4191 /* If it isn't declared locally, it can't be a cell. */
4192 if (!(flags
& (DEF_LOCAL
| DEF_PARAM
)))
4194 v
= PyInt_FromLong(si
->si_ncells
++);
4195 dict
= c
->c_cellvars
;
4197 /* If it is free anyway, then there is no need to do
4200 if (is_free(flags
^ DEF_FREE_CLASS
)
4201 || (flags
== DEF_FREE_CLASS
))
4203 v
= PyInt_FromLong(si
->si_nfrees
++);
4204 dict
= c
->c_freevars
;
4208 if (PyDict_SetItem(dict
, name
, v
) < 0) {
4216 /* If a variable is a cell and an argument, make sure that appears in
4217 co_cellvars before any variable to its right in varnames.
4222 symtable_cellvar_offsets(PyObject
**cellvars
, int argcount
,
4223 PyObject
*varnames
, int flags
)
4225 PyObject
*v
, *w
, *d
, *list
= NULL
;
4228 if (flags
& CO_VARARGS
)
4230 if (flags
& CO_VARKEYWORDS
)
4232 for (i
= argcount
; --i
>= 0; ) {
4233 v
= PyList_GET_ITEM(varnames
, i
);
4234 if (PyDict_GetItem(*cellvars
, v
)) {
4236 list
= PyList_New(1);
4239 PyList_SET_ITEM(list
, 0, v
);
4242 PyList_Insert(list
, 0, v
);
4245 if (list
== NULL
|| PyList_GET_SIZE(list
) == 0)
4247 /* There are cellvars that are also arguments. Create a dict
4248 to replace cellvars and put the args at the front.
4251 for (i
= PyList_GET_SIZE(list
); --i
>= 0; ) {
4252 v
= PyInt_FromLong(i
);
4255 if (PyDict_SetItem(d
, PyList_GET_ITEM(list
, i
), v
) < 0)
4257 if (PyDict_DelItem(*cellvars
, PyList_GET_ITEM(list
, i
)) < 0)
4261 i
= PyList_GET_SIZE(list
);
4263 while (PyDict_Next(*cellvars
, &pos
, &v
, &w
)) {
4264 w
= PyInt_FromLong(i
++); /* don't care about the old key */
4265 if (PyDict_SetItem(d
, v
, w
) < 0) {
4271 Py_DECREF(*cellvars
);
4280 symtable_freevar_offsets(PyObject
*freevars
, int offset
)
4285 /* The cell vars are the first elements of the closure,
4286 followed by the free vars. Update the offsets in
4287 c_freevars to account for number of cellvars. */
4289 while (PyDict_Next(freevars
, &pos
, &name
, &v
)) {
4290 int i
= PyInt_AS_LONG(v
) + offset
;
4291 PyObject
*o
= PyInt_FromLong(i
);
4294 if (PyDict_SetItem(freevars
, name
, o
) < 0) {
4304 symtable_check_unoptimized(struct compiling
*c
,
4305 PySymtableEntryObject
*ste
,
4306 struct symbol_info
*si
)
4310 if (!(si
->si_ncells
|| si
->si_nfrees
|| ste
->ste_child_free
4311 || (ste
->ste_nested
&& si
->si_nimplicit
)))
4314 #define ILLEGAL_CONTAINS "contains a nested function with free variables"
4316 #define ILLEGAL_IS "is a nested function"
4318 #define ILLEGAL_IMPORT_STAR \
4319 "import * is not allowed in function '%.100s' because it %s"
4321 #define ILLEGAL_BARE_EXEC \
4322 "unqualified exec is not allowed in function '%.100s' it %s"
4324 #define ILLEGAL_EXEC_AND_IMPORT_STAR \
4325 "function '%.100s' uses import * and bare exec, which are illegal" \
4328 /* XXX perhaps the linenos for these opt-breaking statements
4329 should be stored so the exception can point to them. */
4331 if (ste
->ste_child_free
) {
4332 if (ste
->ste_optimized
== OPT_IMPORT_STAR
)
4333 sprintf(buf
, ILLEGAL_IMPORT_STAR
,
4334 PyString_AS_STRING(ste
->ste_name
),
4336 else if (ste
->ste_optimized
== (OPT_BARE_EXEC
| OPT_EXEC
))
4337 sprintf(buf
, ILLEGAL_BARE_EXEC
,
4338 PyString_AS_STRING(ste
->ste_name
),
4341 sprintf(buf
, ILLEGAL_EXEC_AND_IMPORT_STAR
,
4342 PyString_AS_STRING(ste
->ste_name
),
4346 if (ste
->ste_optimized
== OPT_IMPORT_STAR
)
4347 sprintf(buf
, ILLEGAL_IMPORT_STAR
,
4348 PyString_AS_STRING(ste
->ste_name
),
4350 else if (ste
->ste_optimized
== (OPT_BARE_EXEC
| OPT_EXEC
))
4351 sprintf(buf
, ILLEGAL_BARE_EXEC
,
4352 PyString_AS_STRING(ste
->ste_name
),
4355 sprintf(buf
, ILLEGAL_EXEC_AND_IMPORT_STAR
,
4356 PyString_AS_STRING(ste
->ste_name
),
4361 PyErr_SetString(PyExc_SyntaxError
, buf
);
4362 PyErr_SyntaxLocation(c
->c_symtable
->st_filename
,
4363 ste
->ste_opt_lineno
);
4368 symtable_update_flags(struct compiling
*c
, PySymtableEntryObject
*ste
,
4369 struct symbol_info
*si
)
4372 c
->c_flags
|= c
->c_future
->ff_features
;
4373 if (ste
->ste_generator
)
4374 c
->c_flags
|= CO_GENERATOR
;
4375 if (ste
->ste_type
!= TYPE_MODULE
)
4376 c
->c_flags
|= CO_NEWLOCALS
;
4377 if (ste
->ste_type
== TYPE_FUNCTION
) {
4378 c
->c_nlocals
= si
->si_nlocals
;
4379 if (ste
->ste_optimized
== 0)
4380 c
->c_flags
|= CO_OPTIMIZED
;
4381 else if (ste
->ste_optimized
!= OPT_EXEC
)
4382 return symtable_check_unoptimized(c
, ste
, si
);
4388 symtable_load_symbols(struct compiling
*c
)
4390 static PyObject
*implicit
= NULL
;
4391 struct symtable
*st
= c
->c_symtable
;
4392 PySymtableEntryObject
*ste
= st
->st_cur
;
4393 PyObject
*name
, *varnames
, *v
;
4395 struct symbol_info si
;
4397 if (implicit
== NULL
) {
4398 implicit
= PyInt_FromLong(1);
4399 if (implicit
== NULL
)
4404 if (symtable_init_compiling_symbols(c
) < 0)
4406 symtable_init_info(&si
);
4407 varnames
= st
->st_cur
->ste_varnames
;
4408 si
.si_nlocals
= PyList_GET_SIZE(varnames
);
4409 c
->c_argcount
= si
.si_nlocals
;
4411 for (i
= 0; i
< si
.si_nlocals
; ++i
) {
4412 v
= PyInt_FromLong(i
);
4413 if (PyDict_SetItem(c
->c_locals
,
4414 PyList_GET_ITEM(varnames
, i
), v
) < 0)
4419 /* XXX The cases below define the rules for whether a name is
4420 local or global. The logic could probably be clearer. */
4422 while (PyDict_Next(ste
->ste_symbols
, &pos
, &name
, &v
)) {
4423 flags
= PyInt_AS_LONG(v
);
4425 if (flags
& DEF_FREE_GLOBAL
)
4426 /* undo the original DEF_FREE */
4427 flags
&= ~(DEF_FREE
| DEF_FREE_CLASS
);
4429 /* Deal with names that need two actions:
4430 1. Cell variables that are also locals.
4431 2. Free variables in methods that are also class
4432 variables or declared global.
4434 if (flags
& (DEF_FREE
| DEF_FREE_CLASS
))
4435 symtable_resolve_free(c
, name
, flags
, &si
);
4437 if (flags
& DEF_STAR
) {
4439 c
->c_flags
|= CO_VARARGS
;
4440 } else if (flags
& DEF_DOUBLESTAR
) {
4442 c
->c_flags
|= CO_VARKEYWORDS
;
4443 } else if (flags
& DEF_INTUPLE
)
4445 else if (flags
& DEF_GLOBAL
) {
4446 if (flags
& DEF_PARAM
) {
4447 PyErr_Format(PyExc_SyntaxError
, LOCAL_GLOBAL
,
4448 PyString_AS_STRING(name
));
4449 PyErr_SyntaxLocation(st
->st_filename
,
4454 if (PyDict_SetItem(c
->c_globals
, name
, Py_None
) < 0)
4456 } else if (flags
& DEF_FREE_GLOBAL
) {
4458 if (PyDict_SetItem(c
->c_globals
, name
, implicit
) < 0)
4460 } else if ((flags
& DEF_LOCAL
) && !(flags
& DEF_PARAM
)) {
4461 v
= PyInt_FromLong(si
.si_nlocals
++);
4464 if (PyDict_SetItem(c
->c_locals
, name
, v
) < 0)
4467 if (ste
->ste_type
!= TYPE_CLASS
)
4468 if (PyList_Append(c
->c_varnames
, name
) < 0)
4470 } else if (is_free(flags
)) {
4471 if (ste
->ste_nested
) {
4472 v
= PyInt_FromLong(si
.si_nfrees
++);
4475 if (PyDict_SetItem(c
->c_freevars
, name
, v
) < 0)
4480 if (PyDict_SetItem(c
->c_globals
, name
,
4483 if (st
->st_nscopes
!= 1) {
4484 v
= PyInt_FromLong(flags
);
4485 if (PyDict_SetItem(st
->st_global
,
4494 assert(PyDict_Size(c
->c_freevars
) == si
.si_nfrees
);
4496 if (si
.si_ncells
> 1) { /* one cell is always in order */
4497 if (symtable_cellvar_offsets(&c
->c_cellvars
, c
->c_argcount
,
4498 c
->c_varnames
, c
->c_flags
) < 0)
4501 if (symtable_freevar_offsets(c
->c_freevars
, si
.si_ncells
) < 0)
4503 return symtable_update_flags(c
, ste
, &si
);
4505 /* is this always the right thing to do? */
4510 static struct symtable
*
4513 struct symtable
*st
;
4515 st
= (struct symtable
*)PyMem_Malloc(sizeof(struct symtable
));
4520 st
->st_filename
= NULL
;
4521 if ((st
->st_stack
= PyList_New(0)) == NULL
)
4523 if ((st
->st_symbols
= PyDict_New()) == NULL
)
4529 st
->st_private
= NULL
;
4532 PySymtable_Free(st
);
4537 PySymtable_Free(struct symtable
*st
)
4539 Py_XDECREF(st
->st_symbols
);
4540 Py_XDECREF(st
->st_stack
);
4541 Py_XDECREF(st
->st_cur
);
4542 PyMem_Free((void *)st
);
4545 /* When the compiler exits a scope, it must should update the scope's
4546 free variable information with the list of free variables in its
4549 Variables that are free in children and defined in the current
4552 If the scope being exited is defined at the top-level (ste_nested is
4553 false), free variables in children that are not defined here are
4559 symtable_update_free_vars(struct symtable
*st
)
4562 PyObject
*o
, *name
, *list
= NULL
;
4563 PySymtableEntryObject
*child
, *ste
= st
->st_cur
;
4565 if (ste
->ste_type
== TYPE_CLASS
)
4566 def
= DEF_FREE_CLASS
;
4569 for (i
= 0; i
< PyList_GET_SIZE(ste
->ste_children
); ++i
) {
4573 PyList_SetSlice(list
, 0,
4574 ((PyVarObject
*)list
)->ob_size
, 0);
4575 child
= (PySymtableEntryObject
*)
4576 PyList_GET_ITEM(ste
->ste_children
, i
);
4577 while (PyDict_Next(child
->ste_symbols
, &pos
, &name
, &o
)) {
4578 int flags
= PyInt_AS_LONG(o
);
4579 if (!(is_free(flags
)))
4580 continue; /* avoids indentation */
4582 list
= PyList_New(0);
4586 ste
->ste_child_free
= 1;
4587 if (PyList_Append(list
, name
) < 0) {
4592 for (j
= 0; list
&& j
< PyList_GET_SIZE(list
); j
++) {
4594 name
= PyList_GET_ITEM(list
, j
);
4595 v
= PyDict_GetItem(ste
->ste_symbols
, name
);
4596 /* If a name N is declared global in scope A and
4597 referenced in scope B contained (perhaps
4598 indirectly) in A and there are no scopes
4599 with bindings for N between B and A, then N
4600 is global in B. Unless A is a class scope,
4601 because class scopes are not considered for
4604 if (v
&& (ste
->ste_type
!= TYPE_CLASS
)) {
4605 int flags
= PyInt_AS_LONG(v
);
4606 if (flags
& DEF_GLOBAL
) {
4607 symtable_undo_free(st
, child
->ste_id
,
4612 if (ste
->ste_nested
) {
4613 if (symtable_add_def_o(st
, ste
->ste_symbols
,
4619 if (symtable_check_global(st
, child
->ste_id
,
4632 /* If the current scope is a non-nested class or if name is not
4633 defined in the current, non-nested scope, then it is an implicit
4634 global in all nested scopes.
4638 symtable_check_global(struct symtable
*st
, PyObject
*child
, PyObject
*name
)
4642 PySymtableEntryObject
*ste
= st
->st_cur
;
4644 if (ste
->ste_type
== TYPE_CLASS
)
4645 return symtable_undo_free(st
, child
, name
);
4646 o
= PyDict_GetItem(ste
->ste_symbols
, name
);
4648 return symtable_undo_free(st
, child
, name
);
4649 v
= PyInt_AS_LONG(o
);
4651 if (is_free(v
) || (v
& DEF_GLOBAL
))
4652 return symtable_undo_free(st
, child
, name
);
4654 return symtable_add_def_o(st
, ste
->ste_symbols
,
4659 symtable_undo_free(struct symtable
*st
, PyObject
*id
,
4664 PySymtableEntryObject
*ste
;
4666 ste
= (PySymtableEntryObject
*)PyDict_GetItem(st
->st_symbols
, id
);
4670 info
= PyDict_GetItem(ste
->ste_symbols
, name
);
4673 v
= PyInt_AS_LONG(info
);
4675 if (symtable_add_def_o(st
, ste
->ste_symbols
, name
,
4676 DEF_FREE_GLOBAL
) < 0)
4679 /* If the name is defined here or declared global,
4680 then the recursion stops. */
4683 for (i
= 0; i
< PyList_GET_SIZE(ste
->ste_children
); ++i
) {
4684 PySymtableEntryObject
*child
;
4685 child
= (PySymtableEntryObject
*)
4686 PyList_GET_ITEM(ste
->ste_children
, i
);
4687 x
= symtable_undo_free(st
, child
->ste_id
, name
);
4694 /* symtable_enter_scope() gets a reference via PySymtableEntry_New().
4695 This reference is released when the scope is exited, via the DECREF
4696 in symtable_exit_scope().
4700 symtable_exit_scope(struct symtable
*st
)
4704 if (st
->st_pass
== 1)
4705 symtable_update_free_vars(st
);
4706 Py_DECREF(st
->st_cur
);
4707 end
= PyList_GET_SIZE(st
->st_stack
) - 1;
4708 st
->st_cur
= (PySymtableEntryObject
*)PyList_GET_ITEM(st
->st_stack
,
4710 if (PySequence_DelItem(st
->st_stack
, end
) < 0)
4716 symtable_enter_scope(struct symtable
*st
, char *name
, int type
,
4719 PySymtableEntryObject
*prev
= NULL
;
4723 if (PyList_Append(st
->st_stack
, (PyObject
*)st
->st_cur
) < 0) {
4724 Py_DECREF(st
->st_cur
);
4729 st
->st_cur
= (PySymtableEntryObject
*)
4730 PySymtableEntry_New(st
, name
, type
, lineno
);
4731 if (strcmp(name
, TOP
) == 0)
4732 st
->st_global
= st
->st_cur
->ste_symbols
;
4733 if (prev
&& st
->st_pass
== 1) {
4734 if (PyList_Append(prev
->ste_children
,
4735 (PyObject
*)st
->st_cur
) < 0)
4741 symtable_lookup(struct symtable
*st
, char *name
)
4743 char buffer
[MANGLE_LEN
];
4747 if (mangle(st
->st_private
, name
, buffer
, sizeof(buffer
)))
4749 v
= PyDict_GetItemString(st
->st_cur
->ste_symbols
, name
);
4751 if (PyErr_Occurred())
4757 flags
= PyInt_AS_LONG(v
);
4762 symtable_add_def(struct symtable
*st
, char *name
, int flag
)
4765 char buffer
[MANGLE_LEN
];
4768 if (mangle(st
->st_private
, name
, buffer
, sizeof(buffer
)))
4770 if ((s
= PyString_InternFromString(name
)) == NULL
)
4772 ret
= symtable_add_def_o(st
, st
->st_cur
->ste_symbols
, s
, flag
);
4777 /* Must only be called with mangled names */
4780 symtable_add_def_o(struct symtable
*st
, PyObject
*dict
,
4781 PyObject
*name
, int flag
)
4786 if ((o
= PyDict_GetItem(dict
, name
))) {
4787 val
= PyInt_AS_LONG(o
);
4788 if ((flag
& DEF_PARAM
) && (val
& DEF_PARAM
)) {
4789 PyErr_Format(PyExc_SyntaxError
, DUPLICATE_ARGUMENT
,
4790 PyString_AsString(name
));
4791 PyErr_SyntaxLocation(st
->st_filename
,
4792 st
->st_cur
->ste_lineno
);
4798 o
= PyInt_FromLong(val
);
4799 if (PyDict_SetItem(dict
, name
, o
) < 0) {
4805 if (flag
& DEF_PARAM
) {
4806 if (PyList_Append(st
->st_cur
->ste_varnames
, name
) < 0)
4808 } else if (flag
& DEF_GLOBAL
) {
4809 /* XXX need to update DEF_GLOBAL for other flags too;
4810 perhaps only DEF_FREE_GLOBAL */
4811 if ((o
= PyDict_GetItem(st
->st_global
, name
))) {
4812 val
= PyInt_AS_LONG(o
);
4816 o
= PyInt_FromLong(val
);
4817 if (PyDict_SetItem(st
->st_global
, name
, o
) < 0) {
4826 #define symtable_add_use(ST, NAME) symtable_add_def((ST), (NAME), USE)
4828 /* Look for a yield stmt under n. Return 1 if found, else 0.
4829 This hack is used to look inside "if 0:" blocks (which are normally
4830 ignored) in case those are the only places a yield occurs (so that this
4831 function is a generator). */
4833 look_for_yield(node
*n
)
4837 for (i
= 0; i
< NCH(n
); ++i
) {
4838 node
*kid
= CHILD(n
, i
);
4840 switch (TYPE(kid
)) {
4845 /* Stuff in nested functions and classes can't make
4846 the parent a generator. */
4853 if (look_for_yield(kid
))
4861 symtable_node(struct symtable
*st
, node
*n
)
4868 char *func_name
= STR(CHILD(n
, 1));
4869 symtable_add_def(st
, func_name
, DEF_LOCAL
);
4870 symtable_default_args(st
, CHILD(n
, 2));
4871 symtable_enter_scope(st
, func_name
, TYPE(n
), n
->n_lineno
);
4872 symtable_funcdef(st
, n
);
4873 symtable_exit_scope(st
);
4878 symtable_default_args(st
, CHILD(n
, 1));
4879 symtable_enter_scope(st
, "lambda", TYPE(n
), n
->n_lineno
);
4880 symtable_funcdef(st
, n
);
4881 symtable_exit_scope(st
);
4884 char *tmp
, *class_name
= STR(CHILD(n
, 1));
4885 symtable_add_def(st
, class_name
, DEF_LOCAL
);
4886 if (TYPE(CHILD(n
, 2)) == LPAR
) {
4887 node
*bases
= CHILD(n
, 3);
4889 for (i
= 0; i
< NCH(bases
); i
+= 2) {
4890 symtable_node(st
, CHILD(bases
, i
));
4893 symtable_enter_scope(st
, class_name
, TYPE(n
), n
->n_lineno
);
4894 tmp
= st
->st_private
;
4895 st
->st_private
= class_name
;
4896 symtable_node(st
, CHILD(n
, NCH(n
) - 1));
4897 st
->st_private
= tmp
;
4898 symtable_exit_scope(st
);
4902 for (i
= 0; i
+ 3 < NCH(n
); i
+= 4) {
4903 if (is_constant_false(NULL
, (CHILD(n
, i
+ 1)))) {
4904 if (st
->st_cur
->ste_generator
== 0)
4905 st
->st_cur
->ste_generator
=
4906 look_for_yield(CHILD(n
, i
+3));
4909 symtable_node(st
, CHILD(n
, i
+ 1));
4910 symtable_node(st
, CHILD(n
, i
+ 3));
4913 symtable_node(st
, CHILD(n
, i
+ 2));
4916 symtable_global(st
, n
);
4919 symtable_import(st
, n
);
4922 st
->st_cur
->ste_optimized
|= OPT_EXEC
;
4923 symtable_node(st
, CHILD(n
, 1));
4925 symtable_node(st
, CHILD(n
, 3));
4927 st
->st_cur
->ste_optimized
|= OPT_BARE_EXEC
;
4928 st
->st_cur
->ste_opt_lineno
= n
->n_lineno
;
4931 symtable_node(st
, CHILD(n
, 5));
4936 if (Py_OptimizeFlag
)
4942 symtable_node(st
, CHILD(n
, 1));
4948 symtable_assign(st
, CHILD(n
, 3), 0);
4955 symtable_assign(st
, CHILD(n
, 1), 0);
4958 st
->st_cur
->ste_generator
= 1;
4965 if (TYPE(CHILD(n
, 1)) == augassign
) {
4966 symtable_assign(st
, CHILD(n
, 0), 0);
4967 symtable_node(st
, CHILD(n
, 2));
4971 for (i
= 0; i
< NCH(n
) - 2; i
+= 2)
4972 symtable_assign(st
, CHILD(n
, i
), 0);
4973 n
= CHILD(n
, NCH(n
) - 1);
4977 /* watchout for fall-through logic below */
4984 if (NCH(n
) > 1 && TYPE(CHILD(n
, 1)) == list_for
) {
4986 symtable_list_comprehension(st
, CHILD(n
, 1));
4987 symtable_node(st
, CHILD(n
, 0));
4992 if (TYPE(n
) == atom
&& TYPE(CHILD(n
, 0)) == NAME
) {
4993 symtable_add_use(st
, STR(CHILD(n
, 0)));
4997 if (TYPE(n
) == for_stmt
) {
4998 symtable_assign(st
, CHILD(n
, 1), 0);
5006 for (i
= start
; i
< NCH(n
); ++i
)
5007 if (TYPE(CHILD(n
, i
)) >= single_input
)
5008 symtable_node(st
, CHILD(n
, i
));
5013 symtable_funcdef(struct symtable
*st
, node
*n
)
5017 if (TYPE(n
) == lambdef
) {
5019 symtable_params(st
, CHILD(n
, 1));
5021 symtable_params(st
, CHILD(n
, 2));
5022 body
= CHILD(n
, NCH(n
) - 1);
5023 symtable_node(st
, body
);
5026 /* The next two functions parse the argument tuple.
5027 symtable_default_arg() checks for names in the default arguments,
5028 which are references in the defining scope. symtable_params()
5029 parses the parameter names, which are defined in the function's
5033 (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] | '**' NAME)
5034 | fpdef ['=' test] (',' fpdef ['=' test])* [',']
5038 symtable_default_args(struct symtable
*st
, node
*n
)
5043 if (TYPE(n
) == parameters
) {
5045 if (TYPE(n
) == RPAR
)
5048 REQ(n
, varargslist
);
5049 for (i
= 0; i
< NCH(n
); i
+= 2) {
5051 if (TYPE(c
) == STAR
|| TYPE(c
) == DOUBLESTAR
) {
5054 if (i
> 0 && (TYPE(CHILD(n
, i
- 1)) == EQUAL
))
5055 symtable_node(st
, CHILD(n
, i
));
5060 symtable_params(struct symtable
*st
, node
*n
)
5062 int i
, complex = -1, ext
= 0;
5065 if (TYPE(n
) == parameters
) {
5067 if (TYPE(n
) == RPAR
)
5070 REQ(n
, varargslist
);
5071 for (i
= 0; i
< NCH(n
); i
+= 2) {
5073 if (TYPE(c
) == STAR
|| TYPE(c
) == DOUBLESTAR
) {
5077 if (TYPE(c
) == test
) {
5080 if (TYPE(CHILD(c
, 0)) == NAME
)
5081 symtable_add_def(st
, STR(CHILD(c
, 0)), DEF_PARAM
);
5084 sprintf(nbuf
, ".%d", i
);
5085 symtable_add_def(st
, nbuf
, DEF_PARAM
);
5091 if (TYPE(c
) == STAR
) {
5093 symtable_add_def(st
, STR(CHILD(n
, i
)),
5094 DEF_PARAM
| DEF_STAR
);
5101 if (c
&& TYPE(c
) == DOUBLESTAR
) {
5103 symtable_add_def(st
, STR(CHILD(n
, i
)),
5104 DEF_PARAM
| DEF_DOUBLESTAR
);
5109 for (j
= 0; j
<= complex; j
++) {
5111 if (TYPE(c
) == COMMA
)
5113 else if (TYPE(c
) == EQUAL
)
5114 c
= CHILD(n
, j
+= 3);
5115 if (TYPE(CHILD(c
, 0)) == LPAR
)
5116 symtable_params_fplist(st
, CHILD(c
, 1));
5122 symtable_params_fplist(struct symtable
*st
, node
*n
)
5128 for (i
= 0; i
< NCH(n
); i
+= 2) {
5132 symtable_add_def(st
, STR(CHILD(c
, 0)),
5133 DEF_PARAM
| DEF_INTUPLE
);
5135 symtable_params_fplist(st
, CHILD(c
, 1));
5141 symtable_global(struct symtable
*st
, node
*n
)
5145 /* XXX It might be helpful to warn about module-level global
5146 statements, but it's hard to tell the difference between
5147 module-level and a string passed to exec.
5150 for (i
= 1; i
< NCH(n
); i
+= 2) {
5151 char *name
= STR(CHILD(n
, i
));
5154 flags
= symtable_lookup(st
, name
);
5157 if (flags
&& flags
!= DEF_GLOBAL
) {
5159 if (flags
& DEF_PARAM
) {
5160 PyErr_Format(PyExc_SyntaxError
,
5161 "name '%.400s' is local and global",
5163 PyErr_SyntaxLocation(st
->st_filename
,
5164 st
->st_cur
->ste_lineno
);
5169 if (flags
& DEF_LOCAL
)
5170 sprintf(buf
, GLOBAL_AFTER_ASSIGN
,
5173 sprintf(buf
, GLOBAL_AFTER_USE
, name
);
5174 symtable_warn(st
, buf
);
5177 symtable_add_def(st
, name
, DEF_GLOBAL
);
5182 symtable_list_comprehension(struct symtable
*st
, node
*n
)
5186 sprintf(tmpname
, "_[%d]", st
->st_tmpname
);
5187 symtable_add_def(st
, tmpname
, DEF_LOCAL
);
5188 symtable_assign(st
, CHILD(n
, 1), 0);
5189 symtable_node(st
, CHILD(n
, 3));
5191 symtable_node(st
, CHILD(n
, 4));
5195 symtable_import(struct symtable
*st
, node
*n
)
5198 /* import_stmt: 'import' dotted_as_name (',' dotted_as_name)*
5199 | 'from' dotted_name 'import'
5200 ('*' | import_as_name (',' import_as_name)*)
5201 import_as_name: NAME [NAME NAME]
5203 if (STR(CHILD(n
, 0))[0] == 'f') { /* from */
5204 node
*dotname
= CHILD(n
, 1);
5205 if (strcmp(STR(CHILD(dotname
, 0)), "__future__") == 0) {
5206 /* check for bogus imports */
5207 if (n
->n_lineno
>= st
->st_future
->ff_last_lineno
) {
5208 PyErr_SetString(PyExc_SyntaxError
,
5210 PyErr_SyntaxLocation(st
->st_filename
,
5216 if (TYPE(CHILD(n
, 3)) == STAR
) {
5217 if (st
->st_cur
->ste_type
!= TYPE_MODULE
) {
5218 if (symtable_warn(st
,
5219 "import * only allowed at module level") < 0)
5222 st
->st_cur
->ste_optimized
|= OPT_IMPORT_STAR
;
5223 st
->st_cur
->ste_opt_lineno
= n
->n_lineno
;
5225 for (i
= 3; i
< NCH(n
); i
+= 2) {
5226 node
*c
= CHILD(n
, i
);
5227 if (NCH(c
) > 1) /* import as */
5228 symtable_assign(st
, CHILD(c
, 2),
5231 symtable_assign(st
, CHILD(c
, 0),
5236 for (i
= 1; i
< NCH(n
); i
+= 2) {
5237 symtable_assign(st
, CHILD(n
, i
), DEF_IMPORT
);
5243 symtable_assign(struct symtable
*st
, node
*n
, int flag
)
5251 /* invalid assignment, e.g. lambda x:x=2. The next
5252 pass will catch this error. */
5256 for (i
= 2; i
< NCH(n
); ++i
)
5257 if (TYPE(CHILD(n
, i
)) != DOUBLESTAR
)
5258 symtable_node(st
, CHILD(n
, i
));
5261 symtable_node(st
, CHILD(n
, 0));
5262 symtable_node(st
, CHILD(n
, 1));
5269 if (NCH(n
) > 1 && TYPE(CHILD(n
, 1)) == list_for
) {
5270 /* XXX This is an error, but the next pass
5274 for (i
= 0; i
< NCH(n
); i
+= 2)
5275 symtable_assign(st
, CHILD(n
, i
), flag
);
5286 for (i
= 0; i
< NCH(n
); i
+= 2)
5287 symtable_assign(st
, CHILD(n
, i
), flag
);
5293 if (TYPE(tmp
) == LPAR
|| TYPE(tmp
) == LSQB
) {
5296 } else if (TYPE(tmp
) == NAME
) {
5297 if (strcmp(STR(tmp
), "__debug__") == 0)
5298 symtable_warn(st
, ASSIGN_DEBUG
);
5299 symtable_add_def(st
, STR(tmp
), DEF_LOCAL
| flag
);
5302 case dotted_as_name
:
5304 symtable_add_def(st
, STR(CHILD(n
, 2)),
5307 symtable_add_def(st
,
5313 symtable_add_def(st
, STR(CHILD(n
, 0)), DEF_LOCAL
| flag
);
5316 symtable_add_def(st
, STR(n
), DEF_LOCAL
| flag
);
5325 /* Should only occur for errors like x + 1 = 1,
5326 which will be caught in the next pass. */
5327 for (i
= 0; i
< NCH(n
); ++i
)
5328 if (TYPE(CHILD(n
, i
)) >= single_input
)
5329 symtable_assign(st
, CHILD(n
, i
), flag
);