1 /* Compile an expression node to intermediate code */
4 XXX add __doc__ attribute == co_doc to code object attributes?
5 XXX (it's currently the first item of the co_const tuple)
6 XXX Generate simple jump for break/return outside 'try...finally'
7 XXX Allow 'continue' inside finally clause of try-finally
8 XXX New opcode for loading the initial index for a for loop
20 #include "structmember.h"
24 /* Three symbols from graminit.h are also defined in Python.h, with
25 Py_ prefixes to their names. Python.h can't include graminit.h
26 (which defines too many confusing symbols), but we can check here
27 that they haven't changed (which is very unlikely, but possible). */
28 #if Py_single_input != single_input
29 #error "single_input has changed -- update Py_single_input in Python.h"
31 #if Py_file_input != file_input
32 #error "file_input has changed -- update Py_file_input in Python.h"
34 #if Py_eval_input != eval_input
35 #error "eval_input has changed -- update Py_eval_input in Python.h"
38 int Py_OptimizeFlag
= 0;
48 #define DEL_CLOSURE_ERROR \
49 "can not delete variable '%.400s' referenced in nested scope"
51 #define DUPLICATE_ARGUMENT \
52 "duplicate argument '%s' in function definition"
54 #define ILLEGAL_DYNAMIC_SCOPE \
55 "%.100s: exec or 'import *' makes names ambiguous in nested scope"
57 #define GLOBAL_AFTER_ASSIGN \
58 "name '%.400s' is assigned to before global declaration"
60 #define GLOBAL_AFTER_USE \
61 "name '%.400s' is used prior to global declaration"
63 #define LOCAL_GLOBAL \
64 "name '%.400s' is a function parameter and declared global"
67 "from __future__ imports must occur at the beginning of the file"
69 #define ASSIGN_DEBUG \
70 "can not assign to __debug__"
72 #define MANGLE_LEN 256
74 #define OFF(x) offsetof(PyCodeObject, x)
76 static PyMemberDef code_memberlist
[] = {
77 {"co_argcount", T_INT
, OFF(co_argcount
), READONLY
},
78 {"co_nlocals", T_INT
, OFF(co_nlocals
), READONLY
},
79 {"co_stacksize",T_INT
, OFF(co_stacksize
), READONLY
},
80 {"co_flags", T_INT
, OFF(co_flags
), READONLY
},
81 {"co_code", T_OBJECT
, OFF(co_code
), READONLY
},
82 {"co_consts", T_OBJECT
, OFF(co_consts
), READONLY
},
83 {"co_names", T_OBJECT
, OFF(co_names
), READONLY
},
84 {"co_varnames", T_OBJECT
, OFF(co_varnames
), READONLY
},
85 {"co_freevars", T_OBJECT
, OFF(co_freevars
), READONLY
},
86 {"co_cellvars", T_OBJECT
, OFF(co_cellvars
), READONLY
},
87 {"co_filename", T_OBJECT
, OFF(co_filename
), READONLY
},
88 {"co_name", T_OBJECT
, OFF(co_name
), READONLY
},
89 {"co_firstlineno", T_INT
, OFF(co_firstlineno
), READONLY
},
90 {"co_lnotab", T_OBJECT
, OFF(co_lnotab
), READONLY
},
94 PyDoc_STRVAR(code_doc
,
95 "code(argcount, nlocals, stacksize, flags, codestring, constants, names,\n\
96 varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]])\n\
98 Create a code object. Not for the faint of heart.");
101 code_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kw
)
108 PyObject
*empty
= NULL
;
113 PyObject
*freevars
= NULL
;
114 PyObject
*cellvars
= NULL
;
120 if (!PyArg_ParseTuple(args
, "iiiiSO!O!O!SSiS|O!O!:code",
121 &argcount
, &nlocals
, &stacksize
, &flags
,
123 &PyTuple_Type
, &consts
,
124 &PyTuple_Type
, &names
,
125 &PyTuple_Type
, &varnames
,
127 &firstlineno
, &lnotab
,
128 &PyTuple_Type
, &freevars
,
129 &PyTuple_Type
, &cellvars
))
132 if (!PyObject_CheckReadBuffer(code
)) {
133 PyErr_SetString(PyExc_TypeError
,
134 "bytecode object must be a single-segment read-only buffer");
138 if (freevars
== NULL
|| cellvars
== NULL
) {
139 empty
= PyTuple_New(0);
142 if (freevars
== NULL
)
144 if (cellvars
== NULL
)
148 co
= (PyObject
*) PyCode_New(argcount
, nlocals
, stacksize
, flags
,
149 code
, consts
, names
, varnames
,
150 freevars
, cellvars
, filename
, name
,
151 firstlineno
, lnotab
);
157 code_dealloc(PyCodeObject
*co
)
159 Py_XDECREF(co
->co_code
);
160 Py_XDECREF(co
->co_consts
);
161 Py_XDECREF(co
->co_names
);
162 Py_XDECREF(co
->co_varnames
);
163 Py_XDECREF(co
->co_freevars
);
164 Py_XDECREF(co
->co_cellvars
);
165 Py_XDECREF(co
->co_filename
);
166 Py_XDECREF(co
->co_name
);
167 Py_XDECREF(co
->co_lnotab
);
172 code_repr(PyCodeObject
*co
)
176 char *filename
= "???";
179 if (co
->co_firstlineno
!= 0)
180 lineno
= co
->co_firstlineno
;
181 if (co
->co_filename
&& PyString_Check(co
->co_filename
))
182 filename
= PyString_AS_STRING(co
->co_filename
);
183 if (co
->co_name
&& PyString_Check(co
->co_name
))
184 name
= PyString_AS_STRING(co
->co_name
);
185 PyOS_snprintf(buf
, sizeof(buf
),
186 "<code object %.100s at %p, file \"%.300s\", line %d>",
187 name
, co
, filename
, lineno
);
188 return PyString_FromString(buf
);
192 code_compare(PyCodeObject
*co
, PyCodeObject
*cp
)
195 cmp
= PyObject_Compare(co
->co_name
, cp
->co_name
);
197 cmp
= co
->co_argcount
- cp
->co_argcount
;
198 if (cmp
) return (cmp
<0)?-1:1;
199 cmp
= co
->co_nlocals
- cp
->co_nlocals
;
200 if (cmp
) return (cmp
<0)?-1:1;
201 cmp
= co
->co_flags
- cp
->co_flags
;
202 if (cmp
) return (cmp
<0)?-1:1;
203 cmp
= PyObject_Compare(co
->co_code
, cp
->co_code
);
205 cmp
= PyObject_Compare(co
->co_consts
, cp
->co_consts
);
207 cmp
= PyObject_Compare(co
->co_names
, cp
->co_names
);
209 cmp
= PyObject_Compare(co
->co_varnames
, cp
->co_varnames
);
211 cmp
= PyObject_Compare(co
->co_freevars
, cp
->co_freevars
);
213 cmp
= PyObject_Compare(co
->co_cellvars
, cp
->co_cellvars
);
218 code_hash(PyCodeObject
*co
)
220 long h
, h0
, h1
, h2
, h3
, h4
, h5
, h6
;
221 h0
= PyObject_Hash(co
->co_name
);
222 if (h0
== -1) return -1;
223 h1
= PyObject_Hash(co
->co_code
);
224 if (h1
== -1) return -1;
225 h2
= PyObject_Hash(co
->co_consts
);
226 if (h2
== -1) return -1;
227 h3
= PyObject_Hash(co
->co_names
);
228 if (h3
== -1) return -1;
229 h4
= PyObject_Hash(co
->co_varnames
);
230 if (h4
== -1) return -1;
231 h5
= PyObject_Hash(co
->co_freevars
);
232 if (h5
== -1) return -1;
233 h6
= PyObject_Hash(co
->co_cellvars
);
234 if (h6
== -1) return -1;
235 h
= h0
^ h1
^ h2
^ h3
^ h4
^ h5
^ h6
^
236 co
->co_argcount
^ co
->co_nlocals
^ co
->co_flags
;
241 /* XXX code objects need to participate in GC? */
243 PyTypeObject PyCode_Type
= {
244 PyObject_HEAD_INIT(&PyType_Type
)
247 sizeof(PyCodeObject
),
249 (destructor
)code_dealloc
, /* tp_dealloc */
253 (cmpfunc
)code_compare
, /* tp_compare */
254 (reprfunc
)code_repr
, /* tp_repr */
255 0, /* tp_as_number */
256 0, /* tp_as_sequence */
257 0, /* tp_as_mapping */
258 (hashfunc
)code_hash
, /* tp_hash */
261 PyObject_GenericGetAttr
, /* tp_getattro */
263 0, /* tp_as_buffer */
264 Py_TPFLAGS_DEFAULT
, /* tp_flags */
265 code_doc
, /* tp_doc */
268 0, /* tp_richcompare */
269 0, /* tp_weaklistoffset */
273 code_memberlist
, /* tp_members */
277 0, /* tp_descr_get */
278 0, /* tp_descr_set */
279 0, /* tp_dictoffset */
282 code_new
, /* tp_new */
286 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
288 /* all_name_chars(s): true iff all chars in s are valid NAME_CHARS */
291 all_name_chars(unsigned char *s
)
293 static char ok_name_char
[256];
294 static unsigned char *name_chars
= (unsigned char *)NAME_CHARS
;
296 if (ok_name_char
[*name_chars
] == 0) {
298 for (p
= name_chars
; *p
; p
++)
299 ok_name_char
[*p
] = 1;
302 if (ok_name_char
[*s
++] == 0)
309 intern_strings(PyObject
*tuple
)
313 for (i
= PyTuple_GET_SIZE(tuple
); --i
>= 0; ) {
314 PyObject
*v
= PyTuple_GET_ITEM(tuple
, i
);
315 if (v
== NULL
|| !PyString_Check(v
)) {
316 Py_FatalError("non-string found in code slot");
317 PyErr_BadInternalCall();
320 PyString_InternInPlace(&PyTuple_GET_ITEM(tuple
, i
));
325 #define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
326 #define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
327 #define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
328 #define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
329 #define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
332 optimize_code(PyObject
*code
, PyObject
* consts
)
335 int tgt
, tgttgt
, opcode
;
336 unsigned char *codestr
;
338 /* Make a modifiable copy of the code string */
339 if (!PyString_Check(code
))
341 codelen
= PyString_Size(code
);
342 codestr
= PyMem_Malloc(codelen
);
345 codestr
= memcpy(codestr
, PyString_AS_STRING(code
), codelen
);
346 assert(PyTuple_Check(consts
));
348 for (i
=0 ; i
<codelen
-7 ; i
+= HAS_ARG(codestr
[i
]) ? 3 : 1) {
352 /* Skip over LOAD_CONST trueconst JUMP_IF_FALSE xx POP_TOP.
353 Note, only the first opcode is changed, the others still
354 perform normally if they happen to be jump targets. */
356 j
= GETARG(codestr
, i
);
357 if (codestr
[i
+3] != JUMP_IF_FALSE
||
358 codestr
[i
+6] != POP_TOP
||
359 !PyObject_IsTrue(PyTuple_GET_ITEM(consts
, j
)))
361 codestr
[i
] = JUMP_FORWARD
;
362 SETARG(codestr
, i
, 4);
365 /* Replace jumps to unconditional jumps */
375 tgt
= GETJUMPTGT(codestr
, i
);
376 if (!UNCONDITIONAL_JUMP(codestr
[tgt
]))
378 tgttgt
= GETJUMPTGT(codestr
, tgt
);
379 if (opcode
== JUMP_FORWARD
) /* JMP_ABS can go backwards */
380 opcode
= JUMP_ABSOLUTE
;
381 if (!ABSOLUTE_JUMP(opcode
))
382 tgttgt
-= i
+ 3; /* Calc relative jump addr */
383 if (tgttgt
< 0) /* No backward relative jumps */
386 SETARG(codestr
, i
, tgttgt
);
394 code
= PyString_FromStringAndSize((char *)codestr
, codelen
);
404 PyCode_New(int argcount
, int nlocals
, int stacksize
, int flags
,
405 PyObject
*code
, PyObject
*consts
, PyObject
*names
,
406 PyObject
*varnames
, PyObject
*freevars
, PyObject
*cellvars
,
407 PyObject
*filename
, PyObject
*name
, int firstlineno
,
412 /* Check argument types */
413 if (argcount
< 0 || nlocals
< 0 ||
415 consts
== NULL
|| !PyTuple_Check(consts
) ||
416 names
== NULL
|| !PyTuple_Check(names
) ||
417 varnames
== NULL
|| !PyTuple_Check(varnames
) ||
418 freevars
== NULL
|| !PyTuple_Check(freevars
) ||
419 cellvars
== NULL
|| !PyTuple_Check(cellvars
) ||
420 name
== NULL
|| !PyString_Check(name
) ||
421 filename
== NULL
|| !PyString_Check(filename
) ||
422 lnotab
== NULL
|| !PyString_Check(lnotab
) ||
423 !PyObject_CheckReadBuffer(code
)) {
424 PyErr_BadInternalCall();
427 intern_strings(names
);
428 intern_strings(varnames
);
429 intern_strings(freevars
);
430 intern_strings(cellvars
);
431 /* Intern selected string constants */
432 for (i
= PyTuple_Size(consts
); --i
>= 0; ) {
433 PyObject
*v
= PyTuple_GetItem(consts
, i
);
434 if (!PyString_Check(v
))
436 if (!all_name_chars((unsigned char *)PyString_AS_STRING(v
)))
438 PyString_InternInPlace(&PyTuple_GET_ITEM(consts
, i
));
440 co
= PyObject_NEW(PyCodeObject
, &PyCode_Type
);
442 co
->co_argcount
= argcount
;
443 co
->co_nlocals
= nlocals
;
444 co
->co_stacksize
= stacksize
;
445 co
->co_flags
= flags
;
446 co
->co_code
= optimize_code(code
, consts
);
448 co
->co_consts
= consts
;
450 co
->co_names
= names
;
452 co
->co_varnames
= varnames
;
454 co
->co_freevars
= freevars
;
456 co
->co_cellvars
= cellvars
;
458 co
->co_filename
= filename
;
461 co
->co_firstlineno
= firstlineno
;
463 co
->co_lnotab
= lnotab
;
464 if (PyTuple_GET_SIZE(freevars
) == 0 &&
465 PyTuple_GET_SIZE(cellvars
) == 0)
466 co
->co_flags
|= CO_NOFREE
;
472 /* Data structure used internally */
474 /* The compiler uses two passes to generate bytecodes. The first pass
475 builds the symbol table. The second pass generates the bytecode.
477 The first pass uses a single symtable struct. The second pass uses
478 a compiling struct for each code block. The compiling structs
479 share a reference to the symtable.
481 The two passes communicate via symtable_load_symbols() and via
482 is_local() and is_global(). The former initializes several slots
483 in the compiling struct: c_varnames, c_locals, c_nlocals,
484 c_argcount, c_globals, and c_flags.
487 /* All about c_lnotab.
489 c_lnotab is an array of unsigned bytes disguised as a Python string. Since
490 version 2.3, SET_LINENO opcodes are never generated and bytecode offsets are
491 mapped to source code line #s via c_lnotab instead.
493 The array is conceptually a list of
494 (bytecode offset increment, line number increment)
495 pairs. The details are important and delicate, best illustrated by example:
497 byte code offset source code line number
504 The first trick is that these numbers aren't stored, only the increments
505 from one row to the next (this doesn't really work, but it's a start):
507 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
509 The second trick is that an unsigned byte can't hold negative values, or
510 values larger than 255, so (a) there's a deep assumption that byte code
511 offsets and their corresponding line #s both increase monotonically, and (b)
512 if at least one column jumps by more than 255 from one row to the next, more
513 than one pair is written to the table. In case #b, there's no way to know
514 from looking at the table later how many were written. That's the delicate
515 part. A user of c_lnotab desiring to find the source line number
516 corresponding to a bytecode address A should do something like this
519 for addr_incr, line_incr in c_lnotab:
525 In order for this to work, when the addr field increments by more than 255,
526 the line # increment in each pair generated must be 0 until the remaining addr
527 increment is < 256. So, in the example above, com_set_lineno should not (as
528 was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
529 255, 0, 45, 255, 0, 45.
533 PyObject
*c_code
; /* string */
534 PyObject
*c_consts
; /* list of objects */
535 PyObject
*c_const_dict
; /* inverse of c_consts */
536 PyObject
*c_names
; /* list of strings (names) */
537 PyObject
*c_name_dict
; /* inverse of c_names */
538 PyObject
*c_globals
; /* dictionary (value=None or True) */
539 PyObject
*c_locals
; /* dictionary (value=localID) */
540 PyObject
*c_varnames
; /* list (inverse of c_locals) */
541 PyObject
*c_freevars
; /* dictionary (value=None) */
542 PyObject
*c_cellvars
; /* list */
543 int c_nlocals
; /* index of next local */
544 int c_argcount
; /* number of top-level arguments */
545 int c_flags
; /* same as co_flags */
546 int c_nexti
; /* index into c_code */
547 int c_errors
; /* counts errors occurred */
548 int c_infunction
; /* set when compiling a function */
549 int c_interactive
; /* generating code for interactive command */
550 int c_loops
; /* counts nested loops */
551 int c_begin
; /* begin of current loop, for 'continue' */
552 int c_block
[CO_MAXBLOCKS
]; /* stack of block types */
553 int c_nblocks
; /* current block stack level */
554 const char *c_filename
; /* filename of current node */
555 char *c_name
; /* name of object (e.g. function) */
556 int c_lineno
; /* Current line number */
557 int c_stacklevel
; /* Current stack level */
558 int c_maxstacklevel
; /* Maximum stack level */
560 PyObject
*c_lnotab
; /* Table mapping address to line number */
561 int c_last_addr
, c_last_line
, c_lnotab_next
;
562 char *c_private
; /* for private name mangling */
563 int c_tmpname
; /* temporary local name counter */
564 int c_nested
; /* Is block nested funcdef or lamdef? */
565 int c_closure
; /* Is nested w/freevars? */
566 struct symtable
*c_symtable
; /* pointer to module symbol table */
567 PyFutureFeatures
*c_future
; /* pointer to module's __future__ */
568 char *c_encoding
; /* source encoding (a borrowed reference) */
574 if ((v
& (USE
| DEF_FREE
))
575 && !(v
& (DEF_LOCAL
| DEF_PARAM
| DEF_GLOBAL
)))
577 if (v
& DEF_FREE_CLASS
)
583 com_error(struct compiling
*c
, PyObject
*exc
, char *msg
)
585 PyObject
*t
= NULL
, *v
= NULL
, *w
= NULL
, *line
= NULL
;
588 /* Error occurred via symtable call to
590 PyErr_SetString(exc
, msg
);
594 if (c
->c_lineno
< 1 || c
->c_interactive
) {
595 /* Unknown line number or interactive input */
596 PyErr_SetString(exc
, msg
);
599 v
= PyString_FromString(msg
);
601 return; /* MemoryError, too bad */
603 line
= PyErr_ProgramText(c
->c_filename
, c
->c_lineno
);
608 if (exc
== PyExc_SyntaxError
) {
609 t
= Py_BuildValue("(ziOO)", c
->c_filename
, c
->c_lineno
,
613 w
= Py_BuildValue("(OO)", v
, t
);
616 PyErr_SetObject(exc
, w
);
618 /* Make sure additional exceptions are printed with
619 file and line, also. */
620 PyErr_SetObject(exc
, v
);
621 PyErr_SyntaxLocation(c
->c_filename
, c
->c_lineno
);
630 /* Interface to the block stack */
633 block_push(struct compiling
*c
, int type
)
635 if (c
->c_nblocks
>= CO_MAXBLOCKS
) {
636 com_error(c
, PyExc_SystemError
,
637 "too many statically nested blocks");
640 c
->c_block
[c
->c_nblocks
++] = type
;
645 block_pop(struct compiling
*c
, int type
)
647 if (c
->c_nblocks
> 0)
649 if (c
->c_block
[c
->c_nblocks
] != type
&& c
->c_errors
== 0) {
650 com_error(c
, PyExc_SystemError
, "bad block pop");
654 /* Prototype forward declarations */
656 static int issue_warning(const char *, const char *, int);
657 static int com_init(struct compiling
*, const char *);
658 static void com_free(struct compiling
*);
659 static void com_push(struct compiling
*, int);
660 static void com_pop(struct compiling
*, int);
661 static void com_done(struct compiling
*);
662 static void com_node(struct compiling
*, node
*);
663 static void com_factor(struct compiling
*, node
*);
664 static void com_addbyte(struct compiling
*, int);
665 static void com_addint(struct compiling
*, int);
666 static void com_addoparg(struct compiling
*, int, int);
667 static void com_addfwref(struct compiling
*, int, int *);
668 static void com_backpatch(struct compiling
*, int);
669 static int com_add(struct compiling
*, PyObject
*, PyObject
*, PyObject
*);
670 static int com_addconst(struct compiling
*, PyObject
*);
671 static int com_addname(struct compiling
*, PyObject
*);
672 static void com_addopname(struct compiling
*, int, node
*);
673 static void com_list(struct compiling
*, node
*, int);
674 static void com_list_iter(struct compiling
*, node
*, node
*, char *);
675 static int com_argdefs(struct compiling
*, node
*);
676 static void com_assign(struct compiling
*, node
*, int, node
*);
677 static void com_assign_name(struct compiling
*, node
*, int);
678 static PyCodeObject
*icompile(node
*, struct compiling
*);
679 static PyCodeObject
*jcompile(node
*, const char *, struct compiling
*,
681 static PyObject
*parsestrplus(struct compiling
*, node
*);
682 static PyObject
*parsestr(struct compiling
*, char *);
683 static node
*get_rawdocstring(node
*);
685 static int get_ref_type(struct compiling
*, char *);
687 /* symtable operations */
688 static struct symtable
*symtable_build(node
*, PyFutureFeatures
*,
689 const char *filename
);
690 static int symtable_load_symbols(struct compiling
*);
691 static struct symtable
*symtable_init(void);
692 static void symtable_enter_scope(struct symtable
*, char *, int, int);
693 static int symtable_exit_scope(struct symtable
*);
694 static int symtable_add_def(struct symtable
*, char *, int);
695 static int symtable_add_def_o(struct symtable
*, PyObject
*, PyObject
*, int);
697 static void symtable_node(struct symtable
*, node
*);
698 static void symtable_funcdef(struct symtable
*, node
*);
699 static void symtable_default_args(struct symtable
*, node
*);
700 static void symtable_params(struct symtable
*, node
*);
701 static void symtable_params_fplist(struct symtable
*, node
*n
);
702 static void symtable_global(struct symtable
*, node
*);
703 static void symtable_import(struct symtable
*, node
*);
704 static void symtable_assign(struct symtable
*, node
*, int);
705 static void symtable_list_comprehension(struct symtable
*, node
*);
706 static void symtable_list_for(struct symtable
*, node
*);
708 static int symtable_update_free_vars(struct symtable
*);
709 static int symtable_undo_free(struct symtable
*, PyObject
*, PyObject
*);
710 static int symtable_check_global(struct symtable
*, PyObject
*, PyObject
*);
717 for (i
= 0; i
< pad
; ++i
)
718 fprintf(stderr
, " ");
722 dump(node
*n
, int pad
, int depth
)
728 fprintf(stderr
, "%d: %s\n", TYPE(n
), STR(n
));
731 for (i
= 0; i
< NCH(n
); ++i
)
732 dump(CHILD(n
, i
), pad
+ 1, depth
);
735 #define DUMP(N) dump(N, 0, -1)
738 com_init(struct compiling
*c
, const char *filename
)
740 memset((void *)c
, '\0', sizeof(struct compiling
));
741 if ((c
->c_code
= PyString_FromStringAndSize((char *)NULL
,
744 if ((c
->c_consts
= PyList_New(0)) == NULL
)
746 if ((c
->c_const_dict
= PyDict_New()) == NULL
)
748 if ((c
->c_names
= PyList_New(0)) == NULL
)
750 if ((c
->c_name_dict
= PyDict_New()) == NULL
)
752 if ((c
->c_locals
= PyDict_New()) == NULL
)
754 if ((c
->c_lnotab
= PyString_FromStringAndSize((char *)NULL
,
758 c
->c_varnames
= NULL
;
759 c
->c_freevars
= NULL
;
760 c
->c_cellvars
= NULL
;
767 c
->c_interactive
= 0;
771 c
->c_filename
= filename
;
775 c
->c_maxstacklevel
= 0;
776 c
->c_firstlineno
= 0;
779 c
->c_lnotab_next
= 0;
783 c
->c_symtable
= NULL
;
792 com_free(struct compiling
*c
)
794 Py_XDECREF(c
->c_code
);
795 Py_XDECREF(c
->c_consts
);
796 Py_XDECREF(c
->c_const_dict
);
797 Py_XDECREF(c
->c_names
);
798 Py_XDECREF(c
->c_name_dict
);
799 Py_XDECREF(c
->c_globals
);
800 Py_XDECREF(c
->c_locals
);
801 Py_XDECREF(c
->c_varnames
);
802 Py_XDECREF(c
->c_freevars
);
803 Py_XDECREF(c
->c_cellvars
);
804 Py_XDECREF(c
->c_lnotab
);
806 PyObject_FREE((void *)c
->c_future
);
810 com_push(struct compiling
*c
, int n
)
812 c
->c_stacklevel
+= n
;
813 if (c
->c_stacklevel
> c
->c_maxstacklevel
) {
814 c
->c_maxstacklevel
= c
->c_stacklevel
;
816 fprintf(stderr, "%s:%s:%d max stack nexti=%d level=%d n=%d\n",
817 c->c_filename, c->c_name, c->c_lineno,
818 c->c_nexti, c->c_stacklevel, n);
824 com_pop(struct compiling
*c
, int n
)
826 if (c
->c_stacklevel
< n
)
829 c
->c_stacklevel
-= n
;
833 com_done(struct compiling
*c
)
835 if (c
->c_code
!= NULL
)
836 _PyString_Resize(&c
->c_code
, c
->c_nexti
);
837 if (c
->c_lnotab
!= NULL
)
838 _PyString_Resize(&c
->c_lnotab
, c
->c_lnotab_next
);
842 com_check_size(PyObject
**s
, int offset
)
844 int len
= PyString_GET_SIZE(*s
);
846 return _PyString_Resize(s
, len
* 2);
851 com_addbyte(struct compiling
*c
, int byte
)
853 /*fprintf(stderr, "%3d: %3d\n", c->c_nexti, byte);*/
854 assert(byte
>= 0 && byte
<= 255);
855 assert(c
->c_code
!= 0);
856 if (com_check_size(&c
->c_code
, c
->c_nexti
)) {
860 PyString_AS_STRING(c
->c_code
)[c
->c_nexti
++] = byte
;
864 com_addint(struct compiling
*c
, int x
)
866 com_addbyte(c
, x
& 0xff);
867 com_addbyte(c
, x
>> 8); /* XXX x should be positive */
871 com_add_lnotab(struct compiling
*c
, int addr
, int line
)
874 if (c
->c_lnotab
== NULL
)
876 if (com_check_size(&c
->c_lnotab
, c
->c_lnotab_next
+ 2)) {
880 p
= PyString_AS_STRING(c
->c_lnotab
) + c
->c_lnotab_next
;
883 c
->c_lnotab_next
+= 2;
887 com_set_lineno(struct compiling
*c
, int lineno
)
889 c
->c_lineno
= lineno
;
890 if (c
->c_firstlineno
== 0) {
891 c
->c_firstlineno
= c
->c_last_line
= lineno
;
894 int incr_addr
= c
->c_nexti
- c
->c_last_addr
;
895 int incr_line
= lineno
- c
->c_last_line
;
896 while (incr_addr
> 255) {
897 com_add_lnotab(c
, 255, 0);
900 while (incr_line
> 255) {
901 com_add_lnotab(c
, incr_addr
, 255);
905 if (incr_addr
> 0 || incr_line
> 0)
906 com_add_lnotab(c
, incr_addr
, incr_line
);
907 c
->c_last_addr
= c
->c_nexti
;
908 c
->c_last_line
= lineno
;
913 com_addoparg(struct compiling
*c
, int op
, int arg
)
915 int extended_arg
= arg
>> 16;
917 com_addbyte(c
, EXTENDED_ARG
);
918 com_addint(c
, extended_arg
);
926 com_addfwref(struct compiling
*c
, int op
, int *p_anchor
)
928 /* Compile a forward reference for backpatching */
935 com_addint(c
, anchor
== 0 ? 0 : here
- anchor
);
939 com_backpatch(struct compiling
*c
, int anchor
)
941 unsigned char *code
= (unsigned char *) PyString_AS_STRING(c
->c_code
);
942 int target
= c
->c_nexti
;
946 /* Make the JUMP instruction at anchor point to target */
947 prev
= code
[anchor
] + (code
[anchor
+1] << 8);
948 dist
= target
- (anchor
+2);
949 code
[anchor
] = dist
& 0xff;
951 code
[anchor
+1] = dist
;
954 com_error(c
, PyExc_SystemError
,
955 "com_backpatch: offset too large");
964 /* Handle literals and names uniformly */
967 com_add(struct compiling
*c
, PyObject
*list
, PyObject
*dict
, PyObject
*v
)
969 PyObject
*w
, *t
, *np
=NULL
;
972 t
= Py_BuildValue("(OO)", v
, v
->ob_type
);
975 w
= PyDict_GetItem(dict
, t
);
979 n
= PyList_Size(list
);
980 np
= PyInt_FromLong(n
);
983 if (PyList_Append(list
, v
) != 0)
985 if (PyDict_SetItem(dict
, t
, np
) != 0)
999 com_addconst(struct compiling
*c
, PyObject
*v
)
1001 return com_add(c
, c
->c_consts
, c
->c_const_dict
, v
);
1005 com_addname(struct compiling
*c
, PyObject
*v
)
1007 return com_add(c
, c
->c_names
, c
->c_name_dict
, v
);
1011 _Py_Mangle(char *p
, char *name
, char *buffer
, size_t maxlen
)
1013 /* Name mangling: __private becomes _classname__private.
1014 This is independent from how the name is used. */
1016 if (p
== NULL
|| name
== NULL
|| name
[0] != '_' || name
[1] != '_')
1018 nlen
= strlen(name
);
1019 if (nlen
+2 >= maxlen
)
1020 return 0; /* Don't mangle __extremely_long_names */
1021 if (name
[nlen
-1] == '_' && name
[nlen
-2] == '_')
1022 return 0; /* Don't mangle __whatever__ */
1023 /* Strip leading underscores from class name */
1027 return 0; /* Don't mangle if class is just underscores */
1029 if (plen
+ nlen
>= maxlen
)
1030 plen
= maxlen
-nlen
-2; /* Truncate class name if too long */
1031 /* buffer = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
1033 strncpy(buffer
+1, p
, plen
);
1034 strcpy(buffer
+1+plen
, name
);
1039 com_addop_name(struct compiling
*c
, int op
, char *name
)
1043 char buffer
[MANGLE_LEN
];
1045 if (_Py_Mangle(c
->c_private
, name
, buffer
, sizeof(buffer
)))
1047 if (name
== NULL
|| (v
= PyString_InternFromString(name
)) == NULL
) {
1052 i
= com_addname(c
, v
);
1055 com_addoparg(c
, op
, i
);
1058 #define NAME_LOCAL 0
1059 #define NAME_GLOBAL 1
1060 #define NAME_DEFAULT 2
1061 #define NAME_CLOSURE 3
1064 com_lookup_arg(PyObject
*dict
, PyObject
*name
)
1066 PyObject
*v
= PyDict_GetItem(dict
, name
);
1070 return PyInt_AS_LONG(v
);
1074 none_assignment_check(struct compiling
*c
, char *name
, int assigning
)
1076 if (name
[0] == 'N' && strcmp(name
, "None") == 0) {
1079 msg
= "assignment to None";
1081 msg
= "deleting None";
1082 if (issue_warning(msg
, c
->c_filename
, c
->c_lineno
) < 0) {
1091 com_addop_varname(struct compiling
*c
, int kind
, char *name
)
1095 int scope
= NAME_DEFAULT
;
1097 char buffer
[MANGLE_LEN
];
1099 if (kind
!= VAR_LOAD
&&
1100 none_assignment_check(c
, name
, kind
== VAR_STORE
))
1106 if (_Py_Mangle(c
->c_private
, name
, buffer
, sizeof(buffer
)))
1108 if (name
== NULL
|| (v
= PyString_InternFromString(name
)) == NULL
) {
1114 reftype
= get_ref_type(c
, name
);
1117 if (c
->c_symtable
->st_cur
->ste_type
== TYPE_FUNCTION
)
1120 case GLOBAL_EXPLICIT
:
1121 scope
= NAME_GLOBAL
;
1123 case GLOBAL_IMPLICIT
:
1124 if (c
->c_flags
& CO_OPTIMIZED
)
1125 scope
= NAME_GLOBAL
;
1129 scope
= NAME_CLOSURE
;
1133 i
= com_addname(c
, v
);
1134 if (scope
== NAME_LOCAL
)
1135 i
= com_lookup_arg(c
->c_locals
, v
);
1136 else if (reftype
== FREE
)
1137 i
= com_lookup_arg(c
->c_freevars
, v
);
1138 else if (reftype
== CELL
)
1139 i
= com_lookup_arg(c
->c_cellvars
, v
);
1141 c
->c_errors
++; /* XXX no exception set */
1191 case NAME_CLOSURE
: {
1193 PyOS_snprintf(buf
, sizeof(buf
),
1194 DEL_CLOSURE_ERROR
, name
);
1195 com_error(c
, PyExc_SyntaxError
, buf
);
1203 com_addoparg(c
, op
, i
);
1207 com_addopname(struct compiling
*c
, int op
, node
*n
)
1211 /* XXX it is possible to write this code without the 1000
1212 chars on the total length of dotted names, I just can't be
1213 bothered right now */
1214 if (TYPE(n
) == STAR
)
1216 else if (TYPE(n
) == dotted_name
) {
1220 for (i
= 0; i
< NCH(n
); i
+= 2) {
1221 char *s
= STR(CHILD(n
, i
));
1222 if (p
+ strlen(s
) > buffer
+ (sizeof buffer
) - 2) {
1223 com_error(c
, PyExc_MemoryError
,
1224 "dotted_name too long");
1231 p
= strchr(p
, '\0');
1238 com_addop_name(c
, op
, name
);
1242 parsenumber(struct compiling
*c
, char *s
)
1247 #ifndef WITHOUT_COMPLEX
1252 end
= s
+ strlen(s
) - 1;
1253 #ifndef WITHOUT_COMPLEX
1254 imflag
= *end
== 'j' || *end
== 'J';
1256 if (*end
== 'l' || *end
== 'L')
1257 return PyLong_FromString(s
, (char **)0, 0);
1259 x
= (long) PyOS_strtoul(s
, &end
, 0);
1260 if (x
< 0 && errno
== 0) {
1261 if (PyErr_WarnExplicit(
1262 PyExc_FutureWarning
,
1263 "hex/oct constants > sys.maxint "
1264 "will return positive values "
1265 "in Python 2.4 and up",
1266 /* XXX: Give WarnExplicit
1267 a const char* argument. */
1268 (char*)c
->c_filename
,
1273 errno
= 0; /* Might be changed by PyErr_Warn() */
1277 x
= PyOS_strtol(s
, &end
, 0);
1280 return PyLong_FromString(s
, (char **)0, 0);
1281 return PyInt_FromLong(x
);
1283 /* XXX Huge floats may silently fail */
1284 #ifndef WITHOUT_COMPLEX
1288 PyFPE_START_PROTECT("atof", return 0)
1290 PyFPE_END_PROTECT(z
)
1291 return PyComplex_FromCComplex(z
);
1296 PyFPE_START_PROTECT("atof", return 0)
1298 PyFPE_END_PROTECT(dx
)
1299 return PyFloat_FromDouble(dx
);
1304 decode_utf8(char **sPtr
, char *end
, char* encoding
)
1306 #ifndef Py_USING_UNICODE
1307 Py_FatalError("decode_utf8 should not be called in this build.");
1313 /* while (s < end && *s != '\\') s++; */ /* inefficient for u".." */
1314 while (s
< end
&& (*s
& 0x80)) s
++;
1316 u
= PyUnicode_DecodeUTF8(t
, s
- t
, NULL
);
1319 v
= PyUnicode_AsEncodedString(u
, encoding
, NULL
);
1325 /* compiler.transformer.Transformer.decode_literal depends on what
1326 might seem like minor details of this function -- changes here
1327 must be reflected there. */
1329 parsestr(struct compiling
*c
, char *s
)
1335 char* encoding
= ((c
== NULL
) ? NULL
: c
->c_encoding
);
1339 if (isalpha(quote
) || quote
== '_') {
1340 if (quote
== 'u' || quote
== 'U') {
1344 if (quote
== 'r' || quote
== 'R') {
1349 if (quote
!= '\'' && quote
!= '\"') {
1350 PyErr_BadInternalCall();
1355 if (len
> INT_MAX
) {
1356 com_error(c
, PyExc_OverflowError
,
1357 "string to parse is too long");
1360 if (s
[--len
] != quote
) {
1361 PyErr_BadInternalCall();
1364 if (len
>= 4 && s
[0] == quote
&& s
[1] == quote
) {
1367 if (s
[--len
] != quote
|| s
[--len
] != quote
) {
1368 PyErr_BadInternalCall();
1372 #ifdef Py_USING_UNICODE
1373 if (unicode
|| Py_UnicodeFlag
) {
1378 if (encoding
== NULL
) {
1381 } else if (strcmp(encoding
, "iso-8859-1") == 0) {
1385 /* "\XX" may become "\u005c\uHHLL" (12 bytes) */
1386 u
= PyString_FromStringAndSize((char *)NULL
, len
* 4);
1389 p
= buf
= PyString_AsString(u
);
1399 if (*s
& 0x80) { /* XXX inefficient */
1402 w
= decode_utf8(&s
, end
, "utf-16-be");
1407 r
= PyString_AsString(w
);
1408 rn
= PyString_Size(w
);
1409 assert(rn
% 2 == 0);
1410 for (i
= 0; i
< rn
; i
+= 2) {
1411 sprintf(p
, "\\u%02x%02x",
1424 v
= PyUnicode_DecodeRawUnicodeEscape(buf
, len
, NULL
);
1426 v
= PyUnicode_DecodeUnicodeEscape(buf
, len
, NULL
);
1429 PyErr_SyntaxLocation(c
->c_filename
, c
->c_lineno
);
1434 need_encoding
= (encoding
!= NULL
&&
1435 strcmp(encoding
, "utf-8") != 0 &&
1436 strcmp(encoding
, "iso-8859-1") != 0);
1437 if (rawmode
|| strchr(s
, '\\') == NULL
) {
1438 if (need_encoding
) {
1439 #ifndef Py_USING_UNICODE
1440 /* This should not happen - we never see any other
1442 Py_FatalError("cannot deal with encodings in this build.");
1444 PyObject
* u
= PyUnicode_DecodeUTF8(s
, len
, NULL
);
1447 v
= PyUnicode_AsEncodedString(u
, encoding
, NULL
);
1452 return PyString_FromStringAndSize(s
, len
);
1456 v
= PyString_DecodeEscape(s
, len
, NULL
, unicode
,
1457 need_encoding
? encoding
: NULL
);
1459 PyErr_SyntaxLocation(c
->c_filename
, c
->c_lineno
);
1464 parsestrplus(struct compiling
* c
, node
*n
)
1468 REQ(CHILD(n
, 0), STRING
);
1469 if ((v
= parsestr(c
, STR(CHILD(n
, 0)))) != NULL
) {
1470 /* String literal concatenation */
1471 for (i
= 1; i
< NCH(n
); i
++) {
1473 s
= parsestr(c
, STR(CHILD(n
, i
)));
1476 if (PyString_Check(v
) && PyString_Check(s
)) {
1477 PyString_ConcatAndDel(&v
, s
);
1481 #ifdef Py_USING_UNICODE
1484 temp
= PyUnicode_Concat(v
, s
);
1502 com_list_for(struct compiling
*c
, node
*n
, node
*e
, char *t
)
1505 int save_begin
= c
->c_begin
;
1507 /* list_iter: for v in expr [list_iter] */
1508 com_node(c
, CHILD(n
, 3)); /* expr */
1509 com_addbyte(c
, GET_ITER
);
1510 c
->c_begin
= c
->c_nexti
;
1511 com_addfwref(c
, FOR_ITER
, &anchor
);
1513 com_assign(c
, CHILD(n
, 1), OP_ASSIGN
, NULL
);
1515 com_list_iter(c
, n
, e
, t
);
1517 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
1518 c
->c_begin
= save_begin
;
1519 com_backpatch(c
, anchor
);
1520 com_pop(c
, 1); /* FOR_ITER has popped this */
1524 com_list_if(struct compiling
*c
, node
*n
, node
*e
, char *t
)
1528 /* list_iter: 'if' test [list_iter] */
1529 com_node(c
, CHILD(n
, 1));
1530 com_addfwref(c
, JUMP_IF_FALSE
, &a
);
1531 com_addbyte(c
, POP_TOP
);
1533 com_list_iter(c
, n
, e
, t
);
1534 com_addfwref(c
, JUMP_FORWARD
, &anchor
);
1535 com_backpatch(c
, a
);
1536 /* We jump here with an extra entry which we now pop */
1537 com_addbyte(c
, POP_TOP
);
1538 com_backpatch(c
, anchor
);
1542 com_list_iter(struct compiling
*c
,
1543 node
*p
, /* parent of list_iter node */
1544 node
*e
, /* element expression node */
1545 char *t
/* name of result list temp local */)
1547 /* list_iter is the last child in a listmaker, list_for, or list_if */
1548 node
*n
= CHILD(p
, NCH(p
)-1);
1549 if (TYPE(n
) == list_iter
) {
1553 com_list_for(c
, n
, e
, t
);
1556 com_list_if(c
, n
, e
, t
);
1559 com_error(c
, PyExc_SystemError
,
1560 "invalid list_iter node type");
1564 com_addop_varname(c
, VAR_LOAD
, t
);
1567 com_addoparg(c
, CALL_FUNCTION
, 1);
1568 com_addbyte(c
, POP_TOP
);
1574 com_list_comprehension(struct compiling
*c
, node
*n
)
1576 /* listmaker: test list_for */
1580 PyOS_snprintf(tmpname
, sizeof(tmpname
), "_[%d]", ++c
->c_tmpname
);
1581 com_addoparg(c
, BUILD_LIST
, 0);
1582 com_addbyte(c
, DUP_TOP
); /* leave the result on the stack */
1584 com_addop_name(c
, LOAD_ATTR
, "append");
1585 com_addop_varname(c
, VAR_STORE
, tmpname
);
1587 com_list_for(c
, CHILD(n
, 1), CHILD(n
, 0), tmpname
);
1588 com_addop_varname(c
, VAR_DELETE
, tmpname
);
1593 com_listmaker(struct compiling
*c
, node
*n
)
1595 /* listmaker: test ( list_for | (',' test)* [','] ) */
1596 if (NCH(n
) > 1 && TYPE(CHILD(n
, 1)) == list_for
)
1597 com_list_comprehension(c
, n
);
1601 for (i
= 0; i
< NCH(n
); i
+= 2, len
++)
1602 com_node(c
, CHILD(n
, i
));
1603 com_addoparg(c
, BUILD_LIST
, len
);
1609 com_dictmaker(struct compiling
*c
, node
*n
)
1612 /* dictmaker: test ':' test (',' test ':' value)* [','] */
1613 for (i
= 0; i
+2 < NCH(n
); i
+= 4) {
1614 /* We must arrange things just right for STORE_SUBSCR.
1615 It wants the stack to look like (value) (dict) (key) */
1616 com_addbyte(c
, DUP_TOP
);
1618 com_node(c
, CHILD(n
, i
)); /* key */
1619 com_node(c
, CHILD(n
, i
+2)); /* value */
1620 com_addbyte(c
, ROT_THREE
);
1621 com_addbyte(c
, STORE_SUBSCR
);
1627 com_atom(struct compiling
*c
, node
*n
)
1636 if (TYPE(CHILD(n
, 1)) == RPAR
) {
1637 com_addoparg(c
, BUILD_TUPLE
, 0);
1641 com_node(c
, CHILD(n
, 1));
1643 case LSQB
: /* '[' [listmaker] ']' */
1644 if (TYPE(CHILD(n
, 1)) == RSQB
) {
1645 com_addoparg(c
, BUILD_LIST
, 0);
1649 com_listmaker(c
, CHILD(n
, 1));
1651 case LBRACE
: /* '{' [dictmaker] '}' */
1652 com_addoparg(c
, BUILD_MAP
, 0);
1654 if (TYPE(CHILD(n
, 1)) == dictmaker
)
1655 com_dictmaker(c
, CHILD(n
, 1));
1658 com_node(c
, CHILD(n
, 1));
1659 com_addbyte(c
, UNARY_CONVERT
);
1662 if ((v
= parsenumber(c
, STR(ch
))) == NULL
) {
1666 i
= com_addconst(c
, v
);
1669 com_addoparg(c
, LOAD_CONST
, i
);
1673 v
= parsestrplus(c
, n
);
1679 i
= com_addconst(c
, v
);
1682 com_addoparg(c
, LOAD_CONST
, i
);
1686 com_addop_varname(c
, VAR_LOAD
, STR(ch
));
1690 com_error(c
, PyExc_SystemError
,
1691 "com_atom: unexpected node type");
1696 com_slice(struct compiling
*c
, node
*n
, int op
)
1701 else if (NCH(n
) == 2) {
1702 if (TYPE(CHILD(n
, 0)) != COLON
) {
1703 com_node(c
, CHILD(n
, 0));
1704 com_addbyte(c
, op
+1);
1707 com_node(c
, CHILD(n
, 1));
1708 com_addbyte(c
, op
+2);
1713 com_node(c
, CHILD(n
, 0));
1714 com_node(c
, CHILD(n
, 2));
1715 com_addbyte(c
, op
+3);
1721 com_augassign_slice(struct compiling
*c
, node
*n
, int opcode
, node
*augn
)
1724 com_addbyte(c
, DUP_TOP
);
1726 com_addbyte(c
, SLICE
);
1728 com_addbyte(c
, opcode
);
1730 com_addbyte(c
, ROT_TWO
);
1731 com_addbyte(c
, STORE_SLICE
);
1733 } else if (NCH(n
) == 2 && TYPE(CHILD(n
, 0)) != COLON
) {
1734 com_node(c
, CHILD(n
, 0));
1735 com_addoparg(c
, DUP_TOPX
, 2);
1737 com_addbyte(c
, SLICE
+1);
1740 com_addbyte(c
, opcode
);
1742 com_addbyte(c
, ROT_THREE
);
1743 com_addbyte(c
, STORE_SLICE
+1);
1745 } else if (NCH(n
) == 2) {
1746 com_node(c
, CHILD(n
, 1));
1747 com_addoparg(c
, DUP_TOPX
, 2);
1749 com_addbyte(c
, SLICE
+2);
1752 com_addbyte(c
, opcode
);
1754 com_addbyte(c
, ROT_THREE
);
1755 com_addbyte(c
, STORE_SLICE
+2);
1758 com_node(c
, CHILD(n
, 0));
1759 com_node(c
, CHILD(n
, 2));
1760 com_addoparg(c
, DUP_TOPX
, 3);
1762 com_addbyte(c
, SLICE
+3);
1765 com_addbyte(c
, opcode
);
1767 com_addbyte(c
, ROT_FOUR
);
1768 com_addbyte(c
, STORE_SLICE
+3);
1774 com_argument(struct compiling
*c
, node
*n
, PyObject
**pkeywords
)
1777 REQ(n
, argument
); /* [test '='] test; really [keyword '='] test */
1779 if (*pkeywords
!= NULL
) {
1780 com_error(c
, PyExc_SyntaxError
,
1781 "non-keyword arg after keyword arg");
1784 com_node(c
, CHILD(n
, 0));
1791 } while (NCH(m
) == 1);
1792 if (TYPE(m
) != NAME
) {
1793 /* f(lambda x: x[0] = 3) ends up getting parsed with
1794 * LHS test = lambda x: x[0], and RHS test = 3.
1795 * SF bug 132313 points out that complaining about a keyword
1796 * then is very confusing.
1798 com_error(c
, PyExc_SyntaxError
,
1799 TYPE(m
) == lambdef
?
1800 "lambda cannot contain assignment" :
1801 "keyword can't be an expression");
1804 PyObject
*v
= PyString_InternFromString(STR(m
));
1805 (void) none_assignment_check(c
, STR(m
), 1);
1806 if (v
!= NULL
&& *pkeywords
== NULL
)
1807 *pkeywords
= PyDict_New();
1810 else if (*pkeywords
== NULL
) {
1814 if (PyDict_GetItem(*pkeywords
, v
) != NULL
)
1815 com_error(c
, PyExc_SyntaxError
,
1816 "duplicate keyword argument");
1818 if (PyDict_SetItem(*pkeywords
, v
, v
) != 0)
1820 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, v
));
1825 com_node(c
, CHILD(n
, 2));
1829 com_call_function(struct compiling
*c
, node
*n
)
1831 if (TYPE(n
) == RPAR
) {
1832 com_addoparg(c
, CALL_FUNCTION
, 0);
1835 PyObject
*keywords
= NULL
;
1837 int lineno
= n
->n_lineno
;
1839 int starstar_flag
= 0;
1844 for (i
= 0; i
< NCH(n
); i
+= 2) {
1845 node
*ch
= CHILD(n
, i
);
1846 if (TYPE(ch
) == STAR
||
1847 TYPE(ch
) == DOUBLESTAR
)
1849 if (ch
->n_lineno
!= lineno
) {
1850 lineno
= ch
->n_lineno
;
1851 com_set_lineno(c
, lineno
);
1853 com_argument(c
, ch
, &keywords
);
1854 if (keywords
== NULL
)
1859 Py_XDECREF(keywords
);
1860 while (i
< NCH(n
)) {
1861 node
*tok
= CHILD(n
, i
);
1862 node
*ch
= CHILD(n
, i
+1);
1864 switch (TYPE(tok
)) {
1865 case STAR
: star_flag
= 1; break;
1866 case DOUBLESTAR
: starstar_flag
= 1; break;
1870 if (na
> 255 || nk
> 255) {
1871 com_error(c
, PyExc_SyntaxError
,
1872 "more than 255 arguments");
1874 if (star_flag
|| starstar_flag
)
1875 opcode
= CALL_FUNCTION_VAR
- 1 +
1876 star_flag
+ (starstar_flag
<< 1);
1878 opcode
= CALL_FUNCTION
;
1879 com_addoparg(c
, opcode
, na
| (nk
<< 8));
1880 com_pop(c
, na
+ 2*nk
+ star_flag
+ starstar_flag
);
1885 com_select_member(struct compiling
*c
, node
*n
)
1887 com_addopname(c
, LOAD_ATTR
, n
);
1891 com_sliceobj(struct compiling
*c
, node
*n
)
1894 int ns
=2; /* number of slice arguments */
1897 /* first argument */
1898 if (TYPE(CHILD(n
,i
)) == COLON
) {
1899 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1904 com_node(c
, CHILD(n
,i
));
1906 REQ(CHILD(n
,i
),COLON
);
1909 /* second argument */
1910 if (i
< NCH(n
) && TYPE(CHILD(n
,i
)) == test
) {
1911 com_node(c
, CHILD(n
,i
));
1915 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1918 /* remaining arguments */
1919 for (; i
< NCH(n
); i
++) {
1924 /* right argument of ':' missing */
1925 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1929 com_node(c
, CHILD(ch
,1));
1931 com_addoparg(c
, BUILD_SLICE
, ns
);
1932 com_pop(c
, 1 + (ns
== 3));
1936 com_subscript(struct compiling
*c
, node
*n
)
1941 /* check for rubber index */
1942 if (TYPE(ch
) == DOT
&& TYPE(CHILD(n
,1)) == DOT
) {
1943 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_Ellipsis
));
1947 /* check for slice */
1948 if ((TYPE(ch
) == COLON
|| NCH(n
) > 1))
1958 com_subscriptlist(struct compiling
*c
, node
*n
, int assigning
, node
*augn
)
1961 REQ(n
, subscriptlist
);
1962 /* Check to make backward compatible slice behavior for '[i:j]' */
1964 node
*sub
= CHILD(n
, 0); /* subscript */
1965 /* 'Basic' slice, should have exactly one colon. */
1966 if ((TYPE(CHILD(sub
, 0)) == COLON
1967 || (NCH(sub
) > 1 && TYPE(CHILD(sub
, 1)) == COLON
))
1968 && (TYPE(CHILD(sub
,NCH(sub
)-1)) != sliceop
))
1970 switch (assigning
) {
1981 com_augassign_slice(c
, sub
, assigning
, augn
);
1984 com_slice(c
, sub
, op
);
1985 if (op
== STORE_SLICE
)
1987 else if (op
== DELETE_SLICE
)
1992 /* Else normal subscriptlist. Compile each subscript. */
1993 for (i
= 0; i
< NCH(n
); i
+= 2)
1994 com_subscript(c
, CHILD(n
, i
));
1995 /* Put multiple subscripts into a tuple */
1998 com_addoparg(c
, BUILD_TUPLE
, i
);
2001 switch (assigning
) {
2016 if (assigning
> OP_APPLY
) {
2017 com_addoparg(c
, DUP_TOPX
, 2);
2019 com_addbyte(c
, BINARY_SUBSCR
);
2022 com_addbyte(c
, assigning
);
2024 com_addbyte(c
, ROT_THREE
);
2031 com_apply_trailer(struct compiling
*c
, node
*n
)
2034 switch (TYPE(CHILD(n
, 0))) {
2036 com_call_function(c
, CHILD(n
, 1));
2039 com_select_member(c
, CHILD(n
, 1));
2042 com_subscriptlist(c
, CHILD(n
, 1), OP_APPLY
, NULL
);
2045 com_error(c
, PyExc_SystemError
,
2046 "com_apply_trailer: unknown trailer type");
2051 com_power(struct compiling
*c
, node
*n
)
2055 com_atom(c
, CHILD(n
, 0));
2056 for (i
= 1; i
< NCH(n
); i
++) {
2057 if (TYPE(CHILD(n
, i
)) == DOUBLESTAR
) {
2058 com_factor(c
, CHILD(n
, i
+1));
2059 com_addbyte(c
, BINARY_POWER
);
2064 com_apply_trailer(c
, CHILD(n
, i
));
2069 com_invert_constant(struct compiling
*c
, node
*n
)
2071 /* Compute the inverse of int and longs and use them directly,
2072 but be prepared to generate code for all other
2073 possibilities (invalid numbers, floats, complex).
2075 PyObject
*num
, *inv
= NULL
;
2079 num
= parsenumber(c
, STR(n
));
2083 inv
= PyNumber_Invert(num
);
2086 i
= com_addconst(c
, num
);
2088 i
= com_addconst(c
, inv
);
2093 com_addoparg(c
, LOAD_CONST
, i
);
2095 if (num
!= NULL
&& inv
== NULL
)
2096 com_addbyte(c
, UNARY_INVERT
);
2100 is_float_zero(const char *p
)
2102 int found_radix_point
= 0;
2104 while ((ch
= Py_CHARMASK(*p
++)) != '\0') {
2107 /* no reason to believe it's not 0 -- continue */
2110 case 'e': case 'E': case 'j': case 'J':
2111 /* If this was a hex constant, we already would have
2112 returned 0 due to the 'x' or 'X', so 'e' or 'E'
2113 must be an exponent marker, and we haven't yet
2114 seen a non-zero digit, and it doesn't matter what
2115 the exponent is then. For 'j' or 'J' similarly,
2116 except that this is an imaginary 0 then. */
2120 found_radix_point
= 1;
2127 return found_radix_point
;
2131 com_factor(struct compiling
*c
, node
*n
)
2133 int childtype
= TYPE(CHILD(n
, 0));
2134 node
*pfactor
, *ppower
, *patom
, *pnum
;
2136 /* If the unary +, -, or ~ operator is applied to a constant,
2137 don't generate a UNARY_xxx opcode. Just store the
2138 approriate value as a constant. If the value is negative,
2139 extend the string containing the constant and insert a
2140 negative in the 0th position -- unless we're doing unary minus
2141 of a floating zero! In that case the sign is significant, but
2142 the const dict can't distinguish +0.0 from -0.0.
2144 if ((childtype
== PLUS
|| childtype
== MINUS
|| childtype
== TILDE
)
2146 && TYPE((pfactor
= CHILD(n
, 1))) == factor
2147 && NCH(pfactor
) == 1
2148 && TYPE((ppower
= CHILD(pfactor
, 0))) == power
2150 && TYPE((patom
= CHILD(ppower
, 0))) == atom
2151 && TYPE((pnum
= CHILD(patom
, 0))) == NUMBER
2152 && !(childtype
== MINUS
&&
2153 (STR(pnum
)[0] == '0' || is_float_zero(STR(pnum
))))) {
2154 if (childtype
== TILDE
) {
2155 com_invert_constant(c
, pnum
);
2158 if (childtype
== MINUS
) {
2159 char *s
= PyObject_MALLOC(strlen(STR(pnum
)) + 2);
2161 com_error(c
, PyExc_MemoryError
, "");
2162 com_addbyte(c
, 255);
2166 strcpy(s
+ 1, STR(pnum
));
2167 PyObject_FREE(STR(pnum
));
2172 else if (childtype
== PLUS
) {
2173 com_factor(c
, CHILD(n
, 1));
2174 com_addbyte(c
, UNARY_POSITIVE
);
2176 else if (childtype
== MINUS
) {
2177 com_factor(c
, CHILD(n
, 1));
2178 com_addbyte(c
, UNARY_NEGATIVE
);
2180 else if (childtype
== TILDE
) {
2181 com_factor(c
, CHILD(n
, 1));
2182 com_addbyte(c
, UNARY_INVERT
);
2185 com_power(c
, CHILD(n
, 0));
2190 com_term(struct compiling
*c
, node
*n
)
2195 com_factor(c
, CHILD(n
, 0));
2196 for (i
= 2; i
< NCH(n
); i
+= 2) {
2197 com_factor(c
, CHILD(n
, i
));
2198 switch (TYPE(CHILD(n
, i
-1))) {
2200 op
= BINARY_MULTIPLY
;
2203 if (c
->c_flags
& CO_FUTURE_DIVISION
)
2204 op
= BINARY_TRUE_DIVIDE
;
2212 op
= BINARY_FLOOR_DIVIDE
;
2215 com_error(c
, PyExc_SystemError
,
2216 "com_term: operator not *, /, // or %");
2225 com_arith_expr(struct compiling
*c
, node
*n
)
2230 com_term(c
, CHILD(n
, 0));
2231 for (i
= 2; i
< NCH(n
); i
+= 2) {
2232 com_term(c
, CHILD(n
, i
));
2233 switch (TYPE(CHILD(n
, i
-1))) {
2238 op
= BINARY_SUBTRACT
;
2241 com_error(c
, PyExc_SystemError
,
2242 "com_arith_expr: operator not + or -");
2251 com_shift_expr(struct compiling
*c
, node
*n
)
2256 com_arith_expr(c
, CHILD(n
, 0));
2257 for (i
= 2; i
< NCH(n
); i
+= 2) {
2258 com_arith_expr(c
, CHILD(n
, i
));
2259 switch (TYPE(CHILD(n
, i
-1))) {
2267 com_error(c
, PyExc_SystemError
,
2268 "com_shift_expr: operator not << or >>");
2277 com_and_expr(struct compiling
*c
, node
*n
)
2282 com_shift_expr(c
, CHILD(n
, 0));
2283 for (i
= 2; i
< NCH(n
); i
+= 2) {
2284 com_shift_expr(c
, CHILD(n
, i
));
2285 if (TYPE(CHILD(n
, i
-1)) == AMPER
) {
2289 com_error(c
, PyExc_SystemError
,
2290 "com_and_expr: operator not &");
2299 com_xor_expr(struct compiling
*c
, node
*n
)
2304 com_and_expr(c
, CHILD(n
, 0));
2305 for (i
= 2; i
< NCH(n
); i
+= 2) {
2306 com_and_expr(c
, CHILD(n
, i
));
2307 if (TYPE(CHILD(n
, i
-1)) == CIRCUMFLEX
) {
2311 com_error(c
, PyExc_SystemError
,
2312 "com_xor_expr: operator not ^");
2321 com_expr(struct compiling
*c
, node
*n
)
2326 com_xor_expr(c
, CHILD(n
, 0));
2327 for (i
= 2; i
< NCH(n
); i
+= 2) {
2328 com_xor_expr(c
, CHILD(n
, i
));
2329 if (TYPE(CHILD(n
, i
-1)) == VBAR
) {
2333 com_error(c
, PyExc_SystemError
,
2334 "com_expr: expr operator not |");
2346 /* comp_op: '<' | '>' | '>=' | '<=' | '<>' | '!=' | '=='
2347 | 'in' | 'not' 'in' | 'is' | 'is' not' */
2351 case LESS
: return PyCmp_LT
;
2352 case GREATER
: return PyCmp_GT
;
2353 case EQEQUAL
: return PyCmp_EQ
;
2354 case LESSEQUAL
: return PyCmp_LE
;
2355 case GREATEREQUAL
: return PyCmp_GE
;
2356 case NOTEQUAL
: return PyCmp_NE
; /* <> or != */
2357 case NAME
: if (strcmp(STR(n
), "in") == 0) return PyCmp_IN
;
2358 if (strcmp(STR(n
), "is") == 0) return PyCmp_IS
;
2361 else if (NCH(n
) == 2) {
2362 switch (TYPE(CHILD(n
, 0))) {
2363 case NAME
: if (strcmp(STR(CHILD(n
, 1)), "in") == 0)
2364 return PyCmp_NOT_IN
;
2365 if (strcmp(STR(CHILD(n
, 0)), "is") == 0)
2366 return PyCmp_IS_NOT
;
2373 com_comparison(struct compiling
*c
, node
*n
)
2378 REQ(n
, comparison
); /* comparison: expr (comp_op expr)* */
2379 com_expr(c
, CHILD(n
, 0));
2383 /****************************************************************
2384 The following code is generated for all but the last
2385 comparison in a chain:
2387 label: on stack: opcode: jump to:
2393 b, 0-or-1 JUMP_IF_FALSE L1
2397 We are now ready to repeat this sequence for the next
2398 comparison in the chain.
2400 For the last we generate:
2406 If there were any jumps to L1 (i.e., there was more than one
2407 comparison), we generate:
2409 0-or-1 JUMP_FORWARD L2
2414 ****************************************************************/
2418 for (i
= 2; i
< NCH(n
); i
+= 2) {
2419 com_expr(c
, CHILD(n
, i
));
2421 com_addbyte(c
, DUP_TOP
);
2423 com_addbyte(c
, ROT_THREE
);
2425 op
= cmp_type(CHILD(n
, i
-1));
2426 if (op
== PyCmp_BAD
) {
2427 com_error(c
, PyExc_SystemError
,
2428 "com_comparison: unknown comparison op");
2430 com_addoparg(c
, COMPARE_OP
, op
);
2433 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
2434 com_addbyte(c
, POP_TOP
);
2441 com_addfwref(c
, JUMP_FORWARD
, &anchor2
);
2442 com_backpatch(c
, anchor
);
2443 com_addbyte(c
, ROT_TWO
);
2444 com_addbyte(c
, POP_TOP
);
2445 com_backpatch(c
, anchor2
);
2450 com_not_test(struct compiling
*c
, node
*n
)
2452 REQ(n
, not_test
); /* 'not' not_test | comparison */
2454 com_comparison(c
, CHILD(n
, 0));
2457 com_not_test(c
, CHILD(n
, 1));
2458 com_addbyte(c
, UNARY_NOT
);
2463 com_and_test(struct compiling
*c
, node
*n
)
2467 REQ(n
, and_test
); /* not_test ('and' not_test)* */
2471 com_not_test(c
, CHILD(n
, i
));
2472 if ((i
+= 2) >= NCH(n
))
2474 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
2475 com_addbyte(c
, POP_TOP
);
2479 com_backpatch(c
, anchor
);
2483 com_make_closure(struct compiling
*c
, PyCodeObject
*co
)
2485 int i
, free
= PyCode_GetNumFree(co
);
2488 for (i
= 0; i
< free
; ++i
) {
2489 /* Bypass com_addop_varname because it will generate
2490 LOAD_DEREF but LOAD_CLOSURE is needed.
2492 PyObject
*name
= PyTuple_GET_ITEM(co
->co_freevars
, i
);
2495 /* Special case: If a class contains a method with a
2496 free variable that has the same name as a method,
2497 the name will be considered free *and* local in the
2498 class. It should be handled by the closure, as
2499 well as by the normal name loookup logic.
2501 reftype
= get_ref_type(c
, PyString_AS_STRING(name
));
2502 if (reftype
== CELL
)
2503 arg
= com_lookup_arg(c
->c_cellvars
, name
);
2504 else /* (reftype == FREE) */
2505 arg
= com_lookup_arg(c
->c_freevars
, name
);
2507 fprintf(stderr
, "lookup %s in %s %d %d\n"
2508 "freevars of %s: %s\n",
2509 PyObject_REPR(name
),
2512 PyString_AS_STRING(co
->co_name
),
2513 PyObject_REPR(co
->co_freevars
));
2514 Py_FatalError("com_make_closure()");
2516 com_addoparg(c
, LOAD_CLOSURE
, arg
);
2524 com_test(struct compiling
*c
, node
*n
)
2526 REQ(n
, test
); /* and_test ('or' and_test)* | lambdef */
2527 if (NCH(n
) == 1 && TYPE(CHILD(n
, 0)) == lambdef
) {
2530 int ndefs
= com_argdefs(c
, CHILD(n
, 0));
2531 symtable_enter_scope(c
->c_symtable
, "lambda", lambdef
,
2533 co
= icompile(CHILD(n
, 0), c
);
2538 symtable_exit_scope(c
->c_symtable
);
2539 i
= com_addconst(c
, (PyObject
*)co
);
2540 closure
= com_make_closure(c
, co
);
2541 com_addoparg(c
, LOAD_CONST
, i
);
2544 com_addoparg(c
, MAKE_CLOSURE
, ndefs
);
2545 com_pop(c
, PyCode_GetNumFree(co
));
2547 com_addoparg(c
, MAKE_FUNCTION
, ndefs
);
2555 com_and_test(c
, CHILD(n
, i
));
2556 if ((i
+= 2) >= NCH(n
))
2558 com_addfwref(c
, JUMP_IF_TRUE
, &anchor
);
2559 com_addbyte(c
, POP_TOP
);
2563 com_backpatch(c
, anchor
);
2568 com_list(struct compiling
*c
, node
*n
, int toplevel
)
2570 /* exprlist: expr (',' expr)* [',']; likewise for testlist */
2571 if (NCH(n
) == 1 && !toplevel
) {
2572 com_node(c
, CHILD(n
, 0));
2577 len
= (NCH(n
) + 1) / 2;
2578 for (i
= 0; i
< NCH(n
); i
+= 2)
2579 com_node(c
, CHILD(n
, i
));
2580 com_addoparg(c
, BUILD_TUPLE
, len
);
2586 /* Begin of assignment compilation */
2590 com_augassign_attr(struct compiling
*c
, node
*n
, int opcode
, node
*augn
)
2592 com_addbyte(c
, DUP_TOP
);
2594 com_addopname(c
, LOAD_ATTR
, n
);
2596 com_addbyte(c
, opcode
);
2598 com_addbyte(c
, ROT_TWO
);
2599 com_addopname(c
, STORE_ATTR
, n
);
2604 com_assign_attr(struct compiling
*c
, node
*n
, int assigning
)
2606 if (none_assignment_check(c
, STR(n
), assigning
))
2608 com_addopname(c
, assigning
? STORE_ATTR
: DELETE_ATTR
, n
);
2609 com_pop(c
, assigning
? 2 : 1);
2613 com_assign_trailer(struct compiling
*c
, node
*n
, int assigning
, node
*augn
)
2616 switch (TYPE(CHILD(n
, 0))) {
2617 case LPAR
: /* '(' [exprlist] ')' */
2618 if (assigning
== OP_DELETE
)
2619 com_error(c
, PyExc_SyntaxError
,
2620 "can't delete function call");
2622 com_error(c
, PyExc_SyntaxError
,
2623 "can't assign to function call");
2625 case DOT
: /* '.' NAME */
2626 if (assigning
> OP_APPLY
)
2627 com_augassign_attr(c
, CHILD(n
, 1), assigning
, augn
);
2629 com_assign_attr(c
, CHILD(n
, 1), assigning
);
2631 case LSQB
: /* '[' subscriptlist ']' */
2632 com_subscriptlist(c
, CHILD(n
, 1), assigning
, augn
);
2635 com_error(c
, PyExc_SystemError
, "unknown trailer type");
2640 com_assign_sequence(struct compiling
*c
, node
*n
, int assigning
)
2643 if (TYPE(n
) != testlist
&& TYPE(n
) != listmaker
)
2647 com_addoparg(c
, UNPACK_SEQUENCE
, i
);
2650 for (i
= 0; i
< NCH(n
); i
+= 2)
2651 com_assign(c
, CHILD(n
, i
), assigning
, NULL
);
2655 com_augassign_name(struct compiling
*c
, node
*n
, int opcode
, node
*augn
)
2658 com_addop_varname(c
, VAR_LOAD
, STR(n
));
2661 com_addbyte(c
, opcode
);
2663 com_assign_name(c
, n
, OP_ASSIGN
);
2667 com_assign_name(struct compiling
*c
, node
*n
, int assigning
)
2670 com_addop_varname(c
, assigning
? VAR_STORE
: VAR_DELETE
, STR(n
));
2676 com_assign(struct compiling
*c
, node
*n
, int assigning
, node
*augn
)
2678 /* Loop to avoid trivial recursion */
2686 if (assigning
> OP_APPLY
) {
2687 com_error(c
, PyExc_SyntaxError
,
2688 "augmented assign to tuple not possible");
2691 com_assign_sequence(c
, n
, assigning
);
2709 com_error(c
, PyExc_SyntaxError
,
2710 "can't assign to operator");
2716 case power
: /* atom trailer* ('**' power)*
2717 ('+'|'-'|'~') factor | atom trailer* */
2718 if (TYPE(CHILD(n
, 0)) != atom
) {
2719 com_error(c
, PyExc_SyntaxError
,
2720 "can't assign to operator");
2723 if (NCH(n
) > 1) { /* trailer or exponent present */
2725 com_node(c
, CHILD(n
, 0));
2726 for (i
= 1; i
+1 < NCH(n
); i
++) {
2727 if (TYPE(CHILD(n
, i
)) == DOUBLESTAR
) {
2728 com_error(c
, PyExc_SyntaxError
,
2729 "can't assign to operator");
2732 com_apply_trailer(c
, CHILD(n
, i
));
2733 } /* NB i is still alive */
2734 com_assign_trailer(c
,
2735 CHILD(n
, i
), assigning
, augn
);
2742 switch (TYPE(CHILD(n
, 0))) {
2745 if (TYPE(n
) == RPAR
) {
2746 /* XXX Should allow () = () ??? */
2747 com_error(c
, PyExc_SyntaxError
,
2748 "can't assign to ()");
2751 if (assigning
> OP_APPLY
) {
2752 com_error(c
, PyExc_SyntaxError
,
2753 "augmented assign to tuple literal not possible");
2759 if (TYPE(n
) == RSQB
) {
2760 com_error(c
, PyExc_SyntaxError
,
2761 "can't assign to []");
2764 if (assigning
> OP_APPLY
) {
2765 com_error(c
, PyExc_SyntaxError
,
2766 "augmented assign to list literal not possible");
2770 && TYPE(CHILD(n
, 1)) == list_for
) {
2771 com_error(c
, PyExc_SyntaxError
,
2772 "can't assign to list comprehension");
2775 com_assign_sequence(c
, n
, assigning
);
2778 if (assigning
> OP_APPLY
)
2779 com_augassign_name(c
, CHILD(n
, 0),
2782 com_assign_name(c
, CHILD(n
, 0),
2786 com_error(c
, PyExc_SyntaxError
,
2787 "can't assign to literal");
2793 com_error(c
, PyExc_SyntaxError
,
2794 "can't assign to lambda");
2798 com_error(c
, PyExc_SystemError
,
2799 "com_assign: bad node");
2807 com_augassign(struct compiling
*c
, node
*n
)
2811 switch (STR(CHILD(CHILD(n
, 1), 0))[0]) {
2812 case '+': opcode
= INPLACE_ADD
; break;
2813 case '-': opcode
= INPLACE_SUBTRACT
; break;
2815 if (STR(CHILD(CHILD(n
, 1), 0))[1] == '/')
2816 opcode
= INPLACE_FLOOR_DIVIDE
;
2817 else if (c
->c_flags
& CO_FUTURE_DIVISION
)
2818 opcode
= INPLACE_TRUE_DIVIDE
;
2820 opcode
= INPLACE_DIVIDE
;
2822 case '%': opcode
= INPLACE_MODULO
; break;
2823 case '<': opcode
= INPLACE_LSHIFT
; break;
2824 case '>': opcode
= INPLACE_RSHIFT
; break;
2825 case '&': opcode
= INPLACE_AND
; break;
2826 case '^': opcode
= INPLACE_XOR
; break;
2827 case '|': opcode
= INPLACE_OR
; break;
2829 if (STR(CHILD(CHILD(n
, 1), 0))[1] == '*')
2830 opcode
= INPLACE_POWER
;
2832 opcode
= INPLACE_MULTIPLY
;
2835 com_error(c
, PyExc_SystemError
, "com_augassign: bad operator");
2838 com_assign(c
, CHILD(n
, 0), opcode
, CHILD(n
, 2));
2842 com_expr_stmt(struct compiling
*c
, node
*n
)
2845 /* testlist (('=' testlist)* | augassign testlist) */
2846 /* Forget it if we have just a doc string here */
2847 if (!c
->c_interactive
&& NCH(n
) == 1 && get_rawdocstring(n
) != NULL
)
2850 com_node(c
, CHILD(n
, NCH(n
)-1));
2851 if (c
->c_interactive
)
2852 com_addbyte(c
, PRINT_EXPR
);
2854 com_addbyte(c
, POP_TOP
);
2857 else if (TYPE(CHILD(n
,1)) == augassign
)
2858 com_augassign(c
, n
);
2861 com_node(c
, CHILD(n
, NCH(n
)-1));
2862 for (i
= 0; i
< NCH(n
)-2; i
+=2) {
2863 if (i
+2 < NCH(n
)-2) {
2864 com_addbyte(c
, DUP_TOP
);
2867 com_assign(c
, CHILD(n
, i
), OP_ASSIGN
, NULL
);
2873 com_assert_stmt(struct compiling
*c
, node
*n
)
2877 REQ(n
, assert_stmt
); /* 'assert' test [',' test] */
2878 if (Py_OptimizeFlag
)
2880 /* Generate code like
2883 raise AssertionError [, <message>]
2885 where <message> is the second test, if present.
2887 com_node(c
, CHILD(n
, 1));
2888 com_addfwref(c
, JUMP_IF_TRUE
, &a
);
2889 com_addbyte(c
, POP_TOP
);
2891 /* Raise that exception! */
2892 com_addop_name(c
, LOAD_GLOBAL
, "AssertionError");
2894 i
= NCH(n
)/2; /* Either 2 or 4 */
2896 com_node(c
, CHILD(n
, 3));
2897 com_addoparg(c
, RAISE_VARARGS
, i
);
2899 /* The interpreter does not fall through */
2900 /* Jump ends up here */
2901 com_backpatch(c
, a
);
2902 com_addbyte(c
, POP_TOP
);
2906 com_print_stmt(struct compiling
*c
, node
*n
)
2909 node
* stream
= NULL
;
2911 REQ(n
, print_stmt
); /* 'print' (test ',')* [test] */
2913 /* are we using the extended print form? */
2914 if (NCH(n
) >= 2 && TYPE(CHILD(n
, 1)) == RIGHTSHIFT
) {
2915 stream
= CHILD(n
, 2);
2916 com_node(c
, stream
);
2917 /* stack: [...] => [... stream] */
2919 if (NCH(n
) > 3 && TYPE(CHILD(n
, 3)) == COMMA
)
2924 for (; i
< NCH(n
); i
+= 2) {
2925 if (stream
!= NULL
) {
2926 com_addbyte(c
, DUP_TOP
);
2927 /* stack: [stream] => [stream stream] */
2929 com_node(c
, CHILD(n
, i
));
2930 /* stack: [stream stream] => [stream stream obj] */
2931 com_addbyte(c
, ROT_TWO
);
2932 /* stack: [stream stream obj] => [stream obj stream] */
2933 com_addbyte(c
, PRINT_ITEM_TO
);
2934 /* stack: [stream obj stream] => [stream] */
2938 com_node(c
, CHILD(n
, i
));
2939 /* stack: [...] => [... obj] */
2940 com_addbyte(c
, PRINT_ITEM
);
2944 /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */
2945 if (TYPE(CHILD(n
, NCH(n
)-1)) == COMMA
) {
2946 if (stream
!= NULL
) {
2947 /* must pop the extra stream object off the stack */
2948 com_addbyte(c
, POP_TOP
);
2949 /* stack: [... stream] => [...] */
2954 if (stream
!= NULL
) {
2955 /* this consumes the last stream object on stack */
2956 com_addbyte(c
, PRINT_NEWLINE_TO
);
2957 /* stack: [... stream] => [...] */
2961 com_addbyte(c
, PRINT_NEWLINE
);
2966 com_return_stmt(struct compiling
*c
, node
*n
)
2968 REQ(n
, return_stmt
); /* 'return' [testlist] */
2969 if (!c
->c_infunction
) {
2970 com_error(c
, PyExc_SyntaxError
, "'return' outside function");
2972 if (c
->c_flags
& CO_GENERATOR
) {
2974 com_error(c
, PyExc_SyntaxError
,
2975 "'return' with argument inside generator");
2979 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
2983 com_node(c
, CHILD(n
, 1));
2984 com_addbyte(c
, RETURN_VALUE
);
2989 com_yield_stmt(struct compiling
*c
, node
*n
)
2992 REQ(n
, yield_stmt
); /* 'yield' testlist */
2993 if (!c
->c_infunction
) {
2994 com_error(c
, PyExc_SyntaxError
, "'yield' outside function");
2997 for (i
= 0; i
< c
->c_nblocks
; ++i
) {
2998 if (c
->c_block
[i
] == SETUP_FINALLY
) {
2999 com_error(c
, PyExc_SyntaxError
,
3000 "'yield' not allowed in a 'try' block "
3001 "with a 'finally' clause");
3005 com_node(c
, CHILD(n
, 1));
3006 com_addbyte(c
, YIELD_VALUE
);
3011 com_raise_stmt(struct compiling
*c
, node
*n
)
3014 REQ(n
, raise_stmt
); /* 'raise' [test [',' test [',' test]]] */
3016 com_node(c
, CHILD(n
, 1));
3018 com_node(c
, CHILD(n
, 3));
3020 com_node(c
, CHILD(n
, 5));
3024 com_addoparg(c
, RAISE_VARARGS
, i
);
3029 com_from_import(struct compiling
*c
, node
*n
)
3031 com_addopname(c
, IMPORT_FROM
, CHILD(n
, 0));
3034 if (strcmp(STR(CHILD(n
, 1)), "as") != 0) {
3035 com_error(c
, PyExc_SyntaxError
, "invalid syntax");
3038 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 2)));
3040 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 0)));
3045 com_import_stmt(struct compiling
*c
, node
*n
)
3048 REQ(n
, import_stmt
);
3049 /* 'import' dotted_name (',' dotted_name)* |
3050 'from' dotted_name 'import' ('*' | NAME (',' NAME)*) */
3051 if (STR(CHILD(n
, 0))[0] == 'f') {
3053 /* 'from' dotted_name 'import' ... */
3054 REQ(CHILD(n
, 1), dotted_name
);
3056 if (TYPE(CHILD(n
, 3)) == STAR
) {
3057 tup
= Py_BuildValue("(s)", "*");
3059 tup
= PyTuple_New((NCH(n
) - 2)/2);
3060 for (i
= 3; i
< NCH(n
); i
+= 2) {
3061 PyTuple_SET_ITEM(tup
, (i
-3)/2,
3062 PyString_FromString(STR(
3063 CHILD(CHILD(n
, i
), 0))));
3066 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, tup
));
3069 com_addopname(c
, IMPORT_NAME
, CHILD(n
, 1));
3070 if (TYPE(CHILD(n
, 3)) == STAR
)
3071 com_addbyte(c
, IMPORT_STAR
);
3073 for (i
= 3; i
< NCH(n
); i
+= 2)
3074 com_from_import(c
, CHILD(n
, i
));
3075 com_addbyte(c
, POP_TOP
);
3081 for (i
= 1; i
< NCH(n
); i
+= 2) {
3082 node
*subn
= CHILD(n
, i
);
3083 REQ(subn
, dotted_as_name
);
3084 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3086 com_addopname(c
, IMPORT_NAME
, CHILD(subn
, 0));
3087 if (NCH(subn
) > 1) {
3089 if (strcmp(STR(CHILD(subn
, 1)), "as") != 0) {
3090 com_error(c
, PyExc_SyntaxError
,
3094 for (j
=2 ; j
< NCH(CHILD(subn
, 0)); j
+= 2)
3095 com_addopname(c
, LOAD_ATTR
,
3096 CHILD(CHILD(subn
, 0),
3098 com_addop_varname(c
, VAR_STORE
,
3099 STR(CHILD(subn
, 2)));
3101 com_addop_varname(c
, VAR_STORE
,
3102 STR(CHILD(CHILD(subn
, 0),
3110 com_exec_stmt(struct compiling
*c
, node
*n
)
3113 /* exec_stmt: 'exec' expr ['in' expr [',' expr]] */
3114 com_node(c
, CHILD(n
, 1));
3116 com_node(c
, CHILD(n
, 3));
3118 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3122 com_node(c
, CHILD(n
, 5));
3124 com_addbyte(c
, DUP_TOP
);
3127 com_addbyte(c
, EXEC_STMT
);
3132 is_constant_false(struct compiling
*c
, node
*n
)
3136 /* argument c will be NULL when called from symtable_node() */
3138 /* Label to avoid tail recursion */
3149 for (i
= 0; i
< NCH(n
); i
++) {
3150 node
*ch
= CHILD(n
, i
);
3151 if (TYPE(ch
) == stmt
) {
3187 if (Py_OptimizeFlag
&& strcmp(STR(n
), "__debug__") == 0)
3192 v
= parsenumber(c
, STR(n
));
3197 i
= PyObject_IsTrue(v
);
3202 v
= parsestr(c
, STR(n
));
3207 i
= PyObject_IsTrue(v
);
3216 /* Look under n for a return stmt with an expression.
3217 * This hack is used to find illegal returns under "if 0:" blocks in
3218 * functions already known to be generators (as determined by the symtable
3220 * Return the offending return node if found, else NULL.
3223 look_for_offending_return(node
*n
)
3227 for (i
= 0; i
< NCH(n
); ++i
) {
3228 node
*kid
= CHILD(n
, i
);
3230 switch (TYPE(kid
)) {
3234 /* Stuff in nested functions & classes doesn't
3235 affect the code block we started in. */
3244 node
*bad
= look_for_offending_return(kid
);
3255 com_if_stmt(struct compiling
*c
, node
*n
)
3260 /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */
3261 for (i
= 0; i
+3 < NCH(n
); i
+=4) {
3263 node
*ch
= CHILD(n
, i
+1);
3264 if (is_constant_false(c
, ch
)) {
3265 /* We're going to skip this block. However, if this
3266 is a generator, we have to check the dead code
3267 anyway to make sure there aren't any return stmts
3268 with expressions, in the same scope. */
3269 if (c
->c_flags
& CO_GENERATOR
) {
3270 node
*p
= look_for_offending_return(n
);
3272 int savelineno
= c
->c_lineno
;
3273 c
->c_lineno
= p
->n_lineno
;
3274 com_error(c
, PyExc_SyntaxError
,
3275 "'return' with argument "
3276 "inside generator");
3277 c
->c_lineno
= savelineno
;
3283 com_set_lineno(c
, ch
->n_lineno
);
3285 com_addfwref(c
, JUMP_IF_FALSE
, &a
);
3286 com_addbyte(c
, POP_TOP
);
3288 com_node(c
, CHILD(n
, i
+3));
3289 com_addfwref(c
, JUMP_FORWARD
, &anchor
);
3290 com_backpatch(c
, a
);
3291 /* We jump here with an extra entry which we now pop */
3292 com_addbyte(c
, POP_TOP
);
3295 com_node(c
, CHILD(n
, i
+2));
3297 com_backpatch(c
, anchor
);
3301 com_while_stmt(struct compiling
*c
, node
*n
)
3303 int break_anchor
= 0;
3305 int save_begin
= c
->c_begin
;
3306 REQ(n
, while_stmt
); /* 'while' test ':' suite ['else' ':' suite] */
3307 com_addfwref(c
, SETUP_LOOP
, &break_anchor
);
3308 block_push(c
, SETUP_LOOP
);
3309 c
->c_begin
= c
->c_nexti
;
3310 com_set_lineno(c
, n
->n_lineno
);
3311 com_node(c
, CHILD(n
, 1));
3312 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
3313 com_addbyte(c
, POP_TOP
);
3316 com_node(c
, CHILD(n
, 3));
3318 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
3319 c
->c_begin
= save_begin
;
3320 com_backpatch(c
, anchor
);
3321 /* We jump here with one entry more on the stack */
3322 com_addbyte(c
, POP_TOP
);
3323 com_addbyte(c
, POP_BLOCK
);
3324 block_pop(c
, SETUP_LOOP
);
3326 com_node(c
, CHILD(n
, 6));
3327 com_backpatch(c
, break_anchor
);
3331 com_for_stmt(struct compiling
*c
, node
*n
)
3333 int break_anchor
= 0;
3335 int save_begin
= c
->c_begin
;
3337 /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */
3338 com_addfwref(c
, SETUP_LOOP
, &break_anchor
);
3339 block_push(c
, SETUP_LOOP
);
3340 com_node(c
, CHILD(n
, 3));
3341 com_addbyte(c
, GET_ITER
);
3342 c
->c_begin
= c
->c_nexti
;
3343 com_set_lineno(c
, c
->c_last_line
);
3344 com_addfwref(c
, FOR_ITER
, &anchor
);
3346 com_assign(c
, CHILD(n
, 1), OP_ASSIGN
, NULL
);
3348 com_node(c
, CHILD(n
, 5));
3350 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
3351 c
->c_begin
= save_begin
;
3352 com_backpatch(c
, anchor
);
3353 com_pop(c
, 1); /* FOR_ITER has popped this */
3354 com_addbyte(c
, POP_BLOCK
);
3355 block_pop(c
, SETUP_LOOP
);
3357 com_node(c
, CHILD(n
, 8));
3358 com_backpatch(c
, break_anchor
);
3361 /* Code generated for "try: S finally: Sf" is as follows:
3370 The special instructions use the block stack. Each block
3371 stack entry contains the instruction that created it (here
3372 SETUP_FINALLY), the level of the value stack at the time the
3373 block stack entry was created, and a label (here L).
3376 Pushes the current value stack level and the label
3377 onto the block stack.
3379 Pops en entry from the block stack, and pops the value
3380 stack until its level is the same as indicated on the
3381 block stack. (The label is ignored.)
3383 Pops a variable number of entries from the *value* stack
3384 and re-raises the exception they specify. The number of
3385 entries popped depends on the (pseudo) exception type.
3387 The block stack is unwound when an exception is raised:
3388 when a SETUP_FINALLY entry is found, the exception is pushed
3389 onto the value stack (and the exception condition is cleared),
3390 and the interpreter jumps to the label gotten from the block
3393 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
3394 (The contents of the value stack is shown in [], with the top
3395 at the right; 'tb' is trace-back info, 'val' the exception's
3396 associated value, and 'exc' the exception.)
3398 Value stack Label Instruction Argument
3404 [tb, val, exc] L1: DUP )
3405 [tb, val, exc, exc] <evaluate E1> )
3406 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
3407 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
3408 [tb, val, exc, 1] POP )
3410 [tb, val] <assign to V1> (or POP if no V1)
3415 [tb, val, exc, 0] L2: POP
3417 .............................etc.......................
3419 [tb, val, exc, 0] Ln+1: POP
3420 [tb, val, exc] END_FINALLY # re-raise exception
3422 [] L0: <next statement>
3424 Of course, parts are not generated if Vi or Ei is not present.
3428 com_try_except(struct compiling
*c
, node
*n
)
3430 int except_anchor
= 0;
3432 int else_anchor
= 0;
3436 com_addfwref(c
, SETUP_EXCEPT
, &except_anchor
);
3437 block_push(c
, SETUP_EXCEPT
);
3438 com_node(c
, CHILD(n
, 2));
3439 com_addbyte(c
, POP_BLOCK
);
3440 block_pop(c
, SETUP_EXCEPT
);
3441 com_addfwref(c
, JUMP_FORWARD
, &else_anchor
);
3442 com_backpatch(c
, except_anchor
);
3444 i
< NCH(n
) && TYPE(ch
= CHILD(n
, i
)) == except_clause
;
3446 /* except_clause: 'except' [expr [',' var]] */
3447 if (except_anchor
== 0) {
3448 com_error(c
, PyExc_SyntaxError
,
3449 "default 'except:' must be last");
3453 com_push(c
, 3); /* tb, val, exc pushed by exception */
3454 com_set_lineno(c
, ch
->n_lineno
);
3456 com_addbyte(c
, DUP_TOP
);
3458 com_node(c
, CHILD(ch
, 1));
3459 com_addoparg(c
, COMPARE_OP
, PyCmp_EXC_MATCH
);
3461 com_addfwref(c
, JUMP_IF_FALSE
, &except_anchor
);
3462 com_addbyte(c
, POP_TOP
);
3465 com_addbyte(c
, POP_TOP
);
3468 com_assign(c
, CHILD(ch
, 3), OP_ASSIGN
, NULL
);
3470 com_addbyte(c
, POP_TOP
);
3473 com_addbyte(c
, POP_TOP
);
3475 com_node(c
, CHILD(n
, i
+2));
3476 com_addfwref(c
, JUMP_FORWARD
, &end_anchor
);
3477 if (except_anchor
) {
3478 com_backpatch(c
, except_anchor
);
3479 /* We come in with [tb, val, exc, 0] on the
3480 stack; one pop and it's the same as
3481 expected at the start of the loop */
3482 com_addbyte(c
, POP_TOP
);
3485 /* We actually come in here with [tb, val, exc] but the
3486 END_FINALLY will zap those and jump around.
3487 The c_stacklevel does not reflect them so we need not pop
3489 com_addbyte(c
, END_FINALLY
);
3490 com_backpatch(c
, else_anchor
);
3492 com_node(c
, CHILD(n
, i
+2));
3493 com_backpatch(c
, end_anchor
);
3497 com_try_finally(struct compiling
*c
, node
*n
)
3499 int finally_anchor
= 0;
3502 com_addfwref(c
, SETUP_FINALLY
, &finally_anchor
);
3503 block_push(c
, SETUP_FINALLY
);
3504 com_node(c
, CHILD(n
, 2));
3505 com_addbyte(c
, POP_BLOCK
);
3506 block_pop(c
, SETUP_FINALLY
);
3507 block_push(c
, END_FINALLY
);
3508 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3509 /* While the generated code pushes only one item,
3510 the try-finally handling can enter here with
3511 up to three items. OK, here are the details:
3512 3 for an exception, 2 for RETURN, 1 for BREAK. */
3514 com_backpatch(c
, finally_anchor
);
3515 ch
= CHILD(n
, NCH(n
)-1);
3516 com_set_lineno(c
, ch
->n_lineno
);
3518 com_addbyte(c
, END_FINALLY
);
3519 block_pop(c
, END_FINALLY
);
3520 com_pop(c
, 3); /* Matches the com_push above */
3524 com_try_stmt(struct compiling
*c
, node
*n
)
3527 /* 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
3528 | 'try' ':' suite 'finally' ':' suite */
3529 if (TYPE(CHILD(n
, 3)) != except_clause
)
3530 com_try_finally(c
, n
);
3532 com_try_except(c
, n
);
3536 get_rawdocstring(node
*n
)
3540 /* Label to avoid tail recursion */
3551 for (i
= 0; i
< NCH(n
); i
++) {
3552 node
*ch
= CHILD(n
, i
);
3553 if (TYPE(ch
) == stmt
) {
3588 if (TYPE(CHILD(n
, 0)) == STRING
)
3597 get_docstring(struct compiling
*c
, node
*n
)
3599 /* Don't generate doc-strings if run with -OO */
3600 if (Py_OptimizeFlag
> 1)
3602 n
= get_rawdocstring(n
);
3605 return parsestrplus(c
, n
);
3609 com_suite(struct compiling
*c
, node
*n
)
3612 /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */
3614 com_node(c
, CHILD(n
, 0));
3618 for (i
= 0; i
< NCH(n
) && c
->c_errors
== 0; i
++) {
3619 node
*ch
= CHILD(n
, i
);
3620 if (TYPE(ch
) == stmt
)
3628 com_continue_stmt(struct compiling
*c
, node
*n
)
3630 int i
= c
->c_nblocks
;
3631 if (i
-- > 0 && c
->c_block
[i
] == SETUP_LOOP
) {
3632 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
3635 /* at the outer level */
3636 com_error(c
, PyExc_SyntaxError
,
3637 "'continue' not properly in loop");
3641 for (j
= i
-1; j
>= 0; --j
) {
3642 if (c
->c_block
[j
] == SETUP_LOOP
)
3646 /* there is a loop, but something interferes */
3647 for (; i
> j
; --i
) {
3648 if (c
->c_block
[i
] == SETUP_EXCEPT
||
3649 c
->c_block
[i
] == SETUP_FINALLY
) {
3650 com_addoparg(c
, CONTINUE_LOOP
,
3654 if (c
->c_block
[i
] == END_FINALLY
) {
3655 com_error(c
, PyExc_SyntaxError
,
3656 "'continue' not supported inside 'finally' clause");
3661 com_error(c
, PyExc_SyntaxError
,
3662 "'continue' not properly in loop");
3664 /* XXX Could allow it inside a 'finally' clause
3665 XXX if we could pop the exception still on the stack */
3669 com_argdefs(struct compiling
*c
, node
*n
)
3671 int i
, nch
, nargs
, ndefs
;
3672 if (TYPE(n
) == lambdef
) {
3673 /* lambdef: 'lambda' [varargslist] ':' test */
3677 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ... */
3679 REQ(n
, parameters
); /* parameters: '(' [varargslist] ')' */
3682 if (TYPE(n
) != varargslist
)
3685 (fpdef ['=' test] ',')* '*' ....... |
3686 fpdef ['=' test] (',' fpdef ['=' test])* [','] */
3690 for (i
= 0; i
< nch
; i
++) {
3692 if (TYPE(CHILD(n
, i
)) == STAR
||
3693 TYPE(CHILD(n
, i
)) == DOUBLESTAR
)
3698 t
= RPAR
; /* Anything except EQUAL or COMMA */
3700 t
= TYPE(CHILD(n
, i
));
3704 com_node(c
, CHILD(n
, i
));
3708 t
= TYPE(CHILD(n
, i
));
3711 /* Treat "(a=1, b)" as an error */
3713 com_error(c
, PyExc_SyntaxError
,
3714 "non-default argument follows default argument");
3723 com_funcdef(struct compiling
*c
, node
*n
)
3727 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ':' suite */
3728 ndefs
= com_argdefs(c
, n
);
3729 symtable_enter_scope(c
->c_symtable
, STR(CHILD(n
, 1)), TYPE(n
),
3731 co
= (PyObject
*)icompile(n
, c
);
3732 symtable_exit_scope(c
->c_symtable
);
3736 int closure
= com_make_closure(c
, (PyCodeObject
*)co
);
3737 int i
= com_addconst(c
, co
);
3738 com_addoparg(c
, LOAD_CONST
, i
);
3741 com_addoparg(c
, MAKE_CLOSURE
, ndefs
);
3743 com_addoparg(c
, MAKE_FUNCTION
, ndefs
);
3745 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 1)));
3752 com_bases(struct compiling
*c
, node
*n
)
3756 /* testlist: test (',' test)* [','] */
3757 for (i
= 0; i
< NCH(n
); i
+= 2)
3758 com_node(c
, CHILD(n
, i
));
3760 com_addoparg(c
, BUILD_TUPLE
, i
);
3765 com_classdef(struct compiling
*c
, node
*n
)
3773 /* classdef: class NAME ['(' testlist ')'] ':' suite */
3774 if ((v
= PyString_InternFromString(STR(CHILD(n
, 1)))) == NULL
) {
3778 /* Push the class name on the stack */
3779 i
= com_addconst(c
, v
);
3780 com_addoparg(c
, LOAD_CONST
, i
);
3783 /* Push the tuple of base classes on the stack */
3784 if (TYPE(CHILD(n
, 2)) != LPAR
) {
3785 com_addoparg(c
, BUILD_TUPLE
, 0);
3789 com_bases(c
, CHILD(n
, 3));
3790 name
= STR(CHILD(n
, 1));
3791 symtable_enter_scope(c
->c_symtable
, name
, TYPE(n
), n
->n_lineno
);
3792 co
= icompile(n
, c
);
3793 symtable_exit_scope(c
->c_symtable
);
3797 int closure
= com_make_closure(c
, co
);
3798 i
= com_addconst(c
, (PyObject
*)co
);
3799 com_addoparg(c
, LOAD_CONST
, i
);
3802 com_addoparg(c
, MAKE_CLOSURE
, 0);
3803 com_pop(c
, PyCode_GetNumFree(co
));
3805 com_addoparg(c
, MAKE_FUNCTION
, 0);
3806 com_addoparg(c
, CALL_FUNCTION
, 0);
3807 com_addbyte(c
, BUILD_CLASS
);
3809 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 1)));
3816 com_node(struct compiling
*c
, node
*n
)
3823 /* Definition nodes */
3832 /* Trivial parse tree nodes */
3841 /* small_stmt (';' small_stmt)* [';'] NEWLINE */
3842 com_set_lineno(c
, n
->n_lineno
);
3845 for (i
= 0; i
< NCH(n
)-1; i
+= 2)
3846 com_node(c
, CHILD(n
, i
));
3851 com_set_lineno(c
, n
->n_lineno
);
3855 /* Statement nodes */
3858 com_expr_stmt(c
, n
);
3861 com_print_stmt(c
, n
);
3863 case del_stmt
: /* 'del' exprlist */
3864 com_assign(c
, CHILD(n
, 1), OP_DELETE
, NULL
);
3869 if (c
->c_loops
== 0) {
3870 com_error(c
, PyExc_SyntaxError
,
3871 "'break' outside loop");
3873 com_addbyte(c
, BREAK_LOOP
);
3876 com_continue_stmt(c
, n
);
3879 com_return_stmt(c
, n
);
3882 com_yield_stmt(c
, n
);
3885 com_raise_stmt(c
, n
);
3888 com_import_stmt(c
, n
);
3893 com_exec_stmt(c
, n
);
3896 com_assert_stmt(c
, n
);
3902 com_while_stmt(c
, n
);
3914 /* Expression nodes */
3931 com_comparison(c
, n
);
3946 com_shift_expr(c
, n
);
3949 com_arith_expr(c
, n
);
3965 com_error(c
, PyExc_SystemError
,
3966 "com_node: unexpected node type");
3970 static void com_fplist(struct compiling
*, node
*);
3973 com_fpdef(struct compiling
*c
, node
*n
)
3975 REQ(n
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
3976 if (TYPE(CHILD(n
, 0)) == LPAR
)
3977 com_fplist(c
, CHILD(n
, 1));
3979 com_addop_varname(c
, VAR_STORE
, STR(CHILD(n
, 0)));
3985 com_fplist(struct compiling
*c
, node
*n
)
3987 REQ(n
, fplist
); /* fplist: fpdef (',' fpdef)* [','] */
3989 com_fpdef(c
, CHILD(n
, 0));
3992 int i
= (NCH(n
)+1)/2;
3993 com_addoparg(c
, UNPACK_SEQUENCE
, i
);
3995 for (i
= 0; i
< NCH(n
); i
+= 2)
3996 com_fpdef(c
, CHILD(n
, i
));
4001 com_arglist(struct compiling
*c
, node
*n
)
4006 REQ(n
, varargslist
);
4008 (fpdef ['=' test] ',')* (fpdef ['=' test] | '*' .....) */
4010 /* Enter all arguments in table of locals */
4011 for (i
= 0, narg
= 0; i
< nch
; i
++) {
4012 node
*ch
= CHILD(n
, i
);
4014 if (TYPE(ch
) == STAR
|| TYPE(ch
) == DOUBLESTAR
)
4016 REQ(ch
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
4018 if (TYPE(fp
) != NAME
) {
4019 PyOS_snprintf(nbuf
, sizeof(nbuf
), ".%d", i
);
4023 /* all name updates handled by symtable */
4027 if (TYPE(ch
) == EQUAL
)
4033 /* Generate code for complex arguments only after
4034 having counted the simple arguments */
4036 for (i
= 0; i
< nch
; i
++) {
4037 node
*ch
= CHILD(n
, i
);
4039 if (TYPE(ch
) == STAR
|| TYPE(ch
) == DOUBLESTAR
)
4041 REQ(ch
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
4043 if (TYPE(fp
) != NAME
) {
4044 com_addoparg(c
, LOAD_FAST
, ilocal
);
4052 if (TYPE(ch
) == EQUAL
)
4061 com_file_input(struct compiling
*c
, node
*n
)
4065 REQ(n
, file_input
); /* (NEWLINE | stmt)* ENDMARKER */
4066 doc
= get_docstring(c
, n
);
4068 int i
= com_addconst(c
, doc
);
4070 com_addoparg(c
, LOAD_CONST
, i
);
4072 com_addop_name(c
, STORE_NAME
, "__doc__");
4075 for (i
= 0; i
< NCH(n
); i
++) {
4076 node
*ch
= CHILD(n
, i
);
4077 if (TYPE(ch
) != ENDMARKER
&& TYPE(ch
) != NEWLINE
)
4082 /* Top-level compile-node interface */
4085 compile_funcdef(struct compiling
*c
, node
*n
)
4089 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ':' suite */
4090 c
->c_name
= STR(CHILD(n
, 1));
4091 doc
= get_docstring(c
, CHILD(n
, 4));
4093 (void) com_addconst(c
, doc
);
4097 (void) com_addconst(c
, Py_None
); /* No docstring */
4098 ch
= CHILD(n
, 2); /* parameters: '(' [varargslist] ')' */
4099 ch
= CHILD(ch
, 1); /* ')' | varargslist */
4100 if (TYPE(ch
) == varargslist
)
4102 c
->c_infunction
= 1;
4103 com_node(c
, CHILD(n
, 4));
4104 c
->c_infunction
= 0;
4105 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
4107 com_addbyte(c
, RETURN_VALUE
);
4112 compile_lambdef(struct compiling
*c
, node
*n
)
4115 REQ(n
, lambdef
); /* lambdef: 'lambda' [varargslist] ':' test */
4116 c
->c_name
= "<lambda>";
4119 (void) com_addconst(c
, Py_None
); /* No docstring */
4120 if (TYPE(ch
) == varargslist
) {
4127 com_addbyte(c
, RETURN_VALUE
);
4132 compile_classdef(struct compiling
*c
, node
*n
)
4137 /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */
4138 c
->c_name
= STR(CHILD(n
, 1));
4139 c
->c_private
= c
->c_name
;
4140 /* Initialize local __module__ from global __name__ */
4141 com_addop_name(c
, LOAD_GLOBAL
, "__name__");
4142 com_addop_name(c
, STORE_NAME
, "__module__");
4143 ch
= CHILD(n
, NCH(n
)-1); /* The suite */
4144 doc
= get_docstring(c
, ch
);
4146 int i
= com_addconst(c
, doc
);
4148 com_addoparg(c
, LOAD_CONST
, i
);
4150 com_addop_name(c
, STORE_NAME
, "__doc__");
4154 (void) com_addconst(c
, Py_None
);
4156 com_addbyte(c
, LOAD_LOCALS
);
4158 com_addbyte(c
, RETURN_VALUE
);
4163 compile_node(struct compiling
*c
, node
*n
)
4165 com_set_lineno(c
, n
->n_lineno
);
4169 case single_input
: /* One interactive command */
4170 /* NEWLINE | simple_stmt | compound_stmt NEWLINE */
4173 if (TYPE(n
) != NEWLINE
)
4175 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
4177 com_addbyte(c
, RETURN_VALUE
);
4182 case file_input
: /* A whole file, or built-in function exec() */
4183 com_file_input(c
, n
);
4184 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
4186 com_addbyte(c
, RETURN_VALUE
);
4190 case eval_input
: /* Built-in function input() */
4191 com_node(c
, CHILD(n
, 0));
4192 com_addbyte(c
, RETURN_VALUE
);
4196 case lambdef
: /* anonymous function definition */
4197 compile_lambdef(c
, n
);
4200 case funcdef
: /* A function definition */
4201 compile_funcdef(c
, n
);
4204 case classdef
: /* A class definition */
4205 compile_classdef(c
, n
);
4209 com_error(c
, PyExc_SystemError
,
4210 "compile_node: unexpected node type");
4215 dict_keys_inorder(PyObject
*dict
, int offset
)
4217 PyObject
*tuple
, *k
, *v
;
4218 int i
, pos
= 0, size
= PyDict_Size(dict
);
4220 tuple
= PyTuple_New(size
);
4223 while (PyDict_Next(dict
, &pos
, &k
, &v
)) {
4224 i
= PyInt_AS_LONG(v
);
4226 assert((i
- offset
) < size
);
4227 PyTuple_SET_ITEM(tuple
, i
- offset
, k
);
4233 PyNode_Compile(node
*n
, const char *filename
)
4235 return PyNode_CompileFlags(n
, filename
, NULL
);
4239 PyNode_CompileFlags(node
*n
, const char *filename
, PyCompilerFlags
*flags
)
4241 return jcompile(n
, filename
, NULL
, flags
);
4245 PyNode_CompileSymtable(node
*n
, const char *filename
)
4247 struct symtable
*st
;
4248 PyFutureFeatures
*ff
;
4250 ff
= PyNode_Future(n
, filename
);
4253 st
= symtable_build(n
, ff
, filename
);
4255 PyObject_FREE((void *)ff
);
4261 static PyCodeObject
*
4262 icompile(node
*n
, struct compiling
*base
)
4264 return jcompile(n
, base
->c_filename
, base
, NULL
);
4267 static PyCodeObject
*
4268 jcompile(node
*n
, const char *filename
, struct compiling
*base
,
4269 PyCompilerFlags
*flags
)
4271 struct compiling sc
;
4273 if (!com_init(&sc
, filename
))
4275 if (flags
&& flags
->cf_flags
& PyCF_SOURCE_IS_UTF8
) {
4276 sc
.c_encoding
= "utf-8";
4277 } else if (TYPE(n
) == encoding_decl
) {
4278 sc
.c_encoding
= STR(n
);
4281 sc
.c_encoding
= NULL
;
4284 sc
.c_private
= base
->c_private
;
4285 sc
.c_symtable
= base
->c_symtable
;
4286 /* c_symtable still points to parent's symbols */
4288 || (sc
.c_symtable
->st_cur
->ste_type
== TYPE_FUNCTION
))
4290 sc
.c_flags
|= base
->c_flags
& PyCF_MASK
;
4291 if (base
->c_encoding
!= NULL
) {
4292 assert(sc
.c_encoding
== NULL
);
4293 sc
.c_encoding
= base
->c_encoding
;
4296 sc
.c_private
= NULL
;
4297 sc
.c_future
= PyNode_Future(n
, filename
);
4298 if (sc
.c_future
== NULL
) {
4303 int merged
= sc
.c_future
->ff_features
|
4305 sc
.c_future
->ff_features
= merged
;
4306 flags
->cf_flags
= merged
;
4308 sc
.c_symtable
= symtable_build(n
, sc
.c_future
, sc
.c_filename
);
4309 if (sc
.c_symtable
== NULL
) {
4313 /* reset symbol table for second pass */
4314 sc
.c_symtable
->st_nscopes
= 1;
4315 sc
.c_symtable
->st_pass
= 2;
4318 if (symtable_load_symbols(&sc
) < 0) {
4322 compile_node(&sc
, n
);
4324 if (sc
.c_errors
== 0) {
4325 PyObject
*consts
, *names
, *varnames
, *filename
, *name
,
4326 *freevars
, *cellvars
;
4327 consts
= PyList_AsTuple(sc
.c_consts
);
4328 names
= PyList_AsTuple(sc
.c_names
);
4329 varnames
= PyList_AsTuple(sc
.c_varnames
);
4330 cellvars
= dict_keys_inorder(sc
.c_cellvars
, 0);
4331 freevars
= dict_keys_inorder(sc
.c_freevars
,
4332 PyTuple_GET_SIZE(cellvars
));
4333 filename
= PyString_InternFromString(sc
.c_filename
);
4334 name
= PyString_InternFromString(sc
.c_name
);
4335 if (!PyErr_Occurred())
4336 co
= PyCode_New(sc
.c_argcount
,
4352 Py_XDECREF(varnames
);
4353 Py_XDECREF(freevars
);
4354 Py_XDECREF(cellvars
);
4355 Py_XDECREF(filename
);
4358 else if (!PyErr_Occurred()) {
4359 /* This could happen if someone called PyErr_Clear() after an
4360 error was reported above. That's not supposed to happen,
4361 but I just plugged one case and I'm not sure there can't be
4362 others. In that case, raise SystemError so that at least
4363 it gets reported instead dumping core. */
4364 PyErr_SetString(PyExc_SystemError
, "lost syntax error");
4368 PySymtable_Free(sc
.c_symtable
);
4369 sc
.c_symtable
= NULL
;
4376 PyCode_Addr2Line(PyCodeObject
*co
, int addrq
)
4378 int size
= PyString_Size(co
->co_lnotab
) / 2;
4379 unsigned char *p
= (unsigned char*)PyString_AsString(co
->co_lnotab
);
4380 int line
= co
->co_firstlineno
;
4382 while (--size
>= 0) {
4391 /* The test for LOCAL must come before the test for FREE in order to
4392 handle classes where name is both local and free. The local var is
4393 a method and the free var is a free var referenced within a method.
4397 get_ref_type(struct compiling
*c
, char *name
)
4402 if (PyDict_GetItemString(c
->c_cellvars
, name
) != NULL
)
4404 if (PyDict_GetItemString(c
->c_locals
, name
) != NULL
)
4406 if (PyDict_GetItemString(c
->c_freevars
, name
) != NULL
)
4408 v
= PyDict_GetItemString(c
->c_globals
, name
);
4411 return GLOBAL_EXPLICIT
;
4413 return GLOBAL_IMPLICIT
;
4416 PyOS_snprintf(buf
, sizeof(buf
),
4417 "unknown scope for %.100s in %.100s(%s) "
4418 "in %s\nsymbols: %s\nlocals: %s\nglobals: %s\n",
4420 PyObject_REPR(c
->c_symtable
->st_cur
->ste_id
),
4422 PyObject_REPR(c
->c_symtable
->st_cur
->ste_symbols
),
4423 PyObject_REPR(c
->c_locals
),
4424 PyObject_REPR(c
->c_globals
)
4431 /* Helper functions to issue warnings */
4434 issue_warning(const char *msg
, const char *filename
, int lineno
)
4436 if (PyErr_Occurred()) {
4437 /* This can happen because symtable_node continues
4438 processing even after raising a SyntaxError.
4439 Calling PyErr_WarnExplicit now would clobber the
4440 pending exception; instead we fail and let that
4441 exception propagate.
4445 if (PyErr_WarnExplicit(PyExc_SyntaxWarning
, msg
, filename
,
4446 lineno
, NULL
, NULL
) < 0) {
4447 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning
)) {
4448 PyErr_SetString(PyExc_SyntaxError
, msg
);
4449 PyErr_SyntaxLocation(filename
, lineno
);
4457 symtable_warn(struct symtable
*st
, char *msg
)
4459 if (issue_warning(msg
, st
->st_filename
, st
->st_cur
->ste_lineno
) < 0) {
4466 /* Helper function for setting lineno and filename */
4468 static struct symtable
*
4469 symtable_build(node
*n
, PyFutureFeatures
*ff
, const char *filename
)
4471 struct symtable
*st
;
4473 st
= symtable_init();
4477 st
->st_filename
= filename
;
4478 symtable_enter_scope(st
, TOP
, TYPE(n
), n
->n_lineno
);
4479 if (st
->st_errors
> 0)
4481 symtable_node(st
, n
);
4482 if (st
->st_errors
> 0)
4486 if (!PyErr_Occurred()) {
4487 /* This could happen because after a syntax error is
4488 detected, the symbol-table-building continues for
4489 a while, and PyErr_Clear() might erroneously be
4490 called during that process. One such case has been
4491 fixed, but there might be more (now or later).
4493 PyErr_SetString(PyExc_SystemError
, "lost exception");
4495 st
->st_future
= NULL
;
4496 st
->st_filename
= NULL
;
4497 PySymtable_Free(st
);
4502 symtable_init_compiling_symbols(struct compiling
*c
)
4506 varnames
= c
->c_symtable
->st_cur
->ste_varnames
;
4507 if (varnames
== NULL
) {
4508 varnames
= PyList_New(0);
4509 if (varnames
== NULL
)
4511 c
->c_symtable
->st_cur
->ste_varnames
= varnames
;
4512 Py_INCREF(varnames
);
4514 Py_INCREF(varnames
);
4515 c
->c_varnames
= varnames
;
4517 c
->c_globals
= PyDict_New();
4518 if (c
->c_globals
== NULL
)
4520 c
->c_freevars
= PyDict_New();
4521 if (c
->c_freevars
== NULL
)
4523 c
->c_cellvars
= PyDict_New();
4524 if (c
->c_cellvars
== NULL
)
4529 struct symbol_info
{
4537 symtable_init_info(struct symbol_info
*si
)
4542 si
->si_nimplicit
= 0;
4546 symtable_resolve_free(struct compiling
*c
, PyObject
*name
, int flags
,
4547 struct symbol_info
*si
)
4551 /* Seperate logic for DEF_FREE. If it occurs in a function,
4552 it indicates a local that we must allocate storage for (a
4553 cell var). If it occurs in a class, then the class has a
4554 method and a free variable with the same name.
4556 if (c
->c_symtable
->st_cur
->ste_type
== TYPE_FUNCTION
) {
4557 /* If it isn't declared locally, it can't be a cell. */
4558 if (!(flags
& (DEF_LOCAL
| DEF_PARAM
)))
4560 v
= PyInt_FromLong(si
->si_ncells
++);
4561 dict
= c
->c_cellvars
;
4563 /* If it is free anyway, then there is no need to do
4566 if (is_free(flags
^ DEF_FREE_CLASS
)
4567 || (flags
== DEF_FREE_CLASS
))
4569 v
= PyInt_FromLong(si
->si_nfrees
++);
4570 dict
= c
->c_freevars
;
4574 if (PyDict_SetItem(dict
, name
, v
) < 0) {
4582 /* If a variable is a cell and an argument, make sure that appears in
4583 co_cellvars before any variable to its right in varnames.
4588 symtable_cellvar_offsets(PyObject
**cellvars
, int argcount
,
4589 PyObject
*varnames
, int flags
)
4592 PyObject
*w
, *d
, *list
= NULL
;
4595 if (flags
& CO_VARARGS
)
4597 if (flags
& CO_VARKEYWORDS
)
4599 for (i
= argcount
; --i
>= 0; ) {
4600 v
= PyList_GET_ITEM(varnames
, i
);
4601 if (PyDict_GetItem(*cellvars
, v
)) {
4603 list
= PyList_New(1);
4606 PyList_SET_ITEM(list
, 0, v
);
4609 if (PyList_Insert(list
, 0, v
) < 0) {
4619 /* There are cellvars that are also arguments. Create a dict
4620 to replace cellvars and put the args at the front.
4625 for (i
= PyList_GET_SIZE(list
); --i
>= 0; ) {
4626 v
= PyInt_FromLong(i
);
4629 if (PyDict_SetItem(d
, PyList_GET_ITEM(list
, i
), v
) < 0)
4631 if (PyDict_DelItem(*cellvars
, PyList_GET_ITEM(list
, i
)) < 0)
4636 i
= PyList_GET_SIZE(list
);
4638 while (PyDict_Next(*cellvars
, &pos
, &v
, &w
)) {
4639 w
= PyInt_FromLong(i
++); /* don't care about the old key */
4642 if (PyDict_SetItem(d
, v
, w
) < 0) {
4649 Py_DECREF(*cellvars
);
4659 symtable_freevar_offsets(PyObject
*freevars
, int offset
)
4664 /* The cell vars are the first elements of the closure,
4665 followed by the free vars. Update the offsets in
4666 c_freevars to account for number of cellvars. */
4668 while (PyDict_Next(freevars
, &pos
, &name
, &v
)) {
4669 int i
= PyInt_AS_LONG(v
) + offset
;
4670 PyObject
*o
= PyInt_FromLong(i
);
4673 if (PyDict_SetItem(freevars
, name
, o
) < 0) {
4683 symtable_check_unoptimized(struct compiling
*c
,
4684 PySymtableEntryObject
*ste
,
4685 struct symbol_info
*si
)
4689 if (!(si
->si_ncells
|| si
->si_nfrees
|| ste
->ste_child_free
4690 || (ste
->ste_nested
&& si
->si_nimplicit
)))
4693 #define ILLEGAL_CONTAINS "contains a nested function with free variables"
4695 #define ILLEGAL_IS "is a nested function"
4697 #define ILLEGAL_IMPORT_STAR \
4698 "import * is not allowed in function '%.100s' because it %s"
4700 #define ILLEGAL_BARE_EXEC \
4701 "unqualified exec is not allowed in function '%.100s' it %s"
4703 #define ILLEGAL_EXEC_AND_IMPORT_STAR \
4704 "function '%.100s' uses import * and bare exec, which are illegal " \
4707 /* XXX perhaps the linenos for these opt-breaking statements
4708 should be stored so the exception can point to them. */
4710 if (ste
->ste_child_free
) {
4711 if (ste
->ste_optimized
== OPT_IMPORT_STAR
)
4712 PyOS_snprintf(buf
, sizeof(buf
),
4713 ILLEGAL_IMPORT_STAR
,
4714 PyString_AS_STRING(ste
->ste_name
),
4716 else if (ste
->ste_optimized
== (OPT_BARE_EXEC
| OPT_EXEC
))
4717 PyOS_snprintf(buf
, sizeof(buf
),
4719 PyString_AS_STRING(ste
->ste_name
),
4722 PyOS_snprintf(buf
, sizeof(buf
),
4723 ILLEGAL_EXEC_AND_IMPORT_STAR
,
4724 PyString_AS_STRING(ste
->ste_name
),
4728 if (ste
->ste_optimized
== OPT_IMPORT_STAR
)
4729 PyOS_snprintf(buf
, sizeof(buf
),
4730 ILLEGAL_IMPORT_STAR
,
4731 PyString_AS_STRING(ste
->ste_name
),
4733 else if (ste
->ste_optimized
== (OPT_BARE_EXEC
| OPT_EXEC
))
4734 PyOS_snprintf(buf
, sizeof(buf
),
4736 PyString_AS_STRING(ste
->ste_name
),
4739 PyOS_snprintf(buf
, sizeof(buf
),
4740 ILLEGAL_EXEC_AND_IMPORT_STAR
,
4741 PyString_AS_STRING(ste
->ste_name
),
4746 PyErr_SetString(PyExc_SyntaxError
, buf
);
4747 PyErr_SyntaxLocation(c
->c_symtable
->st_filename
,
4748 ste
->ste_opt_lineno
);
4753 symtable_update_flags(struct compiling
*c
, PySymtableEntryObject
*ste
,
4754 struct symbol_info
*si
)
4757 c
->c_flags
|= c
->c_future
->ff_features
;
4758 if (ste
->ste_generator
)
4759 c
->c_flags
|= CO_GENERATOR
;
4760 if (ste
->ste_type
!= TYPE_MODULE
)
4761 c
->c_flags
|= CO_NEWLOCALS
;
4762 if (ste
->ste_type
== TYPE_FUNCTION
) {
4763 c
->c_nlocals
= si
->si_nlocals
;
4764 if (ste
->ste_optimized
== 0)
4765 c
->c_flags
|= CO_OPTIMIZED
;
4766 else if (ste
->ste_optimized
!= OPT_EXEC
)
4767 return symtable_check_unoptimized(c
, ste
, si
);
4773 symtable_error(struct symtable
*st
, int lineno
)
4776 lineno
= st
->st_cur
->ste_lineno
;
4777 PyErr_SyntaxLocation(st
->st_filename
, lineno
);
4783 symtable_load_symbols(struct compiling
*c
)
4785 struct symtable
*st
= c
->c_symtable
;
4786 PySymtableEntryObject
*ste
= st
->st_cur
;
4787 PyObject
*name
, *varnames
, *v
;
4789 struct symbol_info si
;
4793 if (symtable_init_compiling_symbols(c
) < 0)
4795 symtable_init_info(&si
);
4796 varnames
= st
->st_cur
->ste_varnames
;
4797 si
.si_nlocals
= PyList_GET_SIZE(varnames
);
4798 c
->c_argcount
= si
.si_nlocals
;
4800 for (i
= 0; i
< si
.si_nlocals
; ++i
) {
4801 v
= PyInt_FromLong(i
);
4804 if (PyDict_SetItem(c
->c_locals
,
4805 PyList_GET_ITEM(varnames
, i
), v
) < 0)
4810 /* XXX The cases below define the rules for whether a name is
4811 local or global. The logic could probably be clearer. */
4813 while (PyDict_Next(ste
->ste_symbols
, &pos
, &name
, &v
)) {
4814 flags
= PyInt_AS_LONG(v
);
4816 if (flags
& DEF_FREE_GLOBAL
)
4817 /* undo the original DEF_FREE */
4818 flags
&= ~(DEF_FREE
| DEF_FREE_CLASS
);
4820 /* Deal with names that need two actions:
4821 1. Cell variables that are also locals.
4822 2. Free variables in methods that are also class
4823 variables or declared global.
4825 if (flags
& (DEF_FREE
| DEF_FREE_CLASS
))
4826 symtable_resolve_free(c
, name
, flags
, &si
);
4828 if (flags
& DEF_STAR
) {
4830 c
->c_flags
|= CO_VARARGS
;
4831 } else if (flags
& DEF_DOUBLESTAR
) {
4833 c
->c_flags
|= CO_VARKEYWORDS
;
4834 } else if (flags
& DEF_INTUPLE
)
4836 else if (flags
& DEF_GLOBAL
) {
4837 if (flags
& DEF_PARAM
) {
4838 PyErr_Format(PyExc_SyntaxError
, LOCAL_GLOBAL
,
4839 PyString_AS_STRING(name
));
4840 symtable_error(st
, 0);
4843 if (PyDict_SetItem(c
->c_globals
, name
, Py_None
) < 0)
4845 } else if (flags
& DEF_FREE_GLOBAL
) {
4847 if (PyDict_SetItem(c
->c_globals
, name
, Py_True
) < 0)
4849 } else if ((flags
& DEF_LOCAL
) && !(flags
& DEF_PARAM
)) {
4850 v
= PyInt_FromLong(si
.si_nlocals
++);
4853 if (PyDict_SetItem(c
->c_locals
, name
, v
) < 0)
4856 if (ste
->ste_type
!= TYPE_CLASS
)
4857 if (PyList_Append(c
->c_varnames
, name
) < 0)
4859 } else if (is_free(flags
)) {
4860 if (ste
->ste_nested
) {
4861 v
= PyInt_FromLong(si
.si_nfrees
++);
4864 if (PyDict_SetItem(c
->c_freevars
, name
, v
) < 0)
4869 if (PyDict_SetItem(c
->c_globals
, name
,
4872 if (st
->st_nscopes
!= 1) {
4873 v
= PyInt_FromLong(flags
);
4876 if (PyDict_SetItem(st
->st_global
,
4885 assert(PyDict_Size(c
->c_freevars
) == si
.si_nfrees
);
4887 if (si
.si_ncells
> 1) { /* one cell is always in order */
4888 if (symtable_cellvar_offsets(&c
->c_cellvars
, c
->c_argcount
,
4889 c
->c_varnames
, c
->c_flags
) < 0)
4892 if (symtable_freevar_offsets(c
->c_freevars
, si
.si_ncells
) < 0)
4894 return symtable_update_flags(c
, ste
, &si
);
4896 /* is this always the right thing to do? */
4901 static struct symtable
*
4904 struct symtable
*st
;
4906 st
= (struct symtable
*)PyObject_MALLOC(sizeof(struct symtable
));
4911 st
->st_filename
= NULL
;
4912 st
->st_symbols
= NULL
;
4913 if ((st
->st_stack
= PyList_New(0)) == NULL
)
4915 if ((st
->st_symbols
= PyDict_New()) == NULL
)
4920 st
->st_private
= NULL
;
4923 PySymtable_Free(st
);
4928 PySymtable_Free(struct symtable
*st
)
4930 Py_XDECREF(st
->st_symbols
);
4931 Py_XDECREF(st
->st_stack
);
4932 Py_XDECREF(st
->st_cur
);
4933 PyObject_FREE((void *)st
);
4936 /* When the compiler exits a scope, it must should update the scope's
4937 free variable information with the list of free variables in its
4940 Variables that are free in children and defined in the current
4943 If the scope being exited is defined at the top-level (ste_nested is
4944 false), free variables in children that are not defined here are
4950 symtable_update_free_vars(struct symtable
*st
)
4953 PyObject
*o
, *name
, *list
= NULL
;
4954 PySymtableEntryObject
*child
, *ste
= st
->st_cur
;
4956 if (ste
->ste_type
== TYPE_CLASS
)
4957 def
= DEF_FREE_CLASS
;
4960 for (i
= 0; i
< PyList_GET_SIZE(ste
->ste_children
); ++i
) {
4963 if (list
&& PyList_SetSlice(list
, 0,
4964 PyList_GET_SIZE(list
), 0) < 0)
4966 child
= (PySymtableEntryObject
*)
4967 PyList_GET_ITEM(ste
->ste_children
, i
);
4968 while (PyDict_Next(child
->ste_symbols
, &pos
, &name
, &o
)) {
4969 int flags
= PyInt_AS_LONG(o
);
4970 if (!(is_free(flags
)))
4971 continue; /* avoids indentation */
4973 list
= PyList_New(0);
4977 ste
->ste_child_free
= 1;
4978 if (PyList_Append(list
, name
) < 0) {
4983 for (j
= 0; list
&& j
< PyList_GET_SIZE(list
); j
++) {
4985 name
= PyList_GET_ITEM(list
, j
);
4986 v
= PyDict_GetItem(ste
->ste_symbols
, name
);
4987 /* If a name N is declared global in scope A and
4988 referenced in scope B contained (perhaps
4989 indirectly) in A and there are no scopes
4990 with bindings for N between B and A, then N
4991 is global in B. Unless A is a class scope,
4992 because class scopes are not considered for
4995 if (v
&& (ste
->ste_type
!= TYPE_CLASS
)) {
4996 int flags
= PyInt_AS_LONG(v
);
4997 if (flags
& DEF_GLOBAL
) {
4998 symtable_undo_free(st
, child
->ste_id
,
5003 if (ste
->ste_nested
) {
5004 if (symtable_add_def_o(st
, ste
->ste_symbols
,
5010 if (symtable_check_global(st
, child
->ste_id
,
5023 /* If the current scope is a non-nested class or if name is not
5024 defined in the current, non-nested scope, then it is an implicit
5025 global in all nested scopes.
5029 symtable_check_global(struct symtable
*st
, PyObject
*child
, PyObject
*name
)
5033 PySymtableEntryObject
*ste
= st
->st_cur
;
5035 if (ste
->ste_type
== TYPE_CLASS
)
5036 return symtable_undo_free(st
, child
, name
);
5037 o
= PyDict_GetItem(ste
->ste_symbols
, name
);
5039 return symtable_undo_free(st
, child
, name
);
5040 v
= PyInt_AS_LONG(o
);
5042 if (is_free(v
) || (v
& DEF_GLOBAL
))
5043 return symtable_undo_free(st
, child
, name
);
5045 return symtable_add_def_o(st
, ste
->ste_symbols
,
5050 symtable_undo_free(struct symtable
*st
, PyObject
*id
,
5055 PySymtableEntryObject
*ste
;
5057 ste
= (PySymtableEntryObject
*)PyDict_GetItem(st
->st_symbols
, id
);
5061 info
= PyDict_GetItem(ste
->ste_symbols
, name
);
5064 v
= PyInt_AS_LONG(info
);
5066 if (symtable_add_def_o(st
, ste
->ste_symbols
, name
,
5067 DEF_FREE_GLOBAL
) < 0)
5070 /* If the name is defined here or declared global,
5071 then the recursion stops. */
5074 for (i
= 0; i
< PyList_GET_SIZE(ste
->ste_children
); ++i
) {
5075 PySymtableEntryObject
*child
;
5076 child
= (PySymtableEntryObject
*)
5077 PyList_GET_ITEM(ste
->ste_children
, i
);
5078 x
= symtable_undo_free(st
, child
->ste_id
, name
);
5085 /* symtable_enter_scope() gets a reference via PySymtableEntry_New().
5086 This reference is released when the scope is exited, via the DECREF
5087 in symtable_exit_scope().
5091 symtable_exit_scope(struct symtable
*st
)
5095 if (st
->st_pass
== 1)
5096 symtable_update_free_vars(st
);
5097 Py_DECREF(st
->st_cur
);
5098 end
= PyList_GET_SIZE(st
->st_stack
) - 1;
5099 st
->st_cur
= (PySymtableEntryObject
*)PyList_GET_ITEM(st
->st_stack
,
5101 if (PySequence_DelItem(st
->st_stack
, end
) < 0)
5107 symtable_enter_scope(struct symtable
*st
, char *name
, int type
,
5110 PySymtableEntryObject
*prev
= NULL
;
5114 if (PyList_Append(st
->st_stack
, (PyObject
*)st
->st_cur
) < 0) {
5119 st
->st_cur
= (PySymtableEntryObject
*)
5120 PySymtableEntry_New(st
, name
, type
, lineno
);
5121 if (st
->st_cur
== NULL
) {
5125 if (strcmp(name
, TOP
) == 0)
5126 st
->st_global
= st
->st_cur
->ste_symbols
;
5127 if (prev
&& st
->st_pass
== 1) {
5128 if (PyList_Append(prev
->ste_children
,
5129 (PyObject
*)st
->st_cur
) < 0)
5135 symtable_lookup(struct symtable
*st
, char *name
)
5137 char buffer
[MANGLE_LEN
];
5141 if (_Py_Mangle(st
->st_private
, name
, buffer
, sizeof(buffer
)))
5143 v
= PyDict_GetItemString(st
->st_cur
->ste_symbols
, name
);
5145 if (PyErr_Occurred())
5151 flags
= PyInt_AS_LONG(v
);
5156 symtable_add_def(struct symtable
*st
, char *name
, int flag
)
5159 char buffer
[MANGLE_LEN
];
5162 /* Warn about None, except inside a tuple (where the assignment
5163 code already issues a warning). */
5164 if ((flag
& DEF_PARAM
) && !(flag
& DEF_INTUPLE
) &&
5165 *name
== 'N' && strcmp(name
, "None") == 0)
5167 if (symtable_warn(st
, "argument named None"))
5170 if (_Py_Mangle(st
->st_private
, name
, buffer
, sizeof(buffer
)))
5172 if ((s
= PyString_InternFromString(name
)) == NULL
)
5174 ret
= symtable_add_def_o(st
, st
->st_cur
->ste_symbols
, s
, flag
);
5179 /* Must only be called with mangled names */
5182 symtable_add_def_o(struct symtable
*st
, PyObject
*dict
,
5183 PyObject
*name
, int flag
)
5188 if ((o
= PyDict_GetItem(dict
, name
))) {
5189 val
= PyInt_AS_LONG(o
);
5190 if ((flag
& DEF_PARAM
) && (val
& DEF_PARAM
)) {
5191 PyErr_Format(PyExc_SyntaxError
, DUPLICATE_ARGUMENT
,
5192 PyString_AsString(name
));
5193 return symtable_error(st
, 0);
5198 o
= PyInt_FromLong(val
);
5201 if (PyDict_SetItem(dict
, name
, o
) < 0) {
5207 if (flag
& DEF_PARAM
) {
5208 if (PyList_Append(st
->st_cur
->ste_varnames
, name
) < 0)
5210 } else if (flag
& DEF_GLOBAL
) {
5211 /* XXX need to update DEF_GLOBAL for other flags too;
5212 perhaps only DEF_FREE_GLOBAL */
5213 if ((o
= PyDict_GetItem(st
->st_global
, name
))) {
5214 val
= PyInt_AS_LONG(o
);
5218 o
= PyInt_FromLong(val
);
5221 if (PyDict_SetItem(st
->st_global
, name
, o
) < 0) {
5230 #define symtable_add_use(ST, NAME) symtable_add_def((ST), (NAME), USE)
5232 /* Look for a yield stmt under n. Return 1 if found, else 0.
5233 This hack is used to look inside "if 0:" blocks (which are normally
5234 ignored) in case those are the only places a yield occurs (so that this
5235 function is a generator). */
5237 look_for_yield(node
*n
)
5241 for (i
= 0; i
< NCH(n
); ++i
) {
5242 node
*kid
= CHILD(n
, i
);
5244 switch (TYPE(kid
)) {
5249 /* Stuff in nested functions and classes can't make
5250 the parent a generator. */
5257 if (look_for_yield(kid
))
5265 symtable_node(struct symtable
*st
, node
*n
)
5272 char *func_name
= STR(CHILD(n
, 1));
5273 symtable_add_def(st
, func_name
, DEF_LOCAL
);
5274 symtable_default_args(st
, CHILD(n
, 2));
5275 symtable_enter_scope(st
, func_name
, TYPE(n
), n
->n_lineno
);
5276 symtable_funcdef(st
, n
);
5277 symtable_exit_scope(st
);
5282 symtable_default_args(st
, CHILD(n
, 1));
5283 symtable_enter_scope(st
, "lambda", TYPE(n
), n
->n_lineno
);
5284 symtable_funcdef(st
, n
);
5285 symtable_exit_scope(st
);
5288 char *tmp
, *class_name
= STR(CHILD(n
, 1));
5289 symtable_add_def(st
, class_name
, DEF_LOCAL
);
5290 if (TYPE(CHILD(n
, 2)) == LPAR
) {
5291 node
*bases
= CHILD(n
, 3);
5293 for (i
= 0; i
< NCH(bases
); i
+= 2) {
5294 symtable_node(st
, CHILD(bases
, i
));
5297 symtable_enter_scope(st
, class_name
, TYPE(n
), n
->n_lineno
);
5298 tmp
= st
->st_private
;
5299 st
->st_private
= class_name
;
5300 symtable_node(st
, CHILD(n
, NCH(n
) - 1));
5301 st
->st_private
= tmp
;
5302 symtable_exit_scope(st
);
5306 for (i
= 0; i
+ 3 < NCH(n
); i
+= 4) {
5307 if (is_constant_false(NULL
, (CHILD(n
, i
+ 1)))) {
5308 if (st
->st_cur
->ste_generator
== 0)
5309 st
->st_cur
->ste_generator
=
5310 look_for_yield(CHILD(n
, i
+3));
5313 symtable_node(st
, CHILD(n
, i
+ 1));
5314 symtable_node(st
, CHILD(n
, i
+ 3));
5317 symtable_node(st
, CHILD(n
, i
+ 2));
5320 symtable_global(st
, n
);
5323 symtable_import(st
, n
);
5326 st
->st_cur
->ste_optimized
|= OPT_EXEC
;
5327 symtable_node(st
, CHILD(n
, 1));
5329 symtable_node(st
, CHILD(n
, 3));
5331 st
->st_cur
->ste_optimized
|= OPT_BARE_EXEC
;
5332 st
->st_cur
->ste_opt_lineno
= n
->n_lineno
;
5335 symtable_node(st
, CHILD(n
, 5));
5340 if (Py_OptimizeFlag
)
5346 symtable_node(st
, CHILD(n
, 1));
5352 symtable_assign(st
, CHILD(n
, 3), 0);
5359 symtable_assign(st
, CHILD(n
, 1), 0);
5362 st
->st_cur
->ste_generator
= 1;
5369 if (TYPE(CHILD(n
, 1)) == augassign
) {
5370 symtable_assign(st
, CHILD(n
, 0), 0);
5371 symtable_node(st
, CHILD(n
, 2));
5375 for (i
= 0; i
< NCH(n
) - 2; i
+= 2)
5376 symtable_assign(st
, CHILD(n
, i
), 0);
5377 n
= CHILD(n
, NCH(n
) - 1);
5382 /* only occurs when there are multiple for loops
5383 in a list comprehension */
5385 if (TYPE(n
) == list_for
)
5386 symtable_list_for(st
, n
);
5389 symtable_node(st
, CHILD(n
, 1));
5397 symtable_assign(st
, CHILD(n
, 1), 0);
5398 for (i
= 3; i
< NCH(n
); ++i
)
5399 if (TYPE(CHILD(n
, i
)) >= single_input
)
5400 symtable_node(st
, CHILD(n
, i
));
5402 /* The remaining cases fall through to default except in
5403 special circumstances. This requires the individual cases
5404 to be coded with great care, even though they look like
5405 rather innocuous. Each case must double-check TYPE(n).
5408 if (TYPE(n
) == argument
&& NCH(n
) == 3) {
5414 if (NCH(n
) > 1 && TYPE(CHILD(n
, 1)) == list_for
) {
5415 symtable_list_comprehension(st
, n
);
5420 if (TYPE(n
) == atom
&& TYPE(CHILD(n
, 0)) == NAME
) {
5421 symtable_add_use(st
, STR(CHILD(n
, 0)));
5426 /* Walk over every non-token child with a special case
5433 for (i
= 0; i
< NCH(n
); ++i
)
5434 if (TYPE(CHILD(n
, i
)) >= single_input
)
5435 symtable_node(st
, CHILD(n
, i
));
5440 symtable_funcdef(struct symtable
*st
, node
*n
)
5444 if (TYPE(n
) == lambdef
) {
5446 symtable_params(st
, CHILD(n
, 1));
5448 symtable_params(st
, CHILD(n
, 2));
5449 body
= CHILD(n
, NCH(n
) - 1);
5450 symtable_node(st
, body
);
5453 /* The next two functions parse the argument tuple.
5454 symtable_default_args() checks for names in the default arguments,
5455 which are references in the defining scope. symtable_params()
5456 parses the parameter names, which are defined in the function's
5460 (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] | '**' NAME)
5461 | fpdef ['=' test] (',' fpdef ['=' test])* [',']
5465 symtable_default_args(struct symtable
*st
, node
*n
)
5470 if (TYPE(n
) == parameters
) {
5472 if (TYPE(n
) == RPAR
)
5475 REQ(n
, varargslist
);
5476 for (i
= 0; i
< NCH(n
); i
+= 2) {
5478 if (TYPE(c
) == STAR
|| TYPE(c
) == DOUBLESTAR
) {
5481 if (i
> 0 && (TYPE(CHILD(n
, i
- 1)) == EQUAL
))
5482 symtable_node(st
, CHILD(n
, i
));
5487 symtable_params(struct symtable
*st
, node
*n
)
5489 int i
, complex = -1, ext
= 0;
5492 if (TYPE(n
) == parameters
) {
5494 if (TYPE(n
) == RPAR
)
5497 REQ(n
, varargslist
);
5498 for (i
= 0; i
< NCH(n
); i
+= 2) {
5500 if (TYPE(c
) == STAR
|| TYPE(c
) == DOUBLESTAR
) {
5504 if (TYPE(c
) == test
) {
5507 if (TYPE(CHILD(c
, 0)) == NAME
)
5508 symtable_add_def(st
, STR(CHILD(c
, 0)), DEF_PARAM
);
5511 PyOS_snprintf(nbuf
, sizeof(nbuf
), ".%d", i
);
5512 symtable_add_def(st
, nbuf
, DEF_PARAM
);
5518 if (TYPE(c
) == STAR
) {
5520 symtable_add_def(st
, STR(CHILD(n
, i
)),
5521 DEF_PARAM
| DEF_STAR
);
5528 if (c
&& TYPE(c
) == DOUBLESTAR
) {
5530 symtable_add_def(st
, STR(CHILD(n
, i
)),
5531 DEF_PARAM
| DEF_DOUBLESTAR
);
5536 for (j
= 0; j
<= complex; j
++) {
5538 if (TYPE(c
) == COMMA
)
5540 else if (TYPE(c
) == EQUAL
)
5541 c
= CHILD(n
, j
+= 3);
5542 if (TYPE(CHILD(c
, 0)) == LPAR
)
5543 symtable_params_fplist(st
, CHILD(c
, 1));
5549 symtable_params_fplist(struct symtable
*st
, node
*n
)
5555 for (i
= 0; i
< NCH(n
); i
+= 2) {
5559 symtable_add_def(st
, STR(CHILD(c
, 0)),
5560 DEF_PARAM
| DEF_INTUPLE
);
5562 symtable_params_fplist(st
, CHILD(c
, 1));
5568 symtable_global(struct symtable
*st
, node
*n
)
5572 /* XXX It might be helpful to warn about module-level global
5573 statements, but it's hard to tell the difference between
5574 module-level and a string passed to exec.
5577 for (i
= 1; i
< NCH(n
); i
+= 2) {
5578 char *name
= STR(CHILD(n
, i
));
5581 flags
= symtable_lookup(st
, name
);
5584 if (flags
&& flags
!= DEF_GLOBAL
) {
5586 if (flags
& DEF_PARAM
) {
5587 PyErr_Format(PyExc_SyntaxError
,
5588 "name '%.400s' is local and global",
5590 symtable_error(st
, 0);
5594 if (flags
& DEF_LOCAL
)
5595 PyOS_snprintf(buf
, sizeof(buf
),
5596 GLOBAL_AFTER_ASSIGN
,
5599 PyOS_snprintf(buf
, sizeof(buf
),
5600 GLOBAL_AFTER_USE
, name
);
5601 symtable_warn(st
, buf
);
5604 symtable_add_def(st
, name
, DEF_GLOBAL
);
5609 symtable_list_comprehension(struct symtable
*st
, node
*n
)
5611 /* listmaker: test list_for */
5615 PyOS_snprintf(tmpname
, sizeof(tmpname
), "_[%d]",
5616 ++st
->st_cur
->ste_tmpname
);
5617 symtable_add_def(st
, tmpname
, DEF_LOCAL
);
5618 symtable_list_for(st
, CHILD(n
, 1));
5619 symtable_node(st
, CHILD(n
, 0));
5620 --st
->st_cur
->ste_tmpname
;
5624 symtable_list_for(struct symtable
*st
, node
*n
)
5627 /* list_for: for v in expr [list_iter] */
5628 symtable_assign(st
, CHILD(n
, 1), 0);
5629 symtable_node(st
, CHILD(n
, 3));
5631 symtable_node(st
, CHILD(n
, 4));
5635 symtable_import(struct symtable
*st
, node
*n
)
5638 /* import_stmt: 'import' dotted_as_name (',' dotted_as_name)*
5639 | 'from' dotted_name 'import'
5640 ('*' | import_as_name (',' import_as_name)*)
5641 import_as_name: NAME [NAME NAME]
5643 if (STR(CHILD(n
, 0))[0] == 'f') { /* from */
5644 node
*dotname
= CHILD(n
, 1);
5645 if (strcmp(STR(CHILD(dotname
, 0)), "__future__") == 0) {
5646 /* check for bogus imports */
5647 if (n
->n_lineno
>= st
->st_future
->ff_last_lineno
) {
5648 PyErr_SetString(PyExc_SyntaxError
,
5650 symtable_error(st
, n
->n_lineno
);
5654 if (TYPE(CHILD(n
, 3)) == STAR
) {
5655 if (st
->st_cur
->ste_type
!= TYPE_MODULE
) {
5656 if (symtable_warn(st
,
5657 "import * only allowed at module level") < 0)
5660 st
->st_cur
->ste_optimized
|= OPT_IMPORT_STAR
;
5661 st
->st_cur
->ste_opt_lineno
= n
->n_lineno
;
5663 for (i
= 3; i
< NCH(n
); i
+= 2) {
5664 node
*c
= CHILD(n
, i
);
5665 if (NCH(c
) > 1) /* import as */
5666 symtable_assign(st
, CHILD(c
, 2),
5669 symtable_assign(st
, CHILD(c
, 0),
5674 for (i
= 1; i
< NCH(n
); i
+= 2) {
5675 symtable_assign(st
, CHILD(n
, i
), DEF_IMPORT
);
5680 /* The third argument to symatble_assign() is a flag to be passed to
5681 symtable_add_def() if it is eventually called. The flag is useful
5682 to specify the particular type of assignment that should be
5683 recorded, e.g. an assignment caused by import.
5687 symtable_assign(struct symtable
*st
, node
*n
, int def_flag
)
5695 /* invalid assignment, e.g. lambda x:x=2. The next
5696 pass will catch this error. */
5700 for (i
= 2; i
< NCH(n
); ++i
)
5701 if (TYPE(CHILD(n
, i
)) != DOUBLESTAR
)
5702 symtable_node(st
, CHILD(n
, i
));
5705 symtable_node(st
, CHILD(n
, 0));
5706 symtable_node(st
, CHILD(n
, 1));
5713 if (NCH(n
) > 1 && TYPE(CHILD(n
, 1)) == list_for
) {
5714 /* XXX This is an error, but the next pass
5718 for (i
= 0; i
< NCH(n
); i
+= 2)
5719 symtable_assign(st
, CHILD(n
, i
), def_flag
);
5731 for (i
= 0; i
< NCH(n
); i
+= 2)
5732 symtable_assign(st
, CHILD(n
, i
), def_flag
);
5737 if (TYPE(tmp
) == LPAR
|| TYPE(tmp
) == LSQB
) {
5740 } else if (TYPE(tmp
) == NAME
) {
5741 if (strcmp(STR(tmp
), "__debug__") == 0) {
5742 PyErr_SetString(PyExc_SyntaxError
,
5744 symtable_error(st
, n
->n_lineno
);
5747 symtable_add_def(st
, STR(tmp
), DEF_LOCAL
| def_flag
);
5750 case dotted_as_name
:
5752 symtable_add_def(st
, STR(CHILD(n
, 2)),
5753 DEF_LOCAL
| def_flag
);
5755 symtable_add_def(st
,
5758 DEF_LOCAL
| def_flag
);
5761 symtable_add_def(st
, STR(CHILD(n
, 0)), DEF_LOCAL
| def_flag
);
5764 symtable_add_def(st
, STR(n
), DEF_LOCAL
| def_flag
);
5773 /* Should only occur for errors like x + 1 = 1,
5774 which will be caught in the next pass. */
5775 for (i
= 0; i
< NCH(n
); ++i
)
5776 if (TYPE(CHILD(n
, i
)) >= single_input
)
5777 symtable_assign(st
, CHILD(n
, i
), def_flag
);