You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

parser.py 22 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. # This is the Python adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
  2. #
  3. # Copyright 2020 Huawei Technologies Co., Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # ============================================================================
  17. """The module of parser python object, called by c++."""
  18. import ast
  19. import hashlib
  20. import inspect
  21. import types
  22. from dataclasses import is_dataclass
  23. from textwrap import dedent
  24. import asttokens
  25. from mindspore import Tensor as MsTensor
  26. from mindspore import context
  27. from mindspore import log as logger
  28. from mindspore import nn
  29. from mindspore import ops
  30. from mindspore.common.api import _MindSporeFunction
  31. from mindspore.common.dtype import pytype_to_dtype
  32. from .namespace import CellNamespace, ClosureNamespace, ClassMemberNamespace
  33. from .resources import parse_object_map, convert_object_map, trope_ns, SYMBOL_UNDEFINE, NO_IMPLEMENT
  34. # define return value
  35. RET_SUCCESS = 0
  36. RET_FAILURE = 0xFF
  37. # define resolve type
  38. RESOLVE_TYPE_NONE = 0 # resolve None
  39. RESOLVE_TYPE_FUNCTION = 1 # resolve function
  40. RESOLVE_TYPE_METHOD = 2 # resolve class method
  41. RESOLVE_TYPE_CLASS_TYPE = 3 # resolve class type
  42. RESOLVE_TYPE_CLASS_INSTANCE = 4 # resolve the class instance of common class
  43. RESOLVE_TYPE_INVALID = 0xFF
  44. # define the class instance detail type
  45. # When the type is RESOLVE_TYPE_CLASS_INSTANCE
  46. CLASS_INSTANCE_TYPE_CELL = 0 # class instance type is Cell
  47. CLASS_INSTANCE_TYPE_PRIMITIVE = 1 # class instance type is Primitive
  48. CLASS_INSTANCE_TYPE_INVALID = 0xFF
  49. # Ast main type
  50. AST_MAIN_TYPE_STMT = 0 # ast.Stmt
  51. AST_MAIN_TYPE_EXPR = 1 # ast.Expr
  52. AST_MAIN_TYPE_SLICE = 2 # ast.Slice
  53. AST_MAIN_TYPE_UNKNOWN = 0xFF # unknown
  54. # Ast sub type
  55. AST_SUB_TYPE_AND = 3 # ast.And
  56. AST_SUB_TYPE_OR = 4 # ast.Or
  57. AST_SUB_TYPE_NAME = 5 # ast.Name
  58. AST_SUB_TYPE_TUPLE = 6 # ast.Tuple
  59. AST_SUB_TYPE_SUBSCRIPT = 7 # ast.Subscript
  60. AST_SUB_TYPE_STARRED = 8 # ast.Starred
  61. AST_SUB_TYPE_ATTRIBUTE = 9 # ast.Attribute
  62. AST_SUB_TYPE_UNKNOWN = 0xFF # unknown
  63. # Process expr statement white list
  64. # add as needed, eg: "clear", "extend", "insert", "remove", "reverse"
  65. parse_expr_statement_white_list = (
  66. "append",
  67. )
  68. def create_slice_obj(start, end, step):
  69. """Create slice object"""
  70. return slice(start, end, step)
  71. def parse_cb(func, parse_method=None):
  72. """Implements the function of parse."""
  73. return Parser(func, parse_method)
  74. def get_parse_method_of_class(obj, parse_method=None):
  75. """
  76. Het parse method of class.
  77. Args:
  78. obj(Object): Instance of class.
  79. parse_method(str): Save the method name. Cell object has default method named 'construct'.
  80. Returns:
  81. Function, obj's method.
  82. """
  83. method = None
  84. method_name = None
  85. if parse_method is not None:
  86. method_name = parse_method
  87. elif isinstance(obj, nn.Cell):
  88. if obj.enable_hook:
  89. if context.get_context("mode") == context.GRAPH_MODE:
  90. raise ValueError("The graph mode does not support hook function.")
  91. method_name = "_hook_construct"
  92. else:
  93. method_name = "construct"
  94. if method_name is not None:
  95. if hasattr(obj, method_name):
  96. method = getattr(obj, method_name)
  97. return method
  98. def get_bprop_method_of_class(obj, parse_method=None):
  99. """
  100. Get bprop method of class.
  101. Args:
  102. obj (Object): Instance of class.
  103. parse_method(str): Save the method name. Cell object has default method named 'bprop'.
  104. Returns:
  105. Function, obj's method.
  106. """
  107. method = None
  108. if isinstance(obj, nn.Cell):
  109. method_name = "bprop"
  110. if hasattr(obj, method_name):
  111. method = getattr(obj, method_name)
  112. return method
  113. def resolve_symbol(namespace, symbol):
  114. """
  115. Resolve a symbol.
  116. Note:
  117. Can't get function when use closure function. So save the fn on namespace.
  118. Args:
  119. namespace (Object): Symbol's namespace.
  120. symbol (str): Need resolve symbol.
  121. Returns:
  122. Object, resolve result of symbol.
  123. """
  124. # All exceptions need to be caught in this function
  125. try:
  126. resolve_ = namespace[symbol]
  127. # list and dict is not hashable ,it can not be key for the map, just return the result
  128. if isinstance(resolve_, (tuple, list, dict)):
  129. return resolve_
  130. # dataclass may not be hashable
  131. if getattr(resolve_, "__hash__") is None:
  132. return resolve_
  133. # Raise NotImplementedError when parsing the numpy methods, but not the numpy constant.
  134. if namespace.name == "numpy" and isinstance(resolve_, (types.FunctionType, types.MethodType, types.ModuleType)):
  135. raise NotImplementedError(
  136. f"MindSpore does not support to use the numpy methods in the function construct with the graph mode.")
  137. # If need trope the obj
  138. if resolve_ in convert_object_map:
  139. resolve_ = convert_object_map.get(resolve_)
  140. logger.debug("convert resolve = %r", resolve_)
  141. if resolve_ == NO_IMPLEMENT:
  142. raise NotImplementedError(f"Not support for `{symbol}`.")
  143. except Exception as e:
  144. if isinstance(e, NotImplementedError):
  145. raise e
  146. resolve_ = None
  147. logger.debug("resolve exception occurred, value = %r", e)
  148. logger.debug("resolve type is invalid, namespace = %s, symbol = %s",
  149. namespace.__str__(), symbol)
  150. if isinstance(resolve_, _MindSporeFunction):
  151. logger.debug("resolve class _MindSporeFunction, resolve fn instead.")
  152. resolve_ = resolve_.fn
  153. return resolve_
  154. def generate_scope(obj):
  155. """Generate the scope for every cell object in the network."""
  156. if isinstance(obj, nn.Cell):
  157. obj.generate_scope()
  158. def get_scope_name(obj):
  159. """Returns the scope of a cell object in one network."""
  160. if isinstance(obj, nn.Cell):
  161. return obj.get_scope()
  162. return None
  163. def get_object_key(obj):
  164. """Return the function key: module + name."""
  165. obj_key = ""
  166. if hasattr(obj, "__name__"):
  167. if hasattr(obj, "cell_init_args"):
  168. obj_key = "%s_ID" % (str(obj.__class__.__name__) + str(obj.__name__) + obj.cell_init_args)
  169. obj_id = "%s_ID%d" % (str(obj.__class__.__name__) + str(obj.__name__), id(obj))
  170. else:
  171. # `<class 'xxxxxxx'>`
  172. # -> `xxxxxxx`
  173. tag = str(obj.__class__)[8:-2]
  174. if hasattr(obj, "cell_init_args"):
  175. obj_key = "%s_ID" % (tag + obj.cell_init_args)
  176. obj_id = "%s_ID%d" % (tag, id(obj))
  177. logger.debug("obj_key %s obj_id = %s", obj_key, obj_id)
  178. # method has same id of different instance
  179. if isinstance(obj, types.MethodType):
  180. method_instance = obj.__self__
  181. instance_id = "%s_ID%d" % (str(method_instance.__class__.__name__), id(method_instance))
  182. obj_id = instance_id + obj_id + str(obj.__hash__())
  183. return obj_id, obj_key
  184. def is_class_member(node):
  185. """Check the attr is class member variable."""
  186. type_ = node.__class__.__name__
  187. if type_ == "Attribute":
  188. if not hasattr(node.value, "id"):
  189. return False
  190. id_ = node.value.id
  191. if id_ == "self":
  192. return True
  193. return False
  194. def get_obj_id(obj):
  195. """Get the obj id."""
  196. return str(id(obj))
  197. def get_obj_type(obj):
  198. """Get the obj type."""
  199. obj_type = RESOLVE_TYPE_INVALID
  200. if obj is None:
  201. obj_type = RESOLVE_TYPE_NONE
  202. elif isinstance(obj, types.FunctionType):
  203. obj_type = RESOLVE_TYPE_FUNCTION
  204. elif isinstance(obj, types.MethodType):
  205. obj_type = RESOLVE_TYPE_METHOD
  206. elif isinstance(obj, type):
  207. obj_type = RESOLVE_TYPE_CLASS_TYPE
  208. elif _is_class_instance(obj):
  209. obj_type = RESOLVE_TYPE_CLASS_INSTANCE
  210. else:
  211. # here for ndarray, just print its shape (in case of the array to large and print many data in screen)
  212. is_ndarray = type(obj).__name__ == 'ndarray' and hasattr(obj, 'shape')
  213. raise TypeError(f'Not support for this object with type `{type(obj)}` and {"shape" if is_ndarray else "value"} '
  214. f'`{obj.shape if is_ndarray else obj}`.')
  215. return obj_type
  216. def get_class_instance_type(obj):
  217. """Get the class instance detail type."""
  218. # check the obj type
  219. logger.debug("Get the class type(%r)", obj)
  220. class_type = CLASS_INSTANCE_TYPE_INVALID
  221. if _is_class_instance(obj):
  222. if isinstance(obj, nn.Cell):
  223. class_type = CLASS_INSTANCE_TYPE_CELL
  224. elif isinstance(obj, ops.Primitive):
  225. class_type = CLASS_INSTANCE_TYPE_PRIMITIVE
  226. # Add the other type base requirement
  227. return class_type
  228. def _is_class_instance(obj):
  229. """Confirm the obj is class instance."""
  230. return isinstance(obj, (nn.Cell, ops.Primitive)) or _is_dataclass_instance(obj)
  231. def _is_dataclass_instance(obj):
  232. """check whether a class is an instance of a dataclass (and not a dataclass itself)"""
  233. return is_dataclass(obj) and not isinstance(obj, type)
  234. def _convert_tuple_to_args_kwargs(params):
  235. args = tuple()
  236. kwargs = dict()
  237. for param in params:
  238. if isinstance(param, dict):
  239. kwargs.update(param)
  240. else:
  241. args += (param,)
  242. return (args, kwargs)
  243. def create_obj_instance(cls_type, params=None):
  244. """Create python instance."""
  245. if not isinstance(cls_type, type):
  246. logger.warning(f"create_obj_instance(), cls_type is not a type, cls_type: {cls_type}")
  247. return None
  248. # Check the type, now only support nn.Cell and Primitive.
  249. obj = None
  250. if issubclass(cls_type, (nn.Cell, ops.Primitive)):
  251. # Check arguments, only support *args or **kwargs.
  252. if params is None:
  253. obj = cls_type()
  254. elif isinstance(params, tuple):
  255. args, kwargs = _convert_tuple_to_args_kwargs(params)
  256. logger.debug(f"create_obj_instance(), args: {args}, kwargs: {kwargs}")
  257. if args and kwargs:
  258. obj = cls_type(*args, **kwargs)
  259. elif args:
  260. obj = cls_type(*args)
  261. elif kwargs:
  262. obj = cls_type(**kwargs)
  263. # If invalid parameters.
  264. if obj is None:
  265. raise ValueError(f"When call 'create_instance', the parameter should be *args or **kwargs, "
  266. f"but got {params.__class__.__name__}, params: {params}")
  267. return obj
  268. def get_module_namespace(obj):
  269. """Get the module's namespace."""
  270. logger.debug("get module namespace, module = %r", obj)
  271. mod_namespace = None
  272. if isinstance(obj, types.ModuleType):
  273. mod_namespace = CellNamespace(obj.__name__)
  274. else:
  275. logger.warning("Module(%r) is invalid, get namespace failure!", obj)
  276. return mod_namespace
  277. def get_class_member_namespace_symbol(obj):
  278. """Get obj class member type."""
  279. logger.debug("get class instance namespace, object = %r", obj)
  280. class_namespace = ClassMemberNamespace(obj)
  281. logger.debug("class namesapce = %r", class_namespace)
  282. return class_namespace
  283. def get_dataclass_attributes(cls):
  284. """Get attributes of dataclass."""
  285. fields = cls.__dataclass_fields__
  286. attributes = {name: pytype_to_dtype(field.type)
  287. for name, field in fields.items()}
  288. return attributes
  289. def get_dataclass_methods(cls):
  290. """Get functions of dataclass."""
  291. methods = {name: getattr(cls, name)
  292. for name in dir(cls)
  293. if isinstance(getattr(cls, name), (types.FunctionType,))}
  294. return methods
  295. def convert_to_ms_tensor(data):
  296. """Convert C++ tensor to mindspore tensor."""
  297. return MsTensor(data)
  298. def get_object_description(obj, fname, fline):
  299. """return method or funcition description for error report, include location, class name, etc."""
  300. if isinstance(obj, types.MethodType):
  301. obj_cls = obj.__self__.__class__
  302. class_name = f'{obj_cls.__module__}.{obj_cls.__qualname__}'
  303. cls_fname = inspect.getfile(obj_cls)
  304. _, cls_fline = inspect.getsourcelines(obj_cls)
  305. class_loc = f'{cls_fname}:{cls_fline}'
  306. return f"bound method '{obj.__name__}' at {fname}:{fline} of <{class_name} at {class_loc} object>"
  307. if isinstance(obj, types.FunctionType):
  308. return f"function '{obj.__name__}' at {fname}:{fline}"
  309. if isinstance(obj, ast.FunctionDef):
  310. return f"function '{obj.name}' at {fname}:{fline}"
  311. return str(obj)
  312. def expand_expr_statement(node):
  313. """
  314. Process the expr statement and expand it.
  315. Returns:
  316. tuple, (True, expr.value, x)/(False, None, None).
  317. """
  318. if isinstance(node, ast.Expr):
  319. expr_value = node.value
  320. if isinstance(expr_value, ast.Call):
  321. func = expr_value.func
  322. if isinstance(func, ast.Attribute) and \
  323. hasattr(func, "attr") and \
  324. hasattr(func, "value"):
  325. method = func.attr
  326. target = func.value
  327. if method in parse_expr_statement_white_list:
  328. logger.debug("Expand expr, target:%s, method:%s", target, method)
  329. return True, expr_value, target
  330. if not isinstance(expr_value, ast.Str):
  331. return True, expr_value
  332. return (False,)
  333. def get_ast_namespace_symbol(obj):
  334. """Get obj type and namespace and symbol."""
  335. # step 1:get symbol from object map
  336. ops_info = parse_object_map.get(type(obj), SYMBOL_UNDEFINE)
  337. logger.debug("ops info = %r", ops_info)
  338. return ops_info
  339. def get_operation_namespace_symbol(var: str):
  340. """Get operation namespace and symbol."""
  341. ops_info = (trope_ns, var)
  342. logger.debug("get operation ops info = %r", ops_info)
  343. return ops_info
  344. def get_ast_type(node):
  345. """Get the ast type."""
  346. ast_type = AST_SUB_TYPE_UNKNOWN
  347. if isinstance(node, ast.And):
  348. ast_type = AST_SUB_TYPE_AND
  349. elif isinstance(node, ast.Or):
  350. ast_type = AST_SUB_TYPE_OR
  351. elif isinstance(node, ast.Name):
  352. ast_type = AST_SUB_TYPE_NAME
  353. elif isinstance(node, ast.Tuple):
  354. ast_type = AST_SUB_TYPE_TUPLE
  355. elif isinstance(node, ast.Subscript):
  356. ast_type = AST_SUB_TYPE_SUBSCRIPT
  357. elif isinstance(node, ast.Starred):
  358. ast_type = AST_SUB_TYPE_STARRED
  359. elif isinstance(node, ast.Attribute):
  360. ast_type = AST_SUB_TYPE_ATTRIBUTE
  361. else:
  362. ast_type = AST_SUB_TYPE_UNKNOWN
  363. return ast_type
  364. def get_node_type(node):
  365. """Process an ast node."""
  366. method_name = f'{node.__class__.__name__}'
  367. node_type = [method_name]
  368. # judge the ast main type
  369. if isinstance(node, ast.stmt):
  370. node_type.append(AST_MAIN_TYPE_STMT)
  371. elif isinstance(node, (ast.expr, ast.slice)) or node is None:
  372. # ast.slice and ast.expr should be expr
  373. node_type.append(AST_MAIN_TYPE_EXPR)
  374. else:
  375. node_type.append(AST_MAIN_TYPE_UNKNOWN)
  376. return node_type
  377. def get_args_default_values(node):
  378. """get the args'default values of parse object."""
  379. nondefaults = [None] * (len(node.args.args) - len(node.args.defaults))
  380. defaults = nondefaults + node.args.defaults + node.args.kw_defaults
  381. if node.args.vararg:
  382. defaults.append(None)
  383. if node.args.kwarg:
  384. defaults.append(None)
  385. return defaults
  386. def get_args(node):
  387. """Get the arg of parse object."""
  388. args = []
  389. # process position args
  390. for arg in node.args.args:
  391. args.append(arg)
  392. # process kwonlyargs: kwonlyargs is append after position args
  393. if node.args.kwonlyargs:
  394. for kwarg in node.args.kwonlyargs:
  395. args.append(kwarg)
  396. # process vararg: vararg is append after kwonlyargs
  397. if node.args.vararg:
  398. args.append(node.args.vararg)
  399. # process kwarg: kwarg is append after vararg
  400. if node.args.kwarg:
  401. args.append(node.args.kwarg)
  402. return args
  403. class Parser:
  404. """
  405. Parser python code to ast tree.
  406. Args:
  407. fn(FunctionType/MethodType): Need parse object instance.
  408. parse_method(ExtendInfoOfParseObj): Extend information for parse the function.
  409. ast_cache: Dictionary for caching ast tree.
  410. """
  411. ast_cache = {}
  412. def __init__(self, fn: (types.FunctionType, types.MethodType), parse_method=None) -> None:
  413. self.fn = fn
  414. self.parse_method = parse_method
  415. self.line_offset = 0
  416. self.filename: str = inspect.getfile(self.fn)
  417. # Used to resolve the function's globals Namespace.
  418. self.global_namespace = CellNamespace(fn.__module__)
  419. self.function_module = fn.__module__
  420. # Used to resolve the function's nonlocals.
  421. self.closure_namespace = ClosureNamespace(fn)
  422. self.function_name = fn.__name__
  423. self.col_offset = 0
  424. def parse(self):
  425. """Parse the function or method."""
  426. logger.debug("fn = %r", self.fn)
  427. tree = None
  428. if isinstance(self.fn, (types.FunctionType, types.MethodType)):
  429. lines, self.line_offset = inspect.getsourcelines(self.fn)
  430. original_src = ''.join(lines)
  431. hexstr = hashlib.sha256(original_src.encode()).hexdigest()
  432. tree = Parser.ast_cache.get(hexstr)
  433. if not tree:
  434. src = dedent(original_src)
  435. self.col_offset = \
  436. len(original_src.split('\n')[0]) - len(src.split('\n')[0])
  437. logger.debug("get source = %s", src)
  438. try:
  439. tree = asttokens.ASTTokens(src, parse=True).tree
  440. except IndentationError as idt_err:
  441. idt_err.filename = self.filename
  442. idt_err.lineno = self.line_offset
  443. idt_err.msg = f"There are incorrect indentations in definition or comment of function: " \
  444. f"'{self.fn.__qualname__}'."
  445. raise idt_err
  446. Parser.ast_cache[hexstr] = tree
  447. else:
  448. logger.error("Fn type is invalid")
  449. return tree
  450. def get_namespace_symbol(self, var: str):
  451. """Get symbol type and namespace and symbol."""
  452. if var in self.closure_namespace:
  453. logger.debug("in closure_namespace")
  454. return self.closure_namespace, var
  455. if var in self.global_namespace:
  456. logger.debug("in global_namespace")
  457. value = self.global_namespace[var]
  458. if isinstance(value, type(abs)) and self.global_namespace[var] not in convert_object_map:
  459. error_info = f"The builtin function '{var}' is not supported in graph mode."
  460. return None, var, error_info
  461. return self.global_namespace, var
  462. error_info = f"The name '{var}' is not defined."
  463. return None, var, error_info
  464. def analyze_super(self, class_type_node, subclass_instance):
  465. """Analyze super and return a class instance."""
  466. sub_class = type(subclass_instance)
  467. if class_type_node is None:
  468. return super(sub_class, subclass_instance)
  469. if isinstance(class_type_node, ast.Name):
  470. class_name = getattr(class_type_node, 'id')
  471. elif isinstance(class_type_node, ast.Attribute):
  472. class_name = getattr(class_type_node, 'attr')
  473. else:
  474. raise ValueError(f"When call 'super', the first arg should be a class type, "
  475. f"but got {class_type_node.__class__.__name__}.")
  476. target_father_class = None
  477. for class_element in sub_class.mro():
  478. if class_element.__name__ == class_name:
  479. target_father_class = class_element
  480. break
  481. if target_father_class is None:
  482. raise ValueError("When call 'super', the second arg should be an instance of first arg.")
  483. return super(target_father_class, subclass_instance)
  484. def get_location(self, node):
  485. """
  486. Get location of node start and end line no.
  487. Args:
  488. node: AST op node or tuple or List. This is a node in the ANF diagram,
  489. here is the code location to get this node.
  490. Returns:
  491. List, [fileName, linestart, colstart, lineend, colend].
  492. """
  493. ret = [self.filename]
  494. err_exit = 0
  495. if isinstance(node, (list, tuple)):
  496. node_size = len(node)
  497. if node_size == 0:
  498. err_exit = 1
  499. else:
  500. start_node = node[0]
  501. end_node = node[-1]
  502. else:
  503. start_node = node
  504. end_node = node
  505. if err_exit == 0:
  506. if hasattr(start_node, "lineno") and \
  507. hasattr(end_node, "col_offset"):
  508. start_lineno, start_colno = start_node.first_token.start
  509. end_lineno, end_colno = end_node.last_token.end
  510. start_lineno += self.line_offset - 1
  511. start_colno += self.col_offset
  512. end_lineno += self.line_offset - 1
  513. end_colno += self.col_offset
  514. ret = ret + [start_lineno, start_colno, end_lineno, end_colno]
  515. else:
  516. ret = ret + [0, 0, 0, 0]
  517. return ret