action_helpers.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603
  1. #include <Python.h>
  2. #include "pegen.h"
  3. #include "pycore_runtime.h" // _PyRuntime
  4. #include "string_parser.h"
  5. #include "tokenizer.h"
  6. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  7. void *_PyPegen_dummy_name(Parser *p, ...) {
  8. return &_PyRuntime.parser.dummy_name;
  9. }
  10. /* Creates a single-element asdl_seq* that contains a */
  11. asdl_seq *_PyPegen_singleton_seq(Parser *p, void *a) {
  12. assert(a != NULL);
  13. asdl_seq *seq = (asdl_seq *)_Py_asdl_generic_seq_new(1, p->arena);
  14. if (!seq) {
  15. return NULL;
  16. }
  17. asdl_seq_SET_UNTYPED(seq, 0, a);
  18. return seq;
  19. }
  20. /* Creates a copy of seq and prepends a to it */
  21. asdl_seq *_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq) {
  22. assert(a != NULL);
  23. if (!seq) {
  24. return _PyPegen_singleton_seq(p, a);
  25. }
  26. asdl_seq *new_seq =
  27. (asdl_seq *)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
  28. if (!new_seq) {
  29. return NULL;
  30. }
  31. asdl_seq_SET_UNTYPED(new_seq, 0, a);
  32. for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
  33. asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
  34. }
  35. return new_seq;
  36. }
  37. /* Creates a copy of seq and appends a to it */
  38. asdl_seq *_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a) {
  39. assert(a != NULL);
  40. if (!seq) {
  41. return _PyPegen_singleton_seq(p, a);
  42. }
  43. asdl_seq *new_seq =
  44. (asdl_seq *)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
  45. if (!new_seq) {
  46. return NULL;
  47. }
  48. for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
  49. asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
  50. }
  51. asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
  52. return new_seq;
  53. }
  54. static Py_ssize_t _get_flattened_seq_size(asdl_seq *seqs) {
  55. Py_ssize_t size = 0;
  56. for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
  57. asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
  58. size += asdl_seq_LEN(inner_seq);
  59. }
  60. return size;
  61. }
  62. /* Flattens an asdl_seq* of asdl_seq*s */
  63. asdl_seq *_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs) {
  64. Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
  65. assert(flattened_seq_size > 0);
  66. asdl_seq *flattened_seq =
  67. (asdl_seq *)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
  68. if (!flattened_seq) {
  69. return NULL;
  70. }
  71. int flattened_seq_idx = 0;
  72. for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
  73. asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
  74. for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
  75. asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++,
  76. asdl_seq_GET_UNTYPED(inner_seq, j));
  77. }
  78. }
  79. assert(flattened_seq_idx == flattened_seq_size);
  80. return flattened_seq;
  81. }
  82. void *_PyPegen_seq_last_item(asdl_seq *seq) {
  83. Py_ssize_t len = asdl_seq_LEN(seq);
  84. return asdl_seq_GET_UNTYPED(seq, len - 1);
  85. }
  86. void *_PyPegen_seq_first_item(asdl_seq *seq) {
  87. return asdl_seq_GET_UNTYPED(seq, 0);
  88. }
  89. /* Creates a new name of the form <first_name>.<second_name> */
  90. expr_ty _PyPegen_join_names_with_dot(Parser *p, expr_ty first_name,
  91. expr_ty second_name) {
  92. assert(first_name != NULL && second_name != NULL);
  93. PyObject *first_identifier = first_name->v.Name.id;
  94. PyObject *second_identifier = second_name->v.Name.id;
  95. if (PyUnicode_READY(first_identifier) == -1) {
  96. return NULL;
  97. }
  98. if (PyUnicode_READY(second_identifier) == -1) {
  99. return NULL;
  100. }
  101. const char *first_str = PyUnicode_AsUTF8(first_identifier);
  102. if (!first_str) {
  103. return NULL;
  104. }
  105. const char *second_str = PyUnicode_AsUTF8(second_identifier);
  106. if (!second_str) {
  107. return NULL;
  108. }
  109. Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
  110. PyObject *str = PyBytes_FromStringAndSize(NULL, len);
  111. if (!str) {
  112. return NULL;
  113. }
  114. char *s = PyBytes_AS_STRING(str);
  115. if (!s) {
  116. return NULL;
  117. }
  118. strcpy(s, first_str);
  119. s += strlen(first_str);
  120. *s++ = '.';
  121. strcpy(s, second_str);
  122. s += strlen(second_str);
  123. *s = '\0';
  124. PyObject *uni =
  125. PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
  126. Py_DECREF(str);
  127. if (!uni) {
  128. return NULL;
  129. }
  130. PyInterpreterState *interp = _PyInterpreterState_GET();
  131. _PyUnicode_InternMortal(interp, &uni);
  132. if (_PyArena_AddPyObject(p->arena, uni) < 0) {
  133. Py_DECREF(uni);
  134. return NULL;
  135. }
  136. return _PyAST_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
  137. }
  138. /* Counts the total number of dots in seq's tokens */
  139. int _PyPegen_seq_count_dots(asdl_seq *seq) {
  140. int number_of_dots = 0;
  141. for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
  142. Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
  143. switch (current_expr->type) {
  144. case ELLIPSIS:
  145. number_of_dots += 3;
  146. break;
  147. case DOT:
  148. number_of_dots += 1;
  149. break;
  150. default:
  151. Py_UNREACHABLE();
  152. }
  153. }
  154. return number_of_dots;
  155. }
  156. /* Creates an alias with '*' as the identifier name */
  157. alias_ty _PyPegen_alias_for_star(Parser *p, int lineno, int col_offset,
  158. int end_lineno, int end_col_offset,
  159. PyArena *arena) {
  160. PyObject *str = PyUnicode_InternFromString("*");
  161. if (!str) {
  162. return NULL;
  163. }
  164. if (_PyArena_AddPyObject(p->arena, str) < 0) {
  165. Py_DECREF(str);
  166. return NULL;
  167. }
  168. return _PyAST_alias(str, NULL, lineno, col_offset, end_lineno, end_col_offset,
  169. arena);
  170. }
  171. /* Creates a new asdl_seq* with the identifiers of all the names in seq */
  172. asdl_identifier_seq *_PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq) {
  173. Py_ssize_t len = asdl_seq_LEN(seq);
  174. assert(len > 0);
  175. asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
  176. if (!new_seq) {
  177. return NULL;
  178. }
  179. for (Py_ssize_t i = 0; i < len; i++) {
  180. expr_ty e = asdl_seq_GET(seq, i);
  181. asdl_seq_SET(new_seq, i, e->v.Name.id);
  182. }
  183. return new_seq;
  184. }
  185. /* Constructs a CmpopExprPair */
  186. CmpopExprPair *_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop,
  187. expr_ty expr) {
  188. assert(expr != NULL);
  189. CmpopExprPair *a = _PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
  190. if (!a) {
  191. return NULL;
  192. }
  193. a->cmpop = cmpop;
  194. a->expr = expr;
  195. return a;
  196. }
  197. asdl_int_seq *_PyPegen_get_cmpops(Parser *p, asdl_seq *seq) {
  198. Py_ssize_t len = asdl_seq_LEN(seq);
  199. assert(len > 0);
  200. asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
  201. if (!new_seq) {
  202. return NULL;
  203. }
  204. for (Py_ssize_t i = 0; i < len; i++) {
  205. CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
  206. asdl_seq_SET(new_seq, i, pair->cmpop);
  207. }
  208. return new_seq;
  209. }
  210. asdl_expr_seq *_PyPegen_get_exprs(Parser *p, asdl_seq *seq) {
  211. Py_ssize_t len = asdl_seq_LEN(seq);
  212. assert(len > 0);
  213. asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
  214. if (!new_seq) {
  215. return NULL;
  216. }
  217. for (Py_ssize_t i = 0; i < len; i++) {
  218. CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
  219. asdl_seq_SET(new_seq, i, pair->expr);
  220. }
  221. return new_seq;
  222. }
  223. /* Creates an asdl_seq* where all the elements have been changed to have ctx as
  224. * context */
  225. static asdl_expr_seq *_set_seq_context(Parser *p, asdl_expr_seq *seq,
  226. expr_context_ty ctx) {
  227. Py_ssize_t len = asdl_seq_LEN(seq);
  228. if (len == 0) {
  229. return NULL;
  230. }
  231. asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
  232. if (!new_seq) {
  233. return NULL;
  234. }
  235. for (Py_ssize_t i = 0; i < len; i++) {
  236. expr_ty e = asdl_seq_GET(seq, i);
  237. asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
  238. }
  239. return new_seq;
  240. }
  241. static expr_ty _set_name_context(Parser *p, expr_ty e, expr_context_ty ctx) {
  242. return _PyAST_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
  243. }
  244. static expr_ty _set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx) {
  245. return _PyAST_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx,
  246. EXTRA_EXPR(e, e));
  247. }
  248. static expr_ty _set_list_context(Parser *p, expr_ty e, expr_context_ty ctx) {
  249. return _PyAST_List(_set_seq_context(p, e->v.List.elts, ctx), ctx,
  250. EXTRA_EXPR(e, e));
  251. }
  252. static expr_ty _set_subscript_context(Parser *p, expr_ty e,
  253. expr_context_ty ctx) {
  254. return _PyAST_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx,
  255. EXTRA_EXPR(e, e));
  256. }
  257. static expr_ty _set_attribute_context(Parser *p, expr_ty e,
  258. expr_context_ty ctx) {
  259. return _PyAST_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx,
  260. EXTRA_EXPR(e, e));
  261. }
  262. static expr_ty _set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx) {
  263. return _PyAST_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx),
  264. ctx, EXTRA_EXPR(e, e));
  265. }
  266. /* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
  267. expr_ty _PyPegen_set_expr_context(Parser *p, expr_ty expr,
  268. expr_context_ty ctx) {
  269. assert(expr != NULL);
  270. expr_ty new = NULL;
  271. switch (expr->kind) {
  272. case Name_kind:
  273. new = _set_name_context(p, expr, ctx);
  274. break;
  275. case Tuple_kind:
  276. new = _set_tuple_context(p, expr, ctx);
  277. break;
  278. case List_kind:
  279. new = _set_list_context(p, expr, ctx);
  280. break;
  281. case Subscript_kind:
  282. new = _set_subscript_context(p, expr, ctx);
  283. break;
  284. case Attribute_kind:
  285. new = _set_attribute_context(p, expr, ctx);
  286. break;
  287. case Starred_kind:
  288. new = _set_starred_context(p, expr, ctx);
  289. break;
  290. default:
  291. new = expr;
  292. }
  293. return new;
  294. }
  295. /* Constructs a KeyValuePair that is used when parsing a dict's key value pairs
  296. */
  297. KeyValuePair *_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value) {
  298. KeyValuePair *a = _PyArena_Malloc(p->arena, sizeof(KeyValuePair));
  299. if (!a) {
  300. return NULL;
  301. }
  302. a->key = key;
  303. a->value = value;
  304. return a;
  305. }
  306. /* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
  307. asdl_expr_seq *_PyPegen_get_keys(Parser *p, asdl_seq *seq) {
  308. Py_ssize_t len = asdl_seq_LEN(seq);
  309. asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
  310. if (!new_seq) {
  311. return NULL;
  312. }
  313. for (Py_ssize_t i = 0; i < len; i++) {
  314. KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
  315. asdl_seq_SET(new_seq, i, pair->key);
  316. }
  317. return new_seq;
  318. }
  319. /* Extracts all values from an asdl_seq* of KeyValuePair*'s */
  320. asdl_expr_seq *_PyPegen_get_values(Parser *p, asdl_seq *seq) {
  321. Py_ssize_t len = asdl_seq_LEN(seq);
  322. asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
  323. if (!new_seq) {
  324. return NULL;
  325. }
  326. for (Py_ssize_t i = 0; i < len; i++) {
  327. KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
  328. asdl_seq_SET(new_seq, i, pair->value);
  329. }
  330. return new_seq;
  331. }
  332. /* Constructs a KeyPatternPair that is used when parsing mapping & class
  333. * patterns */
  334. KeyPatternPair *_PyPegen_key_pattern_pair(Parser *p, expr_ty key,
  335. pattern_ty pattern) {
  336. KeyPatternPair *a = _PyArena_Malloc(p->arena, sizeof(KeyPatternPair));
  337. if (!a) {
  338. return NULL;
  339. }
  340. a->key = key;
  341. a->pattern = pattern;
  342. return a;
  343. }
  344. /* Extracts all keys from an asdl_seq* of KeyPatternPair*'s */
  345. asdl_expr_seq *_PyPegen_get_pattern_keys(Parser *p, asdl_seq *seq) {
  346. Py_ssize_t len = asdl_seq_LEN(seq);
  347. asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
  348. if (!new_seq) {
  349. return NULL;
  350. }
  351. for (Py_ssize_t i = 0; i < len; i++) {
  352. KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
  353. asdl_seq_SET(new_seq, i, pair->key);
  354. }
  355. return new_seq;
  356. }
  357. /* Extracts all patterns from an asdl_seq* of KeyPatternPair*'s */
  358. asdl_pattern_seq *_PyPegen_get_patterns(Parser *p, asdl_seq *seq) {
  359. Py_ssize_t len = asdl_seq_LEN(seq);
  360. asdl_pattern_seq *new_seq = _Py_asdl_pattern_seq_new(len, p->arena);
  361. if (!new_seq) {
  362. return NULL;
  363. }
  364. for (Py_ssize_t i = 0; i < len; i++) {
  365. KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
  366. asdl_seq_SET(new_seq, i, pair->pattern);
  367. }
  368. return new_seq;
  369. }
  370. /* Constructs a NameDefaultPair */
  371. NameDefaultPair *_PyPegen_name_default_pair(Parser *p, arg_ty arg,
  372. expr_ty value, Token *tc) {
  373. NameDefaultPair *a = _PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
  374. if (!a) {
  375. return NULL;
  376. }
  377. a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
  378. a->value = value;
  379. return a;
  380. }
  381. /* Constructs a SlashWithDefault */
  382. SlashWithDefault *_PyPegen_slash_with_default(Parser *p,
  383. asdl_arg_seq *plain_names,
  384. asdl_seq *names_with_defaults) {
  385. SlashWithDefault *a = _PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
  386. if (!a) {
  387. return NULL;
  388. }
  389. a->plain_names = plain_names;
  390. a->names_with_defaults = names_with_defaults;
  391. return a;
  392. }
  393. /* Constructs a StarEtc */
  394. StarEtc *_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs,
  395. arg_ty kwarg) {
  396. StarEtc *a = _PyArena_Malloc(p->arena, sizeof(StarEtc));
  397. if (!a) {
  398. return NULL;
  399. }
  400. a->vararg = vararg;
  401. a->kwonlyargs = kwonlyargs;
  402. a->kwarg = kwarg;
  403. return a;
  404. }
  405. asdl_seq *_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b) {
  406. Py_ssize_t first_len = asdl_seq_LEN(a);
  407. Py_ssize_t second_len = asdl_seq_LEN(b);
  408. asdl_seq *new_seq =
  409. (asdl_seq *)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
  410. if (!new_seq) {
  411. return NULL;
  412. }
  413. int k = 0;
  414. for (Py_ssize_t i = 0; i < first_len; i++) {
  415. asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
  416. }
  417. for (Py_ssize_t i = 0; i < second_len; i++) {
  418. asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
  419. }
  420. return new_seq;
  421. }
  422. static asdl_arg_seq *_get_names(Parser *p, asdl_seq *names_with_defaults) {
  423. Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
  424. asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
  425. if (!seq) {
  426. return NULL;
  427. }
  428. for (Py_ssize_t i = 0; i < len; i++) {
  429. NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
  430. asdl_seq_SET(seq, i, pair->arg);
  431. }
  432. return seq;
  433. }
  434. static asdl_expr_seq *_get_defaults(Parser *p, asdl_seq *names_with_defaults) {
  435. Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
  436. asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
  437. if (!seq) {
  438. return NULL;
  439. }
  440. for (Py_ssize_t i = 0; i < len; i++) {
  441. NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
  442. asdl_seq_SET(seq, i, pair->value);
  443. }
  444. return seq;
  445. }
  446. static int _make_posonlyargs(Parser *p, asdl_arg_seq *slash_without_default,
  447. SlashWithDefault *slash_with_default,
  448. asdl_arg_seq **posonlyargs) {
  449. if (slash_without_default != NULL) {
  450. *posonlyargs = slash_without_default;
  451. } else if (slash_with_default != NULL) {
  452. asdl_arg_seq *slash_with_default_names =
  453. _get_names(p, slash_with_default->names_with_defaults);
  454. if (!slash_with_default_names) {
  455. return -1;
  456. }
  457. *posonlyargs = (asdl_arg_seq *)_PyPegen_join_sequences(
  458. p, (asdl_seq *)slash_with_default->plain_names,
  459. (asdl_seq *)slash_with_default_names);
  460. } else {
  461. *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
  462. }
  463. return *posonlyargs == NULL ? -1 : 0;
  464. }
  465. static int _make_posargs(Parser *p, asdl_arg_seq *plain_names,
  466. asdl_seq *names_with_default, asdl_arg_seq **posargs) {
  467. if (plain_names != NULL && names_with_default != NULL) {
  468. asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
  469. if (!names_with_default_names) {
  470. return -1;
  471. }
  472. *posargs = (asdl_arg_seq *)_PyPegen_join_sequences(
  473. p, (asdl_seq *)plain_names, (asdl_seq *)names_with_default_names);
  474. } else if (plain_names == NULL && names_with_default != NULL) {
  475. *posargs = _get_names(p, names_with_default);
  476. } else if (plain_names != NULL && names_with_default == NULL) {
  477. *posargs = plain_names;
  478. } else {
  479. *posargs = _Py_asdl_arg_seq_new(0, p->arena);
  480. }
  481. return *posargs == NULL ? -1 : 0;
  482. }
  483. static int _make_posdefaults(Parser *p, SlashWithDefault *slash_with_default,
  484. asdl_seq *names_with_default,
  485. asdl_expr_seq **posdefaults) {
  486. if (slash_with_default != NULL && names_with_default != NULL) {
  487. asdl_expr_seq *slash_with_default_values =
  488. _get_defaults(p, slash_with_default->names_with_defaults);
  489. if (!slash_with_default_values) {
  490. return -1;
  491. }
  492. asdl_expr_seq *names_with_default_values =
  493. _get_defaults(p, names_with_default);
  494. if (!names_with_default_values) {
  495. return -1;
  496. }
  497. *posdefaults = (asdl_expr_seq *)_PyPegen_join_sequences(
  498. p, (asdl_seq *)slash_with_default_values,
  499. (asdl_seq *)names_with_default_values);
  500. } else if (slash_with_default == NULL && names_with_default != NULL) {
  501. *posdefaults = _get_defaults(p, names_with_default);
  502. } else if (slash_with_default != NULL && names_with_default == NULL) {
  503. *posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
  504. } else {
  505. *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
  506. }
  507. return *posdefaults == NULL ? -1 : 0;
  508. }
  509. static int _make_kwargs(Parser *p, StarEtc *star_etc, asdl_arg_seq **kwonlyargs,
  510. asdl_expr_seq **kwdefaults) {
  511. if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
  512. *kwonlyargs = _get_names(p, star_etc->kwonlyargs);
  513. } else {
  514. *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
  515. }
  516. if (*kwonlyargs == NULL) {
  517. return -1;
  518. }
  519. if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
  520. *kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
  521. } else {
  522. *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
  523. }
  524. if (*kwdefaults == NULL) {
  525. return -1;
  526. }
  527. return 0;
  528. }
  529. /* Constructs an arguments_ty object out of all the parsed constructs in the
  530. * parameters rule */
  531. arguments_ty _PyPegen_make_arguments(Parser *p,
  532. asdl_arg_seq *slash_without_default,
  533. SlashWithDefault *slash_with_default,
  534. asdl_arg_seq *plain_names,
  535. asdl_seq *names_with_default,
  536. StarEtc *star_etc) {
  537. asdl_arg_seq *posonlyargs;
  538. if (_make_posonlyargs(p, slash_without_default, slash_with_default,
  539. &posonlyargs) == -1) {
  540. return NULL;
  541. }
  542. asdl_arg_seq *posargs;
  543. if (_make_posargs(p, plain_names, names_with_default, &posargs) == -1) {
  544. return NULL;
  545. }
  546. asdl_expr_seq *posdefaults;
  547. if (_make_posdefaults(p, slash_with_default, names_with_default,
  548. &posdefaults) == -1) {
  549. return NULL;
  550. }
  551. arg_ty vararg = NULL;
  552. if (star_etc != NULL && star_etc->vararg != NULL) {
  553. vararg = star_etc->vararg;
  554. }
  555. asdl_arg_seq *kwonlyargs;
  556. asdl_expr_seq *kwdefaults;
  557. if (_make_kwargs(p, star_etc, &kwonlyargs, &kwdefaults) == -1) {
  558. return NULL;
  559. }
  560. arg_ty kwarg = NULL;
  561. if (star_etc != NULL && star_etc->kwarg != NULL) {
  562. kwarg = star_etc->kwarg;
  563. }
  564. return _PyAST_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults,
  565. kwarg, posdefaults, p->arena);
  566. }
  567. /* Constructs an empty arguments_ty object, that gets used when a function
  568. * accepts no arguments. */
  569. arguments_ty _PyPegen_empty_arguments(Parser *p) {
  570. asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
  571. if (!posonlyargs) {
  572. return NULL;
  573. }
  574. asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
  575. if (!posargs) {
  576. return NULL;
  577. }
  578. asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
  579. if (!posdefaults) {
  580. return NULL;
  581. }
  582. asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
  583. if (!kwonlyargs) {
  584. return NULL;
  585. }
  586. asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
  587. if (!kwdefaults) {
  588. return NULL;
  589. }
  590. return _PyAST_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults,
  591. NULL, posdefaults, p->arena);
  592. }
  593. /* Encapsulates the value of an operator_ty into an AugOperator struct */
  594. AugOperator *_PyPegen_augoperator(Parser *p, operator_ty kind) {
  595. AugOperator *a = _PyArena_Malloc(p->arena, sizeof(AugOperator));
  596. if (!a) {
  597. return NULL;
  598. }
  599. a->kind = kind;
  600. return a;
  601. }
  602. /* Construct a FunctionDef equivalent to function_def, but with decorators */
  603. stmt_ty _PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators,
  604. stmt_ty function_def) {
  605. assert(function_def != NULL);
  606. if (function_def->kind == AsyncFunctionDef_kind) {
  607. return _PyAST_AsyncFunctionDef(
  608. function_def->v.AsyncFunctionDef.name,
  609. function_def->v.AsyncFunctionDef.args,
  610. function_def->v.AsyncFunctionDef.body, decorators,
  611. function_def->v.AsyncFunctionDef.returns,
  612. function_def->v.AsyncFunctionDef.type_comment,
  613. function_def->v.AsyncFunctionDef.type_params, function_def->lineno,
  614. function_def->col_offset, function_def->end_lineno,
  615. function_def->end_col_offset, p->arena);
  616. }
  617. return _PyAST_FunctionDef(
  618. function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
  619. function_def->v.FunctionDef.body, decorators,
  620. function_def->v.FunctionDef.returns,
  621. function_def->v.FunctionDef.type_comment,
  622. function_def->v.FunctionDef.type_params, function_def->lineno,
  623. function_def->col_offset, function_def->end_lineno,
  624. function_def->end_col_offset, p->arena);
  625. }
  626. /* Construct a ClassDef equivalent to class_def, but with decorators */
  627. stmt_ty _PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators,
  628. stmt_ty class_def) {
  629. assert(class_def != NULL);
  630. return _PyAST_ClassDef(
  631. class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
  632. class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
  633. class_def->v.ClassDef.type_params, class_def->lineno,
  634. class_def->col_offset, class_def->end_lineno, class_def->end_col_offset,
  635. p->arena);
  636. }
  637. /* Construct a KeywordOrStarred */
  638. KeywordOrStarred *_PyPegen_keyword_or_starred(Parser *p, void *element,
  639. int is_keyword) {
  640. KeywordOrStarred *a = _PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
  641. if (!a) {
  642. return NULL;
  643. }
  644. a->element = element;
  645. a->is_keyword = is_keyword;
  646. return a;
  647. }
  648. /* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s
  649. */
  650. static int _seq_number_of_starred_exprs(asdl_seq *seq) {
  651. int n = 0;
  652. for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
  653. KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
  654. if (!k->is_keyword) {
  655. n++;
  656. }
  657. }
  658. return n;
  659. }
  660. /* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
  661. asdl_expr_seq *_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs) {
  662. int new_len = _seq_number_of_starred_exprs(kwargs);
  663. if (new_len == 0) {
  664. return NULL;
  665. }
  666. asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
  667. if (!new_seq) {
  668. return NULL;
  669. }
  670. int idx = 0;
  671. for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
  672. KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
  673. if (!k->is_keyword) {
  674. asdl_seq_SET(new_seq, idx++, k->element);
  675. }
  676. }
  677. return new_seq;
  678. }
  679. /* Return a new asdl_seq* with only the keywords in kwargs */
  680. asdl_keyword_seq *_PyPegen_seq_delete_starred_exprs(Parser *p,
  681. asdl_seq *kwargs) {
  682. Py_ssize_t len = asdl_seq_LEN(kwargs);
  683. Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
  684. if (new_len == 0) {
  685. return NULL;
  686. }
  687. asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
  688. if (!new_seq) {
  689. return NULL;
  690. }
  691. int idx = 0;
  692. for (Py_ssize_t i = 0; i < len; i++) {
  693. KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
  694. if (k->is_keyword) {
  695. asdl_seq_SET(new_seq, idx++, k->element);
  696. }
  697. }
  698. return new_seq;
  699. }
  700. expr_ty _PyPegen_ensure_imaginary(Parser *p, expr_ty exp) {
  701. if (exp->kind != Constant_kind ||
  702. !PyComplex_CheckExact(exp->v.Constant.value)) {
  703. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
  704. exp, "imaginary number required in complex literal");
  705. return NULL;
  706. }
  707. return exp;
  708. }
  709. expr_ty _PyPegen_ensure_real(Parser *p, expr_ty exp) {
  710. if (exp->kind != Constant_kind ||
  711. PyComplex_CheckExact(exp->v.Constant.value)) {
  712. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
  713. exp, "real number required in complex literal");
  714. return NULL;
  715. }
  716. return exp;
  717. }
  718. mod_ty _PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
  719. asdl_type_ignore_seq *type_ignores = NULL;
  720. Py_ssize_t num = p->type_ignore_comments.num_items;
  721. if (num > 0) {
  722. // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
  723. type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
  724. if (type_ignores == NULL) {
  725. return NULL;
  726. }
  727. for (int i = 0; i < num; i++) {
  728. PyObject *tag = _PyPegen_new_type_comment(
  729. p, p->type_ignore_comments.items[i].comment);
  730. if (tag == NULL) {
  731. return NULL;
  732. }
  733. type_ignore_ty ti = _PyAST_TypeIgnore(
  734. p->type_ignore_comments.items[i].lineno, tag, p->arena);
  735. if (ti == NULL) {
  736. return NULL;
  737. }
  738. asdl_seq_SET(type_ignores, i, ti);
  739. }
  740. }
  741. return _PyAST_Module(a, type_ignores, p->arena);
  742. }
  743. PyObject *_PyPegen_new_type_comment(Parser *p, const char *s) {
  744. PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
  745. if (res == NULL) {
  746. return NULL;
  747. }
  748. if (_PyArena_AddPyObject(p->arena, res) < 0) {
  749. Py_DECREF(res);
  750. return NULL;
  751. }
  752. return res;
  753. }
  754. arg_ty _PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc) {
  755. if (tc == NULL) {
  756. return a;
  757. }
  758. const char *bytes = PyBytes_AsString(tc->bytes);
  759. if (bytes == NULL) {
  760. return NULL;
  761. }
  762. PyObject *tco = _PyPegen_new_type_comment(p, bytes);
  763. if (tco == NULL) {
  764. return NULL;
  765. }
  766. return _PyAST_arg(a->arg, a->annotation, tco, a->lineno, a->col_offset,
  767. a->end_lineno, a->end_col_offset, p->arena);
  768. }
  769. /* Checks if the NOTEQUAL token is valid given the current parser flags
  770. 0 indicates success and nonzero indicates failure (an exception may be set) */
  771. int _PyPegen_check_barry_as_flufl(Parser *p, Token *t) {
  772. assert(t->bytes != NULL);
  773. assert(t->type == NOTEQUAL);
  774. const char *tok_str = PyBytes_AS_STRING(t->bytes);
  775. if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>") != 0) {
  776. RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
  777. return -1;
  778. }
  779. if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
  780. return strcmp(tok_str, "!=");
  781. }
  782. return 0;
  783. }
  784. int _PyPegen_check_legacy_stmt(Parser *p, expr_ty name) {
  785. if (name->kind != Name_kind) {
  786. return 0;
  787. }
  788. const char *candidates[2] = {"print", "exec"};
  789. for (int i = 0; i < 2; i++) {
  790. if (PyUnicode_CompareWithASCIIString(name->v.Name.id, candidates[i]) == 0) {
  791. return 1;
  792. }
  793. }
  794. return 0;
  795. }
  796. static ResultTokenWithMetadata *
  797. result_token_with_metadata(Parser *p, void *result, PyObject *metadata) {
  798. ResultTokenWithMetadata *res =
  799. _PyArena_Malloc(p->arena, sizeof(ResultTokenWithMetadata));
  800. if (res == NULL) {
  801. return NULL;
  802. }
  803. res->metadata = metadata;
  804. res->result = result;
  805. return res;
  806. }
  807. ResultTokenWithMetadata *
  808. _PyPegen_check_fstring_conversion(Parser *p, Token *conv_token, expr_ty conv) {
  809. if (conv_token->lineno != conv->lineno ||
  810. conv_token->end_col_offset != conv->col_offset) {
  811. return RAISE_SYNTAX_ERROR_KNOWN_RANGE(conv_token, conv,
  812. "f-string: conversion type must come "
  813. "right after the exclamanation mark");
  814. }
  815. return result_token_with_metadata(p, conv, conv_token->metadata);
  816. }
  817. ResultTokenWithMetadata *
  818. _PyPegen_setup_full_format_spec(Parser *p, Token *colon, asdl_expr_seq *spec,
  819. int lineno, int col_offset, int end_lineno,
  820. int end_col_offset, PyArena *arena) {
  821. if (!spec) {
  822. return NULL;
  823. }
  824. // This is needed to keep compatibility with 3.11, where an empty format spec
  825. // is parsed as an *empty* JoinedStr node, instead of having an empty constant
  826. // in it.
  827. if (asdl_seq_LEN(spec) == 1) {
  828. expr_ty e = asdl_seq_GET(spec, 0);
  829. if (e->kind == Constant_kind && PyUnicode_Check(e->v.Constant.value) &&
  830. PyUnicode_GetLength(e->v.Constant.value) == 0) {
  831. spec = _Py_asdl_expr_seq_new(0, arena);
  832. }
  833. }
  834. expr_ty res;
  835. Py_ssize_t n = asdl_seq_LEN(spec);
  836. if (n == 0 || (n == 1 && asdl_seq_GET(spec, 0)->kind == Constant_kind)) {
  837. res = _PyAST_JoinedStr(spec, lineno, col_offset, end_lineno, end_col_offset,
  838. p->arena);
  839. } else {
  840. res = _PyPegen_concatenate_strings(p, spec, lineno, col_offset, end_lineno,
  841. end_col_offset, arena);
  842. }
  843. if (!res) {
  844. return NULL;
  845. }
  846. return result_token_with_metadata(p, res, colon->metadata);
  847. }
  848. const char *_PyPegen_get_expr_name(expr_ty e) {
  849. assert(e != NULL);
  850. switch (e->kind) {
  851. case Attribute_kind:
  852. return "attribute";
  853. case Subscript_kind:
  854. return "subscript";
  855. case Starred_kind:
  856. return "starred";
  857. case Name_kind:
  858. return "name";
  859. case List_kind:
  860. return "list";
  861. case Tuple_kind:
  862. return "tuple";
  863. case Lambda_kind:
  864. return "lambda";
  865. case Call_kind:
  866. return "function call";
  867. case BoolOp_kind:
  868. case BinOp_kind:
  869. case UnaryOp_kind:
  870. return "expression";
  871. case GeneratorExp_kind:
  872. return "generator expression";
  873. case Yield_kind:
  874. case YieldFrom_kind:
  875. return "yield expression";
  876. case Await_kind:
  877. return "await expression";
  878. case ListComp_kind:
  879. return "list comprehension";
  880. case SetComp_kind:
  881. return "set comprehension";
  882. case DictComp_kind:
  883. return "dict comprehension";
  884. case Dict_kind:
  885. return "dict literal";
  886. case Set_kind:
  887. return "set display";
  888. case JoinedStr_kind:
  889. case FormattedValue_kind:
  890. return "f-string expression";
  891. case Constant_kind: {
  892. PyObject *value = e->v.Constant.value;
  893. if (value == Py_None) {
  894. return "None";
  895. }
  896. if (value == Py_False) {
  897. return "False";
  898. }
  899. if (value == Py_True) {
  900. return "True";
  901. }
  902. if (value == Py_Ellipsis) {
  903. return "ellipsis";
  904. }
  905. return "literal";
  906. }
  907. case Compare_kind:
  908. return "comparison";
  909. case IfExp_kind:
  910. return "conditional expression";
  911. case NamedExpr_kind:
  912. return "named expression";
  913. default:
  914. PyErr_Format(PyExc_SystemError,
  915. "unexpected expression in assignment %d (line %d)", e->kind,
  916. e->lineno);
  917. return NULL;
  918. }
  919. }
  920. expr_ty _PyPegen_get_last_comprehension_item(comprehension_ty comprehension) {
  921. if (comprehension->ifs == NULL || asdl_seq_LEN(comprehension->ifs) == 0) {
  922. return comprehension->iter;
  923. }
  924. return PyPegen_last_item(comprehension->ifs, expr_ty);
  925. }
  926. expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
  927. int lineno, int col_offset, int end_lineno,
  928. int end_col_offset, PyArena *arena) {
  929. Py_ssize_t args_len = asdl_seq_LEN(a);
  930. Py_ssize_t total_len = args_len;
  931. if (b == NULL) {
  932. return _PyAST_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
  933. end_lineno, end_col_offset, arena);
  934. }
  935. asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
  936. asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
  937. if (starreds) {
  938. total_len += asdl_seq_LEN(starreds);
  939. }
  940. asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
  941. if (args == NULL) {
  942. return NULL;
  943. }
  944. Py_ssize_t i = 0;
  945. for (i = 0; i < args_len; i++) {
  946. asdl_seq_SET(args, i, asdl_seq_GET(a, i));
  947. }
  948. for (; i < total_len; i++) {
  949. asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
  950. }
  951. return _PyAST_Call(_PyPegen_dummy_name(p), args, keywords, lineno, col_offset,
  952. end_lineno, end_col_offset, arena);
  953. }
  954. // AST Error reporting helpers
  955. expr_ty _PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type) {
  956. if (e == NULL) {
  957. return NULL;
  958. }
  959. #define VISIT_CONTAINER(CONTAINER, TYPE) \
  960. do { \
  961. Py_ssize_t len = asdl_seq_LEN((CONTAINER)->v.TYPE.elts); \
  962. for (Py_ssize_t i = 0; i < len; i++) { \
  963. expr_ty other = asdl_seq_GET((CONTAINER)->v.TYPE.elts, i); \
  964. expr_ty child = _PyPegen_get_invalid_target(other, targets_type); \
  965. if (child != NULL) { \
  966. return child; \
  967. } \
  968. } \
  969. } while (0)
  970. // We only need to visit List and Tuple nodes recursively as those
  971. // are the only ones that can contain valid names in targets when
  972. // they are parsed as expressions. Any other kind of expression
  973. // that is a container (like Sets or Dicts) is directly invalid and
  974. // we don't need to visit it recursively.
  975. switch (e->kind) {
  976. case List_kind:
  977. VISIT_CONTAINER(e, List);
  978. return NULL;
  979. case Tuple_kind:
  980. VISIT_CONTAINER(e, Tuple);
  981. return NULL;
  982. case Starred_kind:
  983. if (targets_type == DEL_TARGETS) {
  984. return e;
  985. }
  986. return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
  987. case Compare_kind:
  988. // This is needed, because the `a in b` in `for a in b` gets parsed
  989. // as a comparison, and so we need to search the left side of the comparison
  990. // for invalid targets.
  991. if (targets_type == FOR_TARGETS) {
  992. cmpop_ty cmpop = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, 0);
  993. if (cmpop == In) {
  994. return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
  995. }
  996. return NULL;
  997. }
  998. return e;
  999. case Name_kind:
  1000. case Subscript_kind:
  1001. case Attribute_kind:
  1002. return NULL;
  1003. default:
  1004. return e;
  1005. }
  1006. }
  1007. void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
  1008. int kwarg_unpacking = 0;
  1009. for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
  1010. keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
  1011. if (!keyword->arg) {
  1012. kwarg_unpacking = 1;
  1013. }
  1014. }
  1015. const char *msg = NULL;
  1016. if (kwarg_unpacking) {
  1017. msg = "positional argument follows keyword argument unpacking";
  1018. } else {
  1019. msg = "positional argument follows keyword argument";
  1020. }
  1021. return RAISE_SYNTAX_ERROR(msg);
  1022. }
  1023. void *_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args,
  1024. asdl_comprehension_seq *comprehensions) {
  1025. /* The rule that calls this function is 'args for_if_clauses'.
  1026. For the input f(L, x for x in y), L and x are in args and
  1027. the for is parsed as a for_if_clause. We have to check if
  1028. len <= 1, so that input like dict((a, b) for a, b in x)
  1029. gets successfully parsed and then we pass the last
  1030. argument (x in the above example) as the location of the
  1031. error */
  1032. Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
  1033. if (len <= 1) {
  1034. return NULL;
  1035. }
  1036. comprehension_ty last_comprehension =
  1037. PyPegen_last_item(comprehensions, comprehension_ty);
  1038. return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
  1039. (expr_ty)asdl_seq_GET(args->v.Call.args, len - 1),
  1040. _PyPegen_get_last_comprehension_item(last_comprehension),
  1041. "Generator expression must be parenthesized");
  1042. }
  1043. // Fstring stuff
  1044. static expr_ty _PyPegen_decode_fstring_part(Parser *p, int is_raw,
  1045. expr_ty constant, Token *token) {
  1046. assert(PyUnicode_CheckExact(constant->v.Constant.value));
  1047. const char *bstr = PyUnicode_AsUTF8(constant->v.Constant.value);
  1048. if (bstr == NULL) {
  1049. return NULL;
  1050. }
  1051. size_t len;
  1052. if (strcmp(bstr, "{{") == 0 || strcmp(bstr, "}}") == 0) {
  1053. len = 1;
  1054. } else {
  1055. len = strlen(bstr);
  1056. }
  1057. is_raw = is_raw || strchr(bstr, '\\') == NULL;
  1058. PyObject *str = _PyPegen_decode_string(p, is_raw, bstr, len, token);
  1059. if (str == NULL) {
  1060. _Pypegen_raise_decode_error(p);
  1061. return NULL;
  1062. }
  1063. if (_PyArena_AddPyObject(p->arena, str) < 0) {
  1064. Py_DECREF(str);
  1065. return NULL;
  1066. }
  1067. return _PyAST_Constant(str, NULL, constant->lineno, constant->col_offset,
  1068. constant->end_lineno, constant->end_col_offset,
  1069. p->arena);
  1070. }
  1071. expr_ty
  1072. _PyPegen_joined_str(Parser *p, Token* a, asdl_expr_seq* expr, Token*b) {
  1073. /* The parser might put multiple f-string values into an individual
  1074. * JoinedStr node at the top level due to stuff like f-string debugging
  1075. * expressions. This function flattens those and promotes them to the
  1076. * upper level. Only simplifies AST, but the compiler already takes care
  1077. * of the regular output, so this is not necessary if you are not going
  1078. * to expose the output AST to Python level. */
  1079. Py_ssize_t n_items = asdl_seq_LEN(expr);
  1080. Py_ssize_t total_items = n_items;
  1081. for (Py_ssize_t i = 0; i < n_items; i++) {
  1082. expr_ty item = asdl_seq_GET(expr, i);
  1083. if (item->kind == JoinedStr_kind) {
  1084. total_items += asdl_seq_LEN(item->v.JoinedStr.values) - 1;
  1085. }
  1086. }
  1087. const char *quote_str = PyBytes_AsString(a->bytes);
  1088. if (quote_str == NULL) {
  1089. return NULL;
  1090. }
  1091. int is_raw = strpbrk(quote_str, "rR") != NULL;
  1092. asdl_expr_seq *seq = _Py_asdl_expr_seq_new(total_items, p->arena);
  1093. if (seq == NULL) {
  1094. return NULL;
  1095. }
  1096. Py_ssize_t index = 0;
  1097. for (Py_ssize_t i = 0; i < n_items; i++) {
  1098. expr_ty item = asdl_seq_GET(expr, i);
  1099. // This should correspond to a JoinedStr node of two elements
  1100. // created _PyPegen_formatted_value. This situation can only be the result of
  1101. // a f-string debug expression where the first element is a constant with the text and the second
  1102. // a formatted value with the expression.
  1103. if (item->kind == JoinedStr_kind) {
  1104. asdl_expr_seq *values = item->v.JoinedStr.values;
  1105. if (asdl_seq_LEN(values) != 2) {
  1106. PyErr_Format(PyExc_SystemError,
  1107. "unexpected JoinedStr node without debug data in f-string at line %d",
  1108. item->lineno);
  1109. return NULL;
  1110. }
  1111. expr_ty first = asdl_seq_GET(values, 0);
  1112. assert(first->kind == Constant_kind);
  1113. asdl_seq_SET(seq, index++, first);
  1114. expr_ty second = asdl_seq_GET(values, 1);
  1115. assert(second->kind == FormattedValue_kind);
  1116. asdl_seq_SET(seq, index++, second);
  1117. continue;
  1118. }
  1119. if (item->kind == Constant_kind) {
  1120. item = _PyPegen_decode_fstring_part(p, is_raw, item, b);
  1121. if (item == NULL) {
  1122. return NULL;
  1123. }
  1124. /* Tokenizer emits string parts even when the underlying string
  1125. might become an empty value (e.g. FSTRING_MIDDLE with the value \\n)
  1126. so we need to check for them and simplify it here. */
  1127. if (PyUnicode_CheckExact(item->v.Constant.value) &&
  1128. PyUnicode_GET_LENGTH(item->v.Constant.value) == 0) {
  1129. continue;
  1130. }
  1131. }
  1132. asdl_seq_SET(seq, index++, item);
  1133. }
  1134. asdl_expr_seq *resized_exprs;
  1135. if (index != total_items) {
  1136. resized_exprs = _Py_asdl_expr_seq_new(index, p->arena);
  1137. if (resized_exprs == NULL) {
  1138. return NULL;
  1139. }
  1140. for (Py_ssize_t i = 0; i < index; i++) {
  1141. asdl_seq_SET(resized_exprs, i, asdl_seq_GET(seq, i));
  1142. }
  1143. } else {
  1144. resized_exprs = seq;
  1145. }
  1146. return _PyAST_JoinedStr(resized_exprs, a->lineno, a->col_offset,
  1147. b->end_lineno, b->end_col_offset, p->arena);
  1148. }
  1149. expr_ty _PyPegen_decoded_constant_from_token(Parser *p, Token *tok) {
  1150. Py_ssize_t bsize;
  1151. char *bstr;
  1152. if (PyBytes_AsStringAndSize(tok->bytes, &bstr, &bsize) == -1) {
  1153. return NULL;
  1154. }
  1155. PyObject *str = _PyPegen_decode_string(p, 0, bstr, bsize, tok);
  1156. if (str == NULL) {
  1157. return NULL;
  1158. }
  1159. if (_PyArena_AddPyObject(p->arena, str) < 0) {
  1160. Py_DECREF(str);
  1161. return NULL;
  1162. }
  1163. return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
  1164. tok->end_lineno, tok->end_col_offset, p->arena);
  1165. }
  1166. expr_ty _PyPegen_constant_from_token(Parser *p, Token *tok) {
  1167. char *bstr = PyBytes_AsString(tok->bytes);
  1168. if (bstr == NULL) {
  1169. return NULL;
  1170. }
  1171. PyObject *str = PyUnicode_FromString(bstr);
  1172. if (str == NULL) {
  1173. return NULL;
  1174. }
  1175. if (_PyArena_AddPyObject(p->arena, str) < 0) {
  1176. Py_DECREF(str);
  1177. return NULL;
  1178. }
  1179. return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
  1180. tok->end_lineno, tok->end_col_offset, p->arena);
  1181. }
  1182. expr_ty _PyPegen_constant_from_string(Parser *p, Token *tok) {
  1183. char *the_str = PyBytes_AsString(tok->bytes);
  1184. if (the_str == NULL) {
  1185. return NULL;
  1186. }
  1187. PyObject *s = _PyPegen_parse_string(p, tok);
  1188. if (s == NULL) {
  1189. _Pypegen_raise_decode_error(p);
  1190. return NULL;
  1191. }
  1192. if (_PyArena_AddPyObject(p->arena, s) < 0) {
  1193. Py_DECREF(s);
  1194. return NULL;
  1195. }
  1196. PyObject *kind = NULL;
  1197. if (the_str && the_str[0] == 'u') {
  1198. kind = _PyPegen_new_identifier(p, "u");
  1199. if (kind == NULL) {
  1200. return NULL;
  1201. }
  1202. }
  1203. return _PyAST_Constant(s, kind, tok->lineno, tok->col_offset, tok->end_lineno,
  1204. tok->end_col_offset, p->arena);
  1205. }
  1206. expr_ty _PyPegen_formatted_value(Parser *p, expr_ty expression, Token *debug,
  1207. ResultTokenWithMetadata *conversion,
  1208. ResultTokenWithMetadata *format,
  1209. Token *closing_brace, int lineno,
  1210. int col_offset, int end_lineno,
  1211. int end_col_offset, PyArena *arena) {
  1212. int conversion_val = -1;
  1213. if (conversion != NULL) {
  1214. expr_ty conversion_expr = (expr_ty)conversion->result;
  1215. assert(conversion_expr->kind == Name_kind);
  1216. Py_UCS4 first = PyUnicode_READ_CHAR(conversion_expr->v.Name.id, 0);
  1217. if (PyUnicode_GET_LENGTH(conversion_expr->v.Name.id) > 1 ||
  1218. !(first == 's' || first == 'r' || first == 'a')) {
  1219. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
  1220. conversion_expr,
  1221. "f-string: invalid conversion character %R: expected 's', 'r', or "
  1222. "'a'",
  1223. conversion_expr->v.Name.id);
  1224. return NULL;
  1225. }
  1226. conversion_val = Py_SAFE_DOWNCAST(first, Py_UCS4, int);
  1227. } else if (debug && !format) {
  1228. /* If no conversion is specified, use !r for debug expressions */
  1229. conversion_val = (int)'r';
  1230. }
  1231. expr_ty formatted_value = _PyAST_FormattedValue(
  1232. expression, conversion_val, format ? (expr_ty)format->result : NULL,
  1233. lineno, col_offset, end_lineno, end_col_offset, arena);
  1234. if (debug) {
  1235. /* Find the non whitespace token after the "=" */
  1236. int debug_end_line, debug_end_offset;
  1237. PyObject *debug_metadata;
  1238. if (conversion) {
  1239. debug_end_line = ((expr_ty)conversion->result)->lineno;
  1240. debug_end_offset = ((expr_ty)conversion->result)->col_offset;
  1241. debug_metadata = conversion->metadata;
  1242. } else if (format) {
  1243. debug_end_line = ((expr_ty)format->result)->lineno;
  1244. debug_end_offset = ((expr_ty)format->result)->col_offset + 1;
  1245. debug_metadata = format->metadata;
  1246. } else {
  1247. debug_end_line = end_lineno;
  1248. debug_end_offset = end_col_offset;
  1249. debug_metadata = closing_brace->metadata;
  1250. }
  1251. expr_ty debug_text =
  1252. _PyAST_Constant(debug_metadata, NULL, lineno, col_offset + 1,
  1253. debug_end_line, debug_end_offset - 1, p->arena);
  1254. if (!debug_text) {
  1255. return NULL;
  1256. }
  1257. asdl_expr_seq *values = _Py_asdl_expr_seq_new(2, arena);
  1258. if (values == NULL) {
  1259. return NULL;
  1260. }
  1261. asdl_seq_SET(values, 0, debug_text);
  1262. asdl_seq_SET(values, 1, formatted_value);
  1263. return _PyAST_JoinedStr(values, lineno, col_offset, debug_end_line,
  1264. debug_end_offset, p->arena);
  1265. } else {
  1266. return formatted_value;
  1267. }
  1268. }
  1269. expr_ty _PyPegen_concatenate_strings(Parser *p, asdl_expr_seq *strings,
  1270. int lineno, int col_offset, int end_lineno,
  1271. int end_col_offset, PyArena *arena) {
  1272. Py_ssize_t len = asdl_seq_LEN(strings);
  1273. assert(len > 0);
  1274. int f_string_found = 0;
  1275. int unicode_string_found = 0;
  1276. int bytes_found = 0;
  1277. Py_ssize_t i = 0;
  1278. Py_ssize_t n_flattened_elements = 0;
  1279. for (i = 0; i < len; i++) {
  1280. expr_ty elem = asdl_seq_GET(strings, i);
  1281. switch (elem->kind) {
  1282. case Constant_kind:
  1283. if (PyBytes_CheckExact(elem->v.Constant.value)) {
  1284. bytes_found = 1;
  1285. } else {
  1286. unicode_string_found = 1;
  1287. }
  1288. n_flattened_elements++;
  1289. break;
  1290. case JoinedStr_kind:
  1291. n_flattened_elements += asdl_seq_LEN(elem->v.JoinedStr.values);
  1292. f_string_found = 1;
  1293. break;
  1294. default:
  1295. n_flattened_elements++;
  1296. f_string_found = 1;
  1297. break;
  1298. }
  1299. }
  1300. if ((unicode_string_found || f_string_found) && bytes_found) {
  1301. RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
  1302. return NULL;
  1303. }
  1304. if (bytes_found) {
  1305. PyObject *res = PyBytes_FromString("");
  1306. /* Bytes literals never get a kind, but just for consistency
  1307. since they are represented as Constant nodes, we'll mirror
  1308. the same behavior as unicode strings for determining the
  1309. kind. */
  1310. PyObject *kind = asdl_seq_GET(strings, 0)->v.Constant.kind;
  1311. for (i = 0; i < len; i++) {
  1312. expr_ty elem = asdl_seq_GET(strings, i);
  1313. PyBytes_Concat(&res, elem->v.Constant.value);
  1314. }
  1315. if (!res || _PyArena_AddPyObject(arena, res) < 0) {
  1316. Py_XDECREF(res);
  1317. return NULL;
  1318. }
  1319. return _PyAST_Constant(res, kind, lineno, col_offset, end_lineno,
  1320. end_col_offset, p->arena);
  1321. }
  1322. if (!f_string_found && len == 1) {
  1323. return asdl_seq_GET(strings, 0);
  1324. }
  1325. asdl_expr_seq *flattened =
  1326. _Py_asdl_expr_seq_new(n_flattened_elements, p->arena);
  1327. if (flattened == NULL) {
  1328. return NULL;
  1329. }
  1330. /* build flattened list */
  1331. Py_ssize_t current_pos = 0;
  1332. Py_ssize_t j = 0;
  1333. for (i = 0; i < len; i++) {
  1334. expr_ty elem = asdl_seq_GET(strings, i);
  1335. switch (elem->kind) {
  1336. case JoinedStr_kind:
  1337. for (j = 0; j < asdl_seq_LEN(elem->v.JoinedStr.values); j++) {
  1338. expr_ty subvalue = asdl_seq_GET(elem->v.JoinedStr.values, j);
  1339. if (subvalue == NULL) {
  1340. return NULL;
  1341. }
  1342. asdl_seq_SET(flattened, current_pos++, subvalue);
  1343. }
  1344. break;
  1345. default:
  1346. asdl_seq_SET(flattened, current_pos++, elem);
  1347. break;
  1348. }
  1349. }
  1350. /* calculate folded element count */
  1351. Py_ssize_t n_elements = 0;
  1352. int prev_is_constant = 0;
  1353. for (i = 0; i < n_flattened_elements; i++) {
  1354. expr_ty elem = asdl_seq_GET(flattened, i);
  1355. /* The concatenation of a FormattedValue and an empty Contant should
  1356. lead to the FormattedValue itself. Thus, we will not take any empty
  1357. constants into account, just as in `_PyPegen_joined_str` */
  1358. if (f_string_found && elem->kind == Constant_kind &&
  1359. PyUnicode_CheckExact(elem->v.Constant.value) &&
  1360. PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0)
  1361. continue;
  1362. if (!prev_is_constant || elem->kind != Constant_kind) {
  1363. n_elements++;
  1364. }
  1365. prev_is_constant = elem->kind == Constant_kind;
  1366. }
  1367. asdl_expr_seq *values = _Py_asdl_expr_seq_new(n_elements, p->arena);
  1368. if (values == NULL) {
  1369. return NULL;
  1370. }
  1371. /* build folded list */
  1372. _PyUnicodeWriter writer;
  1373. current_pos = 0;
  1374. for (i = 0; i < n_flattened_elements; i++) {
  1375. expr_ty elem = asdl_seq_GET(flattened, i);
  1376. /* if the current elem and the following are constants,
  1377. fold them and all consequent constants */
  1378. if (elem->kind == Constant_kind) {
  1379. if (i + 1 < n_flattened_elements &&
  1380. asdl_seq_GET(flattened, i + 1)->kind == Constant_kind) {
  1381. expr_ty first_elem = elem;
  1382. /* When a string is getting concatenated, the kind of the string
  1383. is determined by the first string in the concatenation
  1384. sequence.
  1385. u"abc" "def" -> u"abcdef"
  1386. "abc" u"abc" -> "abcabc" */
  1387. PyObject *kind = elem->v.Constant.kind;
  1388. _PyUnicodeWriter_Init(&writer);
  1389. expr_ty last_elem = elem;
  1390. for (j = i; j < n_flattened_elements; j++) {
  1391. expr_ty current_elem = asdl_seq_GET(flattened, j);
  1392. if (current_elem->kind == Constant_kind) {
  1393. if (_PyUnicodeWriter_WriteStr(&writer,
  1394. current_elem->v.Constant.value)) {
  1395. _PyUnicodeWriter_Dealloc(&writer);
  1396. return NULL;
  1397. }
  1398. last_elem = current_elem;
  1399. } else {
  1400. break;
  1401. }
  1402. }
  1403. i = j - 1;
  1404. PyObject *concat_str = _PyUnicodeWriter_Finish(&writer);
  1405. if (concat_str == NULL) {
  1406. _PyUnicodeWriter_Dealloc(&writer);
  1407. return NULL;
  1408. }
  1409. if (_PyArena_AddPyObject(p->arena, concat_str) < 0) {
  1410. Py_DECREF(concat_str);
  1411. return NULL;
  1412. }
  1413. elem = _PyAST_Constant(concat_str, kind, first_elem->lineno,
  1414. first_elem->col_offset, last_elem->end_lineno,
  1415. last_elem->end_col_offset, p->arena);
  1416. if (elem == NULL) {
  1417. return NULL;
  1418. }
  1419. }
  1420. /* Drop all empty contanst strings */
  1421. if (f_string_found && PyUnicode_CheckExact(elem->v.Constant.value) &&
  1422. PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0) {
  1423. continue;
  1424. }
  1425. }
  1426. asdl_seq_SET(values, current_pos++, elem);
  1427. }
  1428. if (!f_string_found) {
  1429. assert(n_elements == 1);
  1430. expr_ty elem = asdl_seq_GET(values, 0);
  1431. assert(elem->kind == Constant_kind);
  1432. return elem;
  1433. }
  1434. assert(current_pos == n_elements);
  1435. return _PyAST_JoinedStr(values, lineno, col_offset, end_lineno,
  1436. end_col_offset, p->arena);
  1437. }