core.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. import ast
  2. import html
  3. import os
  4. import sys
  5. from collections import defaultdict, Counter
  6. from enum import Enum
  7. from textwrap import dedent
  8. from types import FrameType, CodeType, TracebackType
  9. from typing import (
  10. Iterator, List, Tuple, Optional, NamedTuple,
  11. Any, Iterable, Callable, Union,
  12. Sequence)
  13. from typing import Mapping
  14. import executing
  15. from asttokens.util import Token
  16. from executing import only
  17. from pure_eval import Evaluator, is_expression_interesting
  18. from stack_data.utils import (
  19. truncate, unique_in_order, line_range,
  20. frame_and_lineno, iter_stack, collapse_repeated, group_by_key_func,
  21. cached_property, is_frame, _pygmented_with_ranges, assert_)
  22. RangeInLine = NamedTuple('RangeInLine',
  23. [('start', int),
  24. ('end', int),
  25. ('data', Any)])
  26. RangeInLine.__doc__ = """
  27. Represents a range of characters within one line of source code,
  28. and some associated data.
  29. Typically this will be converted to a pair of markers by markers_from_ranges.
  30. """
  31. MarkerInLine = NamedTuple('MarkerInLine',
  32. [('position', int),
  33. ('is_start', bool),
  34. ('string', str)])
  35. MarkerInLine.__doc__ = """
  36. A string that is meant to be inserted at a given position in a line of source code.
  37. For example, this could be an ANSI code or the opening or closing of an HTML tag.
  38. is_start should be True if this is the first of a pair such as the opening of an HTML tag.
  39. This will help to sort and insert markers correctly.
  40. Typically this would be created from a RangeInLine by markers_from_ranges.
  41. Then use Line.render to insert the markers correctly.
  42. """
  43. class BlankLines(Enum):
  44. """The values are intended to correspond to the following behaviour:
  45. HIDDEN: blank lines are not shown in the output
  46. VISIBLE: blank lines are visible in the output
  47. SINGLE: any consecutive blank lines are shown as a single blank line
  48. in the output. This option requires the line number to be shown.
  49. For a single blank line, the corresponding line number is shown.
  50. Two or more consecutive blank lines are shown as a single blank
  51. line in the output with a custom string shown instead of a
  52. specific line number.
  53. """
  54. HIDDEN = 1
  55. VISIBLE = 2
  56. SINGLE=3
  57. class Variable(
  58. NamedTuple('_Variable',
  59. [('name', str),
  60. ('nodes', Sequence[ast.AST]),
  61. ('value', Any)])
  62. ):
  63. """
  64. An expression that appears one or more times in source code and its associated value.
  65. This will usually be a variable but it can be any expression evaluated by pure_eval.
  66. - name is the source text of the expression.
  67. - nodes is a list of equivalent nodes representing the same expression.
  68. - value is the safely evaluated value of the expression.
  69. """
  70. __hash__ = object.__hash__
  71. __eq__ = object.__eq__
  72. class Source(executing.Source):
  73. """
  74. The source code of a single file and associated metadata.
  75. In addition to the attributes from the base class executing.Source,
  76. if .tree is not None, meaning this is valid Python code, objects have:
  77. - pieces: a list of Piece objects
  78. - tokens_by_lineno: a defaultdict(list) mapping line numbers to lists of tokens.
  79. Don't construct this class. Get an instance from frame_info.source.
  80. """
  81. @cached_property
  82. def pieces(self) -> List[range]:
  83. if not self.tree:
  84. return [
  85. range(i, i + 1)
  86. for i in range(1, len(self.lines) + 1)
  87. ]
  88. return list(self._clean_pieces())
  89. @cached_property
  90. def tokens_by_lineno(self) -> Mapping[int, List[Token]]:
  91. if not self.tree:
  92. raise AttributeError("This file doesn't contain valid Python, so .tokens_by_lineno doesn't exist")
  93. return group_by_key_func(
  94. self.asttokens().tokens,
  95. lambda tok: tok.start[0],
  96. )
  97. def _clean_pieces(self) -> Iterator[range]:
  98. pieces = self._raw_split_into_pieces(self.tree, 1, len(self.lines) + 1)
  99. pieces = [
  100. (start, end)
  101. for (start, end) in pieces
  102. if end > start
  103. ]
  104. # Combine overlapping pieces, i.e. consecutive pieces where the end of the first
  105. # is greater than the start of the second.
  106. # This can happen when two statements are on the same line separated by a semicolon.
  107. new_pieces = pieces[:1]
  108. for (start, end) in pieces[1:]:
  109. (last_start, last_end) = new_pieces[-1]
  110. if start < last_end:
  111. assert start == last_end - 1
  112. assert ';' in self.lines[start - 1]
  113. new_pieces[-1] = (last_start, end)
  114. else:
  115. new_pieces.append((start, end))
  116. pieces = new_pieces
  117. starts = [start for start, end in pieces[1:]]
  118. ends = [end for start, end in pieces[:-1]]
  119. if starts != ends:
  120. joins = list(map(set, zip(starts, ends)))
  121. mismatches = [s for s in joins if len(s) > 1]
  122. raise AssertionError("Pieces mismatches: %s" % mismatches)
  123. def is_blank(i):
  124. try:
  125. return not self.lines[i - 1].strip()
  126. except IndexError:
  127. return False
  128. for start, end in pieces:
  129. while is_blank(start):
  130. start += 1
  131. while is_blank(end - 1):
  132. end -= 1
  133. if start < end:
  134. yield range(start, end)
  135. def _raw_split_into_pieces(
  136. self,
  137. stmt: ast.AST,
  138. start: int,
  139. end: int,
  140. ) -> Iterator[Tuple[int, int]]:
  141. for name, body in ast.iter_fields(stmt):
  142. if (
  143. isinstance(body, list) and body and
  144. isinstance(body[0], (ast.stmt, ast.ExceptHandler, getattr(ast, 'match_case', ())))
  145. ):
  146. for rang, group in sorted(group_by_key_func(body, self.line_range).items()):
  147. sub_stmt = group[0]
  148. for inner_start, inner_end in self._raw_split_into_pieces(sub_stmt, *rang):
  149. if start < inner_start:
  150. yield start, inner_start
  151. if inner_start < inner_end:
  152. yield inner_start, inner_end
  153. start = inner_end
  154. yield start, end
  155. def line_range(self, node: ast.AST) -> Tuple[int, int]:
  156. return line_range(self.asttext(), node)
  157. class Options:
  158. """
  159. Configuration for FrameInfo, either in the constructor or the .stack_data classmethod.
  160. These all determine which Lines and gaps are produced by FrameInfo.lines.
  161. before and after are the number of pieces of context to include in a frame
  162. in addition to the executing piece.
  163. include_signature is whether to include the function signature as a piece in a frame.
  164. If a piece (other than the executing piece) has more than max_lines_per_piece lines,
  165. it will be truncated with a gap in the middle.
  166. """
  167. def __init__(
  168. self, *,
  169. before: int = 3,
  170. after: int = 1,
  171. include_signature: bool = False,
  172. max_lines_per_piece: int = 6,
  173. pygments_formatter=None,
  174. blank_lines = BlankLines.HIDDEN
  175. ):
  176. self.before = before
  177. self.after = after
  178. self.include_signature = include_signature
  179. self.max_lines_per_piece = max_lines_per_piece
  180. self.pygments_formatter = pygments_formatter
  181. self.blank_lines = blank_lines
  182. def __repr__(self):
  183. keys = sorted(self.__dict__)
  184. items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
  185. return "{}({})".format(type(self).__name__, ", ".join(items))
  186. class LineGap(object):
  187. """
  188. A singleton representing one or more lines of source code that were skipped
  189. in FrameInfo.lines.
  190. LINE_GAP can be created in two ways:
  191. - by truncating a piece of context that's too long.
  192. - immediately after the signature piece if Options.include_signature is true
  193. and the following piece isn't already part of the included pieces.
  194. """
  195. def __repr__(self):
  196. return "LINE_GAP"
  197. LINE_GAP = LineGap()
  198. class BlankLineRange:
  199. """
  200. Records the line number range for blank lines gaps between pieces.
  201. For a single blank line, begin_lineno == end_lineno.
  202. """
  203. def __init__(self, begin_lineno: int, end_lineno: int):
  204. self.begin_lineno = begin_lineno
  205. self.end_lineno = end_lineno
  206. class Line(object):
  207. """
  208. A single line of source code for a particular stack frame.
  209. Typically this is obtained from FrameInfo.lines.
  210. Since that list may also contain LINE_GAP, you should first check
  211. that this is really a Line before using it.
  212. Attributes:
  213. - frame_info
  214. - lineno: the 1-based line number within the file
  215. - text: the raw source of this line. For displaying text, see .render() instead.
  216. - leading_indent: the number of leading spaces that should probably be stripped.
  217. This attribute is set within FrameInfo.lines. If you construct this class
  218. directly you should probably set it manually (at least to 0).
  219. - is_current: whether this is the line currently being executed by the interpreter
  220. within this frame.
  221. - tokens: a list of source tokens in this line
  222. There are several helpers for constructing RangeInLines which can be converted to markers
  223. using markers_from_ranges which can be passed to .render():
  224. - token_ranges
  225. - variable_ranges
  226. - executing_node_ranges
  227. - range_from_node
  228. """
  229. def __init__(
  230. self,
  231. frame_info: 'FrameInfo',
  232. lineno: int,
  233. ):
  234. self.frame_info = frame_info
  235. self.lineno = lineno
  236. self.text = frame_info.source.lines[lineno - 1] # type: str
  237. self.leading_indent = None # type: Optional[int]
  238. def __repr__(self):
  239. return "<{self.__class__.__name__} {self.lineno} (current={self.is_current}) " \
  240. "{self.text!r} of {self.frame_info.filename}>".format(self=self)
  241. @property
  242. def is_current(self) -> bool:
  243. """
  244. Whether this is the line currently being executed by the interpreter
  245. within this frame.
  246. """
  247. return self.lineno == self.frame_info.lineno
  248. @property
  249. def tokens(self) -> List[Token]:
  250. """
  251. A list of source tokens in this line.
  252. The tokens are Token objects from asttokens:
  253. https://asttokens.readthedocs.io/en/latest/api-index.html#asttokens.util.Token
  254. """
  255. return self.frame_info.source.tokens_by_lineno[self.lineno]
  256. @cached_property
  257. def token_ranges(self) -> List[RangeInLine]:
  258. """
  259. A list of RangeInLines for each token in .tokens,
  260. where range.data is a Token object from asttokens:
  261. https://asttokens.readthedocs.io/en/latest/api-index.html#asttokens.util.Token
  262. """
  263. return [
  264. RangeInLine(
  265. token.start[1],
  266. token.end[1],
  267. token,
  268. )
  269. for token in self.tokens
  270. ]
  271. @cached_property
  272. def variable_ranges(self) -> List[RangeInLine]:
  273. """
  274. A list of RangeInLines for each Variable that appears at least partially in this line.
  275. The data attribute of the range is a pair (variable, node) where node is the particular
  276. AST node from the list variable.nodes that corresponds to this range.
  277. """
  278. return [
  279. self.range_from_node(node, (variable, node))
  280. for variable, node in self.frame_info.variables_by_lineno[self.lineno]
  281. ]
  282. @cached_property
  283. def executing_node_ranges(self) -> List[RangeInLine]:
  284. """
  285. A list of one or zero RangeInLines for the executing node of this frame.
  286. The list will have one element if the node can be found and it overlaps this line.
  287. """
  288. return self._raw_executing_node_ranges(
  289. self.frame_info._executing_node_common_indent
  290. )
  291. def _raw_executing_node_ranges(self, common_indent=0) -> List[RangeInLine]:
  292. ex = self.frame_info.executing
  293. node = ex.node
  294. if node:
  295. rang = self.range_from_node(node, ex, common_indent)
  296. if rang:
  297. return [rang]
  298. return []
  299. def range_from_node(
  300. self, node: ast.AST, data: Any, common_indent: int = 0
  301. ) -> Optional[RangeInLine]:
  302. """
  303. If the given node overlaps with this line, return a RangeInLine
  304. with the correct start and end and the given data.
  305. Otherwise, return None.
  306. """
  307. atext = self.frame_info.source.asttext()
  308. (start, range_start), (end, range_end) = atext.get_text_positions(node, padded=False)
  309. if not (start <= self.lineno <= end):
  310. return None
  311. if start != self.lineno:
  312. range_start = common_indent
  313. if end != self.lineno:
  314. range_end = len(self.text)
  315. if range_start == range_end == 0:
  316. # This is an empty line. If it were included, it would result
  317. # in a value of zero for the common indentation assigned to
  318. # a block of code.
  319. return None
  320. return RangeInLine(range_start, range_end, data)
  321. def render(
  322. self,
  323. markers: Iterable[MarkerInLine] = (),
  324. *,
  325. strip_leading_indent: bool = True,
  326. pygmented: bool = False,
  327. escape_html: bool = False
  328. ) -> str:
  329. """
  330. Produces a string for display consisting of .text
  331. with the .strings of each marker inserted at the correct positions.
  332. If strip_leading_indent is true (the default) then leading spaces
  333. common to all lines in this frame will be excluded.
  334. """
  335. if pygmented and self.frame_info.scope:
  336. assert_(not markers, ValueError("Cannot use pygmented with markers"))
  337. start_line, lines = self.frame_info._pygmented_scope_lines
  338. result = lines[self.lineno - start_line]
  339. if strip_leading_indent:
  340. result = result.replace(self.text[:self.leading_indent], "", 1)
  341. return result
  342. text = self.text
  343. # This just makes the loop below simpler
  344. markers = list(markers) + [MarkerInLine(position=len(text), is_start=False, string='')]
  345. markers.sort(key=lambda t: t[:2])
  346. parts = []
  347. if strip_leading_indent:
  348. start = self.leading_indent
  349. else:
  350. start = 0
  351. original_start = start
  352. for marker in markers:
  353. text_part = text[start:marker.position]
  354. if escape_html:
  355. text_part = html.escape(text_part)
  356. parts.append(text_part)
  357. parts.append(marker.string)
  358. # Ensure that start >= leading_indent
  359. start = max(marker.position, original_start)
  360. return ''.join(parts)
  361. def markers_from_ranges(
  362. ranges: Iterable[RangeInLine],
  363. converter: Callable[[RangeInLine], Optional[Tuple[str, str]]],
  364. ) -> List[MarkerInLine]:
  365. """
  366. Helper to create MarkerInLines given some RangeInLines.
  367. converter should be a function accepting a RangeInLine returning
  368. either None (which is ignored) or a pair of strings which
  369. are used to create two markers included in the returned list.
  370. """
  371. markers = []
  372. for rang in ranges:
  373. converted = converter(rang)
  374. if converted is None:
  375. continue
  376. start_string, end_string = converted
  377. if not (isinstance(start_string, str) and isinstance(end_string, str)):
  378. raise TypeError("converter should return None or a pair of strings")
  379. markers += [
  380. MarkerInLine(position=rang.start, is_start=True, string=start_string),
  381. MarkerInLine(position=rang.end, is_start=False, string=end_string),
  382. ]
  383. return markers
  384. def style_with_executing_node(style, modifier):
  385. from pygments.styles import get_style_by_name
  386. if isinstance(style, str):
  387. style = get_style_by_name(style)
  388. class NewStyle(style):
  389. for_executing_node = True
  390. styles = {
  391. **style.styles,
  392. **{
  393. k.ExecutingNode: v + " " + modifier
  394. for k, v in style.styles.items()
  395. }
  396. }
  397. return NewStyle
  398. class RepeatedFrames:
  399. """
  400. A sequence of consecutive stack frames which shouldn't be displayed because
  401. the same code and line number were repeated many times in the stack, e.g.
  402. because of deep recursion.
  403. Attributes:
  404. - frames: list of raw frame or traceback objects
  405. - frame_keys: list of tuples (frame.f_code, lineno) extracted from the frame objects.
  406. It's this information from the frames that is used to determine
  407. whether two frames should be considered similar (i.e. repeating).
  408. - description: A string briefly describing frame_keys
  409. """
  410. def __init__(
  411. self,
  412. frames: List[Union[FrameType, TracebackType]],
  413. frame_keys: List[Tuple[CodeType, int]],
  414. ):
  415. self.frames = frames
  416. self.frame_keys = frame_keys
  417. @cached_property
  418. def description(self) -> str:
  419. """
  420. A string briefly describing the repeated frames, e.g.
  421. my_function at line 10 (100 times)
  422. """
  423. counts = sorted(Counter(self.frame_keys).items(),
  424. key=lambda item: (-item[1], item[0][0].co_name))
  425. return ', '.join(
  426. '{name} at line {lineno} ({count} times)'.format(
  427. name=Source.for_filename(code.co_filename).code_qualname(code),
  428. lineno=lineno,
  429. count=count,
  430. )
  431. for (code, lineno), count in counts
  432. )
  433. def __repr__(self):
  434. return '<{self.__class__.__name__} {self.description}>'.format(self=self)
  435. class FrameInfo(object):
  436. """
  437. Information about a frame!
  438. Pass either a frame object or a traceback object,
  439. and optionally an Options object to configure.
  440. Or use the classmethod FrameInfo.stack_data() for an iterator of FrameInfo and
  441. RepeatedFrames objects.
  442. Attributes:
  443. - frame: an actual stack frame object, either frame_or_tb or frame_or_tb.tb_frame
  444. - options
  445. - code: frame.f_code
  446. - source: a Source object
  447. - filename: a hopefully absolute file path derived from code.co_filename
  448. - scope: the AST node of the innermost function, class or module being executed
  449. - lines: a list of Line/LineGap objects to display, determined by options
  450. - executing: an Executing object from the `executing` library, which has:
  451. - .node: the AST node being executed in this frame, or None if it's unknown
  452. - .statements: a set of one or more candidate statements (AST nodes, probably just one)
  453. currently being executed in this frame.
  454. - .code_qualname(): the __qualname__ of the function or class being executed,
  455. or just the code name.
  456. Properties returning one or more pieces of source code (ranges of lines):
  457. - scope_pieces: all the pieces in the scope
  458. - included_pieces: a subset of scope_pieces determined by options
  459. - executing_piece: the piece currently being executed in this frame
  460. Properties returning lists of Variable objects:
  461. - variables: all variables in the scope
  462. - variables_by_lineno: variables organised into lines
  463. - variables_in_lines: variables contained within FrameInfo.lines
  464. - variables_in_executing_piece: variables contained within FrameInfo.executing_piece
  465. """
  466. def __init__(
  467. self,
  468. frame_or_tb: Union[FrameType, TracebackType],
  469. options: Optional[Options] = None,
  470. ):
  471. self.executing = Source.executing(frame_or_tb)
  472. frame, self.lineno = frame_and_lineno(frame_or_tb)
  473. self.frame = frame
  474. self.code = frame.f_code
  475. self.options = options or Options() # type: Options
  476. self.source = self.executing.source # type: Source
  477. def __repr__(self):
  478. return "{self.__class__.__name__}({self.frame})".format(self=self)
  479. @classmethod
  480. def stack_data(
  481. cls,
  482. frame_or_tb: Union[FrameType, TracebackType],
  483. options: Optional[Options] = None,
  484. *,
  485. collapse_repeated_frames: bool = True
  486. ) -> Iterator[Union['FrameInfo', RepeatedFrames]]:
  487. """
  488. An iterator of FrameInfo and RepeatedFrames objects representing
  489. a full traceback or stack. Similar consecutive frames are collapsed into RepeatedFrames
  490. objects, so always check what type of object has been yielded.
  491. Pass either a frame object or a traceback object,
  492. and optionally an Options object to configure.
  493. """
  494. stack = list(iter_stack(frame_or_tb))
  495. # Reverse the stack from a frame so that it's in the same order
  496. # as the order from a traceback, which is the order of a printed
  497. # traceback when read top to bottom (most recent call last)
  498. if is_frame(frame_or_tb):
  499. stack = stack[::-1]
  500. def mapper(f):
  501. return cls(f, options)
  502. if not collapse_repeated_frames:
  503. yield from map(mapper, stack)
  504. return
  505. def _frame_key(x):
  506. frame, lineno = frame_and_lineno(x)
  507. return frame.f_code, lineno
  508. yield from collapse_repeated(
  509. stack,
  510. mapper=mapper,
  511. collapser=RepeatedFrames,
  512. key=_frame_key,
  513. )
  514. @cached_property
  515. def scope_pieces(self) -> List[range]:
  516. """
  517. All the pieces (ranges of lines) contained in this object's .scope,
  518. unless there is no .scope (because the source isn't valid Python syntax)
  519. in which case it returns all the pieces in the source file, each containing one line.
  520. """
  521. if not self.scope:
  522. return self.source.pieces
  523. scope_start, scope_end = self.source.line_range(self.scope)
  524. return [
  525. piece
  526. for piece in self.source.pieces
  527. if scope_start <= piece.start and piece.stop <= scope_end
  528. ]
  529. @cached_property
  530. def filename(self) -> str:
  531. """
  532. A hopefully absolute file path derived from .code.co_filename,
  533. the current working directory, and sys.path.
  534. Code based on ipython.
  535. """
  536. result = self.code.co_filename
  537. if (
  538. os.path.isabs(result) or
  539. (
  540. result.startswith("<") and
  541. result.endswith(">")
  542. )
  543. ):
  544. return result
  545. # Try to make the filename absolute by trying all
  546. # sys.path entries (which is also what linecache does)
  547. # as well as the current working directory
  548. for dirname in ["."] + list(sys.path):
  549. try:
  550. fullname = os.path.join(dirname, result)
  551. if os.path.isfile(fullname):
  552. return os.path.abspath(fullname)
  553. except Exception:
  554. # Just in case that sys.path contains very
  555. # strange entries...
  556. pass
  557. return result
  558. @cached_property
  559. def executing_piece(self) -> range:
  560. """
  561. The piece (range of lines) containing the line currently being executed
  562. by the interpreter in this frame.
  563. """
  564. return only(
  565. piece
  566. for piece in self.scope_pieces
  567. if self.lineno in piece
  568. )
  569. @cached_property
  570. def included_pieces(self) -> List[range]:
  571. """
  572. The list of pieces (ranges of lines) to display for this frame.
  573. Consists of .executing_piece, surrounding context pieces
  574. determined by .options.before and .options.after,
  575. and the function signature if a function is being executed and
  576. .options.include_signature is True (in which case this might not
  577. be a contiguous range of pieces).
  578. Always a subset of .scope_pieces.
  579. """
  580. scope_pieces = self.scope_pieces
  581. if not self.scope_pieces:
  582. return []
  583. pos = scope_pieces.index(self.executing_piece)
  584. pieces_start = max(0, pos - self.options.before)
  585. pieces_end = pos + 1 + self.options.after
  586. pieces = scope_pieces[pieces_start:pieces_end]
  587. if (
  588. self.options.include_signature
  589. and not self.code.co_name.startswith('<')
  590. and isinstance(self.scope, (ast.FunctionDef, ast.AsyncFunctionDef))
  591. and pieces_start > 0
  592. ):
  593. pieces.insert(0, scope_pieces[0])
  594. return pieces
  595. @cached_property
  596. def _executing_node_common_indent(self) -> int:
  597. """
  598. The common minimal indentation shared by the markers intended
  599. for an exception node that spans multiple lines.
  600. Intended to be used only internally.
  601. """
  602. indents = []
  603. lines = [line for line in self.lines if isinstance(line, Line)]
  604. for line in lines:
  605. for rang in line._raw_executing_node_ranges():
  606. begin_text = len(line.text) - len(line.text.lstrip())
  607. indent = max(rang.start, begin_text)
  608. indents.append(indent)
  609. if len(indents) <= 1:
  610. return 0
  611. return min(indents[1:])
  612. @cached_property
  613. def lines(self) -> List[Union[Line, LineGap, BlankLineRange]]:
  614. """
  615. A list of lines to display, determined by options.
  616. The objects yielded either have type Line, BlankLineRange
  617. or are the singleton LINE_GAP.
  618. Always check the type that you're dealing with when iterating.
  619. LINE_GAP can be created in two ways:
  620. - by truncating a piece of context that's too long, determined by
  621. .options.max_lines_per_piece
  622. - immediately after the signature piece if Options.include_signature is true
  623. and the following piece isn't already part of the included pieces.
  624. The Line objects are all within the ranges from .included_pieces.
  625. """
  626. pieces = self.included_pieces
  627. if not pieces:
  628. return []
  629. add_empty_lines = self.options.blank_lines in (BlankLines.VISIBLE, BlankLines.SINGLE)
  630. prev_piece = None
  631. result = []
  632. for i, piece in enumerate(pieces):
  633. if (
  634. i == 1
  635. and self.scope
  636. and pieces[0] == self.scope_pieces[0]
  637. and pieces[1] != self.scope_pieces[1]
  638. ):
  639. result.append(LINE_GAP)
  640. elif prev_piece and add_empty_lines and piece.start > prev_piece.stop:
  641. if self.options.blank_lines == BlankLines.SINGLE:
  642. result.append(BlankLineRange(prev_piece.stop, piece.start-1))
  643. else: # BlankLines.VISIBLE
  644. for lineno in range(prev_piece.stop, piece.start):
  645. result.append(Line(self, lineno))
  646. lines = [Line(self, i) for i in piece] # type: List[Line]
  647. if piece != self.executing_piece:
  648. lines = truncate(
  649. lines,
  650. max_length=self.options.max_lines_per_piece,
  651. middle=[LINE_GAP],
  652. )
  653. result.extend(lines)
  654. prev_piece = piece
  655. real_lines = [
  656. line
  657. for line in result
  658. if isinstance(line, Line)
  659. ]
  660. text = "\n".join(
  661. line.text
  662. for line in real_lines
  663. )
  664. dedented_lines = dedent(text).splitlines()
  665. leading_indent = len(real_lines[0].text) - len(dedented_lines[0])
  666. for line in real_lines:
  667. line.leading_indent = leading_indent
  668. return result
  669. @cached_property
  670. def scope(self) -> Optional[ast.AST]:
  671. """
  672. The AST node of the innermost function, class or module being executed.
  673. """
  674. if not self.source.tree or not self.executing.statements:
  675. return None
  676. stmt = list(self.executing.statements)[0]
  677. while True:
  678. # Get the parent first in case the original statement is already
  679. # a function definition, e.g. if we're calling a decorator
  680. # In that case we still want the surrounding scope, not that function
  681. stmt = stmt.parent
  682. if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Module)):
  683. return stmt
  684. @cached_property
  685. def _pygmented_scope_lines(self) -> Optional[Tuple[int, List[str]]]:
  686. # noinspection PyUnresolvedReferences
  687. from pygments.formatters import HtmlFormatter
  688. formatter = self.options.pygments_formatter
  689. scope = self.scope
  690. assert_(formatter, ValueError("Must set a pygments formatter in Options"))
  691. assert_(scope)
  692. if isinstance(formatter, HtmlFormatter):
  693. formatter.nowrap = True
  694. atext = self.source.asttext()
  695. node = self.executing.node
  696. if node and getattr(formatter.style, "for_executing_node", False):
  697. scope_start = atext.get_text_range(scope)[0]
  698. start, end = atext.get_text_range(node)
  699. start -= scope_start
  700. end -= scope_start
  701. ranges = [(start, end)]
  702. else:
  703. ranges = []
  704. code = atext.get_text(scope)
  705. lines = _pygmented_with_ranges(formatter, code, ranges)
  706. start_line = self.source.line_range(scope)[0]
  707. return start_line, lines
  708. @cached_property
  709. def variables(self) -> List[Variable]:
  710. """
  711. All Variable objects whose nodes are contained within .scope
  712. and whose values could be safely evaluated by pure_eval.
  713. """
  714. if not self.scope:
  715. return []
  716. evaluator = Evaluator.from_frame(self.frame)
  717. scope = self.scope
  718. node_values = [
  719. pair
  720. for pair in evaluator.find_expressions(scope)
  721. if is_expression_interesting(*pair)
  722. ] # type: List[Tuple[ast.AST, Any]]
  723. if isinstance(scope, (ast.FunctionDef, ast.AsyncFunctionDef)):
  724. for node in ast.walk(scope.args):
  725. if not isinstance(node, ast.arg):
  726. continue
  727. name = node.arg
  728. try:
  729. value = evaluator.names[name]
  730. except KeyError:
  731. pass
  732. else:
  733. node_values.append((node, value))
  734. # Group equivalent nodes together
  735. def get_text(n):
  736. if isinstance(n, ast.arg):
  737. return n.arg
  738. else:
  739. return self.source.asttext().get_text(n)
  740. def normalise_node(n):
  741. try:
  742. # Add parens to avoid syntax errors for multiline expressions
  743. return ast.parse('(' + get_text(n) + ')')
  744. except Exception:
  745. return n
  746. grouped = group_by_key_func(
  747. node_values,
  748. lambda nv: ast.dump(normalise_node(nv[0])),
  749. )
  750. result = []
  751. for group in grouped.values():
  752. nodes, values = zip(*group)
  753. value = values[0]
  754. text = get_text(nodes[0])
  755. if not text:
  756. continue
  757. result.append(Variable(text, nodes, value))
  758. return result
  759. @cached_property
  760. def variables_by_lineno(self) -> Mapping[int, List[Tuple[Variable, ast.AST]]]:
  761. """
  762. A mapping from 1-based line numbers to lists of pairs:
  763. - A Variable object
  764. - A specific AST node from the variable's .nodes list that's
  765. in the line at that line number.
  766. """
  767. result = defaultdict(list)
  768. for var in self.variables:
  769. for node in var.nodes:
  770. for lineno in range(*self.source.line_range(node)):
  771. result[lineno].append((var, node))
  772. return result
  773. @cached_property
  774. def variables_in_lines(self) -> List[Variable]:
  775. """
  776. A list of Variable objects contained within the lines returned by .lines.
  777. """
  778. return unique_in_order(
  779. var
  780. for line in self.lines
  781. if isinstance(line, Line)
  782. for var, node in self.variables_by_lineno[line.lineno]
  783. )
  784. @cached_property
  785. def variables_in_executing_piece(self) -> List[Variable]:
  786. """
  787. A list of Variable objects contained within the lines
  788. in the range returned by .executing_piece.
  789. """
  790. return unique_in_order(
  791. var
  792. for lineno in self.executing_piece
  793. for var, node in self.variables_by_lineno[lineno]
  794. )