frontend.py 44 KB

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