issue1597011: Fix for bz2 module corner-case error due to error checking bug.
[python.git] / Python / symtable.c
blob1e1279a52cfa7afc5bc09f2cb9d7a8a29a8d74f5
1 #include "Python.h"
2 #include "Python-ast.h"
3 #include "code.h"
4 #include "symtable.h"
5 #include "structmember.h"
7 /* error strings used for warnings */
8 #define GLOBAL_AFTER_ASSIGN \
9 "name '%.400s' is assigned to before global declaration"
11 #define GLOBAL_AFTER_USE \
12 "name '%.400s' is used prior to global declaration"
14 #define IMPORT_STAR_WARNING "import * only allowed at module level"
16 #define RETURN_VAL_IN_GENERATOR \
17 "'return' with argument inside generator"
19 /* XXX(nnorwitz): change name since static? */
20 static PySTEntryObject *
21 PySTEntry_New(struct symtable *st, identifier name, _Py_block_ty block,
22 void *key, int lineno)
24 PySTEntryObject *ste = NULL;
25 PyObject *k;
27 k = PyLong_FromVoidPtr(key);
28 if (k == NULL)
29 goto fail;
30 ste = (PySTEntryObject *)PyObject_New(PySTEntryObject,
31 &PySTEntry_Type);
32 ste->ste_table = st;
33 ste->ste_id = k;
34 ste->ste_tmpname = 0;
36 ste->ste_name = name;
37 Py_INCREF(name);
39 ste->ste_symbols = NULL;
40 ste->ste_varnames = NULL;
41 ste->ste_children = NULL;
43 ste->ste_symbols = PyDict_New();
44 if (ste->ste_symbols == NULL)
45 goto fail;
47 ste->ste_varnames = PyList_New(0);
48 if (ste->ste_varnames == NULL)
49 goto fail;
51 ste->ste_children = PyList_New(0);
52 if (ste->ste_children == NULL)
53 goto fail;
55 ste->ste_type = block;
56 ste->ste_unoptimized = 0;
57 ste->ste_nested = 0;
58 ste->ste_free = 0;
59 ste->ste_varargs = 0;
60 ste->ste_varkeywords = 0;
61 ste->ste_opt_lineno = 0;
62 ste->ste_tmpname = 0;
63 ste->ste_lineno = lineno;
65 if (st->st_cur != NULL &&
66 (st->st_cur->ste_nested ||
67 st->st_cur->ste_type == FunctionBlock))
68 ste->ste_nested = 1;
69 ste->ste_child_free = 0;
70 ste->ste_generator = 0;
71 ste->ste_returns_value = 0;
73 if (PyDict_SetItem(st->st_symbols, ste->ste_id, (PyObject *)ste) < 0)
74 goto fail;
76 return ste;
77 fail:
78 Py_XDECREF(ste);
79 return NULL;
82 static PyObject *
83 ste_repr(PySTEntryObject *ste)
85 char buf[256];
87 PyOS_snprintf(buf, sizeof(buf),
88 "<symtable entry %.100s(%ld), line %d>",
89 PyString_AS_STRING(ste->ste_name),
90 PyInt_AS_LONG(ste->ste_id), ste->ste_lineno);
91 return PyString_FromString(buf);
94 static void
95 ste_dealloc(PySTEntryObject *ste)
97 ste->ste_table = NULL;
98 Py_XDECREF(ste->ste_id);
99 Py_XDECREF(ste->ste_name);
100 Py_XDECREF(ste->ste_symbols);
101 Py_XDECREF(ste->ste_varnames);
102 Py_XDECREF(ste->ste_children);
103 PyObject_Del(ste);
106 #define OFF(x) offsetof(PySTEntryObject, x)
108 static PyMemberDef ste_memberlist[] = {
109 {"id", T_OBJECT, OFF(ste_id), READONLY},
110 {"name", T_OBJECT, OFF(ste_name), READONLY},
111 {"symbols", T_OBJECT, OFF(ste_symbols), READONLY},
112 {"varnames", T_OBJECT, OFF(ste_varnames), READONLY},
113 {"children", T_OBJECT, OFF(ste_children), READONLY},
114 {"type", T_INT, OFF(ste_type), READONLY},
115 {"lineno", T_INT, OFF(ste_lineno), READONLY},
116 {NULL}
119 PyTypeObject PySTEntry_Type = {
120 PyVarObject_HEAD_INIT(&PyType_Type, 0)
121 "symtable entry",
122 sizeof(PySTEntryObject),
124 (destructor)ste_dealloc, /* tp_dealloc */
125 0, /* tp_print */
126 0, /* tp_getattr */
127 0, /* tp_setattr */
128 0, /* tp_compare */
129 (reprfunc)ste_repr, /* tp_repr */
130 0, /* tp_as_number */
131 0, /* tp_as_sequence */
132 0, /* tp_as_mapping */
133 0, /* tp_hash */
134 0, /* tp_call */
135 0, /* tp_str */
136 PyObject_GenericGetAttr, /* tp_getattro */
137 0, /* tp_setattro */
138 0, /* tp_as_buffer */
139 Py_TPFLAGS_DEFAULT, /* tp_flags */
140 0, /* tp_doc */
141 0, /* tp_traverse */
142 0, /* tp_clear */
143 0, /* tp_richcompare */
144 0, /* tp_weaklistoffset */
145 0, /* tp_iter */
146 0, /* tp_iternext */
147 0, /* tp_methods */
148 ste_memberlist, /* tp_members */
149 0, /* tp_getset */
150 0, /* tp_base */
151 0, /* tp_dict */
152 0, /* tp_descr_get */
153 0, /* tp_descr_set */
154 0, /* tp_dictoffset */
155 0, /* tp_init */
156 0, /* tp_alloc */
157 0, /* tp_new */
160 static int symtable_analyze(struct symtable *st);
161 static int symtable_warn(struct symtable *st, char *msg, int lineno);
162 static int symtable_enter_block(struct symtable *st, identifier name,
163 _Py_block_ty block, void *ast, int lineno);
164 static int symtable_exit_block(struct symtable *st, void *ast);
165 static int symtable_visit_stmt(struct symtable *st, stmt_ty s);
166 static int symtable_visit_expr(struct symtable *st, expr_ty s);
167 static int symtable_visit_genexp(struct symtable *st, expr_ty s);
168 static int symtable_visit_arguments(struct symtable *st, arguments_ty);
169 static int symtable_visit_excepthandler(struct symtable *st, excepthandler_ty);
170 static int symtable_visit_alias(struct symtable *st, alias_ty);
171 static int symtable_visit_comprehension(struct symtable *st, comprehension_ty);
172 static int symtable_visit_keyword(struct symtable *st, keyword_ty);
173 static int symtable_visit_slice(struct symtable *st, slice_ty);
174 static int symtable_visit_params(struct symtable *st, asdl_seq *args, int top);
175 static int symtable_visit_params_nested(struct symtable *st, asdl_seq *args);
176 static int symtable_implicit_arg(struct symtable *st, int pos);
179 static identifier top = NULL, lambda = NULL, genexpr = NULL;
181 #define GET_IDENTIFIER(VAR) \
182 ((VAR) ? (VAR) : ((VAR) = PyString_InternFromString(# VAR)))
184 #define DUPLICATE_ARGUMENT \
185 "duplicate argument '%s' in function definition"
187 static struct symtable *
188 symtable_new(void)
190 struct symtable *st;
192 st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable));
193 if (st == NULL)
194 return NULL;
196 st->st_filename = NULL;
197 st->st_symbols = NULL;
199 if ((st->st_stack = PyList_New(0)) == NULL)
200 goto fail;
201 if ((st->st_symbols = PyDict_New()) == NULL)
202 goto fail;
203 st->st_cur = NULL;
204 st->st_tmpname = 0;
205 st->st_private = NULL;
206 return st;
207 fail:
208 PySymtable_Free(st);
209 return NULL;
212 struct symtable *
213 PySymtable_Build(mod_ty mod, const char *filename, PyFutureFeatures *future)
215 struct symtable *st = symtable_new();
216 asdl_seq *seq;
217 int i;
219 if (st == NULL)
220 return st;
221 st->st_filename = filename;
222 st->st_future = future;
223 if (!GET_IDENTIFIER(top) ||
224 !symtable_enter_block(st, top, ModuleBlock, (void *)mod, 0)) {
225 PySymtable_Free(st);
226 return NULL;
229 st->st_top = st->st_cur;
230 st->st_cur->ste_unoptimized = OPT_TOPLEVEL;
231 /* Any other top-level initialization? */
232 switch (mod->kind) {
233 case Module_kind:
234 seq = mod->v.Module.body;
235 for (i = 0; i < asdl_seq_LEN(seq); i++)
236 if (!symtable_visit_stmt(st,
237 (stmt_ty)asdl_seq_GET(seq, i)))
238 goto error;
239 break;
240 case Expression_kind:
241 if (!symtable_visit_expr(st, mod->v.Expression.body))
242 goto error;
243 break;
244 case Interactive_kind:
245 seq = mod->v.Interactive.body;
246 for (i = 0; i < asdl_seq_LEN(seq); i++)
247 if (!symtable_visit_stmt(st,
248 (stmt_ty)asdl_seq_GET(seq, i)))
249 goto error;
250 break;
251 case Suite_kind:
252 PyErr_SetString(PyExc_RuntimeError,
253 "this compiler does not handle Suites");
254 goto error;
256 if (!symtable_exit_block(st, (void *)mod)) {
257 PySymtable_Free(st);
258 return NULL;
260 if (symtable_analyze(st))
261 return st;
262 PySymtable_Free(st);
263 return NULL;
264 error:
265 (void) symtable_exit_block(st, (void *)mod);
266 PySymtable_Free(st);
267 return NULL;
270 void
271 PySymtable_Free(struct symtable *st)
273 Py_XDECREF(st->st_symbols);
274 Py_XDECREF(st->st_stack);
275 PyMem_Free((void *)st);
278 PySTEntryObject *
279 PySymtable_Lookup(struct symtable *st, void *key)
281 PyObject *k, *v;
283 k = PyLong_FromVoidPtr(key);
284 if (k == NULL)
285 return NULL;
286 v = PyDict_GetItem(st->st_symbols, k);
287 if (v) {
288 assert(PySTEntry_Check(v));
289 Py_INCREF(v);
291 else {
292 PyErr_SetString(PyExc_KeyError,
293 "unknown symbol table entry");
296 Py_DECREF(k);
297 return (PySTEntryObject *)v;
300 int
301 PyST_GetScope(PySTEntryObject *ste, PyObject *name)
303 PyObject *v = PyDict_GetItem(ste->ste_symbols, name);
304 if (!v)
305 return 0;
306 assert(PyInt_Check(v));
307 return (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
311 /* Analyze raw symbol information to determine scope of each name.
313 The next several functions are helpers for PySymtable_Analyze(),
314 which determines whether a name is local, global, or free. In addition,
315 it determines which local variables are cell variables; they provide
316 bindings that are used for free variables in enclosed blocks.
318 There are also two kinds of free variables, implicit and explicit. An
319 explicit global is declared with the global statement. An implicit
320 global is a free variable for which the compiler has found no binding
321 in an enclosing function scope. The implicit global is either a global
322 or a builtin. Python's module and class blocks use the xxx_NAME opcodes
323 to handle these names to implement slightly odd semantics. In such a
324 block, the name is treated as global until it is assigned to; then it
325 is treated as a local.
327 The symbol table requires two passes to determine the scope of each name.
328 The first pass collects raw facts from the AST: the name is a parameter
329 here, the name is used by not defined here, etc. The second pass analyzes
330 these facts during a pass over the PySTEntryObjects created during pass 1.
332 When a function is entered during the second pass, the parent passes
333 the set of all name bindings visible to its children. These bindings
334 are used to determine if the variable is free or an implicit global.
335 After doing the local analysis, it analyzes each of its child blocks
336 using an updated set of name bindings.
338 The children update the free variable set. If a local variable is free
339 in a child, the variable is marked as a cell. The current function must
340 provide runtime storage for the variable that may outlive the function's
341 frame. Cell variables are removed from the free set before the analyze
342 function returns to its parent.
344 The sets of bound and free variables are implemented as dictionaries
345 mapping strings to None.
348 #define SET_SCOPE(DICT, NAME, I) { \
349 PyObject *o = PyInt_FromLong(I); \
350 if (!o) \
351 return 0; \
352 if (PyDict_SetItem((DICT), (NAME), o) < 0) { \
353 Py_DECREF(o); \
354 return 0; \
356 Py_DECREF(o); \
359 /* Decide on scope of name, given flags.
361 The dicts passed in as arguments are modified as necessary.
362 ste is passed so that flags can be updated.
365 static int
366 analyze_name(PySTEntryObject *ste, PyObject *dict, PyObject *name, long flags,
367 PyObject *bound, PyObject *local, PyObject *free,
368 PyObject *global)
370 if (flags & DEF_GLOBAL) {
371 if (flags & DEF_PARAM) {
372 PyErr_Format(PyExc_SyntaxError,
373 "name '%s' is local and global",
374 PyString_AS_STRING(name));
375 return 0;
377 SET_SCOPE(dict, name, GLOBAL_EXPLICIT);
378 if (PyDict_SetItem(global, name, Py_None) < 0)
379 return 0;
380 if (bound && PyDict_GetItem(bound, name)) {
381 if (PyDict_DelItem(bound, name) < 0)
382 return 0;
384 return 1;
386 if (flags & DEF_BOUND) {
387 SET_SCOPE(dict, name, LOCAL);
388 if (PyDict_SetItem(local, name, Py_None) < 0)
389 return 0;
390 if (PyDict_GetItem(global, name)) {
391 if (PyDict_DelItem(global, name) < 0)
392 return 0;
394 return 1;
396 /* If an enclosing block has a binding for this name, it
397 is a free variable rather than a global variable.
398 Note that having a non-NULL bound implies that the block
399 is nested.
401 if (bound && PyDict_GetItem(bound, name)) {
402 SET_SCOPE(dict, name, FREE);
403 ste->ste_free = 1;
404 if (PyDict_SetItem(free, name, Py_None) < 0)
405 return 0;
406 return 1;
408 /* If a parent has a global statement, then call it global
409 explicit? It could also be global implicit.
411 else if (global && PyDict_GetItem(global, name)) {
412 SET_SCOPE(dict, name, GLOBAL_EXPLICIT);
413 return 1;
415 else {
416 if (ste->ste_nested)
417 ste->ste_free = 1;
418 SET_SCOPE(dict, name, GLOBAL_IMPLICIT);
419 return 1;
421 return 0; /* Can't get here */
424 #undef SET_SCOPE
426 /* If a name is defined in free and also in locals, then this block
427 provides the binding for the free variable. The name should be
428 marked CELL in this block and removed from the free list.
430 Note that the current block's free variables are included in free.
431 That's safe because no name can be free and local in the same scope.
434 static int
435 analyze_cells(PyObject *scope, PyObject *free)
437 PyObject *name, *v, *w;
438 int success = 0;
439 Py_ssize_t pos = 0;
441 w = PyInt_FromLong(CELL);
442 if (!w)
443 return 0;
444 while (PyDict_Next(scope, &pos, &name, &v)) {
445 long flags;
446 assert(PyInt_Check(v));
447 flags = PyInt_AS_LONG(v);
448 if (flags != LOCAL)
449 continue;
450 if (!PyDict_GetItem(free, name))
451 continue;
452 /* Replace LOCAL with CELL for this name, and remove
453 from free. It is safe to replace the value of name
454 in the dict, because it will not cause a resize.
456 if (PyDict_SetItem(scope, name, w) < 0)
457 goto error;
458 if (!PyDict_DelItem(free, name) < 0)
459 goto error;
461 success = 1;
462 error:
463 Py_DECREF(w);
464 return success;
467 /* Check for illegal statements in unoptimized namespaces */
468 static int
469 check_unoptimized(const PySTEntryObject* ste) {
470 char buf[300];
471 const char* trailer;
473 if (ste->ste_type != FunctionBlock || !ste->ste_unoptimized
474 || !(ste->ste_free || ste->ste_child_free))
475 return 1;
477 trailer = (ste->ste_child_free ?
478 "contains a nested function with free variables" :
479 "is a nested function");
481 switch (ste->ste_unoptimized) {
482 case OPT_TOPLEVEL: /* exec / import * at top-level is fine */
483 case OPT_EXEC: /* qualified exec is fine */
484 return 1;
485 case OPT_IMPORT_STAR:
486 PyOS_snprintf(buf, sizeof(buf),
487 "import * is not allowed in function '%.100s' "
488 "because it is %s",
489 PyString_AS_STRING(ste->ste_name), trailer);
490 break;
491 case OPT_BARE_EXEC:
492 PyOS_snprintf(buf, sizeof(buf),
493 "unqualified exec is not allowed in function "
494 "'%.100s' it %s",
495 PyString_AS_STRING(ste->ste_name), trailer);
496 break;
497 default:
498 PyOS_snprintf(buf, sizeof(buf),
499 "function '%.100s' uses import * and bare exec, "
500 "which are illegal because it %s",
501 PyString_AS_STRING(ste->ste_name), trailer);
502 break;
505 PyErr_SetString(PyExc_SyntaxError, buf);
506 PyErr_SyntaxLocation(ste->ste_table->st_filename,
507 ste->ste_opt_lineno);
508 return 0;
511 /* Enter the final scope information into the st_symbols dict.
513 * All arguments are dicts. Modifies symbols, others are read-only.
515 static int
516 update_symbols(PyObject *symbols, PyObject *scope,
517 PyObject *bound, PyObject *free, int classflag)
519 PyObject *name, *v, *u, *w, *free_value = NULL;
520 Py_ssize_t pos = 0;
522 while (PyDict_Next(symbols, &pos, &name, &v)) {
523 long i, flags;
524 assert(PyInt_Check(v));
525 flags = PyInt_AS_LONG(v);
526 w = PyDict_GetItem(scope, name);
527 assert(w && PyInt_Check(w));
528 i = PyInt_AS_LONG(w);
529 flags |= (i << SCOPE_OFF);
530 u = PyInt_FromLong(flags);
531 if (!u)
532 return 0;
533 if (PyDict_SetItem(symbols, name, u) < 0) {
534 Py_DECREF(u);
535 return 0;
537 Py_DECREF(u);
540 free_value = PyInt_FromLong(FREE << SCOPE_OFF);
541 if (!free_value)
542 return 0;
544 /* add a free variable when it's only use is for creating a closure */
545 pos = 0;
546 while (PyDict_Next(free, &pos, &name, &v)) {
547 PyObject *o = PyDict_GetItem(symbols, name);
549 if (o) {
550 /* It could be a free variable in a method of
551 the class that has the same name as a local
552 or global in the class scope.
554 if (classflag &&
555 PyInt_AS_LONG(o) & (DEF_BOUND | DEF_GLOBAL)) {
556 long i = PyInt_AS_LONG(o) | DEF_FREE_CLASS;
557 o = PyInt_FromLong(i);
558 if (!o) {
559 Py_DECREF(free_value);
560 return 0;
562 if (PyDict_SetItem(symbols, name, o) < 0) {
563 Py_DECREF(o);
564 Py_DECREF(free_value);
565 return 0;
567 Py_DECREF(o);
569 /* else it's not free, probably a cell */
570 continue;
572 if (!PyDict_GetItem(bound, name))
573 continue; /* it's a global */
575 if (PyDict_SetItem(symbols, name, free_value) < 0) {
576 Py_DECREF(free_value);
577 return 0;
580 Py_DECREF(free_value);
581 return 1;
584 /* Make final symbol table decisions for block of ste.
585 Arguments:
586 ste -- current symtable entry (input/output)
587 bound -- set of variables bound in enclosing scopes (input)
588 free -- set of free variables in enclosed scopes (output)
589 globals -- set of declared global variables in enclosing scopes (input)
592 static int
593 analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free,
594 PyObject *global)
596 PyObject *name, *v, *local = NULL, *scope = NULL, *newbound = NULL;
597 PyObject *newglobal = NULL, *newfree = NULL;
598 int i, success = 0;
599 Py_ssize_t pos = 0;
601 local = PyDict_New();
602 if (!local)
603 goto error;
604 scope = PyDict_New();
605 if (!scope)
606 goto error;
607 newglobal = PyDict_New();
608 if (!newglobal)
609 goto error;
610 newfree = PyDict_New();
611 if (!newfree)
612 goto error;
613 newbound = PyDict_New();
614 if (!newbound)
615 goto error;
617 if (ste->ste_type == ClassBlock) {
618 /* make a copy of globals before calling analyze_name(),
619 because global statements in the class have no effect
620 on nested functions.
622 if (PyDict_Update(newglobal, global) < 0)
623 goto error;
624 if (bound)
625 if (PyDict_Update(newbound, bound) < 0)
626 goto error;
629 assert(PySTEntry_Check(ste));
630 assert(PyDict_Check(ste->ste_symbols));
631 while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
632 long flags = PyInt_AS_LONG(v);
633 if (!analyze_name(ste, scope, name, flags, bound, local, free,
634 global))
635 goto error;
638 if (ste->ste_type != ClassBlock) {
639 if (ste->ste_type == FunctionBlock) {
640 if (PyDict_Update(newbound, local) < 0)
641 goto error;
643 if (bound) {
644 if (PyDict_Update(newbound, bound) < 0)
645 goto error;
647 if (PyDict_Update(newglobal, global) < 0)
648 goto error;
651 /* Recursively call analyze_block() on each child block */
652 for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) {
653 PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
654 PySTEntryObject* entry;
655 assert(c && PySTEntry_Check(c));
656 entry = (PySTEntryObject*)c;
657 if (!analyze_block(entry, newbound, newfree, newglobal))
658 goto error;
659 if (entry->ste_free || entry->ste_child_free)
660 ste->ste_child_free = 1;
663 if (ste->ste_type == FunctionBlock && !analyze_cells(scope, newfree))
664 goto error;
665 if (!update_symbols(ste->ste_symbols, scope, bound, newfree,
666 ste->ste_type == ClassBlock))
667 goto error;
668 if (!check_unoptimized(ste))
669 goto error;
671 if (PyDict_Update(free, newfree) < 0)
672 goto error;
673 success = 1;
674 error:
675 Py_XDECREF(local);
676 Py_XDECREF(scope);
677 Py_XDECREF(newbound);
678 Py_XDECREF(newglobal);
679 Py_XDECREF(newfree);
680 if (!success)
681 assert(PyErr_Occurred());
682 return success;
685 static int
686 symtable_analyze(struct symtable *st)
688 PyObject *free, *global;
689 int r;
691 free = PyDict_New();
692 if (!free)
693 return 0;
694 global = PyDict_New();
695 if (!global) {
696 Py_DECREF(free);
697 return 0;
699 r = analyze_block(st->st_top, NULL, free, global);
700 Py_DECREF(free);
701 Py_DECREF(global);
702 return r;
706 static int
707 symtable_warn(struct symtable *st, char *msg, int lineno)
709 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, st->st_filename,
710 lineno, NULL, NULL) < 0) {
711 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
712 PyErr_SetString(PyExc_SyntaxError, msg);
713 PyErr_SyntaxLocation(st->st_filename,
714 st->st_cur->ste_lineno);
716 return 0;
718 return 1;
721 /* symtable_enter_block() gets a reference via PySTEntry_New().
722 This reference is released when the block is exited, via the DECREF
723 in symtable_exit_block().
726 static int
727 symtable_exit_block(struct symtable *st, void *ast)
729 Py_ssize_t end;
731 Py_CLEAR(st->st_cur);
732 end = PyList_GET_SIZE(st->st_stack) - 1;
733 if (end >= 0) {
734 st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack,
735 end);
736 if (st->st_cur == NULL)
737 return 0;
738 Py_INCREF(st->st_cur);
739 if (PySequence_DelItem(st->st_stack, end) < 0)
740 return 0;
742 return 1;
745 static int
746 symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block,
747 void *ast, int lineno)
749 PySTEntryObject *prev = NULL;
751 if (st->st_cur) {
752 prev = st->st_cur;
753 if (PyList_Append(st->st_stack, (PyObject *)st->st_cur) < 0) {
754 return 0;
756 Py_DECREF(st->st_cur);
758 st->st_cur = PySTEntry_New(st, name, block, ast, lineno);
759 if (st->st_cur == NULL)
760 return 0;
761 if (name == GET_IDENTIFIER(top))
762 st->st_global = st->st_cur->ste_symbols;
763 if (prev) {
764 if (PyList_Append(prev->ste_children,
765 (PyObject *)st->st_cur) < 0) {
766 return 0;
769 return 1;
772 static long
773 symtable_lookup(struct symtable *st, PyObject *name)
775 PyObject *o;
776 PyObject *mangled = _Py_Mangle(st->st_private, name);
777 if (!mangled)
778 return 0;
779 o = PyDict_GetItem(st->st_cur->ste_symbols, mangled);
780 Py_DECREF(mangled);
781 if (!o)
782 return 0;
783 return PyInt_AsLong(o);
786 static int
787 symtable_add_def(struct symtable *st, PyObject *name, int flag)
789 PyObject *o;
790 PyObject *dict;
791 long val;
792 PyObject *mangled = _Py_Mangle(st->st_private, name);
794 if (!mangled)
795 return 0;
796 dict = st->st_cur->ste_symbols;
797 if ((o = PyDict_GetItem(dict, mangled))) {
798 val = PyInt_AS_LONG(o);
799 if ((flag & DEF_PARAM) && (val & DEF_PARAM)) {
800 /* Is it better to use 'mangled' or 'name' here? */
801 PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT,
802 PyString_AsString(name));
803 PyErr_SyntaxLocation(st->st_filename,
804 st->st_cur->ste_lineno);
805 goto error;
807 val |= flag;
808 } else
809 val = flag;
810 o = PyInt_FromLong(val);
811 if (o == NULL)
812 goto error;
813 if (PyDict_SetItem(dict, mangled, o) < 0) {
814 Py_DECREF(o);
815 goto error;
817 Py_DECREF(o);
819 if (flag & DEF_PARAM) {
820 if (PyList_Append(st->st_cur->ste_varnames, mangled) < 0)
821 goto error;
822 } else if (flag & DEF_GLOBAL) {
823 /* XXX need to update DEF_GLOBAL for other flags too;
824 perhaps only DEF_FREE_GLOBAL */
825 val = flag;
826 if ((o = PyDict_GetItem(st->st_global, mangled))) {
827 val |= PyInt_AS_LONG(o);
829 o = PyInt_FromLong(val);
830 if (o == NULL)
831 goto error;
832 if (PyDict_SetItem(st->st_global, mangled, o) < 0) {
833 Py_DECREF(o);
834 goto error;
836 Py_DECREF(o);
838 Py_DECREF(mangled);
839 return 1;
841 error:
842 Py_DECREF(mangled);
843 return 0;
846 /* VISIT, VISIT_SEQ and VIST_SEQ_TAIL take an ASDL type as their second argument.
847 They use the ASDL name to synthesize the name of the C type and the visit
848 function.
850 VISIT_SEQ_TAIL permits the start of an ASDL sequence to be skipped, which is
851 useful if the first node in the sequence requires special treatment.
854 #define VISIT(ST, TYPE, V) \
855 if (!symtable_visit_ ## TYPE((ST), (V))) \
856 return 0;
858 #define VISIT_IN_BLOCK(ST, TYPE, V, S) \
859 if (!symtable_visit_ ## TYPE((ST), (V))) { \
860 symtable_exit_block((ST), (S)); \
861 return 0; \
864 #define VISIT_SEQ(ST, TYPE, SEQ) { \
865 int i; \
866 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
867 for (i = 0; i < asdl_seq_LEN(seq); i++) { \
868 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
869 if (!symtable_visit_ ## TYPE((ST), elt)) \
870 return 0; \
874 #define VISIT_SEQ_IN_BLOCK(ST, TYPE, SEQ, S) { \
875 int i; \
876 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
877 for (i = 0; i < asdl_seq_LEN(seq); i++) { \
878 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
879 if (!symtable_visit_ ## TYPE((ST), elt)) { \
880 symtable_exit_block((ST), (S)); \
881 return 0; \
886 #define VISIT_SEQ_TAIL(ST, TYPE, SEQ, START) { \
887 int i; \
888 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
889 for (i = (START); i < asdl_seq_LEN(seq); i++) { \
890 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
891 if (!symtable_visit_ ## TYPE((ST), elt)) \
892 return 0; \
896 #define VISIT_SEQ_TAIL_IN_BLOCK(ST, TYPE, SEQ, START, S) { \
897 int i; \
898 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
899 for (i = (START); i < asdl_seq_LEN(seq); i++) { \
900 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
901 if (!symtable_visit_ ## TYPE((ST), elt)) { \
902 symtable_exit_block((ST), (S)); \
903 return 0; \
908 static int
909 symtable_new_tmpname(struct symtable *st)
911 char tmpname[256];
912 identifier tmp;
914 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]",
915 ++st->st_cur->ste_tmpname);
916 tmp = PyString_InternFromString(tmpname);
917 if (!tmp)
918 return 0;
919 if (!symtable_add_def(st, tmp, DEF_LOCAL))
920 return 0;
921 Py_DECREF(tmp);
922 return 1;
925 static int
926 symtable_visit_stmt(struct symtable *st, stmt_ty s)
928 switch (s->kind) {
929 case FunctionDef_kind:
930 if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL))
931 return 0;
932 if (s->v.FunctionDef.args->defaults)
933 VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults);
934 if (s->v.FunctionDef.decorators)
935 VISIT_SEQ(st, expr, s->v.FunctionDef.decorators);
936 if (!symtable_enter_block(st, s->v.FunctionDef.name,
937 FunctionBlock, (void *)s, s->lineno))
938 return 0;
939 VISIT_IN_BLOCK(st, arguments, s->v.FunctionDef.args, s);
940 VISIT_SEQ_IN_BLOCK(st, stmt, s->v.FunctionDef.body, s);
941 if (!symtable_exit_block(st, s))
942 return 0;
943 break;
944 case ClassDef_kind: {
945 PyObject *tmp;
946 if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL))
947 return 0;
948 VISIT_SEQ(st, expr, s->v.ClassDef.bases);
949 if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock,
950 (void *)s, s->lineno))
951 return 0;
952 tmp = st->st_private;
953 st->st_private = s->v.ClassDef.name;
954 VISIT_SEQ_IN_BLOCK(st, stmt, s->v.ClassDef.body, s);
955 st->st_private = tmp;
956 if (!symtable_exit_block(st, s))
957 return 0;
958 break;
960 case Return_kind:
961 if (s->v.Return.value) {
962 VISIT(st, expr, s->v.Return.value);
963 st->st_cur->ste_returns_value = 1;
964 if (st->st_cur->ste_generator) {
965 PyErr_SetString(PyExc_SyntaxError,
966 RETURN_VAL_IN_GENERATOR);
967 PyErr_SyntaxLocation(st->st_filename,
968 s->lineno);
969 return 0;
972 break;
973 case Delete_kind:
974 VISIT_SEQ(st, expr, s->v.Delete.targets);
975 break;
976 case Assign_kind:
977 VISIT_SEQ(st, expr, s->v.Assign.targets);
978 VISIT(st, expr, s->v.Assign.value);
979 break;
980 case AugAssign_kind:
981 VISIT(st, expr, s->v.AugAssign.target);
982 VISIT(st, expr, s->v.AugAssign.value);
983 break;
984 case Print_kind:
985 if (s->v.Print.dest)
986 VISIT(st, expr, s->v.Print.dest);
987 VISIT_SEQ(st, expr, s->v.Print.values);
988 break;
989 case For_kind:
990 VISIT(st, expr, s->v.For.target);
991 VISIT(st, expr, s->v.For.iter);
992 VISIT_SEQ(st, stmt, s->v.For.body);
993 if (s->v.For.orelse)
994 VISIT_SEQ(st, stmt, s->v.For.orelse);
995 break;
996 case While_kind:
997 VISIT(st, expr, s->v.While.test);
998 VISIT_SEQ(st, stmt, s->v.While.body);
999 if (s->v.While.orelse)
1000 VISIT_SEQ(st, stmt, s->v.While.orelse);
1001 break;
1002 case If_kind:
1003 /* XXX if 0: and lookup_yield() hacks */
1004 VISIT(st, expr, s->v.If.test);
1005 VISIT_SEQ(st, stmt, s->v.If.body);
1006 if (s->v.If.orelse)
1007 VISIT_SEQ(st, stmt, s->v.If.orelse);
1008 break;
1009 case Raise_kind:
1010 if (s->v.Raise.type) {
1011 VISIT(st, expr, s->v.Raise.type);
1012 if (s->v.Raise.inst) {
1013 VISIT(st, expr, s->v.Raise.inst);
1014 if (s->v.Raise.tback)
1015 VISIT(st, expr, s->v.Raise.tback);
1018 break;
1019 case TryExcept_kind:
1020 VISIT_SEQ(st, stmt, s->v.TryExcept.body);
1021 VISIT_SEQ(st, stmt, s->v.TryExcept.orelse);
1022 VISIT_SEQ(st, excepthandler, s->v.TryExcept.handlers);
1023 break;
1024 case TryFinally_kind:
1025 VISIT_SEQ(st, stmt, s->v.TryFinally.body);
1026 VISIT_SEQ(st, stmt, s->v.TryFinally.finalbody);
1027 break;
1028 case Assert_kind:
1029 VISIT(st, expr, s->v.Assert.test);
1030 if (s->v.Assert.msg)
1031 VISIT(st, expr, s->v.Assert.msg);
1032 break;
1033 case Import_kind:
1034 VISIT_SEQ(st, alias, s->v.Import.names);
1035 /* XXX Don't have the lineno available inside
1036 visit_alias */
1037 if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno)
1038 st->st_cur->ste_opt_lineno = s->lineno;
1039 break;
1040 case ImportFrom_kind:
1041 VISIT_SEQ(st, alias, s->v.ImportFrom.names);
1042 /* XXX Don't have the lineno available inside
1043 visit_alias */
1044 if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno)
1045 st->st_cur->ste_opt_lineno = s->lineno;
1046 break;
1047 case Exec_kind:
1048 VISIT(st, expr, s->v.Exec.body);
1049 if (!st->st_cur->ste_opt_lineno)
1050 st->st_cur->ste_opt_lineno = s->lineno;
1051 if (s->v.Exec.globals) {
1052 st->st_cur->ste_unoptimized |= OPT_EXEC;
1053 VISIT(st, expr, s->v.Exec.globals);
1054 if (s->v.Exec.locals)
1055 VISIT(st, expr, s->v.Exec.locals);
1056 } else {
1057 st->st_cur->ste_unoptimized |= OPT_BARE_EXEC;
1059 break;
1060 case Global_kind: {
1061 int i;
1062 asdl_seq *seq = s->v.Global.names;
1063 for (i = 0; i < asdl_seq_LEN(seq); i++) {
1064 identifier name = (identifier)asdl_seq_GET(seq, i);
1065 char *c_name = PyString_AS_STRING(name);
1066 long cur = symtable_lookup(st, name);
1067 if (cur < 0)
1068 return 0;
1069 if (cur & (DEF_LOCAL | USE)) {
1070 char buf[256];
1071 if (cur & DEF_LOCAL)
1072 PyOS_snprintf(buf, sizeof(buf),
1073 GLOBAL_AFTER_ASSIGN,
1074 c_name);
1075 else
1076 PyOS_snprintf(buf, sizeof(buf),
1077 GLOBAL_AFTER_USE,
1078 c_name);
1079 if (!symtable_warn(st, buf, s->lineno))
1080 return 0;
1082 if (!symtable_add_def(st, name, DEF_GLOBAL))
1083 return 0;
1085 break;
1087 case Expr_kind:
1088 VISIT(st, expr, s->v.Expr.value);
1089 break;
1090 case Pass_kind:
1091 case Break_kind:
1092 case Continue_kind:
1093 /* nothing to do here */
1094 break;
1095 case With_kind:
1096 if (!symtable_new_tmpname(st))
1097 return 0;
1098 VISIT(st, expr, s->v.With.context_expr);
1099 if (s->v.With.optional_vars) {
1100 if (!symtable_new_tmpname(st))
1101 return 0;
1102 VISIT(st, expr, s->v.With.optional_vars);
1104 VISIT_SEQ(st, stmt, s->v.With.body);
1105 break;
1107 return 1;
1110 static int
1111 symtable_visit_expr(struct symtable *st, expr_ty e)
1113 switch (e->kind) {
1114 case BoolOp_kind:
1115 VISIT_SEQ(st, expr, e->v.BoolOp.values);
1116 break;
1117 case BinOp_kind:
1118 VISIT(st, expr, e->v.BinOp.left);
1119 VISIT(st, expr, e->v.BinOp.right);
1120 break;
1121 case UnaryOp_kind:
1122 VISIT(st, expr, e->v.UnaryOp.operand);
1123 break;
1124 case Lambda_kind: {
1125 if (!GET_IDENTIFIER(lambda) ||
1126 !symtable_add_def(st, lambda, DEF_LOCAL))
1127 return 0;
1128 if (e->v.Lambda.args->defaults)
1129 VISIT_SEQ(st, expr, e->v.Lambda.args->defaults);
1130 /* XXX how to get line numbers for expressions */
1131 if (!symtable_enter_block(st, lambda,
1132 FunctionBlock, (void *)e, 0))
1133 return 0;
1134 VISIT_IN_BLOCK(st, arguments, e->v.Lambda.args, (void*)e);
1135 VISIT_IN_BLOCK(st, expr, e->v.Lambda.body, (void*)e);
1136 if (!symtable_exit_block(st, (void *)e))
1137 return 0;
1138 break;
1140 case IfExp_kind:
1141 VISIT(st, expr, e->v.IfExp.test);
1142 VISIT(st, expr, e->v.IfExp.body);
1143 VISIT(st, expr, e->v.IfExp.orelse);
1144 break;
1145 case Dict_kind:
1146 VISIT_SEQ(st, expr, e->v.Dict.keys);
1147 VISIT_SEQ(st, expr, e->v.Dict.values);
1148 break;
1149 case ListComp_kind:
1150 if (!symtable_new_tmpname(st))
1151 return 0;
1152 VISIT(st, expr, e->v.ListComp.elt);
1153 VISIT_SEQ(st, comprehension, e->v.ListComp.generators);
1154 break;
1155 case GeneratorExp_kind:
1156 if (!symtable_visit_genexp(st, e))
1157 return 0;
1158 break;
1159 case Yield_kind:
1160 if (e->v.Yield.value)
1161 VISIT(st, expr, e->v.Yield.value);
1162 st->st_cur->ste_generator = 1;
1163 if (st->st_cur->ste_returns_value) {
1164 PyErr_SetString(PyExc_SyntaxError,
1165 RETURN_VAL_IN_GENERATOR);
1166 PyErr_SyntaxLocation(st->st_filename,
1167 e->lineno);
1168 return 0;
1170 break;
1171 case Compare_kind:
1172 VISIT(st, expr, e->v.Compare.left);
1173 VISIT_SEQ(st, expr, e->v.Compare.comparators);
1174 break;
1175 case Call_kind:
1176 VISIT(st, expr, e->v.Call.func);
1177 VISIT_SEQ(st, expr, e->v.Call.args);
1178 VISIT_SEQ(st, keyword, e->v.Call.keywords);
1179 if (e->v.Call.starargs)
1180 VISIT(st, expr, e->v.Call.starargs);
1181 if (e->v.Call.kwargs)
1182 VISIT(st, expr, e->v.Call.kwargs);
1183 break;
1184 case Repr_kind:
1185 VISIT(st, expr, e->v.Repr.value);
1186 break;
1187 case Num_kind:
1188 case Str_kind:
1189 /* Nothing to do here. */
1190 break;
1191 /* The following exprs can be assignment targets. */
1192 case Attribute_kind:
1193 VISIT(st, expr, e->v.Attribute.value);
1194 break;
1195 case Subscript_kind:
1196 VISIT(st, expr, e->v.Subscript.value);
1197 VISIT(st, slice, e->v.Subscript.slice);
1198 break;
1199 case Name_kind:
1200 if (!symtable_add_def(st, e->v.Name.id,
1201 e->v.Name.ctx == Load ? USE : DEF_LOCAL))
1202 return 0;
1203 break;
1204 /* child nodes of List and Tuple will have expr_context set */
1205 case List_kind:
1206 VISIT_SEQ(st, expr, e->v.List.elts);
1207 break;
1208 case Tuple_kind:
1209 VISIT_SEQ(st, expr, e->v.Tuple.elts);
1210 break;
1212 return 1;
1215 static int
1216 symtable_implicit_arg(struct symtable *st, int pos)
1218 PyObject *id = PyString_FromFormat(".%d", pos);
1219 if (id == NULL)
1220 return 0;
1221 if (!symtable_add_def(st, id, DEF_PARAM)) {
1222 Py_DECREF(id);
1223 return 0;
1225 Py_DECREF(id);
1226 return 1;
1229 static int
1230 symtable_visit_params(struct symtable *st, asdl_seq *args, int toplevel)
1232 int i;
1234 /* go through all the toplevel arguments first */
1235 for (i = 0; i < asdl_seq_LEN(args); i++) {
1236 expr_ty arg = (expr_ty)asdl_seq_GET(args, i);
1237 if (arg->kind == Name_kind) {
1238 assert(arg->v.Name.ctx == Param ||
1239 (arg->v.Name.ctx == Store && !toplevel));
1240 if (!symtable_add_def(st, arg->v.Name.id, DEF_PARAM))
1241 return 0;
1243 else if (arg->kind == Tuple_kind) {
1244 assert(arg->v.Tuple.ctx == Store);
1245 if (toplevel) {
1246 if (!symtable_implicit_arg(st, i))
1247 return 0;
1250 else {
1251 PyErr_SetString(PyExc_SyntaxError,
1252 "invalid expression in parameter list");
1253 PyErr_SyntaxLocation(st->st_filename,
1254 st->st_cur->ste_lineno);
1255 return 0;
1259 if (!toplevel) {
1260 if (!symtable_visit_params_nested(st, args))
1261 return 0;
1264 return 1;
1267 static int
1268 symtable_visit_params_nested(struct symtable *st, asdl_seq *args)
1270 int i;
1271 for (i = 0; i < asdl_seq_LEN(args); i++) {
1272 expr_ty arg = (expr_ty)asdl_seq_GET(args, i);
1273 if (arg->kind == Tuple_kind &&
1274 !symtable_visit_params(st, arg->v.Tuple.elts, 0))
1275 return 0;
1278 return 1;
1281 static int
1282 symtable_visit_arguments(struct symtable *st, arguments_ty a)
1284 /* skip default arguments inside function block
1285 XXX should ast be different?
1287 if (a->args && !symtable_visit_params(st, a->args, 1))
1288 return 0;
1289 if (a->vararg) {
1290 if (!symtable_add_def(st, a->vararg, DEF_PARAM))
1291 return 0;
1292 st->st_cur->ste_varargs = 1;
1294 if (a->kwarg) {
1295 if (!symtable_add_def(st, a->kwarg, DEF_PARAM))
1296 return 0;
1297 st->st_cur->ste_varkeywords = 1;
1299 if (a->args && !symtable_visit_params_nested(st, a->args))
1300 return 0;
1301 return 1;
1305 static int
1306 symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh)
1308 if (eh->type)
1309 VISIT(st, expr, eh->type);
1310 if (eh->name)
1311 VISIT(st, expr, eh->name);
1312 VISIT_SEQ(st, stmt, eh->body);
1313 return 1;
1317 static int
1318 symtable_visit_alias(struct symtable *st, alias_ty a)
1320 /* Compute store_name, the name actually bound by the import
1321 operation. It is diferent than a->name when a->name is a
1322 dotted package name (e.g. spam.eggs)
1324 PyObject *store_name;
1325 PyObject *name = (a->asname == NULL) ? a->name : a->asname;
1326 const char *base = PyString_AS_STRING(name);
1327 char *dot = strchr(base, '.');
1328 if (dot) {
1329 store_name = PyString_FromStringAndSize(base, dot - base);
1330 if (!store_name)
1331 return 0;
1333 else {
1334 store_name = name;
1335 Py_INCREF(store_name);
1337 if (strcmp(PyString_AS_STRING(name), "*")) {
1338 int r = symtable_add_def(st, store_name, DEF_IMPORT);
1339 Py_DECREF(store_name);
1340 return r;
1342 else {
1343 if (st->st_cur->ste_type != ModuleBlock) {
1344 int lineno = st->st_cur->ste_lineno;
1345 if (!symtable_warn(st, IMPORT_STAR_WARNING, lineno)) {
1346 Py_DECREF(store_name);
1347 return 0;
1350 st->st_cur->ste_unoptimized |= OPT_IMPORT_STAR;
1351 Py_DECREF(store_name);
1352 return 1;
1357 static int
1358 symtable_visit_comprehension(struct symtable *st, comprehension_ty lc)
1360 VISIT(st, expr, lc->target);
1361 VISIT(st, expr, lc->iter);
1362 VISIT_SEQ(st, expr, lc->ifs);
1363 return 1;
1367 static int
1368 symtable_visit_keyword(struct symtable *st, keyword_ty k)
1370 VISIT(st, expr, k->value);
1371 return 1;
1375 static int
1376 symtable_visit_slice(struct symtable *st, slice_ty s)
1378 switch (s->kind) {
1379 case Slice_kind:
1380 if (s->v.Slice.lower)
1381 VISIT(st, expr, s->v.Slice.lower)
1382 if (s->v.Slice.upper)
1383 VISIT(st, expr, s->v.Slice.upper)
1384 if (s->v.Slice.step)
1385 VISIT(st, expr, s->v.Slice.step)
1386 break;
1387 case ExtSlice_kind:
1388 VISIT_SEQ(st, slice, s->v.ExtSlice.dims)
1389 break;
1390 case Index_kind:
1391 VISIT(st, expr, s->v.Index.value)
1392 break;
1393 case Ellipsis_kind:
1394 break;
1396 return 1;
1399 static int
1400 symtable_visit_genexp(struct symtable *st, expr_ty e)
1402 comprehension_ty outermost = ((comprehension_ty)
1403 (asdl_seq_GET(e->v.GeneratorExp.generators, 0)));
1404 /* Outermost iterator is evaluated in current scope */
1405 VISIT(st, expr, outermost->iter);
1406 /* Create generator scope for the rest */
1407 if (!GET_IDENTIFIER(genexpr) ||
1408 !symtable_enter_block(st, genexpr, FunctionBlock, (void *)e, 0)) {
1409 return 0;
1411 st->st_cur->ste_generator = 1;
1412 /* Outermost iter is received as an argument */
1413 if (!symtable_implicit_arg(st, 0)) {
1414 symtable_exit_block(st, (void *)e);
1415 return 0;
1417 VISIT_IN_BLOCK(st, expr, outermost->target, (void*)e);
1418 VISIT_SEQ_IN_BLOCK(st, expr, outermost->ifs, (void*)e);
1419 VISIT_SEQ_TAIL_IN_BLOCK(st, comprehension,
1420 e->v.GeneratorExp.generators, 1, (void*)e);
1421 VISIT_IN_BLOCK(st, expr, e->v.GeneratorExp.elt, (void*)e);
1422 return symtable_exit_block(st, (void *)e);