frontend.py 44 KB

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