frontend.py 43 KB

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