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 parameter 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 PyMemberDef 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_dealloc(PyCodeObject
*co
)
97 Py_XDECREF(co
->co_code
);
98 Py_XDECREF(co
->co_consts
);
99 Py_XDECREF(co
->co_names
);
100 Py_XDECREF(co
->co_varnames
);
101 Py_XDECREF(co
->co_freevars
);
102 Py_XDECREF(co
->co_cellvars
);
103 Py_XDECREF(co
->co_filename
);
104 Py_XDECREF(co
->co_name
);
105 Py_XDECREF(co
->co_lnotab
);
110 code_repr(PyCodeObject
*co
)
114 char *filename
= "???";
117 if (co
->co_firstlineno
!= 0)
118 lineno
= co
->co_firstlineno
;
119 if (co
->co_filename
&& PyString_Check(co
->co_filename
))
120 filename
= PyString_AS_STRING(co
->co_filename
);
121 if (co
->co_name
&& PyString_Check(co
->co_name
))
122 name
= PyString_AS_STRING(co
->co_name
);
123 PyOS_snprintf(buf
, sizeof(buf
),
124 "<code object %.100s at %p, file \"%.300s\", line %d>",
125 name
, co
, filename
, lineno
);
126 return PyString_FromString(buf
);
130 code_compare(PyCodeObject
*co
, PyCodeObject
*cp
)
133 cmp
= PyObject_Compare(co
->co_name
, cp
->co_name
);
135 cmp
= co
->co_argcount
- cp
->co_argcount
;
137 cmp
= co
->co_nlocals
- cp
->co_nlocals
;
139 cmp
= co
->co_flags
- cp
->co_flags
;
141 cmp
= PyObject_Compare(co
->co_code
, cp
->co_code
);
143 cmp
= PyObject_Compare(co
->co_consts
, cp
->co_consts
);
145 cmp
= PyObject_Compare(co
->co_names
, cp
->co_names
);
147 cmp
= PyObject_Compare(co
->co_varnames
, cp
->co_varnames
);
149 cmp
= PyObject_Compare(co
->co_freevars
, cp
->co_freevars
);
151 cmp
= PyObject_Compare(co
->co_cellvars
, cp
->co_cellvars
);
156 code_hash(PyCodeObject
*co
)
158 long h
, h0
, h1
, h2
, h3
, h4
, h5
, h6
;
159 h0
= PyObject_Hash(co
->co_name
);
160 if (h0
== -1) return -1;
161 h1
= PyObject_Hash(co
->co_code
);
162 if (h1
== -1) return -1;
163 h2
= PyObject_Hash(co
->co_consts
);
164 if (h2
== -1) return -1;
165 h3
= PyObject_Hash(co
->co_names
);
166 if (h3
== -1) return -1;
167 h4
= PyObject_Hash(co
->co_varnames
);
168 if (h4
== -1) return -1;
169 h5
= PyObject_Hash(co
->co_freevars
);
170 if (h5
== -1) return -1;
171 h6
= PyObject_Hash(co
->co_cellvars
);
172 if (h6
== -1) return -1;
173 h
= h0
^ h1
^ h2
^ h3
^ h4
^ h5
^ h6
^
174 co
->co_argcount
^ co
->co_nlocals
^ co
->co_flags
;
179 /* XXX code objects need to participate in GC? */
181 PyTypeObject PyCode_Type
= {
182 PyObject_HEAD_INIT(&PyType_Type
)
185 sizeof(PyCodeObject
),
187 (destructor
)code_dealloc
, /* tp_dealloc */
191 (cmpfunc
)code_compare
, /* tp_compare */
192 (reprfunc
)code_repr
, /* tp_repr */
193 0, /* tp_as_number */
194 0, /* tp_as_sequence */
195 0, /* tp_as_mapping */
196 (hashfunc
)code_hash
, /* tp_hash */
199 PyObject_GenericGetAttr
, /* tp_getattro */
201 0, /* tp_as_buffer */
202 Py_TPFLAGS_DEFAULT
, /* tp_flags */
206 0, /* tp_richcompare */
207 0, /* tp_weaklistoffset */
211 code_memberlist
, /* tp_members */
215 0, /* tp_descr_get */
216 0, /* tp_descr_set */
217 0, /* tp_dictoffset */
224 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
226 /* all_name_chars(s): true iff all chars in s are valid NAME_CHARS */
229 all_name_chars(unsigned char *s
)
231 static char ok_name_char
[256];
232 static unsigned char *name_chars
= (unsigned char *)NAME_CHARS
;
234 if (ok_name_char
[*name_chars
] == 0) {
236 for (p
= name_chars
; *p
; p
++)
237 ok_name_char
[*p
] = 1;
240 if (ok_name_char
[*s
++] == 0)
247 intern_strings(PyObject
*tuple
)
251 for (i
= PyTuple_GET_SIZE(tuple
); --i
>= 0; ) {
252 PyObject
*v
= PyTuple_GET_ITEM(tuple
, i
);
253 if (v
== NULL
|| !PyString_Check(v
)) {
254 Py_FatalError("non-string found in code slot");
255 PyErr_BadInternalCall();
258 PyString_InternInPlace(&PyTuple_GET_ITEM(tuple
, i
));
264 PyCode_New(int argcount
, int nlocals
, int stacksize
, int flags
,
265 PyObject
*code
, PyObject
*consts
, PyObject
*names
,
266 PyObject
*varnames
, PyObject
*freevars
, PyObject
*cellvars
,
267 PyObject
*filename
, PyObject
*name
, int firstlineno
,
272 /* Check argument types */
273 if (argcount
< 0 || nlocals
< 0 ||
275 consts
== NULL
|| !PyTuple_Check(consts
) ||
276 names
== NULL
|| !PyTuple_Check(names
) ||
277 varnames
== NULL
|| !PyTuple_Check(varnames
) ||
278 freevars
== NULL
|| !PyTuple_Check(freevars
) ||
279 cellvars
== NULL
|| !PyTuple_Check(cellvars
) ||
280 name
== NULL
|| !PyString_Check(name
) ||
281 filename
== NULL
|| !PyString_Check(filename
) ||
282 lnotab
== NULL
|| !PyString_Check(lnotab
) ||
283 !PyObject_CheckReadBuffer(code
)) {
284 PyErr_BadInternalCall();
287 intern_strings(names
);
288 intern_strings(varnames
);
289 if (freevars
== NULL
)
290 freevars
= PyTuple_New(0);
291 intern_strings(freevars
);
292 if (cellvars
== NULL
)
293 cellvars
= PyTuple_New(0);
294 intern_strings(cellvars
);
295 /* Intern selected string constants */
296 for (i
= PyTuple_Size(consts
); --i
>= 0; ) {
297 PyObject
*v
= PyTuple_GetItem(consts
, i
);
298 if (!PyString_Check(v
))
300 if (!all_name_chars((unsigned char *)PyString_AS_STRING(v
)))
302 PyString_InternInPlace(&PyTuple_GET_ITEM(consts
, i
));
304 co
= PyObject_NEW(PyCodeObject
, &PyCode_Type
);
306 co
->co_argcount
= argcount
;
307 co
->co_nlocals
= nlocals
;
308 co
->co_stacksize
= stacksize
;
309 co
->co_flags
= flags
;
313 co
->co_consts
= consts
;
315 co
->co_names
= names
;
317 co
->co_varnames
= varnames
;
319 co
->co_freevars
= freevars
;
321 co
->co_cellvars
= cellvars
;
323 co
->co_filename
= filename
;
326 co
->co_firstlineno
= firstlineno
;
328 co
->co_lnotab
= lnotab
;
334 /* Data structure used internally */
336 /* The compiler uses two passes to generate bytecodes. The first pass
337 builds the symbol table. The second pass generates the bytecode.
339 The first pass uses a single symtable struct. The second pass uses
340 a compiling struct for each code block. The compiling structs
341 share a reference to the symtable.
343 The two passes communicate via symtable_load_symbols() and via
344 is_local() and is_global(). The former initializes several slots
345 in the compiling struct: c_varnames, c_locals, c_nlocals,
346 c_argcount, c_globals, and c_flags.
349 /* All about c_lnotab.
351 c_lnotab is an array of unsigned bytes disguised as a Python string. In -O
352 mode, SET_LINENO opcodes aren't generated, and bytecode offsets are mapped
353 to source code line #s (when needed for tracebacks) via c_lnotab instead.
354 The array is conceptually a list of
355 (bytecode offset increment, line number increment)
356 pairs. The details are important and delicate, best illustrated by example:
358 byte code offset source code line number
365 The first trick is that these numbers aren't stored, only the increments
366 from one row to the next (this doesn't really work, but it's a start):
368 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
370 The second trick is that an unsigned byte can't hold negative values, or
371 values larger than 255, so (a) there's a deep assumption that byte code
372 offsets and their corresponding line #s both increase monotonically, and (b)
373 if at least one column jumps by more than 255 from one row to the next, more
374 than one pair is written to the table. In case #b, there's no way to know
375 from looking at the table later how many were written. That's the delicate
376 part. A user of c_lnotab desiring to find the source line number
377 corresponding to a bytecode address A should do something like this
380 for addr_incr, line_incr in c_lnotab:
386 In order for this to work, when the addr field increments by more than 255,
387 the line # increment in each pair generated must be 0 until the remaining addr
388 increment is < 256. So, in the example above, com_set_lineno should not (as
389 was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
390 255, 0, 45, 255, 0, 45.
394 PyObject
*c_code
; /* string */
395 PyObject
*c_consts
; /* list of objects */
396 PyObject
*c_const_dict
; /* inverse of c_consts */
397 PyObject
*c_names
; /* list of strings (names) */
398 PyObject
*c_name_dict
; /* inverse of c_names */
399 PyObject
*c_globals
; /* dictionary (value=None) */
400 PyObject
*c_locals
; /* dictionary (value=localID) */
401 PyObject
*c_varnames
; /* list (inverse of c_locals) */
402 PyObject
*c_freevars
; /* dictionary (value=None) */
403 PyObject
*c_cellvars
; /* list */
404 int c_nlocals
; /* index of next local */
405 int c_argcount
; /* number of top-level arguments */
406 int c_flags
; /* same as co_flags */
407 int c_nexti
; /* index into c_code */
408 int c_errors
; /* counts errors occurred */
409 int c_infunction
; /* set when compiling a function */
410 int c_interactive
; /* generating code for interactive command */
411 int c_loops
; /* counts nested loops */
412 int c_begin
; /* begin of current loop, for 'continue' */
413 int c_block
[CO_MAXBLOCKS
]; /* stack of block types */
414 int c_nblocks
; /* current block stack level */
415 char *c_filename
; /* filename of current node */
416 char *c_name
; /* name of object (e.g. function) */
417 int c_lineno
; /* Current line number */
418 int c_stacklevel
; /* Current stack level */
419 int c_maxstacklevel
; /* Maximum stack level */
421 PyObject
*c_lnotab
; /* Table mapping address to line number */
422 int c_last_addr
, c_last_line
, c_lnotab_next
;
423 char *c_private
; /* for private name mangling */
424 int c_tmpname
; /* temporary local name counter */
425 int c_nested
; /* Is block nested funcdef or lamdef? */
426 int c_closure
; /* Is nested w/freevars? */
427 struct symtable
*c_symtable
; /* pointer to module symbol table */
428 PyFutureFeatures
*c_future
; /* pointer to module's __future__ */
434 if ((v
& (USE
| DEF_FREE
))
435 && !(v
& (DEF_LOCAL
| DEF_PARAM
| DEF_GLOBAL
)))
437 if (v
& DEF_FREE_CLASS
)
443 com_error(struct compiling
*c
, PyObject
*exc
, char *msg
)
445 PyObject
*t
= NULL
, *v
= NULL
, *w
= NULL
, *line
= NULL
;
448 /* Error occurred via symtable call to
450 PyErr_SetString(exc
, msg
);
454 if (c
->c_lineno
< 1 || c
->c_interactive
) {
455 /* Unknown line number or interactive input */
456 PyErr_SetString(exc
, msg
);
459 v
= PyString_FromString(msg
);
461 return; /* MemoryError, too bad */
463 line
= PyErr_ProgramText(c
->c_filename
, c
->c_lineno
);
468 if (exc
== PyExc_SyntaxError
) {
469 t
= Py_BuildValue("(ziOO)", c
->c_filename
, c
->c_lineno
,
473 w
= Py_BuildValue("(OO)", v
, t
);
476 PyErr_SetObject(exc
, w
);
478 /* Make sure additional exceptions are printed with
479 file and line, also. */
480 PyErr_SetObject(exc
, v
);
481 PyErr_SyntaxLocation(c
->c_filename
, c
->c_lineno
);
490 /* Interface to the block stack */
493 block_push(struct compiling
*c
, int type
)
495 if (c
->c_nblocks
>= CO_MAXBLOCKS
) {
496 com_error(c
, PyExc_SystemError
,
497 "too many statically nested blocks");
500 c
->c_block
[c
->c_nblocks
++] = type
;
505 block_pop(struct compiling
*c
, int type
)
507 if (c
->c_nblocks
> 0)
509 if (c
->c_block
[c
->c_nblocks
] != type
&& c
->c_errors
== 0) {
510 com_error(c
, PyExc_SystemError
, "bad block pop");
514 /* Prototype forward declarations */
516 static int com_init(struct compiling
*, char *);
517 static void com_free(struct compiling
*);
518 static void com_push(struct compiling
*, int);
519 static void com_pop(struct compiling
*, int);
520 static void com_done(struct compiling
*);
521 static void com_node(struct compiling
*, node
*);
522 static void com_factor(struct compiling
*, node
*);
523 static void com_addbyte(struct compiling
*, int);
524 static void com_addint(struct compiling
*, int);
525 static void com_addoparg(struct compiling
*, int, int);
526 static void com_addfwref(struct compiling
*, int, int *);
527 static void com_backpatch(struct compiling
*, int);
528 static int com_add(struct compiling
*, PyObject
*, PyObject
*, PyObject
*);
529 static int com_addconst(struct compiling
*, PyObject
*);
530 static int com_addname(struct compiling
*, PyObject
*);
531 static void com_addopname(struct compiling
*, int, node
*);
532 static void com_list(struct compiling
*, node
*, int);
533 static void com_list_iter(struct compiling
*, node
*, node
*, char *);
534 static int com_argdefs(struct compiling
*, node
*);
535 static void com_assign(struct compiling
*, node
*, int, node
*);
536 static void com_assign_name(struct compiling
*, node
*, int);
537 static PyCodeObject
*icompile(node
*, struct compiling
*);
538 static PyCodeObject
*jcompile(node
*, char *, struct compiling
*,
540 static PyObject
*parsestrplus(struct compiling
*, node
*);
541 static PyObject
*parsestr(struct compiling
*, char *);
542 static node
*get_rawdocstring(node
*);
544 static int get_ref_type(struct compiling
*, char *);
546 /* symtable operations */
547 static int symtable_build(struct compiling
*, node
*);
548 static int symtable_load_symbols(struct compiling
*);
549 static struct symtable
*symtable_init(void);
550 static void symtable_enter_scope(struct symtable
*, char *, int, int);
551 static int symtable_exit_scope(struct symtable
*);
552 static int symtable_add_def(struct symtable
*, char *, int);
553 static int symtable_add_def_o(struct symtable
*, PyObject
*, PyObject
*, int);
555 static void symtable_node(struct symtable
*, node
*);
556 static void symtable_funcdef(struct symtable
*, node
*);
557 static void symtable_default_args(struct symtable
*, node
*);
558 static void symtable_params(struct symtable
*, node
*);
559 static void symtable_params_fplist(struct symtable
*, node
*n
);
560 static void symtable_global(struct symtable
*, node
*);
561 static void symtable_import(struct symtable
*, node
*);
562 static void symtable_assign(struct symtable
*, node
*, int);
563 static void symtable_list_comprehension(struct symtable
*, node
*);
565 static int symtable_update_free_vars(struct symtable
*);
566 static int symtable_undo_free(struct symtable
*, PyObject
*, PyObject
*);
567 static int symtable_check_global(struct symtable
*, PyObject
*, PyObject
*);
574 for (i
= 0; i
< pad
; ++i
)
575 fprintf(stderr
, " ");
579 dump(node
*n
, int pad
, int depth
)
585 fprintf(stderr
, "%d: %s\n", TYPE(n
), STR(n
));
588 for (i
= 0; i
< NCH(n
); ++i
)
589 dump(CHILD(n
, i
), pad
+ 1, depth
);
592 #define DUMP(N) dump(N, 0, -1)
595 com_init(struct compiling
*c
, char *filename
)
597 memset((void *)c
, '\0', sizeof(struct compiling
));
598 if ((c
->c_code
= PyString_FromStringAndSize((char *)NULL
,
601 if ((c
->c_consts
= PyList_New(0)) == NULL
)
603 if ((c
->c_const_dict
= PyDict_New()) == NULL
)
605 if ((c
->c_names
= PyList_New(0)) == NULL
)
607 if ((c
->c_name_dict
= PyDict_New()) == NULL
)
609 if ((c
->c_locals
= PyDict_New()) == NULL
)
611 if ((c
->c_lnotab
= PyString_FromStringAndSize((char *)NULL
,
615 c
->c_varnames
= NULL
;
616 c
->c_freevars
= NULL
;
617 c
->c_cellvars
= NULL
;
624 c
->c_interactive
= 0;
628 c
->c_filename
= filename
;
632 c
->c_maxstacklevel
= 0;
633 c
->c_firstlineno
= 0;
636 c
->c_lnotab_next
= 0;
640 c
->c_symtable
= NULL
;
649 com_free(struct compiling
*c
)
651 Py_XDECREF(c
->c_code
);
652 Py_XDECREF(c
->c_consts
);
653 Py_XDECREF(c
->c_const_dict
);
654 Py_XDECREF(c
->c_names
);
655 Py_XDECREF(c
->c_name_dict
);
656 Py_XDECREF(c
->c_globals
);
657 Py_XDECREF(c
->c_locals
);
658 Py_XDECREF(c
->c_varnames
);
659 Py_XDECREF(c
->c_freevars
);
660 Py_XDECREF(c
->c_cellvars
);
661 Py_XDECREF(c
->c_lnotab
);
663 PyMem_Free((void *)c
->c_future
);
667 com_push(struct compiling
*c
, int n
)
669 c
->c_stacklevel
+= n
;
670 if (c
->c_stacklevel
> c
->c_maxstacklevel
) {
671 c
->c_maxstacklevel
= c
->c_stacklevel
;
673 fprintf(stderr, "%s:%s:%d max stack nexti=%d level=%d n=%d\n",
674 c->c_filename, c->c_name, c->c_lineno,
675 c->c_nexti, c->c_stacklevel, n);
681 com_pop(struct compiling
*c
, int n
)
683 if (c
->c_stacklevel
< n
)
686 c
->c_stacklevel
-= n
;
690 com_done(struct compiling
*c
)
692 if (c
->c_code
!= NULL
)
693 _PyString_Resize(&c
->c_code
, c
->c_nexti
);
694 if (c
->c_lnotab
!= NULL
)
695 _PyString_Resize(&c
->c_lnotab
, c
->c_lnotab_next
);
699 com_check_size(PyObject
**s
, int offset
)
701 int len
= PyString_GET_SIZE(*s
);
703 return _PyString_Resize(s
, len
* 2);
708 com_addbyte(struct compiling
*c
, int byte
)
710 /*fprintf(stderr, "%3d: %3d\n", c->c_nexti, byte);*/
711 assert(byte
>= 0 && byte
<= 255);
713 if (com_check_size(&c
->c_code
, c
->c_nexti
)) {
717 PyString_AS_STRING(c
->c_code
)[c
->c_nexti
++] = byte
;
721 com_addint(struct compiling
*c
, int x
)
723 com_addbyte(c
, x
& 0xff);
724 com_addbyte(c
, x
>> 8); /* XXX x should be positive */
728 com_add_lnotab(struct compiling
*c
, int addr
, int line
)
731 if (c
->c_lnotab
== NULL
)
733 if (com_check_size(&c
->c_lnotab
, c
->c_lnotab_next
+ 2)) {
737 p
= PyString_AS_STRING(c
->c_lnotab
) + c
->c_lnotab_next
;
740 c
->c_lnotab_next
+= 2;
744 com_set_lineno(struct compiling
*c
, int lineno
)
746 c
->c_lineno
= lineno
;
747 if (c
->c_firstlineno
== 0) {
748 c
->c_firstlineno
= c
->c_last_line
= lineno
;
751 int incr_addr
= c
->c_nexti
- c
->c_last_addr
;
752 int incr_line
= lineno
- c
->c_last_line
;
753 while (incr_addr
> 255) {
754 com_add_lnotab(c
, 255, 0);
757 while (incr_line
> 255) {
758 com_add_lnotab(c
, incr_addr
, 255);
762 if (incr_addr
> 0 || incr_line
> 0)
763 com_add_lnotab(c
, incr_addr
, incr_line
);
764 c
->c_last_addr
= c
->c_nexti
;
765 c
->c_last_line
= lineno
;
770 com_addoparg(struct compiling
*c
, int op
, int arg
)
772 int extended_arg
= arg
>> 16;
773 if (op
== SET_LINENO
) {
774 com_set_lineno(c
, arg
);
779 com_addbyte(c
, EXTENDED_ARG
);
780 com_addint(c
, extended_arg
);
788 com_addfwref(struct compiling
*c
, int op
, int *p_anchor
)
790 /* Compile a forward reference for backpatching */
797 com_addint(c
, anchor
== 0 ? 0 : here
- anchor
);
801 com_backpatch(struct compiling
*c
, int anchor
)
803 unsigned char *code
= (unsigned char *) PyString_AS_STRING(c
->c_code
);
804 int target
= c
->c_nexti
;
808 /* Make the JUMP instruction at anchor point to target */
809 prev
= code
[anchor
] + (code
[anchor
+1] << 8);
810 dist
= target
- (anchor
+2);
811 code
[anchor
] = dist
& 0xff;
813 code
[anchor
+1] = dist
;
816 com_error(c
, PyExc_SystemError
,
817 "com_backpatch: offset too large");
826 /* Handle literals and names uniformly */
829 com_add(struct compiling
*c
, PyObject
*list
, PyObject
*dict
, PyObject
*v
)
831 PyObject
*w
, *t
, *np
=NULL
;
834 t
= Py_BuildValue("(OO)", v
, v
->ob_type
);
837 w
= PyDict_GetItem(dict
, t
);
841 n
= PyList_Size(list
);
842 np
= PyInt_FromLong(n
);
845 if (PyList_Append(list
, v
) != 0)
847 if (PyDict_SetItem(dict
, t
, np
) != 0)
861 com_addconst(struct compiling
*c
, PyObject
*v
)
863 return com_add(c
, c
->c_consts
, c
->c_const_dict
, v
);
867 com_addname(struct compiling
*c
, PyObject
*v
)
869 return com_add(c
, c
->c_names
, c
->c_name_dict
, v
);
873 mangle(char *p
, char *name
, char *buffer
, size_t maxlen
)
875 /* Name mangling: __private becomes _classname__private.
876 This is independent from how the name is used. */
878 if (p
== NULL
|| name
== NULL
|| name
[0] != '_' || name
[1] != '_')
881 if (nlen
+2 >= maxlen
)
882 return 0; /* Don't mangle __extremely_long_names */
883 if (name
[nlen
-1] == '_' && name
[nlen
-2] == '_')
884 return 0; /* Don't mangle __whatever__ */
885 /* Strip leading underscores from class name */
889 return 0; /* Don't mangle if class is just underscores */
891 if (plen
+ nlen
>= maxlen
)
892 plen
= maxlen
-nlen
-2; /* Truncate class name if too long */
893 /* buffer = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
895 strncpy(buffer
+1, p
, plen
);
896 strcpy(buffer
+1+plen
, name
);
901 com_addop_name(struct compiling
*c
, int op
, char *name
)
905 char buffer
[MANGLE_LEN
];
907 if (mangle(c
->c_private
, name
, buffer
, sizeof(buffer
)))
909 if (name
== NULL
|| (v
= PyString_InternFromString(name
)) == NULL
) {
914 i
= com_addname(c
, v
);
917 com_addoparg(c
, op
, i
);
921 #define NAME_GLOBAL 1
922 #define NAME_DEFAULT 2
923 #define NAME_CLOSURE 3
926 com_lookup_arg(PyObject
*dict
, PyObject
*name
)
928 PyObject
*v
= PyDict_GetItem(dict
, name
);
932 return PyInt_AS_LONG(v
);
936 com_addop_varname(struct compiling
*c
, int kind
, char *name
)
940 int scope
= NAME_DEFAULT
;
942 char buffer
[MANGLE_LEN
];
944 if (mangle(c
->c_private
, name
, buffer
, sizeof(buffer
)))
946 if (name
== NULL
|| (v
= PyString_InternFromString(name
)) == NULL
) {
952 reftype
= get_ref_type(c
, name
);
955 if (c
->c_symtable
->st_cur
->ste_type
== TYPE_FUNCTION
)
958 case GLOBAL_EXPLICIT
:
961 case GLOBAL_IMPLICIT
:
962 if (c
->c_flags
& CO_OPTIMIZED
)
967 scope
= NAME_CLOSURE
;
971 i
= com_addname(c
, v
);
972 if (scope
== NAME_LOCAL
)
973 i
= com_lookup_arg(c
->c_locals
, v
);
974 else if (reftype
== FREE
)
975 i
= com_lookup_arg(c
->c_freevars
, v
);
976 else if (reftype
== CELL
)
977 i
= com_lookup_arg(c
->c_cellvars
, v
);
979 c
->c_errors
++; /* XXX no exception set */
1029 case NAME_CLOSURE
: {
1031 PyOS_snprintf(buf
, sizeof(buf
),
1032 DEL_CLOSURE_ERROR
, name
);
1033 com_error(c
, PyExc_SyntaxError
, buf
);
1041 com_addoparg(c
, op
, i
);
1045 com_addopname(struct compiling
*c
, int op
, node
*n
)
1049 /* XXX it is possible to write this code without the 1000
1050 chars on the total length of dotted names, I just can't be
1051 bothered right now */
1052 if (TYPE(n
) == STAR
)
1054 else if (TYPE(n
) == dotted_name
) {
1058 for (i
= 0; i
< NCH(n
); i
+= 2) {
1059 char *s
= STR(CHILD(n
, i
));
1060 if (p
+ strlen(s
) > buffer
+ (sizeof buffer
) - 2) {
1061 com_error(c
, PyExc_MemoryError
,
1062 "dotted_name too long");
1069 p
= strchr(p
, '\0');
1076 com_addop_name(c
, op
, name
);
1080 parsenumber(struct compiling
*co
, char *s
)
1085 #ifndef WITHOUT_COMPLEX
1091 end
= s
+ strlen(s
) - 1;
1092 #ifndef WITHOUT_COMPLEX
1093 imflag
= *end
== 'j' || *end
== 'J';
1095 if (*end
== 'l' || *end
== 'L')
1096 return PyLong_FromString(s
, (char **)0, 0);
1098 x
= (long) PyOS_strtoul(s
, &end
, 0);
1100 x
= PyOS_strtol(s
, &end
, 0);
1103 return PyLong_FromString(s
, (char **)0, 0);
1104 return PyInt_FromLong(x
);
1106 /* XXX Huge floats may silently fail */
1107 #ifndef WITHOUT_COMPLEX
1110 PyFPE_START_PROTECT("atof", return 0)
1112 PyFPE_END_PROTECT(c
)
1113 return PyComplex_FromCComplex(c
);
1118 PyFPE_START_PROTECT("atof", return 0)
1120 PyFPE_END_PROTECT(dx
)
1121 return PyFloat_FromDouble(dx
);
1126 parsestr(struct compiling
*com
, char *s
)
1137 #ifdef Py_USING_UNICODE
1140 if (isalpha(quote
) || quote
== '_') {
1141 if (quote
== 'u' || quote
== 'U') {
1142 #ifdef Py_USING_UNICODE
1146 com_error(com
, PyExc_SyntaxError
,
1147 "Unicode literals not supported in this Python");
1151 if (quote
== 'r' || quote
== 'R') {
1156 if (quote
!= '\'' && quote
!= '\"') {
1157 PyErr_BadInternalCall();
1162 if (len
> INT_MAX
) {
1163 com_error(com
, PyExc_OverflowError
,
1164 "string to parse is too long");
1167 if (s
[--len
] != quote
) {
1168 PyErr_BadInternalCall();
1171 if (len
>= 4 && s
[0] == quote
&& s
[1] == quote
) {
1174 if (s
[--len
] != quote
|| s
[--len
] != quote
) {
1175 PyErr_BadInternalCall();
1179 #ifdef Py_USING_UNICODE
1180 if (unicode
|| Py_UnicodeFlag
) {
1182 v
= PyUnicode_DecodeRawUnicodeEscape(
1185 v
= PyUnicode_DecodeUnicodeEscape(
1188 PyErr_SyntaxLocation(com
->c_filename
, com
->c_lineno
);
1193 if (rawmode
|| strchr(s
, '\\') == NULL
)
1194 return PyString_FromStringAndSize(s
, len
);
1195 v
= PyString_FromStringAndSize((char *)NULL
, len
);
1198 p
= buf
= PyString_AsString(v
);
1207 /* XXX This assumes ASCII! */
1209 case '\\': *p
++ = '\\'; break;
1210 case '\'': *p
++ = '\''; break;
1211 case '\"': *p
++ = '\"'; break;
1212 case 'b': *p
++ = '\b'; break;
1213 case 'f': *p
++ = '\014'; break; /* FF */
1214 case 't': *p
++ = '\t'; break;
1215 case 'n': *p
++ = '\n'; break;
1216 case 'r': *p
++ = '\r'; break;
1217 case 'v': *p
++ = '\013'; break; /* VT */
1218 case 'a': *p
++ = '\007'; break; /* BEL, not classic C */
1219 case '0': case '1': case '2': case '3':
1220 case '4': case '5': case '6': case '7':
1222 if ('0' <= *s
&& *s
<= '7') {
1223 c
= (c
<<3) + *s
++ - '0';
1224 if ('0' <= *s
&& *s
<= '7')
1225 c
= (c
<<3) + *s
++ - '0';
1230 if (isxdigit(Py_CHARMASK(s
[0]))
1231 && isxdigit(Py_CHARMASK(s
[1]))) {
1233 c
= Py_CHARMASK(*s
);
1237 else if (islower(c
))
1242 c
= Py_CHARMASK(*s
);
1246 else if (islower(c
))
1254 com_error(com
, PyExc_ValueError
,
1255 "invalid \\x escape");
1263 _PyString_Resize(&v
, (int)(p
- buf
));
1268 parsestrplus(struct compiling
* c
, node
*n
)
1272 REQ(CHILD(n
, 0), STRING
);
1273 if ((v
= parsestr(c
, STR(CHILD(n
, 0)))) != NULL
) {
1274 /* String literal concatenation */
1275 for (i
= 1; i
< NCH(n
); i
++) {
1277 s
= parsestr(c
, STR(CHILD(n
, i
)));
1280 if (PyString_Check(v
) && PyString_Check(s
)) {
1281 PyString_ConcatAndDel(&v
, s
);
1285 #ifdef Py_USING_UNICODE
1288 temp
= PyUnicode_Concat(v
, s
);
1306 com_list_for(struct compiling
*c
, node
*n
, node
*e
, char *t
)
1309 int save_begin
= c
->c_begin
;
1311 /* list_iter: for v in expr [list_iter] */
1312 com_node(c
, CHILD(n
, 3)); /* expr */
1313 com_addbyte(c
, GET_ITER
);
1314 c
->c_begin
= c
->c_nexti
;
1315 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
1316 com_addfwref(c
, FOR_ITER
, &anchor
);
1318 com_assign(c
, CHILD(n
, 1), OP_ASSIGN
, NULL
);
1320 com_list_iter(c
, n
, e
, t
);
1322 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
1323 c
->c_begin
= save_begin
;
1324 com_backpatch(c
, anchor
);
1325 com_pop(c
, 1); /* FOR_ITER has popped this */
1329 com_list_if(struct compiling
*c
, node
*n
, node
*e
, char *t
)
1333 /* list_iter: 'if' test [list_iter] */
1334 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
1335 com_node(c
, CHILD(n
, 1));
1336 com_addfwref(c
, JUMP_IF_FALSE
, &a
);
1337 com_addbyte(c
, POP_TOP
);
1339 com_list_iter(c
, n
, e
, t
);
1340 com_addfwref(c
, JUMP_FORWARD
, &anchor
);
1341 com_backpatch(c
, a
);
1342 /* We jump here with an extra entry which we now pop */
1343 com_addbyte(c
, POP_TOP
);
1344 com_backpatch(c
, anchor
);
1348 com_list_iter(struct compiling
*c
,
1349 node
*p
, /* parent of list_iter node */
1350 node
*e
, /* element expression node */
1351 char *t
/* name of result list temp local */)
1353 /* list_iter is the last child in a listmaker, list_for, or list_if */
1354 node
*n
= CHILD(p
, NCH(p
)-1);
1355 if (TYPE(n
) == list_iter
) {
1359 com_list_for(c
, n
, e
, t
);
1362 com_list_if(c
, n
, e
, t
);
1365 com_error(c
, PyExc_SystemError
,
1366 "invalid list_iter node type");
1370 com_addop_varname(c
, VAR_LOAD
, t
);
1373 com_addoparg(c
, CALL_FUNCTION
, 1);
1374 com_addbyte(c
, POP_TOP
);
1380 com_list_comprehension(struct compiling
*c
, node
*n
)
1382 /* listmaker: test list_for */
1384 PyOS_snprintf(tmpname
, sizeof(tmpname
), "_[%d]", ++c
->c_tmpname
);
1385 com_addoparg(c
, BUILD_LIST
, 0);
1386 com_addbyte(c
, DUP_TOP
); /* leave the result on the stack */
1388 com_addop_name(c
, LOAD_ATTR
, "append");
1389 com_addop_varname(c
, VAR_STORE
, tmpname
);
1391 com_list_for(c
, CHILD(n
, 1), CHILD(n
, 0), tmpname
);
1392 com_addop_varname(c
, VAR_DELETE
, tmpname
);
1397 com_listmaker(struct compiling
*c
, node
*n
)
1399 /* listmaker: test ( list_for | (',' test)* [','] ) */
1400 if (NCH(n
) > 1 && TYPE(CHILD(n
, 1)) == list_for
)
1401 com_list_comprehension(c
, n
);
1405 for (i
= 0; i
< NCH(n
); i
+= 2, len
++)
1406 com_node(c
, CHILD(n
, i
));
1407 com_addoparg(c
, BUILD_LIST
, len
);
1413 com_dictmaker(struct compiling
*c
, node
*n
)
1416 /* dictmaker: test ':' test (',' test ':' value)* [','] */
1417 for (i
= 0; i
+2 < NCH(n
); i
+= 4) {
1418 /* We must arrange things just right for STORE_SUBSCR.
1419 It wants the stack to look like (value) (dict) (key) */
1420 com_addbyte(c
, DUP_TOP
);
1422 com_node(c
, CHILD(n
, i
+2)); /* value */
1423 com_addbyte(c
, ROT_TWO
);
1424 com_node(c
, CHILD(n
, i
)); /* key */
1425 com_addbyte(c
, STORE_SUBSCR
);
1431 com_atom(struct compiling
*c
, node
*n
)
1440 if (TYPE(CHILD(n
, 1)) == RPAR
) {
1441 com_addoparg(c
, BUILD_TUPLE
, 0);
1445 com_node(c
, CHILD(n
, 1));
1447 case LSQB
: /* '[' [listmaker] ']' */
1448 if (TYPE(CHILD(n
, 1)) == RSQB
) {
1449 com_addoparg(c
, BUILD_LIST
, 0);
1453 com_listmaker(c
, CHILD(n
, 1));
1455 case LBRACE
: /* '{' [dictmaker] '}' */
1456 com_addoparg(c
, BUILD_MAP
, 0);
1458 if (TYPE(CHILD(n
, 1)) == dictmaker
)
1459 com_dictmaker(c
, CHILD(n
, 1));
1462 com_node(c
, CHILD(n
, 1));
1463 com_addbyte(c
, UNARY_CONVERT
);
1466 if ((v
= parsenumber(c
, STR(ch
))) == NULL
) {
1470 i
= com_addconst(c
, v
);
1473 com_addoparg(c
, LOAD_CONST
, i
);
1477 v
= parsestrplus(c
, n
);
1483 i
= com_addconst(c
, v
);
1486 com_addoparg(c
, LOAD_CONST
, i
);
1490 com_addop_varname(c
, VAR_LOAD
, STR(ch
));
1494 com_error(c
, PyExc_SystemError
,
1495 "com_atom: unexpected node type");
1500 com_slice(struct compiling
*c
, node
*n
, int op
)
1505 else if (NCH(n
) == 2) {
1506 if (TYPE(CHILD(n
, 0)) != COLON
) {
1507 com_node(c
, CHILD(n
, 0));
1508 com_addbyte(c
, op
+1);
1511 com_node(c
, CHILD(n
, 1));
1512 com_addbyte(c
, op
+2);
1517 com_node(c
, CHILD(n
, 0));
1518 com_node(c
, CHILD(n
, 2));
1519 com_addbyte(c
, op
+3);
1525 com_augassign_slice(struct compiling
*c
, node
*n
, int opcode
, node
*augn
)
1528 com_addbyte(c
, DUP_TOP
);
1530 com_addbyte(c
, SLICE
);
1532 com_addbyte(c
, opcode
);
1534 com_addbyte(c
, ROT_TWO
);
1535 com_addbyte(c
, STORE_SLICE
);
1537 } else if (NCH(n
) == 2 && TYPE(CHILD(n
, 0)) != COLON
) {
1538 com_node(c
, CHILD(n
, 0));
1539 com_addoparg(c
, DUP_TOPX
, 2);
1541 com_addbyte(c
, SLICE
+1);
1544 com_addbyte(c
, opcode
);
1546 com_addbyte(c
, ROT_THREE
);
1547 com_addbyte(c
, STORE_SLICE
+1);
1549 } else if (NCH(n
) == 2) {
1550 com_node(c
, CHILD(n
, 1));
1551 com_addoparg(c
, DUP_TOPX
, 2);
1553 com_addbyte(c
, SLICE
+2);
1556 com_addbyte(c
, opcode
);
1558 com_addbyte(c
, ROT_THREE
);
1559 com_addbyte(c
, STORE_SLICE
+2);
1562 com_node(c
, CHILD(n
, 0));
1563 com_node(c
, CHILD(n
, 2));
1564 com_addoparg(c
, DUP_TOPX
, 3);
1566 com_addbyte(c
, SLICE
+3);
1569 com_addbyte(c
, opcode
);
1571 com_addbyte(c
, ROT_FOUR
);
1572 com_addbyte(c
, STORE_SLICE
+3);
1578 com_argument(struct compiling
*c
, node
*n
, PyObject
**pkeywords
)
1581 REQ(n
, argument
); /* [test '='] test; really [keyword '='] test */
1583 if (*pkeywords
!= NULL
) {
1584 com_error(c
, PyExc_SyntaxError
,
1585 "non-keyword arg after keyword arg");
1588 com_node(c
, CHILD(n
, 0));
1595 } while (NCH(m
) == 1);
1596 if (TYPE(m
) != NAME
) {
1597 /* f(lambda x: x[0] = 3) ends up getting parsed with
1598 * LHS test = lambda x: x[0], and RHS test = 3.
1599 * SF bug 132313 points out that complaining about a keyword
1600 * then is very confusing.
1602 com_error(c
, PyExc_SyntaxError
,
1603 TYPE(m
) == lambdef
?
1604 "lambda cannot contain assignment" :
1605 "keyword can't be an expression");
1608 PyObject
*v
= PyString_InternFromString(STR(m
));
1609 if (v
!= NULL
&& *pkeywords
== NULL
)
1610 *pkeywords
= PyDict_New();
1613 else if (*pkeywords
== NULL
) {
1617 if (PyDict_GetItem(*pkeywords
, v
) != NULL
)
1618 com_error(c
, PyExc_SyntaxError
,
1619 "duplicate keyword argument");
1621 if (PyDict_SetItem(*pkeywords
, v
, v
) != 0)
1623 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, v
));
1628 com_node(c
, CHILD(n
, 2));
1632 com_call_function(struct compiling
*c
, node
*n
)
1634 if (TYPE(n
) == RPAR
) {
1635 com_addoparg(c
, CALL_FUNCTION
, 0);
1638 PyObject
*keywords
= NULL
;
1640 int lineno
= n
->n_lineno
;
1642 int starstar_flag
= 0;
1647 for (i
= 0; i
< NCH(n
); i
+= 2) {
1648 node
*ch
= CHILD(n
, i
);
1649 if (TYPE(ch
) == STAR
||
1650 TYPE(ch
) == DOUBLESTAR
)
1652 if (ch
->n_lineno
!= lineno
) {
1653 lineno
= ch
->n_lineno
;
1654 com_addoparg(c
, SET_LINENO
, lineno
);
1656 com_argument(c
, ch
, &keywords
);
1657 if (keywords
== NULL
)
1662 Py_XDECREF(keywords
);
1663 while (i
< NCH(n
)) {
1664 node
*tok
= CHILD(n
, i
);
1665 node
*ch
= CHILD(n
, i
+1);
1667 switch (TYPE(tok
)) {
1668 case STAR
: star_flag
= 1; break;
1669 case DOUBLESTAR
: starstar_flag
= 1; break;
1673 if (na
> 255 || nk
> 255) {
1674 com_error(c
, PyExc_SyntaxError
,
1675 "more than 255 arguments");
1677 if (star_flag
|| starstar_flag
)
1678 opcode
= CALL_FUNCTION_VAR
- 1 +
1679 star_flag
+ (starstar_flag
<< 1);
1681 opcode
= CALL_FUNCTION
;
1682 com_addoparg(c
, opcode
, na
| (nk
<< 8));
1683 com_pop(c
, na
+ 2*nk
+ star_flag
+ starstar_flag
);
1688 com_select_member(struct compiling
*c
, node
*n
)
1690 com_addopname(c
, LOAD_ATTR
, n
);
1694 com_sliceobj(struct compiling
*c
, node
*n
)
1697 int ns
=2; /* number of slice arguments */
1700 /* first argument */
1701 if (TYPE(CHILD(n
,i
)) == COLON
) {
1702 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1707 com_node(c
, CHILD(n
,i
));
1709 REQ(CHILD(n
,i
),COLON
);
1712 /* second argument */
1713 if (i
< NCH(n
) && TYPE(CHILD(n
,i
)) == test
) {
1714 com_node(c
, CHILD(n
,i
));
1718 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1721 /* remaining arguments */
1722 for (; i
< NCH(n
); i
++) {
1727 /* right argument of ':' missing */
1728 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1732 com_node(c
, CHILD(ch
,1));
1734 com_addoparg(c
, BUILD_SLICE
, ns
);
1735 com_pop(c
, 1 + (ns
== 3));
1739 com_subscript(struct compiling
*c
, node
*n
)
1744 /* check for rubber index */
1745 if (TYPE(ch
) == DOT
&& TYPE(CHILD(n
,1)) == DOT
) {
1746 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_Ellipsis
));
1750 /* check for slice */
1751 if ((TYPE(ch
) == COLON
|| NCH(n
) > 1))
1761 com_subscriptlist(struct compiling
*c
, node
*n
, int assigning
, node
*augn
)
1764 REQ(n
, subscriptlist
);
1765 /* Check to make backward compatible slice behavior for '[i:j]' */
1767 node
*sub
= CHILD(n
, 0); /* subscript */
1768 /* 'Basic' slice, should have exactly one colon. */
1769 if ((TYPE(CHILD(sub
, 0)) == COLON
1770 || (NCH(sub
) > 1 && TYPE(CHILD(sub
, 1)) == COLON
))
1771 && (TYPE(CHILD(sub
,NCH(sub
)-1)) != sliceop
))
1773 switch (assigning
) {
1784 com_augassign_slice(c
, sub
, assigning
, augn
);
1787 com_slice(c
, sub
, op
);
1788 if (op
== STORE_SLICE
)
1790 else if (op
== DELETE_SLICE
)
1795 /* Else normal subscriptlist. Compile each subscript. */
1796 for (i
= 0; i
< NCH(n
); i
+= 2)
1797 com_subscript(c
, CHILD(n
, i
));
1798 /* Put multiple subscripts into a tuple */
1801 com_addoparg(c
, BUILD_TUPLE
, i
);
1804 switch (assigning
) {
1819 if (assigning
> OP_APPLY
) {
1820 com_addoparg(c
, DUP_TOPX
, 2);
1822 com_addbyte(c
, BINARY_SUBSCR
);
1825 com_addbyte(c
, assigning
);
1827 com_addbyte(c
, ROT_THREE
);
1834 com_apply_trailer(struct compiling
*c
, node
*n
)
1837 switch (TYPE(CHILD(n
, 0))) {
1839 com_call_function(c
, CHILD(n
, 1));
1842 com_select_member(c
, CHILD(n
, 1));
1845 com_subscriptlist(c
, CHILD(n
, 1), OP_APPLY
, NULL
);
1848 com_error(c
, PyExc_SystemError
,
1849 "com_apply_trailer: unknown trailer type");
1854 com_power(struct compiling
*c
, node
*n
)
1858 com_atom(c
, CHILD(n
, 0));
1859 for (i
= 1; i
< NCH(n
); i
++) {
1860 if (TYPE(CHILD(n
, i
)) == DOUBLESTAR
) {
1861 com_factor(c
, CHILD(n
, i
+1));
1862 com_addbyte(c
, BINARY_POWER
);
1867 com_apply_trailer(c
, CHILD(n
, i
));
1872 com_invert_constant(struct compiling
*c
, node
*n
)
1874 /* Compute the inverse of int and longs and use them directly,
1875 but be prepared to generate code for all other
1876 possibilities (invalid numbers, floats, complex).
1878 PyObject
*num
, *inv
= NULL
;
1882 num
= parsenumber(c
, STR(n
));
1886 inv
= PyNumber_Invert(num
);
1889 i
= com_addconst(c
, num
);
1891 i
= com_addconst(c
, inv
);
1896 com_addoparg(c
, LOAD_CONST
, i
);
1898 if (num
!= NULL
&& inv
== NULL
)
1899 com_addbyte(c
, UNARY_INVERT
);
1903 is_float_zero(const char *p
)
1905 int found_radix_point
= 0;
1907 while ((ch
= Py_CHARMASK(*p
++)) != '\0') {
1910 /* no reason to believe it's not 0 -- continue */
1913 case 'e': case 'E': case 'j': case 'J':
1914 /* If this was a hex constant, we already would have
1915 returned 0 due to the 'x' or 'X', so 'e' or 'E'
1916 must be an exponent marker, and we haven't yet
1917 seen a non-zero digit, and it doesn't matter what
1918 the exponent is then. For 'j' or 'J' similarly,
1919 except that this is an imaginary 0 then. */
1923 found_radix_point
= 1;
1930 return found_radix_point
;
1934 com_factor(struct compiling
*c
, node
*n
)
1936 int childtype
= TYPE(CHILD(n
, 0));
1937 node
*pfactor
, *ppower
, *patom
, *pnum
;
1939 /* If the unary +, -, or ~ operator is applied to a constant,
1940 don't generate a UNARY_xxx opcode. Just store the
1941 approriate value as a constant. If the value is negative,
1942 extend the string containing the constant and insert a
1943 negative in the 0th position -- unless we're doing unary minus
1944 of a floating zero! In that case the sign is significant, but
1945 the const dict can't distinguish +0.0 from -0.0.
1947 if ((childtype
== PLUS
|| childtype
== MINUS
|| childtype
== TILDE
)
1949 && TYPE((pfactor
= CHILD(n
, 1))) == factor
1950 && NCH(pfactor
) == 1
1951 && TYPE((ppower
= CHILD(pfactor
, 0))) == power
1953 && TYPE((patom
= CHILD(ppower
, 0))) == atom
1954 && TYPE((pnum
= CHILD(patom
, 0))) == NUMBER
1955 && !(childtype
== MINUS
&& is_float_zero(STR(pnum
)))) {
1956 if (childtype
== TILDE
) {
1957 com_invert_constant(c
, pnum
);
1960 if (childtype
== MINUS
) {
1961 char *s
= malloc(strlen(STR(pnum
)) + 2);
1963 com_error(c
, PyExc_MemoryError
, "");
1964 com_addbyte(c
, 255);
1968 strcpy(s
+ 1, STR(pnum
));
1974 else if (childtype
== PLUS
) {
1975 com_factor(c
, CHILD(n
, 1));
1976 com_addbyte(c
, UNARY_POSITIVE
);
1978 else if (childtype
== MINUS
) {
1979 com_factor(c
, CHILD(n
, 1));
1980 com_addbyte(c
, UNARY_NEGATIVE
);
1982 else if (childtype
== TILDE
) {
1983 com_factor(c
, CHILD(n
, 1));
1984 com_addbyte(c
, UNARY_INVERT
);
1987 com_power(c
, CHILD(n
, 0));
1992 com_term(struct compiling
*c
, node
*n
)
1997 com_factor(c
, CHILD(n
, 0));
1998 for (i
= 2; i
< NCH(n
); i
+= 2) {
1999 com_factor(c
, CHILD(n
, i
));
2000 switch (TYPE(CHILD(n
, i
-1))) {
2002 op
= BINARY_MULTIPLY
;
2005 if (c
->c_flags
& CO_FUTURE_DIVISION
)
2006 op
= BINARY_TRUE_DIVIDE
;
2014 op
= BINARY_FLOOR_DIVIDE
;
2017 com_error(c
, PyExc_SystemError
,
2018 "com_term: operator not *, /, // or %");
2027 com_arith_expr(struct compiling
*c
, node
*n
)
2032 com_term(c
, CHILD(n
, 0));
2033 for (i
= 2; i
< NCH(n
); i
+= 2) {
2034 com_term(c
, CHILD(n
, i
));
2035 switch (TYPE(CHILD(n
, i
-1))) {
2040 op
= BINARY_SUBTRACT
;
2043 com_error(c
, PyExc_SystemError
,
2044 "com_arith_expr: operator not + or -");
2053 com_shift_expr(struct compiling
*c
, node
*n
)
2058 com_arith_expr(c
, CHILD(n
, 0));
2059 for (i
= 2; i
< NCH(n
); i
+= 2) {
2060 com_arith_expr(c
, CHILD(n
, i
));
2061 switch (TYPE(CHILD(n
, i
-1))) {
2069 com_error(c
, PyExc_SystemError
,
2070 "com_shift_expr: operator not << or >>");
2079 com_and_expr(struct compiling
*c
, node
*n
)
2084 com_shift_expr(c
, CHILD(n
, 0));
2085 for (i
= 2; i
< NCH(n
); i
+= 2) {
2086 com_shift_expr(c
, CHILD(n
, i
));
2087 if (TYPE(CHILD(n
, i
-1)) == AMPER
) {
2091 com_error(c
, PyExc_SystemError
,
2092 "com_and_expr: operator not &");
2101 com_xor_expr(struct compiling
*c
, node
*n
)
2106 com_and_expr(c
, CHILD(n
, 0));
2107 for (i
= 2; i
< NCH(n
); i
+= 2) {
2108 com_and_expr(c
, CHILD(n
, i
));
2109 if (TYPE(CHILD(n
, i
-1)) == CIRCUMFLEX
) {
2113 com_error(c
, PyExc_SystemError
,
2114 "com_xor_expr: operator not ^");
2123 com_expr(struct compiling
*c
, node
*n
)
2128 com_xor_expr(c
, CHILD(n
, 0));
2129 for (i
= 2; i
< NCH(n
); i
+= 2) {
2130 com_xor_expr(c
, CHILD(n
, i
));
2131 if (TYPE(CHILD(n
, i
-1)) == VBAR
) {
2135 com_error(c
, PyExc_SystemError
,
2136 "com_expr: expr operator not |");
2148 /* comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '=='
2149 | 'in' | 'not' 'in' | 'is' | 'is' not' */
2153 case LESS
: return LT
;
2154 case GREATER
: return GT
;
2155 case EQEQUAL
: /* == */
2156 case EQUAL
: return EQ
;
2157 case LESSEQUAL
: return LE
;
2158 case GREATEREQUAL
: return GE
;
2159 case NOTEQUAL
: return NE
; /* <> or != */
2160 case NAME
: if (strcmp(STR(n
), "in") == 0) return IN
;
2161 if (strcmp(STR(n
), "is") == 0) return IS
;
2164 else if (NCH(n
) == 2) {
2165 switch (TYPE(CHILD(n
, 0))) {
2166 case NAME
: if (strcmp(STR(CHILD(n
, 1)), "in") == 0)
2168 if (strcmp(STR(CHILD(n
, 0)), "is") == 0)
2176 com_comparison(struct compiling
*c
, node
*n
)
2181 REQ(n
, comparison
); /* comparison: expr (comp_op expr)* */
2182 com_expr(c
, CHILD(n
, 0));
2186 /****************************************************************
2187 The following code is generated for all but the last
2188 comparison in a chain:
2190 label: on stack: opcode: jump to:
2196 b, 0-or-1 JUMP_IF_FALSE L1
2200 We are now ready to repeat this sequence for the next
2201 comparison in the chain.
2203 For the last we generate:
2209 If there were any jumps to L1 (i.e., there was more than one
2210 comparison), we generate:
2212 0-or-1 JUMP_FORWARD L2
2217 ****************************************************************/
2221 for (i
= 2; i
< NCH(n
); i
+= 2) {
2222 com_expr(c
, CHILD(n
, i
));
2224 com_addbyte(c
, DUP_TOP
);
2226 com_addbyte(c
, ROT_THREE
);
2228 op
= cmp_type(CHILD(n
, i
-1));
2230 com_error(c
, PyExc_SystemError
,
2231 "com_comparison: unknown comparison op");
2233 com_addoparg(c
, COMPARE_OP
, op
);
2236 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
2237 com_addbyte(c
, POP_TOP
);
2244 com_addfwref(c
, JUMP_FORWARD
, &anchor2
);
2245 com_backpatch(c
, anchor
);
2246 com_addbyte(c
, ROT_TWO
);
2247 com_addbyte(c
, POP_TOP
);
2248 com_backpatch(c
, anchor2
);
2253 com_not_test(struct compiling
*c
, node
*n
)
2255 REQ(n
, not_test
); /* 'not' not_test | comparison */
2257 com_comparison(c
, CHILD(n
, 0));
2260 com_not_test(c
, CHILD(n
, 1));
2261 com_addbyte(c
, UNARY_NOT
);
2266 com_and_test(struct compiling
*c
, node
*n
)
2270 REQ(n
, and_test
); /* not_test ('and' not_test)* */
2274 com_not_test(c
, CHILD(n
, i
));
2275 if ((i
+= 2) >= NCH(n
))
2277 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
2278 com_addbyte(c
, POP_TOP
);
2282 com_backpatch(c
, anchor
);
2286 com_make_closure(struct compiling
*c
, PyCodeObject
*co
)
2288 int i
, free
= PyCode_GetNumFree(co
);
2291 for (i
= 0; i
< free
; ++i
) {
2292 /* Bypass com_addop_varname because it will generate
2293 LOAD_DEREF but LOAD_CLOSURE is needed.
2295 PyObject
*name
= PyTuple_GET_ITEM(co
->co_freevars
, i
);
2298 /* Special case: If a class contains a method with a
2299 free variable that has the same name as a method,
2300 the name will be considered free *and* local in the
2301 class. It should be handled by the closure, as
2302 well as by the normal name loookup logic.
2304 reftype
= get_ref_type(c
, PyString_AS_STRING(name
));
2305 if (reftype
== CELL
)
2306 arg
= com_lookup_arg(c
->c_cellvars
, name
);
2307 else /* (reftype == FREE) */
2308 arg
= com_lookup_arg(c
->c_freevars
, name
);
2310 fprintf(stderr
, "lookup %s in %s %d %d\n"
2311 "freevars of %s: %s\n",
2312 PyObject_REPR(name
),
2315 PyString_AS_STRING(co
->co_name
),
2316 PyObject_REPR(co
->co_freevars
));
2317 Py_FatalError("com_make_closure()");
2319 com_addoparg(c
, LOAD_CLOSURE
, arg
);
2327 com_test(struct compiling
*c
, node
*n
)
2329 REQ(n
, test
); /* and_test ('or' and_test)* | lambdef */
2330 if (NCH(n
) == 1 && TYPE(CHILD(n
, 0)) == lambdef
) {
2333 int ndefs
= com_argdefs(c
, CHILD(n
, 0));
2334 symtable_enter_scope(c
->c_symtable
, "lambda", lambdef
,
2336 co
= icompile(CHILD(n
, 0), c
);
2341 symtable_exit_scope(c
->c_symtable
);
2342 i
= com_addconst(c
, (PyObject
*)co
);
2343 closure
= com_make_closure(c
, co
);
2344 com_addoparg(c
, LOAD_CONST
, i
);
2347 com_addoparg(c
, MAKE_CLOSURE
, ndefs
);
2348 com_pop(c
, PyCode_GetNumFree(co
));
2350 com_addoparg(c
, MAKE_FUNCTION
, ndefs
);
2358 com_and_test(c
, CHILD(n
, i
));
2359 if ((i
+= 2) >= NCH(n
))
2361 com_addfwref(c
, JUMP_IF_TRUE
, &anchor
);
2362 com_addbyte(c
, POP_TOP
);
2366 com_backpatch(c
, anchor
);
2371 com_list(struct compiling
*c
, node
*n
, int toplevel
)
2373 /* exprlist: expr (',' expr)* [',']; likewise for testlist */
2374 if (NCH(n
) == 1 && !toplevel
) {
2375 com_node(c
, CHILD(n
, 0));
2380 len
= (NCH(n
) + 1) / 2;
2381 for (i
= 0; i
< NCH(n
); i
+= 2)
2382 com_node(c
, CHILD(n
, i
));
2383 com_addoparg(c
, BUILD_TUPLE
, len
);
2389 /* Begin of assignment compilation */
2393 com_augassign_attr(struct compiling
*c
, node
*n
, int opcode
, node
*augn
)
2395 com_addbyte(c
, DUP_TOP
);
2397 com_addopname(c
, LOAD_ATTR
, n
);
2399 com_addbyte(c
, opcode
);
2401 com_addbyte(c
, ROT_TWO
);
2402 com_addopname(c
, STORE_ATTR
, n
);
2407 com_assign_attr(struct compiling
*c
, node
*n
, int assigning
)
2409 com_addopname(c
, assigning
? STORE_ATTR
: DELETE_ATTR
, n
);
2410 com_pop(c
, assigning
? 2 : 1);
2414 com_assign_trailer(struct compiling
*c
, node
*n
, int assigning
, node
*augn
)
2417 switch (TYPE(CHILD(n
, 0))) {
2418 case LPAR
: /* '(' [exprlist] ')' */
2419 com_error(c
, PyExc_SyntaxError
,
2420 "can't assign to function call");
2422 case DOT
: /* '.' NAME */
2423 if (assigning
> OP_APPLY
)
2424 com_augassign_attr(c
, CHILD(n
, 1), assigning
, augn
);
2426 com_assign_attr(c
, CHILD(n
, 1), assigning
);
2428 case LSQB
: /* '[' subscriptlist ']' */
2429 com_subscriptlist(c
, CHILD(n
, 1), assigning
, augn
);
2432 com_error(c
, PyExc_SystemError
, "unknown trailer type");
2437 com_assign_sequence(struct compiling
*c
, node
*n
, int assigning
)
2440 if (TYPE(n
) != testlist
&& TYPE(n
) != listmaker
)
2444 com_addoparg(c
, UNPACK_SEQUENCE
, i
);
2447 for (i
= 0; i
< NCH(n
); i
+= 2)
2448 com_assign(c
, CHILD(n
, i
), assigning
, NULL
);
2452 com_augassign_name(struct compiling
*c
, node
*n
, int opcode
, node
*augn
)
2455 com_addop_varname(c
, VAR_LOAD
, STR(n
));
2458 com_addbyte(c
, opcode
);
2460 com_assign_name(c
, n
, OP_ASSIGN
);
2464 com_assign_name(struct compiling
*c
, node
*n
, int assigning
)
2467 com_addop_varname(c
, assigning
? VAR_STORE
: VAR_DELETE
, STR(n
));
2473 com_assign(struct compiling
*c
, node
*n
, int assigning
, node
*augn
)
2475 /* Loop to avoid trivial recursion */
2482 if (assigning
> OP_APPLY
) {
2483 com_error(c
, PyExc_SyntaxError
,
2484 "augmented assign to tuple not possible");
2487 com_assign_sequence(c
, n
, assigning
);
2505 com_error(c
, PyExc_SyntaxError
,
2506 "can't assign to operator");
2512 case power
: /* atom trailer* ('**' power)*
2513 ('+'|'-'|'~') factor | atom trailer* */
2514 if (TYPE(CHILD(n
, 0)) != atom
) {
2515 com_error(c
, PyExc_SyntaxError
,
2516 "can't assign to operator");
2519 if (NCH(n
) > 1) { /* trailer or exponent present */
2521 com_node(c
, CHILD(n
, 0));
2522 for (i
= 1; i
+1 < NCH(n
); i
++) {
2523 if (TYPE(CHILD(n
, i
)) == DOUBLESTAR
) {
2524 com_error(c
, PyExc_SyntaxError
,
2525 "can't assign to operator");
2528 com_apply_trailer(c
, CHILD(n
, i
));
2529 } /* NB i is still alive */
2530 com_assign_trailer(c
,
2531 CHILD(n
, i
), assigning
, augn
);
2538 switch (TYPE(CHILD(n
, 0))) {
2541 if (TYPE(n
) == RPAR
) {
2542 /* XXX Should allow () = () ??? */
2543 com_error(c
, PyExc_SyntaxError
,
2544 "can't assign to ()");
2547 if (assigning
> OP_APPLY
) {
2548 com_error(c
, PyExc_SyntaxError
,
2549 "augmented assign to tuple not possible");
2555 if (TYPE(n
) == RSQB
) {
2556 com_error(c
, PyExc_SyntaxError
,
2557 "can't assign to []");
2560 if (assigning
> OP_APPLY
) {
2561 com_error(c
, PyExc_SyntaxError
,
2562 "augmented assign to list not possible");
2566 && TYPE(CHILD(n
, 1)) == list_for
) {
2567 com_error(c
, PyExc_SyntaxError
,
2568 "can't assign to list comprehension");
2571 com_assign_sequence(c
, n
, assigning
);
2574 if (assigning
> OP_APPLY
)
2575 com_augassign_name(c
, CHILD(n
, 0),
2578 com_assign_name(c
, CHILD(n
, 0),
2582 com_error(c
, PyExc_SyntaxError
,
2583 "can't assign to literal");
2589 com_error(c
, PyExc_SyntaxError
,
2590 "can't assign to lambda");
2594 com_error(c
, PyExc_SystemError
,
2595 "com_assign: bad node");
2603 com_augassign(struct compiling
*c
, node
*n
)
2607 switch (STR(CHILD(CHILD(n
, 1), 0))[0]) {
2608 case '+': opcode
= INPLACE_ADD
; break;
2609 case '-': opcode
= INPLACE_SUBTRACT
; break;
2611 if (STR(CHILD(CHILD(n
, 1), 0))[1] == '/')
2612 opcode
= INPLACE_FLOOR_DIVIDE
;
2613 else if (c
->c_flags
& CO_FUTURE_DIVISION
)
2614 opcode
= INPLACE_TRUE_DIVIDE
;
2616 opcode
= INPLACE_DIVIDE
;
2618 case '%': opcode
= INPLACE_MODULO
; break;
2619 case '<': opcode
= INPLACE_LSHIFT
; break;
2620 case '>': opcode
= INPLACE_RSHIFT
; break;
2621 case '&': opcode
= INPLACE_AND
; break;
2622 case '^': opcode
= INPLACE_XOR
; break;
2623 case '|': opcode
= INPLACE_OR
; break;
2625 if (STR(CHILD(CHILD(n
, 1), 0))[1] == '*')
2626 opcode
= INPLACE_POWER
;
2628 opcode
= INPLACE_MULTIPLY
;
2631 com_error(c
, PyExc_SystemError
, "com_augassign: bad operator");
2634 com_assign(c
, CHILD(n
, 0), opcode
, CHILD(n
, 2));
2638 com_expr_stmt(struct compiling
*c
, node
*n
)
2641 /* testlist (('=' testlist)* | augassign testlist) */
2642 /* Forget it if we have just a doc string here */
2643 if (!c
->c_interactive
&& NCH(n
) == 1 && get_rawdocstring(n
) != NULL
)
2646 com_node(c
, CHILD(n
, NCH(n
)-1));
2647 if (c
->c_interactive
)
2648 com_addbyte(c
, PRINT_EXPR
);
2650 com_addbyte(c
, POP_TOP
);
2653 else if (TYPE(CHILD(n
,1)) == augassign
)
2654 com_augassign(c
, n
);
2657 com_node(c
, CHILD(n
, NCH(n
)-1));
2658 for (i
= 0; i
< NCH(n
)-2; i
+=2) {
2659 if (i
+2 < NCH(n
)-2) {
2660 com_addbyte(c
, DUP_TOP
);
2663 com_assign(c
, CHILD(n
, i
), OP_ASSIGN
, NULL
);
2669 com_assert_stmt(struct compiling
*c
, node
*n
)
2673 REQ(n
, assert_stmt
); /* 'assert' test [',' test] */
2674 /* Generate code like for
2678 raise AssertionError [, <message>]
2680 where <message> is the second test, if present.
2683 if (Py_OptimizeFlag
)
2685 com_addop_name(c
, LOAD_GLOBAL
, "__debug__");
2687 com_addfwref(c
, JUMP_IF_FALSE
, &a
);
2688 com_addbyte(c
, POP_TOP
);
2690 com_node(c
, CHILD(n
, 1));
2691 com_addfwref(c
, JUMP_IF_TRUE
, &b
);
2692 com_addbyte(c
, POP_TOP
);
2694 /* Raise that exception! */
2695 com_addop_name(c
, LOAD_GLOBAL
, "AssertionError");
2697 i
= NCH(n
)/2; /* Either 2 or 4 */
2699 com_node(c
, CHILD(n
, 3));
2700 com_addoparg(c
, RAISE_VARARGS
, i
);
2702 /* The interpreter does not fall through */
2703 /* All jumps converge here */
2704 com_backpatch(c
, a
);
2705 com_backpatch(c
, b
);
2706 com_addbyte(c
, POP_TOP
);
2710 com_print_stmt(struct compiling
*c
, node
*n
)
2713 node
* stream
= NULL
;
2715 REQ(n
, print_stmt
); /* 'print' (test ',')* [test] */
2717 /* are we using the extended print form? */
2718 if (NCH(n
) >= 2 && TYPE(CHILD(n
, 1)) == RIGHTSHIFT
) {
2719 stream
= CHILD(n
, 2);
2720 com_node(c
, stream
);
2721 /* stack: [...] => [... stream] */
2723 if (NCH(n
) > 3 && TYPE(CHILD(n
, 3)) == COMMA
)
2728 for (; i
< NCH(n
); i
+= 2) {
2729 if (stream
!= NULL
) {
2730 com_addbyte(c
, DUP_TOP
);
2731 /* stack: [stream] => [stream stream] */
2733 com_node(c
, CHILD(n
, i
));
2734 /* stack: [stream stream] => [stream stream obj] */
2735 com_addbyte(c
, ROT_TWO
);
2736 /* stack: [stream stream obj] => [stream obj stream] */
2737 com_addbyte(c
, PRINT_ITEM_TO
);
2738 /* stack: [stream obj stream] => [stream] */
2742 com_node(c
, CHILD(n
, i
));
2743 /* stack: [...] => [... obj] */
2744 com_addbyte(c
, PRINT_ITEM
);
2748 /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */
2749 if (TYPE(CHILD(n
, NCH(n
)-1)) == COMMA
) {
2750 if (stream
!= NULL
) {
2751 /* must pop the extra stream object off the stack */
2752 com_addbyte(c
, POP_TOP
);
2753 /* stack: [... stream] => [...] */
2758 if (stream
!= NULL
) {
2759 /* this consumes the last stream object on stack */
2760 com_addbyte(c
, PRINT_NEWLINE_TO
);
2761 /* stack: [... stream] => [...] */
2765 com_addbyte(c
, PRINT_NEWLINE
);
2770 com_return_stmt(struct compiling
*c
, node
*n
)
2772 REQ(n
, return_stmt
); /* 'return' [testlist] */
2773 if (!c
->c_infunction
) {
2774 com_error(c
, PyExc_SyntaxError
, "'return' outside function");
2776 if (c
->c_flags
& CO_GENERATOR
) {
2778 com_error(c
, PyExc_SyntaxError
,
2779 "'return' with argument inside generator");
2783 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
2787 com_node(c
, CHILD(n
, 1));
2788 com_addbyte(c
, RETURN_VALUE
);
2793 com_yield_stmt(struct compiling
*c
, node
*n
)
2796 REQ(n
, yield_stmt
); /* 'yield' testlist */
2797 if (!c
->c_infunction
) {
2798 com_error(c
, PyExc_SyntaxError
, "'yield' outside function");
2801 for (i
= 0; i
< c
->c_nblocks
; ++i
) {
2802 if (c
->c_block
[i
] == SETUP_FINALLY
) {
2803 com_error(c
, PyExc_SyntaxError
,
2804 "'yield' not allowed in a 'try' block "
2805 "with a 'finally' clause");
2809 com_node(c
, CHILD(n
, 1));
2810 com_addbyte(c
, YIELD_VALUE
);
2815 com_raise_stmt(struct compiling
*c
, node
*n
)
2818 REQ(n
, raise_stmt
); /* 'raise' [test [',' test [',' test]]] */
2820 com_node(c
, CHILD(n
, 1));
2822 com_node(c
, CHILD(n
, 3));
2824 com_node(c
, CHILD(n
, 5));
2828 com_addoparg(c
, RAISE_VARARGS
, i
);
2833 com_from_import(struct compiling
*c
, node
*n
)
2835 com_addopname(c
, IMPORT_FROM
, CHILD(n
, 0));
2838 if (strcmp(STR(CHILD(n
, 1)), "as") != 0) {
2839 com_error(c
, PyExc_SyntaxError
, "invalid syntax");
2842 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 2)));
2844 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 0)));
2849 com_import_stmt(struct compiling
*c
, node
*n
)
2852 REQ(n
, import_stmt
);
2853 /* 'import' dotted_name (',' dotted_name)* |
2854 'from' dotted_name 'import' ('*' | NAME (',' NAME)*) */
2855 if (STR(CHILD(n
, 0))[0] == 'f') {
2857 /* 'from' dotted_name 'import' ... */
2858 REQ(CHILD(n
, 1), dotted_name
);
2860 if (TYPE(CHILD(n
, 3)) == STAR
) {
2861 tup
= Py_BuildValue("(s)", "*");
2863 tup
= PyTuple_New((NCH(n
) - 2)/2);
2864 for (i
= 3; i
< NCH(n
); i
+= 2) {
2865 PyTuple_SET_ITEM(tup
, (i
-3)/2,
2866 PyString_FromString(STR(
2867 CHILD(CHILD(n
, i
), 0))));
2870 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, tup
));
2873 com_addopname(c
, IMPORT_NAME
, CHILD(n
, 1));
2874 if (TYPE(CHILD(n
, 3)) == STAR
)
2875 com_addbyte(c
, IMPORT_STAR
);
2877 for (i
= 3; i
< NCH(n
); i
+= 2)
2878 com_from_import(c
, CHILD(n
, i
));
2879 com_addbyte(c
, POP_TOP
);
2885 for (i
= 1; i
< NCH(n
); i
+= 2) {
2886 node
*subn
= CHILD(n
, i
);
2887 REQ(subn
, dotted_as_name
);
2888 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
2890 com_addopname(c
, IMPORT_NAME
, CHILD(subn
, 0));
2891 if (NCH(subn
) > 1) {
2893 if (strcmp(STR(CHILD(subn
, 1)), "as") != 0) {
2894 com_error(c
, PyExc_SyntaxError
,
2898 for (j
=2 ; j
< NCH(CHILD(subn
, 0)); j
+= 2)
2899 com_addopname(c
, LOAD_ATTR
,
2900 CHILD(CHILD(subn
, 0),
2902 com_addop_varname(c
, VAR_STORE
,
2903 STR(CHILD(subn
, 2)));
2905 com_addop_varname(c
, VAR_STORE
,
2906 STR(CHILD(CHILD(subn
, 0),
2914 com_exec_stmt(struct compiling
*c
, node
*n
)
2917 /* exec_stmt: 'exec' expr ['in' expr [',' expr]] */
2918 com_node(c
, CHILD(n
, 1));
2920 com_node(c
, CHILD(n
, 3));
2922 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
2926 com_node(c
, CHILD(n
, 5));
2928 com_addbyte(c
, DUP_TOP
);
2931 com_addbyte(c
, EXEC_STMT
);
2936 is_constant_false(struct compiling
*c
, node
*n
)
2940 /* argument c will be NULL when called from symtable_node() */
2942 /* Label to avoid tail recursion */
2953 for (i
= 0; i
< NCH(n
); i
++) {
2954 node
*ch
= CHILD(n
, i
);
2955 if (TYPE(ch
) == stmt
) {
2990 if (Py_OptimizeFlag
&& strcmp(STR(n
), "__debug__") == 0)
2995 v
= parsenumber(c
, STR(n
));
3000 i
= PyObject_IsTrue(v
);
3005 v
= parsestr(c
, STR(n
));
3010 i
= PyObject_IsTrue(v
);
3019 /* Look under n for a return stmt with an expression.
3020 * This hack is used to find illegal returns under "if 0:" blocks in
3021 * functions already known to be generators (as determined by the symtable
3023 * Return the offending return node if found, else NULL.
3026 look_for_offending_return(node
*n
)
3030 for (i
= 0; i
< NCH(n
); ++i
) {
3031 node
*kid
= CHILD(n
, i
);
3033 switch (TYPE(kid
)) {
3037 /* Stuff in nested functions & classes doesn't
3038 affect the code block we started in. */
3047 node
*bad
= look_for_offending_return(kid
);
3058 com_if_stmt(struct compiling
*c
, node
*n
)
3063 /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */
3064 for (i
= 0; i
+3 < NCH(n
); i
+=4) {
3066 node
*ch
= CHILD(n
, i
+1);
3067 if (is_constant_false(c
, ch
)) {
3068 /* We're going to skip this block. However, if this
3069 is a generator, we have to check the dead code
3070 anyway to make sure there aren't any return stmts
3071 with expressions, in the same scope. */
3072 if (c
->c_flags
& CO_GENERATOR
) {
3073 node
*p
= look_for_offending_return(n
);
3075 int savelineno
= c
->c_lineno
;
3076 c
->c_lineno
= p
->n_lineno
;
3077 com_error(c
, PyExc_SyntaxError
,
3078 "'return' with argument "
3079 "inside generator");
3080 c
->c_lineno
= savelineno
;
3086 com_addoparg(c
, SET_LINENO
, ch
->n_lineno
);
3088 com_addfwref(c
, JUMP_IF_FALSE
, &a
);
3089 com_addbyte(c
, POP_TOP
);
3091 com_node(c
, CHILD(n
, i
+3));
3092 com_addfwref(c
, JUMP_FORWARD
, &anchor
);
3093 com_backpatch(c
, a
);
3094 /* We jump here with an extra entry which we now pop */
3095 com_addbyte(c
, POP_TOP
);
3098 com_node(c
, CHILD(n
, i
+2));
3100 com_backpatch(c
, anchor
);
3104 com_while_stmt(struct compiling
*c
, node
*n
)
3106 int break_anchor
= 0;
3108 int save_begin
= c
->c_begin
;
3109 REQ(n
, while_stmt
); /* 'while' test ':' suite ['else' ':' suite] */
3110 com_addfwref(c
, SETUP_LOOP
, &break_anchor
);
3111 block_push(c
, SETUP_LOOP
);
3112 c
->c_begin
= c
->c_nexti
;
3113 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3114 com_node(c
, CHILD(n
, 1));
3115 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
3116 com_addbyte(c
, POP_TOP
);
3119 com_node(c
, CHILD(n
, 3));
3121 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
3122 c
->c_begin
= save_begin
;
3123 com_backpatch(c
, anchor
);
3124 /* We jump here with one entry more on the stack */
3125 com_addbyte(c
, POP_TOP
);
3126 com_addbyte(c
, POP_BLOCK
);
3127 block_pop(c
, SETUP_LOOP
);
3129 com_node(c
, CHILD(n
, 6));
3130 com_backpatch(c
, break_anchor
);
3134 com_for_stmt(struct compiling
*c
, node
*n
)
3136 int break_anchor
= 0;
3138 int save_begin
= c
->c_begin
;
3140 /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */
3141 com_addfwref(c
, SETUP_LOOP
, &break_anchor
);
3142 block_push(c
, SETUP_LOOP
);
3143 com_node(c
, CHILD(n
, 3));
3144 com_addbyte(c
, GET_ITER
);
3145 c
->c_begin
= c
->c_nexti
;
3146 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3147 com_addfwref(c
, FOR_ITER
, &anchor
);
3149 com_assign(c
, CHILD(n
, 1), OP_ASSIGN
, NULL
);
3151 com_node(c
, CHILD(n
, 5));
3153 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
3154 c
->c_begin
= save_begin
;
3155 com_backpatch(c
, anchor
);
3156 com_pop(c
, 1); /* FOR_ITER has popped this */
3157 com_addbyte(c
, POP_BLOCK
);
3158 block_pop(c
, SETUP_LOOP
);
3160 com_node(c
, CHILD(n
, 8));
3161 com_backpatch(c
, break_anchor
);
3164 /* Code generated for "try: S finally: Sf" is as follows:
3173 The special instructions use the block stack. Each block
3174 stack entry contains the instruction that created it (here
3175 SETUP_FINALLY), the level of the value stack at the time the
3176 block stack entry was created, and a label (here L).
3179 Pushes the current value stack level and the label
3180 onto the block stack.
3182 Pops en entry from the block stack, and pops the value
3183 stack until its level is the same as indicated on the
3184 block stack. (The label is ignored.)
3186 Pops a variable number of entries from the *value* stack
3187 and re-raises the exception they specify. The number of
3188 entries popped depends on the (pseudo) exception type.
3190 The block stack is unwound when an exception is raised:
3191 when a SETUP_FINALLY entry is found, the exception is pushed
3192 onto the value stack (and the exception condition is cleared),
3193 and the interpreter jumps to the label gotten from the block
3196 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
3197 (The contents of the value stack is shown in [], with the top
3198 at the right; 'tb' is trace-back info, 'val' the exception's
3199 associated value, and 'exc' the exception.)
3201 Value stack Label Instruction Argument
3207 [tb, val, exc] L1: DUP )
3208 [tb, val, exc, exc] <evaluate E1> )
3209 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
3210 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
3211 [tb, val, exc, 1] POP )
3213 [tb, val] <assign to V1> (or POP if no V1)
3218 [tb, val, exc, 0] L2: POP
3220 .............................etc.......................
3222 [tb, val, exc, 0] Ln+1: POP
3223 [tb, val, exc] END_FINALLY # re-raise exception
3225 [] L0: <next statement>
3227 Of course, parts are not generated if Vi or Ei is not present.
3231 com_try_except(struct compiling
*c
, node
*n
)
3233 int except_anchor
= 0;
3235 int else_anchor
= 0;
3239 com_addfwref(c
, SETUP_EXCEPT
, &except_anchor
);
3240 block_push(c
, SETUP_EXCEPT
);
3241 com_node(c
, CHILD(n
, 2));
3242 com_addbyte(c
, POP_BLOCK
);
3243 block_pop(c
, SETUP_EXCEPT
);
3244 com_addfwref(c
, JUMP_FORWARD
, &else_anchor
);
3245 com_backpatch(c
, except_anchor
);
3247 i
< NCH(n
) && TYPE(ch
= CHILD(n
, i
)) == except_clause
;
3249 /* except_clause: 'except' [expr [',' var]] */
3250 if (except_anchor
== 0) {
3251 com_error(c
, PyExc_SyntaxError
,
3252 "default 'except:' must be last");
3256 com_push(c
, 3); /* tb, val, exc pushed by exception */
3257 com_addoparg(c
, SET_LINENO
, ch
->n_lineno
);
3259 com_addbyte(c
, DUP_TOP
);
3261 com_node(c
, CHILD(ch
, 1));
3262 com_addoparg(c
, COMPARE_OP
, EXC_MATCH
);
3264 com_addfwref(c
, JUMP_IF_FALSE
, &except_anchor
);
3265 com_addbyte(c
, POP_TOP
);
3268 com_addbyte(c
, POP_TOP
);
3271 com_assign(c
, CHILD(ch
, 3), OP_ASSIGN
, NULL
);
3273 com_addbyte(c
, POP_TOP
);
3276 com_addbyte(c
, POP_TOP
);
3278 com_node(c
, CHILD(n
, i
+2));
3279 com_addfwref(c
, JUMP_FORWARD
, &end_anchor
);
3280 if (except_anchor
) {
3281 com_backpatch(c
, except_anchor
);
3282 /* We come in with [tb, val, exc, 0] on the
3283 stack; one pop and it's the same as
3284 expected at the start of the loop */
3285 com_addbyte(c
, POP_TOP
);
3288 /* We actually come in here with [tb, val, exc] but the
3289 END_FINALLY will zap those and jump around.
3290 The c_stacklevel does not reflect them so we need not pop
3292 com_addbyte(c
, END_FINALLY
);
3293 com_backpatch(c
, else_anchor
);
3295 com_node(c
, CHILD(n
, i
+2));
3296 com_backpatch(c
, end_anchor
);
3300 com_try_finally(struct compiling
*c
, node
*n
)
3302 int finally_anchor
= 0;
3305 com_addfwref(c
, SETUP_FINALLY
, &finally_anchor
);
3306 block_push(c
, SETUP_FINALLY
);
3307 com_node(c
, CHILD(n
, 2));
3308 com_addbyte(c
, POP_BLOCK
);
3309 block_pop(c
, SETUP_FINALLY
);
3310 block_push(c
, END_FINALLY
);
3311 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3312 /* While the generated code pushes only one item,
3313 the try-finally handling can enter here with
3314 up to three items. OK, here are the details:
3315 3 for an exception, 2 for RETURN, 1 for BREAK. */
3317 com_backpatch(c
, finally_anchor
);
3318 ch
= CHILD(n
, NCH(n
)-1);
3319 com_addoparg(c
, SET_LINENO
, ch
->n_lineno
);
3321 com_addbyte(c
, END_FINALLY
);
3322 block_pop(c
, END_FINALLY
);
3323 com_pop(c
, 3); /* Matches the com_push above */
3327 com_try_stmt(struct compiling
*c
, node
*n
)
3330 /* 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
3331 | 'try' ':' suite 'finally' ':' suite */
3332 if (TYPE(CHILD(n
, 3)) != except_clause
)
3333 com_try_finally(c
, n
);
3335 com_try_except(c
, n
);
3339 get_rawdocstring(node
*n
)
3343 /* Label to avoid tail recursion */
3354 for (i
= 0; i
< NCH(n
); i
++) {
3355 node
*ch
= CHILD(n
, i
);
3356 if (TYPE(ch
) == stmt
) {
3390 if (TYPE(CHILD(n
, 0)) == STRING
)
3399 get_docstring(struct compiling
*c
, node
*n
)
3401 /* Don't generate doc-strings if run with -OO */
3402 if (Py_OptimizeFlag
> 1)
3404 n
= get_rawdocstring(n
);
3407 return parsestrplus(c
, n
);
3411 com_suite(struct compiling
*c
, node
*n
)
3414 /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */
3416 com_node(c
, CHILD(n
, 0));
3420 for (i
= 0; i
< NCH(n
) && c
->c_errors
== 0; i
++) {
3421 node
*ch
= CHILD(n
, i
);
3422 if (TYPE(ch
) == stmt
)
3430 com_continue_stmt(struct compiling
*c
, node
*n
)
3432 int i
= c
->c_nblocks
;
3433 if (i
-- > 0 && c
->c_block
[i
] == SETUP_LOOP
) {
3434 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
3437 /* at the outer level */
3438 com_error(c
, PyExc_SyntaxError
,
3439 "'continue' not properly in loop");
3443 for (j
= i
-1; j
>= 0; --j
) {
3444 if (c
->c_block
[j
] == SETUP_LOOP
)
3448 /* there is a loop, but something interferes */
3449 for (; i
> j
; --i
) {
3450 if (c
->c_block
[i
] == SETUP_EXCEPT
||
3451 c
->c_block
[i
] == SETUP_FINALLY
) {
3452 com_addoparg(c
, CONTINUE_LOOP
,
3456 if (c
->c_block
[i
] == END_FINALLY
) {
3457 com_error(c
, PyExc_SyntaxError
,
3458 "'continue' not supported inside 'finally' clause");
3463 com_error(c
, PyExc_SyntaxError
,
3464 "'continue' not properly in loop");
3466 /* XXX Could allow it inside a 'finally' clause
3467 XXX if we could pop the exception still on the stack */
3471 com_argdefs(struct compiling
*c
, node
*n
)
3473 int i
, nch
, nargs
, ndefs
;
3474 if (TYPE(n
) == lambdef
) {
3475 /* lambdef: 'lambda' [varargslist] ':' test */
3479 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ... */
3481 REQ(n
, parameters
); /* parameters: '(' [varargslist] ')' */
3484 if (TYPE(n
) != varargslist
)
3487 (fpdef ['=' test] ',')* '*' ....... |
3488 fpdef ['=' test] (',' fpdef ['=' test])* [','] */
3492 for (i
= 0; i
< nch
; i
++) {
3494 if (TYPE(CHILD(n
, i
)) == STAR
||
3495 TYPE(CHILD(n
, i
)) == DOUBLESTAR
)
3500 t
= RPAR
; /* Anything except EQUAL or COMMA */
3502 t
= TYPE(CHILD(n
, i
));
3506 com_node(c
, CHILD(n
, i
));
3510 t
= TYPE(CHILD(n
, i
));
3513 /* Treat "(a=1, b)" as an error */
3515 com_error(c
, PyExc_SyntaxError
,
3516 "non-default argument follows default argument");
3525 com_funcdef(struct compiling
*c
, node
*n
)
3529 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ':' suite */
3530 ndefs
= com_argdefs(c
, n
);
3531 symtable_enter_scope(c
->c_symtable
, STR(CHILD(n
, 1)), TYPE(n
),
3533 co
= (PyObject
*)icompile(n
, c
);
3534 symtable_exit_scope(c
->c_symtable
);
3538 int closure
= com_make_closure(c
, (PyCodeObject
*)co
);
3539 int i
= com_addconst(c
, co
);
3540 com_addoparg(c
, LOAD_CONST
, i
);
3543 com_addoparg(c
, MAKE_CLOSURE
, ndefs
);
3545 com_addoparg(c
, MAKE_FUNCTION
, ndefs
);
3547 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 1)));
3554 com_bases(struct compiling
*c
, node
*n
)
3558 /* testlist: test (',' test)* [','] */
3559 for (i
= 0; i
< NCH(n
); i
+= 2)
3560 com_node(c
, CHILD(n
, i
));
3562 com_addoparg(c
, BUILD_TUPLE
, i
);
3567 com_classdef(struct compiling
*c
, node
*n
)
3575 /* classdef: class NAME ['(' testlist ')'] ':' suite */
3576 if ((v
= PyString_InternFromString(STR(CHILD(n
, 1)))) == NULL
) {
3580 /* Push the class name on the stack */
3581 i
= com_addconst(c
, v
);
3582 com_addoparg(c
, LOAD_CONST
, i
);
3585 /* Push the tuple of base classes on the stack */
3586 if (TYPE(CHILD(n
, 2)) != LPAR
) {
3587 com_addoparg(c
, BUILD_TUPLE
, 0);
3591 com_bases(c
, CHILD(n
, 3));
3592 name
= STR(CHILD(n
, 1));
3593 symtable_enter_scope(c
->c_symtable
, name
, TYPE(n
), n
->n_lineno
);
3594 co
= icompile(n
, c
);
3595 symtable_exit_scope(c
->c_symtable
);
3599 int closure
= com_make_closure(c
, co
);
3600 i
= com_addconst(c
, (PyObject
*)co
);
3601 com_addoparg(c
, LOAD_CONST
, i
);
3604 com_addoparg(c
, MAKE_CLOSURE
, 0);
3605 com_pop(c
, PyCode_GetNumFree(co
));
3607 com_addoparg(c
, MAKE_FUNCTION
, 0);
3608 com_addoparg(c
, CALL_FUNCTION
, 0);
3609 com_addbyte(c
, BUILD_CLASS
);
3611 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 1)));
3618 com_node(struct compiling
*c
, node
*n
)
3625 /* Definition nodes */
3634 /* Trivial parse tree nodes */
3643 /* small_stmt (';' small_stmt)* [';'] NEWLINE */
3644 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3647 for (i
= 0; i
< NCH(n
)-1; i
+= 2)
3648 com_node(c
, CHILD(n
, i
));
3653 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3657 /* Statement nodes */
3660 com_expr_stmt(c
, n
);
3663 com_print_stmt(c
, n
);
3665 case del_stmt
: /* 'del' exprlist */
3666 com_assign(c
, CHILD(n
, 1), OP_DELETE
, NULL
);
3671 if (c
->c_loops
== 0) {
3672 com_error(c
, PyExc_SyntaxError
,
3673 "'break' outside loop");
3675 com_addbyte(c
, BREAK_LOOP
);
3678 com_continue_stmt(c
, n
);
3681 com_return_stmt(c
, n
);
3684 com_yield_stmt(c
, n
);
3687 com_raise_stmt(c
, n
);
3690 com_import_stmt(c
, n
);
3695 com_exec_stmt(c
, n
);
3698 com_assert_stmt(c
, n
);
3704 com_while_stmt(c
, n
);
3716 /* Expression nodes */
3732 com_comparison(c
, n
);
3747 com_shift_expr(c
, n
);
3750 com_arith_expr(c
, n
);
3766 com_error(c
, PyExc_SystemError
,
3767 "com_node: unexpected node type");
3771 static void com_fplist(struct compiling
*, node
*);
3774 com_fpdef(struct compiling
*c
, node
*n
)
3776 REQ(n
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
3777 if (TYPE(CHILD(n
, 0)) == LPAR
)
3778 com_fplist(c
, CHILD(n
, 1));
3780 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 0)));
3786 com_fplist(struct compiling
*c
, node
*n
)
3788 REQ(n
, fplist
); /* fplist: fpdef (',' fpdef)* [','] */
3790 com_fpdef(c
, CHILD(n
, 0));
3793 int i
= (NCH(n
)+1)/2;
3794 com_addoparg(c
, UNPACK_SEQUENCE
, i
);
3796 for (i
= 0; i
< NCH(n
); i
+= 2)
3797 com_fpdef(c
, CHILD(n
, i
));
3802 com_arglist(struct compiling
*c
, node
*n
)
3807 REQ(n
, varargslist
);
3809 (fpdef ['=' test] ',')* (fpdef ['=' test] | '*' .....) */
3811 /* Enter all arguments in table of locals */
3812 for (i
= 0, narg
= 0; i
< nch
; i
++) {
3813 node
*ch
= CHILD(n
, i
);
3815 if (TYPE(ch
) == STAR
|| TYPE(ch
) == DOUBLESTAR
)
3817 REQ(ch
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
3819 if (TYPE(fp
) != NAME
) {
3820 PyOS_snprintf(nbuf
, sizeof(nbuf
), ".%d", i
);
3824 /* all name updates handled by symtable */
3828 if (TYPE(ch
) == EQUAL
)
3834 /* Generate code for complex arguments only after
3835 having counted the simple arguments */
3837 for (i
= 0; i
< nch
; i
++) {
3838 node
*ch
= CHILD(n
, i
);
3840 if (TYPE(ch
) == STAR
|| TYPE(ch
) == DOUBLESTAR
)
3842 REQ(ch
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
3844 if (TYPE(fp
) != NAME
) {
3845 com_addoparg(c
, LOAD_FAST
, ilocal
);
3853 if (TYPE(ch
) == EQUAL
)
3862 com_file_input(struct compiling
*c
, node
*n
)
3866 REQ(n
, file_input
); /* (NEWLINE | stmt)* ENDMARKER */
3867 doc
= get_docstring(c
, n
);
3869 int i
= com_addconst(c
, doc
);
3871 com_addoparg(c
, LOAD_CONST
, i
);
3873 com_addop_name(c
, STORE_NAME
, "__doc__");
3876 for (i
= 0; i
< NCH(n
); i
++) {
3877 node
*ch
= CHILD(n
, i
);
3878 if (TYPE(ch
) != ENDMARKER
&& TYPE(ch
) != NEWLINE
)
3883 /* Top-level compile-node interface */
3886 compile_funcdef(struct compiling
*c
, node
*n
)
3890 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ':' suite */
3891 c
->c_name
= STR(CHILD(n
, 1));
3892 doc
= get_docstring(c
, CHILD(n
, 4));
3894 (void) com_addconst(c
, doc
);
3898 (void) com_addconst(c
, Py_None
); /* No docstring */
3899 ch
= CHILD(n
, 2); /* parameters: '(' [varargslist] ')' */
3900 ch
= CHILD(ch
, 1); /* ')' | varargslist */
3901 if (TYPE(ch
) == varargslist
)
3903 c
->c_infunction
= 1;
3904 com_node(c
, CHILD(n
, 4));
3905 c
->c_infunction
= 0;
3906 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3908 com_addbyte(c
, RETURN_VALUE
);
3913 compile_lambdef(struct compiling
*c
, node
*n
)
3916 REQ(n
, lambdef
); /* lambdef: 'lambda' [varargslist] ':' test */
3917 c
->c_name
= "<lambda>";
3920 (void) com_addconst(c
, Py_None
); /* No docstring */
3921 if (TYPE(ch
) == varargslist
) {
3928 com_addbyte(c
, RETURN_VALUE
);
3933 compile_classdef(struct compiling
*c
, node
*n
)
3938 /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */
3939 c
->c_name
= STR(CHILD(n
, 1));
3940 c
->c_private
= c
->c_name
;
3941 /* Initialize local __module__ from global __name__ */
3942 com_addop_name(c
, LOAD_GLOBAL
, "__name__");
3943 com_addop_name(c
, STORE_NAME
, "__module__");
3944 ch
= CHILD(n
, NCH(n
)-1); /* The suite */
3945 doc
= get_docstring(c
, ch
);
3947 int i
= com_addconst(c
, doc
);
3949 com_addoparg(c
, LOAD_CONST
, i
);
3951 com_addop_name(c
, STORE_NAME
, "__doc__");
3955 (void) com_addconst(c
, Py_None
);
3957 com_addbyte(c
, LOAD_LOCALS
);
3959 com_addbyte(c
, RETURN_VALUE
);
3964 compile_node(struct compiling
*c
, node
*n
)
3966 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3970 case single_input
: /* One interactive command */
3971 /* NEWLINE | simple_stmt | compound_stmt NEWLINE */
3974 if (TYPE(n
) != NEWLINE
)
3976 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3978 com_addbyte(c
, RETURN_VALUE
);
3983 case file_input
: /* A whole file, or built-in function exec() */
3984 com_file_input(c
, n
);
3985 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3987 com_addbyte(c
, RETURN_VALUE
);
3991 case eval_input
: /* Built-in function input() */
3992 com_node(c
, CHILD(n
, 0));
3993 com_addbyte(c
, RETURN_VALUE
);
3997 case lambdef
: /* anonymous function definition */
3998 compile_lambdef(c
, n
);
4001 case funcdef
: /* A function definition */
4002 compile_funcdef(c
, n
);
4005 case classdef
: /* A class definition */
4006 compile_classdef(c
, n
);
4010 com_error(c
, PyExc_SystemError
,
4011 "compile_node: unexpected node type");
4016 dict_keys_inorder(PyObject
*dict
, int offset
)
4018 PyObject
*tuple
, *k
, *v
;
4019 int i
, pos
= 0, size
= PyDict_Size(dict
);
4021 tuple
= PyTuple_New(size
);
4024 while (PyDict_Next(dict
, &pos
, &k
, &v
)) {
4025 i
= PyInt_AS_LONG(v
);
4027 assert((i
- offset
) < size
);
4028 PyTuple_SET_ITEM(tuple
, i
- offset
, k
);
4034 PyNode_Compile(node
*n
, char *filename
)
4036 return PyNode_CompileFlags(n
, filename
, NULL
);
4040 PyNode_CompileFlags(node
*n
, char *filename
, PyCompilerFlags
*flags
)
4042 return jcompile(n
, filename
, NULL
, flags
);
4046 PyNode_CompileSymtable(node
*n
, char *filename
)
4048 struct symtable
*st
;
4049 PyFutureFeatures
*ff
;
4051 ff
= PyNode_Future(n
, filename
);
4055 st
= symtable_init();
4057 PyMem_Free((void *)ff
);
4061 symtable_enter_scope(st
, TOP
, TYPE(n
), n
->n_lineno
);
4062 if (st
->st_errors
> 0)
4064 symtable_node(st
, n
);
4065 if (st
->st_errors
> 0)
4070 PyMem_Free((void *)ff
);
4071 st
->st_future
= NULL
;
4072 PySymtable_Free(st
);
4076 static PyCodeObject
*
4077 icompile(node
*n
, struct compiling
*base
)
4079 return jcompile(n
, base
->c_filename
, base
, NULL
);
4082 static PyCodeObject
*
4083 jcompile(node
*n
, char *filename
, struct compiling
*base
,
4084 PyCompilerFlags
*flags
)
4086 struct compiling sc
;
4088 if (!com_init(&sc
, filename
))
4091 sc
.c_private
= base
->c_private
;
4092 sc
.c_symtable
= base
->c_symtable
;
4093 /* c_symtable still points to parent's symbols */
4095 || (sc
.c_symtable
->st_cur
->ste_type
== TYPE_FUNCTION
))
4097 sc
.c_flags
|= base
->c_flags
& PyCF_MASK
;
4099 sc
.c_private
= NULL
;
4100 sc
.c_future
= PyNode_Future(n
, filename
);
4101 if (sc
.c_future
== NULL
) {
4106 int merged
= sc
.c_future
->ff_features
|
4108 sc
.c_future
->ff_features
= merged
;
4109 flags
->cf_flags
= merged
;
4111 if (symtable_build(&sc
, n
) < 0) {
4117 if (symtable_load_symbols(&sc
) < 0) {
4121 compile_node(&sc
, n
);
4123 if (sc
.c_errors
== 0) {
4124 PyObject
*consts
, *names
, *varnames
, *filename
, *name
,
4125 *freevars
, *cellvars
;
4126 consts
= PyList_AsTuple(sc
.c_consts
);
4127 names
= PyList_AsTuple(sc
.c_names
);
4128 varnames
= PyList_AsTuple(sc
.c_varnames
);
4129 cellvars
= dict_keys_inorder(sc
.c_cellvars
, 0);
4130 freevars
= dict_keys_inorder(sc
.c_freevars
,
4131 PyTuple_GET_SIZE(cellvars
));
4132 filename
= PyString_InternFromString(sc
.c_filename
);
4133 name
= PyString_InternFromString(sc
.c_name
);
4134 if (!PyErr_Occurred())
4135 co
= PyCode_New(sc
.c_argcount
,
4151 Py_XDECREF(varnames
);
4152 Py_XDECREF(freevars
);
4153 Py_XDECREF(cellvars
);
4154 Py_XDECREF(filename
);
4157 else if (!PyErr_Occurred()) {
4158 /* This could happen if someone called PyErr_Clear() after an
4159 error was reported above. That's not supposed to happen,
4160 but I just plugged one case and I'm not sure there can't be
4161 others. In that case, raise SystemError so that at least
4162 it gets reported instead dumping core. */
4163 PyErr_SetString(PyExc_SystemError
, "lost syntax error");
4167 PySymtable_Free(sc
.c_symtable
);
4168 sc
.c_symtable
= NULL
;
4175 PyCode_Addr2Line(PyCodeObject
*co
, int addrq
)
4177 int size
= PyString_Size(co
->co_lnotab
) / 2;
4178 unsigned char *p
= (unsigned char*)PyString_AsString(co
->co_lnotab
);
4179 int line
= co
->co_firstlineno
;
4181 while (--size
>= 0) {
4190 /* The test for LOCAL must come before the test for FREE in order to
4191 handle classes where name is both local and free. The local var is
4192 a method and the free var is a free var referenced within a method.
4196 get_ref_type(struct compiling
*c
, char *name
)
4201 if (PyDict_GetItemString(c
->c_cellvars
, name
) != NULL
)
4203 if (PyDict_GetItemString(c
->c_locals
, name
) != NULL
)
4205 if (PyDict_GetItemString(c
->c_freevars
, name
) != NULL
)
4207 v
= PyDict_GetItemString(c
->c_globals
, name
);
4210 return GLOBAL_EXPLICIT
;
4212 return GLOBAL_IMPLICIT
;
4215 PyOS_snprintf(buf
, sizeof(buf
),
4216 "unknown scope for %.100s in %.100s(%s) "
4217 "in %s\nsymbols: %s\nlocals: %s\nglobals: %s\n",
4219 PyObject_REPR(c
->c_symtable
->st_cur
->ste_id
),
4221 PyObject_REPR(c
->c_symtable
->st_cur
->ste_symbols
),
4222 PyObject_REPR(c
->c_locals
),
4223 PyObject_REPR(c
->c_globals
)
4230 /* Helper functions to issue warnings */
4233 issue_warning(char *msg
, char *filename
, int lineno
)
4235 if (PyErr_WarnExplicit(PyExc_SyntaxWarning
, msg
, filename
,
4236 lineno
, NULL
, NULL
) < 0) {
4237 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning
)) {
4238 PyErr_SetString(PyExc_SyntaxError
, msg
);
4239 PyErr_SyntaxLocation(filename
, lineno
);
4247 symtable_warn(struct symtable
*st
, char *msg
)
4249 if (issue_warning(msg
, st
->st_filename
, st
->st_cur
->ste_lineno
) < 0) {
4256 /* Helper function for setting lineno and filename */
4259 symtable_build(struct compiling
*c
, node
*n
)
4261 if ((c
->c_symtable
= symtable_init()) == NULL
)
4263 c
->c_symtable
->st_future
= c
->c_future
;
4264 c
->c_symtable
->st_filename
= c
->c_filename
;
4265 symtable_enter_scope(c
->c_symtable
, TOP
, TYPE(n
), n
->n_lineno
);
4266 if (c
->c_symtable
->st_errors
> 0)
4268 symtable_node(c
->c_symtable
, n
);
4269 if (c
->c_symtable
->st_errors
> 0)
4271 /* reset for second pass */
4272 c
->c_symtable
->st_nscopes
= 1;
4273 c
->c_symtable
->st_pass
= 2;
4278 symtable_init_compiling_symbols(struct compiling
*c
)
4282 varnames
= c
->c_symtable
->st_cur
->ste_varnames
;
4283 if (varnames
== NULL
) {
4284 varnames
= PyList_New(0);
4285 if (varnames
== NULL
)
4287 c
->c_symtable
->st_cur
->ste_varnames
= varnames
;
4288 Py_INCREF(varnames
);
4290 Py_INCREF(varnames
);
4291 c
->c_varnames
= varnames
;
4293 c
->c_globals
= PyDict_New();
4294 if (c
->c_globals
== NULL
)
4296 c
->c_freevars
= PyDict_New();
4297 if (c
->c_freevars
== NULL
)
4299 c
->c_cellvars
= PyDict_New();
4300 if (c
->c_cellvars
== NULL
)
4305 struct symbol_info
{
4313 symtable_init_info(struct symbol_info
*si
)
4318 si
->si_nimplicit
= 0;
4322 symtable_resolve_free(struct compiling
*c
, PyObject
*name
, int flags
,
4323 struct symbol_info
*si
)
4327 /* Seperate logic for DEF_FREE. If it occurs in a function,
4328 it indicates a local that we must allocate storage for (a
4329 cell var). If it occurs in a class, then the class has a
4330 method and a free variable with the same name.
4332 if (c
->c_symtable
->st_cur
->ste_type
== TYPE_FUNCTION
) {
4333 /* If it isn't declared locally, it can't be a cell. */
4334 if (!(flags
& (DEF_LOCAL
| DEF_PARAM
)))
4336 v
= PyInt_FromLong(si
->si_ncells
++);
4337 dict
= c
->c_cellvars
;
4339 /* If it is free anyway, then there is no need to do
4342 if (is_free(flags
^ DEF_FREE_CLASS
)
4343 || (flags
== DEF_FREE_CLASS
))
4345 v
= PyInt_FromLong(si
->si_nfrees
++);
4346 dict
= c
->c_freevars
;
4350 if (PyDict_SetItem(dict
, name
, v
) < 0) {
4358 /* If a variable is a cell and an argument, make sure that appears in
4359 co_cellvars before any variable to its right in varnames.
4364 symtable_cellvar_offsets(PyObject
**cellvars
, int argcount
,
4365 PyObject
*varnames
, int flags
)
4367 PyObject
*v
, *w
, *d
, *list
= NULL
;
4370 if (flags
& CO_VARARGS
)
4372 if (flags
& CO_VARKEYWORDS
)
4374 for (i
= argcount
; --i
>= 0; ) {
4375 v
= PyList_GET_ITEM(varnames
, i
);
4376 if (PyDict_GetItem(*cellvars
, v
)) {
4378 list
= PyList_New(1);
4381 PyList_SET_ITEM(list
, 0, v
);
4384 PyList_Insert(list
, 0, v
);
4387 if (list
== NULL
|| PyList_GET_SIZE(list
) == 0)
4389 /* There are cellvars that are also arguments. Create a dict
4390 to replace cellvars and put the args at the front.
4393 for (i
= PyList_GET_SIZE(list
); --i
>= 0; ) {
4394 v
= PyInt_FromLong(i
);
4397 if (PyDict_SetItem(d
, PyList_GET_ITEM(list
, i
), v
) < 0)
4399 if (PyDict_DelItem(*cellvars
, PyList_GET_ITEM(list
, i
)) < 0)
4403 i
= PyList_GET_SIZE(list
);
4405 while (PyDict_Next(*cellvars
, &pos
, &v
, &w
)) {
4406 w
= PyInt_FromLong(i
++); /* don't care about the old key */
4407 if (PyDict_SetItem(d
, v
, w
) < 0) {
4413 Py_DECREF(*cellvars
);
4422 symtable_freevar_offsets(PyObject
*freevars
, int offset
)
4427 /* The cell vars are the first elements of the closure,
4428 followed by the free vars. Update the offsets in
4429 c_freevars to account for number of cellvars. */
4431 while (PyDict_Next(freevars
, &pos
, &name
, &v
)) {
4432 int i
= PyInt_AS_LONG(v
) + offset
;
4433 PyObject
*o
= PyInt_FromLong(i
);
4436 if (PyDict_SetItem(freevars
, name
, o
) < 0) {
4446 symtable_check_unoptimized(struct compiling
*c
,
4447 PySymtableEntryObject
*ste
,
4448 struct symbol_info
*si
)
4452 if (!(si
->si_ncells
|| si
->si_nfrees
|| ste
->ste_child_free
4453 || (ste
->ste_nested
&& si
->si_nimplicit
)))
4456 #define ILLEGAL_CONTAINS "contains a nested function with free variables"
4458 #define ILLEGAL_IS "is a nested function"
4460 #define ILLEGAL_IMPORT_STAR \
4461 "import * is not allowed in function '%.100s' because it %s"
4463 #define ILLEGAL_BARE_EXEC \
4464 "unqualified exec is not allowed in function '%.100s' it %s"
4466 #define ILLEGAL_EXEC_AND_IMPORT_STAR \
4467 "function '%.100s' uses import * and bare exec, which are illegal " \
4470 /* XXX perhaps the linenos for these opt-breaking statements
4471 should be stored so the exception can point to them. */
4473 if (ste
->ste_child_free
) {
4474 if (ste
->ste_optimized
== OPT_IMPORT_STAR
)
4475 PyOS_snprintf(buf
, sizeof(buf
),
4476 ILLEGAL_IMPORT_STAR
,
4477 PyString_AS_STRING(ste
->ste_name
),
4479 else if (ste
->ste_optimized
== (OPT_BARE_EXEC
| OPT_EXEC
))
4480 PyOS_snprintf(buf
, sizeof(buf
),
4482 PyString_AS_STRING(ste
->ste_name
),
4485 PyOS_snprintf(buf
, sizeof(buf
),
4486 ILLEGAL_EXEC_AND_IMPORT_STAR
,
4487 PyString_AS_STRING(ste
->ste_name
),
4491 if (ste
->ste_optimized
== OPT_IMPORT_STAR
)
4492 PyOS_snprintf(buf
, sizeof(buf
),
4493 ILLEGAL_IMPORT_STAR
,
4494 PyString_AS_STRING(ste
->ste_name
),
4496 else if (ste
->ste_optimized
== (OPT_BARE_EXEC
| OPT_EXEC
))
4497 PyOS_snprintf(buf
, sizeof(buf
),
4499 PyString_AS_STRING(ste
->ste_name
),
4502 PyOS_snprintf(buf
, sizeof(buf
),
4503 ILLEGAL_EXEC_AND_IMPORT_STAR
,
4504 PyString_AS_STRING(ste
->ste_name
),
4509 PyErr_SetString(PyExc_SyntaxError
, buf
);
4510 PyErr_SyntaxLocation(c
->c_symtable
->st_filename
,
4511 ste
->ste_opt_lineno
);
4516 symtable_update_flags(struct compiling
*c
, PySymtableEntryObject
*ste
,
4517 struct symbol_info
*si
)
4520 c
->c_flags
|= c
->c_future
->ff_features
;
4521 if (ste
->ste_generator
)
4522 c
->c_flags
|= CO_GENERATOR
;
4523 if (ste
->ste_type
!= TYPE_MODULE
)
4524 c
->c_flags
|= CO_NEWLOCALS
;
4525 if (ste
->ste_type
== TYPE_FUNCTION
) {
4526 c
->c_nlocals
= si
->si_nlocals
;
4527 if (ste
->ste_optimized
== 0)
4528 c
->c_flags
|= CO_OPTIMIZED
;
4529 else if (ste
->ste_optimized
!= OPT_EXEC
)
4530 return symtable_check_unoptimized(c
, ste
, si
);
4536 symtable_load_symbols(struct compiling
*c
)
4538 static PyObject
*implicit
= NULL
;
4539 struct symtable
*st
= c
->c_symtable
;
4540 PySymtableEntryObject
*ste
= st
->st_cur
;
4541 PyObject
*name
, *varnames
, *v
;
4543 struct symbol_info si
;
4545 if (implicit
== NULL
) {
4546 implicit
= PyInt_FromLong(1);
4547 if (implicit
== NULL
)
4552 if (symtable_init_compiling_symbols(c
) < 0)
4554 symtable_init_info(&si
);
4555 varnames
= st
->st_cur
->ste_varnames
;
4556 si
.si_nlocals
= PyList_GET_SIZE(varnames
);
4557 c
->c_argcount
= si
.si_nlocals
;
4559 for (i
= 0; i
< si
.si_nlocals
; ++i
) {
4560 v
= PyInt_FromLong(i
);
4561 if (PyDict_SetItem(c
->c_locals
,
4562 PyList_GET_ITEM(varnames
, i
), v
) < 0)
4567 /* XXX The cases below define the rules for whether a name is
4568 local or global. The logic could probably be clearer. */
4570 while (PyDict_Next(ste
->ste_symbols
, &pos
, &name
, &v
)) {
4571 flags
= PyInt_AS_LONG(v
);
4573 if (flags
& DEF_FREE_GLOBAL
)
4574 /* undo the original DEF_FREE */
4575 flags
&= ~(DEF_FREE
| DEF_FREE_CLASS
);
4577 /* Deal with names that need two actions:
4578 1. Cell variables that are also locals.
4579 2. Free variables in methods that are also class
4580 variables or declared global.
4582 if (flags
& (DEF_FREE
| DEF_FREE_CLASS
))
4583 symtable_resolve_free(c
, name
, flags
, &si
);
4585 if (flags
& DEF_STAR
) {
4587 c
->c_flags
|= CO_VARARGS
;
4588 } else if (flags
& DEF_DOUBLESTAR
) {
4590 c
->c_flags
|= CO_VARKEYWORDS
;
4591 } else if (flags
& DEF_INTUPLE
)
4593 else if (flags
& DEF_GLOBAL
) {
4594 if (flags
& DEF_PARAM
) {
4595 PyErr_Format(PyExc_SyntaxError
, LOCAL_GLOBAL
,
4596 PyString_AS_STRING(name
));
4597 PyErr_SyntaxLocation(st
->st_filename
,
4602 if (PyDict_SetItem(c
->c_globals
, name
, Py_None
) < 0)
4604 } else if (flags
& DEF_FREE_GLOBAL
) {
4606 if (PyDict_SetItem(c
->c_globals
, name
, implicit
) < 0)
4608 } else if ((flags
& DEF_LOCAL
) && !(flags
& DEF_PARAM
)) {
4609 v
= PyInt_FromLong(si
.si_nlocals
++);
4612 if (PyDict_SetItem(c
->c_locals
, name
, v
) < 0)
4615 if (ste
->ste_type
!= TYPE_CLASS
)
4616 if (PyList_Append(c
->c_varnames
, name
) < 0)
4618 } else if (is_free(flags
)) {
4619 if (ste
->ste_nested
) {
4620 v
= PyInt_FromLong(si
.si_nfrees
++);
4623 if (PyDict_SetItem(c
->c_freevars
, name
, v
) < 0)
4628 if (PyDict_SetItem(c
->c_globals
, name
,
4631 if (st
->st_nscopes
!= 1) {
4632 v
= PyInt_FromLong(flags
);
4633 if (PyDict_SetItem(st
->st_global
,
4642 assert(PyDict_Size(c
->c_freevars
) == si
.si_nfrees
);
4644 if (si
.si_ncells
> 1) { /* one cell is always in order */
4645 if (symtable_cellvar_offsets(&c
->c_cellvars
, c
->c_argcount
,
4646 c
->c_varnames
, c
->c_flags
) < 0)
4649 if (symtable_freevar_offsets(c
->c_freevars
, si
.si_ncells
) < 0)
4651 return symtable_update_flags(c
, ste
, &si
);
4653 /* is this always the right thing to do? */
4658 static struct symtable
*
4661 struct symtable
*st
;
4663 st
= (struct symtable
*)PyMem_Malloc(sizeof(struct symtable
));
4668 st
->st_filename
= NULL
;
4669 if ((st
->st_stack
= PyList_New(0)) == NULL
)
4671 if ((st
->st_symbols
= PyDict_New()) == NULL
)
4677 st
->st_private
= NULL
;
4680 PySymtable_Free(st
);
4685 PySymtable_Free(struct symtable
*st
)
4687 Py_XDECREF(st
->st_symbols
);
4688 Py_XDECREF(st
->st_stack
);
4689 Py_XDECREF(st
->st_cur
);
4690 PyMem_Free((void *)st
);
4693 /* When the compiler exits a scope, it must should update the scope's
4694 free variable information with the list of free variables in its
4697 Variables that are free in children and defined in the current
4700 If the scope being exited is defined at the top-level (ste_nested is
4701 false), free variables in children that are not defined here are
4707 symtable_update_free_vars(struct symtable
*st
)
4710 PyObject
*o
, *name
, *list
= NULL
;
4711 PySymtableEntryObject
*child
, *ste
= st
->st_cur
;
4713 if (ste
->ste_type
== TYPE_CLASS
)
4714 def
= DEF_FREE_CLASS
;
4717 for (i
= 0; i
< PyList_GET_SIZE(ste
->ste_children
); ++i
) {
4721 PyList_SetSlice(list
, 0,
4722 ((PyVarObject
*)list
)->ob_size
, 0);
4723 child
= (PySymtableEntryObject
*)
4724 PyList_GET_ITEM(ste
->ste_children
, i
);
4725 while (PyDict_Next(child
->ste_symbols
, &pos
, &name
, &o
)) {
4726 int flags
= PyInt_AS_LONG(o
);
4727 if (!(is_free(flags
)))
4728 continue; /* avoids indentation */
4730 list
= PyList_New(0);
4734 ste
->ste_child_free
= 1;
4735 if (PyList_Append(list
, name
) < 0) {
4740 for (j
= 0; list
&& j
< PyList_GET_SIZE(list
); j
++) {
4742 name
= PyList_GET_ITEM(list
, j
);
4743 v
= PyDict_GetItem(ste
->ste_symbols
, name
);
4744 /* If a name N is declared global in scope A and
4745 referenced in scope B contained (perhaps
4746 indirectly) in A and there are no scopes
4747 with bindings for N between B and A, then N
4748 is global in B. Unless A is a class scope,
4749 because class scopes are not considered for
4752 if (v
&& (ste
->ste_type
!= TYPE_CLASS
)) {
4753 int flags
= PyInt_AS_LONG(v
);
4754 if (flags
& DEF_GLOBAL
) {
4755 symtable_undo_free(st
, child
->ste_id
,
4760 if (ste
->ste_nested
) {
4761 if (symtable_add_def_o(st
, ste
->ste_symbols
,
4767 if (symtable_check_global(st
, child
->ste_id
,
4780 /* If the current scope is a non-nested class or if name is not
4781 defined in the current, non-nested scope, then it is an implicit
4782 global in all nested scopes.
4786 symtable_check_global(struct symtable
*st
, PyObject
*child
, PyObject
*name
)
4790 PySymtableEntryObject
*ste
= st
->st_cur
;
4792 if (ste
->ste_type
== TYPE_CLASS
)
4793 return symtable_undo_free(st
, child
, name
);
4794 o
= PyDict_GetItem(ste
->ste_symbols
, name
);
4796 return symtable_undo_free(st
, child
, name
);
4797 v
= PyInt_AS_LONG(o
);
4799 if (is_free(v
) || (v
& DEF_GLOBAL
))
4800 return symtable_undo_free(st
, child
, name
);
4802 return symtable_add_def_o(st
, ste
->ste_symbols
,
4807 symtable_undo_free(struct symtable
*st
, PyObject
*id
,
4812 PySymtableEntryObject
*ste
;
4814 ste
= (PySymtableEntryObject
*)PyDict_GetItem(st
->st_symbols
, id
);
4818 info
= PyDict_GetItem(ste
->ste_symbols
, name
);
4821 v
= PyInt_AS_LONG(info
);
4823 if (symtable_add_def_o(st
, ste
->ste_symbols
, name
,
4824 DEF_FREE_GLOBAL
) < 0)
4827 /* If the name is defined here or declared global,
4828 then the recursion stops. */
4831 for (i
= 0; i
< PyList_GET_SIZE(ste
->ste_children
); ++i
) {
4832 PySymtableEntryObject
*child
;
4833 child
= (PySymtableEntryObject
*)
4834 PyList_GET_ITEM(ste
->ste_children
, i
);
4835 x
= symtable_undo_free(st
, child
->ste_id
, name
);
4842 /* symtable_enter_scope() gets a reference via PySymtableEntry_New().
4843 This reference is released when the scope is exited, via the DECREF
4844 in symtable_exit_scope().
4848 symtable_exit_scope(struct symtable
*st
)
4852 if (st
->st_pass
== 1)
4853 symtable_update_free_vars(st
);
4854 Py_DECREF(st
->st_cur
);
4855 end
= PyList_GET_SIZE(st
->st_stack
) - 1;
4856 st
->st_cur
= (PySymtableEntryObject
*)PyList_GET_ITEM(st
->st_stack
,
4858 if (PySequence_DelItem(st
->st_stack
, end
) < 0)
4864 symtable_enter_scope(struct symtable
*st
, char *name
, int type
,
4867 PySymtableEntryObject
*prev
= NULL
;
4871 if (PyList_Append(st
->st_stack
, (PyObject
*)st
->st_cur
) < 0) {
4872 Py_DECREF(st
->st_cur
);
4877 st
->st_cur
= (PySymtableEntryObject
*)
4878 PySymtableEntry_New(st
, name
, type
, lineno
);
4879 if (strcmp(name
, TOP
) == 0)
4880 st
->st_global
= st
->st_cur
->ste_symbols
;
4881 if (prev
&& st
->st_pass
== 1) {
4882 if (PyList_Append(prev
->ste_children
,
4883 (PyObject
*)st
->st_cur
) < 0)
4889 symtable_lookup(struct symtable
*st
, char *name
)
4891 char buffer
[MANGLE_LEN
];
4895 if (mangle(st
->st_private
, name
, buffer
, sizeof(buffer
)))
4897 v
= PyDict_GetItemString(st
->st_cur
->ste_symbols
, name
);
4899 if (PyErr_Occurred())
4905 flags
= PyInt_AS_LONG(v
);
4910 symtable_add_def(struct symtable
*st
, char *name
, int flag
)
4913 char buffer
[MANGLE_LEN
];
4916 if (mangle(st
->st_private
, name
, buffer
, sizeof(buffer
)))
4918 if ((s
= PyString_InternFromString(name
)) == NULL
)
4920 ret
= symtable_add_def_o(st
, st
->st_cur
->ste_symbols
, s
, flag
);
4925 /* Must only be called with mangled names */
4928 symtable_add_def_o(struct symtable
*st
, PyObject
*dict
,
4929 PyObject
*name
, int flag
)
4934 if ((o
= PyDict_GetItem(dict
, name
))) {
4935 val
= PyInt_AS_LONG(o
);
4936 if ((flag
& DEF_PARAM
) && (val
& DEF_PARAM
)) {
4937 PyErr_Format(PyExc_SyntaxError
, DUPLICATE_ARGUMENT
,
4938 PyString_AsString(name
));
4939 PyErr_SyntaxLocation(st
->st_filename
,
4940 st
->st_cur
->ste_lineno
);
4946 o
= PyInt_FromLong(val
);
4947 if (PyDict_SetItem(dict
, name
, o
) < 0) {
4953 if (flag
& DEF_PARAM
) {
4954 if (PyList_Append(st
->st_cur
->ste_varnames
, name
) < 0)
4956 } else if (flag
& DEF_GLOBAL
) {
4957 /* XXX need to update DEF_GLOBAL for other flags too;
4958 perhaps only DEF_FREE_GLOBAL */
4959 if ((o
= PyDict_GetItem(st
->st_global
, name
))) {
4960 val
= PyInt_AS_LONG(o
);
4964 o
= PyInt_FromLong(val
);
4965 if (PyDict_SetItem(st
->st_global
, name
, o
) < 0) {
4974 #define symtable_add_use(ST, NAME) symtable_add_def((ST), (NAME), USE)
4976 /* Look for a yield stmt under n. Return 1 if found, else 0.
4977 This hack is used to look inside "if 0:" blocks (which are normally
4978 ignored) in case those are the only places a yield occurs (so that this
4979 function is a generator). */
4981 look_for_yield(node
*n
)
4985 for (i
= 0; i
< NCH(n
); ++i
) {
4986 node
*kid
= CHILD(n
, i
);
4988 switch (TYPE(kid
)) {
4993 /* Stuff in nested functions and classes can't make
4994 the parent a generator. */
5001 if (look_for_yield(kid
))
5009 symtable_node(struct symtable
*st
, node
*n
)
5016 char *func_name
= STR(CHILD(n
, 1));
5017 symtable_add_def(st
, func_name
, DEF_LOCAL
);
5018 symtable_default_args(st
, CHILD(n
, 2));
5019 symtable_enter_scope(st
, func_name
, TYPE(n
), n
->n_lineno
);
5020 symtable_funcdef(st
, n
);
5021 symtable_exit_scope(st
);
5026 symtable_default_args(st
, CHILD(n
, 1));
5027 symtable_enter_scope(st
, "lambda", TYPE(n
), n
->n_lineno
);
5028 symtable_funcdef(st
, n
);
5029 symtable_exit_scope(st
);
5032 char *tmp
, *class_name
= STR(CHILD(n
, 1));
5033 symtable_add_def(st
, class_name
, DEF_LOCAL
);
5034 if (TYPE(CHILD(n
, 2)) == LPAR
) {
5035 node
*bases
= CHILD(n
, 3);
5037 for (i
= 0; i
< NCH(bases
); i
+= 2) {
5038 symtable_node(st
, CHILD(bases
, i
));
5041 symtable_enter_scope(st
, class_name
, TYPE(n
), n
->n_lineno
);
5042 tmp
= st
->st_private
;
5043 st
->st_private
= class_name
;
5044 symtable_node(st
, CHILD(n
, NCH(n
) - 1));
5045 st
->st_private
= tmp
;
5046 symtable_exit_scope(st
);
5050 for (i
= 0; i
+ 3 < NCH(n
); i
+= 4) {
5051 if (is_constant_false(NULL
, (CHILD(n
, i
+ 1)))) {
5052 if (st
->st_cur
->ste_generator
== 0)
5053 st
->st_cur
->ste_generator
=
5054 look_for_yield(CHILD(n
, i
+3));
5057 symtable_node(st
, CHILD(n
, i
+ 1));
5058 symtable_node(st
, CHILD(n
, i
+ 3));
5061 symtable_node(st
, CHILD(n
, i
+ 2));
5064 symtable_global(st
, n
);
5067 symtable_import(st
, n
);
5070 st
->st_cur
->ste_optimized
|= OPT_EXEC
;
5071 symtable_node(st
, CHILD(n
, 1));
5073 symtable_node(st
, CHILD(n
, 3));
5075 st
->st_cur
->ste_optimized
|= OPT_BARE_EXEC
;
5076 st
->st_cur
->ste_opt_lineno
= n
->n_lineno
;
5079 symtable_node(st
, CHILD(n
, 5));
5084 if (Py_OptimizeFlag
)
5090 symtable_node(st
, CHILD(n
, 1));
5096 symtable_assign(st
, CHILD(n
, 3), 0);
5103 symtable_assign(st
, CHILD(n
, 1), 0);
5106 st
->st_cur
->ste_generator
= 1;
5113 if (TYPE(CHILD(n
, 1)) == augassign
) {
5114 symtable_assign(st
, CHILD(n
, 0), 0);
5115 symtable_node(st
, CHILD(n
, 2));
5119 for (i
= 0; i
< NCH(n
) - 2; i
+= 2)
5120 symtable_assign(st
, CHILD(n
, i
), 0);
5121 n
= CHILD(n
, NCH(n
) - 1);
5127 if (TYPE(n
) == list_for
) {
5129 symtable_list_comprehension(st
, n
);
5133 symtable_node(st
, CHILD(n
, 1));
5141 symtable_assign(st
, CHILD(n
, 1), 0);
5142 for (i
= 3; i
< NCH(n
); ++i
)
5143 if (TYPE(CHILD(n
, i
)) >= single_input
)
5144 symtable_node(st
, CHILD(n
, i
));
5146 /* The remaining cases fall through to default except in
5147 special circumstances. This requires the individual cases
5148 to be coded with great care, even though they look like
5149 rather innocuous. Each case must double-check TYPE(n).
5152 if (TYPE(n
) == argument
&& NCH(n
) == 3) {
5158 if (NCH(n
) > 1 && TYPE(CHILD(n
, 1)) == list_for
) {
5160 symtable_list_comprehension(st
, CHILD(n
, 1));
5161 symtable_node(st
, CHILD(n
, 0));
5167 if (TYPE(n
) == atom
&& TYPE(CHILD(n
, 0)) == NAME
) {
5168 symtable_add_use(st
, STR(CHILD(n
, 0)));
5173 /* Walk over every non-token child with a special case
5180 for (i
= 0; i
< NCH(n
); ++i
)
5181 if (TYPE(CHILD(n
, i
)) >= single_input
)
5182 symtable_node(st
, CHILD(n
, i
));
5187 symtable_funcdef(struct symtable
*st
, node
*n
)
5191 if (TYPE(n
) == lambdef
) {
5193 symtable_params(st
, CHILD(n
, 1));
5195 symtable_params(st
, CHILD(n
, 2));
5196 body
= CHILD(n
, NCH(n
) - 1);
5197 symtable_node(st
, body
);
5200 /* The next two functions parse the argument tuple.
5201 symtable_default_arg() checks for names in the default arguments,
5202 which are references in the defining scope. symtable_params()
5203 parses the parameter names, which are defined in the function's
5207 (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] | '**' NAME)
5208 | fpdef ['=' test] (',' fpdef ['=' test])* [',']
5212 symtable_default_args(struct symtable
*st
, node
*n
)
5217 if (TYPE(n
) == parameters
) {
5219 if (TYPE(n
) == RPAR
)
5222 REQ(n
, varargslist
);
5223 for (i
= 0; i
< NCH(n
); i
+= 2) {
5225 if (TYPE(c
) == STAR
|| TYPE(c
) == DOUBLESTAR
) {
5228 if (i
> 0 && (TYPE(CHILD(n
, i
- 1)) == EQUAL
))
5229 symtable_node(st
, CHILD(n
, i
));
5234 symtable_params(struct symtable
*st
, node
*n
)
5236 int i
, complex = -1, ext
= 0;
5239 if (TYPE(n
) == parameters
) {
5241 if (TYPE(n
) == RPAR
)
5244 REQ(n
, varargslist
);
5245 for (i
= 0; i
< NCH(n
); i
+= 2) {
5247 if (TYPE(c
) == STAR
|| TYPE(c
) == DOUBLESTAR
) {
5251 if (TYPE(c
) == test
) {
5254 if (TYPE(CHILD(c
, 0)) == NAME
)
5255 symtable_add_def(st
, STR(CHILD(c
, 0)), DEF_PARAM
);
5258 PyOS_snprintf(nbuf
, sizeof(nbuf
), ".%d", i
);
5259 symtable_add_def(st
, nbuf
, DEF_PARAM
);
5265 if (TYPE(c
) == STAR
) {
5267 symtable_add_def(st
, STR(CHILD(n
, i
)),
5268 DEF_PARAM
| DEF_STAR
);
5275 if (c
&& TYPE(c
) == DOUBLESTAR
) {
5277 symtable_add_def(st
, STR(CHILD(n
, i
)),
5278 DEF_PARAM
| DEF_DOUBLESTAR
);
5283 for (j
= 0; j
<= complex; j
++) {
5285 if (TYPE(c
) == COMMA
)
5287 else if (TYPE(c
) == EQUAL
)
5288 c
= CHILD(n
, j
+= 3);
5289 if (TYPE(CHILD(c
, 0)) == LPAR
)
5290 symtable_params_fplist(st
, CHILD(c
, 1));
5296 symtable_params_fplist(struct symtable
*st
, node
*n
)
5302 for (i
= 0; i
< NCH(n
); i
+= 2) {
5306 symtable_add_def(st
, STR(CHILD(c
, 0)),
5307 DEF_PARAM
| DEF_INTUPLE
);
5309 symtable_params_fplist(st
, CHILD(c
, 1));
5315 symtable_global(struct symtable
*st
, node
*n
)
5319 /* XXX It might be helpful to warn about module-level global
5320 statements, but it's hard to tell the difference between
5321 module-level and a string passed to exec.
5324 for (i
= 1; i
< NCH(n
); i
+= 2) {
5325 char *name
= STR(CHILD(n
, i
));
5328 flags
= symtable_lookup(st
, name
);
5331 if (flags
&& flags
!= DEF_GLOBAL
) {
5333 if (flags
& DEF_PARAM
) {
5334 PyErr_Format(PyExc_SyntaxError
,
5335 "name '%.400s' is local and global",
5337 PyErr_SyntaxLocation(st
->st_filename
,
5338 st
->st_cur
->ste_lineno
);
5343 if (flags
& DEF_LOCAL
)
5344 PyOS_snprintf(buf
, sizeof(buf
),
5345 GLOBAL_AFTER_ASSIGN
,
5348 PyOS_snprintf(buf
, sizeof(buf
),
5349 GLOBAL_AFTER_USE
, name
);
5350 symtable_warn(st
, buf
);
5353 symtable_add_def(st
, name
, DEF_GLOBAL
);
5358 symtable_list_comprehension(struct symtable
*st
, node
*n
)
5362 PyOS_snprintf(tmpname
, sizeof(tmpname
), "_[%d]", st
->st_tmpname
);
5363 symtable_add_def(st
, tmpname
, DEF_LOCAL
);
5364 symtable_assign(st
, CHILD(n
, 1), 0);
5365 symtable_node(st
, CHILD(n
, 3));
5367 symtable_node(st
, CHILD(n
, 4));
5371 symtable_import(struct symtable
*st
, node
*n
)
5374 /* import_stmt: 'import' dotted_as_name (',' dotted_as_name)*
5375 | 'from' dotted_name 'import'
5376 ('*' | import_as_name (',' import_as_name)*)
5377 import_as_name: NAME [NAME NAME]
5379 if (STR(CHILD(n
, 0))[0] == 'f') { /* from */
5380 node
*dotname
= CHILD(n
, 1);
5381 if (strcmp(STR(CHILD(dotname
, 0)), "__future__") == 0) {
5382 /* check for bogus imports */
5383 if (n
->n_lineno
>= st
->st_future
->ff_last_lineno
) {
5384 PyErr_SetString(PyExc_SyntaxError
,
5386 PyErr_SyntaxLocation(st
->st_filename
,
5392 if (TYPE(CHILD(n
, 3)) == STAR
) {
5393 if (st
->st_cur
->ste_type
!= TYPE_MODULE
) {
5394 if (symtable_warn(st
,
5395 "import * only allowed at module level") < 0)
5398 st
->st_cur
->ste_optimized
|= OPT_IMPORT_STAR
;
5399 st
->st_cur
->ste_opt_lineno
= n
->n_lineno
;
5401 for (i
= 3; i
< NCH(n
); i
+= 2) {
5402 node
*c
= CHILD(n
, i
);
5403 if (NCH(c
) > 1) /* import as */
5404 symtable_assign(st
, CHILD(c
, 2),
5407 symtable_assign(st
, CHILD(c
, 0),
5412 for (i
= 1; i
< NCH(n
); i
+= 2) {
5413 symtable_assign(st
, CHILD(n
, i
), DEF_IMPORT
);
5418 /* The third argument to symatble_assign() is a flag to be passed to
5419 symtable_add_def() if it is eventually called. The flag is useful
5420 to specify the particular type of assignment that should be
5421 recorded, e.g. an assignment caused by import.
5425 symtable_assign(struct symtable
*st
, node
*n
, int def_flag
)
5433 /* invalid assignment, e.g. lambda x:x=2. The next
5434 pass will catch this error. */
5438 for (i
= 2; i
< NCH(n
); ++i
)
5439 if (TYPE(CHILD(n
, i
)) != DOUBLESTAR
)
5440 symtable_node(st
, CHILD(n
, i
));
5443 symtable_node(st
, CHILD(n
, 0));
5444 symtable_node(st
, CHILD(n
, 1));
5451 if (NCH(n
) > 1 && TYPE(CHILD(n
, 1)) == list_for
) {
5452 /* XXX This is an error, but the next pass
5456 for (i
= 0; i
< NCH(n
); i
+= 2)
5457 symtable_assign(st
, CHILD(n
, i
), def_flag
);
5468 for (i
= 0; i
< NCH(n
); i
+= 2)
5469 symtable_assign(st
, CHILD(n
, i
), def_flag
);
5474 if (TYPE(tmp
) == LPAR
|| TYPE(tmp
) == LSQB
) {
5477 } else if (TYPE(tmp
) == NAME
) {
5478 if (strcmp(STR(tmp
), "__debug__") == 0) {
5479 PyErr_SetString(PyExc_SyntaxError
,
5481 PyErr_SyntaxLocation(st
->st_filename
,
5485 symtable_add_def(st
, STR(tmp
), DEF_LOCAL
| def_flag
);
5488 case dotted_as_name
:
5490 symtable_add_def(st
, STR(CHILD(n
, 2)),
5491 DEF_LOCAL
| def_flag
);
5493 symtable_add_def(st
,
5496 DEF_LOCAL
| def_flag
);
5499 symtable_add_def(st
, STR(CHILD(n
, 0)), DEF_LOCAL
| def_flag
);
5502 symtable_add_def(st
, STR(n
), DEF_LOCAL
| def_flag
);
5511 /* Should only occur for errors like x + 1 = 1,
5512 which will be caught in the next pass. */
5513 for (i
= 0; i
< NCH(n
); ++i
)
5514 if (TYPE(CHILD(n
, i
)) >= single_input
)
5515 symtable_assign(st
, CHILD(n
, i
), def_flag
);