symtable.c 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761
  1. #include "Python.h"
  2. #include "pycore_ast.h" // identifier, stmt_ty
  3. #include "pycore_parser.h" // _PyParser_ASTFromString()
  4. #include "pycore_pystate.h" // _PyThreadState_GET()
  5. #include "pycore_symtable.h" // PySTEntryObject
  6. #include "structmember.h" // PyMemberDef
  7. /* error strings used for warnings */
  8. #define GLOBAL_PARAM \
  9. "name '%U' is parameter and global"
  10. #define NONLOCAL_PARAM \
  11. "name '%U' is parameter and nonlocal"
  12. #define GLOBAL_AFTER_ASSIGN \
  13. "name '%U' is assigned to before global declaration"
  14. #define NONLOCAL_AFTER_ASSIGN \
  15. "name '%U' is assigned to before nonlocal declaration"
  16. #define GLOBAL_AFTER_USE \
  17. "name '%U' is used prior to global declaration"
  18. #define NONLOCAL_AFTER_USE \
  19. "name '%U' is used prior to nonlocal declaration"
  20. #define GLOBAL_ANNOT \
  21. "annotated name '%U' can't be global"
  22. #define NONLOCAL_ANNOT \
  23. "annotated name '%U' can't be nonlocal"
  24. #define IMPORT_STAR_WARNING "import * only allowed at module level"
  25. #define NAMED_EXPR_COMP_IN_CLASS \
  26. "assignment expression within a comprehension cannot be used in a class body"
  27. #define NAMED_EXPR_COMP_IN_TYPEVAR_BOUND \
  28. "assignment expression within a comprehension cannot be used in a TypeVar bound"
  29. #define NAMED_EXPR_COMP_IN_TYPEALIAS \
  30. "assignment expression within a comprehension cannot be used in a type alias"
  31. #define NAMED_EXPR_COMP_IN_TYPEPARAM \
  32. "assignment expression within a comprehension cannot be used within the definition of a generic"
  33. #define NAMED_EXPR_COMP_CONFLICT \
  34. "assignment expression cannot rebind comprehension iteration variable '%U'"
  35. #define NAMED_EXPR_COMP_INNER_LOOP_CONFLICT \
  36. "comprehension inner loop cannot rebind assignment expression target '%U'"
  37. #define NAMED_EXPR_COMP_ITER_EXPR \
  38. "assignment expression cannot be used in a comprehension iterable expression"
  39. #define ANNOTATION_NOT_ALLOWED \
  40. "%s cannot be used within an annotation"
  41. #define TYPEVAR_BOUND_NOT_ALLOWED \
  42. "%s cannot be used within a TypeVar bound"
  43. #define TYPEALIAS_NOT_ALLOWED \
  44. "%s cannot be used within a type alias"
  45. #define TYPEPARAM_NOT_ALLOWED \
  46. "%s cannot be used within the definition of a generic"
  47. #define DUPLICATE_TYPE_PARAM \
  48. "duplicate type parameter '%U'"
  49. #define LOCATION(x) \
  50. (x)->lineno, (x)->col_offset, (x)->end_lineno, (x)->end_col_offset
  51. #define ST_LOCATION(x) \
  52. (x)->ste_lineno, (x)->ste_col_offset, (x)->ste_end_lineno, (x)->ste_end_col_offset
  53. static PySTEntryObject *
  54. ste_new(struct symtable *st, identifier name, _Py_block_ty block,
  55. void *key, int lineno, int col_offset,
  56. int end_lineno, int end_col_offset)
  57. {
  58. PySTEntryObject *ste = NULL;
  59. PyObject *k = NULL;
  60. k = PyLong_FromVoidPtr(key);
  61. if (k == NULL)
  62. goto fail;
  63. ste = PyObject_New(PySTEntryObject, &PySTEntry_Type);
  64. if (ste == NULL) {
  65. Py_DECREF(k);
  66. goto fail;
  67. }
  68. ste->ste_table = st;
  69. ste->ste_id = k; /* ste owns reference to k */
  70. ste->ste_name = Py_NewRef(name);
  71. ste->ste_symbols = NULL;
  72. ste->ste_varnames = NULL;
  73. ste->ste_children = NULL;
  74. ste->ste_directives = NULL;
  75. ste->ste_mangled_names = NULL;
  76. ste->ste_type = block;
  77. ste->ste_nested = 0;
  78. ste->ste_free = 0;
  79. ste->ste_varargs = 0;
  80. ste->ste_varkeywords = 0;
  81. ste->ste_opt_lineno = 0;
  82. ste->ste_opt_col_offset = 0;
  83. ste->ste_lineno = lineno;
  84. ste->ste_col_offset = col_offset;
  85. ste->ste_end_lineno = end_lineno;
  86. ste->ste_end_col_offset = end_col_offset;
  87. if (st->st_cur != NULL &&
  88. (st->st_cur->ste_nested ||
  89. _PyST_IsFunctionLike(st->st_cur)))
  90. ste->ste_nested = 1;
  91. ste->ste_child_free = 0;
  92. ste->ste_generator = 0;
  93. ste->ste_coroutine = 0;
  94. ste->ste_comprehension = NoComprehension;
  95. ste->ste_returns_value = 0;
  96. ste->ste_needs_class_closure = 0;
  97. ste->ste_comp_inlined = 0;
  98. ste->ste_comp_iter_target = 0;
  99. ste->ste_can_see_class_scope = 0;
  100. ste->ste_comp_iter_expr = 0;
  101. ste->ste_needs_classdict = 0;
  102. ste->ste_symbols = PyDict_New();
  103. ste->ste_varnames = PyList_New(0);
  104. ste->ste_children = PyList_New(0);
  105. if (ste->ste_symbols == NULL
  106. || ste->ste_varnames == NULL
  107. || ste->ste_children == NULL)
  108. goto fail;
  109. if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0)
  110. goto fail;
  111. return ste;
  112. fail:
  113. Py_XDECREF(ste);
  114. return NULL;
  115. }
  116. static PyObject *
  117. ste_repr(PySTEntryObject *ste)
  118. {
  119. return PyUnicode_FromFormat("<symtable entry %U(%R), line %d>",
  120. ste->ste_name, ste->ste_id, ste->ste_lineno);
  121. }
  122. static void
  123. ste_dealloc(PySTEntryObject *ste)
  124. {
  125. ste->ste_table = NULL;
  126. Py_XDECREF(ste->ste_id);
  127. Py_XDECREF(ste->ste_name);
  128. Py_XDECREF(ste->ste_symbols);
  129. Py_XDECREF(ste->ste_varnames);
  130. Py_XDECREF(ste->ste_children);
  131. Py_XDECREF(ste->ste_directives);
  132. Py_XDECREF(ste->ste_mangled_names);
  133. PyObject_Free(ste);
  134. }
  135. #define OFF(x) offsetof(PySTEntryObject, x)
  136. static PyMemberDef ste_memberlist[] = {
  137. {"id", T_OBJECT, OFF(ste_id), READONLY},
  138. {"name", T_OBJECT, OFF(ste_name), READONLY},
  139. {"symbols", T_OBJECT, OFF(ste_symbols), READONLY},
  140. {"varnames", T_OBJECT, OFF(ste_varnames), READONLY},
  141. {"children", T_OBJECT, OFF(ste_children), READONLY},
  142. {"nested", T_INT, OFF(ste_nested), READONLY},
  143. {"type", T_INT, OFF(ste_type), READONLY},
  144. {"lineno", T_INT, OFF(ste_lineno), READONLY},
  145. {NULL}
  146. };
  147. PyTypeObject PySTEntry_Type = {
  148. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  149. "symtable entry",
  150. sizeof(PySTEntryObject),
  151. 0,
  152. (destructor)ste_dealloc, /* tp_dealloc */
  153. 0, /* tp_vectorcall_offset */
  154. 0, /* tp_getattr */
  155. 0, /* tp_setattr */
  156. 0, /* tp_as_async */
  157. (reprfunc)ste_repr, /* tp_repr */
  158. 0, /* tp_as_number */
  159. 0, /* tp_as_sequence */
  160. 0, /* tp_as_mapping */
  161. 0, /* tp_hash */
  162. 0, /* tp_call */
  163. 0, /* tp_str */
  164. PyObject_GenericGetAttr, /* tp_getattro */
  165. 0, /* tp_setattro */
  166. 0, /* tp_as_buffer */
  167. Py_TPFLAGS_DEFAULT, /* tp_flags */
  168. 0, /* tp_doc */
  169. 0, /* tp_traverse */
  170. 0, /* tp_clear */
  171. 0, /* tp_richcompare */
  172. 0, /* tp_weaklistoffset */
  173. 0, /* tp_iter */
  174. 0, /* tp_iternext */
  175. 0, /* tp_methods */
  176. ste_memberlist, /* tp_members */
  177. 0, /* tp_getset */
  178. 0, /* tp_base */
  179. 0, /* tp_dict */
  180. 0, /* tp_descr_get */
  181. 0, /* tp_descr_set */
  182. 0, /* tp_dictoffset */
  183. 0, /* tp_init */
  184. 0, /* tp_alloc */
  185. 0, /* tp_new */
  186. };
  187. static int symtable_analyze(struct symtable *st);
  188. static int symtable_enter_block(struct symtable *st, identifier name,
  189. _Py_block_ty block, void *ast,
  190. int lineno, int col_offset,
  191. int end_lineno, int end_col_offset);
  192. static int symtable_exit_block(struct symtable *st);
  193. static int symtable_visit_stmt(struct symtable *st, stmt_ty s);
  194. static int symtable_visit_expr(struct symtable *st, expr_ty s);
  195. static int symtable_visit_type_param(struct symtable *st, type_param_ty s);
  196. static int symtable_visit_genexp(struct symtable *st, expr_ty s);
  197. static int symtable_visit_listcomp(struct symtable *st, expr_ty s);
  198. static int symtable_visit_setcomp(struct symtable *st, expr_ty s);
  199. static int symtable_visit_dictcomp(struct symtable *st, expr_ty s);
  200. static int symtable_visit_arguments(struct symtable *st, arguments_ty);
  201. static int symtable_visit_excepthandler(struct symtable *st, excepthandler_ty);
  202. static int symtable_visit_alias(struct symtable *st, alias_ty);
  203. static int symtable_visit_comprehension(struct symtable *st, comprehension_ty);
  204. static int symtable_visit_keyword(struct symtable *st, keyword_ty);
  205. static int symtable_visit_params(struct symtable *st, asdl_arg_seq *args);
  206. static int symtable_visit_annotation(struct symtable *st, expr_ty annotation);
  207. static int symtable_visit_argannotations(struct symtable *st, asdl_arg_seq *args);
  208. static int symtable_implicit_arg(struct symtable *st, int pos);
  209. static int symtable_visit_annotations(struct symtable *st, stmt_ty, arguments_ty, expr_ty);
  210. static int symtable_visit_withitem(struct symtable *st, withitem_ty item);
  211. static int symtable_visit_match_case(struct symtable *st, match_case_ty m);
  212. static int symtable_visit_pattern(struct symtable *st, pattern_ty s);
  213. static int symtable_raise_if_annotation_block(struct symtable *st, const char *, expr_ty);
  214. static int symtable_raise_if_comprehension_block(struct symtable *st, expr_ty);
  215. #define DUPLICATE_ARGUMENT \
  216. "duplicate argument '%U' in function definition"
  217. static struct symtable *
  218. symtable_new(void)
  219. {
  220. struct symtable *st;
  221. st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable));
  222. if (st == NULL) {
  223. PyErr_NoMemory();
  224. return NULL;
  225. }
  226. st->st_filename = NULL;
  227. st->st_blocks = NULL;
  228. if ((st->st_stack = PyList_New(0)) == NULL)
  229. goto fail;
  230. if ((st->st_blocks = PyDict_New()) == NULL)
  231. goto fail;
  232. st->st_cur = NULL;
  233. st->st_private = NULL;
  234. return st;
  235. fail:
  236. _PySymtable_Free(st);
  237. return NULL;
  238. }
  239. struct symtable *
  240. _PySymtable_Build(mod_ty mod, PyObject *filename, PyFutureFeatures *future)
  241. {
  242. struct symtable *st = symtable_new();
  243. asdl_stmt_seq *seq;
  244. int i;
  245. PyThreadState *tstate;
  246. int starting_recursion_depth;
  247. if (st == NULL)
  248. return NULL;
  249. if (filename == NULL) {
  250. _PySymtable_Free(st);
  251. return NULL;
  252. }
  253. st->st_filename = Py_NewRef(filename);
  254. st->st_future = future;
  255. /* Setup recursion depth check counters */
  256. tstate = _PyThreadState_GET();
  257. if (!tstate) {
  258. _PySymtable_Free(st);
  259. return NULL;
  260. }
  261. /* Be careful here to prevent overflow. */
  262. int recursion_depth = C_RECURSION_LIMIT - tstate->c_recursion_remaining;
  263. starting_recursion_depth = recursion_depth;
  264. st->recursion_depth = starting_recursion_depth;
  265. st->recursion_limit = C_RECURSION_LIMIT;
  266. /* Make the initial symbol information gathering pass */
  267. if (!symtable_enter_block(st, &_Py_ID(top), ModuleBlock, (void *)mod, 0, 0, 0, 0)) {
  268. _PySymtable_Free(st);
  269. return NULL;
  270. }
  271. st->st_top = st->st_cur;
  272. switch (mod->kind) {
  273. case Module_kind:
  274. seq = mod->v.Module.body;
  275. for (i = 0; i < asdl_seq_LEN(seq); i++)
  276. if (!symtable_visit_stmt(st,
  277. (stmt_ty)asdl_seq_GET(seq, i)))
  278. goto error;
  279. break;
  280. case Expression_kind:
  281. if (!symtable_visit_expr(st, mod->v.Expression.body))
  282. goto error;
  283. break;
  284. case Interactive_kind:
  285. seq = mod->v.Interactive.body;
  286. for (i = 0; i < asdl_seq_LEN(seq); i++)
  287. if (!symtable_visit_stmt(st,
  288. (stmt_ty)asdl_seq_GET(seq, i)))
  289. goto error;
  290. break;
  291. case FunctionType_kind:
  292. PyErr_SetString(PyExc_RuntimeError,
  293. "this compiler does not handle FunctionTypes");
  294. goto error;
  295. }
  296. if (!symtable_exit_block(st)) {
  297. _PySymtable_Free(st);
  298. return NULL;
  299. }
  300. /* Check that the recursion depth counting balanced correctly */
  301. if (st->recursion_depth != starting_recursion_depth) {
  302. PyErr_Format(PyExc_SystemError,
  303. "symtable analysis recursion depth mismatch (before=%d, after=%d)",
  304. starting_recursion_depth, st->recursion_depth);
  305. _PySymtable_Free(st);
  306. return NULL;
  307. }
  308. /* Make the second symbol analysis pass */
  309. if (symtable_analyze(st))
  310. return st;
  311. _PySymtable_Free(st);
  312. return NULL;
  313. error:
  314. (void) symtable_exit_block(st);
  315. _PySymtable_Free(st);
  316. return NULL;
  317. }
  318. void
  319. _PySymtable_Free(struct symtable *st)
  320. {
  321. Py_XDECREF(st->st_filename);
  322. Py_XDECREF(st->st_blocks);
  323. Py_XDECREF(st->st_stack);
  324. PyMem_Free((void *)st);
  325. }
  326. PySTEntryObject *
  327. PySymtable_Lookup(struct symtable *st, void *key)
  328. {
  329. PyObject *k, *v;
  330. k = PyLong_FromVoidPtr(key);
  331. if (k == NULL)
  332. return NULL;
  333. v = PyDict_GetItemWithError(st->st_blocks, k);
  334. Py_DECREF(k);
  335. if (v) {
  336. assert(PySTEntry_Check(v));
  337. }
  338. else if (!PyErr_Occurred()) {
  339. PyErr_SetString(PyExc_KeyError,
  340. "unknown symbol table entry");
  341. }
  342. return (PySTEntryObject *)Py_XNewRef(v);
  343. }
  344. long
  345. _PyST_GetSymbol(PySTEntryObject *ste, PyObject *name)
  346. {
  347. PyObject *v = PyDict_GetItemWithError(ste->ste_symbols, name);
  348. if (!v)
  349. return 0;
  350. assert(PyLong_Check(v));
  351. return PyLong_AS_LONG(v);
  352. }
  353. int
  354. _PyST_GetScope(PySTEntryObject *ste, PyObject *name)
  355. {
  356. long symbol = _PyST_GetSymbol(ste, name);
  357. return (symbol >> SCOPE_OFFSET) & SCOPE_MASK;
  358. }
  359. int
  360. _PyST_IsFunctionLike(PySTEntryObject *ste)
  361. {
  362. return ste->ste_type == FunctionBlock
  363. || ste->ste_type == TypeVarBoundBlock
  364. || ste->ste_type == TypeAliasBlock
  365. || ste->ste_type == TypeParamBlock;
  366. }
  367. static int
  368. error_at_directive(PySTEntryObject *ste, PyObject *name)
  369. {
  370. Py_ssize_t i;
  371. PyObject *data;
  372. assert(ste->ste_directives);
  373. for (i = 0; i < PyList_GET_SIZE(ste->ste_directives); i++) {
  374. data = PyList_GET_ITEM(ste->ste_directives, i);
  375. assert(PyTuple_CheckExact(data));
  376. assert(PyUnicode_CheckExact(PyTuple_GET_ITEM(data, 0)));
  377. if (PyUnicode_Compare(PyTuple_GET_ITEM(data, 0), name) == 0) {
  378. PyErr_RangedSyntaxLocationObject(ste->ste_table->st_filename,
  379. PyLong_AsLong(PyTuple_GET_ITEM(data, 1)),
  380. PyLong_AsLong(PyTuple_GET_ITEM(data, 2)) + 1,
  381. PyLong_AsLong(PyTuple_GET_ITEM(data, 3)),
  382. PyLong_AsLong(PyTuple_GET_ITEM(data, 4)) + 1);
  383. return 0;
  384. }
  385. }
  386. PyErr_SetString(PyExc_RuntimeError,
  387. "BUG: internal directive bookkeeping broken");
  388. return 0;
  389. }
  390. /* Analyze raw symbol information to determine scope of each name.
  391. The next several functions are helpers for symtable_analyze(),
  392. which determines whether a name is local, global, or free. In addition,
  393. it determines which local variables are cell variables; they provide
  394. bindings that are used for free variables in enclosed blocks.
  395. There are also two kinds of global variables, implicit and explicit. An
  396. explicit global is declared with the global statement. An implicit
  397. global is a free variable for which the compiler has found no binding
  398. in an enclosing function scope. The implicit global is either a global
  399. or a builtin. Python's module and class blocks use the xxx_NAME opcodes
  400. to handle these names to implement slightly odd semantics. In such a
  401. block, the name is treated as global until it is assigned to; then it
  402. is treated as a local.
  403. The symbol table requires two passes to determine the scope of each name.
  404. The first pass collects raw facts from the AST via the symtable_visit_*
  405. functions: the name is a parameter here, the name is used but not defined
  406. here, etc. The second pass analyzes these facts during a pass over the
  407. PySTEntryObjects created during pass 1.
  408. When a function is entered during the second pass, the parent passes
  409. the set of all name bindings visible to its children. These bindings
  410. are used to determine if non-local variables are free or implicit globals.
  411. Names which are explicitly declared nonlocal must exist in this set of
  412. visible names - if they do not, a syntax error is raised. After doing
  413. the local analysis, it analyzes each of its child blocks using an
  414. updated set of name bindings.
  415. The children update the free variable set. If a local variable is added to
  416. the free variable set by the child, the variable is marked as a cell. The
  417. function object being defined must provide runtime storage for the variable
  418. that may outlive the function's frame. Cell variables are removed from the
  419. free set before the analyze function returns to its parent.
  420. During analysis, the names are:
  421. symbols: dict mapping from symbol names to flag values (including offset scope values)
  422. scopes: dict mapping from symbol names to scope values (no offset)
  423. local: set of all symbol names local to the current scope
  424. bound: set of all symbol names local to a containing function scope
  425. free: set of all symbol names referenced but not bound in child scopes
  426. global: set of all symbol names explicitly declared as global
  427. */
  428. #define SET_SCOPE(DICT, NAME, I) { \
  429. PyObject *o = PyLong_FromLong(I); \
  430. if (!o) \
  431. return 0; \
  432. if (PyDict_SetItem((DICT), (NAME), o) < 0) { \
  433. Py_DECREF(o); \
  434. return 0; \
  435. } \
  436. Py_DECREF(o); \
  437. }
  438. /* Decide on scope of name, given flags.
  439. The namespace dictionaries may be modified to record information
  440. about the new name. For example, a new global will add an entry to
  441. global. A name that was global can be changed to local.
  442. */
  443. static int
  444. analyze_name(PySTEntryObject *ste, PyObject *scopes, PyObject *name, long flags,
  445. PyObject *bound, PyObject *local, PyObject *free,
  446. PyObject *global, PyObject *type_params, PySTEntryObject *class_entry)
  447. {
  448. int contains;
  449. if (flags & DEF_GLOBAL) {
  450. if (flags & DEF_NONLOCAL) {
  451. PyErr_Format(PyExc_SyntaxError,
  452. "name '%U' is nonlocal and global",
  453. name);
  454. return error_at_directive(ste, name);
  455. }
  456. SET_SCOPE(scopes, name, GLOBAL_EXPLICIT);
  457. if (PySet_Add(global, name) < 0)
  458. return 0;
  459. if (bound && (PySet_Discard(bound, name) < 0))
  460. return 0;
  461. return 1;
  462. }
  463. if (flags & DEF_NONLOCAL) {
  464. if (!bound) {
  465. PyErr_Format(PyExc_SyntaxError,
  466. "nonlocal declaration not allowed at module level");
  467. return error_at_directive(ste, name);
  468. }
  469. contains = PySet_Contains(bound, name);
  470. if (contains < 0) {
  471. return 0;
  472. }
  473. if (!contains) {
  474. PyErr_Format(PyExc_SyntaxError,
  475. "no binding for nonlocal '%U' found",
  476. name);
  477. return error_at_directive(ste, name);
  478. }
  479. contains = PySet_Contains(type_params, name);
  480. if (contains < 0) {
  481. return 0;
  482. }
  483. if (contains) {
  484. PyErr_Format(PyExc_SyntaxError,
  485. "nonlocal binding not allowed for type parameter '%U'",
  486. name);
  487. return error_at_directive(ste, name);
  488. }
  489. SET_SCOPE(scopes, name, FREE);
  490. ste->ste_free = 1;
  491. return PySet_Add(free, name) >= 0;
  492. }
  493. if (flags & DEF_BOUND) {
  494. SET_SCOPE(scopes, name, LOCAL);
  495. if (PySet_Add(local, name) < 0)
  496. return 0;
  497. if (PySet_Discard(global, name) < 0)
  498. return 0;
  499. if (flags & DEF_TYPE_PARAM) {
  500. if (PySet_Add(type_params, name) < 0)
  501. return 0;
  502. }
  503. else {
  504. if (PySet_Discard(type_params, name) < 0)
  505. return 0;
  506. }
  507. return 1;
  508. }
  509. // If we were passed class_entry (i.e., we're in an ste_can_see_class_scope scope)
  510. // and the bound name is in that set, then the name is potentially bound both by
  511. // the immediately enclosing class namespace, and also by an outer function namespace.
  512. // In that case, we want the runtime name resolution to look at only the class
  513. // namespace and the globals (not the namespace providing the bound).
  514. // Similarly, if the name is explicitly global in the class namespace (through the
  515. // global statement), we want to also treat it as a global in this scope.
  516. if (class_entry != NULL) {
  517. long class_flags = _PyST_GetSymbol(class_entry, name);
  518. if (class_flags & DEF_GLOBAL) {
  519. SET_SCOPE(scopes, name, GLOBAL_EXPLICIT);
  520. return 1;
  521. }
  522. else if (class_flags & DEF_BOUND && !(class_flags & DEF_NONLOCAL)) {
  523. SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
  524. return 1;
  525. }
  526. }
  527. /* If an enclosing block has a binding for this name, it
  528. is a free variable rather than a global variable.
  529. Note that having a non-NULL bound implies that the block
  530. is nested.
  531. */
  532. if (bound) {
  533. contains = PySet_Contains(bound, name);
  534. if (contains < 0) {
  535. return 0;
  536. }
  537. if (contains) {
  538. SET_SCOPE(scopes, name, FREE);
  539. ste->ste_free = 1;
  540. return PySet_Add(free, name) >= 0;
  541. }
  542. }
  543. /* If a parent has a global statement, then call it global
  544. explicit? It could also be global implicit.
  545. */
  546. if (global) {
  547. contains = PySet_Contains(global, name);
  548. if (contains < 0) {
  549. return 0;
  550. }
  551. if (contains) {
  552. SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
  553. return 1;
  554. }
  555. }
  556. if (ste->ste_nested)
  557. ste->ste_free = 1;
  558. SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
  559. return 1;
  560. }
  561. static int
  562. is_free_in_any_child(PySTEntryObject *entry, PyObject *key)
  563. {
  564. for (Py_ssize_t i = 0; i < PyList_GET_SIZE(entry->ste_children); i++) {
  565. PySTEntryObject *child_ste = (PySTEntryObject *)PyList_GET_ITEM(
  566. entry->ste_children, i);
  567. long scope = _PyST_GetScope(child_ste, key);
  568. if (scope == FREE) {
  569. return 1;
  570. }
  571. }
  572. return 0;
  573. }
  574. static int
  575. inline_comprehension(PySTEntryObject *ste, PySTEntryObject *comp,
  576. PyObject *scopes, PyObject *comp_free,
  577. PyObject *inlined_cells)
  578. {
  579. PyObject *k, *v;
  580. Py_ssize_t pos = 0;
  581. int remove_dunder_class = 0;
  582. while (PyDict_Next(comp->ste_symbols, &pos, &k, &v)) {
  583. // skip comprehension parameter
  584. long comp_flags = PyLong_AS_LONG(v);
  585. if (comp_flags & DEF_PARAM) {
  586. assert(_PyUnicode_EqualToASCIIString(k, ".0"));
  587. continue;
  588. }
  589. int scope = (comp_flags >> SCOPE_OFFSET) & SCOPE_MASK;
  590. int only_flags = comp_flags & ((1 << SCOPE_OFFSET) - 1);
  591. if (scope == CELL || only_flags & DEF_COMP_CELL) {
  592. if (PySet_Add(inlined_cells, k) < 0) {
  593. return 0;
  594. }
  595. }
  596. PyObject *existing = PyDict_GetItemWithError(ste->ste_symbols, k);
  597. if (existing == NULL && PyErr_Occurred()) {
  598. return 0;
  599. }
  600. // __class__ is never allowed to be free through a class scope (see
  601. // drop_class_free)
  602. if (scope == FREE && ste->ste_type == ClassBlock &&
  603. _PyUnicode_EqualToASCIIString(k, "__class__")) {
  604. scope = GLOBAL_IMPLICIT;
  605. if (PySet_Discard(comp_free, k) < 0) {
  606. return 0;
  607. }
  608. remove_dunder_class = 1;
  609. }
  610. if (!existing) {
  611. // name does not exist in scope, copy from comprehension
  612. assert(scope != FREE || PySet_Contains(comp_free, k) == 1);
  613. PyObject *v_flags = PyLong_FromLong(only_flags);
  614. if (v_flags == NULL) {
  615. return 0;
  616. }
  617. int ok = PyDict_SetItem(ste->ste_symbols, k, v_flags);
  618. Py_DECREF(v_flags);
  619. if (ok < 0) {
  620. return 0;
  621. }
  622. SET_SCOPE(scopes, k, scope);
  623. }
  624. else {
  625. if (PyLong_AsLong(existing) & DEF_BOUND) {
  626. // free vars in comprehension that are locals in outer scope can
  627. // now simply be locals, unless they are free in comp children,
  628. // or if the outer scope is a class block
  629. if (!is_free_in_any_child(comp, k) && ste->ste_type != ClassBlock) {
  630. if (PySet_Discard(comp_free, k) < 0) {
  631. return 0;
  632. }
  633. }
  634. }
  635. }
  636. }
  637. comp->ste_free = PySet_Size(comp_free) > 0;
  638. if (remove_dunder_class && PyDict_DelItemString(comp->ste_symbols, "__class__") < 0) {
  639. return 0;
  640. }
  641. return 1;
  642. }
  643. #undef SET_SCOPE
  644. /* If a name is defined in free and also in locals, then this block
  645. provides the binding for the free variable. The name should be
  646. marked CELL in this block and removed from the free list.
  647. Note that the current block's free variables are included in free.
  648. That's safe because no name can be free and local in the same scope.
  649. */
  650. static int
  651. analyze_cells(PyObject *scopes, PyObject *free, PyObject *inlined_cells)
  652. {
  653. PyObject *name, *v, *v_cell;
  654. int success = 0;
  655. Py_ssize_t pos = 0;
  656. v_cell = PyLong_FromLong(CELL);
  657. if (!v_cell)
  658. return 0;
  659. while (PyDict_Next(scopes, &pos, &name, &v)) {
  660. long scope;
  661. assert(PyLong_Check(v));
  662. scope = PyLong_AS_LONG(v);
  663. if (scope != LOCAL)
  664. continue;
  665. int contains = PySet_Contains(free, name);
  666. if (contains < 0) {
  667. goto error;
  668. }
  669. if (!contains) {
  670. contains = PySet_Contains(inlined_cells, name);
  671. if (contains < 0) {
  672. goto error;
  673. }
  674. if (!contains) {
  675. continue;
  676. }
  677. }
  678. /* Replace LOCAL with CELL for this name, and remove
  679. from free. It is safe to replace the value of name
  680. in the dict, because it will not cause a resize.
  681. */
  682. if (PyDict_SetItem(scopes, name, v_cell) < 0)
  683. goto error;
  684. if (PySet_Discard(free, name) < 0)
  685. goto error;
  686. }
  687. success = 1;
  688. error:
  689. Py_DECREF(v_cell);
  690. return success;
  691. }
  692. static int
  693. drop_class_free(PySTEntryObject *ste, PyObject *free)
  694. {
  695. int res;
  696. res = PySet_Discard(free, &_Py_ID(__class__));
  697. if (res < 0)
  698. return 0;
  699. if (res)
  700. ste->ste_needs_class_closure = 1;
  701. res = PySet_Discard(free, &_Py_ID(__classdict__));
  702. if (res < 0)
  703. return 0;
  704. if (res)
  705. ste->ste_needs_classdict = 1;
  706. return 1;
  707. }
  708. /* Enter the final scope information into the ste_symbols dict.
  709. *
  710. * All arguments are dicts. Modifies symbols, others are read-only.
  711. */
  712. static int
  713. update_symbols(PyObject *symbols, PyObject *scopes,
  714. PyObject *bound, PyObject *free,
  715. PyObject *inlined_cells, int classflag)
  716. {
  717. PyObject *name = NULL, *itr = NULL;
  718. PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL;
  719. Py_ssize_t pos = 0;
  720. /* Update scope information for all symbols in this scope */
  721. while (PyDict_Next(symbols, &pos, &name, &v)) {
  722. long scope, flags;
  723. assert(PyLong_Check(v));
  724. flags = PyLong_AS_LONG(v);
  725. int contains = PySet_Contains(inlined_cells, name);
  726. if (contains < 0) {
  727. return 0;
  728. }
  729. if (contains) {
  730. flags |= DEF_COMP_CELL;
  731. }
  732. v_scope = PyDict_GetItemWithError(scopes, name);
  733. assert(v_scope && PyLong_Check(v_scope));
  734. scope = PyLong_AS_LONG(v_scope);
  735. flags |= (scope << SCOPE_OFFSET);
  736. v_new = PyLong_FromLong(flags);
  737. if (!v_new)
  738. return 0;
  739. if (PyDict_SetItem(symbols, name, v_new) < 0) {
  740. Py_DECREF(v_new);
  741. return 0;
  742. }
  743. Py_DECREF(v_new);
  744. }
  745. /* Record not yet resolved free variables from children (if any) */
  746. v_free = PyLong_FromLong(FREE << SCOPE_OFFSET);
  747. if (!v_free)
  748. return 0;
  749. itr = PyObject_GetIter(free);
  750. if (itr == NULL) {
  751. Py_DECREF(v_free);
  752. return 0;
  753. }
  754. while ((name = PyIter_Next(itr))) {
  755. v = PyDict_GetItemWithError(symbols, name);
  756. /* Handle symbol that already exists in this scope */
  757. if (v) {
  758. /* Handle a free variable in a method of
  759. the class that has the same name as a local
  760. or global in the class scope.
  761. */
  762. if (classflag) {
  763. long flags = PyLong_AS_LONG(v) | DEF_FREE_CLASS;
  764. v_new = PyLong_FromLong(flags);
  765. if (!v_new) {
  766. goto error;
  767. }
  768. if (PyDict_SetItem(symbols, name, v_new) < 0) {
  769. Py_DECREF(v_new);
  770. goto error;
  771. }
  772. Py_DECREF(v_new);
  773. }
  774. /* It's a cell, or already free in this scope */
  775. Py_DECREF(name);
  776. continue;
  777. }
  778. else if (PyErr_Occurred()) {
  779. goto error;
  780. }
  781. /* Handle global symbol */
  782. if (bound) {
  783. int contains = PySet_Contains(bound, name);
  784. if (contains < 0) {
  785. goto error;
  786. }
  787. if (!contains) {
  788. Py_DECREF(name);
  789. continue; /* it's a global */
  790. }
  791. }
  792. /* Propagate new free symbol up the lexical stack */
  793. if (PyDict_SetItem(symbols, name, v_free) < 0) {
  794. goto error;
  795. }
  796. Py_DECREF(name);
  797. }
  798. /* Check if loop ended because of exception in PyIter_Next */
  799. if (PyErr_Occurred()) {
  800. goto error;
  801. }
  802. Py_DECREF(itr);
  803. Py_DECREF(v_free);
  804. return 1;
  805. error:
  806. Py_XDECREF(v_free);
  807. Py_XDECREF(itr);
  808. Py_XDECREF(name);
  809. return 0;
  810. }
  811. /* Make final symbol table decisions for block of ste.
  812. Arguments:
  813. ste -- current symtable entry (input/output)
  814. bound -- set of variables bound in enclosing scopes (input). bound
  815. is NULL for module blocks.
  816. free -- set of free variables in enclosed scopes (output)
  817. globals -- set of declared global variables in enclosing scopes (input)
  818. The implementation uses two mutually recursive functions,
  819. analyze_block() and analyze_child_block(). analyze_block() is
  820. responsible for analyzing the individual names defined in a block.
  821. analyze_child_block() prepares temporary namespace dictionaries
  822. used to evaluated nested blocks.
  823. The two functions exist because a child block should see the name
  824. bindings of its enclosing blocks, but those bindings should not
  825. propagate back to a parent block.
  826. */
  827. static int
  828. analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free,
  829. PyObject *global, PyObject *type_params,
  830. PySTEntryObject *class_entry, PyObject **child_free);
  831. static int
  832. analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free,
  833. PyObject *global, PyObject *type_params,
  834. PySTEntryObject *class_entry)
  835. {
  836. PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL;
  837. PyObject *newglobal = NULL, *newfree = NULL, *inlined_cells = NULL;
  838. PyObject *temp;
  839. int success = 0;
  840. Py_ssize_t i, pos = 0;
  841. local = PySet_New(NULL); /* collect new names bound in block */
  842. if (!local)
  843. goto error;
  844. scopes = PyDict_New(); /* collect scopes defined for each name */
  845. if (!scopes)
  846. goto error;
  847. /* Allocate new global, bound and free variable sets. These
  848. sets hold the names visible in nested blocks. For
  849. ClassBlocks, the bound and global names are initialized
  850. before analyzing names, because class bindings aren't
  851. visible in methods. For other blocks, they are initialized
  852. after names are analyzed.
  853. */
  854. /* TODO(jhylton): Package these dicts in a struct so that we
  855. can write reasonable helper functions?
  856. */
  857. newglobal = PySet_New(NULL);
  858. if (!newglobal)
  859. goto error;
  860. newfree = PySet_New(NULL);
  861. if (!newfree)
  862. goto error;
  863. newbound = PySet_New(NULL);
  864. if (!newbound)
  865. goto error;
  866. inlined_cells = PySet_New(NULL);
  867. if (!inlined_cells)
  868. goto error;
  869. /* Class namespace has no effect on names visible in
  870. nested functions, so populate the global and bound
  871. sets to be passed to child blocks before analyzing
  872. this one.
  873. */
  874. if (ste->ste_type == ClassBlock) {
  875. /* Pass down known globals */
  876. temp = PyNumber_InPlaceOr(newglobal, global);
  877. if (!temp)
  878. goto error;
  879. Py_DECREF(temp);
  880. /* Pass down previously bound symbols */
  881. if (bound) {
  882. temp = PyNumber_InPlaceOr(newbound, bound);
  883. if (!temp)
  884. goto error;
  885. Py_DECREF(temp);
  886. }
  887. }
  888. while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
  889. long flags = PyLong_AS_LONG(v);
  890. if (!analyze_name(ste, scopes, name, flags,
  891. bound, local, free, global, type_params, class_entry))
  892. goto error;
  893. }
  894. /* Populate global and bound sets to be passed to children. */
  895. if (ste->ste_type != ClassBlock) {
  896. /* Add function locals to bound set */
  897. if (_PyST_IsFunctionLike(ste)) {
  898. temp = PyNumber_InPlaceOr(newbound, local);
  899. if (!temp)
  900. goto error;
  901. Py_DECREF(temp);
  902. }
  903. /* Pass down previously bound symbols */
  904. if (bound) {
  905. temp = PyNumber_InPlaceOr(newbound, bound);
  906. if (!temp)
  907. goto error;
  908. Py_DECREF(temp);
  909. }
  910. /* Pass down known globals */
  911. temp = PyNumber_InPlaceOr(newglobal, global);
  912. if (!temp)
  913. goto error;
  914. Py_DECREF(temp);
  915. }
  916. else {
  917. /* Special-case __class__ and __classdict__ */
  918. if (PySet_Add(newbound, &_Py_ID(__class__)) < 0)
  919. goto error;
  920. if (PySet_Add(newbound, &_Py_ID(__classdict__)) < 0)
  921. goto error;
  922. }
  923. /* Recursively call analyze_child_block() on each child block.
  924. newbound, newglobal now contain the names visible in
  925. nested blocks. The free variables in the children will
  926. be added to newfree.
  927. */
  928. for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) {
  929. PyObject *child_free = NULL;
  930. PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
  931. PySTEntryObject* entry;
  932. assert(c && PySTEntry_Check(c));
  933. entry = (PySTEntryObject*)c;
  934. PySTEntryObject *new_class_entry = NULL;
  935. if (entry->ste_can_see_class_scope) {
  936. if (ste->ste_type == ClassBlock) {
  937. new_class_entry = ste;
  938. }
  939. else if (class_entry) {
  940. new_class_entry = class_entry;
  941. }
  942. }
  943. // we inline all non-generator-expression comprehensions
  944. int inline_comp =
  945. entry->ste_comprehension &&
  946. !entry->ste_generator;
  947. if (!analyze_child_block(entry, newbound, newfree, newglobal,
  948. type_params, new_class_entry, &child_free))
  949. {
  950. goto error;
  951. }
  952. if (inline_comp) {
  953. if (!inline_comprehension(ste, entry, scopes, child_free, inlined_cells)) {
  954. Py_DECREF(child_free);
  955. goto error;
  956. }
  957. entry->ste_comp_inlined = 1;
  958. }
  959. temp = PyNumber_InPlaceOr(newfree, child_free);
  960. Py_DECREF(child_free);
  961. if (!temp)
  962. goto error;
  963. Py_DECREF(temp);
  964. /* Check if any children have free variables */
  965. if (entry->ste_free || entry->ste_child_free)
  966. ste->ste_child_free = 1;
  967. }
  968. /* Splice children of inlined comprehensions into our children list */
  969. for (i = PyList_GET_SIZE(ste->ste_children) - 1; i >= 0; --i) {
  970. PyObject* c = PyList_GET_ITEM(ste->ste_children, i);
  971. PySTEntryObject* entry;
  972. assert(c && PySTEntry_Check(c));
  973. entry = (PySTEntryObject*)c;
  974. if (entry->ste_comp_inlined &&
  975. PyList_SetSlice(ste->ste_children, i, i + 1,
  976. entry->ste_children) < 0)
  977. {
  978. goto error;
  979. }
  980. }
  981. /* Check if any local variables must be converted to cell variables */
  982. if (_PyST_IsFunctionLike(ste) && !analyze_cells(scopes, newfree, inlined_cells))
  983. goto error;
  984. else if (ste->ste_type == ClassBlock && !drop_class_free(ste, newfree))
  985. goto error;
  986. /* Records the results of the analysis in the symbol table entry */
  987. if (!update_symbols(ste->ste_symbols, scopes, bound, newfree, inlined_cells,
  988. (ste->ste_type == ClassBlock) || ste->ste_can_see_class_scope))
  989. goto error;
  990. temp = PyNumber_InPlaceOr(free, newfree);
  991. if (!temp)
  992. goto error;
  993. Py_DECREF(temp);
  994. success = 1;
  995. error:
  996. Py_XDECREF(scopes);
  997. Py_XDECREF(local);
  998. Py_XDECREF(newbound);
  999. Py_XDECREF(newglobal);
  1000. Py_XDECREF(newfree);
  1001. Py_XDECREF(inlined_cells);
  1002. if (!success)
  1003. assert(PyErr_Occurred());
  1004. return success;
  1005. }
  1006. static int
  1007. analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free,
  1008. PyObject *global, PyObject *type_params,
  1009. PySTEntryObject *class_entry, PyObject** child_free)
  1010. {
  1011. PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL;
  1012. PyObject *temp_type_params = NULL;
  1013. /* Copy the bound/global/free sets.
  1014. These sets are used by all blocks enclosed by the
  1015. current block. The analyze_block() call modifies these
  1016. sets.
  1017. */
  1018. temp_bound = PySet_New(bound);
  1019. if (!temp_bound)
  1020. goto error;
  1021. temp_free = PySet_New(free);
  1022. if (!temp_free)
  1023. goto error;
  1024. temp_global = PySet_New(global);
  1025. if (!temp_global)
  1026. goto error;
  1027. temp_type_params = PySet_New(type_params);
  1028. if (!temp_type_params)
  1029. goto error;
  1030. if (!analyze_block(entry, temp_bound, temp_free, temp_global,
  1031. temp_type_params, class_entry))
  1032. goto error;
  1033. *child_free = temp_free;
  1034. Py_DECREF(temp_bound);
  1035. Py_DECREF(temp_global);
  1036. Py_DECREF(temp_type_params);
  1037. return 1;
  1038. error:
  1039. Py_XDECREF(temp_bound);
  1040. Py_XDECREF(temp_free);
  1041. Py_XDECREF(temp_global);
  1042. Py_XDECREF(temp_type_params);
  1043. return 0;
  1044. }
  1045. static int
  1046. symtable_analyze(struct symtable *st)
  1047. {
  1048. PyObject *free, *global, *type_params;
  1049. int r;
  1050. free = PySet_New(NULL);
  1051. if (!free)
  1052. return 0;
  1053. global = PySet_New(NULL);
  1054. if (!global) {
  1055. Py_DECREF(free);
  1056. return 0;
  1057. }
  1058. type_params = PySet_New(NULL);
  1059. if (!type_params) {
  1060. Py_DECREF(free);
  1061. Py_DECREF(global);
  1062. return 0;
  1063. }
  1064. r = analyze_block(st->st_top, NULL, free, global, type_params, NULL);
  1065. Py_DECREF(free);
  1066. Py_DECREF(global);
  1067. Py_DECREF(type_params);
  1068. return r;
  1069. }
  1070. /* symtable_enter_block() gets a reference via ste_new.
  1071. This reference is released when the block is exited, via the DECREF
  1072. in symtable_exit_block().
  1073. */
  1074. static int
  1075. symtable_exit_block(struct symtable *st)
  1076. {
  1077. Py_ssize_t size;
  1078. st->st_cur = NULL;
  1079. size = PyList_GET_SIZE(st->st_stack);
  1080. if (size) {
  1081. if (PyList_SetSlice(st->st_stack, size - 1, size, NULL) < 0)
  1082. return 0;
  1083. if (--size)
  1084. st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack, size - 1);
  1085. }
  1086. return 1;
  1087. }
  1088. static int
  1089. symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block,
  1090. void *ast, int lineno, int col_offset,
  1091. int end_lineno, int end_col_offset)
  1092. {
  1093. PySTEntryObject *prev = NULL, *ste;
  1094. ste = ste_new(st, name, block, ast, lineno, col_offset, end_lineno, end_col_offset);
  1095. if (ste == NULL)
  1096. return 0;
  1097. if (PyList_Append(st->st_stack, (PyObject *)ste) < 0) {
  1098. Py_DECREF(ste);
  1099. return 0;
  1100. }
  1101. prev = st->st_cur;
  1102. /* bpo-37757: For now, disallow *all* assignment expressions in the
  1103. * outermost iterator expression of a comprehension, even those inside
  1104. * a nested comprehension or a lambda expression.
  1105. */
  1106. if (prev) {
  1107. ste->ste_comp_iter_expr = prev->ste_comp_iter_expr;
  1108. }
  1109. /* No need to inherit ste_mangled_names in classes, where all names
  1110. * are mangled. */
  1111. if (prev && prev->ste_mangled_names != NULL && block != ClassBlock) {
  1112. ste->ste_mangled_names = Py_NewRef(prev->ste_mangled_names);
  1113. }
  1114. /* The entry is owned by the stack. Borrow it for st_cur. */
  1115. Py_DECREF(ste);
  1116. st->st_cur = ste;
  1117. /* Annotation blocks shouldn't have any affect on the symbol table since in
  1118. * the compilation stage, they will all be transformed to strings. They are
  1119. * only created if future 'annotations' feature is activated. */
  1120. if (block == AnnotationBlock) {
  1121. return 1;
  1122. }
  1123. if (block == ModuleBlock)
  1124. st->st_global = st->st_cur->ste_symbols;
  1125. if (prev) {
  1126. if (PyList_Append(prev->ste_children, (PyObject *)ste) < 0) {
  1127. return 0;
  1128. }
  1129. }
  1130. return 1;
  1131. }
  1132. static long
  1133. symtable_lookup_entry(struct symtable *st, PySTEntryObject *ste, PyObject *name)
  1134. {
  1135. PyObject *mangled = _Py_MaybeMangle(st->st_private, ste, name);
  1136. if (!mangled)
  1137. return 0;
  1138. long ret = _PyST_GetSymbol(ste, mangled);
  1139. Py_DECREF(mangled);
  1140. return ret;
  1141. }
  1142. static long
  1143. symtable_lookup(struct symtable *st, PyObject *name)
  1144. {
  1145. return symtable_lookup_entry(st, st->st_cur, name);
  1146. }
  1147. static int
  1148. symtable_add_def_helper(struct symtable *st, PyObject *name, int flag, struct _symtable_entry *ste,
  1149. int lineno, int col_offset, int end_lineno, int end_col_offset)
  1150. {
  1151. PyObject *o;
  1152. PyObject *dict;
  1153. long val;
  1154. PyObject *mangled = _Py_MaybeMangle(st->st_private, st->st_cur, name);
  1155. if (!mangled)
  1156. return 0;
  1157. dict = ste->ste_symbols;
  1158. if ((o = PyDict_GetItemWithError(dict, mangled))) {
  1159. val = PyLong_AS_LONG(o);
  1160. if ((flag & DEF_PARAM) && (val & DEF_PARAM)) {
  1161. /* Is it better to use 'mangled' or 'name' here? */
  1162. PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT, name);
  1163. PyErr_RangedSyntaxLocationObject(st->st_filename,
  1164. lineno, col_offset + 1,
  1165. end_lineno, end_col_offset + 1);
  1166. goto error;
  1167. }
  1168. if ((flag & DEF_TYPE_PARAM) && (val & DEF_TYPE_PARAM)) {
  1169. PyErr_Format(PyExc_SyntaxError, DUPLICATE_TYPE_PARAM, name);
  1170. PyErr_RangedSyntaxLocationObject(st->st_filename,
  1171. lineno, col_offset + 1,
  1172. end_lineno, end_col_offset + 1);
  1173. goto error;
  1174. }
  1175. val |= flag;
  1176. }
  1177. else if (PyErr_Occurred()) {
  1178. goto error;
  1179. }
  1180. else {
  1181. val = flag;
  1182. }
  1183. if (ste->ste_comp_iter_target) {
  1184. /* This name is an iteration variable in a comprehension,
  1185. * so check for a binding conflict with any named expressions.
  1186. * Otherwise, mark it as an iteration variable so subsequent
  1187. * named expressions can check for conflicts.
  1188. */
  1189. if (val & (DEF_GLOBAL | DEF_NONLOCAL)) {
  1190. PyErr_Format(PyExc_SyntaxError,
  1191. NAMED_EXPR_COMP_INNER_LOOP_CONFLICT, name);
  1192. PyErr_RangedSyntaxLocationObject(st->st_filename,
  1193. lineno, col_offset + 1,
  1194. end_lineno, end_col_offset + 1);
  1195. goto error;
  1196. }
  1197. val |= DEF_COMP_ITER;
  1198. }
  1199. o = PyLong_FromLong(val);
  1200. if (o == NULL)
  1201. goto error;
  1202. if (PyDict_SetItem(dict, mangled, o) < 0) {
  1203. Py_DECREF(o);
  1204. goto error;
  1205. }
  1206. Py_DECREF(o);
  1207. if (flag & DEF_PARAM) {
  1208. if (PyList_Append(ste->ste_varnames, mangled) < 0)
  1209. goto error;
  1210. } else if (flag & DEF_GLOBAL) {
  1211. /* XXX need to update DEF_GLOBAL for other flags too;
  1212. perhaps only DEF_FREE_GLOBAL */
  1213. val = flag;
  1214. if ((o = PyDict_GetItemWithError(st->st_global, mangled))) {
  1215. val |= PyLong_AS_LONG(o);
  1216. }
  1217. else if (PyErr_Occurred()) {
  1218. goto error;
  1219. }
  1220. o = PyLong_FromLong(val);
  1221. if (o == NULL)
  1222. goto error;
  1223. if (PyDict_SetItem(st->st_global, mangled, o) < 0) {
  1224. Py_DECREF(o);
  1225. goto error;
  1226. }
  1227. Py_DECREF(o);
  1228. }
  1229. Py_DECREF(mangled);
  1230. return 1;
  1231. error:
  1232. Py_DECREF(mangled);
  1233. return 0;
  1234. }
  1235. static int
  1236. symtable_add_def(struct symtable *st, PyObject *name, int flag,
  1237. int lineno, int col_offset, int end_lineno, int end_col_offset)
  1238. {
  1239. if ((flag & DEF_TYPE_PARAM) && st->st_cur->ste_mangled_names != NULL) {
  1240. if(PySet_Add(st->st_cur->ste_mangled_names, name) < 0) {
  1241. return 0;
  1242. }
  1243. }
  1244. return symtable_add_def_helper(st, name, flag, st->st_cur,
  1245. lineno, col_offset, end_lineno, end_col_offset);
  1246. }
  1247. static int
  1248. symtable_enter_type_param_block(struct symtable *st, identifier name,
  1249. void *ast, int has_defaults, int has_kwdefaults,
  1250. enum _stmt_kind kind,
  1251. int lineno, int col_offset,
  1252. int end_lineno, int end_col_offset)
  1253. {
  1254. _Py_block_ty current_type = st->st_cur->ste_type;
  1255. if(!symtable_enter_block(st, name, TypeParamBlock, ast, lineno,
  1256. col_offset, end_lineno, end_col_offset)) {
  1257. return 0;
  1258. }
  1259. if (current_type == ClassBlock) {
  1260. st->st_cur->ste_can_see_class_scope = 1;
  1261. if (!symtable_add_def(st, &_Py_ID(__classdict__), USE, lineno, col_offset, end_lineno, end_col_offset)) {
  1262. return 0;
  1263. }
  1264. }
  1265. if (kind == ClassDef_kind) {
  1266. _Py_DECLARE_STR(type_params, ".type_params");
  1267. // It gets "set" when we create the type params tuple and
  1268. // "used" when we build up the bases.
  1269. if (!symtable_add_def(st, &_Py_STR(type_params), DEF_LOCAL,
  1270. lineno, col_offset, end_lineno, end_col_offset)) {
  1271. return 0;
  1272. }
  1273. if (!symtable_add_def(st, &_Py_STR(type_params), USE,
  1274. lineno, col_offset, end_lineno, end_col_offset)) {
  1275. return 0;
  1276. }
  1277. // This is used for setting the generic base
  1278. _Py_DECLARE_STR(generic_base, ".generic_base");
  1279. if (!symtable_add_def(st, &_Py_STR(generic_base), DEF_LOCAL,
  1280. lineno, col_offset, end_lineno, end_col_offset)) {
  1281. return 0;
  1282. }
  1283. if (!symtable_add_def(st, &_Py_STR(generic_base), USE,
  1284. lineno, col_offset, end_lineno, end_col_offset)) {
  1285. return 0;
  1286. }
  1287. }
  1288. if (has_defaults) {
  1289. _Py_DECLARE_STR(defaults, ".defaults");
  1290. if (!symtable_add_def(st, &_Py_STR(defaults), DEF_PARAM,
  1291. lineno, col_offset, end_lineno, end_col_offset)) {
  1292. return 0;
  1293. }
  1294. }
  1295. if (has_kwdefaults) {
  1296. _Py_DECLARE_STR(kwdefaults, ".kwdefaults");
  1297. if (!symtable_add_def(st, &_Py_STR(kwdefaults), DEF_PARAM,
  1298. lineno, col_offset, end_lineno, end_col_offset)) {
  1299. return 0;
  1300. }
  1301. }
  1302. return 1;
  1303. }
  1304. /* VISIT, VISIT_SEQ and VIST_SEQ_TAIL take an ASDL type as their second argument.
  1305. They use the ASDL name to synthesize the name of the C type and the visit
  1306. function.
  1307. VISIT_SEQ_TAIL permits the start of an ASDL sequence to be skipped, which is
  1308. useful if the first node in the sequence requires special treatment.
  1309. VISIT_QUIT macro returns the specified value exiting from the function but
  1310. first adjusts current recursion counter depth.
  1311. */
  1312. #define VISIT_QUIT(ST, X) \
  1313. return --(ST)->recursion_depth,(X)
  1314. #define VISIT(ST, TYPE, V) \
  1315. if (!symtable_visit_ ## TYPE((ST), (V))) \
  1316. VISIT_QUIT((ST), 0);
  1317. #define VISIT_SEQ(ST, TYPE, SEQ) { \
  1318. int i; \
  1319. asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
  1320. for (i = 0; i < asdl_seq_LEN(seq); i++) { \
  1321. TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
  1322. if (!symtable_visit_ ## TYPE((ST), elt)) \
  1323. VISIT_QUIT((ST), 0); \
  1324. } \
  1325. }
  1326. #define VISIT_SEQ_TAIL(ST, TYPE, SEQ, START) { \
  1327. int i; \
  1328. asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
  1329. for (i = (START); i < asdl_seq_LEN(seq); i++) { \
  1330. TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
  1331. if (!symtable_visit_ ## TYPE((ST), elt)) \
  1332. VISIT_QUIT((ST), 0); \
  1333. } \
  1334. }
  1335. #define VISIT_SEQ_WITH_NULL(ST, TYPE, SEQ) { \
  1336. int i = 0; \
  1337. asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
  1338. for (i = 0; i < asdl_seq_LEN(seq); i++) { \
  1339. TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
  1340. if (!elt) continue; /* can be NULL */ \
  1341. if (!symtable_visit_ ## TYPE((ST), elt)) \
  1342. VISIT_QUIT((ST), 0); \
  1343. } \
  1344. }
  1345. static int
  1346. symtable_record_directive(struct symtable *st, identifier name, int lineno,
  1347. int col_offset, int end_lineno, int end_col_offset)
  1348. {
  1349. PyObject *data, *mangled;
  1350. int res;
  1351. if (!st->st_cur->ste_directives) {
  1352. st->st_cur->ste_directives = PyList_New(0);
  1353. if (!st->st_cur->ste_directives)
  1354. return 0;
  1355. }
  1356. mangled = _Py_MaybeMangle(st->st_private, st->st_cur, name);
  1357. if (!mangled)
  1358. return 0;
  1359. data = Py_BuildValue("(Niiii)", mangled, lineno, col_offset, end_lineno, end_col_offset);
  1360. if (!data)
  1361. return 0;
  1362. res = PyList_Append(st->st_cur->ste_directives, data);
  1363. Py_DECREF(data);
  1364. return res == 0;
  1365. }
  1366. static int
  1367. has_kwonlydefaults(asdl_arg_seq *kwonlyargs, asdl_expr_seq *kw_defaults)
  1368. {
  1369. for (int i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
  1370. expr_ty default_ = asdl_seq_GET(kw_defaults, i);
  1371. if (default_) {
  1372. return 1;
  1373. }
  1374. }
  1375. return 0;
  1376. }
  1377. static int
  1378. symtable_visit_stmt(struct symtable *st, stmt_ty s)
  1379. {
  1380. if (++st->recursion_depth > st->recursion_limit) {
  1381. PyErr_SetString(PyExc_RecursionError,
  1382. "maximum recursion depth exceeded during compilation");
  1383. VISIT_QUIT(st, 0);
  1384. }
  1385. switch (s->kind) {
  1386. case FunctionDef_kind:
  1387. if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL, LOCATION(s)))
  1388. VISIT_QUIT(st, 0);
  1389. if (s->v.FunctionDef.args->defaults)
  1390. VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults);
  1391. if (s->v.FunctionDef.args->kw_defaults)
  1392. VISIT_SEQ_WITH_NULL(st, expr, s->v.FunctionDef.args->kw_defaults);
  1393. if (s->v.FunctionDef.decorator_list)
  1394. VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list);
  1395. if (asdl_seq_LEN(s->v.FunctionDef.type_params) > 0) {
  1396. if (!symtable_enter_type_param_block(
  1397. st, s->v.FunctionDef.name,
  1398. (void *)s->v.FunctionDef.type_params,
  1399. s->v.FunctionDef.args->defaults != NULL,
  1400. has_kwonlydefaults(s->v.FunctionDef.args->kwonlyargs,
  1401. s->v.FunctionDef.args->kw_defaults),
  1402. s->kind,
  1403. LOCATION(s))) {
  1404. VISIT_QUIT(st, 0);
  1405. }
  1406. VISIT_SEQ(st, type_param, s->v.FunctionDef.type_params);
  1407. }
  1408. if (!symtable_visit_annotations(st, s, s->v.FunctionDef.args,
  1409. s->v.FunctionDef.returns))
  1410. VISIT_QUIT(st, 0);
  1411. if (!symtable_enter_block(st, s->v.FunctionDef.name,
  1412. FunctionBlock, (void *)s,
  1413. LOCATION(s)))
  1414. VISIT_QUIT(st, 0);
  1415. VISIT(st, arguments, s->v.FunctionDef.args);
  1416. VISIT_SEQ(st, stmt, s->v.FunctionDef.body);
  1417. if (!symtable_exit_block(st))
  1418. VISIT_QUIT(st, 0);
  1419. if (asdl_seq_LEN(s->v.FunctionDef.type_params) > 0) {
  1420. if (!symtable_exit_block(st))
  1421. VISIT_QUIT(st, 0);
  1422. }
  1423. break;
  1424. case ClassDef_kind: {
  1425. PyObject *tmp;
  1426. if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL, LOCATION(s)))
  1427. VISIT_QUIT(st, 0);
  1428. if (s->v.ClassDef.decorator_list)
  1429. VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list);
  1430. tmp = st->st_private;
  1431. if (asdl_seq_LEN(s->v.ClassDef.type_params) > 0) {
  1432. if (!symtable_enter_type_param_block(st, s->v.ClassDef.name,
  1433. (void *)s->v.ClassDef.type_params,
  1434. false, false, s->kind,
  1435. LOCATION(s))) {
  1436. VISIT_QUIT(st, 0);
  1437. }
  1438. st->st_private = s->v.ClassDef.name;
  1439. st->st_cur->ste_mangled_names = PySet_New(NULL);
  1440. if (!st->st_cur->ste_mangled_names) {
  1441. VISIT_QUIT(st, 0);
  1442. }
  1443. VISIT_SEQ(st, type_param, s->v.ClassDef.type_params);
  1444. }
  1445. VISIT_SEQ(st, expr, s->v.ClassDef.bases);
  1446. VISIT_SEQ(st, keyword, s->v.ClassDef.keywords);
  1447. if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock,
  1448. (void *)s, s->lineno, s->col_offset,
  1449. s->end_lineno, s->end_col_offset))
  1450. VISIT_QUIT(st, 0);
  1451. st->st_private = s->v.ClassDef.name;
  1452. if (asdl_seq_LEN(s->v.ClassDef.type_params) > 0) {
  1453. if (!symtable_add_def(st, &_Py_ID(__type_params__),
  1454. DEF_LOCAL, LOCATION(s))) {
  1455. VISIT_QUIT(st, 0);
  1456. }
  1457. _Py_DECLARE_STR(type_params, ".type_params");
  1458. if (!symtable_add_def(st, &_Py_STR(type_params),
  1459. USE, LOCATION(s))) {
  1460. VISIT_QUIT(st, 0);
  1461. }
  1462. }
  1463. VISIT_SEQ(st, stmt, s->v.ClassDef.body);
  1464. if (!symtable_exit_block(st))
  1465. VISIT_QUIT(st, 0);
  1466. if (asdl_seq_LEN(s->v.ClassDef.type_params) > 0) {
  1467. if (!symtable_exit_block(st))
  1468. VISIT_QUIT(st, 0);
  1469. }
  1470. st->st_private = tmp;
  1471. break;
  1472. }
  1473. case TypeAlias_kind: {
  1474. VISIT(st, expr, s->v.TypeAlias.name);
  1475. assert(s->v.TypeAlias.name->kind == Name_kind);
  1476. PyObject *name = s->v.TypeAlias.name->v.Name.id;
  1477. int is_in_class = st->st_cur->ste_type == ClassBlock;
  1478. int is_generic = asdl_seq_LEN(s->v.TypeAlias.type_params) > 0;
  1479. if (is_generic) {
  1480. if (!symtable_enter_type_param_block(
  1481. st, name,
  1482. (void *)s->v.TypeAlias.type_params,
  1483. false, false, s->kind,
  1484. LOCATION(s))) {
  1485. VISIT_QUIT(st, 0);
  1486. }
  1487. VISIT_SEQ(st, type_param, s->v.TypeAlias.type_params);
  1488. }
  1489. if (!symtable_enter_block(st, name, TypeAliasBlock,
  1490. (void *)s, LOCATION(s)))
  1491. VISIT_QUIT(st, 0);
  1492. st->st_cur->ste_can_see_class_scope = is_in_class;
  1493. if (is_in_class && !symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(s->v.TypeAlias.value))) {
  1494. VISIT_QUIT(st, 0);
  1495. }
  1496. VISIT(st, expr, s->v.TypeAlias.value);
  1497. if (!symtable_exit_block(st))
  1498. VISIT_QUIT(st, 0);
  1499. if (is_generic) {
  1500. if (!symtable_exit_block(st))
  1501. VISIT_QUIT(st, 0);
  1502. }
  1503. break;
  1504. }
  1505. case Return_kind:
  1506. if (s->v.Return.value) {
  1507. VISIT(st, expr, s->v.Return.value);
  1508. st->st_cur->ste_returns_value = 1;
  1509. }
  1510. break;
  1511. case Delete_kind:
  1512. VISIT_SEQ(st, expr, s->v.Delete.targets);
  1513. break;
  1514. case Assign_kind:
  1515. VISIT_SEQ(st, expr, s->v.Assign.targets);
  1516. VISIT(st, expr, s->v.Assign.value);
  1517. break;
  1518. case AnnAssign_kind:
  1519. if (s->v.AnnAssign.target->kind == Name_kind) {
  1520. expr_ty e_name = s->v.AnnAssign.target;
  1521. long cur = symtable_lookup(st, e_name->v.Name.id);
  1522. if (cur < 0) {
  1523. VISIT_QUIT(st, 0);
  1524. }
  1525. if ((cur & (DEF_GLOBAL | DEF_NONLOCAL))
  1526. && (st->st_cur->ste_symbols != st->st_global)
  1527. && s->v.AnnAssign.simple) {
  1528. PyErr_Format(PyExc_SyntaxError,
  1529. cur & DEF_GLOBAL ? GLOBAL_ANNOT : NONLOCAL_ANNOT,
  1530. e_name->v.Name.id);
  1531. PyErr_RangedSyntaxLocationObject(st->st_filename,
  1532. s->lineno,
  1533. s->col_offset + 1,
  1534. s->end_lineno,
  1535. s->end_col_offset + 1);
  1536. VISIT_QUIT(st, 0);
  1537. }
  1538. if (s->v.AnnAssign.simple &&
  1539. !symtable_add_def(st, e_name->v.Name.id,
  1540. DEF_ANNOT | DEF_LOCAL, LOCATION(e_name))) {
  1541. VISIT_QUIT(st, 0);
  1542. }
  1543. else {
  1544. if (s->v.AnnAssign.value
  1545. && !symtable_add_def(st, e_name->v.Name.id, DEF_LOCAL, LOCATION(e_name))) {
  1546. VISIT_QUIT(st, 0);
  1547. }
  1548. }
  1549. }
  1550. else {
  1551. VISIT(st, expr, s->v.AnnAssign.target);
  1552. }
  1553. if (!symtable_visit_annotation(st, s->v.AnnAssign.annotation)) {
  1554. VISIT_QUIT(st, 0);
  1555. }
  1556. if (s->v.AnnAssign.value) {
  1557. VISIT(st, expr, s->v.AnnAssign.value);
  1558. }
  1559. break;
  1560. case AugAssign_kind:
  1561. VISIT(st, expr, s->v.AugAssign.target);
  1562. VISIT(st, expr, s->v.AugAssign.value);
  1563. break;
  1564. case For_kind:
  1565. VISIT(st, expr, s->v.For.target);
  1566. VISIT(st, expr, s->v.For.iter);
  1567. VISIT_SEQ(st, stmt, s->v.For.body);
  1568. if (s->v.For.orelse)
  1569. VISIT_SEQ(st, stmt, s->v.For.orelse);
  1570. break;
  1571. case While_kind:
  1572. VISIT(st, expr, s->v.While.test);
  1573. VISIT_SEQ(st, stmt, s->v.While.body);
  1574. if (s->v.While.orelse)
  1575. VISIT_SEQ(st, stmt, s->v.While.orelse);
  1576. break;
  1577. case If_kind:
  1578. /* XXX if 0: and lookup_yield() hacks */
  1579. VISIT(st, expr, s->v.If.test);
  1580. VISIT_SEQ(st, stmt, s->v.If.body);
  1581. if (s->v.If.orelse)
  1582. VISIT_SEQ(st, stmt, s->v.If.orelse);
  1583. break;
  1584. case Match_kind:
  1585. VISIT(st, expr, s->v.Match.subject);
  1586. VISIT_SEQ(st, match_case, s->v.Match.cases);
  1587. break;
  1588. case Raise_kind:
  1589. if (s->v.Raise.exc) {
  1590. VISIT(st, expr, s->v.Raise.exc);
  1591. if (s->v.Raise.cause) {
  1592. VISIT(st, expr, s->v.Raise.cause);
  1593. }
  1594. }
  1595. break;
  1596. case Try_kind:
  1597. VISIT_SEQ(st, stmt, s->v.Try.body);
  1598. VISIT_SEQ(st, stmt, s->v.Try.orelse);
  1599. VISIT_SEQ(st, excepthandler, s->v.Try.handlers);
  1600. VISIT_SEQ(st, stmt, s->v.Try.finalbody);
  1601. break;
  1602. case TryStar_kind:
  1603. VISIT_SEQ(st, stmt, s->v.TryStar.body);
  1604. VISIT_SEQ(st, stmt, s->v.TryStar.orelse);
  1605. VISIT_SEQ(st, excepthandler, s->v.TryStar.handlers);
  1606. VISIT_SEQ(st, stmt, s->v.TryStar.finalbody);
  1607. break;
  1608. case Assert_kind:
  1609. VISIT(st, expr, s->v.Assert.test);
  1610. if (s->v.Assert.msg)
  1611. VISIT(st, expr, s->v.Assert.msg);
  1612. break;
  1613. case Import_kind:
  1614. VISIT_SEQ(st, alias, s->v.Import.names);
  1615. break;
  1616. case ImportFrom_kind:
  1617. VISIT_SEQ(st, alias, s->v.ImportFrom.names);
  1618. break;
  1619. case Global_kind: {
  1620. int i;
  1621. asdl_identifier_seq *seq = s->v.Global.names;
  1622. for (i = 0; i < asdl_seq_LEN(seq); i++) {
  1623. identifier name = (identifier)asdl_seq_GET(seq, i);
  1624. long cur = symtable_lookup(st, name);
  1625. if (cur < 0)
  1626. VISIT_QUIT(st, 0);
  1627. if (cur & (DEF_PARAM | DEF_LOCAL | USE | DEF_ANNOT)) {
  1628. const char* msg;
  1629. if (cur & DEF_PARAM) {
  1630. msg = GLOBAL_PARAM;
  1631. } else if (cur & USE) {
  1632. msg = GLOBAL_AFTER_USE;
  1633. } else if (cur & DEF_ANNOT) {
  1634. msg = GLOBAL_ANNOT;
  1635. } else { /* DEF_LOCAL */
  1636. msg = GLOBAL_AFTER_ASSIGN;
  1637. }
  1638. PyErr_Format(PyExc_SyntaxError,
  1639. msg, name);
  1640. PyErr_RangedSyntaxLocationObject(st->st_filename,
  1641. s->lineno,
  1642. s->col_offset + 1,
  1643. s->end_lineno,
  1644. s->end_col_offset + 1);
  1645. VISIT_QUIT(st, 0);
  1646. }
  1647. if (!symtable_add_def(st, name, DEF_GLOBAL, LOCATION(s)))
  1648. VISIT_QUIT(st, 0);
  1649. if (!symtable_record_directive(st, name, s->lineno, s->col_offset,
  1650. s->end_lineno, s->end_col_offset))
  1651. VISIT_QUIT(st, 0);
  1652. }
  1653. break;
  1654. }
  1655. case Nonlocal_kind: {
  1656. int i;
  1657. asdl_identifier_seq *seq = s->v.Nonlocal.names;
  1658. for (i = 0; i < asdl_seq_LEN(seq); i++) {
  1659. identifier name = (identifier)asdl_seq_GET(seq, i);
  1660. long cur = symtable_lookup(st, name);
  1661. if (cur < 0)
  1662. VISIT_QUIT(st, 0);
  1663. if (cur & (DEF_PARAM | DEF_LOCAL | USE | DEF_ANNOT)) {
  1664. const char* msg;
  1665. if (cur & DEF_PARAM) {
  1666. msg = NONLOCAL_PARAM;
  1667. } else if (cur & USE) {
  1668. msg = NONLOCAL_AFTER_USE;
  1669. } else if (cur & DEF_ANNOT) {
  1670. msg = NONLOCAL_ANNOT;
  1671. } else { /* DEF_LOCAL */
  1672. msg = NONLOCAL_AFTER_ASSIGN;
  1673. }
  1674. PyErr_Format(PyExc_SyntaxError, msg, name);
  1675. PyErr_RangedSyntaxLocationObject(st->st_filename,
  1676. s->lineno,
  1677. s->col_offset + 1,
  1678. s->end_lineno,
  1679. s->end_col_offset + 1);
  1680. VISIT_QUIT(st, 0);
  1681. }
  1682. if (!symtable_add_def(st, name, DEF_NONLOCAL, LOCATION(s)))
  1683. VISIT_QUIT(st, 0);
  1684. if (!symtable_record_directive(st, name, s->lineno, s->col_offset,
  1685. s->end_lineno, s->end_col_offset))
  1686. VISIT_QUIT(st, 0);
  1687. }
  1688. break;
  1689. }
  1690. case Expr_kind:
  1691. VISIT(st, expr, s->v.Expr.value);
  1692. break;
  1693. case Pass_kind:
  1694. case Break_kind:
  1695. case Continue_kind:
  1696. /* nothing to do here */
  1697. break;
  1698. case With_kind:
  1699. VISIT_SEQ(st, withitem, s->v.With.items);
  1700. VISIT_SEQ(st, stmt, s->v.With.body);
  1701. break;
  1702. case AsyncFunctionDef_kind:
  1703. if (!symtable_add_def(st, s->v.AsyncFunctionDef.name, DEF_LOCAL, LOCATION(s)))
  1704. VISIT_QUIT(st, 0);
  1705. if (s->v.AsyncFunctionDef.args->defaults)
  1706. VISIT_SEQ(st, expr, s->v.AsyncFunctionDef.args->defaults);
  1707. if (s->v.AsyncFunctionDef.args->kw_defaults)
  1708. VISIT_SEQ_WITH_NULL(st, expr,
  1709. s->v.AsyncFunctionDef.args->kw_defaults);
  1710. if (s->v.AsyncFunctionDef.decorator_list)
  1711. VISIT_SEQ(st, expr, s->v.AsyncFunctionDef.decorator_list);
  1712. if (asdl_seq_LEN(s->v.AsyncFunctionDef.type_params) > 0) {
  1713. if (!symtable_enter_type_param_block(
  1714. st, s->v.AsyncFunctionDef.name,
  1715. (void *)s->v.AsyncFunctionDef.type_params,
  1716. s->v.AsyncFunctionDef.args->defaults != NULL,
  1717. has_kwonlydefaults(s->v.AsyncFunctionDef.args->kwonlyargs,
  1718. s->v.AsyncFunctionDef.args->kw_defaults),
  1719. s->kind,
  1720. LOCATION(s))) {
  1721. VISIT_QUIT(st, 0);
  1722. }
  1723. VISIT_SEQ(st, type_param, s->v.AsyncFunctionDef.type_params);
  1724. }
  1725. if (!symtable_visit_annotations(st, s, s->v.AsyncFunctionDef.args,
  1726. s->v.AsyncFunctionDef.returns))
  1727. VISIT_QUIT(st, 0);
  1728. if (!symtable_enter_block(st, s->v.AsyncFunctionDef.name,
  1729. FunctionBlock, (void *)s,
  1730. s->lineno, s->col_offset,
  1731. s->end_lineno, s->end_col_offset))
  1732. VISIT_QUIT(st, 0);
  1733. st->st_cur->ste_coroutine = 1;
  1734. VISIT(st, arguments, s->v.AsyncFunctionDef.args);
  1735. VISIT_SEQ(st, stmt, s->v.AsyncFunctionDef.body);
  1736. if (!symtable_exit_block(st))
  1737. VISIT_QUIT(st, 0);
  1738. if (asdl_seq_LEN(s->v.AsyncFunctionDef.type_params) > 0) {
  1739. if (!symtable_exit_block(st))
  1740. VISIT_QUIT(st, 0);
  1741. }
  1742. break;
  1743. case AsyncWith_kind:
  1744. VISIT_SEQ(st, withitem, s->v.AsyncWith.items);
  1745. VISIT_SEQ(st, stmt, s->v.AsyncWith.body);
  1746. break;
  1747. case AsyncFor_kind:
  1748. VISIT(st, expr, s->v.AsyncFor.target);
  1749. VISIT(st, expr, s->v.AsyncFor.iter);
  1750. VISIT_SEQ(st, stmt, s->v.AsyncFor.body);
  1751. if (s->v.AsyncFor.orelse)
  1752. VISIT_SEQ(st, stmt, s->v.AsyncFor.orelse);
  1753. break;
  1754. }
  1755. VISIT_QUIT(st, 1);
  1756. }
  1757. static int
  1758. symtable_extend_namedexpr_scope(struct symtable *st, expr_ty e)
  1759. {
  1760. assert(st->st_stack);
  1761. assert(e->kind == Name_kind);
  1762. PyObject *target_name = e->v.Name.id;
  1763. Py_ssize_t i, size;
  1764. struct _symtable_entry *ste;
  1765. size = PyList_GET_SIZE(st->st_stack);
  1766. assert(size);
  1767. /* Iterate over the stack in reverse and add to the nearest adequate scope */
  1768. for (i = size - 1; i >= 0; i--) {
  1769. ste = (struct _symtable_entry *) PyList_GET_ITEM(st->st_stack, i);
  1770. /* If we find a comprehension scope, check for a target
  1771. * binding conflict with iteration variables, otherwise skip it
  1772. */
  1773. if (ste->ste_comprehension) {
  1774. long target_in_scope = symtable_lookup_entry(st, ste, target_name);
  1775. if ((target_in_scope & DEF_COMP_ITER) &&
  1776. (target_in_scope & DEF_LOCAL)) {
  1777. PyErr_Format(PyExc_SyntaxError, NAMED_EXPR_COMP_CONFLICT, target_name);
  1778. PyErr_RangedSyntaxLocationObject(st->st_filename,
  1779. e->lineno,
  1780. e->col_offset + 1,
  1781. e->end_lineno,
  1782. e->end_col_offset + 1);
  1783. VISIT_QUIT(st, 0);
  1784. }
  1785. continue;
  1786. }
  1787. /* If we find a FunctionBlock entry, add as GLOBAL/LOCAL or NONLOCAL/LOCAL */
  1788. if (ste->ste_type == FunctionBlock) {
  1789. long target_in_scope = symtable_lookup_entry(st, ste, target_name);
  1790. if (target_in_scope & DEF_GLOBAL) {
  1791. if (!symtable_add_def(st, target_name, DEF_GLOBAL, LOCATION(e)))
  1792. VISIT_QUIT(st, 0);
  1793. } else {
  1794. if (!symtable_add_def(st, target_name, DEF_NONLOCAL, LOCATION(e)))
  1795. VISIT_QUIT(st, 0);
  1796. }
  1797. if (!symtable_record_directive(st, target_name, LOCATION(e)))
  1798. VISIT_QUIT(st, 0);
  1799. return symtable_add_def_helper(st, target_name, DEF_LOCAL, ste, LOCATION(e));
  1800. }
  1801. /* If we find a ModuleBlock entry, add as GLOBAL */
  1802. if (ste->ste_type == ModuleBlock) {
  1803. if (!symtable_add_def(st, target_name, DEF_GLOBAL, LOCATION(e)))
  1804. VISIT_QUIT(st, 0);
  1805. if (!symtable_record_directive(st, target_name, LOCATION(e)))
  1806. VISIT_QUIT(st, 0);
  1807. return symtable_add_def_helper(st, target_name, DEF_GLOBAL, ste, LOCATION(e));
  1808. }
  1809. /* Disallow usage in ClassBlock and type scopes */
  1810. if (ste->ste_type == ClassBlock ||
  1811. ste->ste_type == TypeParamBlock ||
  1812. ste->ste_type == TypeAliasBlock ||
  1813. ste->ste_type == TypeVarBoundBlock) {
  1814. switch (ste->ste_type) {
  1815. case ClassBlock:
  1816. PyErr_Format(PyExc_SyntaxError, NAMED_EXPR_COMP_IN_CLASS);
  1817. break;
  1818. case TypeParamBlock:
  1819. PyErr_Format(PyExc_SyntaxError, NAMED_EXPR_COMP_IN_TYPEPARAM);
  1820. break;
  1821. case TypeAliasBlock:
  1822. PyErr_Format(PyExc_SyntaxError, NAMED_EXPR_COMP_IN_TYPEALIAS);
  1823. break;
  1824. case TypeVarBoundBlock:
  1825. PyErr_Format(PyExc_SyntaxError, NAMED_EXPR_COMP_IN_TYPEVAR_BOUND);
  1826. break;
  1827. default:
  1828. Py_UNREACHABLE();
  1829. }
  1830. PyErr_RangedSyntaxLocationObject(st->st_filename,
  1831. e->lineno,
  1832. e->col_offset + 1,
  1833. e->end_lineno,
  1834. e->end_col_offset + 1);
  1835. VISIT_QUIT(st, 0);
  1836. }
  1837. }
  1838. /* We should always find either a function-like block, ModuleBlock or ClassBlock
  1839. and should never fall to this case
  1840. */
  1841. Py_UNREACHABLE();
  1842. return 0;
  1843. }
  1844. static int
  1845. symtable_handle_namedexpr(struct symtable *st, expr_ty e)
  1846. {
  1847. if (st->st_cur->ste_comp_iter_expr > 0) {
  1848. /* Assignment isn't allowed in a comprehension iterable expression */
  1849. PyErr_Format(PyExc_SyntaxError, NAMED_EXPR_COMP_ITER_EXPR);
  1850. PyErr_RangedSyntaxLocationObject(st->st_filename,
  1851. e->lineno,
  1852. e->col_offset + 1,
  1853. e->end_lineno,
  1854. e->end_col_offset + 1);
  1855. return 0;
  1856. }
  1857. if (st->st_cur->ste_comprehension) {
  1858. /* Inside a comprehension body, so find the right target scope */
  1859. if (!symtable_extend_namedexpr_scope(st, e->v.NamedExpr.target))
  1860. return 0;
  1861. }
  1862. VISIT(st, expr, e->v.NamedExpr.value);
  1863. VISIT(st, expr, e->v.NamedExpr.target);
  1864. return 1;
  1865. }
  1866. static int
  1867. symtable_visit_expr(struct symtable *st, expr_ty e)
  1868. {
  1869. if (++st->recursion_depth > st->recursion_limit) {
  1870. PyErr_SetString(PyExc_RecursionError,
  1871. "maximum recursion depth exceeded during compilation");
  1872. VISIT_QUIT(st, 0);
  1873. }
  1874. switch (e->kind) {
  1875. case NamedExpr_kind:
  1876. if (!symtable_raise_if_annotation_block(st, "named expression", e)) {
  1877. VISIT_QUIT(st, 0);
  1878. }
  1879. if(!symtable_handle_namedexpr(st, e))
  1880. VISIT_QUIT(st, 0);
  1881. break;
  1882. case BoolOp_kind:
  1883. VISIT_SEQ(st, expr, e->v.BoolOp.values);
  1884. break;
  1885. case BinOp_kind:
  1886. VISIT(st, expr, e->v.BinOp.left);
  1887. VISIT(st, expr, e->v.BinOp.right);
  1888. break;
  1889. case UnaryOp_kind:
  1890. VISIT(st, expr, e->v.UnaryOp.operand);
  1891. break;
  1892. case Lambda_kind: {
  1893. if (st->st_cur->ste_can_see_class_scope) {
  1894. // gh-109118
  1895. PyErr_Format(PyExc_SyntaxError,
  1896. "Cannot use lambda in annotation scope within class scope");
  1897. PyErr_RangedSyntaxLocationObject(st->st_filename,
  1898. e->lineno,
  1899. e->col_offset + 1,
  1900. e->end_lineno,
  1901. e->end_col_offset + 1);
  1902. VISIT_QUIT(st, 0);
  1903. }
  1904. if (e->v.Lambda.args->defaults)
  1905. VISIT_SEQ(st, expr, e->v.Lambda.args->defaults);
  1906. if (e->v.Lambda.args->kw_defaults)
  1907. VISIT_SEQ_WITH_NULL(st, expr, e->v.Lambda.args->kw_defaults);
  1908. if (!symtable_enter_block(st, &_Py_ID(lambda),
  1909. FunctionBlock, (void *)e,
  1910. e->lineno, e->col_offset,
  1911. e->end_lineno, e->end_col_offset))
  1912. VISIT_QUIT(st, 0);
  1913. VISIT(st, arguments, e->v.Lambda.args);
  1914. VISIT(st, expr, e->v.Lambda.body);
  1915. if (!symtable_exit_block(st))
  1916. VISIT_QUIT(st, 0);
  1917. break;
  1918. }
  1919. case IfExp_kind:
  1920. VISIT(st, expr, e->v.IfExp.test);
  1921. VISIT(st, expr, e->v.IfExp.body);
  1922. VISIT(st, expr, e->v.IfExp.orelse);
  1923. break;
  1924. case Dict_kind:
  1925. VISIT_SEQ_WITH_NULL(st, expr, e->v.Dict.keys);
  1926. VISIT_SEQ(st, expr, e->v.Dict.values);
  1927. break;
  1928. case Set_kind:
  1929. VISIT_SEQ(st, expr, e->v.Set.elts);
  1930. break;
  1931. case GeneratorExp_kind:
  1932. if (!symtable_visit_genexp(st, e))
  1933. VISIT_QUIT(st, 0);
  1934. break;
  1935. case ListComp_kind:
  1936. if (!symtable_visit_listcomp(st, e))
  1937. VISIT_QUIT(st, 0);
  1938. break;
  1939. case SetComp_kind:
  1940. if (!symtable_visit_setcomp(st, e))
  1941. VISIT_QUIT(st, 0);
  1942. break;
  1943. case DictComp_kind:
  1944. if (!symtable_visit_dictcomp(st, e))
  1945. VISIT_QUIT(st, 0);
  1946. break;
  1947. case Yield_kind:
  1948. if (!symtable_raise_if_annotation_block(st, "yield expression", e)) {
  1949. VISIT_QUIT(st, 0);
  1950. }
  1951. if (e->v.Yield.value)
  1952. VISIT(st, expr, e->v.Yield.value);
  1953. st->st_cur->ste_generator = 1;
  1954. if (st->st_cur->ste_comprehension) {
  1955. return symtable_raise_if_comprehension_block(st, e);
  1956. }
  1957. break;
  1958. case YieldFrom_kind:
  1959. if (!symtable_raise_if_annotation_block(st, "yield expression", e)) {
  1960. VISIT_QUIT(st, 0);
  1961. }
  1962. VISIT(st, expr, e->v.YieldFrom.value);
  1963. st->st_cur->ste_generator = 1;
  1964. if (st->st_cur->ste_comprehension) {
  1965. return symtable_raise_if_comprehension_block(st, e);
  1966. }
  1967. break;
  1968. case Await_kind:
  1969. if (!symtable_raise_if_annotation_block(st, "await expression", e)) {
  1970. VISIT_QUIT(st, 0);
  1971. }
  1972. VISIT(st, expr, e->v.Await.value);
  1973. st->st_cur->ste_coroutine = 1;
  1974. break;
  1975. case Compare_kind:
  1976. VISIT(st, expr, e->v.Compare.left);
  1977. VISIT_SEQ(st, expr, e->v.Compare.comparators);
  1978. break;
  1979. case Call_kind:
  1980. VISIT(st, expr, e->v.Call.func);
  1981. VISIT_SEQ(st, expr, e->v.Call.args);
  1982. VISIT_SEQ_WITH_NULL(st, keyword, e->v.Call.keywords);
  1983. break;
  1984. case FormattedValue_kind:
  1985. VISIT(st, expr, e->v.FormattedValue.value);
  1986. if (e->v.FormattedValue.format_spec)
  1987. VISIT(st, expr, e->v.FormattedValue.format_spec);
  1988. break;
  1989. case JoinedStr_kind:
  1990. VISIT_SEQ(st, expr, e->v.JoinedStr.values);
  1991. break;
  1992. case Constant_kind:
  1993. /* Nothing to do here. */
  1994. break;
  1995. /* The following exprs can be assignment targets. */
  1996. case Attribute_kind:
  1997. VISIT(st, expr, e->v.Attribute.value);
  1998. break;
  1999. case Subscript_kind:
  2000. VISIT(st, expr, e->v.Subscript.value);
  2001. VISIT(st, expr, e->v.Subscript.slice);
  2002. break;
  2003. case Starred_kind:
  2004. VISIT(st, expr, e->v.Starred.value);
  2005. break;
  2006. case Slice_kind:
  2007. if (e->v.Slice.lower)
  2008. VISIT(st, expr, e->v.Slice.lower)
  2009. if (e->v.Slice.upper)
  2010. VISIT(st, expr, e->v.Slice.upper)
  2011. if (e->v.Slice.step)
  2012. VISIT(st, expr, e->v.Slice.step)
  2013. break;
  2014. case Name_kind:
  2015. if (!symtable_add_def(st, e->v.Name.id,
  2016. e->v.Name.ctx == Load ? USE : DEF_LOCAL, LOCATION(e)))
  2017. VISIT_QUIT(st, 0);
  2018. /* Special-case super: it counts as a use of __class__ */
  2019. if (e->v.Name.ctx == Load &&
  2020. _PyST_IsFunctionLike(st->st_cur) &&
  2021. _PyUnicode_EqualToASCIIString(e->v.Name.id, "super")) {
  2022. if (!symtable_add_def(st, &_Py_ID(__class__), USE, LOCATION(e)))
  2023. VISIT_QUIT(st, 0);
  2024. }
  2025. break;
  2026. /* child nodes of List and Tuple will have expr_context set */
  2027. case List_kind:
  2028. VISIT_SEQ(st, expr, e->v.List.elts);
  2029. break;
  2030. case Tuple_kind:
  2031. VISIT_SEQ(st, expr, e->v.Tuple.elts);
  2032. break;
  2033. }
  2034. VISIT_QUIT(st, 1);
  2035. }
  2036. static int
  2037. symtable_visit_type_param(struct symtable *st, type_param_ty tp)
  2038. {
  2039. if (++st->recursion_depth > st->recursion_limit) {
  2040. PyErr_SetString(PyExc_RecursionError,
  2041. "maximum recursion depth exceeded during compilation");
  2042. VISIT_QUIT(st, 0);
  2043. }
  2044. switch(tp->kind) {
  2045. case TypeVar_kind:
  2046. if (!symtable_add_def(st, tp->v.TypeVar.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp)))
  2047. VISIT_QUIT(st, 0);
  2048. if (tp->v.TypeVar.bound) {
  2049. int is_in_class = st->st_cur->ste_can_see_class_scope;
  2050. if (!symtable_enter_block(st, tp->v.TypeVar.name,
  2051. TypeVarBoundBlock, (void *)tp,
  2052. LOCATION(tp)))
  2053. VISIT_QUIT(st, 0);
  2054. st->st_cur->ste_can_see_class_scope = is_in_class;
  2055. if (is_in_class && !symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(tp->v.TypeVar.bound))) {
  2056. VISIT_QUIT(st, 0);
  2057. }
  2058. VISIT(st, expr, tp->v.TypeVar.bound);
  2059. if (!symtable_exit_block(st))
  2060. VISIT_QUIT(st, 0);
  2061. }
  2062. break;
  2063. case TypeVarTuple_kind:
  2064. if (!symtable_add_def(st, tp->v.TypeVarTuple.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp)))
  2065. VISIT_QUIT(st, 0);
  2066. break;
  2067. case ParamSpec_kind:
  2068. if (!symtable_add_def(st, tp->v.ParamSpec.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp)))
  2069. VISIT_QUIT(st, 0);
  2070. break;
  2071. }
  2072. VISIT_QUIT(st, 1);
  2073. }
  2074. static int
  2075. symtable_visit_pattern(struct symtable *st, pattern_ty p)
  2076. {
  2077. if (++st->recursion_depth > st->recursion_limit) {
  2078. PyErr_SetString(PyExc_RecursionError,
  2079. "maximum recursion depth exceeded during compilation");
  2080. VISIT_QUIT(st, 0);
  2081. }
  2082. switch (p->kind) {
  2083. case MatchValue_kind:
  2084. VISIT(st, expr, p->v.MatchValue.value);
  2085. break;
  2086. case MatchSingleton_kind:
  2087. /* Nothing to do here. */
  2088. break;
  2089. case MatchSequence_kind:
  2090. VISIT_SEQ(st, pattern, p->v.MatchSequence.patterns);
  2091. break;
  2092. case MatchStar_kind:
  2093. if (p->v.MatchStar.name) {
  2094. symtable_add_def(st, p->v.MatchStar.name, DEF_LOCAL, LOCATION(p));
  2095. }
  2096. break;
  2097. case MatchMapping_kind:
  2098. VISIT_SEQ(st, expr, p->v.MatchMapping.keys);
  2099. VISIT_SEQ(st, pattern, p->v.MatchMapping.patterns);
  2100. if (p->v.MatchMapping.rest) {
  2101. symtable_add_def(st, p->v.MatchMapping.rest, DEF_LOCAL, LOCATION(p));
  2102. }
  2103. break;
  2104. case MatchClass_kind:
  2105. VISIT(st, expr, p->v.MatchClass.cls);
  2106. VISIT_SEQ(st, pattern, p->v.MatchClass.patterns);
  2107. VISIT_SEQ(st, pattern, p->v.MatchClass.kwd_patterns);
  2108. break;
  2109. case MatchAs_kind:
  2110. if (p->v.MatchAs.pattern) {
  2111. VISIT(st, pattern, p->v.MatchAs.pattern);
  2112. }
  2113. if (p->v.MatchAs.name) {
  2114. symtable_add_def(st, p->v.MatchAs.name, DEF_LOCAL, LOCATION(p));
  2115. }
  2116. break;
  2117. case MatchOr_kind:
  2118. VISIT_SEQ(st, pattern, p->v.MatchOr.patterns);
  2119. break;
  2120. }
  2121. VISIT_QUIT(st, 1);
  2122. }
  2123. static int
  2124. symtable_implicit_arg(struct symtable *st, int pos)
  2125. {
  2126. PyObject *id = PyUnicode_FromFormat(".%d", pos);
  2127. if (id == NULL)
  2128. return 0;
  2129. if (!symtable_add_def(st, id, DEF_PARAM, ST_LOCATION(st->st_cur))) {
  2130. Py_DECREF(id);
  2131. return 0;
  2132. }
  2133. Py_DECREF(id);
  2134. return 1;
  2135. }
  2136. static int
  2137. symtable_visit_params(struct symtable *st, asdl_arg_seq *args)
  2138. {
  2139. int i;
  2140. if (!args)
  2141. return -1;
  2142. for (i = 0; i < asdl_seq_LEN(args); i++) {
  2143. arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
  2144. if (!symtable_add_def(st, arg->arg, DEF_PARAM, LOCATION(arg)))
  2145. return 0;
  2146. }
  2147. return 1;
  2148. }
  2149. static int
  2150. symtable_visit_annotation(struct symtable *st, expr_ty annotation)
  2151. {
  2152. int future_annotations = st->st_future->ff_features & CO_FUTURE_ANNOTATIONS;
  2153. if (future_annotations &&
  2154. !symtable_enter_block(st, &_Py_ID(_annotation), AnnotationBlock,
  2155. (void *)annotation, annotation->lineno,
  2156. annotation->col_offset, annotation->end_lineno,
  2157. annotation->end_col_offset)) {
  2158. VISIT_QUIT(st, 0);
  2159. }
  2160. VISIT(st, expr, annotation);
  2161. if (future_annotations && !symtable_exit_block(st)) {
  2162. VISIT_QUIT(st, 0);
  2163. }
  2164. return 1;
  2165. }
  2166. static int
  2167. symtable_visit_argannotations(struct symtable *st, asdl_arg_seq *args)
  2168. {
  2169. int i;
  2170. if (!args)
  2171. return -1;
  2172. for (i = 0; i < asdl_seq_LEN(args); i++) {
  2173. arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
  2174. if (arg->annotation)
  2175. VISIT(st, expr, arg->annotation);
  2176. }
  2177. return 1;
  2178. }
  2179. static int
  2180. symtable_visit_annotations(struct symtable *st, stmt_ty o, arguments_ty a, expr_ty returns)
  2181. {
  2182. int future_annotations = st->st_future->ff_features & CO_FUTURE_ANNOTATIONS;
  2183. if (future_annotations &&
  2184. !symtable_enter_block(st, &_Py_ID(_annotation), AnnotationBlock,
  2185. (void *)o, o->lineno, o->col_offset, o->end_lineno,
  2186. o->end_col_offset)) {
  2187. VISIT_QUIT(st, 0);
  2188. }
  2189. if (a->posonlyargs && !symtable_visit_argannotations(st, a->posonlyargs))
  2190. return 0;
  2191. if (a->args && !symtable_visit_argannotations(st, a->args))
  2192. return 0;
  2193. if (a->vararg && a->vararg->annotation)
  2194. VISIT(st, expr, a->vararg->annotation);
  2195. if (a->kwarg && a->kwarg->annotation)
  2196. VISIT(st, expr, a->kwarg->annotation);
  2197. if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs))
  2198. return 0;
  2199. if (future_annotations && !symtable_exit_block(st)) {
  2200. VISIT_QUIT(st, 0);
  2201. }
  2202. if (returns && !symtable_visit_annotation(st, returns)) {
  2203. VISIT_QUIT(st, 0);
  2204. }
  2205. return 1;
  2206. }
  2207. static int
  2208. symtable_visit_arguments(struct symtable *st, arguments_ty a)
  2209. {
  2210. /* skip default arguments inside function block
  2211. XXX should ast be different?
  2212. */
  2213. if (a->posonlyargs && !symtable_visit_params(st, a->posonlyargs))
  2214. return 0;
  2215. if (a->args && !symtable_visit_params(st, a->args))
  2216. return 0;
  2217. if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs))
  2218. return 0;
  2219. if (a->vararg) {
  2220. if (!symtable_add_def(st, a->vararg->arg, DEF_PARAM, LOCATION(a->vararg)))
  2221. return 0;
  2222. st->st_cur->ste_varargs = 1;
  2223. }
  2224. if (a->kwarg) {
  2225. if (!symtable_add_def(st, a->kwarg->arg, DEF_PARAM, LOCATION(a->kwarg)))
  2226. return 0;
  2227. st->st_cur->ste_varkeywords = 1;
  2228. }
  2229. return 1;
  2230. }
  2231. static int
  2232. symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh)
  2233. {
  2234. if (eh->v.ExceptHandler.type)
  2235. VISIT(st, expr, eh->v.ExceptHandler.type);
  2236. if (eh->v.ExceptHandler.name)
  2237. if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL, LOCATION(eh)))
  2238. return 0;
  2239. VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body);
  2240. return 1;
  2241. }
  2242. static int
  2243. symtable_visit_withitem(struct symtable *st, withitem_ty item)
  2244. {
  2245. VISIT(st, expr, item->context_expr);
  2246. if (item->optional_vars) {
  2247. VISIT(st, expr, item->optional_vars);
  2248. }
  2249. return 1;
  2250. }
  2251. static int
  2252. symtable_visit_match_case(struct symtable *st, match_case_ty m)
  2253. {
  2254. VISIT(st, pattern, m->pattern);
  2255. if (m->guard) {
  2256. VISIT(st, expr, m->guard);
  2257. }
  2258. VISIT_SEQ(st, stmt, m->body);
  2259. return 1;
  2260. }
  2261. static int
  2262. symtable_visit_alias(struct symtable *st, alias_ty a)
  2263. {
  2264. /* Compute store_name, the name actually bound by the import
  2265. operation. It is different than a->name when a->name is a
  2266. dotted package name (e.g. spam.eggs)
  2267. */
  2268. PyObject *store_name;
  2269. PyObject *name = (a->asname == NULL) ? a->name : a->asname;
  2270. Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
  2271. PyUnicode_GET_LENGTH(name), 1);
  2272. if (dot != -1) {
  2273. store_name = PyUnicode_Substring(name, 0, dot);
  2274. if (!store_name)
  2275. return 0;
  2276. }
  2277. else {
  2278. store_name = Py_NewRef(name);
  2279. }
  2280. if (!_PyUnicode_EqualToASCIIString(name, "*")) {
  2281. int r = symtable_add_def(st, store_name, DEF_IMPORT, LOCATION(a));
  2282. Py_DECREF(store_name);
  2283. return r;
  2284. }
  2285. else {
  2286. if (st->st_cur->ste_type != ModuleBlock) {
  2287. int lineno = a->lineno;
  2288. int col_offset = a->col_offset;
  2289. int end_lineno = a->end_lineno;
  2290. int end_col_offset = a->end_col_offset;
  2291. PyErr_SetString(PyExc_SyntaxError, IMPORT_STAR_WARNING);
  2292. PyErr_RangedSyntaxLocationObject(st->st_filename,
  2293. lineno, col_offset + 1,
  2294. end_lineno, end_col_offset + 1);
  2295. Py_DECREF(store_name);
  2296. return 0;
  2297. }
  2298. Py_DECREF(store_name);
  2299. return 1;
  2300. }
  2301. }
  2302. static int
  2303. symtable_visit_comprehension(struct symtable *st, comprehension_ty lc)
  2304. {
  2305. st->st_cur->ste_comp_iter_target = 1;
  2306. VISIT(st, expr, lc->target);
  2307. st->st_cur->ste_comp_iter_target = 0;
  2308. st->st_cur->ste_comp_iter_expr++;
  2309. VISIT(st, expr, lc->iter);
  2310. st->st_cur->ste_comp_iter_expr--;
  2311. VISIT_SEQ(st, expr, lc->ifs);
  2312. if (lc->is_async) {
  2313. st->st_cur->ste_coroutine = 1;
  2314. }
  2315. return 1;
  2316. }
  2317. static int
  2318. symtable_visit_keyword(struct symtable *st, keyword_ty k)
  2319. {
  2320. VISIT(st, expr, k->value);
  2321. return 1;
  2322. }
  2323. static int
  2324. symtable_handle_comprehension(struct symtable *st, expr_ty e,
  2325. identifier scope_name, asdl_comprehension_seq *generators,
  2326. expr_ty elt, expr_ty value)
  2327. {
  2328. if (st->st_cur->ste_can_see_class_scope) {
  2329. // gh-109118
  2330. PyErr_Format(PyExc_SyntaxError,
  2331. "Cannot use comprehension in annotation scope within class scope");
  2332. PyErr_RangedSyntaxLocationObject(st->st_filename,
  2333. e->lineno,
  2334. e->col_offset + 1,
  2335. e->end_lineno,
  2336. e->end_col_offset + 1);
  2337. VISIT_QUIT(st, 0);
  2338. }
  2339. int is_generator = (e->kind == GeneratorExp_kind);
  2340. comprehension_ty outermost = ((comprehension_ty)
  2341. asdl_seq_GET(generators, 0));
  2342. /* Outermost iterator is evaluated in current scope */
  2343. st->st_cur->ste_comp_iter_expr++;
  2344. VISIT(st, expr, outermost->iter);
  2345. st->st_cur->ste_comp_iter_expr--;
  2346. /* Create comprehension scope for the rest */
  2347. if (!scope_name ||
  2348. !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e,
  2349. e->lineno, e->col_offset,
  2350. e->end_lineno, e->end_col_offset)) {
  2351. return 0;
  2352. }
  2353. switch(e->kind) {
  2354. case ListComp_kind:
  2355. st->st_cur->ste_comprehension = ListComprehension;
  2356. break;
  2357. case SetComp_kind:
  2358. st->st_cur->ste_comprehension = SetComprehension;
  2359. break;
  2360. case DictComp_kind:
  2361. st->st_cur->ste_comprehension = DictComprehension;
  2362. break;
  2363. default:
  2364. st->st_cur->ste_comprehension = GeneratorExpression;
  2365. break;
  2366. }
  2367. if (outermost->is_async) {
  2368. st->st_cur->ste_coroutine = 1;
  2369. }
  2370. /* Outermost iter is received as an argument */
  2371. if (!symtable_implicit_arg(st, 0)) {
  2372. symtable_exit_block(st);
  2373. return 0;
  2374. }
  2375. /* Visit iteration variable target, and mark them as such */
  2376. st->st_cur->ste_comp_iter_target = 1;
  2377. VISIT(st, expr, outermost->target);
  2378. st->st_cur->ste_comp_iter_target = 0;
  2379. /* Visit the rest of the comprehension body */
  2380. VISIT_SEQ(st, expr, outermost->ifs);
  2381. VISIT_SEQ_TAIL(st, comprehension, generators, 1);
  2382. if (value)
  2383. VISIT(st, expr, value);
  2384. VISIT(st, expr, elt);
  2385. st->st_cur->ste_generator = is_generator;
  2386. int is_async = st->st_cur->ste_coroutine && !is_generator;
  2387. if (!symtable_exit_block(st)) {
  2388. return 0;
  2389. }
  2390. if (is_async) {
  2391. st->st_cur->ste_coroutine = 1;
  2392. }
  2393. return 1;
  2394. }
  2395. static int
  2396. symtable_visit_genexp(struct symtable *st, expr_ty e)
  2397. {
  2398. return symtable_handle_comprehension(st, e, &_Py_ID(genexpr),
  2399. e->v.GeneratorExp.generators,
  2400. e->v.GeneratorExp.elt, NULL);
  2401. }
  2402. static int
  2403. symtable_visit_listcomp(struct symtable *st, expr_ty e)
  2404. {
  2405. return symtable_handle_comprehension(st, e, &_Py_ID(listcomp),
  2406. e->v.ListComp.generators,
  2407. e->v.ListComp.elt, NULL);
  2408. }
  2409. static int
  2410. symtable_visit_setcomp(struct symtable *st, expr_ty e)
  2411. {
  2412. return symtable_handle_comprehension(st, e, &_Py_ID(setcomp),
  2413. e->v.SetComp.generators,
  2414. e->v.SetComp.elt, NULL);
  2415. }
  2416. static int
  2417. symtable_visit_dictcomp(struct symtable *st, expr_ty e)
  2418. {
  2419. return symtable_handle_comprehension(st, e, &_Py_ID(dictcomp),
  2420. e->v.DictComp.generators,
  2421. e->v.DictComp.key,
  2422. e->v.DictComp.value);
  2423. }
  2424. static int
  2425. symtable_raise_if_annotation_block(struct symtable *st, const char *name, expr_ty e)
  2426. {
  2427. enum _block_type type = st->st_cur->ste_type;
  2428. if (type == AnnotationBlock)
  2429. PyErr_Format(PyExc_SyntaxError, ANNOTATION_NOT_ALLOWED, name);
  2430. else if (type == TypeVarBoundBlock)
  2431. PyErr_Format(PyExc_SyntaxError, TYPEVAR_BOUND_NOT_ALLOWED, name);
  2432. else if (type == TypeAliasBlock)
  2433. PyErr_Format(PyExc_SyntaxError, TYPEALIAS_NOT_ALLOWED, name);
  2434. else if (type == TypeParamBlock)
  2435. PyErr_Format(PyExc_SyntaxError, TYPEPARAM_NOT_ALLOWED, name);
  2436. else
  2437. return 1;
  2438. PyErr_RangedSyntaxLocationObject(st->st_filename,
  2439. e->lineno,
  2440. e->col_offset + 1,
  2441. e->end_lineno,
  2442. e->end_col_offset + 1);
  2443. return 0;
  2444. }
  2445. static int
  2446. symtable_raise_if_comprehension_block(struct symtable *st, expr_ty e) {
  2447. _Py_comprehension_ty type = st->st_cur->ste_comprehension;
  2448. PyErr_SetString(PyExc_SyntaxError,
  2449. (type == ListComprehension) ? "'yield' inside list comprehension" :
  2450. (type == SetComprehension) ? "'yield' inside set comprehension" :
  2451. (type == DictComprehension) ? "'yield' inside dict comprehension" :
  2452. "'yield' inside generator expression");
  2453. PyErr_RangedSyntaxLocationObject(st->st_filename,
  2454. e->lineno, e->col_offset + 1,
  2455. e->end_lineno, e->end_col_offset + 1);
  2456. VISIT_QUIT(st, 0);
  2457. }
  2458. struct symtable *
  2459. _Py_SymtableStringObjectFlags(const char *str, PyObject *filename,
  2460. int start, PyCompilerFlags *flags)
  2461. {
  2462. struct symtable *st;
  2463. mod_ty mod;
  2464. PyArena *arena;
  2465. arena = _PyArena_New();
  2466. if (arena == NULL)
  2467. return NULL;
  2468. mod = _PyParser_ASTFromString(str, filename, start, flags, arena);
  2469. if (mod == NULL) {
  2470. _PyArena_Free(arena);
  2471. return NULL;
  2472. }
  2473. PyFutureFeatures future;
  2474. if (!_PyFuture_FromAST(mod, filename, &future)) {
  2475. _PyArena_Free(arena);
  2476. return NULL;
  2477. }
  2478. future.ff_features |= flags->cf_flags;
  2479. st = _PySymtable_Build(mod, filename, &future);
  2480. _PyArena_Free(arena);
  2481. return st;
  2482. }
  2483. PyObject *
  2484. _Py_MaybeMangle(PyObject *privateobj, PySTEntryObject *ste, PyObject *name)
  2485. {
  2486. /* Special case for type parameter blocks around generic classes:
  2487. * we want to mangle type parameter names (so a type param with a private
  2488. * name can be used inside the class body), but we don't want to mangle
  2489. * any other names that appear within the type parameter scope.
  2490. */
  2491. if (ste->ste_mangled_names != NULL) {
  2492. int result = PySet_Contains(ste->ste_mangled_names, name);
  2493. if (result < 0) {
  2494. return NULL;
  2495. }
  2496. if (result == 0) {
  2497. return Py_NewRef(name);
  2498. }
  2499. }
  2500. return _Py_Mangle(privateobj, name);
  2501. }
  2502. PyObject *
  2503. _Py_Mangle(PyObject *privateobj, PyObject *ident)
  2504. {
  2505. /* Name mangling: __private becomes _classname__private.
  2506. This is independent from how the name is used. */
  2507. if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
  2508. PyUnicode_READ_CHAR(ident, 0) != '_' ||
  2509. PyUnicode_READ_CHAR(ident, 1) != '_') {
  2510. return Py_NewRef(ident);
  2511. }
  2512. size_t nlen = PyUnicode_GET_LENGTH(ident);
  2513. size_t plen = PyUnicode_GET_LENGTH(privateobj);
  2514. /* Don't mangle __id__ or names with dots.
  2515. The only time a name with a dot can occur is when
  2516. we are compiling an import statement that has a
  2517. package name.
  2518. TODO(jhylton): Decide whether we want to support
  2519. mangling of the module name, e.g. __M.X.
  2520. */
  2521. if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
  2522. PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
  2523. PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
  2524. return Py_NewRef(ident); /* Don't mangle __whatever__ */
  2525. }
  2526. /* Strip leading underscores from class name */
  2527. size_t ipriv = 0;
  2528. while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_') {
  2529. ipriv++;
  2530. }
  2531. if (ipriv == plen) {
  2532. return Py_NewRef(ident); /* Don't mangle if class is just underscores */
  2533. }
  2534. plen -= ipriv;
  2535. if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
  2536. PyErr_SetString(PyExc_OverflowError,
  2537. "private identifier too large to be mangled");
  2538. return NULL;
  2539. }
  2540. Py_UCS4 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
  2541. if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar) {
  2542. maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
  2543. }
  2544. PyObject *result = PyUnicode_New(1 + nlen + plen, maxchar);
  2545. if (!result) {
  2546. return NULL;
  2547. }
  2548. /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
  2549. PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
  2550. if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
  2551. Py_DECREF(result);
  2552. return NULL;
  2553. }
  2554. if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
  2555. Py_DECREF(result);
  2556. return NULL;
  2557. }
  2558. assert(_PyUnicode_CheckConsistency(result, 1));
  2559. return result;
  2560. }