node_ng.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  1. import pprint
  2. import sys
  3. import typing
  4. import warnings
  5. from functools import singledispatch as _singledispatch
  6. from typing import (
  7. TYPE_CHECKING,
  8. ClassVar,
  9. Iterator,
  10. List,
  11. Optional,
  12. Tuple,
  13. Type,
  14. TypeVar,
  15. Union,
  16. cast,
  17. overload,
  18. )
  19. from astroid import decorators, util
  20. from astroid.exceptions import (
  21. AstroidError,
  22. InferenceError,
  23. ParentMissingError,
  24. StatementMissing,
  25. UseInferenceDefault,
  26. )
  27. from astroid.manager import AstroidManager
  28. from astroid.nodes.as_string import AsStringVisitor
  29. from astroid.nodes.const import OP_PRECEDENCE
  30. if TYPE_CHECKING:
  31. from astroid import nodes
  32. if sys.version_info >= (3, 8):
  33. from typing import Literal
  34. else:
  35. from typing_extensions import Literal
  36. # Types for 'NodeNG.nodes_of_class()'
  37. T_Nodes = TypeVar("T_Nodes", bound="NodeNG")
  38. T_Nodes2 = TypeVar("T_Nodes2", bound="NodeNG")
  39. T_Nodes3 = TypeVar("T_Nodes3", bound="NodeNG")
  40. SkipKlassT = Union[None, Type["NodeNG"], Tuple[Type["NodeNG"], ...]]
  41. class NodeNG:
  42. """A node of the new Abstract Syntax Tree (AST).
  43. This is the base class for all Astroid node classes.
  44. """
  45. is_statement: ClassVar[bool] = False
  46. """Whether this node indicates a statement."""
  47. optional_assign: ClassVar[
  48. bool
  49. ] = False # True for For (and for Comprehension if py <3.0)
  50. """Whether this node optionally assigns a variable.
  51. This is for loop assignments because loop won't necessarily perform an
  52. assignment if the loop has no iterations.
  53. This is also the case from comprehensions in Python 2.
  54. """
  55. is_function: ClassVar[bool] = False # True for FunctionDef nodes
  56. """Whether this node indicates a function."""
  57. is_lambda: ClassVar[bool] = False
  58. # Attributes below are set by the builder module or by raw factories
  59. _astroid_fields: ClassVar[typing.Tuple[str, ...]] = ()
  60. """Node attributes that contain child nodes.
  61. This is redefined in most concrete classes.
  62. """
  63. _other_fields: ClassVar[typing.Tuple[str, ...]] = ()
  64. """Node attributes that do not contain child nodes."""
  65. _other_other_fields: ClassVar[typing.Tuple[str, ...]] = ()
  66. """Attributes that contain AST-dependent fields."""
  67. # instance specific inference function infer(node, context)
  68. _explicit_inference = None
  69. def __init__(
  70. self,
  71. lineno: Optional[int] = None,
  72. col_offset: Optional[int] = None,
  73. parent: Optional["NodeNG"] = None,
  74. *,
  75. end_lineno: Optional[int] = None,
  76. end_col_offset: Optional[int] = None,
  77. ) -> None:
  78. """
  79. :param lineno: The line that this node appears on in the source code.
  80. :param col_offset: The column that this node appears on in the
  81. source code.
  82. :param parent: The parent node in the syntax tree.
  83. :param end_lineno: The last line this node appears on in the source code.
  84. :param end_col_offset: The end column this node appears on in the
  85. source code. Note: This is after the last symbol.
  86. """
  87. self.lineno: Optional[int] = lineno
  88. """The line that this node appears on in the source code."""
  89. self.col_offset: Optional[int] = col_offset
  90. """The column that this node appears on in the source code."""
  91. self.parent: Optional["NodeNG"] = parent
  92. """The parent node in the syntax tree."""
  93. self.end_lineno: Optional[int] = end_lineno
  94. """The last line this node appears on in the source code."""
  95. self.end_col_offset: Optional[int] = end_col_offset
  96. """The end column this node appears on in the source code.
  97. Note: This is after the last symbol.
  98. """
  99. def infer(self, context=None, **kwargs):
  100. """Get a generator of the inferred values.
  101. This is the main entry point to the inference system.
  102. .. seealso:: :ref:`inference`
  103. If the instance has some explicit inference function set, it will be
  104. called instead of the default interface.
  105. :returns: The inferred values.
  106. :rtype: iterable
  107. """
  108. if context is not None:
  109. context = context.extra_context.get(self, context)
  110. if self._explicit_inference is not None:
  111. # explicit_inference is not bound, give it self explicitly
  112. try:
  113. # pylint: disable=not-callable
  114. results = list(self._explicit_inference(self, context, **kwargs))
  115. if context is not None:
  116. context.nodes_inferred += len(results)
  117. yield from results
  118. return
  119. except UseInferenceDefault:
  120. pass
  121. if not context:
  122. # nodes_inferred?
  123. yield from self._infer(context, **kwargs)
  124. return
  125. key = (self, context.lookupname, context.callcontext, context.boundnode)
  126. if key in context.inferred:
  127. yield from context.inferred[key]
  128. return
  129. generator = self._infer(context, **kwargs)
  130. results = []
  131. # Limit inference amount to help with performance issues with
  132. # exponentially exploding possible results.
  133. limit = AstroidManager().max_inferable_values
  134. for i, result in enumerate(generator):
  135. if i >= limit or (context.nodes_inferred > context.max_inferred):
  136. yield util.Uninferable
  137. break
  138. results.append(result)
  139. yield result
  140. context.nodes_inferred += 1
  141. # Cache generated results for subsequent inferences of the
  142. # same node using the same context
  143. context.inferred[key] = tuple(results)
  144. return
  145. def _repr_name(self):
  146. """Get a name for nice representation.
  147. This is either :attr:`name`, :attr:`attrname`, or the empty string.
  148. :returns: The nice name.
  149. :rtype: str
  150. """
  151. if all(name not in self._astroid_fields for name in ("name", "attrname")):
  152. return getattr(self, "name", "") or getattr(self, "attrname", "")
  153. return ""
  154. def __str__(self):
  155. rname = self._repr_name()
  156. cname = type(self).__name__
  157. if rname:
  158. string = "%(cname)s.%(rname)s(%(fields)s)"
  159. alignment = len(cname) + len(rname) + 2
  160. else:
  161. string = "%(cname)s(%(fields)s)"
  162. alignment = len(cname) + 1
  163. result = []
  164. for field in self._other_fields + self._astroid_fields:
  165. value = getattr(self, field)
  166. width = 80 - len(field) - alignment
  167. lines = pprint.pformat(value, indent=2, width=width).splitlines(True)
  168. inner = [lines[0]]
  169. for line in lines[1:]:
  170. inner.append(" " * alignment + line)
  171. result.append(f"{field}={''.join(inner)}")
  172. return string % {
  173. "cname": cname,
  174. "rname": rname,
  175. "fields": (",\n" + " " * alignment).join(result),
  176. }
  177. def __repr__(self):
  178. rname = self._repr_name()
  179. if rname:
  180. string = "<%(cname)s.%(rname)s l.%(lineno)s at 0x%(id)x>"
  181. else:
  182. string = "<%(cname)s l.%(lineno)s at 0x%(id)x>"
  183. return string % {
  184. "cname": type(self).__name__,
  185. "rname": rname,
  186. "lineno": self.fromlineno,
  187. "id": id(self),
  188. }
  189. def accept(self, visitor):
  190. """Visit this node using the given visitor."""
  191. func = getattr(visitor, "visit_" + self.__class__.__name__.lower())
  192. return func(self)
  193. def get_children(self) -> Iterator["NodeNG"]:
  194. """Get the child nodes below this node."""
  195. for field in self._astroid_fields:
  196. attr = getattr(self, field)
  197. if attr is None:
  198. continue
  199. if isinstance(attr, (list, tuple)):
  200. yield from attr
  201. else:
  202. yield attr
  203. yield from ()
  204. def last_child(self) -> Optional["NodeNG"]:
  205. """An optimized version of list(get_children())[-1]"""
  206. for field in self._astroid_fields[::-1]:
  207. attr = getattr(self, field)
  208. if not attr: # None or empty listy / tuple
  209. continue
  210. if isinstance(attr, (list, tuple)):
  211. return attr[-1]
  212. return attr
  213. return None
  214. def node_ancestors(self) -> Iterator["NodeNG"]:
  215. """Yield parent, grandparent, etc until there are no more."""
  216. parent = self.parent
  217. while parent is not None:
  218. yield parent
  219. parent = parent.parent
  220. def parent_of(self, node):
  221. """Check if this node is the parent of the given node.
  222. :param node: The node to check if it is the child.
  223. :type node: NodeNG
  224. :returns: True if this node is the parent of the given node,
  225. False otherwise.
  226. :rtype: bool
  227. """
  228. return any(self is parent for parent in node.node_ancestors())
  229. @overload
  230. def statement(
  231. self, *, future: Literal[None] = ...
  232. ) -> Union["nodes.Statement", "nodes.Module"]:
  233. ...
  234. @overload
  235. def statement(self, *, future: Literal[True]) -> "nodes.Statement":
  236. ...
  237. def statement(
  238. self, *, future: Literal[None, True] = None
  239. ) -> Union["nodes.Statement", "nodes.Module"]:
  240. """The first parent node, including self, marked as statement node.
  241. TODO: Deprecate the future parameter and only raise StatementMissing and return
  242. nodes.Statement
  243. :raises AttributeError: If self has no parent attribute
  244. :raises StatementMissing: If self has no parent attribute and future is True
  245. """
  246. if self.is_statement:
  247. return cast("nodes.Statement", self)
  248. if not self.parent:
  249. if future:
  250. raise StatementMissing(target=self)
  251. warnings.warn(
  252. "In astroid 3.0.0 NodeNG.statement() will return either a nodes.Statement "
  253. "or raise a StatementMissing exception. AttributeError will no longer be raised. "
  254. "This behaviour can already be triggered "
  255. "by passing 'future=True' to a statement() call.",
  256. DeprecationWarning,
  257. )
  258. raise AttributeError(f"{self} object has no attribute 'parent'")
  259. return self.parent.statement(future=future)
  260. def frame(
  261. self, *, future: Literal[None, True] = None
  262. ) -> Union["nodes.FunctionDef", "nodes.Module", "nodes.ClassDef", "nodes.Lambda"]:
  263. """The first parent frame node.
  264. A frame node is a :class:`Module`, :class:`FunctionDef`,
  265. :class:`ClassDef` or :class:`Lambda`.
  266. :returns: The first parent frame node.
  267. """
  268. if self.parent is None:
  269. if future:
  270. raise ParentMissingError(target=self)
  271. warnings.warn(
  272. "In astroid 3.0.0 NodeNG.frame() will return either a Frame node, "
  273. "or raise ParentMissingError. AttributeError will no longer be raised. "
  274. "This behaviour can already be triggered "
  275. "by passing 'future=True' to a frame() call.",
  276. DeprecationWarning,
  277. )
  278. raise AttributeError(f"{self} object has no attribute 'parent'")
  279. return self.parent.frame(future=future)
  280. def scope(self) -> "nodes.LocalsDictNodeNG":
  281. """The first parent node defining a new scope.
  282. These can be Module, FunctionDef, ClassDef, Lambda, or GeneratorExp nodes.
  283. :returns: The first parent scope node.
  284. """
  285. if not self.parent:
  286. raise ParentMissingError(target=self)
  287. return self.parent.scope()
  288. def root(self):
  289. """Return the root node of the syntax tree.
  290. :returns: The root node.
  291. :rtype: Module
  292. """
  293. if self.parent:
  294. return self.parent.root()
  295. return self
  296. def child_sequence(self, child):
  297. """Search for the sequence that contains this child.
  298. :param child: The child node to search sequences for.
  299. :type child: NodeNG
  300. :returns: The sequence containing the given child node.
  301. :rtype: iterable(NodeNG)
  302. :raises AstroidError: If no sequence could be found that contains
  303. the given child.
  304. """
  305. for field in self._astroid_fields:
  306. node_or_sequence = getattr(self, field)
  307. if node_or_sequence is child:
  308. return [node_or_sequence]
  309. # /!\ compiler.ast Nodes have an __iter__ walking over child nodes
  310. if (
  311. isinstance(node_or_sequence, (tuple, list))
  312. and child in node_or_sequence
  313. ):
  314. return node_or_sequence
  315. msg = "Could not find %s in %s's children"
  316. raise AstroidError(msg % (repr(child), repr(self)))
  317. def locate_child(self, child):
  318. """Find the field of this node that contains the given child.
  319. :param child: The child node to search fields for.
  320. :type child: NodeNG
  321. :returns: A tuple of the name of the field that contains the child,
  322. and the sequence or node that contains the child node.
  323. :rtype: tuple(str, iterable(NodeNG) or NodeNG)
  324. :raises AstroidError: If no field could be found that contains
  325. the given child.
  326. """
  327. for field in self._astroid_fields:
  328. node_or_sequence = getattr(self, field)
  329. # /!\ compiler.ast Nodes have an __iter__ walking over child nodes
  330. if child is node_or_sequence:
  331. return field, child
  332. if (
  333. isinstance(node_or_sequence, (tuple, list))
  334. and child in node_or_sequence
  335. ):
  336. return field, node_or_sequence
  337. msg = "Could not find %s in %s's children"
  338. raise AstroidError(msg % (repr(child), repr(self)))
  339. # FIXME : should we merge child_sequence and locate_child ? locate_child
  340. # is only used in are_exclusive, child_sequence one time in pylint.
  341. def next_sibling(self):
  342. """The next sibling statement node.
  343. :returns: The next sibling statement node.
  344. :rtype: NodeNG or None
  345. """
  346. return self.parent.next_sibling()
  347. def previous_sibling(self):
  348. """The previous sibling statement.
  349. :returns: The previous sibling statement node.
  350. :rtype: NodeNG or None
  351. """
  352. return self.parent.previous_sibling()
  353. # these are lazy because they're relatively expensive to compute for every
  354. # single node, and they rarely get looked at
  355. @decorators.cachedproperty
  356. def fromlineno(self) -> Optional[int]:
  357. """The first line that this node appears on in the source code."""
  358. if self.lineno is None:
  359. return self._fixed_source_line()
  360. return self.lineno
  361. @decorators.cachedproperty
  362. def tolineno(self) -> Optional[int]:
  363. """The last line that this node appears on in the source code."""
  364. if not self._astroid_fields:
  365. # can't have children
  366. last_child = None
  367. else:
  368. last_child = self.last_child()
  369. if last_child is None:
  370. return self.fromlineno
  371. return last_child.tolineno
  372. def _fixed_source_line(self) -> Optional[int]:
  373. """Attempt to find the line that this node appears on.
  374. We need this method since not all nodes have :attr:`lineno` set.
  375. """
  376. line = self.lineno
  377. _node: Optional[NodeNG] = self
  378. try:
  379. while line is None:
  380. _node = next(_node.get_children())
  381. line = _node.lineno
  382. except StopIteration:
  383. _node = self.parent
  384. while _node and line is None:
  385. line = _node.lineno
  386. _node = _node.parent
  387. return line
  388. def block_range(self, lineno):
  389. """Get a range from the given line number to where this node ends.
  390. :param lineno: The line number to start the range at.
  391. :type lineno: int
  392. :returns: The range of line numbers that this node belongs to,
  393. starting at the given line number.
  394. :rtype: tuple(int, int or None)
  395. """
  396. return lineno, self.tolineno
  397. def set_local(self, name, stmt):
  398. """Define that the given name is declared in the given statement node.
  399. This definition is stored on the parent scope node.
  400. .. seealso:: :meth:`scope`
  401. :param name: The name that is being defined.
  402. :type name: str
  403. :param stmt: The statement that defines the given name.
  404. :type stmt: NodeNG
  405. """
  406. self.parent.set_local(name, stmt)
  407. @overload
  408. def nodes_of_class(
  409. self,
  410. klass: Type[T_Nodes],
  411. skip_klass: SkipKlassT = None,
  412. ) -> Iterator[T_Nodes]:
  413. ...
  414. @overload
  415. def nodes_of_class(
  416. self,
  417. klass: Tuple[Type[T_Nodes], Type[T_Nodes2]],
  418. skip_klass: SkipKlassT = None,
  419. ) -> Union[Iterator[T_Nodes], Iterator[T_Nodes2]]:
  420. ...
  421. @overload
  422. def nodes_of_class(
  423. self,
  424. klass: Tuple[Type[T_Nodes], Type[T_Nodes2], Type[T_Nodes3]],
  425. skip_klass: SkipKlassT = None,
  426. ) -> Union[Iterator[T_Nodes], Iterator[T_Nodes2], Iterator[T_Nodes3]]:
  427. ...
  428. @overload
  429. def nodes_of_class(
  430. self,
  431. klass: Tuple[Type[T_Nodes], ...],
  432. skip_klass: SkipKlassT = None,
  433. ) -> Iterator[T_Nodes]:
  434. ...
  435. def nodes_of_class( # type: ignore[misc] # mypy doesn't correctly recognize the overloads
  436. self,
  437. klass: Union[
  438. Type[T_Nodes],
  439. Tuple[Type[T_Nodes], Type[T_Nodes2]],
  440. Tuple[Type[T_Nodes], Type[T_Nodes2], Type[T_Nodes3]],
  441. Tuple[Type[T_Nodes], ...],
  442. ],
  443. skip_klass: SkipKlassT = None,
  444. ) -> Union[Iterator[T_Nodes], Iterator[T_Nodes2], Iterator[T_Nodes3]]:
  445. """Get the nodes (including this one or below) of the given types.
  446. :param klass: The types of node to search for.
  447. :param skip_klass: The types of node to ignore. This is useful to ignore
  448. subclasses of :attr:`klass`.
  449. :returns: The node of the given types.
  450. """
  451. if isinstance(self, klass):
  452. yield self
  453. if skip_klass is None:
  454. for child_node in self.get_children():
  455. yield from child_node.nodes_of_class(klass, skip_klass)
  456. return
  457. for child_node in self.get_children():
  458. if isinstance(child_node, skip_klass):
  459. continue
  460. yield from child_node.nodes_of_class(klass, skip_klass)
  461. @decorators.cached
  462. def _get_assign_nodes(self):
  463. return []
  464. def _get_name_nodes(self):
  465. for child_node in self.get_children():
  466. yield from child_node._get_name_nodes()
  467. def _get_return_nodes_skip_functions(self):
  468. yield from ()
  469. def _get_yield_nodes_skip_lambdas(self):
  470. yield from ()
  471. def _infer_name(self, frame, name):
  472. # overridden for ImportFrom, Import, Global, TryExcept and Arguments
  473. pass
  474. def _infer(self, context=None):
  475. """we don't know how to resolve a statement by default"""
  476. # this method is overridden by most concrete classes
  477. raise InferenceError(
  478. "No inference function for {node!r}.", node=self, context=context
  479. )
  480. def inferred(self):
  481. """Get a list of the inferred values.
  482. .. seealso:: :ref:`inference`
  483. :returns: The inferred values.
  484. :rtype: list
  485. """
  486. return list(self.infer())
  487. def instantiate_class(self):
  488. """Instantiate an instance of the defined class.
  489. .. note::
  490. On anything other than a :class:`ClassDef` this will return self.
  491. :returns: An instance of the defined class.
  492. :rtype: object
  493. """
  494. return self
  495. def has_base(self, node):
  496. """Check if this node inherits from the given type.
  497. :param node: The node defining the base to look for.
  498. Usually this is a :class:`Name` node.
  499. :type node: NodeNG
  500. """
  501. return False
  502. def callable(self):
  503. """Whether this node defines something that is callable.
  504. :returns: True if this defines something that is callable,
  505. False otherwise.
  506. :rtype: bool
  507. """
  508. return False
  509. def eq(self, value):
  510. return False
  511. def as_string(self) -> str:
  512. """Get the source code that this node represents."""
  513. return AsStringVisitor()(self)
  514. def repr_tree(
  515. self,
  516. ids=False,
  517. include_linenos=False,
  518. ast_state=False,
  519. indent=" ",
  520. max_depth=0,
  521. max_width=80,
  522. ) -> str:
  523. """Get a string representation of the AST from this node.
  524. :param ids: If true, includes the ids with the node type names.
  525. :type ids: bool
  526. :param include_linenos: If true, includes the line numbers and
  527. column offsets.
  528. :type include_linenos: bool
  529. :param ast_state: If true, includes information derived from
  530. the whole AST like local and global variables.
  531. :type ast_state: bool
  532. :param indent: A string to use to indent the output string.
  533. :type indent: str
  534. :param max_depth: If set to a positive integer, won't return
  535. nodes deeper than max_depth in the string.
  536. :type max_depth: int
  537. :param max_width: Attempt to format the output string to stay
  538. within this number of characters, but can exceed it under some
  539. circumstances. Only positive integer values are valid, the default is 80.
  540. :type max_width: int
  541. :returns: The string representation of the AST.
  542. :rtype: str
  543. """
  544. @_singledispatch
  545. def _repr_tree(node, result, done, cur_indent="", depth=1):
  546. """Outputs a representation of a non-tuple/list, non-node that's
  547. contained within an AST, including strings.
  548. """
  549. lines = pprint.pformat(
  550. node, width=max(max_width - len(cur_indent), 1)
  551. ).splitlines(True)
  552. result.append(lines[0])
  553. result.extend([cur_indent + line for line in lines[1:]])
  554. return len(lines) != 1
  555. # pylint: disable=unused-variable,useless-suppression; doesn't understand singledispatch
  556. @_repr_tree.register(tuple)
  557. @_repr_tree.register(list)
  558. def _repr_seq(node, result, done, cur_indent="", depth=1):
  559. """Outputs a representation of a sequence that's contained within an AST."""
  560. cur_indent += indent
  561. result.append("[")
  562. if not node:
  563. broken = False
  564. elif len(node) == 1:
  565. broken = _repr_tree(node[0], result, done, cur_indent, depth)
  566. elif len(node) == 2:
  567. broken = _repr_tree(node[0], result, done, cur_indent, depth)
  568. if not broken:
  569. result.append(", ")
  570. else:
  571. result.append(",\n")
  572. result.append(cur_indent)
  573. broken = _repr_tree(node[1], result, done, cur_indent, depth) or broken
  574. else:
  575. result.append("\n")
  576. result.append(cur_indent)
  577. for child in node[:-1]:
  578. _repr_tree(child, result, done, cur_indent, depth)
  579. result.append(",\n")
  580. result.append(cur_indent)
  581. _repr_tree(node[-1], result, done, cur_indent, depth)
  582. broken = True
  583. result.append("]")
  584. return broken
  585. # pylint: disable=unused-variable,useless-suppression; doesn't understand singledispatch
  586. @_repr_tree.register(NodeNG)
  587. def _repr_node(node, result, done, cur_indent="", depth=1):
  588. """Outputs a strings representation of an astroid node."""
  589. if node in done:
  590. result.append(
  591. indent + f"<Recursion on {type(node).__name__} with id={id(node)}"
  592. )
  593. return False
  594. done.add(node)
  595. if max_depth and depth > max_depth:
  596. result.append("...")
  597. return False
  598. depth += 1
  599. cur_indent += indent
  600. if ids:
  601. result.append(f"{type(node).__name__}<0x{id(node):x}>(\n")
  602. else:
  603. result.append(f"{type(node).__name__}(")
  604. fields = []
  605. if include_linenos:
  606. fields.extend(("lineno", "col_offset"))
  607. fields.extend(node._other_fields)
  608. fields.extend(node._astroid_fields)
  609. if ast_state:
  610. fields.extend(node._other_other_fields)
  611. if not fields:
  612. broken = False
  613. elif len(fields) == 1:
  614. result.append(f"{fields[0]}=")
  615. broken = _repr_tree(
  616. getattr(node, fields[0]), result, done, cur_indent, depth
  617. )
  618. else:
  619. result.append("\n")
  620. result.append(cur_indent)
  621. for field in fields[:-1]:
  622. result.append(f"{field}=")
  623. _repr_tree(getattr(node, field), result, done, cur_indent, depth)
  624. result.append(",\n")
  625. result.append(cur_indent)
  626. result.append(f"{fields[-1]}=")
  627. _repr_tree(getattr(node, fields[-1]), result, done, cur_indent, depth)
  628. broken = True
  629. result.append(")")
  630. return broken
  631. result: List[str] = []
  632. _repr_tree(self, result, set())
  633. return "".join(result)
  634. def bool_value(self, context=None):
  635. """Determine the boolean value of this node.
  636. The boolean value of a node can have three
  637. possible values:
  638. * False: For instance, empty data structures,
  639. False, empty strings, instances which return
  640. explicitly False from the __nonzero__ / __bool__
  641. method.
  642. * True: Most of constructs are True by default:
  643. classes, functions, modules etc
  644. * Uninferable: The inference engine is uncertain of the
  645. node's value.
  646. :returns: The boolean value of this node.
  647. :rtype: bool or Uninferable
  648. """
  649. return util.Uninferable
  650. def op_precedence(self):
  651. # Look up by class name or default to highest precedence
  652. return OP_PRECEDENCE.get(self.__class__.__name__, len(OP_PRECEDENCE))
  653. def op_left_associative(self):
  654. # Everything is left associative except `**` and IfExp
  655. return True