Changes due to added test for fileConfig contributed by Shane Hathaway.
[python.git] / Python / symtable.c
blob7e876d4c964b1d1566918fa296364592d7e6765c
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"
17 PySTEntryObject *
18 PySTEntry_New(struct symtable *st, identifier name, _Py_block_ty block,
19 void *key, int lineno)
21 PySTEntryObject *ste = NULL;
22 PyObject *k;
24 k = PyLong_FromVoidPtr(key);
25 if (k == NULL)
26 goto fail;
27 ste = (PySTEntryObject *)PyObject_New(PySTEntryObject,
28 &PySTEntry_Type);
29 ste->ste_table = st;
30 ste->ste_id = k;
31 ste->ste_tmpname = 0;
33 ste->ste_name = name;
34 Py_INCREF(name);
36 ste->ste_symbols = NULL;
37 ste->ste_varnames = NULL;
38 ste->ste_children = NULL;
40 ste->ste_symbols = PyDict_New();
41 if (ste->ste_symbols == NULL)
42 goto fail;
44 ste->ste_varnames = PyList_New(0);
45 if (ste->ste_varnames == NULL)
46 goto fail;
48 ste->ste_children = PyList_New(0);
49 if (ste->ste_children == NULL)
50 goto fail;
52 ste->ste_type = block;
53 ste->ste_unoptimized = 0;
54 ste->ste_nested = 0;
55 ste->ste_free = 0;
56 ste->ste_varargs = 0;
57 ste->ste_varkeywords = 0;
58 ste->ste_opt_lineno = 0;
59 ste->ste_tmpname = 0;
60 ste->ste_lineno = lineno;
62 if (st->st_cur != NULL &&
63 (st->st_cur->ste_nested ||
64 st->st_cur->ste_type == FunctionBlock))
65 ste->ste_nested = 1;
66 ste->ste_child_free = 0;
67 ste->ste_generator = 0;
69 if (PyDict_SetItem(st->st_symbols, ste->ste_id, (PyObject *)ste) < 0)
70 goto fail;
72 return ste;
73 fail:
74 Py_XDECREF(ste);
75 return NULL;
78 static PyObject *
79 ste_repr(PySTEntryObject *ste)
81 char buf[256];
83 PyOS_snprintf(buf, sizeof(buf),
84 "<symtable entry %.100s(%ld), line %d>",
85 PyString_AS_STRING(ste->ste_name),
86 PyInt_AS_LONG(ste->ste_id), ste->ste_lineno);
87 return PyString_FromString(buf);
90 static void
91 ste_dealloc(PySTEntryObject *ste)
93 ste->ste_table = NULL;
94 Py_XDECREF(ste->ste_id);
95 Py_XDECREF(ste->ste_name);
96 Py_XDECREF(ste->ste_symbols);
97 Py_XDECREF(ste->ste_varnames);
98 Py_XDECREF(ste->ste_children);
99 PyObject_Del(ste);
102 #define OFF(x) offsetof(PySTEntryObject, x)
104 static PyMemberDef ste_memberlist[] = {
105 {"id", T_OBJECT, OFF(ste_id), READONLY},
106 {"name", T_OBJECT, OFF(ste_name), READONLY},
107 {"symbols", T_OBJECT, OFF(ste_symbols), READONLY},
108 {"varnames", T_OBJECT, OFF(ste_varnames), READONLY},
109 {"children", T_OBJECT, OFF(ste_children), READONLY},
110 {"type", T_INT, OFF(ste_type), READONLY},
111 {"lineno", T_INT, OFF(ste_lineno), READONLY},
112 {NULL}
115 PyTypeObject PySTEntry_Type = {
116 PyObject_HEAD_INIT(&PyType_Type)
118 "symtable entry",
119 sizeof(PySTEntryObject),
121 (destructor)ste_dealloc, /* tp_dealloc */
122 0, /* tp_print */
123 0, /* tp_getattr */
124 0, /* tp_setattr */
125 0, /* tp_compare */
126 (reprfunc)ste_repr, /* tp_repr */
127 0, /* tp_as_number */
128 0, /* tp_as_sequence */
129 0, /* tp_as_mapping */
130 0, /* tp_hash */
131 0, /* tp_call */
132 0, /* tp_str */
133 PyObject_GenericGetAttr, /* tp_getattro */
134 0, /* tp_setattro */
135 0, /* tp_as_buffer */
136 Py_TPFLAGS_DEFAULT, /* tp_flags */
137 0, /* tp_doc */
138 0, /* tp_traverse */
139 0, /* tp_clear */
140 0, /* tp_richcompare */
141 0, /* tp_weaklistoffset */
142 0, /* tp_iter */
143 0, /* tp_iternext */
144 0, /* tp_methods */
145 ste_memberlist, /* tp_members */
146 0, /* tp_getset */
147 0, /* tp_base */
148 0, /* tp_dict */
149 0, /* tp_descr_get */
150 0, /* tp_descr_set */
151 0, /* tp_dictoffset */
152 0, /* tp_init */
153 0, /* tp_alloc */
154 0, /* tp_new */
157 static int symtable_analyze(struct symtable *st);
158 static int symtable_warn(struct symtable *st, char *msg, int lineno);
159 static int symtable_enter_block(struct symtable *st, identifier name,
160 _Py_block_ty block, void *ast, int lineno);
161 static int symtable_exit_block(struct symtable *st, void *ast);
162 static int symtable_visit_stmt(struct symtable *st, stmt_ty s);
163 static int symtable_visit_expr(struct symtable *st, expr_ty s);
164 static int symtable_visit_genexp(struct symtable *st, expr_ty s);
165 static int symtable_visit_arguments(struct symtable *st, arguments_ty);
166 static int symtable_visit_excepthandler(struct symtable *st, excepthandler_ty);
167 static int symtable_visit_alias(struct symtable *st, alias_ty);
168 static int symtable_visit_comprehension(struct symtable *st, comprehension_ty);
169 static int symtable_visit_keyword(struct symtable *st, keyword_ty);
170 static int symtable_visit_slice(struct symtable *st, slice_ty);
171 static int symtable_visit_params(struct symtable *st, asdl_seq *args, int top);
172 static int symtable_visit_params_nested(struct symtable *st, asdl_seq *args);
173 static int symtable_implicit_arg(struct symtable *st, int pos);
176 static identifier top = NULL, lambda = NULL, genexpr = NULL;
178 #define GET_IDENTIFIER(VAR) \
179 ((VAR) ? (VAR) : ((VAR) = PyString_InternFromString(# VAR)))
181 #define DUPLICATE_ARGUMENT \
182 "duplicate argument '%s' in function definition"
184 static struct symtable *
185 symtable_new(void)
187 struct symtable *st;
189 st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable));
190 if (st == NULL)
191 return NULL;
193 st->st_filename = NULL;
194 st->st_symbols = NULL;
196 if ((st->st_stack = PyList_New(0)) == NULL)
197 goto fail;
198 if ((st->st_symbols = PyDict_New()) == NULL)
199 goto fail;
200 st->st_cur = NULL;
201 st->st_tmpname = 0;
202 st->st_private = NULL;
203 return st;
204 fail:
205 PySymtable_Free(st);
206 return NULL;
209 struct symtable *
210 PySymtable_Build(mod_ty mod, const char *filename, PyFutureFeatures *future)
212 struct symtable *st = symtable_new();
213 asdl_seq *seq;
214 int i;
216 if (st == NULL)
217 return st;
218 st->st_filename = filename;
219 st->st_future = future;
220 symtable_enter_block(st, GET_IDENTIFIER(top), ModuleBlock,
221 (void *)mod, 0);
222 st->st_top = st->st_cur;
223 st->st_cur->ste_unoptimized = OPT_TOPLEVEL;
224 /* Any other top-level initialization? */
225 switch (mod->kind) {
226 case Module_kind:
227 seq = mod->v.Module.body;
228 for (i = 0; i < asdl_seq_LEN(seq); i++)
229 if (!symtable_visit_stmt(st, asdl_seq_GET(seq, i)))
230 goto error;
231 break;
232 case Expression_kind:
233 if (!symtable_visit_expr(st, mod->v.Expression.body))
234 goto error;
235 break;
236 case Interactive_kind:
237 seq = mod->v.Interactive.body;
238 for (i = 0; i < asdl_seq_LEN(seq); i++)
239 if (!symtable_visit_stmt(st, asdl_seq_GET(seq, i)))
240 goto error;
241 break;
242 case Suite_kind:
243 PyErr_SetString(PyExc_RuntimeError,
244 "this compiler does not handle Suites");
245 goto error;
247 if (!symtable_exit_block(st, (void *)mod)) {
248 PySymtable_Free(st);
249 return NULL;
251 if (symtable_analyze(st))
252 return st;
253 PySymtable_Free(st);
254 return NULL;
255 error:
256 (void) symtable_exit_block(st, (void *)mod);
257 PySymtable_Free(st);
258 return NULL;
261 void
262 PySymtable_Free(struct symtable *st)
264 Py_XDECREF(st->st_symbols);
265 Py_XDECREF(st->st_stack);
266 PyMem_Free((void *)st);
269 PySTEntryObject *
270 PySymtable_Lookup(struct symtable *st, void *key)
272 PyObject *k, *v;
274 k = PyLong_FromVoidPtr(key);
275 if (k == NULL)
276 return NULL;
277 v = PyDict_GetItem(st->st_symbols, k);
278 if (v) {
279 assert(PySTEntry_Check(v));
280 Py_INCREF(v);
282 else {
283 PyErr_SetString(PyExc_KeyError,
284 "unknown symbol table entry");
287 Py_DECREF(k);
288 return (PySTEntryObject *)v;
291 int
292 PyST_GetScope(PySTEntryObject *ste, PyObject *name)
294 PyObject *v = PyDict_GetItem(ste->ste_symbols, name);
295 if (!v)
296 return 0;
297 assert(PyInt_Check(v));
298 return (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
302 /* Analyze raw symbol information to determine scope of each name.
304 The next several functions are helpers for PySymtable_Analyze(),
305 which determines whether a name is local, global, or free. In addition,
306 it determines which local variables are cell variables; they provide
307 bindings that are used for free variables in enclosed blocks.
309 There are also two kinds of free variables, implicit and explicit. An
310 explicit global is declared with the global statement. An implicit
311 global is a free variable for which the compiler has found no binding
312 in an enclosing function scope. The implicit global is either a global
313 or a builtin. Python's module and class blocks use the xxx_NAME opcodes
314 to handle these names to implement slightly odd semantics. In such a
315 block, the name is treated as global until it is assigned to; then it
316 is treated as a local.
318 The symbol table requires two passes to determine the scope of each name.
319 The first pass collects raw facts from the AST: the name is a parameter
320 here, the name is used by not defined here, etc. The second pass analyzes
321 these facts during a pass over the PySTEntryObjects created during pass 1.
323 When a function is entered during the second pass, the parent passes
324 the set of all name bindings visible to its children. These bindings
325 are used to determine if the variable is free or an implicit global.
326 After doing the local analysis, it analyzes each of its child blocks
327 using an updated set of name bindings.
329 The children update the free variable set. If a local variable is free
330 in a child, the variable is marked as a cell. The current function must
331 provide runtime storage for the variable that may outlive the function's
332 frame. Cell variables are removed from the free set before the analyze
333 function returns to its parent.
335 The sets of bound and free variables are implemented as dictionaries
336 mapping strings to None.
339 #define SET_SCOPE(DICT, NAME, I) { \
340 PyObject *o = PyInt_FromLong(I); \
341 if (!o) \
342 return 0; \
343 if (PyDict_SetItem((DICT), (NAME), o) < 0) { \
344 Py_DECREF(o); \
345 return 0; \
347 Py_DECREF(o); \
350 /* Decide on scope of name, given flags.
352 The dicts passed in as arguments are modified as necessary.
353 ste is passed so that flags can be updated.
356 static int
357 analyze_name(PySTEntryObject *ste, PyObject *dict, PyObject *name, long flags,
358 PyObject *bound, PyObject *local, PyObject *free,
359 PyObject *global)
361 if (flags & DEF_GLOBAL) {
362 if (flags & DEF_PARAM) {
363 PyErr_Format(PyExc_SyntaxError,
364 "name '%s' is local and global",
365 PyString_AS_STRING(name));
366 return 0;
368 SET_SCOPE(dict, name, GLOBAL_EXPLICIT);
369 if (PyDict_SetItem(global, name, Py_None) < 0)
370 return 0;
371 if (bound && PyDict_GetItem(bound, name)) {
372 if (PyDict_DelItem(bound, name) < 0)
373 return 0;
375 return 1;
377 if (flags & DEF_BOUND) {
378 SET_SCOPE(dict, name, LOCAL);
379 if (PyDict_SetItem(local, name, Py_None) < 0)
380 return 0;
381 if (PyDict_GetItem(global, name)) {
382 if (PyDict_DelItem(global, name) < 0)
383 return 0;
385 return 1;
387 /* If an enclosing block has a binding for this name, it
388 is a free variable rather than a global variable.
389 Note that having a non-NULL bound implies that the block
390 is nested.
392 if (bound && PyDict_GetItem(bound, name)) {
393 SET_SCOPE(dict, name, FREE);
394 ste->ste_free = 1;
395 if (PyDict_SetItem(free, name, Py_None) < 0)
396 return 0;
397 return 1;
399 /* If a parent has a global statement, then call it global
400 explicit? It could also be global implicit.
402 else if (global && PyDict_GetItem(global, name)) {
403 SET_SCOPE(dict, name, GLOBAL_EXPLICIT);
404 return 1;
406 else {
407 if (ste->ste_nested)
408 ste->ste_free = 1;
409 SET_SCOPE(dict, name, GLOBAL_IMPLICIT);
410 return 1;
412 return 0; /* Can't get here */
415 #undef SET_SCOPE
417 /* If a name is defined in free and also in locals, then this block
418 provides the binding for the free variable. The name should be
419 marked CELL in this block and removed from the free list.
421 Note that the current block's free variables are included in free.
422 That's safe because no name can be free and local in the same scope.
425 static int
426 analyze_cells(PyObject *scope, PyObject *free)
428 PyObject *name, *v, *w;
429 int pos = 0, success = 0;
431 w = PyInt_FromLong(CELL);
432 if (!w)
433 return 0;
434 while (PyDict_Next(scope, &pos, &name, &v)) {
435 long flags;
436 assert(PyInt_Check(v));
437 flags = PyInt_AS_LONG(v);
438 if (flags != LOCAL)
439 continue;
440 if (!PyDict_GetItem(free, name))
441 continue;
442 /* Replace LOCAL with CELL for this name, and remove
443 from free. It is safe to replace the value of name
444 in the dict, because it will not cause a resize.
446 if (PyDict_SetItem(scope, name, w) < 0)
447 goto error;
448 if (!PyDict_DelItem(free, name) < 0)
449 goto error;
451 success = 1;
452 error:
453 Py_DECREF(w);
454 return success;
457 /* Check for illegal statements in unoptimized namespaces */
458 static int
459 check_unoptimized(const PySTEntryObject* ste) {
460 char buf[300];
461 const char* trailer;
463 if (ste->ste_type != FunctionBlock || !ste->ste_unoptimized
464 || !(ste->ste_free || ste->ste_child_free))
465 return 1;
467 trailer = (ste->ste_child_free ?
468 "contains a nested function with free variables" :
469 "is a nested function");
471 switch (ste->ste_unoptimized) {
472 case OPT_TOPLEVEL: /* exec / import * at top-level is fine */
473 case OPT_EXEC: /* qualified exec is fine */
474 return 1;
475 case OPT_IMPORT_STAR:
476 PyOS_snprintf(buf, sizeof(buf),
477 "import * is not allowed in function '%.100s' "
478 "because it is %s",
479 PyString_AS_STRING(ste->ste_name), trailer);
480 break;
481 case OPT_BARE_EXEC:
482 PyOS_snprintf(buf, sizeof(buf),
483 "unqualified exec is not allowed in function "
484 "'%.100s' it %s",
485 PyString_AS_STRING(ste->ste_name), trailer);
486 break;
487 default:
488 PyOS_snprintf(buf, sizeof(buf),
489 "function '%.100s' uses import * and bare exec, "
490 "which are illegal because it %s",
491 PyString_AS_STRING(ste->ste_name), trailer);
492 break;
495 PyErr_SetString(PyExc_SyntaxError, buf);
496 PyErr_SyntaxLocation(ste->ste_table->st_filename,
497 ste->ste_opt_lineno);
498 return 0;
501 /* Enter the final scope information into the st_symbols dict.
503 * All arguments are dicts. Modifies symbols, others are read-only.
505 static int
506 update_symbols(PyObject *symbols, PyObject *scope,
507 PyObject *bound, PyObject *free, int class)
509 PyObject *name, *v, *u, *w, *free_value = NULL;
510 int pos = 0;
512 while (PyDict_Next(symbols, &pos, &name, &v)) {
513 long i, flags;
514 assert(PyInt_Check(v));
515 flags = PyInt_AS_LONG(v);
516 w = PyDict_GetItem(scope, name);
517 assert(w && PyInt_Check(w));
518 i = PyInt_AS_LONG(w);
519 flags |= (i << SCOPE_OFF);
520 u = PyInt_FromLong(flags);
521 if (PyDict_SetItem(symbols, name, u) < 0) {
522 Py_DECREF(u);
523 return 0;
525 Py_DECREF(u);
528 free_value = PyInt_FromLong(FREE << SCOPE_OFF);
529 if (!free_value)
530 return 0;
532 /* add a free variable when it's only use is for creating a closure */
533 pos = 0;
534 while (PyDict_Next(free, &pos, &name, &v)) {
535 PyObject *o = PyDict_GetItem(symbols, name);
537 if (o) {
538 /* It could be a free variable in a method of
539 the class that has the same name as a local
540 or global in the class scope.
542 if (class &&
543 PyInt_AS_LONG(o) & (DEF_BOUND | DEF_GLOBAL)) {
544 long i = PyInt_AS_LONG(o) | DEF_FREE_CLASS;
545 o = PyInt_FromLong(i);
546 if (!o) {
547 Py_DECREF(free_value);
548 return 0;
550 if (PyDict_SetItem(symbols, name, o) < 0) {
551 Py_DECREF(o);
552 Py_DECREF(free_value);
553 return 0;
555 Py_DECREF(o);
557 /* else it's not free, probably a cell */
558 continue;
560 if (!PyDict_GetItem(bound, name))
561 continue; /* it's a global */
563 if (PyDict_SetItem(symbols, name, free_value) < 0) {
564 Py_DECREF(free_value);
565 return 0;
568 Py_DECREF(free_value);
569 return 1;
572 /* Make final symbol table decisions for block of ste.
573 Arguments:
574 ste -- current symtable entry (input/output)
575 bound -- set of variables bound in enclosing scopes (input)
576 free -- set of free variables in enclosed scopes (output)
577 globals -- set of declared global variables in enclosing scopes (input)
580 static int
581 analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free,
582 PyObject *global)
584 PyObject *name, *v, *local = NULL, *scope = NULL, *newbound = NULL;
585 PyObject *newglobal = NULL, *newfree = NULL;
586 int i, pos = 0, success = 0;
588 local = PyDict_New();
589 if (!local)
590 goto error;
591 scope = PyDict_New();
592 if (!scope)
593 goto error;
594 newglobal = PyDict_New();
595 if (!newglobal)
596 goto error;
597 newfree = PyDict_New();
598 if (!newfree)
599 goto error;
600 newbound = PyDict_New();
601 if (!newbound)
602 goto error;
604 if (ste->ste_type == ClassBlock) {
605 /* make a copy of globals before calling analyze_name(),
606 because global statements in the class have no effect
607 on nested functions.
609 if (PyDict_Update(newglobal, global) < 0)
610 goto error;
611 if (bound)
612 if (PyDict_Update(newbound, bound) < 0)
613 goto error;
616 assert(PySTEntry_Check(ste));
617 assert(PyDict_Check(ste->ste_symbols));
618 while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
619 long flags = PyInt_AS_LONG(v);
620 if (!analyze_name(ste, scope, name, flags, bound, local, free,
621 global))
622 goto error;
625 if (ste->ste_type != ClassBlock) {
626 if (ste->ste_type == FunctionBlock) {
627 if (PyDict_Update(newbound, local) < 0)
628 goto error;
630 if (bound) {
631 if (PyDict_Update(newbound, bound) < 0)
632 goto error;
634 if (PyDict_Update(newglobal, global) < 0)
635 goto error;
638 /* Recursively call analyze_block() on each child block */
639 for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) {
640 PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
641 PySTEntryObject* entry;
642 assert(c && PySTEntry_Check(c));
643 entry = (PySTEntryObject*)c;
644 if (!analyze_block(entry, newbound, newfree, newglobal))
645 goto error;
646 if (entry->ste_free || entry->ste_child_free)
647 ste->ste_child_free = 1;
650 if (ste->ste_type == FunctionBlock && !analyze_cells(scope, newfree))
651 goto error;
652 if (!update_symbols(ste->ste_symbols, scope, bound, newfree,
653 ste->ste_type == ClassBlock))
654 goto error;
655 if (!check_unoptimized(ste))
656 goto error;
658 if (PyDict_Update(free, newfree) < 0)
659 goto error;
660 success = 1;
661 error:
662 Py_XDECREF(local);
663 Py_XDECREF(scope);
664 Py_XDECREF(newbound);
665 Py_XDECREF(newglobal);
666 Py_XDECREF(newfree);
667 if (!success)
668 assert(PyErr_Occurred());
669 return success;
672 static int
673 symtable_analyze(struct symtable *st)
675 PyObject *free, *global;
676 int r;
678 free = PyDict_New();
679 if (!free)
680 return 0;
681 global = PyDict_New();
682 if (!global) {
683 Py_DECREF(free);
684 return 0;
686 r = analyze_block(st->st_top, NULL, free, global);
687 Py_DECREF(free);
688 Py_DECREF(global);
689 return r;
693 static int
694 symtable_warn(struct symtable *st, char *msg, int lineno)
696 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, st->st_filename,
697 lineno, NULL, NULL) < 0) {
698 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
699 PyErr_SetString(PyExc_SyntaxError, msg);
700 PyErr_SyntaxLocation(st->st_filename,
701 st->st_cur->ste_lineno);
703 return 0;
705 return 1;
708 /* symtable_enter_block() gets a reference via PySTEntry_New().
709 This reference is released when the block is exited, via the DECREF
710 in symtable_exit_block().
713 static int
714 symtable_exit_block(struct symtable *st, void *ast)
716 int end;
718 Py_DECREF(st->st_cur);
719 end = PyList_GET_SIZE(st->st_stack) - 1;
720 if (end >= 0) {
721 st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack,
722 end);
723 Py_INCREF(st->st_cur);
724 if (PySequence_DelItem(st->st_stack, end) < 0)
725 return 0;
727 return 1;
730 static int
731 symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block,
732 void *ast, int lineno)
734 PySTEntryObject *prev = NULL;
736 if (st->st_cur) {
737 prev = st->st_cur;
738 if (PyList_Append(st->st_stack, (PyObject *)st->st_cur) < 0) {
739 return 0;
741 Py_DECREF(st->st_cur);
743 st->st_cur = PySTEntry_New(st, name, block, ast, lineno);
744 if (name == GET_IDENTIFIER(top))
745 st->st_global = st->st_cur->ste_symbols;
746 if (prev) {
747 if (PyList_Append(prev->ste_children,
748 (PyObject *)st->st_cur) < 0) {
749 return 0;
752 return 1;
755 static long
756 symtable_lookup(struct symtable *st, PyObject *name)
758 PyObject *o;
759 PyObject *mangled = _Py_Mangle(st->st_private, name);
760 if (!mangled)
761 return 0;
762 o = PyDict_GetItem(st->st_cur->ste_symbols, mangled);
763 Py_DECREF(mangled);
764 if (!o)
765 return 0;
766 return PyInt_AsLong(o);
769 static int
770 symtable_add_def(struct symtable *st, PyObject *name, int flag)
772 PyObject *o;
773 PyObject *dict;
774 long val;
775 PyObject *mangled = _Py_Mangle(st->st_private, name);
777 if (!mangled)
778 return 0;
779 dict = st->st_cur->ste_symbols;
780 if ((o = PyDict_GetItem(dict, mangled))) {
781 val = PyInt_AS_LONG(o);
782 if ((flag & DEF_PARAM) && (val & DEF_PARAM)) {
783 /* Is it better to use 'mangled' or 'name' here? */
784 PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT,
785 PyString_AsString(name));
786 PyErr_SyntaxLocation(st->st_filename,
787 st->st_cur->ste_lineno);
788 goto error;
790 val |= flag;
791 } else
792 val = flag;
793 o = PyInt_FromLong(val);
794 if (o == NULL)
795 goto error;
796 if (PyDict_SetItem(dict, mangled, o) < 0) {
797 Py_DECREF(o);
798 goto error;
800 Py_DECREF(o);
802 if (flag & DEF_PARAM) {
803 if (PyList_Append(st->st_cur->ste_varnames, mangled) < 0)
804 goto error;
805 } else if (flag & DEF_GLOBAL) {
806 /* XXX need to update DEF_GLOBAL for other flags too;
807 perhaps only DEF_FREE_GLOBAL */
808 val = flag;
809 if ((o = PyDict_GetItem(st->st_global, mangled))) {
810 val |= PyInt_AS_LONG(o);
812 o = PyInt_FromLong(val);
813 if (o == NULL)
814 goto error;
815 if (PyDict_SetItem(st->st_global, mangled, o) < 0) {
816 Py_DECREF(o);
817 goto error;
819 Py_DECREF(o);
821 Py_DECREF(mangled);
822 return 1;
824 error:
825 Py_DECREF(mangled);
826 return 0;
829 /* VISIT, VISIT_SEQ and VIST_SEQ_TAIL take an ASDL type as their second argument.
830 They use the ASDL name to synthesize the name of the C type and the visit
831 function.
833 VISIT_SEQ_TAIL permits the start of an ASDL sequence to be skipped, which is
834 useful if the first node in the sequence requires special treatment.
837 #define VISIT(ST, TYPE, V) \
838 if (!symtable_visit_ ## TYPE((ST), (V))) \
839 return 0;
841 #define VISIT_IN_BLOCK(ST, TYPE, V, S) \
842 if (!symtable_visit_ ## TYPE((ST), (V))) { \
843 symtable_exit_block((ST), (S)); \
844 return 0; \
847 #define VISIT_SEQ(ST, TYPE, SEQ) { \
848 int i; \
849 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
850 for (i = 0; i < asdl_seq_LEN(seq); i++) { \
851 TYPE ## _ty elt = asdl_seq_GET(seq, i); \
852 if (!symtable_visit_ ## TYPE((ST), elt)) \
853 return 0; \
857 #define VISIT_SEQ_IN_BLOCK(ST, TYPE, SEQ, S) { \
858 int i; \
859 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
860 for (i = 0; i < asdl_seq_LEN(seq); i++) { \
861 TYPE ## _ty elt = asdl_seq_GET(seq, i); \
862 if (!symtable_visit_ ## TYPE((ST), elt)) { \
863 symtable_exit_block((ST), (S)); \
864 return 0; \
869 #define VISIT_SEQ_TAIL(ST, TYPE, SEQ, START) { \
870 int i; \
871 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
872 for (i = (START); i < asdl_seq_LEN(seq); i++) { \
873 TYPE ## _ty elt = asdl_seq_GET(seq, i); \
874 if (!symtable_visit_ ## TYPE((ST), elt)) \
875 return 0; \
879 #define VISIT_SEQ_TAIL_IN_BLOCK(ST, TYPE, SEQ, START, S) { \
880 int i; \
881 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
882 for (i = (START); i < asdl_seq_LEN(seq); i++) { \
883 TYPE ## _ty elt = asdl_seq_GET(seq, i); \
884 if (!symtable_visit_ ## TYPE((ST), elt)) { \
885 symtable_exit_block((ST), (S)); \
886 return 0; \
891 static int
892 symtable_visit_stmt(struct symtable *st, stmt_ty s)
894 switch (s->kind) {
895 case FunctionDef_kind:
896 if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL))
897 return 0;
898 if (s->v.FunctionDef.args->defaults)
899 VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults);
900 if (s->v.FunctionDef.decorators)
901 VISIT_SEQ(st, expr, s->v.FunctionDef.decorators);
902 if (!symtable_enter_block(st, s->v.FunctionDef.name,
903 FunctionBlock, (void *)s, s->lineno))
904 return 0;
905 VISIT_IN_BLOCK(st, arguments, s->v.FunctionDef.args, s);
906 VISIT_SEQ_IN_BLOCK(st, stmt, s->v.FunctionDef.body, s);
907 if (!symtable_exit_block(st, s))
908 return 0;
909 break;
910 case ClassDef_kind: {
911 PyObject *tmp;
912 if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL))
913 return 0;
914 VISIT_SEQ(st, expr, s->v.ClassDef.bases);
915 if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock,
916 (void *)s, s->lineno))
917 return 0;
918 tmp = st->st_private;
919 st->st_private = s->v.ClassDef.name;
920 VISIT_SEQ_IN_BLOCK(st, stmt, s->v.ClassDef.body, s);
921 st->st_private = tmp;
922 if (!symtable_exit_block(st, s))
923 return 0;
924 break;
926 case Return_kind:
927 if (s->v.Return.value)
928 VISIT(st, expr, s->v.Return.value);
929 break;
930 case Delete_kind:
931 VISIT_SEQ(st, expr, s->v.Delete.targets);
932 break;
933 case Assign_kind:
934 VISIT_SEQ(st, expr, s->v.Assign.targets);
935 VISIT(st, expr, s->v.Assign.value);
936 break;
937 case AugAssign_kind:
938 VISIT(st, expr, s->v.AugAssign.target);
939 VISIT(st, expr, s->v.AugAssign.value);
940 break;
941 case Print_kind:
942 if (s->v.Print.dest)
943 VISIT(st, expr, s->v.Print.dest);
944 VISIT_SEQ(st, expr, s->v.Print.values);
945 break;
946 case For_kind:
947 VISIT(st, expr, s->v.For.target);
948 VISIT(st, expr, s->v.For.iter);
949 VISIT_SEQ(st, stmt, s->v.For.body);
950 if (s->v.For.orelse)
951 VISIT_SEQ(st, stmt, s->v.For.orelse);
952 break;
953 case While_kind:
954 VISIT(st, expr, s->v.While.test);
955 VISIT_SEQ(st, stmt, s->v.While.body);
956 if (s->v.While.orelse)
957 VISIT_SEQ(st, stmt, s->v.While.orelse);
958 break;
959 case If_kind:
960 /* XXX if 0: and lookup_yield() hacks */
961 VISIT(st, expr, s->v.If.test);
962 VISIT_SEQ(st, stmt, s->v.If.body);
963 if (s->v.If.orelse)
964 VISIT_SEQ(st, stmt, s->v.If.orelse);
965 break;
966 case Raise_kind:
967 if (s->v.Raise.type) {
968 VISIT(st, expr, s->v.Raise.type);
969 if (s->v.Raise.inst) {
970 VISIT(st, expr, s->v.Raise.inst);
971 if (s->v.Raise.tback)
972 VISIT(st, expr, s->v.Raise.tback);
975 break;
976 case TryExcept_kind:
977 VISIT_SEQ(st, stmt, s->v.TryExcept.body);
978 VISIT_SEQ(st, stmt, s->v.TryExcept.orelse);
979 VISIT_SEQ(st, excepthandler, s->v.TryExcept.handlers);
980 break;
981 case TryFinally_kind:
982 VISIT_SEQ(st, stmt, s->v.TryFinally.body);
983 VISIT_SEQ(st, stmt, s->v.TryFinally.finalbody);
984 break;
985 case Assert_kind:
986 VISIT(st, expr, s->v.Assert.test);
987 if (s->v.Assert.msg)
988 VISIT(st, expr, s->v.Assert.msg);
989 break;
990 case Import_kind:
991 VISIT_SEQ(st, alias, s->v.Import.names);
992 /* XXX Don't have the lineno available inside
993 visit_alias */
994 if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno)
995 st->st_cur->ste_opt_lineno = s->lineno;
996 break;
997 case ImportFrom_kind:
998 VISIT_SEQ(st, alias, s->v.ImportFrom.names);
999 /* XXX Don't have the lineno available inside
1000 visit_alias */
1001 if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno)
1002 st->st_cur->ste_opt_lineno = s->lineno;
1003 break;
1004 case Exec_kind:
1005 VISIT(st, expr, s->v.Exec.body);
1006 if (!st->st_cur->ste_opt_lineno)
1007 st->st_cur->ste_opt_lineno = s->lineno;
1008 if (s->v.Exec.globals) {
1009 st->st_cur->ste_unoptimized |= OPT_EXEC;
1010 VISIT(st, expr, s->v.Exec.globals);
1011 if (s->v.Exec.locals)
1012 VISIT(st, expr, s->v.Exec.locals);
1013 } else {
1014 st->st_cur->ste_unoptimized |= OPT_BARE_EXEC;
1016 break;
1017 case Global_kind: {
1018 int i;
1019 asdl_seq *seq = s->v.Global.names;
1020 for (i = 0; i < asdl_seq_LEN(seq); i++) {
1021 identifier name = asdl_seq_GET(seq, i);
1022 char *c_name = PyString_AS_STRING(name);
1023 long cur = symtable_lookup(st, name);
1024 if (cur < 0)
1025 return 0;
1026 if (cur & (DEF_LOCAL | USE)) {
1027 char buf[256];
1028 if (cur & DEF_LOCAL)
1029 PyOS_snprintf(buf, sizeof(buf),
1030 GLOBAL_AFTER_ASSIGN,
1031 c_name);
1032 else
1033 PyOS_snprintf(buf, sizeof(buf),
1034 GLOBAL_AFTER_USE,
1035 c_name);
1036 if (!symtable_warn(st, buf, s->lineno))
1037 return 0;
1039 if (!symtable_add_def(st, name, DEF_GLOBAL))
1040 return 0;
1042 break;
1044 case Expr_kind:
1045 VISIT(st, expr, s->v.Expr.value);
1046 break;
1047 case Pass_kind:
1048 case Break_kind:
1049 case Continue_kind:
1050 /* nothing to do here */
1051 break;
1053 return 1;
1056 static int
1057 symtable_visit_expr(struct symtable *st, expr_ty e)
1059 switch (e->kind) {
1060 case BoolOp_kind:
1061 VISIT_SEQ(st, expr, e->v.BoolOp.values);
1062 break;
1063 case BinOp_kind:
1064 VISIT(st, expr, e->v.BinOp.left);
1065 VISIT(st, expr, e->v.BinOp.right);
1066 break;
1067 case UnaryOp_kind:
1068 VISIT(st, expr, e->v.UnaryOp.operand);
1069 break;
1070 case Lambda_kind: {
1071 if (!symtable_add_def(st, GET_IDENTIFIER(lambda), DEF_LOCAL))
1072 return 0;
1073 if (e->v.Lambda.args->defaults)
1074 VISIT_SEQ(st, expr, e->v.Lambda.args->defaults);
1075 /* XXX how to get line numbers for expressions */
1076 if (!symtable_enter_block(st, GET_IDENTIFIER(lambda),
1077 FunctionBlock, (void *)e, 0))
1078 return 0;
1079 VISIT_IN_BLOCK(st, arguments, e->v.Lambda.args, (void*)e);
1080 VISIT_IN_BLOCK(st, expr, e->v.Lambda.body, (void*)e);
1081 if (!symtable_exit_block(st, (void *)e))
1082 return 0;
1083 break;
1085 case Dict_kind:
1086 VISIT_SEQ(st, expr, e->v.Dict.keys);
1087 VISIT_SEQ(st, expr, e->v.Dict.values);
1088 break;
1089 case ListComp_kind: {
1090 char tmpname[256];
1091 identifier tmp;
1093 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]",
1094 ++st->st_cur->ste_tmpname);
1095 tmp = PyString_InternFromString(tmpname);
1096 if (!symtable_add_def(st, tmp, DEF_LOCAL))
1097 return 0;
1098 Py_DECREF(tmp);
1099 VISIT(st, expr, e->v.ListComp.elt);
1100 VISIT_SEQ(st, comprehension, e->v.ListComp.generators);
1101 break;
1103 case GeneratorExp_kind: {
1104 if (!symtable_visit_genexp(st, e)) {
1105 return 0;
1107 break;
1109 case Yield_kind:
1110 if (e->v.Yield.value)
1111 VISIT(st, expr, e->v.Yield.value);
1112 st->st_cur->ste_generator = 1;
1113 break;
1114 case Compare_kind:
1115 VISIT(st, expr, e->v.Compare.left);
1116 VISIT_SEQ(st, expr, e->v.Compare.comparators);
1117 break;
1118 case Call_kind:
1119 VISIT(st, expr, e->v.Call.func);
1120 VISIT_SEQ(st, expr, e->v.Call.args);
1121 VISIT_SEQ(st, keyword, e->v.Call.keywords);
1122 if (e->v.Call.starargs)
1123 VISIT(st, expr, e->v.Call.starargs);
1124 if (e->v.Call.kwargs)
1125 VISIT(st, expr, e->v.Call.kwargs);
1126 break;
1127 case Repr_kind:
1128 VISIT(st, expr, e->v.Repr.value);
1129 break;
1130 case Num_kind:
1131 case Str_kind:
1132 /* Nothing to do here. */
1133 break;
1134 /* The following exprs can be assignment targets. */
1135 case Attribute_kind:
1136 VISIT(st, expr, e->v.Attribute.value);
1137 break;
1138 case Subscript_kind:
1139 VISIT(st, expr, e->v.Subscript.value);
1140 VISIT(st, slice, e->v.Subscript.slice);
1141 break;
1142 case Name_kind:
1143 if (!symtable_add_def(st, e->v.Name.id,
1144 e->v.Name.ctx == Load ? USE : DEF_LOCAL))
1145 return 0;
1146 break;
1147 /* child nodes of List and Tuple will have expr_context set */
1148 case List_kind:
1149 VISIT_SEQ(st, expr, e->v.List.elts);
1150 break;
1151 case Tuple_kind:
1152 VISIT_SEQ(st, expr, e->v.Tuple.elts);
1153 break;
1155 return 1;
1158 static int
1159 symtable_implicit_arg(struct symtable *st, int pos)
1161 PyObject *id = PyString_FromFormat(".%d", pos);
1162 if (id == NULL)
1163 return 0;
1164 if (!symtable_add_def(st, id, DEF_PARAM)) {
1165 Py_DECREF(id);
1166 return 0;
1168 Py_DECREF(id);
1169 return 1;
1172 static int
1173 symtable_visit_params(struct symtable *st, asdl_seq *args, int toplevel)
1175 int i;
1177 /* go through all the toplevel arguments first */
1178 for (i = 0; i < asdl_seq_LEN(args); i++) {
1179 expr_ty arg = asdl_seq_GET(args, i);
1180 if (arg->kind == Name_kind) {
1181 assert(arg->v.Name.ctx == Param ||
1182 (arg->v.Name.ctx == Store && !toplevel));
1183 if (!symtable_add_def(st, arg->v.Name.id, DEF_PARAM))
1184 return 0;
1186 else if (arg->kind == Tuple_kind) {
1187 assert(arg->v.Tuple.ctx == Store);
1188 if (toplevel) {
1189 if (!symtable_implicit_arg(st, i))
1190 return 0;
1193 else {
1194 PyErr_SetString(PyExc_SyntaxError,
1195 "invalid expression in parameter list");
1196 PyErr_SyntaxLocation(st->st_filename,
1197 st->st_cur->ste_lineno);
1198 return 0;
1202 if (!toplevel) {
1203 if (!symtable_visit_params_nested(st, args))
1204 return 0;
1207 return 1;
1210 static int
1211 symtable_visit_params_nested(struct symtable *st, asdl_seq *args)
1213 int i;
1214 for (i = 0; i < asdl_seq_LEN(args); i++) {
1215 expr_ty arg = asdl_seq_GET(args, i);
1216 if (arg->kind == Tuple_kind &&
1217 !symtable_visit_params(st, arg->v.Tuple.elts, 0))
1218 return 0;
1221 return 1;
1224 static int
1225 symtable_visit_arguments(struct symtable *st, arguments_ty a)
1227 /* skip default arguments inside function block
1228 XXX should ast be different?
1230 if (a->args && !symtable_visit_params(st, a->args, 1))
1231 return 0;
1232 if (a->vararg) {
1233 if (!symtable_add_def(st, a->vararg, DEF_PARAM))
1234 return 0;
1235 st->st_cur->ste_varargs = 1;
1237 if (a->kwarg) {
1238 if (!symtable_add_def(st, a->kwarg, DEF_PARAM))
1239 return 0;
1240 st->st_cur->ste_varkeywords = 1;
1242 if (a->args && !symtable_visit_params_nested(st, a->args))
1243 return 0;
1244 return 1;
1248 static int
1249 symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh)
1251 if (eh->type)
1252 VISIT(st, expr, eh->type);
1253 if (eh->name)
1254 VISIT(st, expr, eh->name);
1255 VISIT_SEQ(st, stmt, eh->body);
1256 return 1;
1260 static int
1261 symtable_visit_alias(struct symtable *st, alias_ty a)
1263 /* Compute store_name, the name actually bound by the import
1264 operation. It is diferent than a->name when a->name is a
1265 dotted package name (e.g. spam.eggs)
1267 PyObject *store_name;
1268 PyObject *name = (a->asname == NULL) ? a->name : a->asname;
1269 const char *base = PyString_AS_STRING(name);
1270 char *dot = strchr(base, '.');
1271 if (dot)
1272 store_name = PyString_FromStringAndSize(base, dot - base);
1273 else {
1274 store_name = name;
1275 Py_INCREF(store_name);
1277 if (strcmp(PyString_AS_STRING(name), "*")) {
1278 int r = symtable_add_def(st, store_name, DEF_IMPORT);
1279 Py_DECREF(store_name);
1280 return r;
1282 else {
1283 if (st->st_cur->ste_type != ModuleBlock) {
1284 int lineno = st->st_cur->ste_lineno;
1285 if (!symtable_warn(st, IMPORT_STAR_WARNING, lineno)) {
1286 Py_DECREF(store_name);
1287 return 0;
1290 st->st_cur->ste_unoptimized |= OPT_IMPORT_STAR;
1291 Py_DECREF(store_name);
1292 return 1;
1297 static int
1298 symtable_visit_comprehension(struct symtable *st, comprehension_ty lc)
1300 VISIT(st, expr, lc->target);
1301 VISIT(st, expr, lc->iter);
1302 VISIT_SEQ(st, expr, lc->ifs);
1303 return 1;
1307 static int
1308 symtable_visit_keyword(struct symtable *st, keyword_ty k)
1310 VISIT(st, expr, k->value);
1311 return 1;
1315 static int
1316 symtable_visit_slice(struct symtable *st, slice_ty s)
1318 switch (s->kind) {
1319 case Slice_kind:
1320 if (s->v.Slice.lower)
1321 VISIT(st, expr, s->v.Slice.lower)
1322 if (s->v.Slice.upper)
1323 VISIT(st, expr, s->v.Slice.upper)
1324 if (s->v.Slice.step)
1325 VISIT(st, expr, s->v.Slice.step)
1326 break;
1327 case ExtSlice_kind:
1328 VISIT_SEQ(st, slice, s->v.ExtSlice.dims)
1329 break;
1330 case Index_kind:
1331 VISIT(st, expr, s->v.Index.value)
1332 break;
1333 case Ellipsis_kind:
1334 break;
1336 return 1;
1339 static int
1340 symtable_visit_genexp(struct symtable *st, expr_ty e)
1342 comprehension_ty outermost = ((comprehension_ty)
1343 (asdl_seq_GET(e->v.GeneratorExp.generators, 0)));
1344 /* Outermost iterator is evaluated in current scope */
1345 VISIT(st, expr, outermost->iter);
1346 /* Create generator scope for the rest */
1347 if (!symtable_enter_block(st, GET_IDENTIFIER(genexpr),
1348 FunctionBlock, (void *)e, 0)) {
1349 return 0;
1351 st->st_cur->ste_generator = 1;
1352 /* Outermost iter is received as an argument */
1353 if (!symtable_implicit_arg(st, 0)) {
1354 symtable_exit_block(st, (void *)e);
1355 return 0;
1357 VISIT_IN_BLOCK(st, expr, outermost->target, (void*)e);
1358 VISIT_SEQ_IN_BLOCK(st, expr, outermost->ifs, (void*)e);
1359 VISIT_SEQ_TAIL_IN_BLOCK(st, comprehension,
1360 e->v.GeneratorExp.generators, 1, (void*)e);
1361 VISIT_IN_BLOCK(st, expr, e->v.GeneratorExp.elt, (void*)e);
1362 if (!symtable_exit_block(st, (void *)e))
1363 return 0;
1364 return 1;