frontend.py 40 KB

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