You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1024 lines
48 KiB

  1. # PEG grammar for Python
  2. @trailer '''
  3. void *
  4. _PyPegen_parse(Parser *p)
  5. {
  6. // Initialize keywords
  7. p->keywords = reserved_keywords;
  8. p->n_keyword_lists = n_keyword_lists;
  9. p->soft_keywords = soft_keywords;
  10. // Run parser
  11. void *result = NULL;
  12. if (p->start_rule == Py_file_input) {
  13. result = file_rule(p);
  14. } else if (p->start_rule == Py_single_input) {
  15. result = interactive_rule(p);
  16. } else if (p->start_rule == Py_eval_input) {
  17. result = eval_rule(p);
  18. } else if (p->start_rule == Py_func_type_input) {
  19. result = func_type_rule(p);
  20. } else if (p->start_rule == Py_fstring_input) {
  21. result = fstring_rule(p);
  22. }
  23. return result;
  24. }
  25. // The end
  26. '''
  27. file[mod_ty]: a=[statements] ENDMARKER { _PyPegen_make_module(p, a) }
  28. interactive[mod_ty]: a=statement_newline { _PyAST_Interactive(a, p->arena) }
  29. eval[mod_ty]: a=expressions NEWLINE* ENDMARKER { _PyAST_Expression(a, p->arena) }
  30. func_type[mod_ty]: '(' a=[type_expressions] ')' '->' b=expression NEWLINE* ENDMARKER { _PyAST_FunctionType(a, b, p->arena) }
  31. fstring[expr_ty]: star_expressions
  32. # type_expressions allow */** but ignore them
  33. type_expressions[asdl_expr_seq*]:
  34. | a=','.expression+ ',' '*' b=expression ',' '**' c=expression {
  35. (asdl_expr_seq*)_PyPegen_seq_append_to_end(
  36. p,
  37. CHECK(asdl_seq*, _PyPegen_seq_append_to_end(p, a, b)),
  38. c) }
  39. | a=','.expression+ ',' '*' b=expression { (asdl_expr_seq*)_PyPegen_seq_append_to_end(p, a, b) }
  40. | a=','.expression+ ',' '**' b=expression { (asdl_expr_seq*)_PyPegen_seq_append_to_end(p, a, b) }
  41. | '*' a=expression ',' '**' b=expression {
  42. (asdl_expr_seq*)_PyPegen_seq_append_to_end(
  43. p,
  44. CHECK(asdl_seq*, _PyPegen_singleton_seq(p, a)),
  45. b) }
  46. | '*' a=expression { (asdl_expr_seq*)_PyPegen_singleton_seq(p, a) }
  47. | '**' a=expression { (asdl_expr_seq*)_PyPegen_singleton_seq(p, a) }
  48. | a[asdl_expr_seq*]=','.expression+ {a}
  49. statements[asdl_stmt_seq*]: a=statement+ { (asdl_stmt_seq*)_PyPegen_seq_flatten(p, a) }
  50. statement[asdl_stmt_seq*]: a=compound_stmt { (asdl_stmt_seq*)_PyPegen_singleton_seq(p, a) } | a[asdl_stmt_seq*]=simple_stmts { a }
  51. statement_newline[asdl_stmt_seq*]:
  52. | a=compound_stmt NEWLINE { (asdl_stmt_seq*)_PyPegen_singleton_seq(p, a) }
  53. | simple_stmts
  54. | NEWLINE { (asdl_stmt_seq*)_PyPegen_singleton_seq(p, CHECK(stmt_ty, _PyAST_Pass(EXTRA))) }
  55. | ENDMARKER { _PyPegen_interactive_exit(p) }
  56. simple_stmts[asdl_stmt_seq*]:
  57. | a=simple_stmt !';' NEWLINE { (asdl_stmt_seq*)_PyPegen_singleton_seq(p, a) } # Not needed, there for speedup
  58. | a[asdl_stmt_seq*]=';'.simple_stmt+ [';'] NEWLINE { a }
  59. # NOTE: assignment MUST precede expression, else parsing a simple assignment
  60. # will throw a SyntaxError.
  61. simple_stmt[stmt_ty] (memo):
  62. | assignment
  63. | e=star_expressions { _PyAST_Expr(e, EXTRA) }
  64. | &'return' return_stmt
  65. | &('import' | 'from') import_stmt
  66. | &'raise' raise_stmt
  67. | 'pass' { _PyAST_Pass(EXTRA) }
  68. | &'del' del_stmt
  69. | &'yield' yield_stmt
  70. | &'assert' assert_stmt
  71. | 'break' { _PyAST_Break(EXTRA) }
  72. | 'continue' { _PyAST_Continue(EXTRA) }
  73. | &'global' global_stmt
  74. | &'nonlocal' nonlocal_stmt
  75. compound_stmt[stmt_ty]:
  76. | &('def' | '@' | ASYNC) function_def
  77. | &'if' if_stmt
  78. | &('class' | '@') class_def
  79. | &('with' | ASYNC) with_stmt
  80. | &('for' | ASYNC) for_stmt
  81. | &'try' try_stmt
  82. | &'while' while_stmt
  83. | match_stmt
  84. # NOTE: annotated_rhs may start with 'yield'; yield_expr must start with 'yield'
  85. assignment[stmt_ty]:
  86. | a=NAME ':' b=expression c=['=' d=annotated_rhs { d }] {
  87. CHECK_VERSION(
  88. stmt_ty,
  89. 6,
  90. "Variable annotation syntax is",
  91. _PyAST_AnnAssign(CHECK(expr_ty, _PyPegen_set_expr_context(p, a, Store)), b, c, 1, EXTRA)
  92. ) }
  93. | a=('(' b=single_target ')' { b }
  94. | single_subscript_attribute_target) ':' b=expression c=['=' d=annotated_rhs { d }] {
  95. CHECK_VERSION(stmt_ty, 6, "Variable annotations syntax is", _PyAST_AnnAssign(a, b, c, 0, EXTRA)) }
  96. | a[asdl_expr_seq*]=(z=star_targets '=' { z })+ b=(yield_expr | star_expressions) !'=' tc=[TYPE_COMMENT] {
  97. _PyAST_Assign(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA) }
  98. | a=single_target b=augassign ~ c=(yield_expr | star_expressions) {
  99. _PyAST_AugAssign(a, b->kind, c, EXTRA) }
  100. | invalid_assignment
  101. augassign[AugOperator*]:
  102. | '+=' { _PyPegen_augoperator(p, Add) }
  103. | '-=' { _PyPegen_augoperator(p, Sub) }
  104. | '*=' { _PyPegen_augoperator(p, Mult) }
  105. | '@=' { CHECK_VERSION(AugOperator*, 5, "The '@' operator is", _PyPegen_augoperator(p, MatMult)) }
  106. | '/=' { _PyPegen_augoperator(p, Div) }
  107. | '%=' { _PyPegen_augoperator(p, Mod) }
  108. | '&=' { _PyPegen_augoperator(p, BitAnd) }
  109. | '|=' { _PyPegen_augoperator(p, BitOr) }
  110. | '^=' { _PyPegen_augoperator(p, BitXor) }
  111. | '<<=' { _PyPegen_augoperator(p, LShift) }
  112. | '>>=' { _PyPegen_augoperator(p, RShift) }
  113. | '**=' { _PyPegen_augoperator(p, Pow) }
  114. | '//=' { _PyPegen_augoperator(p, FloorDiv) }
  115. global_stmt[stmt_ty]: 'global' a[asdl_expr_seq*]=','.NAME+ {
  116. _PyAST_Global(CHECK(asdl_identifier_seq*, _PyPegen_map_names_to_ids(p, a)), EXTRA) }
  117. nonlocal_stmt[stmt_ty]: 'nonlocal' a[asdl_expr_seq*]=','.NAME+ {
  118. _PyAST_Nonlocal(CHECK(asdl_identifier_seq*, _PyPegen_map_names_to_ids(p, a)), EXTRA) }
  119. yield_stmt[stmt_ty]: y=yield_expr { _PyAST_Expr(y, EXTRA) }
  120. assert_stmt[stmt_ty]: 'assert' a=expression b=[',' z=expression { z }] { _PyAST_Assert(a, b, EXTRA) }
  121. del_stmt[stmt_ty]:
  122. | 'del' a=del_targets &(';' | NEWLINE) { _PyAST_Delete(a, EXTRA) }
  123. | invalid_del_stmt
  124. import_stmt[stmt_ty]: import_name | import_from
  125. import_name[stmt_ty]: 'import' a=dotted_as_names { _PyAST_Import(a, EXTRA) }
  126. # note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS
  127. import_from[stmt_ty]:
  128. | 'from' a=('.' | '...')* b=dotted_name 'import' c=import_from_targets {
  129. _PyAST_ImportFrom(b->v.Name.id, c, _PyPegen_seq_count_dots(a), EXTRA) }
  130. | 'from' a=('.' | '...')+ 'import' b=import_from_targets {
  131. _PyAST_ImportFrom(NULL, b, _PyPegen_seq_count_dots(a), EXTRA) }
  132. import_from_targets[asdl_alias_seq*]:
  133. | '(' a=import_from_as_names [','] ')' { a }
  134. | import_from_as_names !','
  135. | '*' { (asdl_alias_seq*)_PyPegen_singleton_seq(p, CHECK(alias_ty, _PyPegen_alias_for_star(p, EXTRA))) }
  136. | invalid_import_from_targets
  137. import_from_as_names[asdl_alias_seq*]:
  138. | a[asdl_alias_seq*]=','.import_from_as_name+ { a }
  139. import_from_as_name[alias_ty]:
  140. | a=NAME b=['as' z=NAME { z }] { _PyAST_alias(a->v.Name.id,
  141. (b) ? ((expr_ty) b)->v.Name.id : NULL,
  142. EXTRA) }
  143. dotted_as_names[asdl_alias_seq*]:
  144. | a[asdl_alias_seq*]=','.dotted_as_name+ { a }
  145. dotted_as_name[alias_ty]:
  146. | a=dotted_name b=['as' z=NAME { z }] { _PyAST_alias(a->v.Name.id,
  147. (b) ? ((expr_ty) b)->v.Name.id : NULL,
  148. EXTRA) }
  149. dotted_name[expr_ty]:
  150. | a=dotted_name '.' b=NAME { _PyPegen_join_names_with_dot(p, a, b) }
  151. | NAME
  152. if_stmt[stmt_ty]:
  153. | invalid_if_stmt
  154. | 'if' a=named_expression ':' b=block c=elif_stmt {
  155. _PyAST_If(a, b, CHECK(asdl_stmt_seq*, _PyPegen_singleton_seq(p, c)), EXTRA) }
  156. | 'if' a=named_expression ':' b=block c=[else_block] { _PyAST_If(a, b, c, EXTRA) }
  157. elif_stmt[stmt_ty]:
  158. | invalid_elif_stmt
  159. | 'elif' a=named_expression ':' b=block c=elif_stmt {
  160. _PyAST_If(a, b, CHECK(asdl_stmt_seq*, _PyPegen_singleton_seq(p, c)), EXTRA) }
  161. | 'elif' a=named_expression ':' b=block c=[else_block] { _PyAST_If(a, b, c, EXTRA) }
  162. else_block[asdl_stmt_seq*]:
  163. | invalid_else_stmt
  164. | 'else' &&':' b=block { b }
  165. while_stmt[stmt_ty]:
  166. | invalid_while_stmt
  167. | 'while' a=named_expression ':' b=block c=[else_block] { _PyAST_While(a, b, c, EXTRA) }
  168. for_stmt[stmt_ty]:
  169. | invalid_for_stmt
  170. | 'for' t=star_targets 'in' ~ ex=star_expressions &&':' tc=[TYPE_COMMENT] b=block el=[else_block] {
  171. _PyAST_For(t, ex, b, el, NEW_TYPE_COMMENT(p, tc), EXTRA) }
  172. | ASYNC 'for' t=star_targets 'in' ~ ex=star_expressions &&':' tc=[TYPE_COMMENT] b=block el=[else_block] {
  173. CHECK_VERSION(stmt_ty, 5, "Async for loops are", _PyAST_AsyncFor(t, ex, b, el, NEW_TYPE_COMMENT(p, tc), EXTRA)) }
  174. | invalid_for_target
  175. with_stmt[stmt_ty]:
  176. | invalid_with_stmt_indent
  177. | 'with' '(' a[asdl_withitem_seq*]=','.with_item+ ','? ')' ':' b=block {
  178. _PyAST_With(a, b, NULL, EXTRA) }
  179. | 'with' a[asdl_withitem_seq*]=','.with_item+ ':' tc=[TYPE_COMMENT] b=block {
  180. _PyAST_With(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA) }
  181. | ASYNC 'with' '(' a[asdl_withitem_seq*]=','.with_item+ ','? ')' ':' b=block {
  182. CHECK_VERSION(stmt_ty, 5, "Async with statements are", _PyAST_AsyncWith(a, b, NULL, EXTRA)) }
  183. | ASYNC 'with' a[asdl_withitem_seq*]=','.with_item+ ':' tc=[TYPE_COMMENT] b=block {
  184. CHECK_VERSION(stmt_ty, 5, "Async with statements are", _PyAST_AsyncWith(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA)) }
  185. | invalid_with_stmt
  186. with_item[withitem_ty]:
  187. | e=expression 'as' t=star_target &(',' | ')' | ':') { _PyAST_withitem(e, t, p->arena) }
  188. | invalid_with_item
  189. | e=expression { _PyAST_withitem(e, NULL, p->arena) }
  190. try_stmt[stmt_ty]:
  191. | invalid_try_stmt
  192. | 'try' &&':' b=block f=finally_block { _PyAST_Try(b, NULL, NULL, f, EXTRA) }
  193. | 'try' &&':' b=block ex[asdl_excepthandler_seq*]=except_block+ el=[else_block] f=[finally_block] { _PyAST_Try(b, ex, el, f, EXTRA) }
  194. except_block[excepthandler_ty]:
  195. | invalid_except_stmt_indent
  196. | 'except' e=expression t=['as' z=NAME { z }] ':' b=block {
  197. _PyAST_ExceptHandler(e, (t) ? ((expr_ty) t)->v.Name.id : NULL, b, EXTRA) }
  198. | 'except' ':' b=block { _PyAST_ExceptHandler(NULL, NULL, b, EXTRA) }
  199. | invalid_except_stmt
  200. finally_block[asdl_stmt_seq*]:
  201. | invalid_finally_stmt
  202. | 'finally' &&':' a=block { a }
  203. match_stmt[stmt_ty]:
  204. | "match" subject=subject_expr ':' NEWLINE INDENT cases[asdl_match_case_seq*]=case_block+ DEDENT {
  205. CHECK_VERSION(stmt_ty, 10, "Pattern matching is", _PyAST_Match(subject, cases, EXTRA)) }
  206. | invalid_match_stmt
  207. subject_expr[expr_ty]:
  208. | value=star_named_expression ',' values=star_named_expressions? {
  209. _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, value, values)), Load, EXTRA) }
  210. | named_expression
  211. case_block[match_case_ty]:
  212. | invalid_case_block
  213. | "case" pattern=patterns guard=guard? ':' body=block {
  214. _PyAST_match_case(pattern, guard, body, p->arena) }
  215. guard[expr_ty]: 'if' guard=named_expression { guard }
  216. patterns[pattern_ty]:
  217. | patterns[asdl_pattern_seq*]=open_sequence_pattern {
  218. _PyAST_MatchSequence(patterns, EXTRA) }
  219. | pattern
  220. pattern[pattern_ty]:
  221. | as_pattern
  222. | or_pattern
  223. as_pattern[pattern_ty]:
  224. | pattern=or_pattern 'as' target=pattern_capture_target {
  225. _PyAST_MatchAs(pattern, target->v.Name.id, EXTRA) }
  226. | invalid_as_pattern
  227. or_pattern[pattern_ty]:
  228. | patterns[asdl_pattern_seq*]='|'.closed_pattern+ {
  229. asdl_seq_LEN(patterns) == 1 ? asdl_seq_GET(patterns, 0) : _PyAST_MatchOr(patterns, EXTRA) }
  230. closed_pattern[pattern_ty]:
  231. | literal_pattern
  232. | capture_pattern
  233. | wildcard_pattern
  234. | value_pattern
  235. | group_pattern
  236. | sequence_pattern
  237. | mapping_pattern
  238. | class_pattern
  239. # Literal patterns are used for equality and identity constraints
  240. literal_pattern[pattern_ty]:
  241. | value=signed_number !('+' | '-') { _PyAST_MatchValue(value, EXTRA) }
  242. | value=complex_number { _PyAST_MatchValue(value, EXTRA) }
  243. | value=strings { _PyAST_MatchValue(value, EXTRA) }
  244. | 'None' { _PyAST_MatchSingleton(Py_None, EXTRA) }
  245. | 'True' { _PyAST_MatchSingleton(Py_True, EXTRA) }
  246. | 'False' { _PyAST_MatchSingleton(Py_False, EXTRA) }
  247. # Literal expressions are used to restrict permitted mapping pattern keys
  248. literal_expr[expr_ty]:
  249. | signed_number !('+' | '-')
  250. | complex_number
  251. | strings
  252. | 'None' { _PyAST_Constant(Py_None, NULL, EXTRA) }
  253. | 'True' { _PyAST_Constant(Py_True, NULL, EXTRA) }
  254. | 'False' { _PyAST_Constant(Py_False, NULL, EXTRA) }
  255. complex_number[expr_ty]:
  256. | real=signed_real_number '+' imag=imaginary_number {
  257. _PyAST_BinOp(real, Add, imag, EXTRA) }
  258. | real=signed_real_number '-' imag=imaginary_number {
  259. _PyAST_BinOp(real, Sub, imag, EXTRA) }
  260. signed_number[expr_ty]:
  261. | NUMBER
  262. | '-' number=NUMBER { _PyAST_UnaryOp(USub, number, EXTRA) }
  263. signed_real_number[expr_ty]:
  264. | real_number
  265. | '-' real=real_number { _PyAST_UnaryOp(USub, real, EXTRA) }
  266. real_number[expr_ty]:
  267. | real=NUMBER { _PyPegen_ensure_real(p, real) }
  268. imaginary_number[expr_ty]:
  269. | imag=NUMBER { _PyPegen_ensure_imaginary(p, imag) }
  270. capture_pattern[pattern_ty]:
  271. | target=pattern_capture_target { _PyAST_MatchAs(NULL, target->v.Name.id, EXTRA) }
  272. pattern_capture_target[expr_ty]:
  273. | !"_" name=NAME !('.' | '(' | '=') {
  274. _PyPegen_set_expr_context(p, name, Store) }
  275. wildcard_pattern[pattern_ty]:
  276. | "_" { _PyAST_MatchAs(NULL, NULL, EXTRA) }
  277. value_pattern[pattern_ty]:
  278. | attr=attr !('.' | '(' | '=') { _PyAST_MatchValue(attr, EXTRA) }
  279. attr[expr_ty]:
  280. | value=name_or_attr '.' attr=NAME {
  281. _PyAST_Attribute(value, attr->v.Name.id, Load, EXTRA) }
  282. name_or_attr[expr_ty]:
  283. | attr
  284. | NAME
  285. group_pattern[pattern_ty]:
  286. | '(' pattern=pattern ')' { pattern }
  287. sequence_pattern[pattern_ty]:
  288. | '[' patterns=maybe_sequence_pattern? ']' { _PyAST_MatchSequence(patterns, EXTRA) }
  289. | '(' patterns=open_sequence_pattern? ')' { _PyAST_MatchSequence(patterns, EXTRA) }
  290. open_sequence_pattern[asdl_seq*]:
  291. | pattern=maybe_star_pattern ',' patterns=maybe_sequence_pattern? {
  292. _PyPegen_seq_insert_in_front(p, pattern, patterns) }
  293. maybe_sequence_pattern[asdl_seq*]:
  294. | patterns=','.maybe_star_pattern+ ','? { patterns }
  295. maybe_star_pattern[pattern_ty]:
  296. | star_pattern
  297. | pattern
  298. star_pattern[pattern_ty]:
  299. | '*' target=pattern_capture_target {
  300. _PyAST_MatchStar(target->v.Name.id, EXTRA) }
  301. | '*' wildcard_pattern {
  302. _PyAST_MatchStar(NULL, EXTRA) }
  303. mapping_pattern[pattern_ty]:
  304. | '{' '}' {
  305. _PyAST_MatchMapping(NULL, NULL, NULL, EXTRA) }
  306. | '{' rest=double_star_pattern ','? '}' {
  307. _PyAST_MatchMapping(NULL, NULL, rest->v.Name.id, EXTRA) }
  308. | '{' items=items_pattern ',' rest=double_star_pattern ','? '}' {
  309. _PyAST_MatchMapping(
  310. CHECK(asdl_expr_seq*, _PyPegen_get_pattern_keys(p, items)),
  311. CHECK(asdl_pattern_seq*, _PyPegen_get_patterns(p, items)),
  312. rest->v.Name.id,
  313. EXTRA) }
  314. | '{' items=items_pattern ','? '}' {
  315. _PyAST_MatchMapping(
  316. CHECK(asdl_expr_seq*, _PyPegen_get_pattern_keys(p, items)),
  317. CHECK(asdl_pattern_seq*, _PyPegen_get_patterns(p, items)),
  318. NULL,
  319. EXTRA) }
  320. items_pattern[asdl_seq*]:
  321. | ','.key_value_pattern+
  322. key_value_pattern[KeyPatternPair*]:
  323. | key=(literal_expr | attr) ':' pattern=pattern {
  324. _PyPegen_key_pattern_pair(p, key, pattern) }
  325. double_star_pattern[expr_ty]:
  326. | '**' target=pattern_capture_target { target }
  327. class_pattern[pattern_ty]:
  328. | cls=name_or_attr '(' ')' {
  329. _PyAST_MatchClass(cls, NULL, NULL, NULL, EXTRA) }
  330. | cls=name_or_attr '(' patterns=positional_patterns ','? ')' {
  331. _PyAST_MatchClass(cls, patterns, NULL, NULL, EXTRA) }
  332. | cls=name_or_attr '(' keywords=keyword_patterns ','? ')' {
  333. _PyAST_MatchClass(
  334. cls, NULL,
  335. CHECK(asdl_identifier_seq*, _PyPegen_map_names_to_ids(p,
  336. CHECK(asdl_expr_seq*, _PyPegen_get_pattern_keys(p, keywords)))),
  337. CHECK(asdl_pattern_seq*, _PyPegen_get_patterns(p, keywords)),
  338. EXTRA) }
  339. | cls=name_or_attr '(' patterns=positional_patterns ',' keywords=keyword_patterns ','? ')' {
  340. _PyAST_MatchClass(
  341. cls,
  342. patterns,
  343. CHECK(asdl_identifier_seq*, _PyPegen_map_names_to_ids(p,
  344. CHECK(asdl_expr_seq*, _PyPegen_get_pattern_keys(p, keywords)))),
  345. CHECK(asdl_pattern_seq*, _PyPegen_get_patterns(p, keywords)),
  346. EXTRA) }
  347. | invalid_class_pattern
  348. positional_patterns[asdl_pattern_seq*]:
  349. | args[asdl_pattern_seq*]=','.pattern+ { args }
  350. keyword_patterns[asdl_seq*]:
  351. | ','.keyword_pattern+
  352. keyword_pattern[KeyPatternPair*]:
  353. | arg=NAME '=' value=pattern { _PyPegen_key_pattern_pair(p, arg, value) }
  354. return_stmt[stmt_ty]:
  355. | 'return' a=[star_expressions] { _PyAST_Return(a, EXTRA) }
  356. raise_stmt[stmt_ty]:
  357. | 'raise' a=expression b=['from' z=expression { z }] { _PyAST_Raise(a, b, EXTRA) }
  358. | 'raise' { _PyAST_Raise(NULL, NULL, EXTRA) }
  359. function_def[stmt_ty]:
  360. | d=decorators f=function_def_raw { _PyPegen_function_def_decorators(p, d, f) }
  361. | function_def_raw
  362. function_def_raw[stmt_ty]:
  363. | invalid_def_raw
  364. | 'def' n=NAME '(' params=[params] ')' a=['->' z=expression { z }] &&':' tc=[func_type_comment] b=block {
  365. _PyAST_FunctionDef(n->v.Name.id,
  366. (params) ? params : CHECK(arguments_ty, _PyPegen_empty_arguments(p)),
  367. b, NULL, a, NEW_TYPE_COMMENT(p, tc), EXTRA) }
  368. | ASYNC 'def' n=NAME '(' params=[params] ')' a=['->' z=expression { z }] &&':' tc=[func_type_comment] b=block {
  369. CHECK_VERSION(
  370. stmt_ty,
  371. 5,
  372. "Async functions are",
  373. _PyAST_AsyncFunctionDef(n->v.Name.id,
  374. (params) ? params : CHECK(arguments_ty, _PyPegen_empty_arguments(p)),
  375. b, NULL, a, NEW_TYPE_COMMENT(p, tc), EXTRA)
  376. ) }
  377. func_type_comment[Token*]:
  378. | NEWLINE t=TYPE_COMMENT &(NEWLINE INDENT) { t } # Must be followed by indented block
  379. | invalid_double_type_comments
  380. | TYPE_COMMENT
  381. params[arguments_ty]:
  382. | invalid_parameters
  383. | parameters
  384. parameters[arguments_ty]:
  385. | a=slash_no_default b[asdl_arg_seq*]=param_no_default* c=param_with_default* d=[star_etc] {
  386. _PyPegen_make_arguments(p, a, NULL, b, c, d) }
  387. | a=slash_with_default b=param_with_default* c=[star_etc] {
  388. _PyPegen_make_arguments(p, NULL, a, NULL, b, c) }
  389. | a[asdl_arg_seq*]=param_no_default+ b=param_with_default* c=[star_etc] {
  390. _PyPegen_make_arguments(p, NULL, NULL, a, b, c) }
  391. | a=param_with_default+ b=[star_etc] { _PyPegen_make_arguments(p, NULL, NULL, NULL, a, b)}
  392. | a=star_etc { _PyPegen_make_arguments(p, NULL, NULL, NULL, NULL, a) }
  393. # Some duplication here because we can't write (',' | &')'),
  394. # which is because we don't support empty alternatives (yet).
  395. #
  396. slash_no_default[asdl_arg_seq*]:
  397. | a[asdl_arg_seq*]=param_no_default+ '/' ',' { a }
  398. | a[asdl_arg_seq*]=param_no_default+ '/' &')' { a }
  399. slash_with_default[SlashWithDefault*]:
  400. | a=param_no_default* b=param_with_default+ '/' ',' { _PyPegen_slash_with_default(p, (asdl_arg_seq *)a, b) }
  401. | a=param_no_default* b=param_with_default+ '/' &')' { _PyPegen_slash_with_default(p, (asdl_arg_seq *)a, b) }
  402. star_etc[StarEtc*]:
  403. | '*' a=param_no_default b=param_maybe_default* c=[kwds] {
  404. _PyPegen_star_etc(p, a, b, c) }
  405. | '*' ',' b=param_maybe_default+ c=[kwds] {
  406. _PyPegen_star_etc(p, NULL, b, c) }
  407. | a=kwds { _PyPegen_star_etc(p, NULL, NULL, a) }
  408. | invalid_star_etc
  409. kwds[arg_ty]: '**' a=param_no_default { a }
  410. # One parameter. This *includes* a following comma and type comment.
  411. #
  412. # There are three styles:
  413. # - No default
  414. # - With default
  415. # - Maybe with default
  416. #
  417. # There are two alternative forms of each, to deal with type comments:
  418. # - Ends in a comma followed by an optional type comment
  419. # - No comma, optional type comment, must be followed by close paren
  420. # The latter form is for a final parameter without trailing comma.
  421. #
  422. param_no_default[arg_ty]:
  423. | a=param ',' tc=TYPE_COMMENT? { _PyPegen_add_type_comment_to_arg(p, a, tc) }
  424. | a=param tc=TYPE_COMMENT? &')' { _PyPegen_add_type_comment_to_arg(p, a, tc) }
  425. param_with_default[NameDefaultPair*]:
  426. | a=param c=default ',' tc=TYPE_COMMENT? { _PyPegen_name_default_pair(p, a, c, tc) }
  427. | a=param c=default tc=TYPE_COMMENT? &')' { _PyPegen_name_default_pair(p, a, c, tc) }
  428. param_maybe_default[NameDefaultPair*]:
  429. | a=param c=default? ',' tc=TYPE_COMMENT? { _PyPegen_name_default_pair(p, a, c, tc) }
  430. | a=param c=default? tc=TYPE_COMMENT? &')' { _PyPegen_name_default_pair(p, a, c, tc) }
  431. param[arg_ty]: a=NAME b=annotation? { _PyAST_arg(a->v.Name.id, b, NULL, EXTRA) }
  432. annotation[expr_ty]: ':' a=expression { a }
  433. default[expr_ty]: '=' a=expression { a }
  434. decorators[asdl_expr_seq*]: a[asdl_expr_seq*]=('@' f=named_expression NEWLINE { f })+ { a }
  435. class_def[stmt_ty]:
  436. | a=decorators b=class_def_raw { _PyPegen_class_def_decorators(p, a, b) }
  437. | class_def_raw
  438. class_def_raw[stmt_ty]:
  439. | invalid_class_def_raw
  440. | 'class' a=NAME b=['(' z=[arguments] ')' { z }] &&':' c=block {
  441. _PyAST_ClassDef(a->v.Name.id,
  442. (b) ? ((expr_ty) b)->v.Call.args : NULL,
  443. (b) ? ((expr_ty) b)->v.Call.keywords : NULL,
  444. c, NULL, EXTRA) }
  445. block[asdl_stmt_seq*] (memo):
  446. | NEWLINE INDENT a=statements DEDENT { a }
  447. | simple_stmts
  448. | invalid_block
  449. star_expressions[expr_ty]:
  450. | a=star_expression b=(',' c=star_expression { c })+ [','] {
  451. _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)), Load, EXTRA) }
  452. | a=star_expression ',' { _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_singleton_seq(p, a)), Load, EXTRA) }
  453. | star_expression
  454. star_expression[expr_ty] (memo):
  455. | '*' a=bitwise_or { _PyAST_Starred(a, Load, EXTRA) }
  456. | expression
  457. star_named_expressions[asdl_expr_seq*]: a[asdl_expr_seq*]=','.star_named_expression+ [','] { a }
  458. star_named_expression[expr_ty]:
  459. | '*' a=bitwise_or { _PyAST_Starred(a, Load, EXTRA) }
  460. | named_expression
  461. assigment_expression[expr_ty]:
  462. | a=NAME ':=' ~ b=expression { _PyAST_NamedExpr(CHECK(expr_ty, _PyPegen_set_expr_context(p, a, Store)), b, EXTRA) }
  463. named_expression[expr_ty]:
  464. | assigment_expression
  465. | invalid_named_expression
  466. | expression !':='
  467. annotated_rhs[expr_ty]: yield_expr | star_expressions
  468. expressions[expr_ty]:
  469. | a=expression b=(',' c=expression { c })+ [','] {
  470. _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)), Load, EXTRA) }
  471. | a=expression ',' { _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_singleton_seq(p, a)), Load, EXTRA) }
  472. | expression
  473. expression[expr_ty] (memo):
  474. | invalid_expression
  475. | a=disjunction 'if' b=disjunction 'else' c=expression { _PyAST_IfExp(b, a, c, EXTRA) }
  476. | disjunction
  477. | lambdef
  478. lambdef[expr_ty]:
  479. | 'lambda' a=[lambda_params] ':' b=expression {
  480. _PyAST_Lambda((a) ? a : CHECK(arguments_ty, _PyPegen_empty_arguments(p)), b, EXTRA) }
  481. lambda_params[arguments_ty]:
  482. | invalid_lambda_parameters
  483. | lambda_parameters
  484. # lambda_parameters etc. duplicates parameters but without annotations
  485. # or type comments, and if there's no comma after a parameter, we expect
  486. # a colon, not a close parenthesis. (For more, see parameters above.)
  487. #
  488. lambda_parameters[arguments_ty]:
  489. | a=lambda_slash_no_default b[asdl_arg_seq*]=lambda_param_no_default* c=lambda_param_with_default* d=[lambda_star_etc] {
  490. _PyPegen_make_arguments(p, a, NULL, b, c, d) }
  491. | a=lambda_slash_with_default b=lambda_param_with_default* c=[lambda_star_etc] {
  492. _PyPegen_make_arguments(p, NULL, a, NULL, b, c) }
  493. | a[asdl_arg_seq*]=lambda_param_no_default+ b=lambda_param_with_default* c=[lambda_star_etc] {
  494. _PyPegen_make_arguments(p, NULL, NULL, a, b, c) }
  495. | a=lambda_param_with_default+ b=[lambda_star_etc] { _PyPegen_make_arguments(p, NULL, NULL, NULL, a, b)}
  496. | a=lambda_star_etc { _PyPegen_make_arguments(p, NULL, NULL, NULL, NULL, a) }
  497. lambda_slash_no_default[asdl_arg_seq*]:
  498. | a[asdl_arg_seq*]=lambda_param_no_default+ '/' ',' { a }
  499. | a[asdl_arg_seq*]=lambda_param_no_default+ '/' &':' { a }
  500. lambda_slash_with_default[SlashWithDefault*]:
  501. | a=lambda_param_no_default* b=lambda_param_with_default+ '/' ',' { _PyPegen_slash_with_default(p, (asdl_arg_seq *)a, b) }
  502. | a=lambda_param_no_default* b=lambda_param_with_default+ '/' &':' { _PyPegen_slash_with_default(p, (asdl_arg_seq *)a, b) }
  503. lambda_star_etc[StarEtc*]:
  504. | '*' a=lambda_param_no_default b=lambda_param_maybe_default* c=[lambda_kwds] {
  505. _PyPegen_star_etc(p, a, b, c) }
  506. | '*' ',' b=lambda_param_maybe_default+ c=[lambda_kwds] {
  507. _PyPegen_star_etc(p, NULL, b, c) }
  508. | a=lambda_kwds { _PyPegen_star_etc(p, NULL, NULL, a) }
  509. | invalid_lambda_star_etc
  510. lambda_kwds[arg_ty]: '**' a=lambda_param_no_default { a }
  511. lambda_param_no_default[arg_ty]:
  512. | a=lambda_param ',' { a }
  513. | a=lambda_param &':' { a }
  514. lambda_param_with_default[NameDefaultPair*]:
  515. | a=lambda_param c=default ',' { _PyPegen_name_default_pair(p, a, c, NULL) }
  516. | a=lambda_param c=default &':' { _PyPegen_name_default_pair(p, a, c, NULL) }
  517. lambda_param_maybe_default[NameDefaultPair*]:
  518. | a=lambda_param c=default? ',' { _PyPegen_name_default_pair(p, a, c, NULL) }
  519. | a=lambda_param c=default? &':' { _PyPegen_name_default_pair(p, a, c, NULL) }
  520. lambda_param[arg_ty]: a=NAME { _PyAST_arg(a->v.Name.id, NULL, NULL, EXTRA) }
  521. disjunction[expr_ty] (memo):
  522. | a=conjunction b=('or' c=conjunction { c })+ { _PyAST_BoolOp(
  523. Or,
  524. CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)),
  525. EXTRA) }
  526. | conjunction
  527. conjunction[expr_ty] (memo):
  528. | a=inversion b=('and' c=inversion { c })+ { _PyAST_BoolOp(
  529. And,
  530. CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)),
  531. EXTRA) }
  532. | inversion
  533. inversion[expr_ty] (memo):
  534. | 'not' a=inversion { _PyAST_UnaryOp(Not, a, EXTRA) }
  535. | comparison
  536. comparison[expr_ty]:
  537. | a=bitwise_or b=compare_op_bitwise_or_pair+ {
  538. _PyAST_Compare(
  539. a,
  540. CHECK(asdl_int_seq*, _PyPegen_get_cmpops(p, b)),
  541. CHECK(asdl_expr_seq*, _PyPegen_get_exprs(p, b)),
  542. EXTRA) }
  543. | bitwise_or
  544. compare_op_bitwise_or_pair[CmpopExprPair*]:
  545. | eq_bitwise_or
  546. | noteq_bitwise_or
  547. | lte_bitwise_or
  548. | lt_bitwise_or
  549. | gte_bitwise_or
  550. | gt_bitwise_or
  551. | notin_bitwise_or
  552. | in_bitwise_or
  553. | isnot_bitwise_or
  554. | is_bitwise_or
  555. eq_bitwise_or[CmpopExprPair*]: '==' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, Eq, a) }
  556. noteq_bitwise_or[CmpopExprPair*]:
  557. | (tok='!=' { _PyPegen_check_barry_as_flufl(p, tok) ? NULL : tok}) a=bitwise_or {_PyPegen_cmpop_expr_pair(p, NotEq, a) }
  558. lte_bitwise_or[CmpopExprPair*]: '<=' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, LtE, a) }
  559. lt_bitwise_or[CmpopExprPair*]: '<' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, Lt, a) }
  560. gte_bitwise_or[CmpopExprPair*]: '>=' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, GtE, a) }
  561. gt_bitwise_or[CmpopExprPair*]: '>' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, Gt, a) }
  562. notin_bitwise_or[CmpopExprPair*]: 'not' 'in' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, NotIn, a) }
  563. in_bitwise_or[CmpopExprPair*]: 'in' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, In, a) }
  564. isnot_bitwise_or[CmpopExprPair*]: 'is' 'not' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, IsNot, a) }
  565. is_bitwise_or[CmpopExprPair*]: 'is' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, Is, a) }
  566. bitwise_or[expr_ty]:
  567. | a=bitwise_or '|' b=bitwise_xor { _PyAST_BinOp(a, BitOr, b, EXTRA) }
  568. | bitwise_xor
  569. bitwise_xor[expr_ty]:
  570. | a=bitwise_xor '^' b=bitwise_and { _PyAST_BinOp(a, BitXor, b, EXTRA) }
  571. | bitwise_and
  572. bitwise_and[expr_ty]:
  573. | a=bitwise_and '&' b=shift_expr { _PyAST_BinOp(a, BitAnd, b, EXTRA) }
  574. | shift_expr
  575. shift_expr[expr_ty]:
  576. | a=shift_expr '<<' b=sum { _PyAST_BinOp(a, LShift, b, EXTRA) }
  577. | a=shift_expr '>>' b=sum { _PyAST_BinOp(a, RShift, b, EXTRA) }
  578. | sum
  579. sum[expr_ty]:
  580. | a=sum '+' b=term { _PyAST_BinOp(a, Add, b, EXTRA) }
  581. | a=sum '-' b=term { _PyAST_BinOp(a, Sub, b, EXTRA) }
  582. | term
  583. term[expr_ty]:
  584. | a=term '*' b=factor { _PyAST_BinOp(a, Mult, b, EXTRA) }
  585. | a=term '/' b=factor { _PyAST_BinOp(a, Div, b, EXTRA) }
  586. | a=term '//' b=factor { _PyAST_BinOp(a, FloorDiv, b, EXTRA) }
  587. | a=term '%' b=factor { _PyAST_BinOp(a, Mod, b, EXTRA) }
  588. | a=term '@' b=factor { CHECK_VERSION(expr_ty, 5, "The '@' operator is", _PyAST_BinOp(a, MatMult, b, EXTRA)) }
  589. | factor
  590. factor[expr_ty] (memo):
  591. | '+' a=factor { _PyAST_UnaryOp(UAdd, a, EXTRA) }
  592. | '-' a=factor { _PyAST_UnaryOp(USub, a, EXTRA) }
  593. | '~' a=factor { _PyAST_UnaryOp(Invert, a, EXTRA) }
  594. | power
  595. power[expr_ty]:
  596. | a=await_primary '**' b=factor { _PyAST_BinOp(a, Pow, b, EXTRA) }
  597. | await_primary
  598. await_primary[expr_ty] (memo):
  599. | AWAIT a=primary { CHECK_VERSION(expr_ty, 5, "Await expressions are", _PyAST_Await(a, EXTRA)) }
  600. | primary
  601. primary[expr_ty]:
  602. | a=primary '.' b=NAME { _PyAST_Attribute(a, b->v.Name.id, Load, EXTRA) }
  603. | a=primary b=genexp { _PyAST_Call(a, CHECK(asdl_expr_seq*, (asdl_expr_seq*)_PyPegen_singleton_seq(p, b)), NULL, EXTRA) }
  604. | a=primary '(' b=[arguments] ')' {
  605. _PyAST_Call(a,
  606. (b) ? ((expr_ty) b)->v.Call.args : NULL,
  607. (b) ? ((expr_ty) b)->v.Call.keywords : NULL,
  608. EXTRA) }
  609. | a=primary '[' b=slices ']' { _PyAST_Subscript(a, b, Load, EXTRA) }
  610. | atom
  611. slices[expr_ty]:
  612. | a=slice !',' { a }
  613. | a[asdl_expr_seq*]=','.slice+ [','] { _PyAST_Tuple(a, Load, EXTRA) }
  614. slice[expr_ty]:
  615. | a=[expression] ':' b=[expression] c=[':' d=[expression] { d }] { _PyAST_Slice(a, b, c, EXTRA) }
  616. | a=named_expression { a }
  617. atom[expr_ty]:
  618. | NAME
  619. | 'True' { _PyAST_Constant(Py_True, NULL, EXTRA) }
  620. | 'False' { _PyAST_Constant(Py_False, NULL, EXTRA) }
  621. | 'None' { _PyAST_Constant(Py_None, NULL, EXTRA) }
  622. | &STRING strings
  623. | NUMBER
  624. | &'(' (tuple | group | genexp)
  625. | &'[' (list | listcomp)
  626. | &'{' (dict | set | dictcomp | setcomp)
  627. | '...' { _PyAST_Constant(Py_Ellipsis, NULL, EXTRA) }
  628. strings[expr_ty] (memo): a=STRING+ { _PyPegen_concatenate_strings(p, a) }
  629. list[expr_ty]:
  630. | '[' a=[star_named_expressions] ']' { _PyAST_List(a, Load, EXTRA) }
  631. listcomp[expr_ty]:
  632. | '[' a=named_expression b=for_if_clauses ']' { _PyAST_ListComp(a, b, EXTRA) }
  633. | invalid_comprehension
  634. tuple[expr_ty]:
  635. | '(' a=[y=star_named_expression ',' z=[star_named_expressions] { _PyPegen_seq_insert_in_front(p, y, z) } ] ')' {
  636. _PyAST_Tuple(a, Load, EXTRA) }
  637. group[expr_ty]:
  638. | '(' a=(yield_expr | named_expression) ')' { a }
  639. | invalid_group
  640. genexp[expr_ty]:
  641. | '(' a=( assigment_expression | expression !':=') b=for_if_clauses ')' { _PyAST_GeneratorExp(a, b, EXTRA) }
  642. | invalid_comprehension
  643. set[expr_ty]: '{' a=star_named_expressions '}' { _PyAST_Set(a, EXTRA) }
  644. setcomp[expr_ty]:
  645. | '{' a=named_expression b=for_if_clauses '}' { _PyAST_SetComp(a, b, EXTRA) }
  646. | invalid_comprehension
  647. dict[expr_ty]:
  648. | '{' a=[double_starred_kvpairs] '}' {
  649. _PyAST_Dict(
  650. CHECK(asdl_expr_seq*, _PyPegen_get_keys(p, a)),
  651. CHECK(asdl_expr_seq*, _PyPegen_get_values(p, a)),
  652. EXTRA) }
  653. | '{' invalid_double_starred_kvpairs '}'
  654. dictcomp[expr_ty]:
  655. | '{' a=kvpair b=for_if_clauses '}' { _PyAST_DictComp(a->key, a->value, b, EXTRA) }
  656. | invalid_dict_comprehension
  657. double_starred_kvpairs[asdl_seq*]: a=','.double_starred_kvpair+ [','] { a }
  658. double_starred_kvpair[KeyValuePair*]:
  659. | '**' a=bitwise_or { _PyPegen_key_value_pair(p, NULL, a) }
  660. | kvpair
  661. kvpair[KeyValuePair*]: a=expression ':' b=expression { _PyPegen_key_value_pair(p, a, b) }
  662. for_if_clauses[asdl_comprehension_seq*]:
  663. | a[asdl_comprehension_seq*]=for_if_clause+ { a }
  664. for_if_clause[comprehension_ty]:
  665. | ASYNC 'for' a=star_targets 'in' ~ b=disjunction c[asdl_expr_seq*]=('if' z=disjunction { z })* {
  666. CHECK_VERSION(comprehension_ty, 6, "Async comprehensions are", _PyAST_comprehension(a, b, c, 1, p->arena)) }
  667. | 'for' a=star_targets 'in' ~ b=disjunction c[asdl_expr_seq*]=('if' z=disjunction { z })* {
  668. _PyAST_comprehension(a, b, c, 0, p->arena) }
  669. | invalid_for_target
  670. yield_expr[expr_ty]:
  671. | 'yield' 'from' a=expression { _PyAST_YieldFrom(a, EXTRA) }
  672. | 'yield' a=[star_expressions] { _PyAST_Yield(a, EXTRA) }
  673. arguments[expr_ty] (memo):
  674. | a=args [','] &')' { a }
  675. | invalid_arguments
  676. args[expr_ty]:
  677. | a[asdl_expr_seq*]=','.(starred_expression | ( assigment_expression | expression !':=') !'=')+ b=[',' k=kwargs {k}] {
  678. _PyPegen_collect_call_seqs(p, a, b, EXTRA) }
  679. | a=kwargs { _PyAST_Call(_PyPegen_dummy_name(p),
  680. CHECK_NULL_ALLOWED(asdl_expr_seq*, _PyPegen_seq_extract_starred_exprs(p, a)),
  681. CHECK_NULL_ALLOWED(asdl_keyword_seq*, _PyPegen_seq_delete_starred_exprs(p, a)),
  682. EXTRA) }
  683. kwargs[asdl_seq*]:
  684. | a=','.kwarg_or_starred+ ',' b=','.kwarg_or_double_starred+ { _PyPegen_join_sequences(p, a, b) }
  685. | ','.kwarg_or_starred+
  686. | ','.kwarg_or_double_starred+
  687. starred_expression[expr_ty]:
  688. | '*' a=expression { _PyAST_Starred(a, Load, EXTRA) }
  689. kwarg_or_starred[KeywordOrStarred*]:
  690. | invalid_kwarg
  691. | a=NAME '=' b=expression {
  692. _PyPegen_keyword_or_starred(p, CHECK(keyword_ty, _PyAST_keyword(a->v.Name.id, b, EXTRA)), 1) }
  693. | a=starred_expression { _PyPegen_keyword_or_starred(p, a, 0) }
  694. kwarg_or_double_starred[KeywordOrStarred*]:
  695. | invalid_kwarg
  696. | a=NAME '=' b=expression {
  697. _PyPegen_keyword_or_starred(p, CHECK(keyword_ty, _PyAST_keyword(a->v.Name.id, b, EXTRA)), 1) }
  698. | '**' a=expression { _PyPegen_keyword_or_starred(p, CHECK(keyword_ty, _PyAST_keyword(NULL, a, EXTRA)), 1) }
  699. # NOTE: star_targets may contain *bitwise_or, targets may not.
  700. star_targets[expr_ty]:
  701. | a=star_target !',' { a }
  702. | a=star_target b=(',' c=star_target { c })* [','] {
  703. _PyAST_Tuple(CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)), Store, EXTRA) }
  704. star_targets_list_seq[asdl_expr_seq*]: a[asdl_expr_seq*]=','.star_target+ [','] { a }
  705. star_targets_tuple_seq[asdl_expr_seq*]:
  706. | a=star_target b=(',' c=star_target { c })+ [','] { (asdl_expr_seq*) _PyPegen_seq_insert_in_front(p, a, b) }
  707. | a=star_target ',' { (asdl_expr_seq*) _PyPegen_singleton_seq(p, a) }
  708. star_target[expr_ty] (memo):
  709. | '*' a=(!'*' star_target) {
  710. _PyAST_Starred(CHECK(expr_ty, _PyPegen_set_expr_context(p, a, Store)), Store, EXTRA) }
  711. | target_with_star_atom
  712. target_with_star_atom[expr_ty] (memo):
  713. | a=t_primary '.' b=NAME !t_lookahead { _PyAST_Attribute(a, b->v.Name.id, Store, EXTRA) }
  714. | a=t_primary '[' b=slices ']' !t_lookahead { _PyAST_Subscript(a, b, Store, EXTRA) }
  715. | star_atom
  716. star_atom[expr_ty]:
  717. | a=NAME { _PyPegen_set_expr_context(p, a, Store) }
  718. | '(' a=target_with_star_atom ')' { _PyPegen_set_expr_context(p, a, Store) }
  719. | '(' a=[star_targets_tuple_seq] ')' { _PyAST_Tuple(a, Store, EXTRA) }
  720. | '[' a=[star_targets_list_seq] ']' { _PyAST_List(a, Store, EXTRA) }
  721. single_target[expr_ty]:
  722. | single_subscript_attribute_target
  723. | a=NAME { _PyPegen_set_expr_context(p, a, Store) }
  724. | '(' a=single_target ')' { a }
  725. single_subscript_attribute_target[expr_ty]:
  726. | a=t_primary '.' b=NAME !t_lookahead { _PyAST_Attribute(a, b->v.Name.id, Store, EXTRA) }
  727. | a=t_primary '[' b=slices ']' !t_lookahead { _PyAST_Subscript(a, b, Store, EXTRA) }
  728. del_targets[asdl_expr_seq*]: a[asdl_expr_seq*]=','.del_target+ [','] { a }
  729. del_target[expr_ty] (memo):
  730. | a=t_primary '.' b=NAME !t_lookahead { _PyAST_Attribute(a, b->v.Name.id, Del, EXTRA) }
  731. | a=t_primary '[' b=slices ']' !t_lookahead { _PyAST_Subscript(a, b, Del, EXTRA) }
  732. | del_t_atom
  733. del_t_atom[expr_ty]:
  734. | a=NAME { _PyPegen_set_expr_context(p, a, Del) }
  735. | '(' a=del_target ')' { _PyPegen_set_expr_context(p, a, Del) }
  736. | '(' a=[del_targets] ')' { _PyAST_Tuple(a, Del, EXTRA) }
  737. | '[' a=[del_targets] ']' { _PyAST_List(a, Del, EXTRA) }
  738. t_primary[expr_ty]:
  739. | a=t_primary '.' b=NAME &t_lookahead { _PyAST_Attribute(a, b->v.Name.id, Load, EXTRA) }
  740. | a=t_primary '[' b=slices ']' &t_lookahead { _PyAST_Subscript(a, b, Load, EXTRA) }
  741. | a=t_primary b=genexp &t_lookahead {
  742. _PyAST_Call(a, CHECK(asdl_expr_seq*, (asdl_expr_seq*)_PyPegen_singleton_seq(p, b)), NULL, EXTRA) }
  743. | a=t_primary '(' b=[arguments] ')' &t_lookahead {
  744. _PyAST_Call(a,
  745. (b) ? ((expr_ty) b)->v.Call.args : NULL,
  746. (b) ? ((expr_ty) b)->v.Call.keywords : NULL,
  747. EXTRA) }
  748. | a=atom &t_lookahead { a }
  749. t_lookahead: '(' | '[' | '.'
  750. # From here on, there are rules for invalid syntax with specialised error messages
  751. invalid_arguments:
  752. | a=args ',' '*' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "iterable argument unpacking follows keyword argument unpacking") }
  753. | a=expression b=for_if_clauses ',' [args | expression for_if_clauses] {
  754. RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, PyPegen_last_item(b, comprehension_ty)->target, "Generator expression must be parenthesized") }
  755. | a=NAME b='=' expression for_if_clauses {
  756. RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Maybe you meant '==' or ':=' instead of '='?")}
  757. | a=args for_if_clauses { _PyPegen_nonparen_genexp_in_call(p, a) }
  758. | args ',' a=expression b=for_if_clauses {
  759. RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, asdl_seq_GET(b, b->size-1)->target, "Generator expression must be parenthesized") }
  760. | a=args ',' args { _PyPegen_arguments_parsing_error(p, a) }
  761. invalid_kwarg:
  762. | a=NAME b='=' expression for_if_clauses {
  763. RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Maybe you meant '==' or ':=' instead of '='?")}
  764. | !(NAME '=') a=expression b='=' {
  765. RAISE_SYNTAX_ERROR_KNOWN_RANGE(
  766. a, b, "expression cannot contain assignment, perhaps you meant \"==\"?") }
  767. expression_without_invalid[expr_ty]:
  768. | a=disjunction 'if' b=disjunction 'else' c=expression { _PyAST_IfExp(b, a, c, EXTRA) }
  769. | disjunction
  770. | lambdef
  771. invalid_legacy_expression:
  772. | a=NAME b=expression_without_invalid {
  773. _PyPegen_check_legacy_stmt(p, a) ? RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "Missing parentheses in call to '%U'.", a->v.Name.id) : NULL}
  774. invalid_expression:
  775. | invalid_legacy_expression
  776. # !(NAME STRING) is not matched so we don't show this error with some invalid string prefixes like: kf"dsfsdf"
  777. # Soft keywords need to also be ignored because they can be parsed as NAME NAME
  778. | !(NAME STRING | SOFT_KEYWORD) a=disjunction b=expression_without_invalid {
  779. RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Perhaps you forgot a comma?") }
  780. invalid_named_expression:
  781. | a=expression ':=' expression {
  782. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
  783. a, "cannot use assignment expressions with %s", _PyPegen_get_expr_name(a)) }
  784. | a=NAME '=' b=bitwise_or !('='|':=') {
  785. p->in_raw_rule ? NULL : RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Maybe you meant '==' or ':=' instead of '='?") }
  786. | !(list|tuple|genexp|'True'|'None'|'False') a=bitwise_or b='=' bitwise_or !('='|':=') {
  787. p->in_raw_rule ? NULL : RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot assign to %s here. Maybe you meant '==' instead of '='?",
  788. _PyPegen_get_expr_name(a)) }
  789. invalid_assignment:
  790. | a=invalid_ann_assign_target ':' expression {
  791. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
  792. a,
  793. "only single target (not %s) can be annotated",
  794. _PyPegen_get_expr_name(a)
  795. )}
  796. | a=star_named_expression ',' star_named_expressions* ':' expression {
  797. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "only single target (not tuple) can be annotated") }
  798. | a=expression ':' expression {
  799. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "illegal target for annotation") }
  800. | (star_targets '=')* a=star_expressions '=' {
  801. RAISE_SYNTAX_ERROR_INVALID_TARGET(STAR_TARGETS, a) }
  802. | (star_targets '=')* a=yield_expr '=' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "assignment to yield expression not possible") }
  803. | a=star_expressions augassign (yield_expr | star_expressions) {
  804. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
  805. a,
  806. "'%s' is an illegal expression for augmented assignment",
  807. _PyPegen_get_expr_name(a)
  808. )}
  809. invalid_ann_assign_target[expr_ty]:
  810. | list
  811. | tuple
  812. | '(' a=invalid_ann_assign_target ')' { a }
  813. invalid_del_stmt:
  814. | 'del' a=star_expressions {
  815. RAISE_SYNTAX_ERROR_INVALID_TARGET(DEL_TARGETS, a) }
  816. invalid_block:
  817. | NEWLINE !INDENT { RAISE_INDENTATION_ERROR("expected an indented block") }
  818. invalid_comprehension:
  819. | ('[' | '(' | '{') a=starred_expression for_if_clauses {
  820. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "iterable unpacking cannot be used in comprehension") }
  821. | ('[' | '{') a=star_named_expression ',' b=star_named_expressions for_if_clauses {
  822. RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, PyPegen_last_item(b, expr_ty),
  823. "did you forget parentheses around the comprehension target?") }
  824. | ('[' | '{') a=star_named_expression b=',' for_if_clauses {
  825. RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "did you forget parentheses around the comprehension target?") }
  826. invalid_dict_comprehension:
  827. | '{' a='**' bitwise_or for_if_clauses '}' {
  828. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "dict unpacking cannot be used in dict comprehension") }
  829. invalid_parameters:
  830. | param_no_default* invalid_parameters_helper a=param_no_default {
  831. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "non-default argument follows default argument") }
  832. invalid_parameters_helper: # This is only there to avoid type errors
  833. | a=slash_with_default { _PyPegen_singleton_seq(p, a) }
  834. | param_with_default+
  835. invalid_lambda_parameters:
  836. | lambda_param_no_default* invalid_lambda_parameters_helper a=lambda_param_no_default {
  837. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "non-default argument follows default argument") }
  838. invalid_lambda_parameters_helper:
  839. | a=lambda_slash_with_default { _PyPegen_singleton_seq(p, a) }
  840. | lambda_param_with_default+
  841. invalid_star_etc:
  842. | a='*' (')' | ',' (')' | '**')) { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "named arguments must follow bare *") }
  843. | '*' ',' TYPE_COMMENT { RAISE_SYNTAX_ERROR("bare * has associated type comment") }
  844. invalid_lambda_star_etc:
  845. | '*' (':' | ',' (':' | '**')) { RAISE_SYNTAX_ERROR("named arguments must follow bare *") }
  846. invalid_double_type_comments:
  847. | TYPE_COMMENT NEWLINE TYPE_COMMENT NEWLINE INDENT {
  848. RAISE_SYNTAX_ERROR("Cannot have two type comments on def") }
  849. invalid_with_item:
  850. | expression 'as' a=expression &(',' | ')' | ':') {
  851. RAISE_SYNTAX_ERROR_INVALID_TARGET(STAR_TARGETS, a) }
  852. invalid_for_target:
  853. | ASYNC? 'for' a=star_expressions {
  854. RAISE_SYNTAX_ERROR_INVALID_TARGET(FOR_TARGETS, a) }
  855. invalid_group:
  856. | '(' a=starred_expression ')' {
  857. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot use starred expression here") }
  858. | '(' a='**' expression ')' {
  859. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot use double starred expression here") }
  860. invalid_import_from_targets:
  861. | import_from_as_names ',' {
  862. RAISE_SYNTAX_ERROR("trailing comma not allowed without surrounding parentheses") }
  863. invalid_with_stmt:
  864. | [ASYNC] 'with' ','.(expression ['as' star_target])+ &&':'
  865. | [ASYNC] 'with' '(' ','.(expressions ['as' star_target])+ ','? ')' &&':'
  866. invalid_with_stmt_indent:
  867. | [ASYNC] a='with' ','.(expression ['as' star_target])+ ':' NEWLINE !INDENT {
  868. RAISE_INDENTATION_ERROR("expected an indented block after 'with' statement on line %d", a->lineno) }
  869. | [ASYNC] a='with' '(' ','.(expressions ['as' star_target])+ ','? ')' ':' NEWLINE !INDENT {
  870. RAISE_INDENTATION_ERROR("expected an indented block after 'with' statement on line %d", a->lineno) }
  871. invalid_try_stmt:
  872. | a='try' ':' NEWLINE !INDENT {
  873. RAISE_INDENTATION_ERROR("expected an indented block after 'try' statement on line %d", a->lineno) }
  874. | 'try' ':' block !('except' | 'finally') { RAISE_SYNTAX_ERROR("expected 'except' or 'finally' block") }
  875. invalid_except_stmt:
  876. | 'except' a=expression ',' expressions ['as' NAME ] ':' {
  877. RAISE_SYNTAX_ERROR_STARTING_FROM(a, "multiple exception types must be parenthesized") }
  878. | a='except' expression ['as' NAME ] NEWLINE { RAISE_SYNTAX_ERROR("expected ':'") }
  879. | a='except' NEWLINE { RAISE_SYNTAX_ERROR("expected ':'") }
  880. invalid_finally_stmt:
  881. | a='finally' ':' NEWLINE !INDENT {
  882. RAISE_INDENTATION_ERROR("expected an indented block after 'finally' statement on line %d", a->lineno) }
  883. invalid_except_stmt_indent:
  884. | a='except' expression ['as' NAME ] ':' NEWLINE !INDENT {
  885. RAISE_INDENTATION_ERROR("expected an indented block after 'except' statement on line %d", a->lineno) }
  886. | a='except' ':' NEWLINE !INDENT { RAISE_SYNTAX_ERROR("expected an indented block after except statement on line %d", a->lineno) }
  887. invalid_match_stmt:
  888. | "match" subject_expr !':' { CHECK_VERSION(void*, 10, "Pattern matching is", RAISE_SYNTAX_ERROR("expected ':'") ) }
  889. | a="match" subject=subject_expr ':' NEWLINE !INDENT {
  890. RAISE_INDENTATION_ERROR("expected an indented block after 'match' statement on line %d", a->lineno) }
  891. invalid_case_block:
  892. | "case" patterns guard? !':' { RAISE_SYNTAX_ERROR("expected ':'") }
  893. | a="case" patterns guard? ':' NEWLINE !INDENT {
  894. RAISE_INDENTATION_ERROR("expected an indented block after 'case' statement on line %d", a->lineno) }
  895. invalid_as_pattern:
  896. | or_pattern 'as' a="_" { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot use '_' as a target") }
  897. | or_pattern 'as' !NAME a=expression { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "invalid pattern target") }
  898. invalid_class_pattern:
  899. | name_or_attr '(' a=invalid_class_argument_pattern { RAISE_SYNTAX_ERROR_KNOWN_RANGE(
  900. PyPegen_first_item(a, pattern_ty),
  901. PyPegen_last_item(a, pattern_ty),
  902. "positional patterns follow keyword patterns") }
  903. invalid_class_argument_pattern[asdl_pattern_seq*]:
  904. | [positional_patterns ','] keyword_patterns ',' a=positional_patterns { a }
  905. invalid_if_stmt:
  906. | 'if' named_expression NEWLINE { RAISE_SYNTAX_ERROR("expected ':'") }
  907. | a='if' a=named_expression ':' NEWLINE !INDENT {
  908. RAISE_INDENTATION_ERROR("expected an indented block after 'if' statement on line %d", a->lineno) }
  909. invalid_elif_stmt:
  910. | 'elif' named_expression NEWLINE { RAISE_SYNTAX_ERROR("expected ':'") }
  911. | a='elif' named_expression ':' NEWLINE !INDENT {
  912. RAISE_INDENTATION_ERROR("expected an indented block after 'elif' statement on line %d", a->lineno) }
  913. invalid_else_stmt:
  914. | a='else' ':' NEWLINE !INDENT {
  915. RAISE_INDENTATION_ERROR("expected an indented block after 'else' statement on line %d", a->lineno) }
  916. invalid_while_stmt:
  917. | 'while' named_expression NEWLINE { RAISE_SYNTAX_ERROR("expected ':'") }
  918. | a='while' named_expression ':' NEWLINE !INDENT {
  919. RAISE_INDENTATION_ERROR("expected an indented block after 'while' statement on line %d", a->lineno) }
  920. invalid_for_stmt:
  921. | [ASYNC] a='for' star_targets 'in' star_expressions ':' NEWLINE !INDENT {
  922. RAISE_INDENTATION_ERROR("expected an indented block after 'for' statement on line %d", a->lineno) }
  923. invalid_def_raw:
  924. | [ASYNC] a='def' NAME '(' [params] ')' ['->' expression] ':' NEWLINE !INDENT {
  925. RAISE_INDENTATION_ERROR("expected an indented block after function definition on line %d", a->lineno) }
  926. invalid_class_def_raw:
  927. | a='class' NAME ['('[arguments] ')'] ':' NEWLINE !INDENT {
  928. RAISE_INDENTATION_ERROR("expected an indented block after class definition on line %d", a->lineno) }
  929. invalid_double_starred_kvpairs:
  930. | ','.double_starred_kvpair+ ',' invalid_kvpair
  931. | expression ':' a='*' bitwise_or { RAISE_SYNTAX_ERROR_STARTING_FROM(a, "cannot use a starred expression in a dictionary value") }
  932. | expression a=':' &('}'|',') { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "expression expected after dictionary key and ':'") }
  933. invalid_kvpair:
  934. | a=expression !(':') {
  935. RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError, a->lineno, a->end_col_offset - 1, a->end_lineno, -1, "':' expected after dictionary key") }
  936. | expression ':' a='*' bitwise_or { RAISE_SYNTAX_ERROR_STARTING_FROM(a, "cannot use a starred expression in a dictionary value") }
  937. | expression a=':' {RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "expression expected after dictionary key and ':'") }