action_helpers.c 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611
  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. static asdl_expr_seq *
  818. unpack_top_level_joined_strs(Parser *p, asdl_expr_seq *raw_expressions);
  819. ResultTokenWithMetadata *
  820. _PyPegen_setup_full_format_spec(Parser *p, Token *colon, asdl_expr_seq *spec,
  821. int lineno, int col_offset, int end_lineno,
  822. int end_col_offset, PyArena *arena) {
  823. if (!spec) {
  824. return NULL;
  825. }
  826. // This is needed to keep compatibility with 3.11, where an empty format spec
  827. // is parsed as an *empty* JoinedStr node, instead of having an empty constant
  828. // in it.
  829. if (asdl_seq_LEN(spec) == 1) {
  830. expr_ty e = asdl_seq_GET(spec, 0);
  831. if (e->kind == Constant_kind && PyUnicode_Check(e->v.Constant.value) &&
  832. PyUnicode_GetLength(e->v.Constant.value) == 0) {
  833. spec = _Py_asdl_expr_seq_new(0, arena);
  834. }
  835. }
  836. expr_ty res;
  837. Py_ssize_t n = asdl_seq_LEN(spec);
  838. if (n == 0 || (n == 1 && asdl_seq_GET(spec, 0)->kind == Constant_kind)) {
  839. res = _PyAST_JoinedStr(spec, lineno, col_offset, end_lineno, end_col_offset,
  840. p->arena);
  841. } else {
  842. res = _PyPegen_concatenate_strings(p, spec, lineno, col_offset, end_lineno,
  843. end_col_offset, arena);
  844. }
  845. if (!res) {
  846. return NULL;
  847. }
  848. return result_token_with_metadata(p, res, colon->metadata);
  849. }
  850. const char *_PyPegen_get_expr_name(expr_ty e) {
  851. assert(e != NULL);
  852. switch (e->kind) {
  853. case Attribute_kind:
  854. return "attribute";
  855. case Subscript_kind:
  856. return "subscript";
  857. case Starred_kind:
  858. return "starred";
  859. case Name_kind:
  860. return "name";
  861. case List_kind:
  862. return "list";
  863. case Tuple_kind:
  864. return "tuple";
  865. case Lambda_kind:
  866. return "lambda";
  867. case Call_kind:
  868. return "function call";
  869. case BoolOp_kind:
  870. case BinOp_kind:
  871. case UnaryOp_kind:
  872. return "expression";
  873. case GeneratorExp_kind:
  874. return "generator expression";
  875. case Yield_kind:
  876. case YieldFrom_kind:
  877. return "yield expression";
  878. case Await_kind:
  879. return "await expression";
  880. case ListComp_kind:
  881. return "list comprehension";
  882. case SetComp_kind:
  883. return "set comprehension";
  884. case DictComp_kind:
  885. return "dict comprehension";
  886. case Dict_kind:
  887. return "dict literal";
  888. case Set_kind:
  889. return "set display";
  890. case JoinedStr_kind:
  891. case FormattedValue_kind:
  892. return "f-string expression";
  893. case Constant_kind: {
  894. PyObject *value = e->v.Constant.value;
  895. if (value == Py_None) {
  896. return "None";
  897. }
  898. if (value == Py_False) {
  899. return "False";
  900. }
  901. if (value == Py_True) {
  902. return "True";
  903. }
  904. if (value == Py_Ellipsis) {
  905. return "ellipsis";
  906. }
  907. return "literal";
  908. }
  909. case Compare_kind:
  910. return "comparison";
  911. case IfExp_kind:
  912. return "conditional expression";
  913. case NamedExpr_kind:
  914. return "named expression";
  915. default:
  916. PyErr_Format(PyExc_SystemError,
  917. "unexpected expression in assignment %d (line %d)", e->kind,
  918. e->lineno);
  919. return NULL;
  920. }
  921. }
  922. expr_ty _PyPegen_get_last_comprehension_item(comprehension_ty comprehension) {
  923. if (comprehension->ifs == NULL || asdl_seq_LEN(comprehension->ifs) == 0) {
  924. return comprehension->iter;
  925. }
  926. return PyPegen_last_item(comprehension->ifs, expr_ty);
  927. }
  928. expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
  929. int lineno, int col_offset, int end_lineno,
  930. int end_col_offset, PyArena *arena) {
  931. Py_ssize_t args_len = asdl_seq_LEN(a);
  932. Py_ssize_t total_len = args_len;
  933. if (b == NULL) {
  934. return _PyAST_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
  935. end_lineno, end_col_offset, arena);
  936. }
  937. asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
  938. asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
  939. if (starreds) {
  940. total_len += asdl_seq_LEN(starreds);
  941. }
  942. asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
  943. if (args == NULL) {
  944. return NULL;
  945. }
  946. Py_ssize_t i = 0;
  947. for (i = 0; i < args_len; i++) {
  948. asdl_seq_SET(args, i, asdl_seq_GET(a, i));
  949. }
  950. for (; i < total_len; i++) {
  951. asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
  952. }
  953. return _PyAST_Call(_PyPegen_dummy_name(p), args, keywords, lineno, col_offset,
  954. end_lineno, end_col_offset, arena);
  955. }
  956. // AST Error reporting helpers
  957. expr_ty _PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type) {
  958. if (e == NULL) {
  959. return NULL;
  960. }
  961. #define VISIT_CONTAINER(CONTAINER, TYPE) \
  962. do { \
  963. Py_ssize_t len = asdl_seq_LEN((CONTAINER)->v.TYPE.elts); \
  964. for (Py_ssize_t i = 0; i < len; i++) { \
  965. expr_ty other = asdl_seq_GET((CONTAINER)->v.TYPE.elts, i); \
  966. expr_ty child = _PyPegen_get_invalid_target(other, targets_type); \
  967. if (child != NULL) { \
  968. return child; \
  969. } \
  970. } \
  971. } while (0)
  972. // We only need to visit List and Tuple nodes recursively as those
  973. // are the only ones that can contain valid names in targets when
  974. // they are parsed as expressions. Any other kind of expression
  975. // that is a container (like Sets or Dicts) is directly invalid and
  976. // we don't need to visit it recursively.
  977. switch (e->kind) {
  978. case List_kind:
  979. VISIT_CONTAINER(e, List);
  980. return NULL;
  981. case Tuple_kind:
  982. VISIT_CONTAINER(e, Tuple);
  983. return NULL;
  984. case Starred_kind:
  985. if (targets_type == DEL_TARGETS) {
  986. return e;
  987. }
  988. return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
  989. case Compare_kind:
  990. // This is needed, because the `a in b` in `for a in b` gets parsed
  991. // as a comparison, and so we need to search the left side of the comparison
  992. // for invalid targets.
  993. if (targets_type == FOR_TARGETS) {
  994. cmpop_ty cmpop = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, 0);
  995. if (cmpop == In) {
  996. return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
  997. }
  998. return NULL;
  999. }
  1000. return e;
  1001. case Name_kind:
  1002. case Subscript_kind:
  1003. case Attribute_kind:
  1004. return NULL;
  1005. default:
  1006. return e;
  1007. }
  1008. }
  1009. void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
  1010. int kwarg_unpacking = 0;
  1011. for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
  1012. keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
  1013. if (!keyword->arg) {
  1014. kwarg_unpacking = 1;
  1015. }
  1016. }
  1017. const char *msg = NULL;
  1018. if (kwarg_unpacking) {
  1019. msg = "positional argument follows keyword argument unpacking";
  1020. } else {
  1021. msg = "positional argument follows keyword argument";
  1022. }
  1023. return RAISE_SYNTAX_ERROR(msg);
  1024. }
  1025. void *_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args,
  1026. asdl_comprehension_seq *comprehensions) {
  1027. /* The rule that calls this function is 'args for_if_clauses'.
  1028. For the input f(L, x for x in y), L and x are in args and
  1029. the for is parsed as a for_if_clause. We have to check if
  1030. len <= 1, so that input like dict((a, b) for a, b in x)
  1031. gets successfully parsed and then we pass the last
  1032. argument (x in the above example) as the location of the
  1033. error */
  1034. Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
  1035. if (len <= 1) {
  1036. return NULL;
  1037. }
  1038. comprehension_ty last_comprehension =
  1039. PyPegen_last_item(comprehensions, comprehension_ty);
  1040. return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
  1041. (expr_ty)asdl_seq_GET(args->v.Call.args, len - 1),
  1042. _PyPegen_get_last_comprehension_item(last_comprehension),
  1043. "Generator expression must be parenthesized");
  1044. }
  1045. // Fstring stuff
  1046. static expr_ty _PyPegen_decode_fstring_part(Parser *p, int is_raw,
  1047. expr_ty constant, Token *token) {
  1048. assert(PyUnicode_CheckExact(constant->v.Constant.value));
  1049. const char *bstr = PyUnicode_AsUTF8(constant->v.Constant.value);
  1050. if (bstr == NULL) {
  1051. return NULL;
  1052. }
  1053. size_t len;
  1054. if (strcmp(bstr, "{{") == 0 || strcmp(bstr, "}}") == 0) {
  1055. len = 1;
  1056. } else {
  1057. len = strlen(bstr);
  1058. }
  1059. is_raw = is_raw || strchr(bstr, '\\') == NULL;
  1060. PyObject *str = _PyPegen_decode_string(p, is_raw, bstr, len, token);
  1061. if (str == NULL) {
  1062. _Pypegen_raise_decode_error(p);
  1063. return NULL;
  1064. }
  1065. if (_PyArena_AddPyObject(p->arena, str) < 0) {
  1066. Py_DECREF(str);
  1067. return NULL;
  1068. }
  1069. return _PyAST_Constant(str, NULL, constant->lineno, constant->col_offset,
  1070. constant->end_lineno, constant->end_col_offset,
  1071. p->arena);
  1072. }
  1073. static asdl_expr_seq *
  1074. unpack_top_level_joined_strs(Parser *p, asdl_expr_seq *raw_expressions) {
  1075. /* The parser might put multiple f-string values into an individual
  1076. * JoinedStr node at the top level due to stuff like f-string debugging
  1077. * expressions. This function flattens those and promotes them to the
  1078. * upper level. Only simplifies AST, but the compiler already takes care
  1079. * of the regular output, so this is not necessary if you are not going
  1080. * to expose the output AST to Python level. */
  1081. Py_ssize_t i, req_size, raw_size;
  1082. req_size = raw_size = asdl_seq_LEN(raw_expressions);
  1083. expr_ty expr;
  1084. for (i = 0; i < raw_size; i++) {
  1085. expr = asdl_seq_GET(raw_expressions, i);
  1086. if (expr->kind == JoinedStr_kind) {
  1087. req_size += asdl_seq_LEN(expr->v.JoinedStr.values) - 1;
  1088. }
  1089. }
  1090. asdl_expr_seq *expressions = _Py_asdl_expr_seq_new(req_size, p->arena);
  1091. if (expressions == NULL) {
  1092. return NULL;
  1093. }
  1094. Py_ssize_t raw_index, req_index = 0;
  1095. for (raw_index = 0; raw_index < raw_size; raw_index++) {
  1096. expr = asdl_seq_GET(raw_expressions, raw_index);
  1097. if (expr->kind == JoinedStr_kind) {
  1098. asdl_expr_seq *values = expr->v.JoinedStr.values;
  1099. for (Py_ssize_t n = 0; n < asdl_seq_LEN(values); n++) {
  1100. asdl_seq_SET(expressions, req_index, asdl_seq_GET(values, n));
  1101. req_index++;
  1102. }
  1103. } else {
  1104. asdl_seq_SET(expressions, req_index, expr);
  1105. req_index++;
  1106. }
  1107. }
  1108. return expressions;
  1109. }
  1110. expr_ty _PyPegen_joined_str(Parser *p, Token *a, asdl_expr_seq *raw_expressions,
  1111. Token *b) {
  1112. asdl_expr_seq *expr = unpack_top_level_joined_strs(p, raw_expressions);
  1113. Py_ssize_t n_items = asdl_seq_LEN(expr);
  1114. const char *quote_str = PyBytes_AsString(a->bytes);
  1115. if (quote_str == NULL) {
  1116. return NULL;
  1117. }
  1118. int is_raw = strpbrk(quote_str, "rR") != NULL;
  1119. asdl_expr_seq *seq = _Py_asdl_expr_seq_new(n_items, p->arena);
  1120. if (seq == NULL) {
  1121. return NULL;
  1122. }
  1123. Py_ssize_t index = 0;
  1124. for (Py_ssize_t i = 0; i < n_items; i++) {
  1125. expr_ty item = asdl_seq_GET(expr, i);
  1126. if (item->kind == Constant_kind) {
  1127. item = _PyPegen_decode_fstring_part(p, is_raw, item, b);
  1128. if (item == NULL) {
  1129. return NULL;
  1130. }
  1131. /* Tokenizer emits string parts even when the underlying string
  1132. might become an empty value (e.g. FSTRING_MIDDLE with the value \\n)
  1133. so we need to check for them and simplify it here. */
  1134. if (PyUnicode_CheckExact(item->v.Constant.value) &&
  1135. PyUnicode_GET_LENGTH(item->v.Constant.value) == 0) {
  1136. continue;
  1137. }
  1138. }
  1139. asdl_seq_SET(seq, index++, item);
  1140. }
  1141. asdl_expr_seq *resized_exprs;
  1142. if (index != n_items) {
  1143. resized_exprs = _Py_asdl_expr_seq_new(index, p->arena);
  1144. if (resized_exprs == NULL) {
  1145. return NULL;
  1146. }
  1147. for (Py_ssize_t i = 0; i < index; i++) {
  1148. asdl_seq_SET(resized_exprs, i, asdl_seq_GET(seq, i));
  1149. }
  1150. } else {
  1151. resized_exprs = seq;
  1152. }
  1153. return _PyAST_JoinedStr(resized_exprs, a->lineno, a->col_offset,
  1154. b->end_lineno, b->end_col_offset, p->arena);
  1155. }
  1156. expr_ty _PyPegen_decoded_constant_from_token(Parser *p, Token *tok) {
  1157. Py_ssize_t bsize;
  1158. char *bstr;
  1159. if (PyBytes_AsStringAndSize(tok->bytes, &bstr, &bsize) == -1) {
  1160. return NULL;
  1161. }
  1162. PyObject *str = _PyPegen_decode_string(p, 0, bstr, bsize, tok);
  1163. if (str == NULL) {
  1164. return NULL;
  1165. }
  1166. if (_PyArena_AddPyObject(p->arena, str) < 0) {
  1167. Py_DECREF(str);
  1168. return NULL;
  1169. }
  1170. return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
  1171. tok->end_lineno, tok->end_col_offset, p->arena);
  1172. }
  1173. expr_ty _PyPegen_constant_from_token(Parser *p, Token *tok) {
  1174. char *bstr = PyBytes_AsString(tok->bytes);
  1175. if (bstr == NULL) {
  1176. return NULL;
  1177. }
  1178. PyObject *str = PyUnicode_FromString(bstr);
  1179. if (str == NULL) {
  1180. return NULL;
  1181. }
  1182. if (_PyArena_AddPyObject(p->arena, str) < 0) {
  1183. Py_DECREF(str);
  1184. return NULL;
  1185. }
  1186. return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
  1187. tok->end_lineno, tok->end_col_offset, p->arena);
  1188. }
  1189. expr_ty _PyPegen_constant_from_string(Parser *p, Token *tok) {
  1190. char *the_str = PyBytes_AsString(tok->bytes);
  1191. if (the_str == NULL) {
  1192. return NULL;
  1193. }
  1194. PyObject *s = _PyPegen_parse_string(p, tok);
  1195. if (s == NULL) {
  1196. _Pypegen_raise_decode_error(p);
  1197. return NULL;
  1198. }
  1199. if (_PyArena_AddPyObject(p->arena, s) < 0) {
  1200. Py_DECREF(s);
  1201. return NULL;
  1202. }
  1203. PyObject *kind = NULL;
  1204. if (the_str && the_str[0] == 'u') {
  1205. kind = _PyPegen_new_identifier(p, "u");
  1206. if (kind == NULL) {
  1207. return NULL;
  1208. }
  1209. }
  1210. return _PyAST_Constant(s, kind, tok->lineno, tok->col_offset, tok->end_lineno,
  1211. tok->end_col_offset, p->arena);
  1212. }
  1213. expr_ty _PyPegen_formatted_value(Parser *p, expr_ty expression, Token *debug,
  1214. ResultTokenWithMetadata *conversion,
  1215. ResultTokenWithMetadata *format,
  1216. Token *closing_brace, int lineno,
  1217. int col_offset, int end_lineno,
  1218. int end_col_offset, PyArena *arena) {
  1219. int conversion_val = -1;
  1220. if (conversion != NULL) {
  1221. expr_ty conversion_expr = (expr_ty)conversion->result;
  1222. assert(conversion_expr->kind == Name_kind);
  1223. Py_UCS4 first = PyUnicode_READ_CHAR(conversion_expr->v.Name.id, 0);
  1224. if (PyUnicode_GET_LENGTH(conversion_expr->v.Name.id) > 1 ||
  1225. !(first == 's' || first == 'r' || first == 'a')) {
  1226. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
  1227. conversion_expr,
  1228. "f-string: invalid conversion character %R: expected 's', 'r', or "
  1229. "'a'",
  1230. conversion_expr->v.Name.id);
  1231. return NULL;
  1232. }
  1233. conversion_val = Py_SAFE_DOWNCAST(first, Py_UCS4, int);
  1234. } else if (debug && !format) {
  1235. /* If no conversion is specified, use !r for debug expressions */
  1236. conversion_val = (int)'r';
  1237. }
  1238. expr_ty formatted_value = _PyAST_FormattedValue(
  1239. expression, conversion_val, format ? (expr_ty)format->result : NULL,
  1240. lineno, col_offset, end_lineno, end_col_offset, arena);
  1241. if (debug) {
  1242. /* Find the non whitespace token after the "=" */
  1243. int debug_end_line, debug_end_offset;
  1244. PyObject *debug_metadata;
  1245. if (conversion) {
  1246. debug_end_line = ((expr_ty)conversion->result)->lineno;
  1247. debug_end_offset = ((expr_ty)conversion->result)->col_offset;
  1248. debug_metadata = conversion->metadata;
  1249. } else if (format) {
  1250. debug_end_line = ((expr_ty)format->result)->lineno;
  1251. debug_end_offset = ((expr_ty)format->result)->col_offset + 1;
  1252. debug_metadata = format->metadata;
  1253. } else {
  1254. debug_end_line = end_lineno;
  1255. debug_end_offset = end_col_offset;
  1256. debug_metadata = closing_brace->metadata;
  1257. }
  1258. expr_ty debug_text =
  1259. _PyAST_Constant(debug_metadata, NULL, lineno, col_offset + 1,
  1260. debug_end_line, debug_end_offset - 1, p->arena);
  1261. if (!debug_text) {
  1262. return NULL;
  1263. }
  1264. asdl_expr_seq *values = _Py_asdl_expr_seq_new(2, arena);
  1265. if (values == NULL) {
  1266. return NULL;
  1267. }
  1268. asdl_seq_SET(values, 0, debug_text);
  1269. asdl_seq_SET(values, 1, formatted_value);
  1270. return _PyAST_JoinedStr(values, lineno, col_offset, debug_end_line,
  1271. debug_end_offset, p->arena);
  1272. } else {
  1273. return formatted_value;
  1274. }
  1275. }
  1276. expr_ty _PyPegen_concatenate_strings(Parser *p, asdl_expr_seq *strings,
  1277. int lineno, int col_offset, int end_lineno,
  1278. int end_col_offset, PyArena *arena) {
  1279. Py_ssize_t len = asdl_seq_LEN(strings);
  1280. assert(len > 0);
  1281. int f_string_found = 0;
  1282. int unicode_string_found = 0;
  1283. int bytes_found = 0;
  1284. Py_ssize_t i = 0;
  1285. Py_ssize_t n_flattened_elements = 0;
  1286. for (i = 0; i < len; i++) {
  1287. expr_ty elem = asdl_seq_GET(strings, i);
  1288. switch (elem->kind) {
  1289. case Constant_kind:
  1290. if (PyBytes_CheckExact(elem->v.Constant.value)) {
  1291. bytes_found = 1;
  1292. } else {
  1293. unicode_string_found = 1;
  1294. }
  1295. n_flattened_elements++;
  1296. break;
  1297. case JoinedStr_kind:
  1298. n_flattened_elements += asdl_seq_LEN(elem->v.JoinedStr.values);
  1299. f_string_found = 1;
  1300. break;
  1301. default:
  1302. n_flattened_elements++;
  1303. f_string_found = 1;
  1304. break;
  1305. }
  1306. }
  1307. if ((unicode_string_found || f_string_found) && bytes_found) {
  1308. RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
  1309. return NULL;
  1310. }
  1311. if (bytes_found) {
  1312. PyObject *res = PyBytes_FromString("");
  1313. /* Bytes literals never get a kind, but just for consistency
  1314. since they are represented as Constant nodes, we'll mirror
  1315. the same behavior as unicode strings for determining the
  1316. kind. */
  1317. PyObject *kind = asdl_seq_GET(strings, 0)->v.Constant.kind;
  1318. for (i = 0; i < len; i++) {
  1319. expr_ty elem = asdl_seq_GET(strings, i);
  1320. PyBytes_Concat(&res, elem->v.Constant.value);
  1321. }
  1322. if (!res || _PyArena_AddPyObject(arena, res) < 0) {
  1323. Py_XDECREF(res);
  1324. return NULL;
  1325. }
  1326. return _PyAST_Constant(res, kind, lineno, col_offset, end_lineno,
  1327. end_col_offset, p->arena);
  1328. }
  1329. if (!f_string_found && len == 1) {
  1330. return asdl_seq_GET(strings, 0);
  1331. }
  1332. asdl_expr_seq *flattened =
  1333. _Py_asdl_expr_seq_new(n_flattened_elements, p->arena);
  1334. if (flattened == NULL) {
  1335. return NULL;
  1336. }
  1337. /* build flattened list */
  1338. Py_ssize_t current_pos = 0;
  1339. Py_ssize_t j = 0;
  1340. for (i = 0; i < len; i++) {
  1341. expr_ty elem = asdl_seq_GET(strings, i);
  1342. switch (elem->kind) {
  1343. case JoinedStr_kind:
  1344. for (j = 0; j < asdl_seq_LEN(elem->v.JoinedStr.values); j++) {
  1345. expr_ty subvalue = asdl_seq_GET(elem->v.JoinedStr.values, j);
  1346. if (subvalue == NULL) {
  1347. return NULL;
  1348. }
  1349. asdl_seq_SET(flattened, current_pos++, subvalue);
  1350. }
  1351. break;
  1352. default:
  1353. asdl_seq_SET(flattened, current_pos++, elem);
  1354. break;
  1355. }
  1356. }
  1357. /* calculate folded element count */
  1358. Py_ssize_t n_elements = 0;
  1359. int prev_is_constant = 0;
  1360. for (i = 0; i < n_flattened_elements; i++) {
  1361. expr_ty elem = asdl_seq_GET(flattened, i);
  1362. /* The concatenation of a FormattedValue and an empty Contant should
  1363. lead to the FormattedValue itself. Thus, we will not take any empty
  1364. constants into account, just as in `_PyPegen_joined_str` */
  1365. if (f_string_found && elem->kind == Constant_kind &&
  1366. PyUnicode_CheckExact(elem->v.Constant.value) &&
  1367. PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0)
  1368. continue;
  1369. if (!prev_is_constant || elem->kind != Constant_kind) {
  1370. n_elements++;
  1371. }
  1372. prev_is_constant = elem->kind == Constant_kind;
  1373. }
  1374. asdl_expr_seq *values = _Py_asdl_expr_seq_new(n_elements, p->arena);
  1375. if (values == NULL) {
  1376. return NULL;
  1377. }
  1378. /* build folded list */
  1379. _PyUnicodeWriter writer;
  1380. current_pos = 0;
  1381. for (i = 0; i < n_flattened_elements; i++) {
  1382. expr_ty elem = asdl_seq_GET(flattened, i);
  1383. /* if the current elem and the following are constants,
  1384. fold them and all consequent constants */
  1385. if (elem->kind == Constant_kind) {
  1386. if (i + 1 < n_flattened_elements &&
  1387. asdl_seq_GET(flattened, i + 1)->kind == Constant_kind) {
  1388. expr_ty first_elem = elem;
  1389. /* When a string is getting concatenated, the kind of the string
  1390. is determined by the first string in the concatenation
  1391. sequence.
  1392. u"abc" "def" -> u"abcdef"
  1393. "abc" u"abc" -> "abcabc" */
  1394. PyObject *kind = elem->v.Constant.kind;
  1395. _PyUnicodeWriter_Init(&writer);
  1396. expr_ty last_elem = elem;
  1397. for (j = i; j < n_flattened_elements; j++) {
  1398. expr_ty current_elem = asdl_seq_GET(flattened, j);
  1399. if (current_elem->kind == Constant_kind) {
  1400. if (_PyUnicodeWriter_WriteStr(&writer,
  1401. current_elem->v.Constant.value)) {
  1402. _PyUnicodeWriter_Dealloc(&writer);
  1403. return NULL;
  1404. }
  1405. last_elem = current_elem;
  1406. } else {
  1407. break;
  1408. }
  1409. }
  1410. i = j - 1;
  1411. PyObject *concat_str = _PyUnicodeWriter_Finish(&writer);
  1412. if (concat_str == NULL) {
  1413. _PyUnicodeWriter_Dealloc(&writer);
  1414. return NULL;
  1415. }
  1416. if (_PyArena_AddPyObject(p->arena, concat_str) < 0) {
  1417. Py_DECREF(concat_str);
  1418. return NULL;
  1419. }
  1420. elem = _PyAST_Constant(concat_str, kind, first_elem->lineno,
  1421. first_elem->col_offset, last_elem->end_lineno,
  1422. last_elem->end_col_offset, p->arena);
  1423. if (elem == NULL) {
  1424. return NULL;
  1425. }
  1426. }
  1427. /* Drop all empty contanst strings */
  1428. if (f_string_found && PyUnicode_CheckExact(elem->v.Constant.value) &&
  1429. PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0) {
  1430. continue;
  1431. }
  1432. }
  1433. asdl_seq_SET(values, current_pos++, elem);
  1434. }
  1435. if (!f_string_found) {
  1436. assert(n_elements == 1);
  1437. expr_ty elem = asdl_seq_GET(values, 0);
  1438. assert(elem->kind == Constant_kind);
  1439. return elem;
  1440. }
  1441. assert(current_pos == n_elements);
  1442. return _PyAST_JoinedStr(values, lineno, col_offset, end_lineno,
  1443. end_col_offset, p->arena);
  1444. }