parse37base.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  1. # Copyright (c) 2016-2017, 2019-2020, 2022-2024 Rocky Bernstein
  2. """
  3. Python 3.7 base code. We keep non-custom-generated grammar rules out of this file.
  4. """
  5. from spark_parser import DEFAULT_DEBUG as PARSER_DEFAULT_DEBUG
  6. from spark_parser.spark import rule2str
  7. from uncompyle6.parser import ParserError, PythonParser, nop_func
  8. from uncompyle6.parsers.reducecheck import (
  9. and_invalid,
  10. ifelsestmt,
  11. iflaststmt,
  12. ifstmt,
  13. ifstmts_jump,
  14. or_check,
  15. testtrue,
  16. tryelsestmtl3,
  17. while1elsestmt,
  18. while1stmt,
  19. )
  20. from uncompyle6.parsers.treenode import SyntaxTree
  21. class Python37BaseParser(PythonParser):
  22. def __init__(self, debug_parser=PARSER_DEFAULT_DEBUG):
  23. self.added_rules = set()
  24. super(Python37BaseParser, self).__init__(
  25. SyntaxTree, "stmts", debug=debug_parser
  26. )
  27. self.new_rules = set()
  28. @staticmethod
  29. def call_fn_name(token):
  30. """Customize CALL_FUNCTION to add the number of positional arguments"""
  31. if token.attr is not None:
  32. return "%s_%i" % (token.kind, token.attr)
  33. else:
  34. return "%s_0" % (token.kind)
  35. def add_make_function_rule(self, rule, opname, attr, customize):
  36. """Python 3.3 added a an additional LOAD_STR before MAKE_FUNCTION and
  37. this has an effect on many rules.
  38. """
  39. new_rule = rule % "LOAD_STR "
  40. self.add_unique_rule(new_rule, opname, attr, customize)
  41. def custom_build_class_rule(self, opname, i, token, tokens, customize):
  42. """
  43. # Should the first rule be somehow folded into the 2nd one?
  44. build_class ::= LOAD_BUILD_CLASS mkfunc
  45. LOAD_CLASSNAME {expr}^n-1 CALL_FUNCTION_n
  46. LOAD_CONST CALL_FUNCTION_n
  47. build_class ::= LOAD_BUILD_CLASS mkfunc
  48. expr
  49. call
  50. CALL_FUNCTION_3
  51. """
  52. # FIXME: I bet this can be simplified
  53. # look for next MAKE_FUNCTION
  54. for i in range(i + 1, len(tokens)):
  55. if tokens[i].kind.startswith("MAKE_FUNCTION"):
  56. break
  57. elif tokens[i].kind.startswith("MAKE_CLOSURE"):
  58. break
  59. pass
  60. assert i < len(
  61. tokens
  62. ), "build_class needs to find MAKE_FUNCTION or MAKE_CLOSURE"
  63. assert (
  64. tokens[i + 1].kind == "LOAD_STR"
  65. ), "build_class expecting CONST after MAKE_FUNCTION/MAKE_CLOSURE"
  66. call_fn_tok = None
  67. for i in range(i, len(tokens)):
  68. if tokens[i].kind.startswith("CALL_FUNCTION"):
  69. call_fn_tok = tokens[i]
  70. break
  71. if not call_fn_tok:
  72. raise RuntimeError(
  73. "build_class custom rule for %s needs to find CALL_FUNCTION" % opname
  74. )
  75. # customize build_class rule
  76. # FIXME: What's the deal with the two rules? Different Python versions?
  77. # Different situations? Note that the above rule is based on the CALL_FUNCTION
  78. # token found, while this one doesn't.
  79. # 3.6+ handling
  80. call_function = call_fn_tok.kind
  81. if call_function.startswith("CALL_FUNCTION_KW"):
  82. self.addRule("classdef ::= build_class_kw store", nop_func)
  83. rule = "build_class_kw ::= LOAD_BUILD_CLASS mkfunc %sLOAD_CONST %s" % (
  84. "expr " * (call_fn_tok.attr - 1),
  85. call_function,
  86. )
  87. else:
  88. call_function = self.call_fn_name(call_fn_tok)
  89. rule = "build_class ::= LOAD_BUILD_CLASS mkfunc %s%s" % (
  90. "expr " * (call_fn_tok.attr - 1),
  91. call_function,
  92. )
  93. self.addRule(rule, nop_func)
  94. return
  95. # FIXME FIXME FIXME: The below is an utter mess. Come up with a better
  96. # organization for this. For example, arrange organize by opcode base?
  97. def customize_grammar_rules(self, tokens, customize):
  98. is_pypy = False
  99. # For a rough break out on the first word. This may
  100. # include instructions that don't need customization,
  101. # but we'll do a finer check after the rough breakout.
  102. customize_instruction_basenames = frozenset(
  103. (
  104. "BEFORE",
  105. "BUILD",
  106. "CALL",
  107. "CONTINUE",
  108. "DELETE",
  109. "FORMAT",
  110. "GET",
  111. "JUMP",
  112. "LOAD",
  113. "LOOKUP",
  114. "MAKE",
  115. "RETURN",
  116. "RAISE",
  117. "SETUP",
  118. "UNPACK",
  119. "WITH",
  120. )
  121. )
  122. # Opcode names in the custom_ops_processed set have rules that get added
  123. # unconditionally and the rules are constant. So they need to be done
  124. # only once and if we see the opcode a second we don't have to consider
  125. # adding more rules.
  126. #
  127. # Note: BUILD_TUPLE_UNPACK_WITH_CALL gets considered by
  128. # default because it starts with BUILD. So we'll set to ignore it from
  129. # the start.
  130. custom_ops_processed = {"BUILD_TUPLE_UNPACK_WITH_CALL"}
  131. # A set of instruction operation names that exist in the token stream.
  132. # We use this customize the grammar that we create.
  133. # 2.6-compatible set comprehensions
  134. self.seen_ops = frozenset([t.kind for t in tokens])
  135. self.seen_op_basenames = frozenset(
  136. [opname[: opname.rfind("_")] for opname in self.seen_ops]
  137. )
  138. # Loop over instructions adding custom grammar rules based on
  139. # a specific instruction seen.
  140. if "PyPy" in customize:
  141. is_pypy = True
  142. self.addRule(
  143. """
  144. stmt ::= assign3_pypy
  145. stmt ::= assign2_pypy
  146. assign3_pypy ::= expr expr expr store store store
  147. assign2_pypy ::= expr expr store store
  148. stmt ::= if_exp_lambda
  149. stmt ::= if_exp_not_lambda
  150. if_exp_lambda ::= expr jmp_false expr return_if_lambda
  151. return_expr_lambda LAMBDA_MARKER
  152. if_exp_not_lambda ::= expr jmp_true expr return_if_lambda
  153. return_expr_lambda LAMBDA_MARKER
  154. """,
  155. nop_func,
  156. )
  157. n = len(tokens)
  158. # Determine if we have an iteration CALL_FUNCTION_1.
  159. has_get_iter_call_function1 = False
  160. for i, token in enumerate(tokens):
  161. if (
  162. token == "GET_ITER"
  163. and i < n - 2
  164. and self.call_fn_name(tokens[i + 1]) == "CALL_FUNCTION_1"
  165. ):
  166. has_get_iter_call_function1 = True
  167. for i, token in enumerate(tokens):
  168. opname = token.kind
  169. # Do a quick breakout before testing potentially
  170. # each of the dozen or so instruction in if elif.
  171. if (
  172. opname[: opname.find("_")] not in customize_instruction_basenames
  173. or opname in custom_ops_processed
  174. ):
  175. continue
  176. opname_base = opname[: opname.rfind("_")]
  177. # The order of opname listed is roughly sorted below
  178. if opname == "LOAD_ASSERT" and "PyPy" in customize:
  179. rules_str = """
  180. stmt ::= JUMP_IF_NOT_DEBUG stmts COME_FROM
  181. """
  182. self.add_unique_doc_rules(rules_str, customize)
  183. elif opname == "BEFORE_ASYNC_WITH":
  184. rules_str = """
  185. stmt ::= async_with_stmt
  186. stmt ::= async_with_as_stmt
  187. """
  188. if self.version < (3, 8):
  189. rules_str += """
  190. stmt ::= async_with_stmt SETUP_ASYNC_WITH
  191. c_stmt ::= c_async_with_stmt SETUP_ASYNC_WITH
  192. async_with_stmt ::= expr
  193. async_with_pre
  194. POP_TOP
  195. suite_stmts_opt
  196. POP_BLOCK LOAD_CONST
  197. async_with_post
  198. c_async_with_stmt ::= expr
  199. async_with_pre
  200. POP_TOP
  201. c_suite_stmts_opt
  202. POP_BLOCK LOAD_CONST
  203. async_with_post
  204. async_with_stmt ::= expr
  205. async_with_pre
  206. POP_TOP
  207. suite_stmts_opt
  208. async_with_post
  209. c_async_with_stmt ::= expr
  210. async_with_pre
  211. POP_TOP
  212. c_suite_stmts_opt
  213. async_with_post
  214. async_with_as_stmt ::= expr
  215. async_with_pre
  216. store
  217. suite_stmts_opt
  218. POP_BLOCK LOAD_CONST
  219. async_with_post
  220. c_async_with_as_stmt ::= expr
  221. async_with_pre
  222. store
  223. c_suite_stmts_opt
  224. POP_BLOCK LOAD_CONST
  225. async_with_post
  226. async_with_as_stmt ::= expr
  227. async_with_pre
  228. store
  229. suite_stmts_opt
  230. async_with_post
  231. c_async_with_as_stmt ::= expr
  232. async_with_pre
  233. store
  234. suite_stmts_opt
  235. async_with_post
  236. """
  237. else:
  238. rules_str += """
  239. async_with_pre ::= BEFORE_ASYNC_WITH GET_AWAITABLE LOAD_CONST YIELD_FROM SETUP_ASYNC_WITH
  240. async_with_post ::= BEGIN_FINALLY COME_FROM_ASYNC_WITH
  241. WITH_CLEANUP_START GET_AWAITABLE LOAD_CONST YIELD_FROM
  242. WITH_CLEANUP_FINISH END_FINALLY
  243. async_with_stmt ::= expr
  244. async_with_pre
  245. POP_TOP
  246. suite_stmts
  247. POP_TOP POP_BLOCK
  248. async_with_post
  249. c_async_with_stmt ::= expr
  250. async_with_pre
  251. POP_TOP
  252. c_suite_stmts
  253. POP_TOP POP_BLOCK
  254. async_with_post
  255. async_with_stmt ::= expr
  256. async_with_pre
  257. POP_TOP
  258. suite_stmts
  259. POP_BLOCK
  260. BEGIN_FINALLY
  261. WITH_CLEANUP_START GET_AWAITABLE LOAD_CONST YIELD_FROM
  262. WITH_CLEANUP_FINISH POP_FINALLY LOAD_CONST RETURN_VALUE
  263. COME_FROM_ASYNC_WITH
  264. WITH_CLEANUP_START GET_AWAITABLE LOAD_CONST YIELD_FROM
  265. WITH_CLEANUP_FINISH END_FINALLY
  266. c_async_with_stmt ::= expr
  267. async_with_pre
  268. POP_TOP
  269. c_suite_stmts
  270. POP_BLOCK
  271. BEGIN_FINALLY
  272. WITH_CLEANUP_START GET_AWAITABLE LOAD_CONST YIELD_FROM
  273. WITH_CLEANUP_FINISH POP_FINALLY LOAD_CONST RETURN_VALUE
  274. COME_FROM_ASYNC_WITH
  275. WITH_CLEANUP_START GET_AWAITABLE LOAD_CONST YIELD_FROM
  276. WITH_CLEANUP_FINISH END_FINALLY
  277. async_with_as_stmt ::= expr
  278. async_with_pre
  279. store suite_stmts
  280. POP_TOP POP_BLOCK
  281. async_with_post
  282. c_async_with_as_stmt ::= expr
  283. async_with_pre
  284. store suite_stmts
  285. POP_TOP POP_BLOCK
  286. async_with_post
  287. async_with_as_stmt ::= expr
  288. async_with_pre
  289. store suite_stmts
  290. POP_BLOCK async_with_post
  291. c_async_with_as_stmt ::= expr
  292. async_with_pre
  293. store suite_stmts
  294. POP_BLOCK async_with_post
  295. """
  296. self.addRule(rules_str, nop_func)
  297. elif opname in ("BUILD_CONST_LIST", "BUILD_CONST_DICT", "BUILD_CONST_SET"):
  298. if opname == "BUILD_CONST_DICT":
  299. rule = f"""
  300. add_consts ::= ADD_VALUE*
  301. const_list ::= COLLECTION_START add_consts {opname}
  302. dict ::= const_list
  303. expr ::= dict
  304. """
  305. else:
  306. rule = f"""
  307. add_consts ::= ADD_VALUE*
  308. const_list ::= COLLECTION_START add_consts {opname}
  309. expr ::= const_list
  310. """
  311. self.addRule(rule, nop_func)
  312. elif opname_base == "BUILD_CONST_KEY_MAP":
  313. kvlist_n = "expr " * (token.attr)
  314. rule = "dict ::= %sLOAD_CONST %s" % (kvlist_n, opname)
  315. self.addRule(rule, nop_func)
  316. elif opname.startswith("BUILD_LIST_UNPACK"):
  317. v = token.attr
  318. rule = "build_list_unpack ::= %s%s" % ("expr " * v, opname)
  319. self.addRule(rule, nop_func)
  320. rule = "expr ::= build_list_unpack"
  321. self.addRule(rule, nop_func)
  322. elif opname_base in ("BUILD_MAP", "BUILD_MAP_UNPACK"):
  323. if opname == "BUILD_MAP_UNPACK":
  324. self.addRule(
  325. """
  326. expr ::= dict_unpack
  327. dict_unpack ::= dict_comp BUILD_MAP_UNPACK
  328. """,
  329. nop_func,
  330. )
  331. pass
  332. elif opname.startswith("BUILD_MAP_UNPACK_WITH_CALL"):
  333. v = token.attr
  334. rule = "build_map_unpack_with_call ::= %s%s" % ("expr " * v, opname)
  335. self.addRule(rule, nop_func)
  336. kvlist_n = "kvlist_%s" % token.attr
  337. if opname == "BUILD_MAP_n":
  338. # PyPy sometimes has no count. Sigh.
  339. rule = (
  340. "dict_comp_func ::= BUILD_MAP_n LOAD_ARG for_iter store "
  341. "comp_iter JUMP_BACK RETURN_VALUE RETURN_LAST"
  342. )
  343. self.add_unique_rule(rule, "dict_comp_func", 1, customize)
  344. kvlist_n = "kvlist_n"
  345. rule = "kvlist_n ::= kvlist_n kv3"
  346. self.add_unique_rule(rule, "kvlist_n", 0, customize)
  347. rule = "kvlist_n ::="
  348. self.add_unique_rule(rule, "kvlist_n", 1, customize)
  349. rule = "dict ::= BUILD_MAP_n kvlist_n"
  350. if not opname.startswith("BUILD_MAP_WITH_CALL"):
  351. # FIXME: Use the attr
  352. # so this doesn't run into exponential parsing time.
  353. if opname.startswith("BUILD_MAP_UNPACK"):
  354. # FIXME: start here. The LHS should be dict_unpack, not dict.
  355. # FIXME: really we need a combination of dict_entry-like things.
  356. # It just so happens the most common case is not to mix
  357. # dictionary comphensions with dictionary, elements
  358. if "LOAD_DICTCOMP" in self.seen_ops:
  359. rule = "dict ::= %s%s" % ("dict_comp " * token.attr, opname)
  360. self.addRule(rule, nop_func)
  361. rule = """
  362. expr ::= dict_unpack
  363. dict_unpack ::= %s%s
  364. """ % (
  365. "expr " * token.attr,
  366. opname,
  367. )
  368. else:
  369. rule = "%s ::= %s %s" % (
  370. kvlist_n,
  371. "expr " * (token.attr * 2),
  372. opname,
  373. )
  374. self.add_unique_rule(rule, opname, token.attr, customize)
  375. rule = "dict ::= %s" % kvlist_n
  376. self.add_unique_rule(rule, opname, token.attr, customize)
  377. elif opname.startswith("BUILD_MAP_UNPACK_WITH_CALL"):
  378. v = token.attr
  379. rule = "build_map_unpack_with_call ::= %s%s" % ("expr " * v, opname)
  380. self.addRule(rule, nop_func)
  381. elif opname.startswith("BUILD_TUPLE_UNPACK_WITH_CALL"):
  382. v = token.attr
  383. rule = (
  384. "build_tuple_unpack_with_call ::= "
  385. + "expr1024 " * int(v // 1024)
  386. + "expr32 " * int((v // 32) % 32)
  387. + "expr " * (v % 32)
  388. + opname
  389. )
  390. self.addRule(rule, nop_func)
  391. rule = "starred ::= %s %s" % ("expr " * v, opname)
  392. self.addRule(rule, nop_func)
  393. elif opname_base in (
  394. "BUILD_LIST",
  395. "BUILD_SET",
  396. "BUILD_TUPLE",
  397. "BUILD_TUPLE_UNPACK",
  398. ):
  399. collection_size = token.attr
  400. is_LOAD_CLOSURE = False
  401. if opname_base == "BUILD_TUPLE":
  402. # If is part of a "load_closure", then it is not part of a
  403. # "list".
  404. is_LOAD_CLOSURE = True
  405. for j in range(collection_size):
  406. if tokens[i - j - 1].kind != "LOAD_CLOSURE":
  407. is_LOAD_CLOSURE = False
  408. break
  409. if is_LOAD_CLOSURE:
  410. rule = "load_closure ::= %s%s" % (
  411. ("LOAD_CLOSURE " * collection_size),
  412. opname,
  413. )
  414. self.add_unique_rule(rule, opname, token.attr, customize)
  415. if not is_LOAD_CLOSURE or collection_size == 0:
  416. # We do this complicated test to speed up parsing of
  417. # pathelogically long literals, especially those over 1024.
  418. thousands = collection_size // 1024
  419. thirty32s = (collection_size // 32) % 32
  420. if thirty32s > 0:
  421. rule = "expr32 ::=%s" % (" expr" * 32)
  422. self.add_unique_rule(
  423. rule, opname_base, collection_size, customize
  424. )
  425. pass
  426. if thousands > 0:
  427. self.add_unique_rule(
  428. "expr1024 ::=%s" % (" expr32" * 32),
  429. opname_base,
  430. collection_size,
  431. customize,
  432. )
  433. pass
  434. collection = opname_base[opname_base.find("_") + 1 :].lower()
  435. rule = (
  436. ("%s ::= " % collection)
  437. + "expr1024 " * thousands
  438. + "expr32 " * thirty32s
  439. + "expr " * (collection_size % 32)
  440. + opname
  441. )
  442. self.add_unique_rules(["expr ::= %s" % collection, rule], customize)
  443. continue
  444. continue
  445. elif opname_base == "BUILD_SLICE":
  446. if token.attr == 2:
  447. self.add_unique_rules(
  448. [
  449. "expr ::= slice2",
  450. "slice2 ::= expr expr BUILD_SLICE_2",
  451. ],
  452. customize,
  453. )
  454. else:
  455. assert token.attr == 3, (
  456. "BUILD_SLICE value must be 2 or 3; is %s" % token.attr
  457. )
  458. self.add_unique_rules(
  459. [
  460. "expr ::= slice3",
  461. "slice3 ::= expr expr expr BUILD_SLICE_3",
  462. ],
  463. customize,
  464. )
  465. elif opname.startswith("BUILD_STRING"):
  466. v = token.attr
  467. rules_str = """
  468. expr ::= joined_str
  469. joined_str ::= %sBUILD_STRING_%d
  470. """ % (
  471. "expr " * v,
  472. v,
  473. )
  474. self.add_unique_doc_rules(rules_str, customize)
  475. if "FORMAT_VALUE_ATTR" in self.seen_ops:
  476. rules_str = """
  477. formatted_value_attr ::= expr expr FORMAT_VALUE_ATTR expr BUILD_STRING
  478. expr ::= formatted_value_attr
  479. """
  480. self.add_unique_doc_rules(rules_str, customize)
  481. elif opname in frozenset(
  482. (
  483. "CALL_FUNCTION",
  484. "CALL_FUNCTION_EX",
  485. "CALL_FUNCTION_EX_KW",
  486. "CALL_FUNCTION_VAR",
  487. "CALL_FUNCTION_VAR_KW",
  488. )
  489. ) or opname.startswith("CALL_FUNCTION_KW"):
  490. if opname == "CALL_FUNCTION" and token.attr == 1:
  491. rule = """
  492. expr ::= dict_comp
  493. dict_comp ::= LOAD_DICTCOMP LOAD_STR MAKE_FUNCTION_0 expr
  494. GET_ITER CALL_FUNCTION_1
  495. classdefdeco1 ::= expr classdefdeco2 CALL_FUNCTION_1
  496. classdefdeco1 ::= expr classdefdeco1 CALL_FUNCTION_1
  497. """
  498. self.addRule(rule, nop_func)
  499. self.custom_classfunc_rule(opname, token, customize, tokens[i + 1])
  500. # Note: don't add to custom_ops_processed.
  501. elif opname_base == "CALL_METHOD":
  502. # PyPy and Python 3.7+ only - DRY with parse2
  503. args_pos, args_kw = self.get_pos_kw(token)
  504. if opname == "CALL_METHOD_KW":
  505. args_kw = token.attr
  506. rules_str = """
  507. expr ::= call_kw_pypy37
  508. pypy_kw_keys ::= LOAD_CONST
  509. """
  510. self.add_unique_doc_rules(rules_str, customize)
  511. rule = (
  512. "call_kw_pypy37 ::= expr "
  513. + ("expr " * args_kw)
  514. + " pypy_kw_keys "
  515. + opname
  516. )
  517. else:
  518. args_pos, args_kw = self.get_pos_kw(token)
  519. # number of apply equiv arguments:
  520. nak = (len(opname_base) - len("CALL_METHOD")) // 3
  521. rule = (
  522. "call ::= expr "
  523. + ("pos_arg " * args_pos)
  524. + ("kwarg " * args_kw)
  525. + "expr " * nak
  526. + opname
  527. )
  528. self.add_unique_rule(rule, opname, token.attr, customize)
  529. elif opname == "CONTINUE":
  530. self.addRule("continue ::= CONTINUE", nop_func)
  531. custom_ops_processed.add(opname)
  532. elif opname == "CONTINUE_LOOP":
  533. self.addRule("continue ::= CONTINUE_LOOP", nop_func)
  534. custom_ops_processed.add(opname)
  535. elif opname == "DELETE_ATTR":
  536. self.addRule("delete ::= expr DELETE_ATTR", nop_func)
  537. custom_ops_processed.add(opname)
  538. elif opname == "DELETE_DEREF":
  539. self.addRule(
  540. """
  541. stmt ::= del_deref_stmt
  542. del_deref_stmt ::= DELETE_DEREF
  543. """,
  544. nop_func,
  545. )
  546. custom_ops_processed.add(opname)
  547. elif opname == "DELETE_SUBSCR":
  548. self.addRule(
  549. """
  550. delete ::= delete_subscript
  551. delete_subscript ::= expr expr DELETE_SUBSCR
  552. """,
  553. nop_func,
  554. )
  555. custom_ops_processed.add(opname)
  556. elif opname == "FORMAT_VALUE":
  557. rules_str = """
  558. expr ::= formatted_value1
  559. formatted_value1 ::= expr FORMAT_VALUE
  560. """
  561. self.add_unique_doc_rules(rules_str, customize)
  562. elif opname == "GET_ANEXT":
  563. self.addRule(
  564. """
  565. func_async_prefix ::= _come_froms SETUP_FINALLY GET_ANEXT LOAD_CONST YIELD_FROM POP_BLOCK
  566. func_async_middle ::= JUMP_FORWARD COME_FROM_EXCEPT
  567. DUP_TOP LOAD_GLOBAL COMPARE_OP POP_JUMP_IF_TRUE
  568. list_afor2 ::= func_async_prefix
  569. store list_iter
  570. JUMP_BACK COME_FROM_FINALLY
  571. END_ASYNC_FOR
  572. """,
  573. nop_func,
  574. )
  575. custom_ops_processed.add(opname)
  576. elif opname == "FORMAT_VALUE_ATTR":
  577. rules_str = """
  578. expr ::= formatted_value2
  579. formatted_value2 ::= expr expr FORMAT_VALUE_ATTR
  580. """
  581. self.add_unique_doc_rules(rules_str, customize)
  582. elif opname == "GET_ITER":
  583. self.addRule(
  584. """
  585. expr ::= get_iter
  586. get_iter ::= expr GET_ITER
  587. """,
  588. nop_func,
  589. )
  590. custom_ops_processed.add(opname)
  591. elif opname == "GET_AITER":
  592. self.addRule(
  593. """
  594. expr ::= generator_exp_async
  595. generator_exp_async ::= load_genexpr LOAD_STR MAKE_FUNCTION_0 expr
  596. GET_AITER CALL_FUNCTION_1
  597. stmt ::= genexpr_func_async
  598. func_async_prefix ::= _come_froms SETUP_EXCEPT GET_ANEXT LOAD_CONST YIELD_FROM
  599. func_async_middle ::= POP_BLOCK JUMP_FORWARD COME_FROM_EXCEPT
  600. DUP_TOP LOAD_GLOBAL COMPARE_OP POP_JUMP_IF_TRUE
  601. END_FINALLY COME_FROM
  602. genexpr_func_async ::= LOAD_ARG func_async_prefix
  603. store func_async_middle comp_iter
  604. JUMP_BACK COME_FROM
  605. POP_TOP POP_TOP POP_TOP POP_EXCEPT POP_TOP
  606. expr ::= list_comp_async
  607. list_comp_async ::= LOAD_LISTCOMP LOAD_STR MAKE_FUNCTION_0
  608. expr GET_AITER CALL_FUNCTION_1
  609. GET_AWAITABLE LOAD_CONST
  610. YIELD_FROM
  611. expr ::= list_comp_async
  612. list_afor2 ::= func_async_prefix
  613. store func_async_middle list_iter
  614. JUMP_BACK COME_FROM
  615. POP_TOP POP_TOP POP_TOP POP_EXCEPT POP_TOP
  616. list_comp_async ::= BUILD_LIST_0 LOAD_ARG list_afor2
  617. get_aiter ::= expr GET_AITER
  618. list_afor ::= get_aiter list_afor2
  619. list_iter ::= list_afor
  620. """,
  621. nop_func,
  622. )
  623. elif opname == "JUMP_IF_NOT_DEBUG":
  624. v = token.attr
  625. self.addRule(
  626. """
  627. stmt ::= assert_pypy
  628. stmt ::= assert2_pypy", nop_func)
  629. assert_pypy ::= JUMP_IF_NOT_DEBUG expr jmp_true
  630. LOAD_ASSERT RAISE_VARARGS_1 COME_FROM
  631. assert2_pypy ::= JUMP_IF_NOT_DEBUG assert_expr jmp_true
  632. LOAD_ASSERT expr CALL_FUNCTION_1
  633. RAISE_VARARGS_1 COME_FROM
  634. assert2_pypy ::= JUMP_IF_NOT_DEBUG expr jmp_true
  635. LOAD_ASSERT expr CALL_FUNCTION_1
  636. RAISE_VARARGS_1 COME_FROM,
  637. """,
  638. nop_func,
  639. )
  640. custom_ops_processed.add(opname)
  641. elif opname == "LOAD_BUILD_CLASS":
  642. self.custom_build_class_rule(opname, i, token, tokens, customize)
  643. # Note: don't add to custom_ops_processed.
  644. elif opname == "LOAD_CLASSDEREF":
  645. # Python 3.4+
  646. self.addRule("expr ::= LOAD_CLASSDEREF", nop_func)
  647. custom_ops_processed.add(opname)
  648. elif opname == "LOAD_CLASSNAME":
  649. self.addRule("expr ::= LOAD_CLASSNAME", nop_func)
  650. custom_ops_processed.add(opname)
  651. elif opname == "LOAD_DICTCOMP":
  652. if has_get_iter_call_function1:
  653. rule_pat = (
  654. "dict_comp ::= LOAD_DICTCOMP %sMAKE_FUNCTION_0 expr "
  655. "GET_ITER CALL_FUNCTION_1"
  656. )
  657. self.add_make_function_rule(rule_pat, opname, token.attr, customize)
  658. pass
  659. custom_ops_processed.add(opname)
  660. elif opname == "LOAD_ATTR":
  661. self.addRule(
  662. """
  663. expr ::= attribute
  664. attribute ::= expr LOAD_ATTR
  665. """,
  666. nop_func,
  667. )
  668. custom_ops_processed.add(opname)
  669. elif opname == "LOAD_LISTCOMP":
  670. self.add_unique_rule(
  671. "expr ::= list_comp", opname, token.attr, customize
  672. )
  673. custom_ops_processed.add(opname)
  674. elif opname == "LOAD_NAME":
  675. if (
  676. token.attr == "__annotations__"
  677. and "SETUP_ANNOTATIONS" in self.seen_ops
  678. ):
  679. token.kind = "LOAD_ANNOTATION"
  680. self.addRule(
  681. """
  682. stmt ::= SETUP_ANNOTATIONS
  683. stmt ::= ann_assign
  684. ann_assign ::= expr LOAD_ANNOTATION LOAD_STR STORE_SUBSCR
  685. """,
  686. nop_func,
  687. )
  688. pass
  689. elif opname == "LOAD_SETCOMP":
  690. # Should this be generalized and put under MAKE_FUNCTION?
  691. if has_get_iter_call_function1:
  692. self.addRule("expr ::= set_comp", nop_func)
  693. rule_pat = (
  694. "set_comp ::= LOAD_SETCOMP %sMAKE_FUNCTION_0 expr "
  695. "GET_ITER CALL_FUNCTION_1"
  696. )
  697. self.add_make_function_rule(rule_pat, opname, token.attr, customize)
  698. pass
  699. custom_ops_processed.add(opname)
  700. elif opname == "LOOKUP_METHOD":
  701. # A PyPy speciality - DRY with parse3
  702. self.addRule(
  703. """
  704. expr ::= attribute
  705. attribute ::= expr LOOKUP_METHOD
  706. """,
  707. nop_func,
  708. )
  709. custom_ops_processed.add(opname)
  710. elif opname.startswith("MAKE_CLOSURE"):
  711. # DRY with MAKE_FUNCTION
  712. # Note: this probably doesn't handle kwargs proprerly
  713. if opname == "MAKE_CLOSURE_0" and "LOAD_DICTCOMP" in self.seen_ops:
  714. # Is there something general going on here?
  715. # Note that 3.6+ doesn't do this, but we'll remove
  716. # this rule in parse36.py
  717. rule = """
  718. dict_comp ::= load_closure LOAD_DICTCOMP LOAD_STR
  719. MAKE_CLOSURE_0 expr
  720. GET_ITER CALL_FUNCTION_1
  721. """
  722. self.addRule(rule, nop_func)
  723. args_pos, args_kw, annotate_args = token.attr
  724. # FIXME: Fold test into add_make_function_rule
  725. j = 2
  726. if is_pypy or (i >= j and tokens[i - j] == "LOAD_LAMBDA"):
  727. rule_pat = "lambda_body ::= %sload_closure LOAD_LAMBDA %%s%s" % (
  728. "pos_arg " * args_pos,
  729. opname,
  730. )
  731. self.add_make_function_rule(rule_pat, opname, token.attr, customize)
  732. if has_get_iter_call_function1:
  733. rule_pat = (
  734. "generator_exp ::= %sload_closure load_genexpr %%s%s expr "
  735. "GET_ITER CALL_FUNCTION_1" % ("pos_arg " * args_pos, opname)
  736. )
  737. self.add_make_function_rule(rule_pat, opname, token.attr, customize)
  738. if has_get_iter_call_function1:
  739. if is_pypy or (i >= j and tokens[i - j] == "LOAD_LISTCOMP"):
  740. # In the tokens we saw:
  741. # LOAD_LISTCOMP LOAD_CONST MAKE_FUNCTION (>= 3.3) or
  742. # LOAD_LISTCOMP MAKE_FUNCTION (< 3.3) or
  743. # and have GET_ITER CALL_FUNCTION_1
  744. # Todo: For Pypy we need to modify this slightly
  745. rule_pat = (
  746. "list_comp ::= %sload_closure LOAD_LISTCOMP %%s%s expr "
  747. "GET_ITER CALL_FUNCTION_1"
  748. % ("pos_arg " * args_pos, opname)
  749. )
  750. self.add_make_function_rule(
  751. rule_pat, opname, token.attr, customize
  752. )
  753. if is_pypy or (i >= j and tokens[i - j] == "LOAD_SETCOMP"):
  754. rule_pat = (
  755. "set_comp ::= %sload_closure LOAD_SETCOMP %%s%s expr "
  756. "GET_ITER CALL_FUNCTION_1"
  757. % ("pos_arg " * args_pos, opname)
  758. )
  759. self.add_make_function_rule(
  760. rule_pat, opname, token.attr, customize
  761. )
  762. if is_pypy or (i >= j and tokens[i - j] == "LOAD_DICTCOMP"):
  763. self.add_unique_rule(
  764. "dict_comp ::= %sload_closure LOAD_DICTCOMP %s "
  765. "expr GET_ITER CALL_FUNCTION_1"
  766. % ("pos_arg " * args_pos, opname),
  767. opname,
  768. token.attr,
  769. customize,
  770. )
  771. if args_kw > 0:
  772. kwargs_str = "kwargs "
  773. else:
  774. kwargs_str = ""
  775. rule = "mkfunc ::= %s%s%s load_closure LOAD_CODE LOAD_STR %s" % (
  776. "expr " * args_pos,
  777. kwargs_str,
  778. "expr " * annotate_args,
  779. opname,
  780. )
  781. self.add_unique_rule(rule, opname, token.attr, customize)
  782. if args_kw == 0:
  783. rule = "mkfunc ::= %sload_closure load_genexpr %s" % (
  784. "pos_arg " * args_pos,
  785. opname,
  786. )
  787. self.add_unique_rule(rule, opname, token.attr, customize)
  788. pass
  789. elif opname_base.startswith("MAKE_FUNCTION"):
  790. args_pos, args_kw, annotate_args, closure = token.attr
  791. stack_count = args_pos + args_kw + annotate_args
  792. if closure:
  793. if args_pos:
  794. rule = "lambda_body ::= %s%s%s%s" % (
  795. "expr " * stack_count,
  796. "load_closure " * closure,
  797. "BUILD_TUPLE_1 LOAD_LAMBDA LOAD_STR ",
  798. opname,
  799. )
  800. else:
  801. rule = "lambda_body ::= %s%s%s" % (
  802. "load_closure " * closure,
  803. "LOAD_LAMBDA LOAD_STR ",
  804. opname,
  805. )
  806. self.add_unique_rule(rule, opname, token.attr, customize)
  807. else:
  808. rule = "lambda_body ::= %sLOAD_LAMBDA LOAD_STR %s" % (
  809. ("expr " * stack_count),
  810. opname,
  811. )
  812. self.add_unique_rule(rule, opname, token.attr, customize)
  813. rule = "mkfunc ::= %s%s%s%s" % (
  814. "expr " * stack_count,
  815. "load_closure " * closure,
  816. "LOAD_CODE LOAD_STR ",
  817. opname,
  818. )
  819. self.add_unique_rule(rule, opname, token.attr, customize)
  820. if has_get_iter_call_function1:
  821. rule_pat = (
  822. "generator_exp ::= %sload_genexpr %%s%s expr "
  823. "GET_ITER CALL_FUNCTION_1" % ("pos_arg " * args_pos, opname)
  824. )
  825. self.add_make_function_rule(rule_pat, opname, token.attr, customize)
  826. rule_pat = (
  827. "generator_exp ::= %sload_closure load_genexpr %%s%s expr "
  828. "GET_ITER CALL_FUNCTION_1" % ("pos_arg " * args_pos, opname)
  829. )
  830. self.add_make_function_rule(rule_pat, opname, token.attr, customize)
  831. if is_pypy or (i >= 2 and tokens[i - 2] == "LOAD_LISTCOMP"):
  832. # 3.6+ sometimes bundles all of the
  833. # 'exprs' in the rule above into a
  834. # tuple.
  835. rule_pat = (
  836. "list_comp ::= load_closure LOAD_LISTCOMP %%s%s "
  837. "expr GET_ITER CALL_FUNCTION_1" % (opname,)
  838. )
  839. self.add_make_function_rule(
  840. rule_pat, opname, token.attr, customize
  841. )
  842. rule_pat = (
  843. "list_comp ::= %sLOAD_LISTCOMP %%s%s expr "
  844. "GET_ITER CALL_FUNCTION_1" % ("expr " * args_pos, opname)
  845. )
  846. self.add_make_function_rule(
  847. rule_pat, opname, token.attr, customize
  848. )
  849. if is_pypy or (i >= 2 and tokens[i - 2] == "LOAD_LAMBDA"):
  850. rule_pat = "lambda_body ::= %s%sLOAD_LAMBDA %%s%s" % (
  851. ("pos_arg " * args_pos),
  852. ("kwarg " * args_kw),
  853. opname,
  854. )
  855. self.add_make_function_rule(rule_pat, opname, token.attr, customize)
  856. continue
  857. args_pos, args_kw, annotate_args, closure = token.attr
  858. j = 2
  859. if has_get_iter_call_function1:
  860. rule_pat = (
  861. "generator_exp ::= %sload_genexpr %%s%s expr "
  862. "GET_ITER CALL_FUNCTION_1" % ("pos_arg " * args_pos, opname)
  863. )
  864. self.add_make_function_rule(rule_pat, opname, token.attr, customize)
  865. if is_pypy or (i >= j and tokens[i - j] == "LOAD_LISTCOMP"):
  866. # In the tokens we saw:
  867. # LOAD_LISTCOMP LOAD_CONST MAKE_FUNCTION (>= 3.3) or
  868. # LOAD_LISTCOMP MAKE_FUNCTION (< 3.3) or
  869. # and have GET_ITER CALL_FUNCTION_1
  870. # Todo: For Pypy we need to modify this slightly
  871. rule_pat = (
  872. "list_comp ::= %sLOAD_LISTCOMP %%s%s expr "
  873. "GET_ITER CALL_FUNCTION_1" % ("expr " * args_pos, opname)
  874. )
  875. self.add_make_function_rule(
  876. rule_pat, opname, token.attr, customize
  877. )
  878. # FIXME: Fold test into add_make_function_rule
  879. if is_pypy or (i >= j and tokens[i - j] == "LOAD_LAMBDA"):
  880. rule_pat = "lambda_body ::= %s%sLOAD_LAMBDA %%s%s" % (
  881. ("pos_arg " * args_pos),
  882. ("kwarg " * args_kw),
  883. opname,
  884. )
  885. self.add_make_function_rule(rule_pat, opname, token.attr, customize)
  886. if args_kw == 0:
  887. kwargs = "no_kwargs"
  888. self.add_unique_rule("no_kwargs ::=", opname, token.attr, customize)
  889. else:
  890. kwargs = "kwargs"
  891. # positional args before keyword args
  892. rule = "mkfunc ::= %s%s %s%s" % (
  893. "pos_arg " * args_pos,
  894. kwargs,
  895. "LOAD_CODE LOAD_STR ",
  896. opname,
  897. )
  898. self.add_unique_rule(rule, opname, token.attr, customize)
  899. elif opname == "MAKE_FUNCTION_CLOSURE":
  900. if "LOAD_DICTCOMP" in self.seen_ops:
  901. # Is there something general going on here?
  902. rule = """
  903. dict_comp ::= load_closure LOAD_DICTCOMP LOAD_STR
  904. MAKE_FUNCTION_CLOSURE expr
  905. GET_ITER CALL_FUNCTION_1
  906. """
  907. self.addRule(rule, nop_func)
  908. elif "LOAD_SETCOMP" in self.seen_ops:
  909. rule = """
  910. set_comp ::= load_closure LOAD_SETCOMP LOAD_STR
  911. MAKE_FUNCTION_CLOSURE expr
  912. GET_ITER CALL_FUNCTION_1
  913. """
  914. self.addRule(rule, nop_func)
  915. elif opname == "RETURN_VALUE_LAMBDA":
  916. self.addRule(
  917. """
  918. return_expr_lambda ::= return_expr RETURN_VALUE_LAMBDA
  919. """,
  920. nop_func,
  921. )
  922. custom_ops_processed.add(opname)
  923. elif opname == "RAISE_VARARGS_0":
  924. self.addRule(
  925. """
  926. stmt ::= raise_stmt0
  927. raise_stmt0 ::= RAISE_VARARGS_0
  928. """,
  929. nop_func,
  930. )
  931. custom_ops_processed.add(opname)
  932. elif opname == "RAISE_VARARGS_1":
  933. self.addRule(
  934. """
  935. stmt ::= raise_stmt1
  936. raise_stmt1 ::= expr RAISE_VARARGS_1
  937. """,
  938. nop_func,
  939. )
  940. custom_ops_processed.add(opname)
  941. elif opname == "RAISE_VARARGS_2":
  942. self.addRule(
  943. """
  944. stmt ::= raise_stmt2
  945. raise_stmt2 ::= expr expr RAISE_VARARGS_2
  946. """,
  947. nop_func,
  948. )
  949. custom_ops_processed.add(opname)
  950. elif opname == "SETUP_EXCEPT":
  951. self.addRule(
  952. """
  953. try_except ::= SETUP_EXCEPT suite_stmts_opt POP_BLOCK
  954. except_handler opt_come_from_except
  955. tryelsestmt ::= SETUP_EXCEPT suite_stmts_opt POP_BLOCK
  956. except_handler else_suite come_from_except_clauses
  957. tryelsestmt ::= SETUP_EXCEPT suite_stmts_opt POP_BLOCK
  958. except_handler else_suite come_froms
  959. tryelsestmtl ::= SETUP_EXCEPT suite_stmts_opt POP_BLOCK
  960. except_handler else_suitel come_from_except_clauses
  961. stmt ::= tryelsestmtl3
  962. tryelsestmtl3 ::= SETUP_EXCEPT suite_stmts_opt POP_BLOCK
  963. except_handler COME_FROM else_suitel
  964. opt_come_from_except
  965. """,
  966. nop_func,
  967. )
  968. custom_ops_processed.add(opname)
  969. elif opname == "WITH_CLEANUP_START":
  970. rules_str = """
  971. stmt ::= with_null
  972. with_null ::= with_suffix
  973. with_suffix ::= WITH_CLEANUP_START WITH_CLEANUP_FINISH END_FINALLY
  974. """
  975. self.addRule(rules_str, nop_func)
  976. elif opname == "SETUP_WITH":
  977. rules_str = """
  978. stmt ::= with
  979. stmt ::= with_as
  980. with ::= expr
  981. SETUP_WITH POP_TOP
  982. suite_stmts_opt
  983. COME_FROM_WITH
  984. with_suffix
  985. with_as ::= expr SETUP_WITH store suite_stmts_opt COME_FROM_WITH
  986. with_suffix
  987. with ::= expr
  988. SETUP_WITH POP_TOP
  989. suite_stmts_opt
  990. POP_BLOCK LOAD_CONST COME_FROM_WITH
  991. with_suffix
  992. with_as ::= expr
  993. SETUP_WITH store suite_stmts_opt
  994. POP_BLOCK LOAD_CONST COME_FROM_WITH
  995. with_suffix
  996. with ::= expr
  997. SETUP_WITH POP_TOP suite_stmts_opt
  998. POP_BLOCK LOAD_CONST COME_FROM_WITH
  999. with_suffix
  1000. with_as ::= expr
  1001. SETUP_WITH store suite_stmts_opt
  1002. POP_BLOCK LOAD_CONST COME_FROM_WITH
  1003. with_suffix
  1004. """
  1005. if self.version < (3, 8):
  1006. rules_str += """
  1007. with ::= expr SETUP_WITH POP_TOP suite_stmts_opt POP_BLOCK
  1008. LOAD_CONST
  1009. with_suffix
  1010. """
  1011. else:
  1012. rules_str += """
  1013. with ::= expr
  1014. SETUP_WITH POP_TOP suite_stmts_opt
  1015. POP_BLOCK LOAD_CONST COME_FROM_WITH
  1016. with_suffix
  1017. with ::= expr SETUP_WITH POP_TOP suite_stmts_opt POP_BLOCK
  1018. BEGIN_FINALLY COME_FROM_WITH
  1019. with_suffix
  1020. with_as ::= expr
  1021. SETUP_WITH store suite_stmts_opt
  1022. POP_BLOCK LOAD_CONST COME_FROM_WITH
  1023. with_as ::= expr
  1024. SETUP_WITH store suite_stmts
  1025. POP_BLOCK BEGIN_FINALLY COME_FROM_WITH with_suffix
  1026. """
  1027. self.addRule(rules_str, nop_func)
  1028. elif opname_base in ("UNPACK_EX",):
  1029. before_count, after_count = token.attr
  1030. rule = (
  1031. "unpack ::= " + opname + " store" * (before_count + after_count + 1)
  1032. )
  1033. self.addRule(rule, nop_func)
  1034. elif opname_base in ("UNPACK_TUPLE", "UNPACK_SEQUENCE"):
  1035. rule = "unpack ::= " + opname + " store" * token.attr
  1036. self.addRule(rule, nop_func)
  1037. elif opname_base == "UNPACK_LIST":
  1038. rule = "unpack_list ::= " + opname + " store" * token.attr
  1039. self.addRule(rule, nop_func)
  1040. custom_ops_processed.add(opname)
  1041. pass
  1042. pass
  1043. self.reduce_check_table = {
  1044. "_ifstmts_jump": ifstmts_jump,
  1045. "and": and_invalid,
  1046. "ifelsestmt": ifelsestmt,
  1047. "ifelsestmtl": ifelsestmt,
  1048. "iflaststmt": iflaststmt,
  1049. "iflaststmtl": iflaststmt,
  1050. "ifstmt": ifstmt,
  1051. "ifstmtl": ifstmt,
  1052. "or": or_check,
  1053. "testtrue": testtrue,
  1054. "testfalsel": testtrue,
  1055. "while1elsestmt": while1elsestmt,
  1056. "while1stmt": while1stmt,
  1057. "try_elsestmtl38": tryelsestmtl3,
  1058. }
  1059. self.check_reduce["and"] = "AST"
  1060. self.check_reduce["annotate_tuple"] = "noAST"
  1061. self.check_reduce["aug_assign1"] = "AST"
  1062. self.check_reduce["aug_assign2"] = "AST"
  1063. self.check_reduce["while1stmt"] = "noAST"
  1064. self.check_reduce["while1elsestmt"] = "noAST"
  1065. self.check_reduce["_ifstmts_jump"] = "AST"
  1066. self.check_reduce["import_as37"] = "tokens"
  1067. self.check_reduce["import_from_as37"] = "tokens"
  1068. self.check_reduce["import_from_as37"] = "tokens"
  1069. self.check_reduce["ifelsestmt"] = "AST"
  1070. self.check_reduce["ifelsestmtl"] = "AST"
  1071. self.check_reduce["iflaststmt"] = "AST"
  1072. self.check_reduce["iflaststmtl"] = "AST"
  1073. self.check_reduce["ifstmt"] = "AST"
  1074. self.check_reduce["ifstmtl"] = "AST"
  1075. self.check_reduce["import_from37"] = "AST"
  1076. self.check_reduce["or"] = "AST"
  1077. self.check_reduce["testtrue"] = "tokens"
  1078. self.check_reduce["testfalsel"] = "tokens"
  1079. return
  1080. def custom_classfunc_rule(self, opname, token, customize, next_token):
  1081. """
  1082. call ::= expr {expr}^n CALL_FUNCTION_n
  1083. call ::= expr {expr}^n CALL_FUNCTION_VAR_n
  1084. call ::= expr {expr}^n CALL_FUNCTION_VAR_KW_n
  1085. call ::= expr {expr}^n CALL_FUNCTION_KW_n
  1086. classdefdeco2 ::= LOAD_BUILD_CLASS mkfunc {expr}^n-1 CALL_FUNCTION_n
  1087. """
  1088. args_pos, args_kw = self.get_pos_kw(token)
  1089. # Additional exprs for * and ** args:
  1090. # 0 if neither
  1091. # 1 for CALL_FUNCTION_VAR or CALL_FUNCTION_KW
  1092. # 2 for * and ** args (CALL_FUNCTION_VAR_KW).
  1093. # Yes, this computation based on instruction name is a little bit hoaky.
  1094. nak = (len(opname) - len("CALL_FUNCTION")) // 3
  1095. uniq_param = args_kw + args_pos
  1096. if frozenset(("GET_AWAITABLE", "YIELD_FROM")).issubset(self.seen_ops):
  1097. rule = (
  1098. "async_call ::= expr "
  1099. + ("pos_arg " * args_pos)
  1100. + ("kwarg " * args_kw)
  1101. + "expr " * nak
  1102. + token.kind
  1103. + " GET_AWAITABLE LOAD_CONST YIELD_FROM"
  1104. )
  1105. self.add_unique_rule(rule, token.kind, uniq_param, customize)
  1106. self.add_unique_rule(
  1107. "expr ::= async_call", token.kind, uniq_param, customize
  1108. )
  1109. if opname.startswith("CALL_FUNCTION_VAR"):
  1110. token.kind = self.call_fn_name(token)
  1111. if opname.endswith("KW"):
  1112. kw = "expr "
  1113. else:
  1114. kw = ""
  1115. rule = (
  1116. "call ::= expr expr "
  1117. + ("pos_arg " * args_pos)
  1118. + ("kwarg " * args_kw)
  1119. + kw
  1120. + token.kind
  1121. )
  1122. # Note: Semantic actions make use of whether or not "args_pos"
  1123. # is zero when creating a template rule.
  1124. self.add_unique_rule(rule, token.kind, args_pos, customize)
  1125. else:
  1126. token.kind = self.call_fn_name(token)
  1127. uniq_param = args_kw + args_pos
  1128. # Note: 3.5+ have subclassed this method; so we don't handle
  1129. # 'CALL_FUNCTION_VAR' or 'CALL_FUNCTION_EX' here.
  1130. rule = (
  1131. "call ::= expr "
  1132. + ("pos_arg " * args_pos)
  1133. + ("kwarg " * args_kw)
  1134. + "expr " * nak
  1135. + token.kind
  1136. )
  1137. self.add_unique_rule(rule, token.kind, uniq_param, customize)
  1138. if "LOAD_BUILD_CLASS" in self.seen_ops:
  1139. if (
  1140. next_token == "CALL_FUNCTION"
  1141. and next_token.attr == 1
  1142. and args_pos > 1
  1143. ):
  1144. rule = "classdefdeco2 ::= LOAD_BUILD_CLASS mkfunc %s%s_%d" % (
  1145. ("expr " * (args_pos - 1)),
  1146. opname,
  1147. args_pos,
  1148. )
  1149. self.add_unique_rule(rule, token.kind, uniq_param, customize)
  1150. def reduce_is_invalid(self, rule, ast, tokens, first, last):
  1151. lhs = rule[0]
  1152. n = len(tokens)
  1153. last = min(last, n - 1)
  1154. fn = self.reduce_check_table.get(lhs, None)
  1155. try:
  1156. if fn:
  1157. return fn(self, lhs, n, rule, ast, tokens, first, last)
  1158. except Exception:
  1159. import sys
  1160. import traceback
  1161. print(
  1162. f"Exception in {fn.__name__} {sys.exc_info()[1]}\n"
  1163. + f"rule: {rule2str(rule)}\n"
  1164. + f"offsets {tokens[first].offset} .. {tokens[last].offset}"
  1165. )
  1166. print(traceback.print_tb(sys.exc_info()[2], -1))
  1167. raise ParserError(tokens[last], tokens[last].off2int(), self.debug["rules"])
  1168. if lhs in ("aug_assign1", "aug_assign2") and ast[0][0] == "and":
  1169. return True
  1170. elif lhs == "annotate_tuple":
  1171. return not isinstance(tokens[first].attr, tuple)
  1172. elif lhs == "import_from37":
  1173. importlist37 = ast[3]
  1174. alias37 = importlist37[0]
  1175. if importlist37 == "importlist37" and alias37 == "alias37":
  1176. store = alias37[1]
  1177. assert store == "store"
  1178. return alias37[0].attr != store[0].attr
  1179. return False
  1180. elif lhs == "import_as37":
  1181. return tokens[first + 1].pattr is not None
  1182. elif lhs == "import_from_as37":
  1183. return tokens[first + 1].pattr is None
  1184. return False