action_helpers.c 51 KB

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