customize36.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. # Copyright (c) 2019-2024 by Rocky Bernstein
  2. #
  3. # This program is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation, either version 3 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. """Isolate Python 3.6 version-specific semantic actions here.
  16. """
  17. from spark_parser.ast import GenericASTTraversalPruningException
  18. from xdis import iscode
  19. from uncompyle6.scanners.tok import Token
  20. from uncompyle6.semantics.consts import (
  21. INDENT_PER_LEVEL,
  22. PRECEDENCE,
  23. TABLE_DIRECT,
  24. TABLE_R,
  25. )
  26. from uncompyle6.semantics.helper import escape_string, flatten_list, strip_quotes
  27. from uncompyle6.util import get_code_name
  28. def escape_format(s):
  29. return s.replace("\r", "\\r").replace("\n", "\\n").replace("'''", '"""')
  30. #######################
  31. # Python 3.6+ Changes #
  32. #######################
  33. def customize_for_version36(self, version: tuple):
  34. # fmt: off
  35. PRECEDENCE["call_kw"] = 0
  36. PRECEDENCE["call_kw36"] = 1
  37. PRECEDENCE["call_ex"] = 1
  38. PRECEDENCE["call_ex_kw"] = 1
  39. PRECEDENCE["call_ex_kw2"] = 1
  40. PRECEDENCE["call_ex_kw3"] = 1
  41. PRECEDENCE["call_ex_kw4"] = 1
  42. PRECEDENCE["dict_pack"] = 0 # **{ ... }
  43. PRECEDENCE["formatted_value1"] = 100
  44. self.TABLE_DIRECT.update(
  45. {
  46. "ann_assign_init_value": (
  47. "%|%c = %p\n",
  48. (-1, "store_annotation"),
  49. (0, "expr", 200),
  50. ),
  51. "ann_assign_no_init": ("%|%c\n", (0, "store_annotation")),
  52. "async_for_stmt36": (
  53. "%|async for %c in %c:\n%+%c%-\n\n",
  54. (9, "store"),
  55. (1, "expr"),
  56. # Count from end, since COME_FROM shifts things in the forward direction
  57. (-9, ("for_block", "pass")),
  58. ),
  59. "async_forelse_stmt36": (
  60. "%|async for %c in %c:\n%+%c%-%|else:\n%+%c%-\n\n",
  61. (9, "store"),
  62. (1, "expr"),
  63. (-10, "for_block"),
  64. (-2, "else_suite"),
  65. ),
  66. "call_ex": ("%c(%p)", (0, "expr"), (1, 100)),
  67. "except_return": ("%|except:\n%+%c%-", 3),
  68. "func_args36": ("%c(**", 0),
  69. # This comes from 3.7. Eventually we will rebase from 3.7
  70. # and then this can go away
  71. "if_exp37": ("%p if %c else %c", (1, "expr", 27), 0, 3),
  72. "ifstmtl": ("%|if %c:\n%+%c%-",
  73. (0, "testexpr"), (1, "_ifstmts_jumpl")),
  74. "list_afor": (
  75. " async for %[1]{%c} in %c%[1]{%c}",
  76. (1, "store"), (0, "get_aiter"), (3, "list_iter"),
  77. ),
  78. "try_except36": ("%|try:\n%+%c%-%c\n\n", 1, -2),
  79. "tryfinally36": ("%|try:\n%+%c%-%|finally:\n%+%c%-\n\n", (1, "returns"), 3),
  80. "tryfinally_return_stmt": ("%|try:\n%+%c%-%|finally:\n%+%|return%-\n\n", 1),
  81. "unpack_list": ("*%c", (0, "list")),
  82. "store_annotation": ("%[1]{pattr}: %c", 0),
  83. }
  84. )
  85. self.TABLE_R.update(
  86. {
  87. "CALL_FUNCTION_EX": ("%c(*%P)", 0, (1, 2, ", ", 100)),
  88. # Not quite right
  89. "CALL_FUNCTION_EX_KW": ("%c(**%C)", 0, (2, 3, ",")),
  90. }
  91. )
  92. # fmt: on
  93. def build_unpack_tuple_with_call(node):
  94. n = node[0]
  95. if n == "expr":
  96. n = n[0]
  97. if n == "tuple":
  98. self.call36_tuple(n)
  99. first = 1
  100. sep = ", *"
  101. elif n == "LOAD_STR":
  102. value = self.format_pos_args(n)
  103. self.f.write(value)
  104. first = 1
  105. sep = ", *"
  106. else:
  107. first = 0
  108. sep = "*"
  109. buwc = node[-1]
  110. assert buwc.kind.startswith("BUILD_TUPLE_UNPACK_WITH_CALL")
  111. for n in node[first:-1]:
  112. self.f.write(sep)
  113. self.preorder(n)
  114. sep = ", *"
  115. pass
  116. self.prune()
  117. return
  118. self.n_build_tuple_unpack_with_call = build_unpack_tuple_with_call
  119. def build_unpack_map_with_call(node):
  120. n = node[0]
  121. if n == "expr":
  122. n = n[0]
  123. if n == "dict":
  124. self.call36_dict(n)
  125. first = 1
  126. sep = ", **"
  127. else:
  128. first = 0
  129. sep = "**"
  130. for n in node[first:-1]:
  131. self.f.write(sep)
  132. self.preorder(n)
  133. sep = ", **"
  134. pass
  135. self.prune()
  136. return
  137. self.n_build_map_unpack_with_call = build_unpack_map_with_call
  138. def n_classdef36(node):
  139. # class definition ('class X(A,B,C):')
  140. cclass = self.currentclass
  141. # Pick out various needed bits of information
  142. # * class_name - the name of the class
  143. # * subclass_info - the parameters to the class e.g.
  144. # class Foo(bar, baz)
  145. # ----------
  146. # * subclass_code - the code for the subclass body
  147. subclass_info = None
  148. if node == "classdefdeco2":
  149. if isinstance(node[1][1].attr, str):
  150. class_name = node[1][1].attr
  151. if self.is_pypy and class_name.find("<locals>") > 0:
  152. class_name = class_name.split(".")[-1]
  153. else:
  154. class_name = node[1][2].attr
  155. build_class = node
  156. else:
  157. build_class = node[0]
  158. if build_class == "build_class_kw":
  159. mkfunc = build_class[1]
  160. assert mkfunc == "mkfunc"
  161. subclass_info = build_class
  162. if hasattr(mkfunc[0], "attr") and iscode(mkfunc[0].attr):
  163. subclass_code = mkfunc[0].attr
  164. else:
  165. assert mkfunc[0] == "load_closure"
  166. subclass_code = mkfunc[1].attr
  167. assert iscode(subclass_code)
  168. if build_class[1][0] == "load_closure":
  169. code_node = build_class[1][1]
  170. else:
  171. code_node = build_class[1][0]
  172. class_name = get_code_name(code_node.attr)
  173. assert "mkfunc" == build_class[1]
  174. mkfunc = build_class[1]
  175. if mkfunc[0] in ("kwargs", "no_kwargs"):
  176. for n in mkfunc:
  177. if hasattr(n, "attr") and iscode(n.attr):
  178. subclass_code = n.attr
  179. break
  180. pass
  181. if node == "classdefdeco2":
  182. subclass_info = node
  183. else:
  184. subclass_info = node[0]
  185. elif build_class[1][0] == "load_closure":
  186. # Python 3 with closures not functions
  187. load_closure = build_class[1]
  188. subclass_code = None
  189. for i in range(-4, -1):
  190. if load_closure[i] == "LOAD_CODE":
  191. subclass_code = load_closure[i].attr
  192. break
  193. if subclass_code is None:
  194. raise RuntimeError(
  195. "Internal Error n_classdef: cannot find " "class body"
  196. )
  197. if hasattr(build_class[3], "__len__"):
  198. if not subclass_info:
  199. subclass_info = build_class[3]
  200. elif hasattr(build_class[2], "__len__"):
  201. subclass_info = build_class[2]
  202. else:
  203. raise RuntimeError(
  204. "Internal Error n_classdef: cannot " "superclass name"
  205. )
  206. elif node == "classdefdeco2":
  207. subclass_info = node
  208. subclass_code = build_class[1][0].attr
  209. elif not subclass_info:
  210. if mkfunc[0] in ("no_kwargs", "kwargs"):
  211. subclass_code = mkfunc[1].attr
  212. else:
  213. subclass_code = mkfunc[0].attr
  214. if node == "classdefdeco2":
  215. subclass_info = node
  216. else:
  217. subclass_info = node[0]
  218. if node == "classdefdeco2":
  219. self.write("\n")
  220. else:
  221. self.write("\n\n")
  222. self.currentclass = str(class_name)
  223. self.write(self.indent, "class ", self.currentclass)
  224. self.print_super_classes3(subclass_info)
  225. self.println(":")
  226. # class body
  227. self.indent_more()
  228. self.build_class(subclass_code)
  229. self.indent_less()
  230. self.currentclass = cclass
  231. if len(self.param_stack) > 1:
  232. self.write("\n\n")
  233. else:
  234. self.write("\n\n\n")
  235. self.prune()
  236. self.n_classdef36 = n_classdef36
  237. def call_ex_kw(node):
  238. """Handle CALL_FUNCTION_EX 1 (have KW) but with
  239. BUILD_MAP_UNPACK_WITH_CALL"""
  240. expr = node[1]
  241. assert expr == "expr"
  242. value = self.format_pos_args(expr)
  243. if value == "":
  244. fmt = "%c(%p)"
  245. else:
  246. fmt = "%c" + ("(%s, " % value).replace("%", "%%") + "%p)"
  247. self.template_engine(
  248. (fmt, (0, "expr"), (2, "build_map_unpack_with_call", 100)), node
  249. )
  250. self.prune()
  251. self.n_call_ex_kw = call_ex_kw
  252. def call_ex_kw2(node):
  253. """Handle CALL_FUNCTION_EX 2 (have KW) but with
  254. BUILD_{MAP,TUPLE}_UNPACK_WITH_CALL"""
  255. assert node[1] == "build_tuple_unpack_with_call"
  256. value = self.format_pos_args(node[1])
  257. if value == "":
  258. fmt = "%c(%p)"
  259. else:
  260. fmt = "%c" + ("(%s, " % value).replace("%", "%%") + "%p)"
  261. self.template_engine(
  262. (fmt, (0, "expr"), (2, "build_map_unpack_with_call", 100)), node
  263. )
  264. self.prune()
  265. self.n_call_ex_kw2 = call_ex_kw2
  266. def call_ex_kw3(node):
  267. """Handle CALL_FUNCTION_EX 1 (have KW) but without
  268. BUILD_MAP_UNPACK_WITH_CALL"""
  269. self.preorder(node[0])
  270. self.write("(")
  271. value = self.format_pos_args(node[1][0])
  272. if value == "":
  273. pass
  274. else:
  275. self.write(value)
  276. self.write(", ")
  277. self.write("*")
  278. self.preorder(node[1][1])
  279. self.write(", ")
  280. kwargs = node[2]
  281. if kwargs == "expr" and kwargs[0] != "dict":
  282. kwargs = kwargs[0]
  283. if kwargs == "dict":
  284. self.call36_dict(kwargs)
  285. else:
  286. self.write("**")
  287. self.preorder(kwargs)
  288. self.write(")")
  289. self.prune()
  290. self.n_call_ex_kw3 = call_ex_kw3
  291. def call_ex_kw4(node):
  292. """Handle CALL_FUNCTION_EX {1 or 2} but without
  293. BUILD_{MAP,TUPLE}_UNPACK_WITH_CALL"""
  294. self.preorder(node[0])
  295. self.write("(")
  296. args = node[1][0]
  297. if args == "tuple":
  298. if self.call36_tuple(args) > 0:
  299. self.write(", ")
  300. pass
  301. pass
  302. else:
  303. self.write("*")
  304. self.preorder(args)
  305. self.write(", ")
  306. pass
  307. kwargs = node[2]
  308. if kwargs == "expr":
  309. kwargs = kwargs[0]
  310. call_function_ex = node[-1]
  311. assert call_function_ex == "CALL_FUNCTION_EX_KW" or (
  312. self.version >= (3, 6) and call_function_ex == "CALL_FUNCTION_EX"
  313. )
  314. # FIXME: decide if the below test be on kwargs == 'dict'
  315. if (
  316. call_function_ex.attr & 1
  317. and (not isinstance(kwargs, Token) and kwargs != "attribute")
  318. and kwargs != "call_kw36"
  319. and not kwargs[0].kind.startswith("kvlist")
  320. ):
  321. self.call36_dict(kwargs)
  322. else:
  323. self.write("**")
  324. self.preorder(kwargs)
  325. self.write(")")
  326. self.prune()
  327. self.n_call_ex_kw4 = call_ex_kw4
  328. def format_pos_args(node):
  329. """
  330. Positional args should format to:
  331. (*(2, ), ...) -> (2, ...)
  332. We remove starting and trailing parenthesis and ', ' if
  333. tuple has only one element.
  334. """
  335. value = self.traverse(node, indent="")
  336. if value.startswith("("):
  337. assert value.endswith(")")
  338. value = value[1:-1].rstrip(
  339. " "
  340. ) # Remove starting '(' and trailing ')' and additional spaces
  341. if value == "":
  342. pass # args is empty
  343. else:
  344. if value.endswith(","): # if args has only one item
  345. value = value[:-1]
  346. return value
  347. self.format_pos_args = format_pos_args
  348. def call36_tuple(node):
  349. """
  350. A tuple used in a call; these are like normal tuples, but they
  351. don't have the enclosing parenthesis.
  352. """
  353. assert node == "tuple"
  354. # Note: don't iterate over last element which is a
  355. # BUILD_TUPLE...
  356. flat_elems = flatten_list(node[:-1])
  357. self.indent_more(INDENT_PER_LEVEL)
  358. sep = ""
  359. for elem in flat_elems:
  360. if elem in ("ROT_THREE", "EXTENDED_ARG"):
  361. continue
  362. assert elem == "expr"
  363. line_number = self.line_number
  364. value = self.traverse(elem)
  365. if line_number != self.line_number:
  366. sep += "\n" + self.indent + INDENT_PER_LEVEL[:-1]
  367. self.write(sep, value)
  368. sep = ", "
  369. self.indent_less(INDENT_PER_LEVEL)
  370. return len(flat_elems)
  371. self.call36_tuple = call36_tuple
  372. def call36_dict(node):
  373. """
  374. A dict used in a call_ex_kw2, which are a dictionary items expressed
  375. in a call. This should format to:
  376. a=1, b=2
  377. In other words, no braces, no quotes around keys and ":" becomes
  378. "=".
  379. We will source-code use line breaks to guide us when to break.
  380. """
  381. p = self.prec
  382. self.prec = 100
  383. self.indent_more(INDENT_PER_LEVEL)
  384. sep = INDENT_PER_LEVEL[:-1]
  385. line_number = self.line_number
  386. if node[0].kind.startswith("kvlist"):
  387. # Python 3.5+ style key/value list in dict
  388. kv_node = node[0]
  389. l = list(kv_node)
  390. i = 0
  391. length = len(l)
  392. # FIXME: Parser-speed improved grammars will have BUILD_MAP
  393. # at the end. So in the future when everything is
  394. # complete, we can do an "assert" instead of "if".
  395. if kv_node[-1].kind.startswith("BUILD_MAP"):
  396. length -= 1
  397. # Respect line breaks from source
  398. while i < length:
  399. self.write(sep)
  400. name = self.traverse(l[i], indent="")
  401. # Strip off beginning and trailing quotes in name
  402. name = name[1:-1]
  403. if i > 0:
  404. line_number = self.indent_if_source_nl(
  405. line_number, self.indent + INDENT_PER_LEVEL[:-1]
  406. )
  407. line_number = self.line_number
  408. self.write(name, "=")
  409. value = self.traverse(
  410. l[i + 1], indent=self.indent + (len(name) + 2) * " "
  411. )
  412. self.write(value)
  413. sep = ", "
  414. if line_number != self.line_number:
  415. sep += "\n" + self.indent + INDENT_PER_LEVEL[:-1]
  416. line_number = self.line_number
  417. i += 2
  418. pass
  419. elif node[-1].kind.startswith("BUILD_CONST_KEY_MAP"):
  420. keys_node = node[-2]
  421. keys = keys_node.attr
  422. # from trepan.api import debug; debug()
  423. assert keys_node == "LOAD_CONST" and isinstance(keys, tuple)
  424. for i in range(node[-1].attr):
  425. self.write(sep)
  426. self.write(keys[i], "=")
  427. value = self.traverse(node[i], indent="")
  428. self.write(value)
  429. sep = ", "
  430. if line_number != self.line_number:
  431. sep += "\n" + self.indent + INDENT_PER_LEVEL[:-1]
  432. line_number = self.line_number
  433. pass
  434. pass
  435. else:
  436. self.write("**")
  437. try:
  438. self.default(node)
  439. except GenericASTTraversalPruningException:
  440. pass
  441. self.prec = p
  442. self.indent_less(INDENT_PER_LEVEL)
  443. return
  444. self.call36_dict = call36_dict
  445. def n_call_kw36(node):
  446. self.template_engine(("%p(", (0, 100)), node)
  447. keys = node[-2].attr
  448. num_kwargs = len(keys)
  449. num_posargs = len(node) - (num_kwargs + 2)
  450. n = len(node)
  451. assert n >= len(keys) + 1, "not enough parameters keyword-tuple values"
  452. sep = ""
  453. line_number = self.line_number
  454. for i in range(1, num_posargs):
  455. self.write(sep)
  456. self.preorder(node[i])
  457. if line_number != self.line_number:
  458. sep = ",\n" + self.indent + " "
  459. else:
  460. sep = ", "
  461. line_number = self.line_number
  462. i = num_posargs
  463. j = 0
  464. # FIXME: adjust output for line breaks?
  465. while i < n - 2:
  466. self.write(sep)
  467. self.write(keys[j] + "=")
  468. self.preorder(node[i])
  469. if line_number != self.line_number:
  470. sep = ",\n" + self.indent + " "
  471. else:
  472. sep = ", "
  473. i += 1
  474. j += 1
  475. self.write(")")
  476. self.prune()
  477. return
  478. self.n_call_kw36 = n_call_kw36
  479. FSTRING_CONVERSION_MAP = {1: "!s", 2: "!r", 3: "!a", "X": ":X"}
  480. def n_except_suite_finalize(node):
  481. if node[1] == "returns" and self.hide_internal:
  482. # Process node[1] only.
  483. # The code after "returns", e.g. node[3], is dead code.
  484. # Adding it is wrong as it dedents and another
  485. # exception handler "except_stmt" afterwards.
  486. # Note it is also possible that the grammar is wrong here.
  487. # and this should not be "except_stmt".
  488. self.indent_more()
  489. self.preorder(node[1])
  490. self.indent_less()
  491. else:
  492. self.default(node)
  493. self.prune()
  494. self.n_except_suite_finalize = n_except_suite_finalize
  495. def n_formatted_value(node):
  496. if node[0] in ("LOAD_STR", "LOAD_CONST"):
  497. value = node[0].attr
  498. if isinstance(value, tuple):
  499. self.write(node[0].attr)
  500. else:
  501. self.write(escape_string(node[0].attr))
  502. self.prune()
  503. else:
  504. self.default(node)
  505. self.n_formatted_value = n_formatted_value
  506. def n_formatted_value_attr(node):
  507. f_conversion(node)
  508. fmt_node = node.data[3]
  509. if fmt_node == "expr" and fmt_node[0] == "LOAD_STR":
  510. node.string = escape_format(fmt_node[0].attr)
  511. else:
  512. node.string = fmt_node
  513. self.default(node)
  514. self.n_formatted_value_attr = n_formatted_value_attr
  515. def f_conversion(node):
  516. fmt_node = node.data[1]
  517. if fmt_node == "expr" and fmt_node[0] == "LOAD_STR":
  518. data = fmt_node[0].attr
  519. else:
  520. data = fmt_node.attr
  521. node.conversion = FSTRING_CONVERSION_MAP.get(data, "")
  522. return node.conversion
  523. def n_formatted_value1(node):
  524. expr = node[0]
  525. assert expr == "expr"
  526. conversion = f_conversion(node)
  527. if self.in_format_string and self.in_format_string != "formatted_value1":
  528. value = self.traverse(expr, indent="")
  529. if value[0] == "{":
  530. # If we have a set or dictionary comprehension, then we need to add a space
  531. # so as not to confuse the format string with {{.
  532. fmt = "{ %s%s }"
  533. else:
  534. fmt = "{%s%s}"
  535. es = escape_string(fmt % (value, conversion))
  536. f_str = "%s" % es
  537. else:
  538. old_in_format_string = self.in_format_string
  539. self.in_format_string = "formatted_value1"
  540. value = self.traverse(expr, indent="")
  541. self.in_format_string = old_in_format_string
  542. es = escape_string("{%s%s}" % (value, conversion))
  543. f_str = "f%s" % es
  544. self.write(f_str)
  545. self.prune()
  546. self.n_formatted_value1 = n_formatted_value1
  547. def n_formatted_value2(node):
  548. p = self.prec
  549. self.prec = 100
  550. expr = node[0]
  551. assert expr == "expr"
  552. old_in_format_string = self.in_format_string
  553. self.in_format_string = "formatted_value2"
  554. value = self.traverse(expr, indent="")
  555. format_value_attr = node[-1]
  556. assert format_value_attr == "FORMAT_VALUE_ATTR"
  557. attr = format_value_attr.attr
  558. if attr & 4:
  559. assert node[1] == "expr"
  560. fmt = strip_quotes(self.traverse(node[1], indent=""))
  561. attr_flags = attr & 3
  562. if attr_flags:
  563. conversion = "%s:%s" % (FSTRING_CONVERSION_MAP.get(attr_flags, ""), fmt)
  564. else:
  565. conversion = ":%s" % fmt
  566. else:
  567. conversion = FSTRING_CONVERSION_MAP.get(attr, "")
  568. self.in_format_string = old_in_format_string
  569. f_str = "f%s" % escape_string("{%s%s}" % (value, conversion))
  570. self.write(f_str)
  571. self.prec = p
  572. self.prune()
  573. self.n_formatted_value2 = n_formatted_value2
  574. def n_joined_str(node):
  575. p = self.prec
  576. self.prec = 100
  577. old_in_format_string = self.in_format_string
  578. self.in_format_string = "joined_str"
  579. result = ""
  580. for expr in node[:-1]:
  581. assert expr == "expr"
  582. value = self.traverse(expr, indent="")
  583. if expr[0].kind.startswith("formatted_value"):
  584. # remove leading 'f'
  585. if value.startswith("f"):
  586. value = value[1:]
  587. pass
  588. else:
  589. # {{ and }} in Python source-code format strings mean
  590. # { and } respectively. But only when *not* part of a
  591. # formatted value. However, in the LOAD_STR
  592. # bytecode, the escaping of the braces has been
  593. # removed. So we need to put back the braces escaping in
  594. # reconstructing the source.
  595. assert (
  596. expr[0] == "LOAD_STR"
  597. or expr[0] == "LOAD_CONST"
  598. and isinstance(expr[0].attr, unicode)
  599. )
  600. value = value.replace("{", "{{").replace("}", "}}")
  601. # Remove leading quotes
  602. result += strip_quotes(value)
  603. pass
  604. self.in_format_string = old_in_format_string
  605. if self.in_format_string:
  606. self.write(result)
  607. else:
  608. self.write("f%s" % escape_string(result))
  609. self.prec = p
  610. self.prune()
  611. self.n_joined_str = n_joined_str
  612. def n_list_comp_async(node):
  613. self.write("[")
  614. if node[0].kind == "load_closure":
  615. self.listcomp_closure3(node)
  616. else:
  617. self.comprehension_walk_newer(node, iter_index=3, code_index=0)
  618. self.write("]")
  619. self.prune()
  620. self.n_list_comp_async = n_list_comp_async
  621. # def kwargs_only_36(node):
  622. # keys = node[-1].attr
  623. # num_kwargs = len(keys)
  624. # values = node[:num_kwargs]
  625. # for i, (key, value) in enumerate(zip(keys, values)):
  626. # self.write(key + '=')
  627. # self.preorder(value)
  628. # if i < num_kwargs:
  629. # self.write(',')
  630. # self.prune()
  631. # return
  632. # self.n_kwargs_only_36 = kwargs_only_36
  633. def starred(node):
  634. l = len(node)
  635. assert l > 0
  636. pos_args = node[0]
  637. if pos_args == "expr":
  638. pos_args = pos_args[0]
  639. if pos_args == "tuple":
  640. build_tuple = pos_args[0]
  641. if build_tuple.kind.startswith("BUILD_TUPLE"):
  642. tuple_len = 0
  643. else:
  644. tuple_len = len(node) - 1
  645. star_start = 1
  646. template = "%C", (0, -1, ", ")
  647. self.template_engine(template, pos_args)
  648. if tuple_len == 0:
  649. self.write("*()")
  650. # That's it
  651. self.prune()
  652. self.write(", ")
  653. else:
  654. star_start = 0
  655. if l > 1:
  656. template = ("*%C", (star_start, -1, ", *"))
  657. else:
  658. template = ("*%c", (star_start, "expr"))
  659. self.template_engine(template, node)
  660. self.prune()
  661. self.n_starred = starred
  662. def return_closure(node):
  663. # Nothing should be output here
  664. self.prune()
  665. return
  666. self.n_return_closure = return_closure