blob: fad7cec638df63d1ff4a8a3263627a237c88d120 [file] [log] [blame]
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +00001#include "Python.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002#include "Python-ast.h"
3#include "code.h"
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +00004#include "symtable.h"
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +00005#include "structmember.h"
6
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007/* two error strings used for warnings */
8#define GLOBAL_AFTER_ASSIGN \
9"name '%.400s' is assigned to before global declaration"
Jeremy Hylton29906402001-12-10 00:53:18 +000010
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000011#define GLOBAL_AFTER_USE \
12"name '%.400s' is used prior to global declaration"
Jeremy Hylton29906402001-12-10 00:53:18 +000013
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000014PySTEntryObject *
Neal Norwitz62c2fac2005-10-24 00:30:44 +000015PySTEntry_New(struct symtable *st, identifier name, _Py_block_ty block,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000016 void *key, int lineno)
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000017{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000018 PySTEntryObject *ste = NULL;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +000019 PyObject *k;
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000020
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000021 k = PyLong_FromVoidPtr(key);
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000022 if (k == NULL)
23 goto fail;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000024 ste = (PySTEntryObject *)PyObject_New(PySTEntryObject,
25 &PySTEntry_Type);
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000026 ste->ste_table = st;
27 ste->ste_id = k;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028 ste->ste_tmpname = 0;
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000029
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000030 ste->ste_name = name;
31 Py_INCREF(name);
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000032
Neal Norwitzb6fc9df2005-11-13 18:50:34 +000033 ste->ste_symbols = NULL;
34 ste->ste_varnames = NULL;
35 ste->ste_children = NULL;
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000036
Neal Norwitzb6fc9df2005-11-13 18:50:34 +000037 ste->ste_symbols = PyDict_New();
38 if (ste->ste_symbols == NULL)
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000039 goto fail;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +000040
41 ste->ste_varnames = PyList_New(0);
42 if (ste->ste_varnames == NULL)
43 goto fail;
44
45 ste->ste_children = PyList_New(0);
46 if (ste->ste_children == NULL)
47 goto fail;
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000048
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000049 ste->ste_type = block;
50 ste->ste_unoptimized = 0;
51 ste->ste_nested = 0;
52 ste->ste_free = 0;
53 ste->ste_varargs = 0;
54 ste->ste_varkeywords = 0;
Jeremy Hylton86424e32001-12-04 02:41:46 +000055 ste->ste_opt_lineno = 0;
Jeremy Hylton4d508ad2003-05-21 17:34:50 +000056 ste->ste_tmpname = 0;
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000057 ste->ste_lineno = lineno;
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000058
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000059 if (st->st_cur != NULL &&
60 (st->st_cur->ste_nested ||
61 st->st_cur->ste_type == FunctionBlock))
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000062 ste->ste_nested = 1;
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000063 ste->ste_child_free = 0;
Tim Peters5ca576e2001-06-18 22:08:13 +000064 ste->ste_generator = 0;
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000065
66 if (PyDict_SetItem(st->st_symbols, ste->ste_id, (PyObject *)ste) < 0)
67 goto fail;
Jeremy Hylton74b3bc42001-02-23 17:55:27 +000068
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000069 return ste;
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000070 fail:
71 Py_XDECREF(ste);
72 return NULL;
73}
74
75static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076ste_repr(PySTEntryObject *ste)
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000077{
78 char buf[256];
79
Barry Warsaw4b4ab202001-11-28 21:36:28 +000080 PyOS_snprintf(buf, sizeof(buf),
81 "<symtable entry %.100s(%ld), line %d>",
82 PyString_AS_STRING(ste->ste_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000083 PyInt_AS_LONG(ste->ste_id), ste->ste_lineno);
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000084 return PyString_FromString(buf);
85}
86
87static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000088ste_dealloc(PySTEntryObject *ste)
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +000089{
90 ste->ste_table = NULL;
91 Py_XDECREF(ste->ste_id);
92 Py_XDECREF(ste->ste_name);
93 Py_XDECREF(ste->ste_symbols);
94 Py_XDECREF(ste->ste_varnames);
95 Py_XDECREF(ste->ste_children);
96 PyObject_Del(ste);
97}
98
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000099#define OFF(x) offsetof(PySTEntryObject, x)
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +0000100
Guido van Rossum6f799372001-09-20 20:46:19 +0000101static PyMemberDef ste_memberlist[] = {
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +0000102 {"id", T_OBJECT, OFF(ste_id), READONLY},
103 {"name", T_OBJECT, OFF(ste_name), READONLY},
104 {"symbols", T_OBJECT, OFF(ste_symbols), READONLY},
105 {"varnames", T_OBJECT, OFF(ste_varnames), READONLY},
106 {"children", T_OBJECT, OFF(ste_children), READONLY},
107 {"type", T_INT, OFF(ste_type), READONLY},
108 {"lineno", T_INT, OFF(ste_lineno), READONLY},
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +0000109 {NULL}
110};
111
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000112PyTypeObject PySTEntry_Type = {
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +0000113 PyObject_HEAD_INIT(&PyType_Type)
114 0,
115 "symtable entry",
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000116 sizeof(PySTEntryObject),
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +0000117 0,
118 (destructor)ste_dealloc, /* tp_dealloc */
119 0, /* tp_print */
Guido van Rossum6f799372001-09-20 20:46:19 +0000120 0, /* tp_getattr */
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +0000121 0, /* tp_setattr */
122 0, /* tp_compare */
123 (reprfunc)ste_repr, /* tp_repr */
124 0, /* tp_as_number */
125 0, /* tp_as_sequence */
126 0, /* tp_as_mapping */
127 0, /* tp_hash */
128 0, /* tp_call */
129 0, /* tp_str */
Guido van Rossum6f799372001-09-20 20:46:19 +0000130 PyObject_GenericGetAttr, /* tp_getattro */
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +0000131 0, /* tp_setattro */
132 0, /* tp_as_buffer */
133 Py_TPFLAGS_DEFAULT, /* tp_flags */
134 0, /* tp_doc */
Guido van Rossum6f799372001-09-20 20:46:19 +0000135 0, /* tp_traverse */
136 0, /* tp_clear */
137 0, /* tp_richcompare */
138 0, /* tp_weaklistoffset */
139 0, /* tp_iter */
140 0, /* tp_iternext */
141 0, /* tp_methods */
142 ste_memberlist, /* tp_members */
143 0, /* tp_getset */
144 0, /* tp_base */
145 0, /* tp_dict */
146 0, /* tp_descr_get */
147 0, /* tp_descr_set */
148 0, /* tp_dictoffset */
149 0, /* tp_init */
150 0, /* tp_alloc */
151 0, /* tp_new */
Jeremy Hyltoncb17ae82001-02-09 22:22:18 +0000152};
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153
154static int symtable_analyze(struct symtable *st);
155static int symtable_warn(struct symtable *st, char *msg);
156static int symtable_enter_block(struct symtable *st, identifier name,
Neal Norwitz62c2fac2005-10-24 00:30:44 +0000157 _Py_block_ty block, void *ast, int lineno);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000158static int symtable_exit_block(struct symtable *st, void *ast);
159static int symtable_visit_stmt(struct symtable *st, stmt_ty s);
160static int symtable_visit_expr(struct symtable *st, expr_ty s);
161static int symtable_visit_genexp(struct symtable *st, expr_ty s);
162static int symtable_visit_arguments(struct symtable *st, arguments_ty);
163static int symtable_visit_excepthandler(struct symtable *st, excepthandler_ty);
164static int symtable_visit_alias(struct symtable *st, alias_ty);
165static int symtable_visit_comprehension(struct symtable *st, comprehension_ty);
166static int symtable_visit_keyword(struct symtable *st, keyword_ty);
167static int symtable_visit_slice(struct symtable *st, slice_ty);
168static int symtable_visit_params(struct symtable *st, asdl_seq *args, int top);
169static int symtable_visit_params_nested(struct symtable *st, asdl_seq *args);
170static int symtable_implicit_arg(struct symtable *st, int pos);
171
172
Nick Coghlan99b25332005-11-16 12:45:24 +0000173static identifier top = NULL, lambda = NULL, genexpr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174
175#define GET_IDENTIFIER(VAR) \
176 ((VAR) ? (VAR) : ((VAR) = PyString_InternFromString(# VAR)))
177
178#define DUPLICATE_ARGUMENT \
179"duplicate argument '%s' in function definition"
180
181static struct symtable *
182symtable_new(void)
183{
184 struct symtable *st;
185
186 st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable));
187 if (st == NULL)
188 return NULL;
189
190 st->st_filename = NULL;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000191 st->st_symbols = NULL;
192
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193 if ((st->st_stack = PyList_New(0)) == NULL)
194 goto fail;
195 if ((st->st_symbols = PyDict_New()) == NULL)
196 goto fail;
197 st->st_cur = NULL;
198 st->st_tmpname = 0;
199 st->st_private = NULL;
200 return st;
201 fail:
202 PySymtable_Free(st);
203 return NULL;
204}
205
206struct symtable *
207PySymtable_Build(mod_ty mod, const char *filename, PyFutureFeatures *future)
208{
209 struct symtable *st = symtable_new();
210 asdl_seq *seq;
211 int i;
212
213 if (st == NULL)
214 return st;
215 st->st_filename = filename;
216 st->st_future = future;
217 symtable_enter_block(st, GET_IDENTIFIER(top), ModuleBlock,
218 (void *)mod, 0);
219 st->st_top = st->st_cur;
220 st->st_cur->ste_unoptimized = OPT_TOPLEVEL;
221 /* Any other top-level initialization? */
222 switch (mod->kind) {
223 case Module_kind:
224 seq = mod->v.Module.body;
225 for (i = 0; i < asdl_seq_LEN(seq); i++)
226 if (!symtable_visit_stmt(st, asdl_seq_GET(seq, i)))
227 goto error;
228 break;
229 case Expression_kind:
230 if (!symtable_visit_expr(st, mod->v.Expression.body))
231 goto error;
232 break;
233 case Interactive_kind:
234 seq = mod->v.Interactive.body;
235 for (i = 0; i < asdl_seq_LEN(seq); i++)
236 if (!symtable_visit_stmt(st, asdl_seq_GET(seq, i)))
237 goto error;
238 break;
239 case Suite_kind:
240 PyErr_SetString(PyExc_RuntimeError,
241 "this compiler does not handle Suites");
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000242 goto error;
243 }
244 if (!symtable_exit_block(st, (void *)mod)) {
245 PySymtable_Free(st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000246 return NULL;
247 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000248 if (symtable_analyze(st))
249 return st;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000250 PySymtable_Free(st);
251 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252 error:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000253 (void) symtable_exit_block(st, (void *)mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254 PySymtable_Free(st);
255 return NULL;
256}
257
258void
259PySymtable_Free(struct symtable *st)
260{
261 Py_XDECREF(st->st_symbols);
262 Py_XDECREF(st->st_stack);
263 PyMem_Free((void *)st);
264}
265
266PySTEntryObject *
267PySymtable_Lookup(struct symtable *st, void *key)
268{
269 PyObject *k, *v;
270
271 k = PyLong_FromVoidPtr(key);
272 if (k == NULL)
273 return NULL;
274 v = PyDict_GetItem(st->st_symbols, k);
275 if (v) {
276 assert(PySTEntry_Check(v));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277 Py_INCREF(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000278 }
279 else {
280 PyErr_SetString(PyExc_KeyError,
281 "unknown symbol table entry");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000282 }
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000283
284 Py_DECREF(k);
285 return (PySTEntryObject *)v;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286}
287
288int
289PyST_GetScope(PySTEntryObject *ste, PyObject *name)
290{
291 PyObject *v = PyDict_GetItem(ste->ste_symbols, name);
292 if (!v)
293 return 0;
294 assert(PyInt_Check(v));
295 return (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
296}
297
298
299/* Analyze raw symbol information to determine scope of each name.
300
301 The next several functions are helpers for PySymtable_Analyze(),
302 which determines whether a name is local, global, or free. In addition,
303 it determines which local variables are cell variables; they provide
304 bindings that are used for free variables in enclosed blocks.
305
306 There are also two kinds of free variables, implicit and explicit. An
307 explicit global is declared with the global statement. An implicit
308 global is a free variable for which the compiler has found no binding
309 in an enclosing function scope. The implicit global is either a global
310 or a builtin. Python's module and class blocks use the xxx_NAME opcodes
311 to handle these names to implement slightly odd semantics. In such a
312 block, the name is treated as global until it is assigned to; then it
313 is treated as a local.
314
315 The symbol table requires two passes to determine the scope of each name.
316 The first pass collects raw facts from the AST: the name is a parameter
317 here, the name is used by not defined here, etc. The second pass analyzes
318 these facts during a pass over the PySTEntryObjects created during pass 1.
319
320 When a function is entered during the second pass, the parent passes
321 the set of all name bindings visible to its children. These bindings
322 are used to determine if the variable is free or an implicit global.
323 After doing the local analysis, it analyzes each of its child blocks
324 using an updated set of name bindings.
325
326 The children update the free variable set. If a local variable is free
327 in a child, the variable is marked as a cell. The current function must
328 provide runtime storage for the variable that may outlive the function's
329 frame. Cell variables are removed from the free set before the analyze
330 function returns to its parent.
331
332 The sets of bound and free variables are implemented as dictionaries
333 mapping strings to None.
334*/
335
336#define SET_SCOPE(DICT, NAME, I) { \
337 PyObject *o = PyInt_FromLong(I); \
338 if (!o) \
339 return 0; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000340 if (PyDict_SetItem((DICT), (NAME), o) < 0) { \
341 Py_DECREF(o); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342 return 0; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000343 } \
344 Py_DECREF(o); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345}
346
347/* Decide on scope of name, given flags.
348
349 The dicts passed in as arguments are modified as necessary.
350 ste is passed so that flags can be updated.
351*/
352
353static int
354analyze_name(PySTEntryObject *ste, PyObject *dict, PyObject *name, int flags,
355 PyObject *bound, PyObject *local, PyObject *free,
356 PyObject *global)
357{
358 if (flags & DEF_GLOBAL) {
359 if (flags & DEF_PARAM) {
360 PyErr_Format(PyExc_SyntaxError,
361 "name '%s' is local and global",
362 PyString_AS_STRING(name));
363 return 0;
364 }
365 SET_SCOPE(dict, name, GLOBAL_EXPLICIT);
366 if (PyDict_SetItem(global, name, Py_None) < 0)
367 return 0;
368 if (bound && PyDict_GetItem(bound, name)) {
369 if (PyDict_DelItem(bound, name) < 0)
370 return 0;
371 }
372 return 1;
373 }
374 if (flags & DEF_BOUND) {
375 SET_SCOPE(dict, name, LOCAL);
376 if (PyDict_SetItem(local, name, Py_None) < 0)
377 return 0;
378 if (PyDict_GetItem(global, name)) {
379 if (PyDict_DelItem(global, name) < 0)
380 return 0;
381 }
382 return 1;
383 }
384 /* If an enclosing block has a binding for this name, it
385 is a free variable rather than a global variable.
386 Note that having a non-NULL bound implies that the block
387 is nested.
388 */
389 if (bound && PyDict_GetItem(bound, name)) {
390 SET_SCOPE(dict, name, FREE);
391 ste->ste_free = 1;
392 if (PyDict_SetItem(free, name, Py_None) < 0)
393 return 0;
394 return 1;
395 }
396 /* If a parent has a global statement, then call it global
397 explicit? It could also be global implicit.
398 */
399 else if (global && PyDict_GetItem(global, name)) {
400 SET_SCOPE(dict, name, GLOBAL_EXPLICIT);
401 return 1;
402 }
403 else {
404 if (ste->ste_nested)
405 ste->ste_free = 1;
406 SET_SCOPE(dict, name, GLOBAL_IMPLICIT);
407 return 1;
408 }
409 return 0; /* Can't get here */
410}
411
412#undef SET_SCOPE
413
414/* If a name is defined in free and also in locals, then this block
415 provides the binding for the free variable. The name should be
416 marked CELL in this block and removed from the free list.
417
418 Note that the current block's free variables are included in free.
419 That's safe because no name can be free and local in the same scope.
420*/
421
422static int
423analyze_cells(PyObject *scope, PyObject *free)
424{
425 PyObject *name, *v, *w;
426 int flags, pos = 0, success = 0;
427
428 w = PyInt_FromLong(CELL);
429 if (!w)
430 return 0;
431 while (PyDict_Next(scope, &pos, &name, &v)) {
432 assert(PyInt_Check(v));
433 flags = PyInt_AS_LONG(v);
434 if (flags != LOCAL)
435 continue;
436 if (!PyDict_GetItem(free, name))
437 continue;
438 /* Replace LOCAL with CELL for this name, and remove
439 from free. It is safe to replace the value of name
440 in the dict, because it will not cause a resize.
441 */
442 if (PyDict_SetItem(scope, name, w) < 0)
443 goto error;
444 if (!PyDict_DelItem(free, name) < 0)
445 goto error;
446 }
447 success = 1;
448 error:
449 Py_DECREF(w);
450 return success;
451}
452
453/* Check for illegal statements in unoptimized namespaces */
454static int
455check_unoptimized(const PySTEntryObject* ste) {
456 char buf[300];
Armin Rigo31441302005-10-21 12:57:31 +0000457 const char* trailer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458
Neil Schemenauer2dfcef52005-10-23 18:50:36 +0000459 if (ste->ste_type != FunctionBlock || !ste->ste_unoptimized
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460 || !(ste->ste_free || ste->ste_child_free))
461 return 1;
462
Armin Rigo31441302005-10-21 12:57:31 +0000463 trailer = (ste->ste_child_free ?
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000464 "contains a nested function with free variables" :
465 "is a nested function");
466
467 switch (ste->ste_unoptimized) {
468 case OPT_TOPLEVEL: /* exec / import * at top-level is fine */
469 case OPT_EXEC: /* qualified exec is fine */
470 return 1;
471 case OPT_IMPORT_STAR:
472 PyOS_snprintf(buf, sizeof(buf),
473 "import * is not allowed in function '%.100s' "
474 "because it is %s",
475 PyString_AS_STRING(ste->ste_name), trailer);
476 break;
477 case OPT_BARE_EXEC:
478 PyOS_snprintf(buf, sizeof(buf),
479 "unqualified exec is not allowed in function "
480 "'%.100s' it %s",
481 PyString_AS_STRING(ste->ste_name), trailer);
482 break;
483 default:
484 PyOS_snprintf(buf, sizeof(buf),
485 "function '%.100s' uses import * and bare exec, "
486 "which are illegal because it %s",
487 PyString_AS_STRING(ste->ste_name), trailer);
488 break;
489 }
490
491 PyErr_SetString(PyExc_SyntaxError, buf);
492 PyErr_SyntaxLocation(ste->ste_table->st_filename,
493 ste->ste_opt_lineno);
494 return 0;
495}
496
497/* Enter the final scope information into the st_symbols dict.
498 *
499 * All arguments are dicts. Modifies symbols, others are read-only.
500*/
501static int
502update_symbols(PyObject *symbols, PyObject *scope,
503 PyObject *bound, PyObject *free, int class)
504{
505 PyObject *name, *v, *u, *w, *free_value = NULL;
506 int i, flags, pos = 0;
507
508 while (PyDict_Next(symbols, &pos, &name, &v)) {
509 assert(PyInt_Check(v));
510 flags = PyInt_AS_LONG(v);
511 w = PyDict_GetItem(scope, name);
512 assert(w && PyInt_Check(w));
513 i = PyInt_AS_LONG(w);
514 flags |= (i << SCOPE_OFF);
515 u = PyInt_FromLong(flags);
516 if (PyDict_SetItem(symbols, name, u) < 0) {
517 Py_DECREF(u);
518 return 0;
519 }
520 Py_DECREF(u);
521 }
522
523 free_value = PyInt_FromLong(FREE << SCOPE_OFF);
524 if (!free_value)
525 return 0;
526
527 /* add a free variable when it's only use is for creating a closure */
528 pos = 0;
529 while (PyDict_Next(free, &pos, &name, &v)) {
530 PyObject *o = PyDict_GetItem(symbols, name);
531
532 if (o) {
533 /* It could be a free variable in a method of
534 the class that has the same name as a local
535 or global in the class scope.
536 */
537 if (class &&
538 PyInt_AS_LONG(o) & (DEF_BOUND | DEF_GLOBAL)) {
539 int i = PyInt_AS_LONG(o) | DEF_FREE_CLASS;
540 o = PyInt_FromLong(i);
541 if (!o) {
542 Py_DECREF(free_value);
543 return 0;
544 }
545 if (PyDict_SetItem(symbols, name, o) < 0) {
546 Py_DECREF(o);
547 Py_DECREF(free_value);
548 return 0;
549 }
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000550 Py_DECREF(o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000551 }
552 /* else it's not free, probably a cell */
553 continue;
554 }
555 if (!PyDict_GetItem(bound, name))
556 continue; /* it's a global */
557
558 if (PyDict_SetItem(symbols, name, free_value) < 0) {
559 Py_DECREF(free_value);
560 return 0;
561 }
562 }
563 Py_DECREF(free_value);
564 return 1;
565}
566
567/* Make final symbol table decisions for block of ste.
568 Arguments:
569 ste -- current symtable entry (input/output)
570 bound -- set of variables bound in enclosing scopes (input)
571 free -- set of free variables in enclosed scopes (output)
572 globals -- set of declared global variables in enclosing scopes (input)
573*/
574
575static int
576analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free,
577 PyObject *global)
578{
579 PyObject *name, *v, *local = NULL, *scope = NULL, *newbound = NULL;
580 PyObject *newglobal = NULL, *newfree = NULL;
581 int i, flags, pos = 0, success = 0;
582
583 local = PyDict_New();
584 if (!local)
585 goto error;
586 scope = PyDict_New();
587 if (!scope)
588 goto error;
589 newglobal = PyDict_New();
590 if (!newglobal)
591 goto error;
592 newfree = PyDict_New();
593 if (!newfree)
594 goto error;
595 newbound = PyDict_New();
596 if (!newbound)
597 goto error;
598
599 if (ste->ste_type == ClassBlock) {
600 /* make a copy of globals before calling analyze_name(),
601 because global statements in the class have no effect
602 on nested functions.
603 */
604 if (PyDict_Update(newglobal, global) < 0)
605 goto error;
606 if (bound)
607 if (PyDict_Update(newbound, bound) < 0)
608 goto error;
609 }
610
611 assert(PySTEntry_Check(ste));
612 assert(PyDict_Check(ste->ste_symbols));
613 while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
614 flags = PyInt_AS_LONG(v);
615 if (!analyze_name(ste, scope, name, flags, bound, local, free,
616 global))
617 goto error;
618 }
619
620 if (ste->ste_type != ClassBlock) {
621 if (ste->ste_type == FunctionBlock) {
622 if (PyDict_Update(newbound, local) < 0)
623 goto error;
624 }
625 if (bound) {
626 if (PyDict_Update(newbound, bound) < 0)
627 goto error;
628 }
629 if (PyDict_Update(newglobal, global) < 0)
630 goto error;
631 }
632
633 /* Recursively call analyze_block() on each child block */
634 for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) {
635 PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
Armin Rigo31441302005-10-21 12:57:31 +0000636 PySTEntryObject* entry;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000637 assert(c && PySTEntry_Check(c));
Armin Rigo31441302005-10-21 12:57:31 +0000638 entry = (PySTEntryObject*)c;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639 if (!analyze_block(entry, newbound, newfree, newglobal))
640 goto error;
641 if (entry->ste_free || entry->ste_child_free)
642 ste->ste_child_free = 1;
643 }
644
645 if (ste->ste_type == FunctionBlock && !analyze_cells(scope, newfree))
646 goto error;
647 if (!update_symbols(ste->ste_symbols, scope, bound, newfree,
648 ste->ste_type == ClassBlock))
649 goto error;
650 if (!check_unoptimized(ste))
651 goto error;
652
653 if (PyDict_Update(free, newfree) < 0)
654 goto error;
655 success = 1;
656 error:
657 Py_XDECREF(local);
658 Py_XDECREF(scope);
659 Py_XDECREF(newbound);
660 Py_XDECREF(newglobal);
661 Py_XDECREF(newfree);
662 if (!success)
663 assert(PyErr_Occurred());
664 return success;
665}
666
667static int
668symtable_analyze(struct symtable *st)
669{
670 PyObject *free, *global;
671 int r;
672
673 free = PyDict_New();
674 if (!free)
675 return 0;
676 global = PyDict_New();
677 if (!global) {
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000678 Py_DECREF(free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000679 return 0;
680 }
681 r = analyze_block(st->st_top, NULL, free, global);
682 Py_DECREF(free);
683 Py_DECREF(global);
684 return r;
685}
686
687
688static int
689symtable_warn(struct symtable *st, char *msg)
690{
691 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, st->st_filename,
692 st->st_cur->ste_lineno, NULL, NULL) < 0) {
693 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
694 PyErr_SetString(PyExc_SyntaxError, msg);
695 PyErr_SyntaxLocation(st->st_filename,
696 st->st_cur->ste_lineno);
697 }
698 return 0;
699 }
700 return 1;
701}
702
703/* symtable_enter_block() gets a reference via PySTEntry_New().
704 This reference is released when the block is exited, via the DECREF
705 in symtable_exit_block().
706*/
707
708static int
709symtable_exit_block(struct symtable *st, void *ast)
710{
711 int end;
712
713 Py_DECREF(st->st_cur);
714 end = PyList_GET_SIZE(st->st_stack) - 1;
715 if (end >= 0) {
716 st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack,
717 end);
718 Py_INCREF(st->st_cur);
719 if (PySequence_DelItem(st->st_stack, end) < 0)
720 return 0;
721 }
722 return 1;
723}
724
725static int
Neal Norwitz62c2fac2005-10-24 00:30:44 +0000726symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000727 void *ast, int lineno)
728{
729 PySTEntryObject *prev = NULL;
730
731 if (st->st_cur) {
732 prev = st->st_cur;
733 if (PyList_Append(st->st_stack, (PyObject *)st->st_cur) < 0) {
734 Py_DECREF(st->st_cur);
735 return 0;
736 }
737 Py_DECREF(st->st_cur);
738 }
739 st->st_cur = PySTEntry_New(st, name, block, ast, lineno);
740 if (name == GET_IDENTIFIER(top))
741 st->st_global = st->st_cur->ste_symbols;
742 if (prev) {
743 if (PyList_Append(prev->ste_children,
744 (PyObject *)st->st_cur) < 0) {
745 return 0;
746 }
747 }
748 return 1;
749}
750
751static int
752symtable_lookup(struct symtable *st, PyObject *name)
753{
754 PyObject *o;
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000755 PyObject *mangled = _Py_Mangle(st->st_private, name);
756 if (!mangled)
757 return 0;
758 o = PyDict_GetItem(st->st_cur->ste_symbols, mangled);
759 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000760 if (!o)
761 return 0;
762 return PyInt_AsLong(o);
763}
764
765static int
766symtable_add_def(struct symtable *st, PyObject *name, int flag)
767{
768 PyObject *o;
769 PyObject *dict;
770 int val;
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000771 PyObject *mangled = _Py_Mangle(st->st_private, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000772
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000773 if (!mangled)
774 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000775 dict = st->st_cur->ste_symbols;
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000776 if ((o = PyDict_GetItem(dict, mangled))) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777 val = PyInt_AS_LONG(o);
778 if ((flag & DEF_PARAM) && (val & DEF_PARAM)) {
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000779 /* Is it better to use 'mangled' or 'name' here? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000780 PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT,
781 PyString_AsString(name));
782 PyErr_SyntaxLocation(st->st_filename,
783 st->st_cur->ste_lineno);
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000784 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785 }
786 val |= flag;
787 } else
788 val = flag;
789 o = PyInt_FromLong(val);
790 if (o == NULL)
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000791 goto error;
792 if (PyDict_SetItem(dict, mangled, o) < 0) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793 Py_DECREF(o);
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000794 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000795 }
796 Py_DECREF(o);
797
798 if (flag & DEF_PARAM) {
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000799 if (PyList_Append(st->st_cur->ste_varnames, mangled) < 0)
800 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000801 } else if (flag & DEF_GLOBAL) {
802 /* XXX need to update DEF_GLOBAL for other flags too;
803 perhaps only DEF_FREE_GLOBAL */
804 val = flag;
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000805 if ((o = PyDict_GetItem(st->st_global, mangled))) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000806 val |= PyInt_AS_LONG(o);
807 }
808 o = PyInt_FromLong(val);
809 if (o == NULL)
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000810 goto error;
811 if (PyDict_SetItem(st->st_global, mangled, o) < 0) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000812 Py_DECREF(o);
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000813 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000814 }
815 Py_DECREF(o);
816 }
817 return 1;
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000818
819error:
820 Py_DECREF(mangled);
821 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000822}
823
824/* VISIT, VISIT_SEQ and VIST_SEQ_TAIL take an ASDL type as their second argument.
825 They use the ASDL name to synthesize the name of the C type and the visit
826 function.
827
828 VISIT_SEQ_TAIL permits the start of an ASDL sequence to be skipped, which is
829 useful if the first node in the sequence requires special treatment.
830*/
831
832#define VISIT(ST, TYPE, V) \
833 if (!symtable_visit_ ## TYPE((ST), (V))) \
834 return 0;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000835
836#define VISIT_IN_BLOCK(ST, TYPE, V, S) \
837 if (!symtable_visit_ ## TYPE((ST), (V))) { \
838 symtable_exit_block((ST), (S)); \
839 return 0; \
840 }
841
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000842#define VISIT_SEQ(ST, TYPE, SEQ) { \
843 int i; \
844 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
845 for (i = 0; i < asdl_seq_LEN(seq); i++) { \
846 TYPE ## _ty elt = asdl_seq_GET(seq, i); \
847 if (!symtable_visit_ ## TYPE((ST), elt)) \
848 return 0; \
849 } \
850}
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000851
852#define VISIT_SEQ_IN_BLOCK(ST, TYPE, SEQ, S) { \
853 int i; \
854 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
855 for (i = 0; i < asdl_seq_LEN(seq); i++) { \
856 TYPE ## _ty elt = asdl_seq_GET(seq, i); \
857 if (!symtable_visit_ ## TYPE((ST), elt)) { \
858 symtable_exit_block((ST), (S)); \
859 return 0; \
860 } \
861 } \
862}
863
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000864#define VISIT_SEQ_TAIL(ST, TYPE, SEQ, START) { \
865 int i; \
866 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
867 for (i = (START); i < asdl_seq_LEN(seq); i++) { \
868 TYPE ## _ty elt = asdl_seq_GET(seq, i); \
869 if (!symtable_visit_ ## TYPE((ST), elt)) \
870 return 0; \
871 } \
872}
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000873
874#define VISIT_SEQ_TAIL_IN_BLOCK(ST, TYPE, SEQ, START, S) { \
875 int i; \
876 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
877 for (i = (START); i < asdl_seq_LEN(seq); i++) { \
878 TYPE ## _ty elt = asdl_seq_GET(seq, i); \
879 if (!symtable_visit_ ## TYPE((ST), elt)) { \
880 symtable_exit_block((ST), (S)); \
881 return 0; \
882 } \
883 } \
884}
885
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000886static int
887symtable_visit_stmt(struct symtable *st, stmt_ty s)
888{
889 switch (s->kind) {
890 case FunctionDef_kind:
891 if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL))
892 return 0;
893 if (s->v.FunctionDef.args->defaults)
894 VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults);
895 if (s->v.FunctionDef.decorators)
896 VISIT_SEQ(st, expr, s->v.FunctionDef.decorators);
897 if (!symtable_enter_block(st, s->v.FunctionDef.name,
898 FunctionBlock, (void *)s, s->lineno))
899 return 0;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000900 VISIT_IN_BLOCK(st, arguments, s->v.FunctionDef.args, s);
901 VISIT_SEQ_IN_BLOCK(st, stmt, s->v.FunctionDef.body, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000902 if (!symtable_exit_block(st, s))
903 return 0;
904 break;
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000905 case ClassDef_kind: {
906 PyObject *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000907 if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL))
908 return 0;
909 VISIT_SEQ(st, expr, s->v.ClassDef.bases);
910 if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock,
911 (void *)s, s->lineno))
912 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000913 tmp = st->st_private;
914 st->st_private = s->v.ClassDef.name;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000915 VISIT_SEQ_IN_BLOCK(st, stmt, s->v.ClassDef.body, s);
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000916 st->st_private = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917 if (!symtable_exit_block(st, s))
918 return 0;
919 break;
Neil Schemenauer8b528b22005-10-23 18:37:42 +0000920 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000921 case Return_kind:
922 if (s->v.Return.value)
923 VISIT(st, expr, s->v.Return.value);
924 break;
925 case Delete_kind:
926 VISIT_SEQ(st, expr, s->v.Delete.targets);
927 break;
928 case Assign_kind:
929 VISIT_SEQ(st, expr, s->v.Assign.targets);
930 VISIT(st, expr, s->v.Assign.value);
931 break;
932 case AugAssign_kind:
933 VISIT(st, expr, s->v.AugAssign.target);
934 VISIT(st, expr, s->v.AugAssign.value);
935 break;
936 case Print_kind:
937 if (s->v.Print.dest)
938 VISIT(st, expr, s->v.Print.dest);
939 VISIT_SEQ(st, expr, s->v.Print.values);
940 break;
941 case For_kind:
942 VISIT(st, expr, s->v.For.target);
943 VISIT(st, expr, s->v.For.iter);
944 VISIT_SEQ(st, stmt, s->v.For.body);
945 if (s->v.For.orelse)
946 VISIT_SEQ(st, stmt, s->v.For.orelse);
947 break;
948 case While_kind:
949 VISIT(st, expr, s->v.While.test);
950 VISIT_SEQ(st, stmt, s->v.While.body);
951 if (s->v.While.orelse)
952 VISIT_SEQ(st, stmt, s->v.While.orelse);
953 break;
954 case If_kind:
955 /* XXX if 0: and lookup_yield() hacks */
956 VISIT(st, expr, s->v.If.test);
957 VISIT_SEQ(st, stmt, s->v.If.body);
958 if (s->v.If.orelse)
959 VISIT_SEQ(st, stmt, s->v.If.orelse);
960 break;
961 case Raise_kind:
962 if (s->v.Raise.type) {
963 VISIT(st, expr, s->v.Raise.type);
964 if (s->v.Raise.inst) {
965 VISIT(st, expr, s->v.Raise.inst);
966 if (s->v.Raise.tback)
967 VISIT(st, expr, s->v.Raise.tback);
968 }
969 }
970 break;
971 case TryExcept_kind:
972 VISIT_SEQ(st, stmt, s->v.TryExcept.body);
973 VISIT_SEQ(st, stmt, s->v.TryExcept.orelse);
974 VISIT_SEQ(st, excepthandler, s->v.TryExcept.handlers);
975 break;
976 case TryFinally_kind:
977 VISIT_SEQ(st, stmt, s->v.TryFinally.body);
978 VISIT_SEQ(st, stmt, s->v.TryFinally.finalbody);
979 break;
980 case Assert_kind:
981 VISIT(st, expr, s->v.Assert.test);
982 if (s->v.Assert.msg)
983 VISIT(st, expr, s->v.Assert.msg);
984 break;
985 case Import_kind:
986 VISIT_SEQ(st, alias, s->v.Import.names);
987 /* XXX Don't have the lineno available inside
988 visit_alias */
989 if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno)
990 st->st_cur->ste_opt_lineno = s->lineno;
991 break;
992 case ImportFrom_kind:
993 VISIT_SEQ(st, alias, s->v.ImportFrom.names);
994 /* XXX Don't have the lineno available inside
995 visit_alias */
996 if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno)
997 st->st_cur->ste_opt_lineno = s->lineno;
998 break;
999 case Exec_kind:
1000 VISIT(st, expr, s->v.Exec.body);
1001 if (!st->st_cur->ste_opt_lineno)
1002 st->st_cur->ste_opt_lineno = s->lineno;
1003 if (s->v.Exec.globals) {
1004 st->st_cur->ste_unoptimized |= OPT_EXEC;
1005 VISIT(st, expr, s->v.Exec.globals);
1006 if (s->v.Exec.locals)
1007 VISIT(st, expr, s->v.Exec.locals);
1008 } else {
1009 st->st_cur->ste_unoptimized |= OPT_BARE_EXEC;
1010 }
1011 break;
1012 case Global_kind: {
1013 int i;
1014 asdl_seq *seq = s->v.Global.names;
1015 for (i = 0; i < asdl_seq_LEN(seq); i++) {
1016 identifier name = asdl_seq_GET(seq, i);
1017 char *c_name = PyString_AS_STRING(name);
1018 int cur = symtable_lookup(st, name);
1019 if (cur < 0)
1020 return 0;
1021 if (cur & (DEF_LOCAL | USE)) {
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001022 char buf[256];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001023 if (cur & DEF_LOCAL)
1024 PyOS_snprintf(buf, sizeof(buf),
1025 GLOBAL_AFTER_ASSIGN,
1026 c_name);
1027 else
1028 PyOS_snprintf(buf, sizeof(buf),
1029 GLOBAL_AFTER_USE,
1030 c_name);
1031 if (!symtable_warn(st, buf))
1032 return 0;
1033 }
1034 if (!symtable_add_def(st, name, DEF_GLOBAL))
1035 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001037 break;
1038 }
1039 case Expr_kind:
1040 VISIT(st, expr, s->v.Expr.value);
1041 break;
1042 case Pass_kind:
1043 case Break_kind:
1044 case Continue_kind:
1045 /* nothing to do here */
1046 break;
1047 }
1048 return 1;
1049}
1050
1051static int
1052symtable_visit_expr(struct symtable *st, expr_ty e)
1053{
1054 switch (e->kind) {
1055 case BoolOp_kind:
1056 VISIT_SEQ(st, expr, e->v.BoolOp.values);
1057 break;
1058 case BinOp_kind:
1059 VISIT(st, expr, e->v.BinOp.left);
1060 VISIT(st, expr, e->v.BinOp.right);
1061 break;
1062 case UnaryOp_kind:
1063 VISIT(st, expr, e->v.UnaryOp.operand);
1064 break;
1065 case Lambda_kind: {
1066 if (!symtable_add_def(st, GET_IDENTIFIER(lambda), DEF_LOCAL))
1067 return 0;
1068 if (e->v.Lambda.args->defaults)
1069 VISIT_SEQ(st, expr, e->v.Lambda.args->defaults);
1070 /* XXX how to get line numbers for expressions */
1071 if (!symtable_enter_block(st, GET_IDENTIFIER(lambda),
1072 FunctionBlock, (void *)e, 0))
1073 return 0;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001074 VISIT_IN_BLOCK(st, arguments, e->v.Lambda.args, (void*)e);
1075 VISIT_IN_BLOCK(st, expr, e->v.Lambda.body, (void*)e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001076 if (!symtable_exit_block(st, (void *)e))
1077 return 0;
1078 break;
1079 }
1080 case Dict_kind:
1081 VISIT_SEQ(st, expr, e->v.Dict.keys);
1082 VISIT_SEQ(st, expr, e->v.Dict.values);
1083 break;
1084 case ListComp_kind: {
1085 char tmpname[256];
1086 identifier tmp;
1087
1088 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]",
1089 ++st->st_cur->ste_tmpname);
1090 tmp = PyString_FromString(tmpname);
1091 if (!symtable_add_def(st, tmp, DEF_LOCAL))
1092 return 0;
1093 VISIT(st, expr, e->v.ListComp.elt);
1094 VISIT_SEQ(st, comprehension, e->v.ListComp.generators);
1095 break;
1096 }
1097 case GeneratorExp_kind: {
1098 if (!symtable_visit_genexp(st, e)) {
1099 return 0;
1100 }
1101 break;
1102 }
1103 case Yield_kind:
1104 if (e->v.Yield.value)
1105 VISIT(st, expr, e->v.Yield.value);
1106 st->st_cur->ste_generator = 1;
1107 break;
1108 case Compare_kind:
1109 VISIT(st, expr, e->v.Compare.left);
1110 VISIT_SEQ(st, expr, e->v.Compare.comparators);
1111 break;
1112 case Call_kind:
1113 VISIT(st, expr, e->v.Call.func);
1114 VISIT_SEQ(st, expr, e->v.Call.args);
1115 VISIT_SEQ(st, keyword, e->v.Call.keywords);
1116 if (e->v.Call.starargs)
1117 VISIT(st, expr, e->v.Call.starargs);
1118 if (e->v.Call.kwargs)
1119 VISIT(st, expr, e->v.Call.kwargs);
1120 break;
1121 case Repr_kind:
1122 VISIT(st, expr, e->v.Repr.value);
1123 break;
1124 case Num_kind:
1125 case Str_kind:
1126 /* Nothing to do here. */
1127 break;
1128 /* The following exprs can be assignment targets. */
1129 case Attribute_kind:
1130 VISIT(st, expr, e->v.Attribute.value);
1131 break;
1132 case Subscript_kind:
1133 VISIT(st, expr, e->v.Subscript.value);
1134 VISIT(st, slice, e->v.Subscript.slice);
1135 break;
1136 case Name_kind:
1137 if (!symtable_add_def(st, e->v.Name.id,
1138 e->v.Name.ctx == Load ? USE : DEF_LOCAL))
1139 return 0;
1140 break;
1141 /* child nodes of List and Tuple will have expr_context set */
1142 case List_kind:
1143 VISIT_SEQ(st, expr, e->v.List.elts);
1144 break;
1145 case Tuple_kind:
1146 VISIT_SEQ(st, expr, e->v.Tuple.elts);
1147 break;
1148 }
1149 return 1;
1150}
1151
1152static int
1153symtable_implicit_arg(struct symtable *st, int pos)
1154{
1155 PyObject *id = PyString_FromFormat(".%d", pos);
1156 if (id == NULL)
1157 return 0;
1158 if (!symtable_add_def(st, id, DEF_PARAM)) {
1159 Py_DECREF(id);
1160 return 0;
1161 }
1162 Py_DECREF(id);
1163 return 1;
1164}
1165
1166static int
1167symtable_visit_params(struct symtable *st, asdl_seq *args, int toplevel)
1168{
1169 int i, complex = 0;
1170
1171 /* go through all the toplevel arguments first */
1172 for (i = 0; i < asdl_seq_LEN(args); i++) {
1173 expr_ty arg = asdl_seq_GET(args, i);
1174 if (arg->kind == Name_kind) {
1175 assert(arg->v.Name.ctx == Param ||
1176 (arg->v.Name.ctx == Store && !toplevel));
1177 if (!symtable_add_def(st, arg->v.Name.id, DEF_PARAM))
1178 return 0;
1179 }
1180 else if (arg->kind == Tuple_kind) {
1181 assert(arg->v.Tuple.ctx == Store);
1182 complex = 1;
1183 if (toplevel) {
1184 if (!symtable_implicit_arg(st, i))
1185 return 0;
1186 }
1187 }
1188 else {
1189 /* syntax error */
1190 fprintf(stderr, "unexpected expr in parameter list\n");
1191 return 0;
1192 }
1193 }
1194
1195 if (!toplevel) {
1196 if (!symtable_visit_params_nested(st, args))
1197 return 0;
1198 }
1199
1200 return 1;
1201}
1202
1203static int
1204symtable_visit_params_nested(struct symtable *st, asdl_seq *args)
1205{
1206 int i;
1207 for (i = 0; i < asdl_seq_LEN(args); i++) {
1208 expr_ty arg = asdl_seq_GET(args, i);
1209 if (arg->kind == Tuple_kind &&
1210 !symtable_visit_params(st, arg->v.Tuple.elts, 0))
1211 return 0;
1212 }
1213
1214 return 1;
1215}
1216
1217static int
1218symtable_visit_arguments(struct symtable *st, arguments_ty a)
1219{
1220 /* skip default arguments inside function block
1221 XXX should ast be different?
1222 */
1223 if (a->args && !symtable_visit_params(st, a->args, 1))
1224 return 0;
1225 if (a->vararg) {
1226 if (!symtable_add_def(st, a->vararg, DEF_PARAM))
1227 return 0;
1228 st->st_cur->ste_varargs = 1;
1229 }
1230 if (a->kwarg) {
1231 if (!symtable_add_def(st, a->kwarg, DEF_PARAM))
1232 return 0;
1233 st->st_cur->ste_varkeywords = 1;
1234 }
1235 if (a->args && !symtable_visit_params_nested(st, a->args))
1236 return 0;
1237 return 1;
1238}
1239
1240
1241static int
1242symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh)
1243{
1244 if (eh->type)
1245 VISIT(st, expr, eh->type);
1246 if (eh->name)
1247 VISIT(st, expr, eh->name);
1248 VISIT_SEQ(st, stmt, eh->body);
1249 return 1;
1250}
1251
1252
1253static int
1254symtable_visit_alias(struct symtable *st, alias_ty a)
1255{
1256 /* Compute store_name, the name actually bound by the import
1257 operation. It is diferent than a->name when a->name is a
1258 dotted package name (e.g. spam.eggs)
1259 */
1260 PyObject *store_name;
1261 PyObject *name = (a->asname == NULL) ? a->name : a->asname;
1262 const char *base = PyString_AS_STRING(name);
1263 char *dot = strchr(base, '.');
1264 if (dot)
1265 store_name = PyString_FromStringAndSize(base, dot - base);
1266 else {
1267 store_name = name;
1268 Py_INCREF(store_name);
1269 }
1270 if (strcmp(PyString_AS_STRING(name), "*")) {
1271 int r = symtable_add_def(st, store_name, DEF_IMPORT);
1272 Py_DECREF(store_name);
1273 return r;
1274 }
1275 else {
1276 if (st->st_cur->ste_type != ModuleBlock) {
1277 if (!symtable_warn(st,
1278 "import * only allowed at module level"))
1279 return 0;
1280 }
1281 st->st_cur->ste_unoptimized |= OPT_IMPORT_STAR;
1282 return 1;
1283 }
1284}
1285
1286
1287static int
1288symtable_visit_comprehension(struct symtable *st, comprehension_ty lc)
1289{
1290 VISIT(st, expr, lc->target);
1291 VISIT(st, expr, lc->iter);
1292 VISIT_SEQ(st, expr, lc->ifs);
1293 return 1;
1294}
1295
1296
1297static int
1298symtable_visit_keyword(struct symtable *st, keyword_ty k)
1299{
1300 VISIT(st, expr, k->value);
1301 return 1;
1302}
1303
1304
1305static int
1306symtable_visit_slice(struct symtable *st, slice_ty s)
1307{
1308 switch (s->kind) {
1309 case Slice_kind:
1310 if (s->v.Slice.lower)
1311 VISIT(st, expr, s->v.Slice.lower)
1312 if (s->v.Slice.upper)
1313 VISIT(st, expr, s->v.Slice.upper)
1314 if (s->v.Slice.step)
1315 VISIT(st, expr, s->v.Slice.step)
1316 break;
1317 case ExtSlice_kind:
1318 VISIT_SEQ(st, slice, s->v.ExtSlice.dims)
1319 break;
1320 case Index_kind:
1321 VISIT(st, expr, s->v.Index.value)
1322 break;
1323 case Ellipsis_kind:
1324 break;
1325 }
1326 return 1;
1327}
1328
1329static int
1330symtable_visit_genexp(struct symtable *st, expr_ty e)
1331{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332 comprehension_ty outermost = ((comprehension_ty)
1333 (asdl_seq_GET(e->v.GeneratorExp.generators, 0)));
1334 /* Outermost iterator is evaluated in current scope */
1335 VISIT(st, expr, outermost->iter);
1336 /* Create generator scope for the rest */
Nick Coghlan99b25332005-11-16 12:45:24 +00001337 if (!symtable_enter_block(st, GET_IDENTIFIER(genexpr),
1338 FunctionBlock, (void *)e, 0)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001339 return 0;
1340 }
1341 st->st_cur->ste_generator = 1;
1342 /* Outermost iter is received as an argument */
1343 if (!symtable_implicit_arg(st, 0)) {
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001344 symtable_exit_block(st, (void *)e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345 return 0;
1346 }
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001347 VISIT_IN_BLOCK(st, expr, outermost->target, (void*)e);
1348 VISIT_SEQ_IN_BLOCK(st, expr, outermost->ifs, (void*)e);
1349 VISIT_SEQ_TAIL_IN_BLOCK(st, comprehension,
1350 e->v.GeneratorExp.generators, 1, (void*)e);
1351 VISIT_IN_BLOCK(st, expr, e->v.GeneratorExp.elt, (void*)e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001352 if (!symtable_exit_block(st, (void *)e))
1353 return 0;
1354 return 1;
1355}