1 /* Compile an expression node to intermediate code */
4 XXX add __doc__ attribute == co_doc to code object attributes?
5 XXX (it's currently the first item of the co_const tuple)
6 XXX Generate simple jump for break/return outside 'try...finally'
7 XXX Allow 'continue' inside finally clause of try-finally
8 XXX New opcode for loading the initial index for a for loop
20 #include "structmember.h"
24 /* Three symbols from graminit.h are also defined in Python.h, with
25 Py_ prefixes to their names. Python.h can't include graminit.h
26 (which defines too many confusing symbols), but we can check here
27 that they haven't changed (which is very unlikely, but possible). */
28 #if Py_single_input != single_input
29 #error "single_input has changed -- update Py_single_input in Python.h"
31 #if Py_file_input != file_input
32 #error "file_input has changed -- update Py_file_input in Python.h"
34 #if Py_eval_input != eval_input
35 #error "eval_input has changed -- update Py_eval_input in Python.h"
38 int Py_OptimizeFlag
= 0;
48 #define DEL_CLOSURE_ERROR \
49 "can not delete variable '%.400s' referenced in nested scope"
51 #define DUPLICATE_ARGUMENT \
52 "duplicate argument '%s' in function definition"
54 #define ILLEGAL_DYNAMIC_SCOPE \
55 "%.100s: exec or 'import *' makes names ambiguous in nested scope"
57 #define GLOBAL_AFTER_ASSIGN \
58 "name '%.400s' is assigned to before global declaration"
60 #define GLOBAL_AFTER_USE \
61 "name '%.400s' is used prior to global declaration"
63 #define LOCAL_GLOBAL \
64 "name '%.400s' is a function paramter and declared global"
67 "from __future__ imports must occur at the beginning of the file"
69 #define ASSIGN_DEBUG \
70 "can not assign to __debug__"
72 #define MANGLE_LEN 256
74 #define OFF(x) offsetof(PyCodeObject, x)
76 static 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 t
= Py_BuildValue("(ziOO)", c
->c_filename
, c
->c_lineno
,
472 w
= Py_BuildValue("(OO)", v
, t
);
475 PyErr_SetObject(exc
, w
);
483 /* Interface to the block stack */
486 block_push(struct compiling
*c
, int type
)
488 if (c
->c_nblocks
>= CO_MAXBLOCKS
) {
489 com_error(c
, PyExc_SystemError
,
490 "too many statically nested blocks");
493 c
->c_block
[c
->c_nblocks
++] = type
;
498 block_pop(struct compiling
*c
, int type
)
500 if (c
->c_nblocks
> 0)
502 if (c
->c_block
[c
->c_nblocks
] != type
&& c
->c_errors
== 0) {
503 com_error(c
, PyExc_SystemError
, "bad block pop");
507 /* Prototype forward declarations */
509 static int com_init(struct compiling
*, char *);
510 static void com_free(struct compiling
*);
511 static void com_push(struct compiling
*, int);
512 static void com_pop(struct compiling
*, int);
513 static void com_done(struct compiling
*);
514 static void com_node(struct compiling
*, node
*);
515 static void com_factor(struct compiling
*, node
*);
516 static void com_addbyte(struct compiling
*, int);
517 static void com_addint(struct compiling
*, int);
518 static void com_addoparg(struct compiling
*, int, int);
519 static void com_addfwref(struct compiling
*, int, int *);
520 static void com_backpatch(struct compiling
*, int);
521 static int com_add(struct compiling
*, PyObject
*, PyObject
*, PyObject
*);
522 static int com_addconst(struct compiling
*, PyObject
*);
523 static int com_addname(struct compiling
*, PyObject
*);
524 static void com_addopname(struct compiling
*, int, node
*);
525 static void com_list(struct compiling
*, node
*, int);
526 static void com_list_iter(struct compiling
*, node
*, node
*, char *);
527 static int com_argdefs(struct compiling
*, node
*);
528 static void com_assign(struct compiling
*, node
*, int, node
*);
529 static void com_assign_name(struct compiling
*, node
*, int);
530 static PyCodeObject
*icompile(node
*, struct compiling
*);
531 static PyCodeObject
*jcompile(node
*, char *, struct compiling
*,
533 static PyObject
*parsestrplus(struct compiling
*, node
*);
534 static PyObject
*parsestr(struct compiling
*, char *);
535 static node
*get_rawdocstring(node
*);
537 static int get_ref_type(struct compiling
*, char *);
539 /* symtable operations */
540 static int symtable_build(struct compiling
*, node
*);
541 static int symtable_load_symbols(struct compiling
*);
542 static struct symtable
*symtable_init(void);
543 static void symtable_enter_scope(struct symtable
*, char *, int, int);
544 static int symtable_exit_scope(struct symtable
*);
545 static int symtable_add_def(struct symtable
*, char *, int);
546 static int symtable_add_def_o(struct symtable
*, PyObject
*, PyObject
*, int);
548 static void symtable_node(struct symtable
*, node
*);
549 static void symtable_funcdef(struct symtable
*, node
*);
550 static void symtable_default_args(struct symtable
*, node
*);
551 static void symtable_params(struct symtable
*, node
*);
552 static void symtable_params_fplist(struct symtable
*, node
*n
);
553 static void symtable_global(struct symtable
*, node
*);
554 static void symtable_import(struct symtable
*, node
*);
555 static void symtable_assign(struct symtable
*, node
*, int);
556 static void symtable_list_comprehension(struct symtable
*, node
*);
558 static int symtable_update_free_vars(struct symtable
*);
559 static int symtable_undo_free(struct symtable
*, PyObject
*, PyObject
*);
560 static int symtable_check_global(struct symtable
*, PyObject
*, PyObject
*);
567 for (i
= 0; i
< pad
; ++i
)
568 fprintf(stderr
, " ");
572 dump(node
*n
, int pad
, int depth
)
578 fprintf(stderr
, "%d: %s\n", TYPE(n
), STR(n
));
581 for (i
= 0; i
< NCH(n
); ++i
)
582 dump(CHILD(n
, i
), pad
+ 1, depth
);
585 #define DUMP(N) dump(N, 0, -1)
588 com_init(struct compiling
*c
, char *filename
)
590 memset((void *)c
, '\0', sizeof(struct compiling
));
591 if ((c
->c_code
= PyString_FromStringAndSize((char *)NULL
,
594 if ((c
->c_consts
= PyList_New(0)) == NULL
)
596 if ((c
->c_const_dict
= PyDict_New()) == NULL
)
598 if ((c
->c_names
= PyList_New(0)) == NULL
)
600 if ((c
->c_name_dict
= PyDict_New()) == NULL
)
602 if ((c
->c_locals
= PyDict_New()) == NULL
)
604 if ((c
->c_lnotab
= PyString_FromStringAndSize((char *)NULL
,
608 c
->c_varnames
= NULL
;
609 c
->c_freevars
= NULL
;
610 c
->c_cellvars
= NULL
;
617 c
->c_interactive
= 0;
621 c
->c_filename
= filename
;
625 c
->c_maxstacklevel
= 0;
626 c
->c_firstlineno
= 0;
629 c
->c_lnotab_next
= 0;
633 c
->c_symtable
= NULL
;
642 com_free(struct compiling
*c
)
644 Py_XDECREF(c
->c_code
);
645 Py_XDECREF(c
->c_consts
);
646 Py_XDECREF(c
->c_const_dict
);
647 Py_XDECREF(c
->c_names
);
648 Py_XDECREF(c
->c_name_dict
);
649 Py_XDECREF(c
->c_globals
);
650 Py_XDECREF(c
->c_locals
);
651 Py_XDECREF(c
->c_varnames
);
652 Py_XDECREF(c
->c_freevars
);
653 Py_XDECREF(c
->c_cellvars
);
654 Py_XDECREF(c
->c_lnotab
);
656 PyMem_Free((void *)c
->c_future
);
660 com_push(struct compiling
*c
, int n
)
662 c
->c_stacklevel
+= n
;
663 if (c
->c_stacklevel
> c
->c_maxstacklevel
) {
664 c
->c_maxstacklevel
= c
->c_stacklevel
;
666 fprintf(stderr, "%s:%s:%d max stack nexti=%d level=%d n=%d\n",
667 c->c_filename, c->c_name, c->c_lineno,
668 c->c_nexti, c->c_stacklevel, n);
674 com_pop(struct compiling
*c
, int n
)
676 if (c
->c_stacklevel
< n
)
679 c
->c_stacklevel
-= n
;
683 com_done(struct compiling
*c
)
685 if (c
->c_code
!= NULL
)
686 _PyString_Resize(&c
->c_code
, c
->c_nexti
);
687 if (c
->c_lnotab
!= NULL
)
688 _PyString_Resize(&c
->c_lnotab
, c
->c_lnotab_next
);
692 com_check_size(PyObject
**s
, int offset
)
694 int len
= PyString_GET_SIZE(*s
);
696 return _PyString_Resize(s
, len
* 2);
701 com_addbyte(struct compiling
*c
, int byte
)
703 /*fprintf(stderr, "%3d: %3d\n", c->c_nexti, byte);*/
704 assert(byte
>= 0 && byte
<= 255);
706 if (com_check_size(&c
->c_code
, c
->c_nexti
)) {
710 PyString_AS_STRING(c
->c_code
)[c
->c_nexti
++] = byte
;
714 com_addint(struct compiling
*c
, int x
)
716 com_addbyte(c
, x
& 0xff);
717 com_addbyte(c
, x
>> 8); /* XXX x should be positive */
721 com_add_lnotab(struct compiling
*c
, int addr
, int line
)
724 if (c
->c_lnotab
== NULL
)
726 if (com_check_size(&c
->c_lnotab
, c
->c_lnotab_next
+ 2)) {
730 p
= PyString_AS_STRING(c
->c_lnotab
) + c
->c_lnotab_next
;
733 c
->c_lnotab_next
+= 2;
737 com_set_lineno(struct compiling
*c
, int lineno
)
739 c
->c_lineno
= lineno
;
740 if (c
->c_firstlineno
== 0) {
741 c
->c_firstlineno
= c
->c_last_line
= lineno
;
744 int incr_addr
= c
->c_nexti
- c
->c_last_addr
;
745 int incr_line
= lineno
- c
->c_last_line
;
746 while (incr_addr
> 255) {
747 com_add_lnotab(c
, 255, 0);
750 while (incr_line
> 255) {
751 com_add_lnotab(c
, incr_addr
, 255);
755 if (incr_addr
> 0 || incr_line
> 0)
756 com_add_lnotab(c
, incr_addr
, incr_line
);
757 c
->c_last_addr
= c
->c_nexti
;
758 c
->c_last_line
= lineno
;
763 com_addoparg(struct compiling
*c
, int op
, int arg
)
765 int extended_arg
= arg
>> 16;
766 if (op
== SET_LINENO
) {
767 com_set_lineno(c
, arg
);
772 com_addbyte(c
, EXTENDED_ARG
);
773 com_addint(c
, extended_arg
);
781 com_addfwref(struct compiling
*c
, int op
, int *p_anchor
)
783 /* Compile a forward reference for backpatching */
790 com_addint(c
, anchor
== 0 ? 0 : here
- anchor
);
794 com_backpatch(struct compiling
*c
, int anchor
)
796 unsigned char *code
= (unsigned char *) PyString_AS_STRING(c
->c_code
);
797 int target
= c
->c_nexti
;
801 /* Make the JUMP instruction at anchor point to target */
802 prev
= code
[anchor
] + (code
[anchor
+1] << 8);
803 dist
= target
- (anchor
+2);
804 code
[anchor
] = dist
& 0xff;
806 code
[anchor
+1] = dist
;
809 com_error(c
, PyExc_SystemError
,
810 "com_backpatch: offset too large");
819 /* Handle literals and names uniformly */
822 com_add(struct compiling
*c
, PyObject
*list
, PyObject
*dict
, PyObject
*v
)
824 PyObject
*w
, *t
, *np
=NULL
;
827 t
= Py_BuildValue("(OO)", v
, v
->ob_type
);
830 w
= PyDict_GetItem(dict
, t
);
834 n
= PyList_Size(list
);
835 np
= PyInt_FromLong(n
);
838 if (PyList_Append(list
, v
) != 0)
840 if (PyDict_SetItem(dict
, t
, np
) != 0)
854 com_addconst(struct compiling
*c
, PyObject
*v
)
856 return com_add(c
, c
->c_consts
, c
->c_const_dict
, v
);
860 com_addname(struct compiling
*c
, PyObject
*v
)
862 return com_add(c
, c
->c_names
, c
->c_name_dict
, v
);
866 mangle(char *p
, char *name
, char *buffer
, size_t maxlen
)
868 /* Name mangling: __private becomes _classname__private.
869 This is independent from how the name is used. */
871 if (p
== NULL
|| name
== NULL
|| name
[0] != '_' || name
[1] != '_')
874 if (nlen
+2 >= maxlen
)
875 return 0; /* Don't mangle __extremely_long_names */
876 if (name
[nlen
-1] == '_' && name
[nlen
-2] == '_')
877 return 0; /* Don't mangle __whatever__ */
878 /* Strip leading underscores from class name */
882 return 0; /* Don't mangle if class is just underscores */
884 if (plen
+ nlen
>= maxlen
)
885 plen
= maxlen
-nlen
-2; /* Truncate class name if too long */
886 /* buffer = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
888 strncpy(buffer
+1, p
, plen
);
889 strcpy(buffer
+1+plen
, name
);
894 com_addop_name(struct compiling
*c
, int op
, char *name
)
898 char buffer
[MANGLE_LEN
];
900 if (mangle(c
->c_private
, name
, buffer
, sizeof(buffer
)))
902 if (name
== NULL
|| (v
= PyString_InternFromString(name
)) == NULL
) {
907 i
= com_addname(c
, v
);
910 com_addoparg(c
, op
, i
);
914 #define NAME_GLOBAL 1
915 #define NAME_DEFAULT 2
916 #define NAME_CLOSURE 3
919 com_lookup_arg(PyObject
*dict
, PyObject
*name
)
921 PyObject
*v
= PyDict_GetItem(dict
, name
);
925 return PyInt_AS_LONG(v
);
929 com_addop_varname(struct compiling
*c
, int kind
, char *name
)
933 int scope
= NAME_DEFAULT
;
935 char buffer
[MANGLE_LEN
];
937 if (mangle(c
->c_private
, name
, buffer
, sizeof(buffer
)))
939 if (name
== NULL
|| (v
= PyString_InternFromString(name
)) == NULL
) {
945 reftype
= get_ref_type(c
, name
);
948 if (c
->c_symtable
->st_cur
->ste_type
== TYPE_FUNCTION
)
951 case GLOBAL_EXPLICIT
:
954 case GLOBAL_IMPLICIT
:
955 if (c
->c_flags
& CO_OPTIMIZED
)
960 scope
= NAME_CLOSURE
;
964 i
= com_addname(c
, v
);
965 if (scope
== NAME_LOCAL
)
966 i
= com_lookup_arg(c
->c_locals
, v
);
967 else if (reftype
== FREE
)
968 i
= com_lookup_arg(c
->c_freevars
, v
);
969 else if (reftype
== CELL
)
970 i
= com_lookup_arg(c
->c_cellvars
, v
);
972 c
->c_errors
++; /* XXX no exception set */
1022 case NAME_CLOSURE
: {
1024 PyOS_snprintf(buf
, sizeof(buf
),
1025 DEL_CLOSURE_ERROR
, name
);
1026 com_error(c
, PyExc_SyntaxError
, buf
);
1034 com_addoparg(c
, op
, i
);
1038 com_addopname(struct compiling
*c
, int op
, node
*n
)
1042 /* XXX it is possible to write this code without the 1000
1043 chars on the total length of dotted names, I just can't be
1044 bothered right now */
1045 if (TYPE(n
) == STAR
)
1047 else if (TYPE(n
) == dotted_name
) {
1051 for (i
= 0; i
< NCH(n
); i
+= 2) {
1052 char *s
= STR(CHILD(n
, i
));
1053 if (p
+ strlen(s
) > buffer
+ (sizeof buffer
) - 2) {
1054 com_error(c
, PyExc_MemoryError
,
1055 "dotted_name too long");
1062 p
= strchr(p
, '\0');
1069 com_addop_name(c
, op
, name
);
1073 parsenumber(struct compiling
*co
, char *s
)
1078 #ifndef WITHOUT_COMPLEX
1084 end
= s
+ strlen(s
) - 1;
1085 #ifndef WITHOUT_COMPLEX
1086 imflag
= *end
== 'j' || *end
== 'J';
1088 if (*end
== 'l' || *end
== 'L')
1089 return PyLong_FromString(s
, (char **)0, 0);
1091 x
= (long) PyOS_strtoul(s
, &end
, 0);
1093 x
= PyOS_strtol(s
, &end
, 0);
1096 return PyLong_FromString(s
, (char **)0, 0);
1097 return PyInt_FromLong(x
);
1099 /* XXX Huge floats may silently fail */
1100 #ifndef WITHOUT_COMPLEX
1103 PyFPE_START_PROTECT("atof", return 0)
1105 PyFPE_END_PROTECT(c
)
1106 return PyComplex_FromCComplex(c
);
1111 PyFPE_START_PROTECT("atof", return 0)
1113 PyFPE_END_PROTECT(dx
)
1114 return PyFloat_FromDouble(dx
);
1119 parsestr(struct compiling
*com
, char *s
)
1130 #ifdef Py_USING_UNICODE
1133 if (isalpha(quote
) || quote
== '_') {
1134 if (quote
== 'u' || quote
== 'U') {
1135 #ifdef Py_USING_UNICODE
1139 com_error(com
, PyExc_SyntaxError
,
1140 "Unicode literals not supported in this Python");
1144 if (quote
== 'r' || quote
== 'R') {
1149 if (quote
!= '\'' && quote
!= '\"') {
1150 PyErr_BadInternalCall();
1155 if (len
> INT_MAX
) {
1156 PyErr_SetString(PyExc_OverflowError
, "string to parse is too long");
1159 if (s
[--len
] != quote
) {
1160 PyErr_BadInternalCall();
1163 if (len
>= 4 && s
[0] == quote
&& s
[1] == quote
) {
1166 if (s
[--len
] != quote
|| s
[--len
] != quote
) {
1167 PyErr_BadInternalCall();
1171 #ifdef Py_USING_UNICODE
1172 if (unicode
|| Py_UnicodeFlag
) {
1174 return PyUnicode_DecodeRawUnicodeEscape(
1177 return PyUnicode_DecodeUnicodeEscape(
1181 if (rawmode
|| strchr(s
, '\\') == NULL
)
1182 return PyString_FromStringAndSize(s
, len
);
1183 v
= PyString_FromStringAndSize((char *)NULL
, len
);
1186 p
= buf
= PyString_AsString(v
);
1195 /* XXX This assumes ASCII! */
1197 case '\\': *p
++ = '\\'; break;
1198 case '\'': *p
++ = '\''; break;
1199 case '\"': *p
++ = '\"'; break;
1200 case 'b': *p
++ = '\b'; break;
1201 case 'f': *p
++ = '\014'; break; /* FF */
1202 case 't': *p
++ = '\t'; break;
1203 case 'n': *p
++ = '\n'; break;
1204 case 'r': *p
++ = '\r'; break;
1205 case 'v': *p
++ = '\013'; break; /* VT */
1206 case 'a': *p
++ = '\007'; break; /* BEL, not classic C */
1207 case '0': case '1': case '2': case '3':
1208 case '4': case '5': case '6': case '7':
1210 if ('0' <= *s
&& *s
<= '7') {
1211 c
= (c
<<3) + *s
++ - '0';
1212 if ('0' <= *s
&& *s
<= '7')
1213 c
= (c
<<3) + *s
++ - '0';
1218 if (isxdigit(Py_CHARMASK(s
[0]))
1219 && isxdigit(Py_CHARMASK(s
[1]))) {
1221 c
= Py_CHARMASK(*s
);
1225 else if (islower(c
))
1230 c
= Py_CHARMASK(*s
);
1234 else if (islower(c
))
1241 PyErr_SetString(PyExc_ValueError
,
1242 "invalid \\x escape");
1251 _PyString_Resize(&v
, (int)(p
- buf
));
1256 parsestrplus(struct compiling
* c
, node
*n
)
1260 REQ(CHILD(n
, 0), STRING
);
1261 if ((v
= parsestr(c
, STR(CHILD(n
, 0)))) != NULL
) {
1262 /* String literal concatenation */
1263 for (i
= 1; i
< NCH(n
); i
++) {
1265 s
= parsestr(c
, STR(CHILD(n
, i
)));
1268 if (PyString_Check(v
) && PyString_Check(s
)) {
1269 PyString_ConcatAndDel(&v
, s
);
1273 #ifdef Py_USING_UNICODE
1276 temp
= PyUnicode_Concat(v
, s
);
1294 com_list_for(struct compiling
*c
, node
*n
, node
*e
, char *t
)
1297 int save_begin
= c
->c_begin
;
1299 /* list_iter: for v in expr [list_iter] */
1300 com_node(c
, CHILD(n
, 3)); /* expr */
1301 com_addbyte(c
, GET_ITER
);
1302 c
->c_begin
= c
->c_nexti
;
1303 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
1304 com_addfwref(c
, FOR_ITER
, &anchor
);
1306 com_assign(c
, CHILD(n
, 1), OP_ASSIGN
, NULL
);
1308 com_list_iter(c
, n
, e
, t
);
1310 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
1311 c
->c_begin
= save_begin
;
1312 com_backpatch(c
, anchor
);
1313 com_pop(c
, 1); /* FOR_ITER has popped this */
1317 com_list_if(struct compiling
*c
, node
*n
, node
*e
, char *t
)
1321 /* list_iter: 'if' test [list_iter] */
1322 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
1323 com_node(c
, CHILD(n
, 1));
1324 com_addfwref(c
, JUMP_IF_FALSE
, &a
);
1325 com_addbyte(c
, POP_TOP
);
1327 com_list_iter(c
, n
, e
, t
);
1328 com_addfwref(c
, JUMP_FORWARD
, &anchor
);
1329 com_backpatch(c
, a
);
1330 /* We jump here with an extra entry which we now pop */
1331 com_addbyte(c
, POP_TOP
);
1332 com_backpatch(c
, anchor
);
1336 com_list_iter(struct compiling
*c
,
1337 node
*p
, /* parent of list_iter node */
1338 node
*e
, /* element expression node */
1339 char *t
/* name of result list temp local */)
1341 /* list_iter is the last child in a listmaker, list_for, or list_if */
1342 node
*n
= CHILD(p
, NCH(p
)-1);
1343 if (TYPE(n
) == list_iter
) {
1347 com_list_for(c
, n
, e
, t
);
1350 com_list_if(c
, n
, e
, t
);
1353 com_error(c
, PyExc_SystemError
,
1354 "invalid list_iter node type");
1358 com_addop_varname(c
, VAR_LOAD
, t
);
1361 com_addoparg(c
, CALL_FUNCTION
, 1);
1362 com_addbyte(c
, POP_TOP
);
1368 com_list_comprehension(struct compiling
*c
, node
*n
)
1370 /* listmaker: test list_for */
1372 PyOS_snprintf(tmpname
, sizeof(tmpname
), "_[%d]", ++c
->c_tmpname
);
1373 com_addoparg(c
, BUILD_LIST
, 0);
1374 com_addbyte(c
, DUP_TOP
); /* leave the result on the stack */
1376 com_addop_name(c
, LOAD_ATTR
, "append");
1377 com_addop_varname(c
, VAR_STORE
, tmpname
);
1379 com_list_for(c
, CHILD(n
, 1), CHILD(n
, 0), tmpname
);
1380 com_addop_varname(c
, VAR_DELETE
, tmpname
);
1385 com_listmaker(struct compiling
*c
, node
*n
)
1387 /* listmaker: test ( list_for | (',' test)* [','] ) */
1388 if (NCH(n
) > 1 && TYPE(CHILD(n
, 1)) == list_for
)
1389 com_list_comprehension(c
, n
);
1393 for (i
= 0; i
< NCH(n
); i
+= 2, len
++)
1394 com_node(c
, CHILD(n
, i
));
1395 com_addoparg(c
, BUILD_LIST
, len
);
1401 com_dictmaker(struct compiling
*c
, node
*n
)
1404 /* dictmaker: test ':' test (',' test ':' value)* [','] */
1405 for (i
= 0; i
+2 < NCH(n
); i
+= 4) {
1406 /* We must arrange things just right for STORE_SUBSCR.
1407 It wants the stack to look like (value) (dict) (key) */
1408 com_addbyte(c
, DUP_TOP
);
1410 com_node(c
, CHILD(n
, i
+2)); /* value */
1411 com_addbyte(c
, ROT_TWO
);
1412 com_node(c
, CHILD(n
, i
)); /* key */
1413 com_addbyte(c
, STORE_SUBSCR
);
1419 com_atom(struct compiling
*c
, node
*n
)
1428 if (TYPE(CHILD(n
, 1)) == RPAR
) {
1429 com_addoparg(c
, BUILD_TUPLE
, 0);
1433 com_node(c
, CHILD(n
, 1));
1435 case LSQB
: /* '[' [listmaker] ']' */
1436 if (TYPE(CHILD(n
, 1)) == RSQB
) {
1437 com_addoparg(c
, BUILD_LIST
, 0);
1441 com_listmaker(c
, CHILD(n
, 1));
1443 case LBRACE
: /* '{' [dictmaker] '}' */
1444 com_addoparg(c
, BUILD_MAP
, 0);
1446 if (TYPE(CHILD(n
, 1)) == dictmaker
)
1447 com_dictmaker(c
, CHILD(n
, 1));
1450 com_node(c
, CHILD(n
, 1));
1451 com_addbyte(c
, UNARY_CONVERT
);
1454 if ((v
= parsenumber(c
, STR(ch
))) == NULL
) {
1458 i
= com_addconst(c
, v
);
1461 com_addoparg(c
, LOAD_CONST
, i
);
1465 v
= parsestrplus(c
, n
);
1471 i
= com_addconst(c
, v
);
1474 com_addoparg(c
, LOAD_CONST
, i
);
1478 com_addop_varname(c
, VAR_LOAD
, STR(ch
));
1482 com_error(c
, PyExc_SystemError
,
1483 "com_atom: unexpected node type");
1488 com_slice(struct compiling
*c
, node
*n
, int op
)
1493 else if (NCH(n
) == 2) {
1494 if (TYPE(CHILD(n
, 0)) != COLON
) {
1495 com_node(c
, CHILD(n
, 0));
1496 com_addbyte(c
, op
+1);
1499 com_node(c
, CHILD(n
, 1));
1500 com_addbyte(c
, op
+2);
1505 com_node(c
, CHILD(n
, 0));
1506 com_node(c
, CHILD(n
, 2));
1507 com_addbyte(c
, op
+3);
1513 com_augassign_slice(struct compiling
*c
, node
*n
, int opcode
, node
*augn
)
1516 com_addbyte(c
, DUP_TOP
);
1518 com_addbyte(c
, SLICE
);
1520 com_addbyte(c
, opcode
);
1522 com_addbyte(c
, ROT_TWO
);
1523 com_addbyte(c
, STORE_SLICE
);
1525 } else if (NCH(n
) == 2 && TYPE(CHILD(n
, 0)) != COLON
) {
1526 com_node(c
, CHILD(n
, 0));
1527 com_addoparg(c
, DUP_TOPX
, 2);
1529 com_addbyte(c
, SLICE
+1);
1532 com_addbyte(c
, opcode
);
1534 com_addbyte(c
, ROT_THREE
);
1535 com_addbyte(c
, STORE_SLICE
+1);
1537 } else if (NCH(n
) == 2) {
1538 com_node(c
, CHILD(n
, 1));
1539 com_addoparg(c
, DUP_TOPX
, 2);
1541 com_addbyte(c
, SLICE
+2);
1544 com_addbyte(c
, opcode
);
1546 com_addbyte(c
, ROT_THREE
);
1547 com_addbyte(c
, STORE_SLICE
+2);
1550 com_node(c
, CHILD(n
, 0));
1551 com_node(c
, CHILD(n
, 2));
1552 com_addoparg(c
, DUP_TOPX
, 3);
1554 com_addbyte(c
, SLICE
+3);
1557 com_addbyte(c
, opcode
);
1559 com_addbyte(c
, ROT_FOUR
);
1560 com_addbyte(c
, STORE_SLICE
+3);
1566 com_argument(struct compiling
*c
, node
*n
, PyObject
**pkeywords
)
1569 REQ(n
, argument
); /* [test '='] test; really [keyword '='] test */
1571 if (*pkeywords
!= NULL
) {
1572 com_error(c
, PyExc_SyntaxError
,
1573 "non-keyword arg after keyword arg");
1576 com_node(c
, CHILD(n
, 0));
1583 } while (NCH(m
) == 1);
1584 if (TYPE(m
) != NAME
) {
1585 /* f(lambda x: x[0] = 3) ends up getting parsed with
1586 * LHS test = lambda x: x[0], and RHS test = 3.
1587 * SF bug 132313 points out that complaining about a keyword
1588 * then is very confusing.
1590 com_error(c
, PyExc_SyntaxError
,
1591 TYPE(m
) == lambdef
?
1592 "lambda cannot contain assignment" :
1593 "keyword can't be an expression");
1596 PyObject
*v
= PyString_InternFromString(STR(m
));
1597 if (v
!= NULL
&& *pkeywords
== NULL
)
1598 *pkeywords
= PyDict_New();
1601 else if (*pkeywords
== NULL
) {
1605 if (PyDict_GetItem(*pkeywords
, v
) != NULL
)
1606 com_error(c
, PyExc_SyntaxError
,
1607 "duplicate keyword argument");
1609 if (PyDict_SetItem(*pkeywords
, v
, v
) != 0)
1611 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, v
));
1616 com_node(c
, CHILD(n
, 2));
1620 com_call_function(struct compiling
*c
, node
*n
)
1622 if (TYPE(n
) == RPAR
) {
1623 com_addoparg(c
, CALL_FUNCTION
, 0);
1626 PyObject
*keywords
= NULL
;
1628 int lineno
= n
->n_lineno
;
1630 int starstar_flag
= 0;
1635 for (i
= 0; i
< NCH(n
); i
+= 2) {
1636 node
*ch
= CHILD(n
, i
);
1637 if (TYPE(ch
) == STAR
||
1638 TYPE(ch
) == DOUBLESTAR
)
1640 if (ch
->n_lineno
!= lineno
) {
1641 lineno
= ch
->n_lineno
;
1642 com_addoparg(c
, SET_LINENO
, lineno
);
1644 com_argument(c
, ch
, &keywords
);
1645 if (keywords
== NULL
)
1650 Py_XDECREF(keywords
);
1651 while (i
< NCH(n
)) {
1652 node
*tok
= CHILD(n
, i
);
1653 node
*ch
= CHILD(n
, i
+1);
1655 switch (TYPE(tok
)) {
1656 case STAR
: star_flag
= 1; break;
1657 case DOUBLESTAR
: starstar_flag
= 1; break;
1661 if (na
> 255 || nk
> 255) {
1662 com_error(c
, PyExc_SyntaxError
,
1663 "more than 255 arguments");
1665 if (star_flag
|| starstar_flag
)
1666 opcode
= CALL_FUNCTION_VAR
- 1 +
1667 star_flag
+ (starstar_flag
<< 1);
1669 opcode
= CALL_FUNCTION
;
1670 com_addoparg(c
, opcode
, na
| (nk
<< 8));
1671 com_pop(c
, na
+ 2*nk
+ star_flag
+ starstar_flag
);
1676 com_select_member(struct compiling
*c
, node
*n
)
1678 com_addopname(c
, LOAD_ATTR
, n
);
1682 com_sliceobj(struct compiling
*c
, node
*n
)
1685 int ns
=2; /* number of slice arguments */
1688 /* first argument */
1689 if (TYPE(CHILD(n
,i
)) == COLON
) {
1690 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1695 com_node(c
, CHILD(n
,i
));
1697 REQ(CHILD(n
,i
),COLON
);
1700 /* second argument */
1701 if (i
< NCH(n
) && TYPE(CHILD(n
,i
)) == test
) {
1702 com_node(c
, CHILD(n
,i
));
1706 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1709 /* remaining arguments */
1710 for (; i
< NCH(n
); i
++) {
1715 /* right argument of ':' missing */
1716 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1720 com_node(c
, CHILD(ch
,1));
1722 com_addoparg(c
, BUILD_SLICE
, ns
);
1723 com_pop(c
, 1 + (ns
== 3));
1727 com_subscript(struct compiling
*c
, node
*n
)
1732 /* check for rubber index */
1733 if (TYPE(ch
) == DOT
&& TYPE(CHILD(n
,1)) == DOT
) {
1734 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_Ellipsis
));
1738 /* check for slice */
1739 if ((TYPE(ch
) == COLON
|| NCH(n
) > 1))
1749 com_subscriptlist(struct compiling
*c
, node
*n
, int assigning
, node
*augn
)
1752 REQ(n
, subscriptlist
);
1753 /* Check to make backward compatible slice behavior for '[i:j]' */
1755 node
*sub
= CHILD(n
, 0); /* subscript */
1756 /* 'Basic' slice, should have exactly one colon. */
1757 if ((TYPE(CHILD(sub
, 0)) == COLON
1758 || (NCH(sub
) > 1 && TYPE(CHILD(sub
, 1)) == COLON
))
1759 && (TYPE(CHILD(sub
,NCH(sub
)-1)) != sliceop
))
1761 switch (assigning
) {
1772 com_augassign_slice(c
, sub
, assigning
, augn
);
1775 com_slice(c
, sub
, op
);
1776 if (op
== STORE_SLICE
)
1778 else if (op
== DELETE_SLICE
)
1783 /* Else normal subscriptlist. Compile each subscript. */
1784 for (i
= 0; i
< NCH(n
); i
+= 2)
1785 com_subscript(c
, CHILD(n
, i
));
1786 /* Put multiple subscripts into a tuple */
1789 com_addoparg(c
, BUILD_TUPLE
, i
);
1792 switch (assigning
) {
1807 if (assigning
> OP_APPLY
) {
1808 com_addoparg(c
, DUP_TOPX
, 2);
1810 com_addbyte(c
, BINARY_SUBSCR
);
1813 com_addbyte(c
, assigning
);
1815 com_addbyte(c
, ROT_THREE
);
1822 com_apply_trailer(struct compiling
*c
, node
*n
)
1825 switch (TYPE(CHILD(n
, 0))) {
1827 com_call_function(c
, CHILD(n
, 1));
1830 com_select_member(c
, CHILD(n
, 1));
1833 com_subscriptlist(c
, CHILD(n
, 1), OP_APPLY
, NULL
);
1836 com_error(c
, PyExc_SystemError
,
1837 "com_apply_trailer: unknown trailer type");
1842 com_power(struct compiling
*c
, node
*n
)
1846 com_atom(c
, CHILD(n
, 0));
1847 for (i
= 1; i
< NCH(n
); i
++) {
1848 if (TYPE(CHILD(n
, i
)) == DOUBLESTAR
) {
1849 com_factor(c
, CHILD(n
, i
+1));
1850 com_addbyte(c
, BINARY_POWER
);
1855 com_apply_trailer(c
, CHILD(n
, i
));
1860 com_invert_constant(struct compiling
*c
, node
*n
)
1862 /* Compute the inverse of int and longs and use them directly,
1863 but be prepared to generate code for all other
1864 possibilities (invalid numbers, floats, complex).
1866 PyObject
*num
, *inv
= NULL
;
1870 num
= parsenumber(c
, STR(n
));
1874 inv
= PyNumber_Invert(num
);
1877 i
= com_addconst(c
, num
);
1879 i
= com_addconst(c
, inv
);
1884 com_addoparg(c
, LOAD_CONST
, i
);
1886 if (num
!= NULL
&& inv
== NULL
)
1887 com_addbyte(c
, UNARY_INVERT
);
1891 is_float_zero(const char *p
)
1893 int found_radix_point
= 0;
1895 while ((ch
= Py_CHARMASK(*p
++)) != '\0') {
1898 /* no reason to believe it's not 0 -- continue */
1901 case 'e': case 'E': case 'j': case 'J':
1902 /* If this was a hex constant, we already would have
1903 returned 0 due to the 'x' or 'X', so 'e' or 'E'
1904 must be an exponent marker, and we haven't yet
1905 seen a non-zero digit, and it doesn't matter what
1906 the exponent is then. For 'j' or 'J' similarly,
1907 except that this is an imaginary 0 then. */
1911 found_radix_point
= 1;
1918 return found_radix_point
;
1922 com_factor(struct compiling
*c
, node
*n
)
1924 int childtype
= TYPE(CHILD(n
, 0));
1925 node
*pfactor
, *ppower
, *patom
, *pnum
;
1927 /* If the unary +, -, or ~ operator is applied to a constant,
1928 don't generate a UNARY_xxx opcode. Just store the
1929 approriate value as a constant. If the value is negative,
1930 extend the string containing the constant and insert a
1931 negative in the 0th position -- unless we're doing unary minus
1932 of a floating zero! In that case the sign is significant, but
1933 the const dict can't distinguish +0.0 from -0.0.
1935 if ((childtype
== PLUS
|| childtype
== MINUS
|| childtype
== TILDE
)
1937 && TYPE((pfactor
= CHILD(n
, 1))) == factor
1938 && NCH(pfactor
) == 1
1939 && TYPE((ppower
= CHILD(pfactor
, 0))) == power
1941 && TYPE((patom
= CHILD(ppower
, 0))) == atom
1942 && TYPE((pnum
= CHILD(patom
, 0))) == NUMBER
1943 && !(childtype
== MINUS
&& is_float_zero(STR(pnum
)))) {
1944 if (childtype
== TILDE
) {
1945 com_invert_constant(c
, pnum
);
1948 if (childtype
== MINUS
) {
1949 char *s
= malloc(strlen(STR(pnum
)) + 2);
1951 com_error(c
, PyExc_MemoryError
, "");
1952 com_addbyte(c
, 255);
1956 strcpy(s
+ 1, STR(pnum
));
1962 else if (childtype
== PLUS
) {
1963 com_factor(c
, CHILD(n
, 1));
1964 com_addbyte(c
, UNARY_POSITIVE
);
1966 else if (childtype
== MINUS
) {
1967 com_factor(c
, CHILD(n
, 1));
1968 com_addbyte(c
, UNARY_NEGATIVE
);
1970 else if (childtype
== TILDE
) {
1971 com_factor(c
, CHILD(n
, 1));
1972 com_addbyte(c
, UNARY_INVERT
);
1975 com_power(c
, CHILD(n
, 0));
1980 com_term(struct compiling
*c
, node
*n
)
1985 com_factor(c
, CHILD(n
, 0));
1986 for (i
= 2; i
< NCH(n
); i
+= 2) {
1987 com_factor(c
, CHILD(n
, i
));
1988 switch (TYPE(CHILD(n
, i
-1))) {
1990 op
= BINARY_MULTIPLY
;
1993 if (c
->c_flags
& CO_FUTURE_DIVISION
)
1994 op
= BINARY_TRUE_DIVIDE
;
2002 op
= BINARY_FLOOR_DIVIDE
;
2005 com_error(c
, PyExc_SystemError
,
2006 "com_term: operator not *, /, // or %");
2015 com_arith_expr(struct compiling
*c
, node
*n
)
2020 com_term(c
, CHILD(n
, 0));
2021 for (i
= 2; i
< NCH(n
); i
+= 2) {
2022 com_term(c
, CHILD(n
, i
));
2023 switch (TYPE(CHILD(n
, i
-1))) {
2028 op
= BINARY_SUBTRACT
;
2031 com_error(c
, PyExc_SystemError
,
2032 "com_arith_expr: operator not + or -");
2041 com_shift_expr(struct compiling
*c
, node
*n
)
2046 com_arith_expr(c
, CHILD(n
, 0));
2047 for (i
= 2; i
< NCH(n
); i
+= 2) {
2048 com_arith_expr(c
, CHILD(n
, i
));
2049 switch (TYPE(CHILD(n
, i
-1))) {
2057 com_error(c
, PyExc_SystemError
,
2058 "com_shift_expr: operator not << or >>");
2067 com_and_expr(struct compiling
*c
, node
*n
)
2072 com_shift_expr(c
, CHILD(n
, 0));
2073 for (i
= 2; i
< NCH(n
); i
+= 2) {
2074 com_shift_expr(c
, CHILD(n
, i
));
2075 if (TYPE(CHILD(n
, i
-1)) == AMPER
) {
2079 com_error(c
, PyExc_SystemError
,
2080 "com_and_expr: operator not &");
2089 com_xor_expr(struct compiling
*c
, node
*n
)
2094 com_and_expr(c
, CHILD(n
, 0));
2095 for (i
= 2; i
< NCH(n
); i
+= 2) {
2096 com_and_expr(c
, CHILD(n
, i
));
2097 if (TYPE(CHILD(n
, i
-1)) == CIRCUMFLEX
) {
2101 com_error(c
, PyExc_SystemError
,
2102 "com_xor_expr: operator not ^");
2111 com_expr(struct compiling
*c
, node
*n
)
2116 com_xor_expr(c
, CHILD(n
, 0));
2117 for (i
= 2; i
< NCH(n
); i
+= 2) {
2118 com_xor_expr(c
, CHILD(n
, i
));
2119 if (TYPE(CHILD(n
, i
-1)) == VBAR
) {
2123 com_error(c
, PyExc_SystemError
,
2124 "com_expr: expr operator not |");
2136 /* comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '=='
2137 | 'in' | 'not' 'in' | 'is' | 'is' not' */
2141 case LESS
: return LT
;
2142 case GREATER
: return GT
;
2143 case EQEQUAL
: /* == */
2144 case EQUAL
: return EQ
;
2145 case LESSEQUAL
: return LE
;
2146 case GREATEREQUAL
: return GE
;
2147 case NOTEQUAL
: return NE
; /* <> or != */
2148 case NAME
: if (strcmp(STR(n
), "in") == 0) return IN
;
2149 if (strcmp(STR(n
), "is") == 0) return IS
;
2152 else if (NCH(n
) == 2) {
2153 switch (TYPE(CHILD(n
, 0))) {
2154 case NAME
: if (strcmp(STR(CHILD(n
, 1)), "in") == 0)
2156 if (strcmp(STR(CHILD(n
, 0)), "is") == 0)
2164 com_comparison(struct compiling
*c
, node
*n
)
2169 REQ(n
, comparison
); /* comparison: expr (comp_op expr)* */
2170 com_expr(c
, CHILD(n
, 0));
2174 /****************************************************************
2175 The following code is generated for all but the last
2176 comparison in a chain:
2178 label: on stack: opcode: jump to:
2184 b, 0-or-1 JUMP_IF_FALSE L1
2188 We are now ready to repeat this sequence for the next
2189 comparison in the chain.
2191 For the last we generate:
2197 If there were any jumps to L1 (i.e., there was more than one
2198 comparison), we generate:
2200 0-or-1 JUMP_FORWARD L2
2205 ****************************************************************/
2209 for (i
= 2; i
< NCH(n
); i
+= 2) {
2210 com_expr(c
, CHILD(n
, i
));
2212 com_addbyte(c
, DUP_TOP
);
2214 com_addbyte(c
, ROT_THREE
);
2216 op
= cmp_type(CHILD(n
, i
-1));
2218 com_error(c
, PyExc_SystemError
,
2219 "com_comparison: unknown comparison op");
2221 com_addoparg(c
, COMPARE_OP
, op
);
2224 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
2225 com_addbyte(c
, POP_TOP
);
2232 com_addfwref(c
, JUMP_FORWARD
, &anchor2
);
2233 com_backpatch(c
, anchor
);
2234 com_addbyte(c
, ROT_TWO
);
2235 com_addbyte(c
, POP_TOP
);
2236 com_backpatch(c
, anchor2
);
2241 com_not_test(struct compiling
*c
, node
*n
)
2243 REQ(n
, not_test
); /* 'not' not_test | comparison */
2245 com_comparison(c
, CHILD(n
, 0));
2248 com_not_test(c
, CHILD(n
, 1));
2249 com_addbyte(c
, UNARY_NOT
);
2254 com_and_test(struct compiling
*c
, node
*n
)
2258 REQ(n
, and_test
); /* not_test ('and' not_test)* */
2262 com_not_test(c
, CHILD(n
, i
));
2263 if ((i
+= 2) >= NCH(n
))
2265 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
2266 com_addbyte(c
, POP_TOP
);
2270 com_backpatch(c
, anchor
);
2274 com_make_closure(struct compiling
*c
, PyCodeObject
*co
)
2276 int i
, free
= PyCode_GetNumFree(co
);
2279 for (i
= 0; i
< free
; ++i
) {
2280 /* Bypass com_addop_varname because it will generate
2281 LOAD_DEREF but LOAD_CLOSURE is needed.
2283 PyObject
*name
= PyTuple_GET_ITEM(co
->co_freevars
, i
);
2286 /* Special case: If a class contains a method with a
2287 free variable that has the same name as a method,
2288 the name will be considered free *and* local in the
2289 class. It should be handled by the closure, as
2290 well as by the normal name loookup logic.
2292 reftype
= get_ref_type(c
, PyString_AS_STRING(name
));
2293 if (reftype
== CELL
)
2294 arg
= com_lookup_arg(c
->c_cellvars
, name
);
2295 else /* (reftype == FREE) */
2296 arg
= com_lookup_arg(c
->c_freevars
, name
);
2298 fprintf(stderr
, "lookup %s in %s %d %d\n"
2299 "freevars of %s: %s\n",
2300 PyObject_REPR(name
),
2303 PyString_AS_STRING(co
->co_name
),
2304 PyObject_REPR(co
->co_freevars
));
2305 Py_FatalError("com_make_closure()");
2307 com_addoparg(c
, LOAD_CLOSURE
, arg
);
2315 com_test(struct compiling
*c
, node
*n
)
2317 REQ(n
, test
); /* and_test ('or' and_test)* | lambdef */
2318 if (NCH(n
) == 1 && TYPE(CHILD(n
, 0)) == lambdef
) {
2321 int ndefs
= com_argdefs(c
, CHILD(n
, 0));
2322 symtable_enter_scope(c
->c_symtable
, "lambda", lambdef
,
2324 co
= icompile(CHILD(n
, 0), c
);
2329 symtable_exit_scope(c
->c_symtable
);
2330 i
= com_addconst(c
, (PyObject
*)co
);
2331 closure
= com_make_closure(c
, co
);
2332 com_addoparg(c
, LOAD_CONST
, i
);
2335 com_addoparg(c
, MAKE_CLOSURE
, ndefs
);
2336 com_pop(c
, PyCode_GetNumFree(co
));
2338 com_addoparg(c
, MAKE_FUNCTION
, ndefs
);
2346 com_and_test(c
, CHILD(n
, i
));
2347 if ((i
+= 2) >= NCH(n
))
2349 com_addfwref(c
, JUMP_IF_TRUE
, &anchor
);
2350 com_addbyte(c
, POP_TOP
);
2354 com_backpatch(c
, anchor
);
2359 com_list(struct compiling
*c
, node
*n
, int toplevel
)
2361 /* exprlist: expr (',' expr)* [',']; likewise for testlist */
2362 if (NCH(n
) == 1 && !toplevel
) {
2363 com_node(c
, CHILD(n
, 0));
2368 len
= (NCH(n
) + 1) / 2;
2369 for (i
= 0; i
< NCH(n
); i
+= 2)
2370 com_node(c
, CHILD(n
, i
));
2371 com_addoparg(c
, BUILD_TUPLE
, len
);
2377 /* Begin of assignment compilation */
2381 com_augassign_attr(struct compiling
*c
, node
*n
, int opcode
, node
*augn
)
2383 com_addbyte(c
, DUP_TOP
);
2385 com_addopname(c
, LOAD_ATTR
, n
);
2387 com_addbyte(c
, opcode
);
2389 com_addbyte(c
, ROT_TWO
);
2390 com_addopname(c
, STORE_ATTR
, n
);
2395 com_assign_attr(struct compiling
*c
, node
*n
, int assigning
)
2397 com_addopname(c
, assigning
? STORE_ATTR
: DELETE_ATTR
, n
);
2398 com_pop(c
, assigning
? 2 : 1);
2402 com_assign_trailer(struct compiling
*c
, node
*n
, int assigning
, node
*augn
)
2405 switch (TYPE(CHILD(n
, 0))) {
2406 case LPAR
: /* '(' [exprlist] ')' */
2407 com_error(c
, PyExc_SyntaxError
,
2408 "can't assign to function call");
2410 case DOT
: /* '.' NAME */
2411 if (assigning
> OP_APPLY
)
2412 com_augassign_attr(c
, CHILD(n
, 1), assigning
, augn
);
2414 com_assign_attr(c
, CHILD(n
, 1), assigning
);
2416 case LSQB
: /* '[' subscriptlist ']' */
2417 com_subscriptlist(c
, CHILD(n
, 1), assigning
, augn
);
2420 com_error(c
, PyExc_SystemError
, "unknown trailer type");
2425 com_assign_sequence(struct compiling
*c
, node
*n
, int assigning
)
2428 if (TYPE(n
) != testlist
&& TYPE(n
) != listmaker
)
2432 com_addoparg(c
, UNPACK_SEQUENCE
, i
);
2435 for (i
= 0; i
< NCH(n
); i
+= 2)
2436 com_assign(c
, CHILD(n
, i
), assigning
, NULL
);
2440 com_augassign_name(struct compiling
*c
, node
*n
, int opcode
, node
*augn
)
2443 com_addop_varname(c
, VAR_LOAD
, STR(n
));
2446 com_addbyte(c
, opcode
);
2448 com_assign_name(c
, n
, OP_ASSIGN
);
2452 com_assign_name(struct compiling
*c
, node
*n
, int assigning
)
2455 com_addop_varname(c
, assigning
? VAR_STORE
: VAR_DELETE
, STR(n
));
2461 com_assign(struct compiling
*c
, node
*n
, int assigning
, node
*augn
)
2463 /* Loop to avoid trivial recursion */
2470 if (assigning
> OP_APPLY
) {
2471 com_error(c
, PyExc_SyntaxError
,
2472 "augmented assign to tuple not possible");
2475 com_assign_sequence(c
, n
, assigning
);
2493 com_error(c
, PyExc_SyntaxError
,
2494 "can't assign to operator");
2500 case power
: /* atom trailer* ('**' power)*
2501 ('+'|'-'|'~') factor | atom trailer* */
2502 if (TYPE(CHILD(n
, 0)) != atom
) {
2503 com_error(c
, PyExc_SyntaxError
,
2504 "can't assign to operator");
2507 if (NCH(n
) > 1) { /* trailer or exponent present */
2509 com_node(c
, CHILD(n
, 0));
2510 for (i
= 1; i
+1 < NCH(n
); i
++) {
2511 if (TYPE(CHILD(n
, i
)) == DOUBLESTAR
) {
2512 com_error(c
, PyExc_SyntaxError
,
2513 "can't assign to operator");
2516 com_apply_trailer(c
, CHILD(n
, i
));
2517 } /* NB i is still alive */
2518 com_assign_trailer(c
,
2519 CHILD(n
, i
), assigning
, augn
);
2526 switch (TYPE(CHILD(n
, 0))) {
2529 if (TYPE(n
) == RPAR
) {
2530 /* XXX Should allow () = () ??? */
2531 com_error(c
, PyExc_SyntaxError
,
2532 "can't assign to ()");
2535 if (assigning
> OP_APPLY
) {
2536 com_error(c
, PyExc_SyntaxError
,
2537 "augmented assign to tuple not possible");
2543 if (TYPE(n
) == RSQB
) {
2544 com_error(c
, PyExc_SyntaxError
,
2545 "can't assign to []");
2548 if (assigning
> OP_APPLY
) {
2549 com_error(c
, PyExc_SyntaxError
,
2550 "augmented assign to list not possible");
2554 && TYPE(CHILD(n
, 1)) == list_for
) {
2555 com_error(c
, PyExc_SyntaxError
,
2556 "can't assign to list comprehension");
2559 com_assign_sequence(c
, n
, assigning
);
2562 if (assigning
> OP_APPLY
)
2563 com_augassign_name(c
, CHILD(n
, 0),
2566 com_assign_name(c
, CHILD(n
, 0),
2570 com_error(c
, PyExc_SyntaxError
,
2571 "can't assign to literal");
2577 com_error(c
, PyExc_SyntaxError
,
2578 "can't assign to lambda");
2582 com_error(c
, PyExc_SystemError
,
2583 "com_assign: bad node");
2591 com_augassign(struct compiling
*c
, node
*n
)
2595 switch (STR(CHILD(CHILD(n
, 1), 0))[0]) {
2596 case '+': opcode
= INPLACE_ADD
; break;
2597 case '-': opcode
= INPLACE_SUBTRACT
; break;
2599 if (STR(CHILD(CHILD(n
, 1), 0))[1] == '/')
2600 opcode
= INPLACE_FLOOR_DIVIDE
;
2601 else if (c
->c_flags
& CO_FUTURE_DIVISION
)
2602 opcode
= INPLACE_TRUE_DIVIDE
;
2604 opcode
= INPLACE_DIVIDE
;
2606 case '%': opcode
= INPLACE_MODULO
; break;
2607 case '<': opcode
= INPLACE_LSHIFT
; break;
2608 case '>': opcode
= INPLACE_RSHIFT
; break;
2609 case '&': opcode
= INPLACE_AND
; break;
2610 case '^': opcode
= INPLACE_XOR
; break;
2611 case '|': opcode
= INPLACE_OR
; break;
2613 if (STR(CHILD(CHILD(n
, 1), 0))[1] == '*')
2614 opcode
= INPLACE_POWER
;
2616 opcode
= INPLACE_MULTIPLY
;
2619 com_error(c
, PyExc_SystemError
, "com_augassign: bad operator");
2622 com_assign(c
, CHILD(n
, 0), opcode
, CHILD(n
, 2));
2626 com_expr_stmt(struct compiling
*c
, node
*n
)
2629 /* testlist (('=' testlist)* | augassign testlist) */
2630 /* Forget it if we have just a doc string here */
2631 if (!c
->c_interactive
&& NCH(n
) == 1 && get_rawdocstring(n
) != NULL
)
2634 com_node(c
, CHILD(n
, NCH(n
)-1));
2635 if (c
->c_interactive
)
2636 com_addbyte(c
, PRINT_EXPR
);
2638 com_addbyte(c
, POP_TOP
);
2641 else if (TYPE(CHILD(n
,1)) == augassign
)
2642 com_augassign(c
, n
);
2645 com_node(c
, CHILD(n
, NCH(n
)-1));
2646 for (i
= 0; i
< NCH(n
)-2; i
+=2) {
2647 if (i
+2 < NCH(n
)-2) {
2648 com_addbyte(c
, DUP_TOP
);
2651 com_assign(c
, CHILD(n
, i
), OP_ASSIGN
, NULL
);
2657 com_assert_stmt(struct compiling
*c
, node
*n
)
2661 REQ(n
, assert_stmt
); /* 'assert' test [',' test] */
2662 /* Generate code like for
2666 raise AssertionError [, <message>]
2668 where <message> is the second test, if present.
2671 if (Py_OptimizeFlag
)
2673 com_addop_name(c
, LOAD_GLOBAL
, "__debug__");
2675 com_addfwref(c
, JUMP_IF_FALSE
, &a
);
2676 com_addbyte(c
, POP_TOP
);
2678 com_node(c
, CHILD(n
, 1));
2679 com_addfwref(c
, JUMP_IF_TRUE
, &b
);
2680 com_addbyte(c
, POP_TOP
);
2682 /* Raise that exception! */
2683 com_addop_name(c
, LOAD_GLOBAL
, "AssertionError");
2685 i
= NCH(n
)/2; /* Either 2 or 4 */
2687 com_node(c
, CHILD(n
, 3));
2688 com_addoparg(c
, RAISE_VARARGS
, i
);
2690 /* The interpreter does not fall through */
2691 /* All jumps converge here */
2692 com_backpatch(c
, a
);
2693 com_backpatch(c
, b
);
2694 com_addbyte(c
, POP_TOP
);
2698 com_print_stmt(struct compiling
*c
, node
*n
)
2701 node
* stream
= NULL
;
2703 REQ(n
, print_stmt
); /* 'print' (test ',')* [test] */
2705 /* are we using the extended print form? */
2706 if (NCH(n
) >= 2 && TYPE(CHILD(n
, 1)) == RIGHTSHIFT
) {
2707 stream
= CHILD(n
, 2);
2708 com_node(c
, stream
);
2709 /* stack: [...] => [... stream] */
2711 if (NCH(n
) > 3 && TYPE(CHILD(n
, 3)) == COMMA
)
2716 for (; i
< NCH(n
); i
+= 2) {
2717 if (stream
!= NULL
) {
2718 com_addbyte(c
, DUP_TOP
);
2719 /* stack: [stream] => [stream stream] */
2721 com_node(c
, CHILD(n
, i
));
2722 /* stack: [stream stream] => [stream stream obj] */
2723 com_addbyte(c
, ROT_TWO
);
2724 /* stack: [stream stream obj] => [stream obj stream] */
2725 com_addbyte(c
, PRINT_ITEM_TO
);
2726 /* stack: [stream obj stream] => [stream] */
2730 com_node(c
, CHILD(n
, i
));
2731 /* stack: [...] => [... obj] */
2732 com_addbyte(c
, PRINT_ITEM
);
2736 /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */
2737 if (TYPE(CHILD(n
, NCH(n
)-1)) == COMMA
) {
2738 if (stream
!= NULL
) {
2739 /* must pop the extra stream object off the stack */
2740 com_addbyte(c
, POP_TOP
);
2741 /* stack: [... stream] => [...] */
2746 if (stream
!= NULL
) {
2747 /* this consumes the last stream object on stack */
2748 com_addbyte(c
, PRINT_NEWLINE_TO
);
2749 /* stack: [... stream] => [...] */
2753 com_addbyte(c
, PRINT_NEWLINE
);
2758 com_return_stmt(struct compiling
*c
, node
*n
)
2760 REQ(n
, return_stmt
); /* 'return' [testlist] */
2761 if (!c
->c_infunction
) {
2762 com_error(c
, PyExc_SyntaxError
, "'return' outside function");
2764 if (c
->c_flags
& CO_GENERATOR
) {
2766 com_error(c
, PyExc_SyntaxError
,
2767 "'return' with argument inside generator");
2771 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
2775 com_node(c
, CHILD(n
, 1));
2776 com_addbyte(c
, RETURN_VALUE
);
2781 com_yield_stmt(struct compiling
*c
, node
*n
)
2784 REQ(n
, yield_stmt
); /* 'yield' testlist */
2785 if (!c
->c_infunction
) {
2786 com_error(c
, PyExc_SyntaxError
, "'yield' outside function");
2789 for (i
= 0; i
< c
->c_nblocks
; ++i
) {
2790 if (c
->c_block
[i
] == SETUP_FINALLY
) {
2791 com_error(c
, PyExc_SyntaxError
,
2792 "'yield' not allowed in a 'try' block "
2793 "with a 'finally' clause");
2797 com_node(c
, CHILD(n
, 1));
2798 com_addbyte(c
, YIELD_VALUE
);
2803 com_raise_stmt(struct compiling
*c
, node
*n
)
2806 REQ(n
, raise_stmt
); /* 'raise' [test [',' test [',' test]]] */
2808 com_node(c
, CHILD(n
, 1));
2810 com_node(c
, CHILD(n
, 3));
2812 com_node(c
, CHILD(n
, 5));
2816 com_addoparg(c
, RAISE_VARARGS
, i
);
2821 com_from_import(struct compiling
*c
, node
*n
)
2823 com_addopname(c
, IMPORT_FROM
, CHILD(n
, 0));
2826 if (strcmp(STR(CHILD(n
, 1)), "as") != 0) {
2827 com_error(c
, PyExc_SyntaxError
, "invalid syntax");
2830 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 2)));
2832 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 0)));
2837 com_import_stmt(struct compiling
*c
, node
*n
)
2840 REQ(n
, import_stmt
);
2841 /* 'import' dotted_name (',' dotted_name)* |
2842 'from' dotted_name 'import' ('*' | NAME (',' NAME)*) */
2843 if (STR(CHILD(n
, 0))[0] == 'f') {
2845 /* 'from' dotted_name 'import' ... */
2846 REQ(CHILD(n
, 1), dotted_name
);
2848 if (TYPE(CHILD(n
, 3)) == STAR
) {
2849 tup
= Py_BuildValue("(s)", "*");
2851 tup
= PyTuple_New((NCH(n
) - 2)/2);
2852 for (i
= 3; i
< NCH(n
); i
+= 2) {
2853 PyTuple_SET_ITEM(tup
, (i
-3)/2,
2854 PyString_FromString(STR(
2855 CHILD(CHILD(n
, i
), 0))));
2858 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, tup
));
2861 com_addopname(c
, IMPORT_NAME
, CHILD(n
, 1));
2862 if (TYPE(CHILD(n
, 3)) == STAR
)
2863 com_addbyte(c
, IMPORT_STAR
);
2865 for (i
= 3; i
< NCH(n
); i
+= 2)
2866 com_from_import(c
, CHILD(n
, i
));
2867 com_addbyte(c
, POP_TOP
);
2873 for (i
= 1; i
< NCH(n
); i
+= 2) {
2874 node
*subn
= CHILD(n
, i
);
2875 REQ(subn
, dotted_as_name
);
2876 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
2878 com_addopname(c
, IMPORT_NAME
, CHILD(subn
, 0));
2879 if (NCH(subn
) > 1) {
2881 if (strcmp(STR(CHILD(subn
, 1)), "as") != 0) {
2882 com_error(c
, PyExc_SyntaxError
,
2886 for (j
=2 ; j
< NCH(CHILD(subn
, 0)); j
+= 2)
2887 com_addopname(c
, LOAD_ATTR
,
2888 CHILD(CHILD(subn
, 0),
2890 com_addop_varname(c
, VAR_STORE
,
2891 STR(CHILD(subn
, 2)));
2893 com_addop_varname(c
, VAR_STORE
,
2894 STR(CHILD(CHILD(subn
, 0),
2902 com_exec_stmt(struct compiling
*c
, node
*n
)
2905 /* exec_stmt: 'exec' expr ['in' expr [',' expr]] */
2906 com_node(c
, CHILD(n
, 1));
2908 com_node(c
, CHILD(n
, 3));
2910 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
2914 com_node(c
, CHILD(n
, 5));
2916 com_addbyte(c
, DUP_TOP
);
2919 com_addbyte(c
, EXEC_STMT
);
2924 is_constant_false(struct compiling
*c
, node
*n
)
2928 /* argument c will be NULL when called from symtable_node() */
2930 /* Label to avoid tail recursion */
2941 for (i
= 0; i
< NCH(n
); i
++) {
2942 node
*ch
= CHILD(n
, i
);
2943 if (TYPE(ch
) == stmt
) {
2978 if (Py_OptimizeFlag
&& strcmp(STR(n
), "__debug__") == 0)
2983 v
= parsenumber(c
, STR(n
));
2988 i
= PyObject_IsTrue(v
);
2993 v
= parsestr(c
, STR(n
));
2998 i
= PyObject_IsTrue(v
);
3007 /* Look under n for a return stmt with an expression.
3008 * This hack is used to find illegal returns under "if 0:" blocks in
3009 * functions already known to be generators (as determined by the symtable
3011 * Return the offending return node if found, else NULL.
3014 look_for_offending_return(node
*n
)
3018 for (i
= 0; i
< NCH(n
); ++i
) {
3019 node
*kid
= CHILD(n
, i
);
3021 switch (TYPE(kid
)) {
3025 /* Stuff in nested functions & classes doesn't
3026 affect the code block we started in. */
3035 node
*bad
= look_for_offending_return(kid
);
3046 com_if_stmt(struct compiling
*c
, node
*n
)
3051 /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */
3052 for (i
= 0; i
+3 < NCH(n
); i
+=4) {
3054 node
*ch
= CHILD(n
, i
+1);
3055 if (is_constant_false(c
, ch
)) {
3056 /* We're going to skip this block. However, if this
3057 is a generator, we have to check the dead code
3058 anyway to make sure there aren't any return stmts
3059 with expressions, in the same scope. */
3060 if (c
->c_flags
& CO_GENERATOR
) {
3061 node
*p
= look_for_offending_return(n
);
3063 int savelineno
= c
->c_lineno
;
3064 c
->c_lineno
= p
->n_lineno
;
3065 com_error(c
, PyExc_SyntaxError
,
3066 "'return' with argument "
3067 "inside generator");
3068 c
->c_lineno
= savelineno
;
3074 com_addoparg(c
, SET_LINENO
, ch
->n_lineno
);
3076 com_addfwref(c
, JUMP_IF_FALSE
, &a
);
3077 com_addbyte(c
, POP_TOP
);
3079 com_node(c
, CHILD(n
, i
+3));
3080 com_addfwref(c
, JUMP_FORWARD
, &anchor
);
3081 com_backpatch(c
, a
);
3082 /* We jump here with an extra entry which we now pop */
3083 com_addbyte(c
, POP_TOP
);
3086 com_node(c
, CHILD(n
, i
+2));
3088 com_backpatch(c
, anchor
);
3092 com_while_stmt(struct compiling
*c
, node
*n
)
3094 int break_anchor
= 0;
3096 int save_begin
= c
->c_begin
;
3097 REQ(n
, while_stmt
); /* 'while' test ':' suite ['else' ':' suite] */
3098 com_addfwref(c
, SETUP_LOOP
, &break_anchor
);
3099 block_push(c
, SETUP_LOOP
);
3100 c
->c_begin
= c
->c_nexti
;
3101 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3102 com_node(c
, CHILD(n
, 1));
3103 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
3104 com_addbyte(c
, POP_TOP
);
3107 com_node(c
, CHILD(n
, 3));
3109 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
3110 c
->c_begin
= save_begin
;
3111 com_backpatch(c
, anchor
);
3112 /* We jump here with one entry more on the stack */
3113 com_addbyte(c
, POP_TOP
);
3114 com_addbyte(c
, POP_BLOCK
);
3115 block_pop(c
, SETUP_LOOP
);
3117 com_node(c
, CHILD(n
, 6));
3118 com_backpatch(c
, break_anchor
);
3122 com_for_stmt(struct compiling
*c
, node
*n
)
3124 int break_anchor
= 0;
3126 int save_begin
= c
->c_begin
;
3128 /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */
3129 com_addfwref(c
, SETUP_LOOP
, &break_anchor
);
3130 block_push(c
, SETUP_LOOP
);
3131 com_node(c
, CHILD(n
, 3));
3132 com_addbyte(c
, GET_ITER
);
3133 c
->c_begin
= c
->c_nexti
;
3134 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3135 com_addfwref(c
, FOR_ITER
, &anchor
);
3137 com_assign(c
, CHILD(n
, 1), OP_ASSIGN
, NULL
);
3139 com_node(c
, CHILD(n
, 5));
3141 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
3142 c
->c_begin
= save_begin
;
3143 com_backpatch(c
, anchor
);
3144 com_pop(c
, 1); /* FOR_ITER has popped this */
3145 com_addbyte(c
, POP_BLOCK
);
3146 block_pop(c
, SETUP_LOOP
);
3148 com_node(c
, CHILD(n
, 8));
3149 com_backpatch(c
, break_anchor
);
3152 /* Code generated for "try: S finally: Sf" is as follows:
3161 The special instructions use the block stack. Each block
3162 stack entry contains the instruction that created it (here
3163 SETUP_FINALLY), the level of the value stack at the time the
3164 block stack entry was created, and a label (here L).
3167 Pushes the current value stack level and the label
3168 onto the block stack.
3170 Pops en entry from the block stack, and pops the value
3171 stack until its level is the same as indicated on the
3172 block stack. (The label is ignored.)
3174 Pops a variable number of entries from the *value* stack
3175 and re-raises the exception they specify. The number of
3176 entries popped depends on the (pseudo) exception type.
3178 The block stack is unwound when an exception is raised:
3179 when a SETUP_FINALLY entry is found, the exception is pushed
3180 onto the value stack (and the exception condition is cleared),
3181 and the interpreter jumps to the label gotten from the block
3184 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
3185 (The contents of the value stack is shown in [], with the top
3186 at the right; 'tb' is trace-back info, 'val' the exception's
3187 associated value, and 'exc' the exception.)
3189 Value stack Label Instruction Argument
3195 [tb, val, exc] L1: DUP )
3196 [tb, val, exc, exc] <evaluate E1> )
3197 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
3198 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
3199 [tb, val, exc, 1] POP )
3201 [tb, val] <assign to V1> (or POP if no V1)
3206 [tb, val, exc, 0] L2: POP
3208 .............................etc.......................
3210 [tb, val, exc, 0] Ln+1: POP
3211 [tb, val, exc] END_FINALLY # re-raise exception
3213 [] L0: <next statement>
3215 Of course, parts are not generated if Vi or Ei is not present.
3219 com_try_except(struct compiling
*c
, node
*n
)
3221 int except_anchor
= 0;
3223 int else_anchor
= 0;
3227 com_addfwref(c
, SETUP_EXCEPT
, &except_anchor
);
3228 block_push(c
, SETUP_EXCEPT
);
3229 com_node(c
, CHILD(n
, 2));
3230 com_addbyte(c
, POP_BLOCK
);
3231 block_pop(c
, SETUP_EXCEPT
);
3232 com_addfwref(c
, JUMP_FORWARD
, &else_anchor
);
3233 com_backpatch(c
, except_anchor
);
3235 i
< NCH(n
) && TYPE(ch
= CHILD(n
, i
)) == except_clause
;
3237 /* except_clause: 'except' [expr [',' var]] */
3238 if (except_anchor
== 0) {
3239 com_error(c
, PyExc_SyntaxError
,
3240 "default 'except:' must be last");
3244 com_push(c
, 3); /* tb, val, exc pushed by exception */
3245 com_addoparg(c
, SET_LINENO
, ch
->n_lineno
);
3247 com_addbyte(c
, DUP_TOP
);
3249 com_node(c
, CHILD(ch
, 1));
3250 com_addoparg(c
, COMPARE_OP
, EXC_MATCH
);
3252 com_addfwref(c
, JUMP_IF_FALSE
, &except_anchor
);
3253 com_addbyte(c
, POP_TOP
);
3256 com_addbyte(c
, POP_TOP
);
3259 com_assign(c
, CHILD(ch
, 3), OP_ASSIGN
, NULL
);
3261 com_addbyte(c
, POP_TOP
);
3264 com_addbyte(c
, POP_TOP
);
3266 com_node(c
, CHILD(n
, i
+2));
3267 com_addfwref(c
, JUMP_FORWARD
, &end_anchor
);
3268 if (except_anchor
) {
3269 com_backpatch(c
, except_anchor
);
3270 /* We come in with [tb, val, exc, 0] on the
3271 stack; one pop and it's the same as
3272 expected at the start of the loop */
3273 com_addbyte(c
, POP_TOP
);
3276 /* We actually come in here with [tb, val, exc] but the
3277 END_FINALLY will zap those and jump around.
3278 The c_stacklevel does not reflect them so we need not pop
3280 com_addbyte(c
, END_FINALLY
);
3281 com_backpatch(c
, else_anchor
);
3283 com_node(c
, CHILD(n
, i
+2));
3284 com_backpatch(c
, end_anchor
);
3288 com_try_finally(struct compiling
*c
, node
*n
)
3290 int finally_anchor
= 0;
3293 com_addfwref(c
, SETUP_FINALLY
, &finally_anchor
);
3294 block_push(c
, SETUP_FINALLY
);
3295 com_node(c
, CHILD(n
, 2));
3296 com_addbyte(c
, POP_BLOCK
);
3297 block_pop(c
, SETUP_FINALLY
);
3298 block_push(c
, END_FINALLY
);
3299 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3300 /* While the generated code pushes only one item,
3301 the try-finally handling can enter here with
3302 up to three items. OK, here are the details:
3303 3 for an exception, 2 for RETURN, 1 for BREAK. */
3305 com_backpatch(c
, finally_anchor
);
3306 ch
= CHILD(n
, NCH(n
)-1);
3307 com_addoparg(c
, SET_LINENO
, ch
->n_lineno
);
3309 com_addbyte(c
, END_FINALLY
);
3310 block_pop(c
, END_FINALLY
);
3311 com_pop(c
, 3); /* Matches the com_push above */
3315 com_try_stmt(struct compiling
*c
, node
*n
)
3318 /* 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
3319 | 'try' ':' suite 'finally' ':' suite */
3320 if (TYPE(CHILD(n
, 3)) != except_clause
)
3321 com_try_finally(c
, n
);
3323 com_try_except(c
, n
);
3327 get_rawdocstring(node
*n
)
3331 /* Label to avoid tail recursion */
3342 for (i
= 0; i
< NCH(n
); i
++) {
3343 node
*ch
= CHILD(n
, i
);
3344 if (TYPE(ch
) == stmt
) {
3378 if (TYPE(CHILD(n
, 0)) == STRING
)
3387 get_docstring(struct compiling
*c
, node
*n
)
3389 /* Don't generate doc-strings if run with -OO */
3390 if (Py_OptimizeFlag
> 1)
3392 n
= get_rawdocstring(n
);
3395 return parsestrplus(c
, n
);
3399 com_suite(struct compiling
*c
, node
*n
)
3402 /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */
3404 com_node(c
, CHILD(n
, 0));
3408 for (i
= 0; i
< NCH(n
) && c
->c_errors
== 0; i
++) {
3409 node
*ch
= CHILD(n
, i
);
3410 if (TYPE(ch
) == stmt
)
3418 com_continue_stmt(struct compiling
*c
, node
*n
)
3420 int i
= c
->c_nblocks
;
3421 if (i
-- > 0 && c
->c_block
[i
] == SETUP_LOOP
) {
3422 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
3425 /* at the outer level */
3426 com_error(c
, PyExc_SyntaxError
,
3427 "'continue' not properly in loop");
3431 for (j
= i
-1; j
>= 0; --j
) {
3432 if (c
->c_block
[j
] == SETUP_LOOP
)
3436 /* there is a loop, but something interferes */
3437 for (; i
> j
; --i
) {
3438 if (c
->c_block
[i
] == SETUP_EXCEPT
||
3439 c
->c_block
[i
] == SETUP_FINALLY
) {
3440 com_addoparg(c
, CONTINUE_LOOP
,
3444 if (c
->c_block
[i
] == END_FINALLY
) {
3445 com_error(c
, PyExc_SyntaxError
,
3446 "'continue' not supported inside 'finally' clause");
3451 com_error(c
, PyExc_SyntaxError
,
3452 "'continue' not properly in loop");
3454 /* XXX Could allow it inside a 'finally' clause
3455 XXX if we could pop the exception still on the stack */
3459 com_argdefs(struct compiling
*c
, node
*n
)
3461 int i
, nch
, nargs
, ndefs
;
3462 if (TYPE(n
) == lambdef
) {
3463 /* lambdef: 'lambda' [varargslist] ':' test */
3467 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ... */
3469 REQ(n
, parameters
); /* parameters: '(' [varargslist] ')' */
3472 if (TYPE(n
) != varargslist
)
3475 (fpdef ['=' test] ',')* '*' ....... |
3476 fpdef ['=' test] (',' fpdef ['=' test])* [','] */
3480 for (i
= 0; i
< nch
; i
++) {
3482 if (TYPE(CHILD(n
, i
)) == STAR
||
3483 TYPE(CHILD(n
, i
)) == DOUBLESTAR
)
3488 t
= RPAR
; /* Anything except EQUAL or COMMA */
3490 t
= TYPE(CHILD(n
, i
));
3494 com_node(c
, CHILD(n
, i
));
3498 t
= TYPE(CHILD(n
, i
));
3501 /* Treat "(a=1, b)" as an error */
3503 com_error(c
, PyExc_SyntaxError
,
3504 "non-default argument follows default argument");
3513 com_funcdef(struct compiling
*c
, node
*n
)
3517 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ':' suite */
3518 ndefs
= com_argdefs(c
, n
);
3519 symtable_enter_scope(c
->c_symtable
, STR(CHILD(n
, 1)), TYPE(n
),
3521 co
= (PyObject
*)icompile(n
, c
);
3522 symtable_exit_scope(c
->c_symtable
);
3526 int closure
= com_make_closure(c
, (PyCodeObject
*)co
);
3527 int i
= com_addconst(c
, co
);
3528 com_addoparg(c
, LOAD_CONST
, i
);
3531 com_addoparg(c
, MAKE_CLOSURE
, ndefs
);
3533 com_addoparg(c
, MAKE_FUNCTION
, ndefs
);
3535 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 1)));
3542 com_bases(struct compiling
*c
, node
*n
)
3546 /* testlist: test (',' test)* [','] */
3547 for (i
= 0; i
< NCH(n
); i
+= 2)
3548 com_node(c
, CHILD(n
, i
));
3550 com_addoparg(c
, BUILD_TUPLE
, i
);
3555 com_classdef(struct compiling
*c
, node
*n
)
3563 /* classdef: class NAME ['(' testlist ')'] ':' suite */
3564 if ((v
= PyString_InternFromString(STR(CHILD(n
, 1)))) == NULL
) {
3568 /* Push the class name on the stack */
3569 i
= com_addconst(c
, v
);
3570 com_addoparg(c
, LOAD_CONST
, i
);
3573 /* Push the tuple of base classes on the stack */
3574 if (TYPE(CHILD(n
, 2)) != LPAR
) {
3575 com_addoparg(c
, BUILD_TUPLE
, 0);
3579 com_bases(c
, CHILD(n
, 3));
3580 name
= STR(CHILD(n
, 1));
3581 symtable_enter_scope(c
->c_symtable
, name
, TYPE(n
), n
->n_lineno
);
3582 co
= icompile(n
, c
);
3583 symtable_exit_scope(c
->c_symtable
);
3587 int closure
= com_make_closure(c
, co
);
3588 i
= com_addconst(c
, (PyObject
*)co
);
3589 com_addoparg(c
, LOAD_CONST
, i
);
3592 com_addoparg(c
, MAKE_CLOSURE
, 0);
3593 com_pop(c
, PyCode_GetNumFree(co
));
3595 com_addoparg(c
, MAKE_FUNCTION
, 0);
3596 com_addoparg(c
, CALL_FUNCTION
, 0);
3597 com_addbyte(c
, BUILD_CLASS
);
3599 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 1)));
3606 com_node(struct compiling
*c
, node
*n
)
3613 /* Definition nodes */
3622 /* Trivial parse tree nodes */
3631 /* small_stmt (';' small_stmt)* [';'] NEWLINE */
3632 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3635 for (i
= 0; i
< NCH(n
)-1; i
+= 2)
3636 com_node(c
, CHILD(n
, i
));
3641 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3645 /* Statement nodes */
3648 com_expr_stmt(c
, n
);
3651 com_print_stmt(c
, n
);
3653 case del_stmt
: /* 'del' exprlist */
3654 com_assign(c
, CHILD(n
, 1), OP_DELETE
, NULL
);
3659 if (c
->c_loops
== 0) {
3660 com_error(c
, PyExc_SyntaxError
,
3661 "'break' outside loop");
3663 com_addbyte(c
, BREAK_LOOP
);
3666 com_continue_stmt(c
, n
);
3669 com_return_stmt(c
, n
);
3672 com_yield_stmt(c
, n
);
3675 com_raise_stmt(c
, n
);
3678 com_import_stmt(c
, n
);
3683 com_exec_stmt(c
, n
);
3686 com_assert_stmt(c
, n
);
3692 com_while_stmt(c
, n
);
3704 /* Expression nodes */
3720 com_comparison(c
, n
);
3735 com_shift_expr(c
, n
);
3738 com_arith_expr(c
, n
);
3754 com_error(c
, PyExc_SystemError
,
3755 "com_node: unexpected node type");
3759 static void com_fplist(struct compiling
*, node
*);
3762 com_fpdef(struct compiling
*c
, node
*n
)
3764 REQ(n
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
3765 if (TYPE(CHILD(n
, 0)) == LPAR
)
3766 com_fplist(c
, CHILD(n
, 1));
3768 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 0)));
3774 com_fplist(struct compiling
*c
, node
*n
)
3776 REQ(n
, fplist
); /* fplist: fpdef (',' fpdef)* [','] */
3778 com_fpdef(c
, CHILD(n
, 0));
3781 int i
= (NCH(n
)+1)/2;
3782 com_addoparg(c
, UNPACK_SEQUENCE
, i
);
3784 for (i
= 0; i
< NCH(n
); i
+= 2)
3785 com_fpdef(c
, CHILD(n
, i
));
3790 com_arglist(struct compiling
*c
, node
*n
)
3795 REQ(n
, varargslist
);
3797 (fpdef ['=' test] ',')* (fpdef ['=' test] | '*' .....) */
3799 /* Enter all arguments in table of locals */
3800 for (i
= 0, narg
= 0; i
< nch
; i
++) {
3801 node
*ch
= CHILD(n
, i
);
3803 if (TYPE(ch
) == STAR
|| TYPE(ch
) == DOUBLESTAR
)
3805 REQ(ch
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
3807 if (TYPE(fp
) != NAME
) {
3808 PyOS_snprintf(nbuf
, sizeof(nbuf
), ".%d", i
);
3812 /* all name updates handled by symtable */
3816 if (TYPE(ch
) == EQUAL
)
3822 /* Generate code for complex arguments only after
3823 having counted the simple arguments */
3825 for (i
= 0; i
< nch
; i
++) {
3826 node
*ch
= CHILD(n
, i
);
3828 if (TYPE(ch
) == STAR
|| TYPE(ch
) == DOUBLESTAR
)
3830 REQ(ch
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
3832 if (TYPE(fp
) != NAME
) {
3833 com_addoparg(c
, LOAD_FAST
, ilocal
);
3841 if (TYPE(ch
) == EQUAL
)
3850 com_file_input(struct compiling
*c
, node
*n
)
3854 REQ(n
, file_input
); /* (NEWLINE | stmt)* ENDMARKER */
3855 doc
= get_docstring(c
, n
);
3857 int i
= com_addconst(c
, doc
);
3859 com_addoparg(c
, LOAD_CONST
, i
);
3861 com_addop_name(c
, STORE_NAME
, "__doc__");
3864 for (i
= 0; i
< NCH(n
); i
++) {
3865 node
*ch
= CHILD(n
, i
);
3866 if (TYPE(ch
) != ENDMARKER
&& TYPE(ch
) != NEWLINE
)
3871 /* Top-level compile-node interface */
3874 compile_funcdef(struct compiling
*c
, node
*n
)
3878 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ':' suite */
3879 c
->c_name
= STR(CHILD(n
, 1));
3880 doc
= get_docstring(c
, CHILD(n
, 4));
3882 (void) com_addconst(c
, doc
);
3886 (void) com_addconst(c
, Py_None
); /* No docstring */
3887 ch
= CHILD(n
, 2); /* parameters: '(' [varargslist] ')' */
3888 ch
= CHILD(ch
, 1); /* ')' | varargslist */
3889 if (TYPE(ch
) == varargslist
)
3891 c
->c_infunction
= 1;
3892 com_node(c
, CHILD(n
, 4));
3893 c
->c_infunction
= 0;
3894 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3896 com_addbyte(c
, RETURN_VALUE
);
3901 compile_lambdef(struct compiling
*c
, node
*n
)
3904 REQ(n
, lambdef
); /* lambdef: 'lambda' [varargslist] ':' test */
3905 c
->c_name
= "<lambda>";
3908 (void) com_addconst(c
, Py_None
); /* No docstring */
3909 if (TYPE(ch
) == varargslist
) {
3916 com_addbyte(c
, RETURN_VALUE
);
3921 compile_classdef(struct compiling
*c
, node
*n
)
3926 /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */
3927 c
->c_name
= STR(CHILD(n
, 1));
3928 c
->c_private
= c
->c_name
;
3929 ch
= CHILD(n
, NCH(n
)-1); /* The suite */
3930 doc
= get_docstring(c
, ch
);
3932 int i
= com_addconst(c
, doc
);
3934 com_addoparg(c
, LOAD_CONST
, i
);
3936 com_addop_name(c
, STORE_NAME
, "__doc__");
3940 (void) com_addconst(c
, Py_None
);
3942 com_addbyte(c
, LOAD_LOCALS
);
3944 com_addbyte(c
, RETURN_VALUE
);
3949 compile_node(struct compiling
*c
, node
*n
)
3951 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3955 case single_input
: /* One interactive command */
3956 /* NEWLINE | simple_stmt | compound_stmt NEWLINE */
3959 if (TYPE(n
) != NEWLINE
)
3961 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3963 com_addbyte(c
, RETURN_VALUE
);
3968 case file_input
: /* A whole file, or built-in function exec() */
3969 com_file_input(c
, n
);
3970 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3972 com_addbyte(c
, RETURN_VALUE
);
3976 case eval_input
: /* Built-in function input() */
3977 com_node(c
, CHILD(n
, 0));
3978 com_addbyte(c
, RETURN_VALUE
);
3982 case lambdef
: /* anonymous function definition */
3983 compile_lambdef(c
, n
);
3986 case funcdef
: /* A function definition */
3987 compile_funcdef(c
, n
);
3990 case classdef
: /* A class definition */
3991 compile_classdef(c
, n
);
3995 com_error(c
, PyExc_SystemError
,
3996 "compile_node: unexpected node type");
4001 dict_keys_inorder(PyObject
*dict
, int offset
)
4003 PyObject
*tuple
, *k
, *v
;
4004 int i
, pos
= 0, size
= PyDict_Size(dict
);
4006 tuple
= PyTuple_New(size
);
4009 while (PyDict_Next(dict
, &pos
, &k
, &v
)) {
4010 i
= PyInt_AS_LONG(v
);
4012 assert((i
- offset
) < size
);
4013 PyTuple_SET_ITEM(tuple
, i
- offset
, k
);
4019 PyNode_Compile(node
*n
, char *filename
)
4021 return PyNode_CompileFlags(n
, filename
, NULL
);
4025 PyNode_CompileFlags(node
*n
, char *filename
, PyCompilerFlags
*flags
)
4027 return jcompile(n
, filename
, NULL
, flags
);
4031 PyNode_CompileSymtable(node
*n
, char *filename
)
4033 struct symtable
*st
;
4034 PyFutureFeatures
*ff
;
4036 ff
= PyNode_Future(n
, filename
);
4040 st
= symtable_init();
4042 PyMem_Free((void *)ff
);
4046 symtable_enter_scope(st
, TOP
, TYPE(n
), n
->n_lineno
);
4047 if (st
->st_errors
> 0)
4049 symtable_node(st
, n
);
4050 if (st
->st_errors
> 0)
4055 PyMem_Free((void *)ff
);
4056 st
->st_future
= NULL
;
4057 PySymtable_Free(st
);
4061 static PyCodeObject
*
4062 icompile(node
*n
, struct compiling
*base
)
4064 return jcompile(n
, base
->c_filename
, base
, NULL
);
4067 static PyCodeObject
*
4068 jcompile(node
*n
, char *filename
, struct compiling
*base
,
4069 PyCompilerFlags
*flags
)
4071 struct compiling sc
;
4073 if (!com_init(&sc
, filename
))
4076 sc
.c_private
= base
->c_private
;
4077 sc
.c_symtable
= base
->c_symtable
;
4078 /* c_symtable still points to parent's symbols */
4080 || (sc
.c_symtable
->st_cur
->ste_type
== TYPE_FUNCTION
))
4082 sc
.c_flags
|= base
->c_flags
& PyCF_MASK
;
4084 sc
.c_private
= NULL
;
4085 sc
.c_future
= PyNode_Future(n
, filename
);
4086 if (sc
.c_future
== NULL
) {
4091 int merged
= sc
.c_future
->ff_features
|
4093 sc
.c_future
->ff_features
= merged
;
4094 flags
->cf_flags
= merged
;
4096 if (symtable_build(&sc
, n
) < 0) {
4102 if (symtable_load_symbols(&sc
) < 0) {
4106 compile_node(&sc
, n
);
4108 if (sc
.c_errors
== 0) {
4109 PyObject
*consts
, *names
, *varnames
, *filename
, *name
,
4110 *freevars
, *cellvars
;
4111 consts
= PyList_AsTuple(sc
.c_consts
);
4112 names
= PyList_AsTuple(sc
.c_names
);
4113 varnames
= PyList_AsTuple(sc
.c_varnames
);
4114 cellvars
= dict_keys_inorder(sc
.c_cellvars
, 0);
4115 freevars
= dict_keys_inorder(sc
.c_freevars
,
4116 PyTuple_GET_SIZE(cellvars
));
4117 filename
= PyString_InternFromString(sc
.c_filename
);
4118 name
= PyString_InternFromString(sc
.c_name
);
4119 if (!PyErr_Occurred())
4120 co
= PyCode_New(sc
.c_argcount
,
4136 Py_XDECREF(varnames
);
4137 Py_XDECREF(freevars
);
4138 Py_XDECREF(cellvars
);
4139 Py_XDECREF(filename
);
4142 else if (!PyErr_Occurred()) {
4143 /* This could happen if someone called PyErr_Clear() after an
4144 error was reported above. That's not supposed to happen,
4145 but I just plugged one case and I'm not sure there can't be
4146 others. In that case, raise SystemError so that at least
4147 it gets reported instead dumping core. */
4148 PyErr_SetString(PyExc_SystemError
, "lost syntax error");
4152 PySymtable_Free(sc
.c_symtable
);
4153 sc
.c_symtable
= NULL
;
4160 PyCode_Addr2Line(PyCodeObject
*co
, int addrq
)
4162 int size
= PyString_Size(co
->co_lnotab
) / 2;
4163 unsigned char *p
= (unsigned char*)PyString_AsString(co
->co_lnotab
);
4164 int line
= co
->co_firstlineno
;
4166 while (--size
>= 0) {
4175 /* The test for LOCAL must come before the test for FREE in order to
4176 handle classes where name is both local and free. The local var is
4177 a method and the free var is a free var referenced within a method.
4181 get_ref_type(struct compiling
*c
, char *name
)
4186 if (PyDict_GetItemString(c
->c_cellvars
, name
) != NULL
)
4188 if (PyDict_GetItemString(c
->c_locals
, name
) != NULL
)
4190 if (PyDict_GetItemString(c
->c_freevars
, name
) != NULL
)
4192 v
= PyDict_GetItemString(c
->c_globals
, name
);
4195 return GLOBAL_EXPLICIT
;
4197 return GLOBAL_IMPLICIT
;
4200 PyOS_snprintf(buf
, sizeof(buf
),
4201 "unknown scope for %.100s in %.100s(%s) "
4202 "in %s\nsymbols: %s\nlocals: %s\nglobals: %s\n",
4204 PyObject_REPR(c
->c_symtable
->st_cur
->ste_id
),
4206 PyObject_REPR(c
->c_symtable
->st_cur
->ste_symbols
),
4207 PyObject_REPR(c
->c_locals
),
4208 PyObject_REPR(c
->c_globals
)
4215 /* Helper functions to issue warnings */
4218 issue_warning(char *msg
, char *filename
, int lineno
)
4220 if (PyErr_WarnExplicit(PyExc_SyntaxWarning
, msg
, filename
,
4221 lineno
, NULL
, NULL
) < 0) {
4222 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning
)) {
4223 PyErr_SetString(PyExc_SyntaxError
, msg
);
4224 PyErr_SyntaxLocation(filename
, lineno
);
4232 symtable_warn(struct symtable
*st
, char *msg
)
4234 if (issue_warning(msg
, st
->st_filename
, st
->st_cur
->ste_lineno
) < 0) {
4241 /* Helper function for setting lineno and filename */
4244 symtable_build(struct compiling
*c
, node
*n
)
4246 if ((c
->c_symtable
= symtable_init()) == NULL
)
4248 c
->c_symtable
->st_future
= c
->c_future
;
4249 c
->c_symtable
->st_filename
= c
->c_filename
;
4250 symtable_enter_scope(c
->c_symtable
, TOP
, TYPE(n
), n
->n_lineno
);
4251 if (c
->c_symtable
->st_errors
> 0)
4253 symtable_node(c
->c_symtable
, n
);
4254 if (c
->c_symtable
->st_errors
> 0)
4256 /* reset for second pass */
4257 c
->c_symtable
->st_nscopes
= 1;
4258 c
->c_symtable
->st_pass
= 2;
4263 symtable_init_compiling_symbols(struct compiling
*c
)
4267 varnames
= c
->c_symtable
->st_cur
->ste_varnames
;
4268 if (varnames
== NULL
) {
4269 varnames
= PyList_New(0);
4270 if (varnames
== NULL
)
4272 c
->c_symtable
->st_cur
->ste_varnames
= varnames
;
4273 Py_INCREF(varnames
);
4275 Py_INCREF(varnames
);
4276 c
->c_varnames
= varnames
;
4278 c
->c_globals
= PyDict_New();
4279 if (c
->c_globals
== NULL
)
4281 c
->c_freevars
= PyDict_New();
4282 if (c
->c_freevars
== NULL
)
4284 c
->c_cellvars
= PyDict_New();
4285 if (c
->c_cellvars
== NULL
)
4290 struct symbol_info
{
4298 symtable_init_info(struct symbol_info
*si
)
4303 si
->si_nimplicit
= 0;
4307 symtable_resolve_free(struct compiling
*c
, PyObject
*name
, int flags
,
4308 struct symbol_info
*si
)
4312 /* Seperate logic for DEF_FREE. If it occurs in a function,
4313 it indicates a local that we must allocate storage for (a
4314 cell var). If it occurs in a class, then the class has a
4315 method and a free variable with the same name.
4317 if (c
->c_symtable
->st_cur
->ste_type
== TYPE_FUNCTION
) {
4318 /* If it isn't declared locally, it can't be a cell. */
4319 if (!(flags
& (DEF_LOCAL
| DEF_PARAM
)))
4321 v
= PyInt_FromLong(si
->si_ncells
++);
4322 dict
= c
->c_cellvars
;
4324 /* If it is free anyway, then there is no need to do
4327 if (is_free(flags
^ DEF_FREE_CLASS
)
4328 || (flags
== DEF_FREE_CLASS
))
4330 v
= PyInt_FromLong(si
->si_nfrees
++);
4331 dict
= c
->c_freevars
;
4335 if (PyDict_SetItem(dict
, name
, v
) < 0) {
4343 /* If a variable is a cell and an argument, make sure that appears in
4344 co_cellvars before any variable to its right in varnames.
4349 symtable_cellvar_offsets(PyObject
**cellvars
, int argcount
,
4350 PyObject
*varnames
, int flags
)
4352 PyObject
*v
, *w
, *d
, *list
= NULL
;
4355 if (flags
& CO_VARARGS
)
4357 if (flags
& CO_VARKEYWORDS
)
4359 for (i
= argcount
; --i
>= 0; ) {
4360 v
= PyList_GET_ITEM(varnames
, i
);
4361 if (PyDict_GetItem(*cellvars
, v
)) {
4363 list
= PyList_New(1);
4366 PyList_SET_ITEM(list
, 0, v
);
4369 PyList_Insert(list
, 0, v
);
4372 if (list
== NULL
|| PyList_GET_SIZE(list
) == 0)
4374 /* There are cellvars that are also arguments. Create a dict
4375 to replace cellvars and put the args at the front.
4378 for (i
= PyList_GET_SIZE(list
); --i
>= 0; ) {
4379 v
= PyInt_FromLong(i
);
4382 if (PyDict_SetItem(d
, PyList_GET_ITEM(list
, i
), v
) < 0)
4384 if (PyDict_DelItem(*cellvars
, PyList_GET_ITEM(list
, i
)) < 0)
4388 i
= PyList_GET_SIZE(list
);
4390 while (PyDict_Next(*cellvars
, &pos
, &v
, &w
)) {
4391 w
= PyInt_FromLong(i
++); /* don't care about the old key */
4392 if (PyDict_SetItem(d
, v
, w
) < 0) {
4398 Py_DECREF(*cellvars
);
4407 symtable_freevar_offsets(PyObject
*freevars
, int offset
)
4412 /* The cell vars are the first elements of the closure,
4413 followed by the free vars. Update the offsets in
4414 c_freevars to account for number of cellvars. */
4416 while (PyDict_Next(freevars
, &pos
, &name
, &v
)) {
4417 int i
= PyInt_AS_LONG(v
) + offset
;
4418 PyObject
*o
= PyInt_FromLong(i
);
4421 if (PyDict_SetItem(freevars
, name
, o
) < 0) {
4431 symtable_check_unoptimized(struct compiling
*c
,
4432 PySymtableEntryObject
*ste
,
4433 struct symbol_info
*si
)
4437 if (!(si
->si_ncells
|| si
->si_nfrees
|| ste
->ste_child_free
4438 || (ste
->ste_nested
&& si
->si_nimplicit
)))
4441 #define ILLEGAL_CONTAINS "contains a nested function with free variables"
4443 #define ILLEGAL_IS "is a nested function"
4445 #define ILLEGAL_IMPORT_STAR \
4446 "import * is not allowed in function '%.100s' because it %s"
4448 #define ILLEGAL_BARE_EXEC \
4449 "unqualified exec is not allowed in function '%.100s' it %s"
4451 #define ILLEGAL_EXEC_AND_IMPORT_STAR \
4452 "function '%.100s' uses import * and bare exec, which are illegal" \
4455 /* XXX perhaps the linenos for these opt-breaking statements
4456 should be stored so the exception can point to them. */
4458 if (ste
->ste_child_free
) {
4459 if (ste
->ste_optimized
== OPT_IMPORT_STAR
)
4460 PyOS_snprintf(buf
, sizeof(buf
),
4461 ILLEGAL_IMPORT_STAR
,
4462 PyString_AS_STRING(ste
->ste_name
),
4464 else if (ste
->ste_optimized
== (OPT_BARE_EXEC
| OPT_EXEC
))
4465 PyOS_snprintf(buf
, sizeof(buf
),
4467 PyString_AS_STRING(ste
->ste_name
),
4470 PyOS_snprintf(buf
, sizeof(buf
),
4471 ILLEGAL_EXEC_AND_IMPORT_STAR
,
4472 PyString_AS_STRING(ste
->ste_name
),
4476 if (ste
->ste_optimized
== OPT_IMPORT_STAR
)
4477 PyOS_snprintf(buf
, sizeof(buf
),
4478 ILLEGAL_IMPORT_STAR
,
4479 PyString_AS_STRING(ste
->ste_name
),
4481 else if (ste
->ste_optimized
== (OPT_BARE_EXEC
| OPT_EXEC
))
4482 PyOS_snprintf(buf
, sizeof(buf
),
4484 PyString_AS_STRING(ste
->ste_name
),
4487 PyOS_snprintf(buf
, sizeof(buf
),
4488 ILLEGAL_EXEC_AND_IMPORT_STAR
,
4489 PyString_AS_STRING(ste
->ste_name
),
4494 PyErr_SetString(PyExc_SyntaxError
, buf
);
4495 PyErr_SyntaxLocation(c
->c_symtable
->st_filename
,
4496 ste
->ste_opt_lineno
);
4501 symtable_update_flags(struct compiling
*c
, PySymtableEntryObject
*ste
,
4502 struct symbol_info
*si
)
4505 c
->c_flags
|= c
->c_future
->ff_features
;
4506 if (ste
->ste_generator
)
4507 c
->c_flags
|= CO_GENERATOR
;
4508 if (ste
->ste_type
!= TYPE_MODULE
)
4509 c
->c_flags
|= CO_NEWLOCALS
;
4510 if (ste
->ste_type
== TYPE_FUNCTION
) {
4511 c
->c_nlocals
= si
->si_nlocals
;
4512 if (ste
->ste_optimized
== 0)
4513 c
->c_flags
|= CO_OPTIMIZED
;
4514 else if (ste
->ste_optimized
!= OPT_EXEC
)
4515 return symtable_check_unoptimized(c
, ste
, si
);
4521 symtable_load_symbols(struct compiling
*c
)
4523 static PyObject
*implicit
= NULL
;
4524 struct symtable
*st
= c
->c_symtable
;
4525 PySymtableEntryObject
*ste
= st
->st_cur
;
4526 PyObject
*name
, *varnames
, *v
;
4528 struct symbol_info si
;
4530 if (implicit
== NULL
) {
4531 implicit
= PyInt_FromLong(1);
4532 if (implicit
== NULL
)
4537 if (symtable_init_compiling_symbols(c
) < 0)
4539 symtable_init_info(&si
);
4540 varnames
= st
->st_cur
->ste_varnames
;
4541 si
.si_nlocals
= PyList_GET_SIZE(varnames
);
4542 c
->c_argcount
= si
.si_nlocals
;
4544 for (i
= 0; i
< si
.si_nlocals
; ++i
) {
4545 v
= PyInt_FromLong(i
);
4546 if (PyDict_SetItem(c
->c_locals
,
4547 PyList_GET_ITEM(varnames
, i
), v
) < 0)
4552 /* XXX The cases below define the rules for whether a name is
4553 local or global. The logic could probably be clearer. */
4555 while (PyDict_Next(ste
->ste_symbols
, &pos
, &name
, &v
)) {
4556 flags
= PyInt_AS_LONG(v
);
4558 if (flags
& DEF_FREE_GLOBAL
)
4559 /* undo the original DEF_FREE */
4560 flags
&= ~(DEF_FREE
| DEF_FREE_CLASS
);
4562 /* Deal with names that need two actions:
4563 1. Cell variables that are also locals.
4564 2. Free variables in methods that are also class
4565 variables or declared global.
4567 if (flags
& (DEF_FREE
| DEF_FREE_CLASS
))
4568 symtable_resolve_free(c
, name
, flags
, &si
);
4570 if (flags
& DEF_STAR
) {
4572 c
->c_flags
|= CO_VARARGS
;
4573 } else if (flags
& DEF_DOUBLESTAR
) {
4575 c
->c_flags
|= CO_VARKEYWORDS
;
4576 } else if (flags
& DEF_INTUPLE
)
4578 else if (flags
& DEF_GLOBAL
) {
4579 if (flags
& DEF_PARAM
) {
4580 PyErr_Format(PyExc_SyntaxError
, LOCAL_GLOBAL
,
4581 PyString_AS_STRING(name
));
4582 PyErr_SyntaxLocation(st
->st_filename
,
4587 if (PyDict_SetItem(c
->c_globals
, name
, Py_None
) < 0)
4589 } else if (flags
& DEF_FREE_GLOBAL
) {
4591 if (PyDict_SetItem(c
->c_globals
, name
, implicit
) < 0)
4593 } else if ((flags
& DEF_LOCAL
) && !(flags
& DEF_PARAM
)) {
4594 v
= PyInt_FromLong(si
.si_nlocals
++);
4597 if (PyDict_SetItem(c
->c_locals
, name
, v
) < 0)
4600 if (ste
->ste_type
!= TYPE_CLASS
)
4601 if (PyList_Append(c
->c_varnames
, name
) < 0)
4603 } else if (is_free(flags
)) {
4604 if (ste
->ste_nested
) {
4605 v
= PyInt_FromLong(si
.si_nfrees
++);
4608 if (PyDict_SetItem(c
->c_freevars
, name
, v
) < 0)
4613 if (PyDict_SetItem(c
->c_globals
, name
,
4616 if (st
->st_nscopes
!= 1) {
4617 v
= PyInt_FromLong(flags
);
4618 if (PyDict_SetItem(st
->st_global
,
4627 assert(PyDict_Size(c
->c_freevars
) == si
.si_nfrees
);
4629 if (si
.si_ncells
> 1) { /* one cell is always in order */
4630 if (symtable_cellvar_offsets(&c
->c_cellvars
, c
->c_argcount
,
4631 c
->c_varnames
, c
->c_flags
) < 0)
4634 if (symtable_freevar_offsets(c
->c_freevars
, si
.si_ncells
) < 0)
4636 return symtable_update_flags(c
, ste
, &si
);
4638 /* is this always the right thing to do? */
4643 static struct symtable
*
4646 struct symtable
*st
;
4648 st
= (struct symtable
*)PyMem_Malloc(sizeof(struct symtable
));
4653 st
->st_filename
= NULL
;
4654 if ((st
->st_stack
= PyList_New(0)) == NULL
)
4656 if ((st
->st_symbols
= PyDict_New()) == NULL
)
4662 st
->st_private
= NULL
;
4665 PySymtable_Free(st
);
4670 PySymtable_Free(struct symtable
*st
)
4672 Py_XDECREF(st
->st_symbols
);
4673 Py_XDECREF(st
->st_stack
);
4674 Py_XDECREF(st
->st_cur
);
4675 PyMem_Free((void *)st
);
4678 /* When the compiler exits a scope, it must should update the scope's
4679 free variable information with the list of free variables in its
4682 Variables that are free in children and defined in the current
4685 If the scope being exited is defined at the top-level (ste_nested is
4686 false), free variables in children that are not defined here are
4692 symtable_update_free_vars(struct symtable
*st
)
4695 PyObject
*o
, *name
, *list
= NULL
;
4696 PySymtableEntryObject
*child
, *ste
= st
->st_cur
;
4698 if (ste
->ste_type
== TYPE_CLASS
)
4699 def
= DEF_FREE_CLASS
;
4702 for (i
= 0; i
< PyList_GET_SIZE(ste
->ste_children
); ++i
) {
4706 PyList_SetSlice(list
, 0,
4707 ((PyVarObject
*)list
)->ob_size
, 0);
4708 child
= (PySymtableEntryObject
*)
4709 PyList_GET_ITEM(ste
->ste_children
, i
);
4710 while (PyDict_Next(child
->ste_symbols
, &pos
, &name
, &o
)) {
4711 int flags
= PyInt_AS_LONG(o
);
4712 if (!(is_free(flags
)))
4713 continue; /* avoids indentation */
4715 list
= PyList_New(0);
4719 ste
->ste_child_free
= 1;
4720 if (PyList_Append(list
, name
) < 0) {
4725 for (j
= 0; list
&& j
< PyList_GET_SIZE(list
); j
++) {
4727 name
= PyList_GET_ITEM(list
, j
);
4728 v
= PyDict_GetItem(ste
->ste_symbols
, name
);
4729 /* If a name N is declared global in scope A and
4730 referenced in scope B contained (perhaps
4731 indirectly) in A and there are no scopes
4732 with bindings for N between B and A, then N
4733 is global in B. Unless A is a class scope,
4734 because class scopes are not considered for
4737 if (v
&& (ste
->ste_type
!= TYPE_CLASS
)) {
4738 int flags
= PyInt_AS_LONG(v
);
4739 if (flags
& DEF_GLOBAL
) {
4740 symtable_undo_free(st
, child
->ste_id
,
4745 if (ste
->ste_nested
) {
4746 if (symtable_add_def_o(st
, ste
->ste_symbols
,
4752 if (symtable_check_global(st
, child
->ste_id
,
4765 /* If the current scope is a non-nested class or if name is not
4766 defined in the current, non-nested scope, then it is an implicit
4767 global in all nested scopes.
4771 symtable_check_global(struct symtable
*st
, PyObject
*child
, PyObject
*name
)
4775 PySymtableEntryObject
*ste
= st
->st_cur
;
4777 if (ste
->ste_type
== TYPE_CLASS
)
4778 return symtable_undo_free(st
, child
, name
);
4779 o
= PyDict_GetItem(ste
->ste_symbols
, name
);
4781 return symtable_undo_free(st
, child
, name
);
4782 v
= PyInt_AS_LONG(o
);
4784 if (is_free(v
) || (v
& DEF_GLOBAL
))
4785 return symtable_undo_free(st
, child
, name
);
4787 return symtable_add_def_o(st
, ste
->ste_symbols
,
4792 symtable_undo_free(struct symtable
*st
, PyObject
*id
,
4797 PySymtableEntryObject
*ste
;
4799 ste
= (PySymtableEntryObject
*)PyDict_GetItem(st
->st_symbols
, id
);
4803 info
= PyDict_GetItem(ste
->ste_symbols
, name
);
4806 v
= PyInt_AS_LONG(info
);
4808 if (symtable_add_def_o(st
, ste
->ste_symbols
, name
,
4809 DEF_FREE_GLOBAL
) < 0)
4812 /* If the name is defined here or declared global,
4813 then the recursion stops. */
4816 for (i
= 0; i
< PyList_GET_SIZE(ste
->ste_children
); ++i
) {
4817 PySymtableEntryObject
*child
;
4818 child
= (PySymtableEntryObject
*)
4819 PyList_GET_ITEM(ste
->ste_children
, i
);
4820 x
= symtable_undo_free(st
, child
->ste_id
, name
);
4827 /* symtable_enter_scope() gets a reference via PySymtableEntry_New().
4828 This reference is released when the scope is exited, via the DECREF
4829 in symtable_exit_scope().
4833 symtable_exit_scope(struct symtable
*st
)
4837 if (st
->st_pass
== 1)
4838 symtable_update_free_vars(st
);
4839 Py_DECREF(st
->st_cur
);
4840 end
= PyList_GET_SIZE(st
->st_stack
) - 1;
4841 st
->st_cur
= (PySymtableEntryObject
*)PyList_GET_ITEM(st
->st_stack
,
4843 if (PySequence_DelItem(st
->st_stack
, end
) < 0)
4849 symtable_enter_scope(struct symtable
*st
, char *name
, int type
,
4852 PySymtableEntryObject
*prev
= NULL
;
4856 if (PyList_Append(st
->st_stack
, (PyObject
*)st
->st_cur
) < 0) {
4857 Py_DECREF(st
->st_cur
);
4862 st
->st_cur
= (PySymtableEntryObject
*)
4863 PySymtableEntry_New(st
, name
, type
, lineno
);
4864 if (strcmp(name
, TOP
) == 0)
4865 st
->st_global
= st
->st_cur
->ste_symbols
;
4866 if (prev
&& st
->st_pass
== 1) {
4867 if (PyList_Append(prev
->ste_children
,
4868 (PyObject
*)st
->st_cur
) < 0)
4874 symtable_lookup(struct symtable
*st
, char *name
)
4876 char buffer
[MANGLE_LEN
];
4880 if (mangle(st
->st_private
, name
, buffer
, sizeof(buffer
)))
4882 v
= PyDict_GetItemString(st
->st_cur
->ste_symbols
, name
);
4884 if (PyErr_Occurred())
4890 flags
= PyInt_AS_LONG(v
);
4895 symtable_add_def(struct symtable
*st
, char *name
, int flag
)
4898 char buffer
[MANGLE_LEN
];
4901 if (mangle(st
->st_private
, name
, buffer
, sizeof(buffer
)))
4903 if ((s
= PyString_InternFromString(name
)) == NULL
)
4905 ret
= symtable_add_def_o(st
, st
->st_cur
->ste_symbols
, s
, flag
);
4910 /* Must only be called with mangled names */
4913 symtable_add_def_o(struct symtable
*st
, PyObject
*dict
,
4914 PyObject
*name
, int flag
)
4919 if ((o
= PyDict_GetItem(dict
, name
))) {
4920 val
= PyInt_AS_LONG(o
);
4921 if ((flag
& DEF_PARAM
) && (val
& DEF_PARAM
)) {
4922 PyErr_Format(PyExc_SyntaxError
, DUPLICATE_ARGUMENT
,
4923 PyString_AsString(name
));
4924 PyErr_SyntaxLocation(st
->st_filename
,
4925 st
->st_cur
->ste_lineno
);
4931 o
= PyInt_FromLong(val
);
4932 if (PyDict_SetItem(dict
, name
, o
) < 0) {
4938 if (flag
& DEF_PARAM
) {
4939 if (PyList_Append(st
->st_cur
->ste_varnames
, name
) < 0)
4941 } else if (flag
& DEF_GLOBAL
) {
4942 /* XXX need to update DEF_GLOBAL for other flags too;
4943 perhaps only DEF_FREE_GLOBAL */
4944 if ((o
= PyDict_GetItem(st
->st_global
, name
))) {
4945 val
= PyInt_AS_LONG(o
);
4949 o
= PyInt_FromLong(val
);
4950 if (PyDict_SetItem(st
->st_global
, name
, o
) < 0) {
4959 #define symtable_add_use(ST, NAME) symtable_add_def((ST), (NAME), USE)
4961 /* Look for a yield stmt under n. Return 1 if found, else 0.
4962 This hack is used to look inside "if 0:" blocks (which are normally
4963 ignored) in case those are the only places a yield occurs (so that this
4964 function is a generator). */
4966 look_for_yield(node
*n
)
4970 for (i
= 0; i
< NCH(n
); ++i
) {
4971 node
*kid
= CHILD(n
, i
);
4973 switch (TYPE(kid
)) {
4978 /* Stuff in nested functions and classes can't make
4979 the parent a generator. */
4986 if (look_for_yield(kid
))
4994 symtable_node(struct symtable
*st
, node
*n
)
5001 char *func_name
= STR(CHILD(n
, 1));
5002 symtable_add_def(st
, func_name
, DEF_LOCAL
);
5003 symtable_default_args(st
, CHILD(n
, 2));
5004 symtable_enter_scope(st
, func_name
, TYPE(n
), n
->n_lineno
);
5005 symtable_funcdef(st
, n
);
5006 symtable_exit_scope(st
);
5011 symtable_default_args(st
, CHILD(n
, 1));
5012 symtable_enter_scope(st
, "lambda", TYPE(n
), n
->n_lineno
);
5013 symtable_funcdef(st
, n
);
5014 symtable_exit_scope(st
);
5017 char *tmp
, *class_name
= STR(CHILD(n
, 1));
5018 symtable_add_def(st
, class_name
, DEF_LOCAL
);
5019 if (TYPE(CHILD(n
, 2)) == LPAR
) {
5020 node
*bases
= CHILD(n
, 3);
5022 for (i
= 0; i
< NCH(bases
); i
+= 2) {
5023 symtable_node(st
, CHILD(bases
, i
));
5026 symtable_enter_scope(st
, class_name
, TYPE(n
), n
->n_lineno
);
5027 tmp
= st
->st_private
;
5028 st
->st_private
= class_name
;
5029 symtable_node(st
, CHILD(n
, NCH(n
) - 1));
5030 st
->st_private
= tmp
;
5031 symtable_exit_scope(st
);
5035 for (i
= 0; i
+ 3 < NCH(n
); i
+= 4) {
5036 if (is_constant_false(NULL
, (CHILD(n
, i
+ 1)))) {
5037 if (st
->st_cur
->ste_generator
== 0)
5038 st
->st_cur
->ste_generator
=
5039 look_for_yield(CHILD(n
, i
+3));
5042 symtable_node(st
, CHILD(n
, i
+ 1));
5043 symtable_node(st
, CHILD(n
, i
+ 3));
5046 symtable_node(st
, CHILD(n
, i
+ 2));
5049 symtable_global(st
, n
);
5052 symtable_import(st
, n
);
5055 st
->st_cur
->ste_optimized
|= OPT_EXEC
;
5056 symtable_node(st
, CHILD(n
, 1));
5058 symtable_node(st
, CHILD(n
, 3));
5060 st
->st_cur
->ste_optimized
|= OPT_BARE_EXEC
;
5061 st
->st_cur
->ste_opt_lineno
= n
->n_lineno
;
5064 symtable_node(st
, CHILD(n
, 5));
5069 if (Py_OptimizeFlag
)
5075 symtable_node(st
, CHILD(n
, 1));
5081 symtable_assign(st
, CHILD(n
, 3), 0);
5088 symtable_assign(st
, CHILD(n
, 1), 0);
5091 st
->st_cur
->ste_generator
= 1;
5098 if (TYPE(CHILD(n
, 1)) == augassign
) {
5099 symtable_assign(st
, CHILD(n
, 0), 0);
5100 symtable_node(st
, CHILD(n
, 2));
5104 for (i
= 0; i
< NCH(n
) - 2; i
+= 2)
5105 symtable_assign(st
, CHILD(n
, i
), 0);
5106 n
= CHILD(n
, NCH(n
) - 1);
5112 if (TYPE(n
) == list_for
) {
5114 symtable_list_comprehension(st
, n
);
5118 symtable_node(st
, CHILD(n
, 1));
5126 symtable_assign(st
, CHILD(n
, 1), 0);
5127 for (i
= 3; i
< NCH(n
); ++i
)
5128 if (TYPE(CHILD(n
, i
)) >= single_input
)
5129 symtable_node(st
, CHILD(n
, i
));
5131 /* The remaining cases fall through to default except in
5132 special circumstances. This requires the individual cases
5133 to be coded with great care, even though they look like
5134 rather innocuous. Each case must double-check TYPE(n).
5137 if (TYPE(n
) == argument
&& NCH(n
) == 3) {
5143 if (NCH(n
) > 1 && TYPE(CHILD(n
, 1)) == list_for
) {
5145 symtable_list_comprehension(st
, CHILD(n
, 1));
5146 symtable_node(st
, CHILD(n
, 0));
5152 if (TYPE(n
) == atom
&& TYPE(CHILD(n
, 0)) == NAME
) {
5153 symtable_add_use(st
, STR(CHILD(n
, 0)));
5158 /* Walk over every non-token child with a special case
5165 for (i
= 0; i
< NCH(n
); ++i
)
5166 if (TYPE(CHILD(n
, i
)) >= single_input
)
5167 symtable_node(st
, CHILD(n
, i
));
5172 symtable_funcdef(struct symtable
*st
, node
*n
)
5176 if (TYPE(n
) == lambdef
) {
5178 symtable_params(st
, CHILD(n
, 1));
5180 symtable_params(st
, CHILD(n
, 2));
5181 body
= CHILD(n
, NCH(n
) - 1);
5182 symtable_node(st
, body
);
5185 /* The next two functions parse the argument tuple.
5186 symtable_default_arg() checks for names in the default arguments,
5187 which are references in the defining scope. symtable_params()
5188 parses the parameter names, which are defined in the function's
5192 (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] | '**' NAME)
5193 | fpdef ['=' test] (',' fpdef ['=' test])* [',']
5197 symtable_default_args(struct symtable
*st
, node
*n
)
5202 if (TYPE(n
) == parameters
) {
5204 if (TYPE(n
) == RPAR
)
5207 REQ(n
, varargslist
);
5208 for (i
= 0; i
< NCH(n
); i
+= 2) {
5210 if (TYPE(c
) == STAR
|| TYPE(c
) == DOUBLESTAR
) {
5213 if (i
> 0 && (TYPE(CHILD(n
, i
- 1)) == EQUAL
))
5214 symtable_node(st
, CHILD(n
, i
));
5219 symtable_params(struct symtable
*st
, node
*n
)
5221 int i
, complex = -1, ext
= 0;
5224 if (TYPE(n
) == parameters
) {
5226 if (TYPE(n
) == RPAR
)
5229 REQ(n
, varargslist
);
5230 for (i
= 0; i
< NCH(n
); i
+= 2) {
5232 if (TYPE(c
) == STAR
|| TYPE(c
) == DOUBLESTAR
) {
5236 if (TYPE(c
) == test
) {
5239 if (TYPE(CHILD(c
, 0)) == NAME
)
5240 symtable_add_def(st
, STR(CHILD(c
, 0)), DEF_PARAM
);
5243 PyOS_snprintf(nbuf
, sizeof(nbuf
), ".%d", i
);
5244 symtable_add_def(st
, nbuf
, DEF_PARAM
);
5250 if (TYPE(c
) == STAR
) {
5252 symtable_add_def(st
, STR(CHILD(n
, i
)),
5253 DEF_PARAM
| DEF_STAR
);
5260 if (c
&& TYPE(c
) == DOUBLESTAR
) {
5262 symtable_add_def(st
, STR(CHILD(n
, i
)),
5263 DEF_PARAM
| DEF_DOUBLESTAR
);
5268 for (j
= 0; j
<= complex; j
++) {
5270 if (TYPE(c
) == COMMA
)
5272 else if (TYPE(c
) == EQUAL
)
5273 c
= CHILD(n
, j
+= 3);
5274 if (TYPE(CHILD(c
, 0)) == LPAR
)
5275 symtable_params_fplist(st
, CHILD(c
, 1));
5281 symtable_params_fplist(struct symtable
*st
, node
*n
)
5287 for (i
= 0; i
< NCH(n
); i
+= 2) {
5291 symtable_add_def(st
, STR(CHILD(c
, 0)),
5292 DEF_PARAM
| DEF_INTUPLE
);
5294 symtable_params_fplist(st
, CHILD(c
, 1));
5300 symtable_global(struct symtable
*st
, node
*n
)
5304 /* XXX It might be helpful to warn about module-level global
5305 statements, but it's hard to tell the difference between
5306 module-level and a string passed to exec.
5309 for (i
= 1; i
< NCH(n
); i
+= 2) {
5310 char *name
= STR(CHILD(n
, i
));
5313 flags
= symtable_lookup(st
, name
);
5316 if (flags
&& flags
!= DEF_GLOBAL
) {
5318 if (flags
& DEF_PARAM
) {
5319 PyErr_Format(PyExc_SyntaxError
,
5320 "name '%.400s' is local and global",
5322 PyErr_SyntaxLocation(st
->st_filename
,
5323 st
->st_cur
->ste_lineno
);
5328 if (flags
& DEF_LOCAL
)
5329 PyOS_snprintf(buf
, sizeof(buf
),
5330 GLOBAL_AFTER_ASSIGN
,
5333 PyOS_snprintf(buf
, sizeof(buf
),
5334 GLOBAL_AFTER_USE
, name
);
5335 symtable_warn(st
, buf
);
5338 symtable_add_def(st
, name
, DEF_GLOBAL
);
5343 symtable_list_comprehension(struct symtable
*st
, node
*n
)
5347 PyOS_snprintf(tmpname
, sizeof(tmpname
), "_[%d]", st
->st_tmpname
);
5348 symtable_add_def(st
, tmpname
, DEF_LOCAL
);
5349 symtable_assign(st
, CHILD(n
, 1), 0);
5350 symtable_node(st
, CHILD(n
, 3));
5352 symtable_node(st
, CHILD(n
, 4));
5356 symtable_import(struct symtable
*st
, node
*n
)
5359 /* import_stmt: 'import' dotted_as_name (',' dotted_as_name)*
5360 | 'from' dotted_name 'import'
5361 ('*' | import_as_name (',' import_as_name)*)
5362 import_as_name: NAME [NAME NAME]
5364 if (STR(CHILD(n
, 0))[0] == 'f') { /* from */
5365 node
*dotname
= CHILD(n
, 1);
5366 if (strcmp(STR(CHILD(dotname
, 0)), "__future__") == 0) {
5367 /* check for bogus imports */
5368 if (n
->n_lineno
>= st
->st_future
->ff_last_lineno
) {
5369 PyErr_SetString(PyExc_SyntaxError
,
5371 PyErr_SyntaxLocation(st
->st_filename
,
5377 if (TYPE(CHILD(n
, 3)) == STAR
) {
5378 if (st
->st_cur
->ste_type
!= TYPE_MODULE
) {
5379 if (symtable_warn(st
,
5380 "import * only allowed at module level") < 0)
5383 st
->st_cur
->ste_optimized
|= OPT_IMPORT_STAR
;
5384 st
->st_cur
->ste_opt_lineno
= n
->n_lineno
;
5386 for (i
= 3; i
< NCH(n
); i
+= 2) {
5387 node
*c
= CHILD(n
, i
);
5388 if (NCH(c
) > 1) /* import as */
5389 symtable_assign(st
, CHILD(c
, 2),
5392 symtable_assign(st
, CHILD(c
, 0),
5397 for (i
= 1; i
< NCH(n
); i
+= 2) {
5398 symtable_assign(st
, CHILD(n
, i
), DEF_IMPORT
);
5403 /* The third argument to symatble_assign() is a flag to be passed to
5404 symtable_add_def() if it is eventually called. The flag is useful
5405 to specify the particular type of assignment that should be
5406 recorded, e.g. an assignment caused by import.
5410 symtable_assign(struct symtable
*st
, node
*n
, int def_flag
)
5418 /* invalid assignment, e.g. lambda x:x=2. The next
5419 pass will catch this error. */
5423 for (i
= 2; i
< NCH(n
); ++i
)
5424 if (TYPE(CHILD(n
, i
)) != DOUBLESTAR
)
5425 symtable_node(st
, CHILD(n
, i
));
5428 symtable_node(st
, CHILD(n
, 0));
5429 symtable_node(st
, CHILD(n
, 1));
5436 if (NCH(n
) > 1 && TYPE(CHILD(n
, 1)) == list_for
) {
5437 /* XXX This is an error, but the next pass
5441 for (i
= 0; i
< NCH(n
); i
+= 2)
5442 symtable_assign(st
, CHILD(n
, i
), def_flag
);
5453 for (i
= 0; i
< NCH(n
); i
+= 2)
5454 symtable_assign(st
, CHILD(n
, i
), def_flag
);
5459 if (TYPE(tmp
) == LPAR
|| TYPE(tmp
) == LSQB
) {
5462 } else if (TYPE(tmp
) == NAME
) {
5463 if (strcmp(STR(tmp
), "__debug__") == 0) {
5464 PyErr_SetString(PyExc_SyntaxError
,
5466 PyErr_SyntaxLocation(st
->st_filename
,
5470 symtable_add_def(st
, STR(tmp
), DEF_LOCAL
| def_flag
);
5473 case dotted_as_name
:
5475 symtable_add_def(st
, STR(CHILD(n
, 2)),
5476 DEF_LOCAL
| def_flag
);
5478 symtable_add_def(st
,
5481 DEF_LOCAL
| def_flag
);
5484 symtable_add_def(st
, STR(CHILD(n
, 0)), DEF_LOCAL
| def_flag
);
5487 symtable_add_def(st
, STR(n
), DEF_LOCAL
| def_flag
);
5496 /* Should only occur for errors like x + 1 = 1,
5497 which will be caught in the next pass. */
5498 for (i
= 0; i
< NCH(n
); ++i
)
5499 if (TYPE(CHILD(n
, i
)) >= single_input
)
5500 symtable_assign(st
, CHILD(n
, i
), def_flag
);