action_helpers.c 49 KB

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