frontend.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  1. # mypy: allow-untyped-defs
  2. import ast
  3. import copy
  4. import dataclasses
  5. import inspect
  6. import re
  7. import string
  8. from collections import namedtuple
  9. from textwrap import dedent
  10. import torch
  11. import torch.jit.annotations
  12. from torch import _jit_internal
  13. from torch._C._jit_tree_views import (
  14. Apply,
  15. Assert,
  16. Assign,
  17. Attribute,
  18. AugAssign,
  19. BinOp,
  20. Break,
  21. ClassDef,
  22. Const,
  23. Continue,
  24. Decl,
  25. Def,
  26. Delete,
  27. DictComp,
  28. DictLiteral,
  29. Dots,
  30. EmptyTypeAnnotation,
  31. ExprStmt,
  32. FalseLiteral,
  33. For,
  34. Ident,
  35. If,
  36. ListComp,
  37. ListLiteral,
  38. NoneLiteral,
  39. Param,
  40. Pass,
  41. Property,
  42. Raise,
  43. Return,
  44. Select,
  45. SliceExpr,
  46. Starred,
  47. Stmt,
  48. StringLiteral,
  49. Subscript,
  50. TernaryIf,
  51. TrueLiteral,
  52. TupleLiteral,
  53. UnaryOp,
  54. Var,
  55. While,
  56. With,
  57. WithItem,
  58. )
  59. from torch._jit_internal import ( # noqa: F401
  60. _is_drop_fn,
  61. FunctionModifiers,
  62. is_static_fn,
  63. should_drop,
  64. )
  65. from torch._sources import (
  66. get_source_lines_and_file,
  67. make_source_context,
  68. parse_def,
  69. ParsedDef as _ParsedDef,
  70. )
  71. from torch.jit._dataclass_impls import DATACLASS_MAGIC_METHODS
  72. from torch.jit._monkeytype_config import get_qualified_name, monkeytype_trace
  73. # Borrowed from cPython implementation
  74. # https://github.com/python/cpython/blob/561612d8456cfab5672c9b445521113b847bd6b3/Lib/textwrap.py#L411#
  75. _reserved_prefix = "__jit"
  76. _reserved_names = {"print"}
  77. _identifier_chars = set(string.ascii_lowercase + string.ascii_uppercase + string.digits)
  78. def is_reserved_name(name):
  79. return name.startswith(_reserved_prefix) or name in _reserved_names
  80. pretty_node_names = {
  81. ast.FunctionDef: "function definitions",
  82. ast.For: "for loops",
  83. ast.Delete: "del statements",
  84. ast.ClassDef: "class definitions",
  85. ast.With: "with statements",
  86. ast.Raise: "raise statements",
  87. ast.Assert: "assertions",
  88. ast.Import: "import statements",
  89. ast.ImportFrom: "import statements",
  90. ast.Global: "global variables",
  91. ast.Break: "break statements",
  92. ast.Continue: "continue statements",
  93. }
  94. node_start_tokens = {
  95. ast.FunctionDef: "def",
  96. ast.For: "for",
  97. ast.Delete: "del",
  98. ast.ClassDef: "class",
  99. ast.With: "with",
  100. ast.Raise: "raise",
  101. ast.Assert: "assert",
  102. ast.Import: "import",
  103. ast.ImportFrom: "from",
  104. ast.Global: "global",
  105. ast.Break: "break",
  106. ast.Continue: "continue",
  107. }
  108. # pyrefly: ignore [no-matching-overload]
  109. pretty_node_names.update(
  110. {
  111. ast.AsyncFunctionDef: "async function definitions",
  112. ast.AsyncFor: "async for loops",
  113. ast.AsyncWith: "async with statements",
  114. ast.Try: "try blocks",
  115. ast.Nonlocal: "nonlocal variables",
  116. }
  117. )
  118. # pyrefly: ignore [no-matching-overload]
  119. node_start_tokens.update(
  120. {
  121. ast.AsyncFunctionDef: "async def",
  122. ast.AsyncFor: "async for",
  123. ast.AsyncWith: "async with",
  124. ast.Try: "try",
  125. ast.Nonlocal: "nonlocal",
  126. }
  127. )
  128. # pyrefly: ignore [no-matching-overload]
  129. pretty_node_names.update(
  130. {
  131. ast.AnnAssign: "annotated assignments",
  132. }
  133. )
  134. # NB: no specific token for AnnAssign
  135. class FrontendError(Exception):
  136. def __init__(self, source_range, msg) -> None:
  137. self.source_range = source_range
  138. self.msg = msg
  139. # This has to be instantiated here so the ErrorReport is accurate to the
  140. # call stack when the FrontendError was raised
  141. self.error_report = torch._C.ErrorReport(self.source_range)
  142. def __str__(self) -> str:
  143. return self.msg + self.error_report.what().lstrip()
  144. class NotSupportedError(FrontendError):
  145. pass
  146. class UnsupportedNodeError(NotSupportedError):
  147. def __init__(self, ctx, offending_node, reason="") -> None:
  148. # If we don't have a specific token, we default to length of 1
  149. node_type = type(offending_node)
  150. range_len = len(node_start_tokens.get(node_type, " "))
  151. source_range = ctx.make_range(
  152. offending_node.lineno,
  153. offending_node.col_offset,
  154. offending_node.col_offset + range_len,
  155. )
  156. feature_name = pretty_node_names.get(node_type, node_type.__name__)
  157. msg = f"{feature_name} {reason + ' ' if reason else ''}aren't supported"
  158. super().__init__(source_range, msg)
  159. class FrontendTypeError(FrontendError):
  160. pass
  161. def build_withitems(ctx, items):
  162. items = [build_withitem(ctx, i) for i in items]
  163. return list(items)
  164. def build_stmts(ctx, stmts):
  165. stmts = [build_stmt(ctx, s) for s in stmts]
  166. return list(filter(None, stmts))
  167. def get_class_properties(cls, self_name):
  168. """
  169. Get a list of Property objects representing the properties of a class.
  170. Args:
  171. cls: The class to get properties of.
  172. self_name: The name of the class that the properties should belong to.
  173. Returns:
  174. A list of Property objects corresponding to the properties of cls. Property
  175. here refers to the subclass of TreeView.
  176. """
  177. props = inspect.getmembers(cls, predicate=lambda m: isinstance(m, property))
  178. # Any property that should not compiled must be in this list on the Module.
  179. unused_properties = getattr(cls, "__jit_unused_properties__", [])
  180. # Create Property TreeView objects from inspected property objects.
  181. properties = []
  182. for prop in props:
  183. if prop[0] not in unused_properties and not should_drop(prop[1].fget):
  184. getter = get_jit_def(
  185. prop[1].fget, f"__{prop[0]}_getter", self_name=self_name
  186. )
  187. setter = (
  188. get_jit_def(prop[1].fset, f"__{prop[0]}_setter", self_name=self_name)
  189. if prop[1].fset
  190. else None
  191. )
  192. properties.append(
  193. Property(getter.range(), Ident(getter.range(), prop[0]), getter, setter)
  194. )
  195. return properties
  196. def get_class_assigns(ctx, cls_ast):
  197. assigns = []
  198. def maybe_build_assign(builder, entry) -> None:
  199. nonlocal assigns
  200. try:
  201. assigns.append(builder(ctx, entry))
  202. except NotSupportedError:
  203. pass
  204. for entry in cls_ast.body:
  205. if isinstance(entry, ast.Assign):
  206. maybe_build_assign(StmtBuilder.build_Assign, entry)
  207. elif isinstance(entry, ast.AnnAssign):
  208. maybe_build_assign(StmtBuilder.build_AnnAssign, entry)
  209. return assigns
  210. def get_jit_class_def(cls, self_name):
  211. """Get definitions for each method within the current class independently.
  212. Args:
  213. cls: The class to get definition of.
  214. self_name: The name of the class that the properties should belong to.
  215. Returns:
  216. torch._C._jit_tree_views.ClassDef: A representation of the class,
  217. the methods in the class and their definition as a tree.
  218. """
  219. # TODO: proper overriding analysis when implementing class inheritance
  220. methods = inspect.getmembers(
  221. cls,
  222. predicate=lambda m: (inspect.ismethod(m) or inspect.isfunction(m))
  223. and not is_static_fn(cls, m.__name__)
  224. and m.__name__ in cls.__dict__
  225. and not _is_drop_fn(m),
  226. )
  227. def is_classmethod(fn):
  228. return inspect.ismethod(fn) and getattr(fn, "__self__", None) == cls
  229. # Get and parse the source code for this class
  230. sourcelines, file_lineno, filename = get_source_lines_and_file(
  231. cls, torch._C.ErrorReport.call_stack()
  232. )
  233. source = "".join(sourcelines)
  234. dedent_src = dedent(source)
  235. py_ast = ast.parse(dedent_src)
  236. class_ast = py_ast.body[0]
  237. if not isinstance(class_ast, ast.ClassDef):
  238. raise AssertionError(
  239. f"Expected class definition, got {type(class_ast).__name__}"
  240. )
  241. # Special case for dataclasses. In general we need access to the source code for
  242. # an object in order to JIT compile it. But the dataclasses module dynamically synthesizes
  243. # magic methods for classes, and we can't get the source code for these methods. As a
  244. # workaround, we synthesize TorchScript-friendly implementations ourselves.
  245. if dataclasses.is_dataclass(cls):
  246. # Detect whether the user manually implemented any of the magic methods. If they did,
  247. # we don't want to synthesize/override them.
  248. overrides = {
  249. method.name
  250. for method in class_ast.body
  251. if isinstance(method, ast.FunctionDef)
  252. and method.name in DATACLASS_MAGIC_METHODS
  253. }
  254. for i, (name, _) in enumerate(methods):
  255. # Is this a magic method we can synthesize?
  256. synthesizer_fn = DATACLASS_MAGIC_METHODS.get(name)
  257. if synthesizer_fn and name not in overrides:
  258. parsed_def = synthesizer_fn(cls)
  259. methods[i] = name, parsed_def
  260. func = getattr(cls, name)
  261. _jit_internal.loader.cache(func, parsed_def.source)
  262. method_defs = [
  263. get_jit_def(obj, name, self_name=self_name, is_classmethod=is_classmethod(obj))
  264. for (name, obj) in methods
  265. ]
  266. properties = get_class_properties(cls, self_name)
  267. leading_whitespace_len = len(source.split("\n", 1)[0]) - len(
  268. dedent_src.split("\n", 1)[0]
  269. )
  270. ctx = make_source_context(
  271. source, filename, file_lineno, leading_whitespace_len, False
  272. )
  273. assigns = get_class_assigns(ctx, class_ast)
  274. return build_class_def(ctx, class_ast, method_defs, properties, self_name, assigns)
  275. def get_jit_def(fn, def_name, self_name=None, is_classmethod=False):
  276. """
  277. Build a JIT AST (TreeView) from the given function.
  278. Args:
  279. fn: A function object to compile or a pre-parsed ParsedDef object
  280. def_name: The name to give to the resulting AST object. This is not
  281. always the same as `fn.__name__`, for example:
  282. def _forward(self):
  283. ...
  284. forward = _forward
  285. In this case, the `__name__` attribute of the function object is "_forward",
  286. but we want the result AST to have the name "forward".
  287. self_name: If this function is a method, what the type name of `self` is.
  288. """
  289. parsed_def = parse_def(fn) if not isinstance(fn, _ParsedDef) else fn
  290. type_line = torch.jit.annotations.get_type_line(parsed_def.source)
  291. fn_def = parsed_def.ast.body[0]
  292. if is_classmethod:
  293. arg_name = fn_def.args.args[0].arg # type:ignore[union-attr]
  294. # Insert a statement that assigns the first argument to the class
  295. assign_stmt = ast.parse(f"{arg_name} = {self_name}").body[0]
  296. fn_def.body.insert(0, assign_stmt) # type:ignore[union-attr]
  297. # Swap out the function signature and body if it is unused
  298. if should_drop(fn):
  299. unused_fn_def = ast.parse(
  300. 'def unused_fn(self: Any):\n\traise RuntimeError("Cannot call @unused methods")'
  301. )
  302. if len(unused_fn_def.body) != 1 or not isinstance(
  303. unused_fn_def.body[0], ast.FunctionDef
  304. ):
  305. raise RuntimeError(
  306. f"Expected a single top-level function: {parsed_def.filename}:{parsed_def.file_lineno}"
  307. )
  308. unused_def = unused_fn_def.body[0]
  309. fn_def.body = unused_def.body # type:ignore[union-attr]
  310. # kwarg/vararg not supported by `build_def`
  311. fn_def.args.kwarg = fn_def.args.vararg = None # type:ignore[union-attr]
  312. for arg in fn_def.args.args + fn_def.args.kwonlyargs: # type:ignore[union-attr]
  313. # Replace potentially unsupported type annotations by "Any"
  314. arg.annotation = unused_def.args.args[0].annotation
  315. if _is_drop_fn(fn):
  316. # Dropping potentially unsupported return type annotation for jit._drop
  317. fn_def.returns = None # type:ignore[union-attr]
  318. fn_def.type_comment = None # type:ignore[union-attr]
  319. # If MonkeyType is installed, get all the consolidated type traces
  320. # for the arguments from type_trace_db
  321. type_trace_db = torch.jit._script._get_type_trace_db()
  322. pdt_arg_types = None
  323. if monkeytype_trace and not isinstance(fn, _ParsedDef): # type: ignore[truthy-function]
  324. qualname = get_qualified_name(fn)
  325. pdt_arg_types = type_trace_db.get_args_types(qualname)
  326. return build_def(
  327. parsed_def.ctx,
  328. fn_def,
  329. type_line,
  330. def_name,
  331. self_name=self_name,
  332. pdt_arg_types=pdt_arg_types,
  333. )
  334. # TODO: more robust handling of recognizing ignore context manager
  335. def is_torch_jit_ignore_context_manager(stmt) -> bool:
  336. # checks if the statement is torch.jit.ignore context manager
  337. if isinstance(stmt.items[0].context_expr, ast.Call):
  338. # extract torch part
  339. function = stmt.items[0].context_expr.func
  340. if isinstance(function, ast.Attribute):
  341. attr_name = function.attr
  342. attr_value = function.value
  343. if attr_name == "_IgnoreContextManager" and isinstance(
  344. attr_value, ast.Attribute
  345. ):
  346. # there should be at most two nested attributes (e.g torch.jit._IgnoreContextManager)
  347. if attr_value.attr == "jit" and isinstance(attr_value.value, ast.Name):
  348. if attr_value.value.id == "torch":
  349. return True
  350. return False
  351. class Builder:
  352. def __call__(self, ctx, node):
  353. method = getattr(self, "build_" + node.__class__.__name__, None)
  354. if method is None:
  355. raise UnsupportedNodeError(ctx, node)
  356. return method(ctx, node)
  357. def build_class_def(ctx, py_def, methods, properties, self_name, assigns):
  358. r = ctx.make_range(
  359. py_def.lineno, py_def.col_offset, py_def.col_offset + len("class")
  360. )
  361. return ClassDef(
  362. Ident(r, self_name), [Stmt(method) for method in methods], properties, assigns
  363. )
  364. def build_def(ctx, py_def, type_line, def_name, self_name=None, pdt_arg_types=None):
  365. body = py_def.body
  366. r = ctx.make_range(py_def.lineno, py_def.col_offset, py_def.col_offset + len("def"))
  367. param_list = build_param_list(ctx, py_def.args, self_name, pdt_arg_types)
  368. return_type = None
  369. if getattr(py_def, "returns", None) is not None:
  370. return_type = build_expr(ctx, py_def.returns)
  371. decl = Decl(r, param_list, return_type)
  372. is_method = self_name is not None
  373. if type_line is not None:
  374. type_comment_decl = torch._C.parse_type_comment(type_line)
  375. decl = torch._C.merge_type_from_type_comment(
  376. decl, # type: ignore[arg-type]
  377. type_comment_decl,
  378. is_method, # type: ignore[assignment]
  379. )
  380. return Def(Ident(r, def_name), decl, build_stmts(ctx, body))
  381. _vararg_kwarg_err = (
  382. "Compiled functions can't take variable number of arguments "
  383. "or use keyword-only arguments with defaults"
  384. )
  385. def build_param_list(ctx, py_args, self_name, pdt_arg_types=None):
  386. if py_args.kwarg is not None:
  387. expr = py_args.kwarg
  388. ctx_range = ctx.make_range(
  389. expr.lineno, expr.col_offset - 1, expr.col_offset + len(expr.arg)
  390. )
  391. raise NotSupportedError(ctx_range, _vararg_kwarg_err)
  392. if py_args.vararg is not None:
  393. expr = py_args.vararg
  394. ctx_range = ctx.make_range(
  395. expr.lineno, expr.col_offset - 1, expr.col_offset + len(expr.arg)
  396. )
  397. raise NotSupportedError(ctx_range, _vararg_kwarg_err)
  398. if len(py_args.kw_defaults) > 0:
  399. # kw_defaults is a list of the values for the kwargs (which default to None),
  400. # so they don't actually have line numbers.
  401. for arg in py_args.kw_defaults:
  402. if arg is not None:
  403. ctx_range = build_expr(ctx, arg).range()
  404. raise NotSupportedError(ctx_range, _vararg_kwarg_err)
  405. # List of Tuple of args and type as inferred by profile directed typing
  406. arg_and_types = [
  407. (
  408. arg,
  409. pdt_arg_types[arg.arg]
  410. if pdt_arg_types and bool(pdt_arg_types[arg.arg])
  411. else None,
  412. )
  413. for arg in py_args.args
  414. ]
  415. arg_and_types_kwonlyargs = [
  416. (
  417. arg,
  418. pdt_arg_types[arg.arg]
  419. if pdt_arg_types and bool(pdt_arg_types[arg.arg])
  420. else None,
  421. )
  422. for arg in py_args.kwonlyargs
  423. ]
  424. result = [
  425. build_param(ctx, arg, self_name, kwarg_only=False, pdt_arg_type=arg_type)
  426. for arg, arg_type in arg_and_types
  427. ]
  428. result += [
  429. build_param(ctx, arg, self_name, kwarg_only=True, pdt_arg_type=arg_type)
  430. for arg, arg_type in arg_and_types_kwonlyargs
  431. ]
  432. return result
  433. def build_param(ctx, py_arg, self_name, kwarg_only, pdt_arg_type=None):
  434. # NB: In Python3 py_arg is a pair of (str arg, expr? annotation)
  435. name = py_arg.arg
  436. r = ctx.make_range(py_arg.lineno, py_arg.col_offset, py_arg.col_offset + len(name))
  437. if getattr(py_arg, "annotation", None) is not None:
  438. annotation_expr = build_expr(ctx, py_arg.annotation)
  439. elif pdt_arg_type:
  440. annotation_expr = Var(Ident(r, pdt_arg_type))
  441. elif self_name is not None and name == "self":
  442. annotation_expr = Var(Ident(r, self_name))
  443. else:
  444. annotation_expr = EmptyTypeAnnotation(r)
  445. return Param(annotation_expr, Ident(r, name), kwarg_only)
  446. def build_ignore_context_manager(ctx, stmt):
  447. InputType = namedtuple("InputType", ["name", "ann"])
  448. OutputType = namedtuple("OutputType", ["name", "ann"])
  449. def process_ins_outs(args):
  450. # parse the context manager to figure out inputs and outputs
  451. # with their annotated types
  452. # TODO: add input, output validator
  453. inputs = []
  454. outputs = []
  455. for arg in args:
  456. var_name = arg.arg
  457. var_ann = arg.value.value
  458. var_decl_type, var_ann = var_ann.split(":")
  459. if var_decl_type == "inp":
  460. inputs.append(InputType(var_name, var_ann))
  461. if var_decl_type == "out":
  462. outputs.append(OutputType(var_name, var_ann))
  463. return inputs, outputs
  464. def create_unique_name_ext(ctx, stmt) -> str:
  465. # extension will be based on the full path filename plus
  466. # the line number of original context manager
  467. fn = re.sub(r"[^a-zA-Z0-9_]", "_", ctx.filename)
  468. return f"{fn}_{stmt.lineno}"
  469. def build_return_ann_stmt(outputs):
  470. return_type_ann = ""
  471. return_statement_str = "return "
  472. if len(outputs) == 0:
  473. return_type_ann += " -> None"
  474. if len(outputs) == 1:
  475. return_type_ann = " -> " + outputs[0].ann
  476. return_statement_str += outputs[0].name
  477. if len(outputs) > 1:
  478. return_type_ann = " -> tuple"
  479. return_type_ann += "[" + ", ".join([var.ann for var in outputs]) + "]"
  480. return_statement_str += ", ".join([var.name for var in outputs])
  481. return return_type_ann, return_statement_str
  482. def build_args(args):
  483. return ", ".join([arg.name for arg in args])
  484. inputs, outputs = process_ins_outs(stmt.items[0].context_expr.keywords)
  485. # build the replacement function str with given inputs and outputs
  486. ignore_function_name = "func_ignore_" + create_unique_name_ext(ctx, stmt)
  487. ignore_function_str = "\ndef " + ignore_function_name
  488. ignore_function_str += (
  489. "(" + ", ".join([var.name + " :" + var.ann for var in inputs]) + ")"
  490. )
  491. return_ann, return_stmt = build_return_ann_stmt(outputs)
  492. ignore_function_str += return_ann + ": pass"
  493. # first create the functionDef object from just declaration
  494. ignore_function = ast.parse(ignore_function_str).body[0]
  495. # dump the body of context manager to dummy function
  496. ignore_function.body = stmt.body # type: ignore[attr-defined]
  497. # insert return statement to the function
  498. return_stmt = ast.parse(return_stmt).body[0]
  499. ignore_function.body.append(return_stmt) # type: ignore[attr-defined]
  500. ignore_func_str = f"""\
  501. # Backward compat: These used to be imported into the outer global scope so some
  502. # code may still expect them.
  503. from typing import List, Dict, Tuple
  504. @torch.jit.ignore
  505. {ast.unparse(ignore_function)}
  506. """
  507. g = copy.copy(globals())
  508. exec(ignore_func_str, g) # noqa: P204
  509. # registers the custom function in the global context
  510. globals()[ignore_function_name] = g[ignore_function_name]
  511. # build the statements as:
  512. # <out_1>, <out_2>, ... = torch.jit.frontend.<func>(<in_1>, <in_2>)
  513. assign_str_lhs = build_args(outputs)
  514. # this function will be registered in torch.jit.frontend module by default
  515. assign_str_rhs = (
  516. f"torch.jit.frontend.{ignore_function_name}(" + build_args(inputs) + ")"
  517. )
  518. if len(outputs) > 0:
  519. assign_str = assign_str_lhs + " = " + assign_str_rhs
  520. else:
  521. assign_str = assign_str_rhs
  522. assign_ast = ast.parse(assign_str).body[0]
  523. return assign_ast
  524. def get_default_args(fn):
  525. """
  526. Get a dictionary of default arguments for a function.
  527. Args:
  528. fn: Callable - The function to inspect for default arguments.
  529. Returns:
  530. (Dict[str, Any]): mapping argument names to their default values if
  531. :attr:`fn` is not None, else empty dictionary.
  532. """
  533. if fn is None:
  534. return {}
  535. signature = inspect.signature(fn)
  536. return {
  537. k: v.default
  538. for k, v in signature.parameters.items()
  539. if v.default is not inspect.Parameter.empty
  540. }
  541. def get_default_args_for_class(cls):
  542. """
  543. Get default arguments for all methods in a class (except for static methods).
  544. Args:
  545. cls: type - The class type to inspect for default arguments.
  546. Returns:
  547. A Dict[str, Dict[str, Any]] which maps each method name to a Dict[str, Any]
  548. that maps each argument name to its default value.
  549. """
  550. # Get methods (except static methods because those are compiled separately as
  551. # if they were independent script functions).
  552. methods = inspect.getmembers(
  553. cls,
  554. predicate=lambda m: (inspect.ismethod(m) or inspect.isfunction(m))
  555. and not is_static_fn(cls, m.__name__)
  556. and m.__name__ in cls.__dict__,
  557. )
  558. # Get method defaults. Property defaults do not need to be considered
  559. # because setters cannot be invoked without a value.
  560. defaults = {
  561. method_name: get_default_args(method_impl)
  562. for method_name, method_impl in methods
  563. }
  564. return defaults
  565. class WithItemBuilder(Builder):
  566. @staticmethod
  567. def build_withitem(ctx, item):
  568. lineno = item.context_expr.lineno
  569. start = item.context_expr.col_offset
  570. end = start + len(pretty_node_names[ast.With])
  571. op_vars = item.optional_vars
  572. r = ctx.make_range(lineno, start, end)
  573. return WithItem(
  574. r,
  575. build_expr(ctx, item.context_expr),
  576. build_expr(ctx, op_vars) if op_vars else None,
  577. )
  578. class StmtBuilder(Builder):
  579. augassign_map = {
  580. ast.Add: "+",
  581. ast.Sub: "-",
  582. ast.Mult: "*",
  583. ast.Div: "/",
  584. ast.Mod: "%",
  585. ast.BitOr: "|",
  586. ast.BitAnd: "&",
  587. ast.BitXor: "^",
  588. ast.LShift: "<<",
  589. ast.RShift: ">>",
  590. ast.Pow: "**",
  591. }
  592. @staticmethod
  593. def build_Expr(ctx, stmt):
  594. value = stmt.value
  595. if value.__class__.__name__ == "Str":
  596. # If a statement is a string literal expression,
  597. # then it is a docstring. Just ignore it.
  598. return None
  599. else:
  600. return ExprStmt(build_expr(ctx, value))
  601. @staticmethod
  602. def build_Assign(ctx, stmt):
  603. rhs = build_expr(ctx, stmt.value)
  604. lhs = [build_expr(ctx, x) for x in stmt.targets]
  605. return Assign(lhs, rhs)
  606. @staticmethod
  607. def build_AnnAssign(ctx, stmt):
  608. if stmt.value is None:
  609. raise UnsupportedNodeError(ctx, stmt, reason="without assigned value")
  610. # Disallow type annotations on instance attributes outside of __init__
  611. if (
  612. type(stmt.target) is ast.Attribute
  613. and stmt.target.value.id == "self" # type: ignore[attr-defined]
  614. and ctx.funcname != "__init__"
  615. ):
  616. start = stmt.col_offset
  617. end = start + len(f"self.{stmt.target.attr}")
  618. if hasattr(stmt.annotation, "id"):
  619. end += len(f": {stmt.annotation.id}")
  620. sr = ctx.make_range(stmt.lineno, start, end)
  621. raise ValueError(
  622. "Type annotations on instance attributes must be declared in "
  623. f"__init__, not '{ctx.funcname}': {sr}"
  624. )
  625. rhs = build_expr(ctx, stmt.value)
  626. lhs = build_expr(ctx, stmt.target)
  627. the_type = build_expr(ctx, stmt.annotation)
  628. return Assign([lhs], rhs, the_type)
  629. @staticmethod
  630. def build_Delete(ctx, stmt):
  631. r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("del"))
  632. return Delete(r, [build_expr(ctx, target) for target in stmt.targets])
  633. @staticmethod
  634. def build_Return(ctx, stmt):
  635. r = ctx.make_range(
  636. stmt.lineno, stmt.col_offset, stmt.col_offset + len("return")
  637. )
  638. return Return(r, None if stmt.value is None else build_expr(ctx, stmt.value))
  639. @staticmethod
  640. def build_Raise(ctx, stmt):
  641. r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("raise"))
  642. expr = build_expr(ctx, stmt.exc)
  643. return Raise(r, expr)
  644. @staticmethod
  645. def build_Assert(ctx, stmt):
  646. r = ctx.make_range(
  647. stmt.lineno, stmt.col_offset, stmt.col_offset + len("assert")
  648. )
  649. test = build_expr(ctx, stmt.test)
  650. msg = build_expr(ctx, stmt.msg) if stmt.msg is not None else None
  651. return Assert(r, test, msg)
  652. @staticmethod
  653. def build_AugAssign(ctx, stmt):
  654. lhs = build_expr(ctx, stmt.target)
  655. rhs = build_expr(ctx, stmt.value)
  656. op = type(stmt.op)
  657. if op in StmtBuilder.augassign_map:
  658. op_token = StmtBuilder.augassign_map[op]
  659. else:
  660. raise NotSupportedError(
  661. find_before(ctx, rhs.range().start, "=", offsets=(-1, 0)),
  662. "unsupported kind of augmented assignment: " + op.__name__,
  663. )
  664. return AugAssign(lhs, op_token, rhs)
  665. @staticmethod
  666. def build_While(ctx, stmt):
  667. if stmt.orelse:
  668. # TODO: try to recover the location of else:? Python doesn't give us useful
  669. # annotations in this case
  670. raise NotSupportedError(
  671. None, "else branches of while loops aren't supported"
  672. )
  673. r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("while"))
  674. return While(r, build_expr(ctx, stmt.test), build_stmts(ctx, stmt.body))
  675. @staticmethod
  676. def build_For(ctx, stmt):
  677. r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("for"))
  678. if stmt.orelse:
  679. raise NotSupportedError(r, "else branches of for loops aren't supported")
  680. return For(
  681. r,
  682. [build_expr(ctx, stmt.target)],
  683. [build_expr(ctx, stmt.iter)],
  684. build_stmts(ctx, stmt.body),
  685. )
  686. @staticmethod
  687. def build_If(ctx, stmt):
  688. r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("if"))
  689. return If(
  690. r,
  691. build_expr(ctx, stmt.test),
  692. build_stmts(ctx, stmt.body),
  693. build_stmts(ctx, stmt.orelse),
  694. )
  695. @staticmethod
  696. def build_Print(ctx, stmt):
  697. r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("print"))
  698. if stmt.dest:
  699. raise NotSupportedError(
  700. r, "print statements with non-default destinations aren't supported"
  701. )
  702. args = [build_expr(ctx, val) for val in stmt.values]
  703. return ExprStmt(Apply(Var(Ident(r, "print")), args, []))
  704. @staticmethod
  705. def build_Pass(ctx, stmt):
  706. r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("pass"))
  707. return Pass(r)
  708. @staticmethod
  709. def build_Break(ctx, stmt):
  710. r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("break"))
  711. return Break(r)
  712. @staticmethod
  713. def build_Continue(ctx, stmt):
  714. r = ctx.make_range(
  715. stmt.lineno, stmt.col_offset, stmt.col_offset + len("continue")
  716. )
  717. return Continue(r)
  718. @staticmethod
  719. def build_With(ctx, stmt):
  720. r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("with"))
  721. # Handle ignore context manager
  722. if is_torch_jit_ignore_context_manager(stmt):
  723. assign_ast = build_ignore_context_manager(ctx, stmt)
  724. return build_stmt(ctx, assign_ast)
  725. return With(r, build_withitems(ctx, stmt.items), build_stmts(ctx, stmt.body))
  726. class ExprBuilder(Builder):
  727. binop_map = {
  728. ast.Add: "+",
  729. ast.Sub: "-",
  730. ast.Mult: "*",
  731. ast.Div: "/",
  732. ast.Pow: "**",
  733. ast.Mod: "%",
  734. ast.FloorDiv: "//",
  735. ast.BitAnd: "&",
  736. ast.BitXor: "^",
  737. ast.BitOr: "|",
  738. ast.LShift: "<<",
  739. ast.RShift: ">>",
  740. }
  741. # pyrefly: ignore [unsupported-operation]
  742. binop_map[ast.MatMult] = "@"
  743. unop_map = {
  744. ast.Not: "not",
  745. ast.USub: "-",
  746. ast.Invert: "~",
  747. }
  748. boolop_map = {
  749. ast.And: "and",
  750. ast.Or: "or",
  751. }
  752. cmpop_map = {
  753. ast.Eq: "==",
  754. ast.NotEq: "!=",
  755. ast.LtE: "<=",
  756. ast.Lt: "<",
  757. ast.GtE: ">=",
  758. ast.Gt: ">",
  759. ast.Is: "is",
  760. ast.IsNot: "is not",
  761. ast.In: "in",
  762. ast.NotIn: "not in",
  763. }
  764. @staticmethod
  765. def build_Attribute(ctx, expr):
  766. base = build_expr(ctx, expr.value)
  767. # expr.attr is just a string, so it's not annotated in any way, so we have
  768. # to build the range manually
  769. source = ctx.source.encode("utf-8")
  770. def get_char(index):
  771. return chr(source[index])
  772. start_pos = base.range().end + 1
  773. while get_char(start_pos) in string.whitespace: # Skip whitespace
  774. start_pos += 1
  775. end_pos = start_pos + len(expr.attr)
  776. name_range = ctx.make_raw_range(start_pos, end_pos)
  777. return Select(base, Ident(name_range, expr.attr))
  778. @staticmethod
  779. def build_Call(ctx, expr):
  780. func = build_expr(ctx, expr.func)
  781. args = [build_expr(ctx, py_arg) for py_arg in expr.args]
  782. if hasattr(expr, "starargs") and expr.starargs:
  783. stararg_expr = build_expr(ctx, expr.starargs)
  784. args += [Starred(stararg_expr.range(), stararg_expr)]
  785. kwargs = []
  786. for kw in expr.keywords:
  787. kw_expr = build_expr(ctx, kw.value)
  788. # XXX: we could do a better job at figuring out the range for the name here
  789. if not kw.arg:
  790. raise NotSupportedError(
  791. kw_expr.range(), "keyword-arg expansion is not supported"
  792. )
  793. kwargs.append(Attribute(Ident(kw_expr.range(), kw.arg), kw_expr))
  794. return Apply(func, args, kwargs)
  795. @staticmethod
  796. def build_Ellipsis(ctx, expr):
  797. r = ctx.make_range(
  798. expr.lineno, expr.col_offset, expr.col_offset + 3
  799. ) # len("...") == 3
  800. return Dots(r)
  801. @staticmethod
  802. def build_Name(ctx, expr):
  803. r = ctx.make_range(expr.lineno, expr.col_offset, expr.col_offset + len(expr.id))
  804. if expr.id.startswith(_reserved_prefix):
  805. raise NotSupportedError(
  806. r,
  807. "names of variables used in JIT-ed functions "
  808. "can't start with " + _reserved_prefix,
  809. )
  810. if expr.id == "True":
  811. return TrueLiteral(r)
  812. elif expr.id == "False":
  813. return FalseLiteral(r)
  814. elif expr.id == "None":
  815. return NoneLiteral(r)
  816. elif expr.id == "Ellipsis":
  817. return Dots(r)
  818. return Var(Ident(r, expr.id))
  819. @staticmethod
  820. def build_NameConstant(ctx, expr):
  821. r = ctx.make_range(
  822. expr.lineno, expr.col_offset, expr.col_offset + len(str(expr.value))
  823. )
  824. if expr.value is True:
  825. return TrueLiteral(r)
  826. elif expr.value is False:
  827. return FalseLiteral(r)
  828. elif expr.value is None:
  829. return NoneLiteral(r)
  830. elif expr.value == Ellipsis:
  831. return Dots(r)
  832. else:
  833. raise ValueError("Name constant value unsupported: " + str(expr.value))
  834. @staticmethod
  835. def build_BinOp(ctx, expr):
  836. lhs = build_expr(ctx, expr.left)
  837. rhs = build_expr(ctx, expr.right)
  838. op = type(expr.op)
  839. if op == ast.Div and not ctx.uses_true_division:
  840. err_range = ctx.make_raw_range(lhs.range().end, rhs.range().start)
  841. raise FrontendError(
  842. err_range,
  843. "Division of ints in TorchScript uses Python 3 true "
  844. "division semantics. Please put `from __future__ "
  845. "import division` at the top of your file",
  846. )
  847. op_token = ExprBuilder.binop_map.get(op)
  848. if op_token is None:
  849. err_range = ctx.make_raw_range(lhs.range().end, rhs.range().start)
  850. raise NotSupportedError(
  851. err_range, "unsupported binary operator: " + op.__name__
  852. )
  853. return BinOp(op_token, lhs, rhs)
  854. @staticmethod
  855. def build_UnaryOp(ctx, expr):
  856. sub_expr = build_expr(ctx, expr.operand)
  857. op = type(expr.op)
  858. op_token = ExprBuilder.unop_map.get(op)
  859. if op_token is None:
  860. raise NotSupportedError(
  861. expr.range(), "unsupported unary operator: " + op.__name__
  862. )
  863. r = ctx.make_range(
  864. expr.lineno, expr.col_offset, expr.col_offset + len(op_token)
  865. )
  866. return UnaryOp(r, op_token, sub_expr)
  867. @staticmethod
  868. def build_BoolOp(ctx, expr):
  869. if len(expr.values) < 2:
  870. raise AssertionError(
  871. "expected at least 2 values in BoolOp, but got " + str(len(expr.values))
  872. )
  873. sub_exprs = [build_expr(ctx, sub_expr) for sub_expr in expr.values]
  874. op = type(expr.op)
  875. op_token = ExprBuilder.boolop_map.get(op)
  876. if op_token is None:
  877. err_range = ctx.make_raw_range(
  878. sub_exprs[0].range().end, sub_exprs[1].range().start
  879. )
  880. raise NotSupportedError(
  881. err_range, "unsupported boolean operator: " + op.__name__
  882. )
  883. lhs = sub_exprs[0]
  884. for rhs in sub_exprs[1:]:
  885. lhs = BinOp(op_token, lhs, rhs)
  886. return lhs
  887. @staticmethod
  888. def build_IfExp(ctx, expr):
  889. return TernaryIf(
  890. build_expr(ctx, expr.test),
  891. build_expr(ctx, expr.body),
  892. build_expr(ctx, expr.orelse),
  893. )
  894. @staticmethod
  895. def build_Compare(ctx, expr):
  896. operands = [build_expr(ctx, e) for e in [expr.left] + list(expr.comparators)]
  897. result = None
  898. # pyrefly: ignore [bad-assignment]
  899. for lhs, op_, rhs in zip(operands, expr.ops, operands[1:]):
  900. op = type(op_)
  901. op_token = ExprBuilder.cmpop_map.get(op)
  902. r = ctx.make_raw_range(lhs.range().end, rhs.range().start)
  903. if op_token is None:
  904. raise NotSupportedError(
  905. r, "unsupported comparison operator: " + op.__name__
  906. )
  907. if op == ast.NotIn:
  908. # NB: `not in` is just `not( in )`, so we don't introduce new tree view
  909. # but just make it a nested call in our tree view structure
  910. in_expr = BinOp("in", lhs, rhs)
  911. cmp_expr = UnaryOp(r, "not", in_expr)
  912. else:
  913. cmp_expr = BinOp(op_token, lhs, rhs) # type: ignore[assignment]
  914. if result is None:
  915. result = cmp_expr
  916. else:
  917. result = BinOp("and", result, cmp_expr) # type: ignore[assignment]
  918. return result
  919. @staticmethod
  920. def build_Subscript(ctx, expr):
  921. def build_SliceExpr(ctx, base, slice_expr):
  922. lower = (
  923. build_expr(ctx, slice_expr.lower)
  924. if slice_expr.lower is not None
  925. else None
  926. )
  927. upper = (
  928. build_expr(ctx, slice_expr.upper)
  929. if slice_expr.upper is not None
  930. else None
  931. )
  932. step = (
  933. build_expr(ctx, slice_expr.step)
  934. if slice_expr.step is not None
  935. else None
  936. )
  937. return SliceExpr(base.range(), lower, upper, step)
  938. def build_Index(ctx, base, index_expr):
  939. if isinstance(index_expr.value, ast.Tuple):
  940. raise NotSupportedError(
  941. base.range(),
  942. "slicing multiple dimensions with tuples not supported yet",
  943. )
  944. return build_expr(ctx, index_expr.value)
  945. def build_ExtSlice(ctx, base, extslice):
  946. sub_exprs = []
  947. for expr in extslice.dims:
  948. sub_type = type(expr)
  949. if sub_type is ast.Index:
  950. sub_exprs.append(build_Index(ctx, base, expr))
  951. elif sub_type is ast.Slice:
  952. sub_exprs.append(build_SliceExpr(ctx, base, expr))
  953. elif sub_type is ast.Constant and expr.value is Ellipsis:
  954. sub_exprs.append(Dots(base.range()))
  955. else:
  956. raise NotSupportedError(
  957. base.range(),
  958. f"slicing multiple dimensions with {sub_type} not supported",
  959. )
  960. return sub_exprs
  961. base = build_expr(ctx, expr.value)
  962. sub_type = type(expr.slice)
  963. if sub_type is ast.Index:
  964. if isinstance(expr.slice.value, ast.Tuple):
  965. # N-dimensional indexing using Tuple: x[(i, j, k)] is equivalent to x[i, j, k]
  966. # XXX: Indexing using a list is **different**! It triggers advanced indexing.
  967. indices = [
  968. build_expr(ctx, index_expr) for index_expr in expr.slice.value.elts
  969. ]
  970. if not indices:
  971. # `col_offset` is an int, but `end_col_offset` is
  972. # `Optional[int]`. The magic number is here to make
  973. # sure we can parse `()` on any machine
  974. r = ctx.make_range(
  975. expr.lineno,
  976. expr.slice.value.col_offset,
  977. expr.slice.value.col_offset + 2,
  978. )
  979. tup = TupleLiteral(r, [])
  980. indices.append(tup)
  981. return Subscript(base, indices)
  982. else:
  983. return Subscript(base, [build_expr(ctx, expr.slice.value)])
  984. elif sub_type is ast.Slice:
  985. return Subscript(base, [build_SliceExpr(ctx, base, expr.slice)])
  986. elif sub_type is ast.ExtSlice:
  987. return Subscript(base, build_ExtSlice(ctx, base, expr.slice))
  988. else: # In Python3.9 array indices are not wrapped in ast.Index
  989. if sub_type is ast.Tuple:
  990. # N-dimensional indexing using Tuple: x[(i, j, k)] is equivalent to x[i, j, k]
  991. indices = []
  992. for index_expr in expr.slice.elts:
  993. if isinstance(index_expr, ast.Slice):
  994. indices.append(build_SliceExpr(ctx, base, index_expr))
  995. else:
  996. indices.append(build_expr(ctx, index_expr))
  997. # Special-case logic for `typing.Tuple[()]`
  998. if not indices:
  999. # See note above r.e. magic number
  1000. r = ctx.make_range(
  1001. expr.lineno, expr.slice.col_offset, expr.slice.col_offset + 2
  1002. )
  1003. tup = TupleLiteral(r, [])
  1004. indices.append(tup)
  1005. return Subscript(base, indices)
  1006. return Subscript(base, [build_expr(ctx, expr.slice)])
  1007. @staticmethod
  1008. def build_List(ctx, expr):
  1009. return ListLiteral(
  1010. ctx.make_range(expr.lineno, expr.col_offset, expr.col_offset + 1),
  1011. [build_expr(ctx, e) for e in expr.elts],
  1012. )
  1013. @staticmethod
  1014. def build_Tuple(ctx, expr):
  1015. return TupleLiteral(
  1016. ctx.make_range(expr.lineno, expr.col_offset, expr.col_offset + 1),
  1017. [build_expr(ctx, e) for e in expr.elts],
  1018. )
  1019. @staticmethod
  1020. def build_Dict(ctx, expr):
  1021. range = ctx.make_range(expr.lineno, expr.col_offset, expr.col_offset + 1)
  1022. if expr.keys and not expr.keys[0]:
  1023. raise NotSupportedError(
  1024. range, "Dict expansion (e.g. `{**dict}`) is not supported"
  1025. )
  1026. return DictLiteral(
  1027. range,
  1028. [build_expr(ctx, e) for e in expr.keys],
  1029. [build_expr(ctx, e) for e in expr.values],
  1030. )
  1031. @staticmethod
  1032. def build_Num(ctx, expr):
  1033. value = str(expr.value)
  1034. r = ctx.make_range(expr.lineno, expr.col_offset, expr.col_offset + len(value))
  1035. return Const(r, value)
  1036. @staticmethod
  1037. def build_Constant(ctx, expr):
  1038. value = expr.value
  1039. if value is None or isinstance(value, bool):
  1040. # NB: this check has to happen before the int check because bool is
  1041. # a subclass of int
  1042. return ExprBuilder.build_NameConstant(ctx, expr)
  1043. if isinstance(value, (int, float, complex)):
  1044. return ExprBuilder.build_Num(ctx, expr)
  1045. elif isinstance(value, str):
  1046. return ExprBuilder.build_Str(ctx, expr)
  1047. elif isinstance(value, type(Ellipsis)):
  1048. return ExprBuilder.build_Ellipsis(ctx, expr)
  1049. else:
  1050. error_range = ctx.make_range(
  1051. expr.lineno, expr.col_offset, expr.col_offset + len(str(value))
  1052. )
  1053. raise FrontendError(error_range, "Unknown Constant expression type")
  1054. @staticmethod
  1055. def build_Str(ctx, expr):
  1056. value = str(expr.value)
  1057. r = ctx.make_range(
  1058. expr.lineno, expr.col_offset, expr.col_offset + len(value) + 1
  1059. )
  1060. return StringLiteral(r, value)
  1061. @staticmethod
  1062. def build_JoinedStr(ctx, expr):
  1063. s = ""
  1064. args = []
  1065. for value in expr.values:
  1066. r = ctx.make_range(value.lineno, value.col_offset, value.col_offset + 1)
  1067. if isinstance(value, ast.FormattedValue):
  1068. if value.conversion != -1:
  1069. raise NotSupportedError(r, "Don't support conversion in JoinedStr")
  1070. if value.format_spec is not None:
  1071. raise NotSupportedError(r, "Don't support formatting in JoinedStr")
  1072. s += "{}"
  1073. args.append(build_expr(ctx, value.value))
  1074. elif isinstance(value, ast.Constant):
  1075. # pyrefly: ignore [unsupported-operation]
  1076. s += value.value
  1077. else:
  1078. raise NotSupportedError(r, "Unsupported value in JoinedStr")
  1079. r = ctx.make_range(expr.lineno, expr.col_offset, expr.col_offset + 1)
  1080. return Apply(Select(StringLiteral(r, s), Ident(r, "format")), args, [])
  1081. @staticmethod
  1082. def build_ListComp(ctx, stmt):
  1083. r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset)
  1084. if len(stmt.generators) != 1:
  1085. raise NotSupportedError(r, "Only a single generator is currently supported")
  1086. if len(stmt.generators[0].ifs) != 0:
  1087. raise NotSupportedError(r, "Comprehension ifs are not supported yet")
  1088. elt_expr = build_expr(ctx, stmt.elt)
  1089. target_expr = build_expr(ctx, stmt.generators[0].target)
  1090. iter_expr = build_expr(ctx, stmt.generators[0].iter)
  1091. return ListComp(r, elt_expr, target_expr, iter_expr)
  1092. @staticmethod
  1093. def build_GeneratorExp(ctx, stmt):
  1094. # Convert Generator expression to ListComp
  1095. return ExprBuilder.build_ListComp(ctx, stmt)
  1096. @staticmethod
  1097. def build_DictComp(ctx, stmt):
  1098. r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset)
  1099. if len(stmt.generators) != 1:
  1100. raise NotSupportedError(r, "Only a single generator is currently supported")
  1101. if len(stmt.generators[0].ifs) != 0:
  1102. raise NotSupportedError(r, "Comprehension ifs are not supported yet")
  1103. key_expr = build_expr(ctx, stmt.key)
  1104. value_expr = build_expr(ctx, stmt.value)
  1105. target_expr = build_expr(ctx, stmt.generators[0].target)
  1106. iter_expr = build_expr(ctx, stmt.generators[0].iter)
  1107. return DictComp(r, key_expr, value_expr, target_expr, iter_expr)
  1108. @staticmethod
  1109. def build_Starred(ctx, expr):
  1110. r = ctx.make_range(expr.lineno, expr.col_offset, expr.col_offset + 1)
  1111. return Starred(r, build_expr(ctx, expr.value))
  1112. build_expr = ExprBuilder()
  1113. build_stmt = StmtBuilder()
  1114. build_withitem = WithItemBuilder()
  1115. def find_before(ctx, pos, substr, offsets=(0, 0)):
  1116. new_pos = ctx.source[:pos].rindex(substr)
  1117. return ctx.make_raw_range(new_pos + offsets[0], new_pos + len(substr) + offsets[1])