You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1554 lines
48 KiB

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