parser.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
  2. # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
  3. """Code parsing for coverage.py."""
  4. import ast
  5. import collections
  6. import os
  7. import re
  8. import token
  9. import tokenize
  10. from coverage import env
  11. from coverage.backward import range # pylint: disable=redefined-builtin
  12. from coverage.backward import bytes_to_ints, string_class
  13. from coverage.bytecode import CodeObjects
  14. from coverage.debug import short_stack
  15. from coverage.misc import contract, new_contract, nice_pair, join_regex
  16. from coverage.misc import CoverageException, NoSource, NotPython
  17. from coverage.phystokens import compile_unicode, generate_tokens, neuter_encoding_declaration
  18. class PythonParser(object):
  19. """Parse code to find executable lines, excluded lines, etc.
  20. This information is all based on static analysis: no code execution is
  21. involved.
  22. """
  23. @contract(text='unicode|None')
  24. def __init__(self, text=None, filename=None, exclude=None):
  25. """
  26. Source can be provided as `text`, the text itself, or `filename`, from
  27. which the text will be read. Excluded lines are those that match
  28. `exclude`, a regex.
  29. """
  30. assert text or filename, "PythonParser needs either text or filename"
  31. self.filename = filename or "<code>"
  32. self.text = text
  33. if not self.text:
  34. from coverage.python import get_python_source
  35. try:
  36. self.text = get_python_source(self.filename)
  37. except IOError as err:
  38. raise NoSource(
  39. "No source for code: '%s': %s" % (self.filename, err)
  40. )
  41. self.exclude = exclude
  42. # The text lines of the parsed code.
  43. self.lines = self.text.split('\n')
  44. # The normalized line numbers of the statements in the code. Exclusions
  45. # are taken into account, and statements are adjusted to their first
  46. # lines.
  47. self.statements = set()
  48. # The normalized line numbers of the excluded lines in the code,
  49. # adjusted to their first lines.
  50. self.excluded = set()
  51. # The raw_* attributes are only used in this class, and in
  52. # lab/parser.py to show how this class is working.
  53. # The line numbers that start statements, as reported by the line
  54. # number table in the bytecode.
  55. self.raw_statements = set()
  56. # The raw line numbers of excluded lines of code, as marked by pragmas.
  57. self.raw_excluded = set()
  58. # The line numbers of class and function definitions.
  59. self.raw_classdefs = set()
  60. # The line numbers of docstring lines.
  61. self.raw_docstrings = set()
  62. # Internal detail, used by lab/parser.py.
  63. self.show_tokens = False
  64. # A dict mapping line numbers to lexical statement starts for
  65. # multi-line statements.
  66. self._multiline = {}
  67. # Lazily-created ByteParser, arc data, and missing arc descriptions.
  68. self._byte_parser = None
  69. self._all_arcs = None
  70. self._missing_arc_fragments = None
  71. @property
  72. def byte_parser(self):
  73. """Create a ByteParser on demand."""
  74. if not self._byte_parser:
  75. self._byte_parser = ByteParser(self.text, filename=self.filename)
  76. return self._byte_parser
  77. def lines_matching(self, *regexes):
  78. """Find the lines matching one of a list of regexes.
  79. Returns a set of line numbers, the lines that contain a match for one
  80. of the regexes in `regexes`. The entire line needn't match, just a
  81. part of it.
  82. """
  83. combined = join_regex(regexes)
  84. if env.PY2:
  85. # pylint: disable=redefined-variable-type
  86. combined = combined.decode("utf8")
  87. regex_c = re.compile(combined)
  88. matches = set()
  89. for i, ltext in enumerate(self.lines, start=1):
  90. if regex_c.search(ltext):
  91. matches.add(i)
  92. return matches
  93. def _raw_parse(self):
  94. """Parse the source to find the interesting facts about its lines.
  95. A handful of attributes are updated.
  96. """
  97. # Find lines which match an exclusion pattern.
  98. if self.exclude:
  99. self.raw_excluded = self.lines_matching(self.exclude)
  100. # Tokenize, to find excluded suites, to find docstrings, and to find
  101. # multi-line statements.
  102. indent = 0
  103. exclude_indent = 0
  104. excluding = False
  105. excluding_decorators = False
  106. prev_toktype = token.INDENT
  107. first_line = None
  108. empty = True
  109. first_on_line = True
  110. tokgen = generate_tokens(self.text)
  111. for toktype, ttext, (slineno, _), (elineno, _), ltext in tokgen:
  112. if self.show_tokens: # pragma: not covered
  113. print("%10s %5s %-20r %r" % (
  114. tokenize.tok_name.get(toktype, toktype),
  115. nice_pair((slineno, elineno)), ttext, ltext
  116. ))
  117. if toktype == token.INDENT:
  118. indent += 1
  119. elif toktype == token.DEDENT:
  120. indent -= 1
  121. elif toktype == token.NAME:
  122. if ttext == 'class':
  123. # Class definitions look like branches in the bytecode, so
  124. # we need to exclude them. The simplest way is to note the
  125. # lines with the 'class' keyword.
  126. self.raw_classdefs.add(slineno)
  127. elif toktype == token.OP:
  128. if ttext == ':':
  129. should_exclude = (elineno in self.raw_excluded) or excluding_decorators
  130. if not excluding and should_exclude:
  131. # Start excluding a suite. We trigger off of the colon
  132. # token so that the #pragma comment will be recognized on
  133. # the same line as the colon.
  134. self.raw_excluded.add(elineno)
  135. exclude_indent = indent
  136. excluding = True
  137. excluding_decorators = False
  138. elif ttext == '@' and first_on_line:
  139. # A decorator.
  140. if elineno in self.raw_excluded:
  141. excluding_decorators = True
  142. if excluding_decorators:
  143. self.raw_excluded.add(elineno)
  144. elif toktype == token.STRING and prev_toktype == token.INDENT:
  145. # Strings that are first on an indented line are docstrings.
  146. # (a trick from trace.py in the stdlib.) This works for
  147. # 99.9999% of cases. For the rest (!) see:
  148. # http://stackoverflow.com/questions/1769332/x/1769794#1769794
  149. self.raw_docstrings.update(range(slineno, elineno+1))
  150. elif toktype == token.NEWLINE:
  151. if first_line is not None and elineno != first_line:
  152. # We're at the end of a line, and we've ended on a
  153. # different line than the first line of the statement,
  154. # so record a multi-line range.
  155. for l in range(first_line, elineno+1):
  156. self._multiline[l] = first_line
  157. first_line = None
  158. first_on_line = True
  159. if ttext.strip() and toktype != tokenize.COMMENT:
  160. # A non-whitespace token.
  161. empty = False
  162. if first_line is None:
  163. # The token is not whitespace, and is the first in a
  164. # statement.
  165. first_line = slineno
  166. # Check whether to end an excluded suite.
  167. if excluding and indent <= exclude_indent:
  168. excluding = False
  169. if excluding:
  170. self.raw_excluded.add(elineno)
  171. first_on_line = False
  172. prev_toktype = toktype
  173. # Find the starts of the executable statements.
  174. if not empty:
  175. self.raw_statements.update(self.byte_parser._find_statements())
  176. def first_line(self, line):
  177. """Return the first line number of the statement including `line`."""
  178. return self._multiline.get(line, line)
  179. def first_lines(self, lines):
  180. """Map the line numbers in `lines` to the correct first line of the
  181. statement.
  182. Returns a set of the first lines.
  183. """
  184. return set(self.first_line(l) for l in lines)
  185. def translate_lines(self, lines):
  186. """Implement `FileReporter.translate_lines`."""
  187. return self.first_lines(lines)
  188. def translate_arcs(self, arcs):
  189. """Implement `FileReporter.translate_arcs`."""
  190. return [(self.first_line(a), self.first_line(b)) for (a, b) in arcs]
  191. def parse_source(self):
  192. """Parse source text to find executable lines, excluded lines, etc.
  193. Sets the .excluded and .statements attributes, normalized to the first
  194. line of multi-line statements.
  195. """
  196. try:
  197. self._raw_parse()
  198. except (tokenize.TokenError, IndentationError) as err:
  199. if hasattr(err, "lineno"):
  200. lineno = err.lineno # IndentationError
  201. else:
  202. lineno = err.args[1][0] # TokenError
  203. raise NotPython(
  204. u"Couldn't parse '%s' as Python source: '%s' at line %d" % (
  205. self.filename, err.args[0], lineno
  206. )
  207. )
  208. self.excluded = self.first_lines(self.raw_excluded)
  209. ignore = self.excluded | self.raw_docstrings
  210. starts = self.raw_statements - ignore
  211. self.statements = self.first_lines(starts) - ignore
  212. def arcs(self):
  213. """Get information about the arcs available in the code.
  214. Returns a set of line number pairs. Line numbers have been normalized
  215. to the first line of multi-line statements.
  216. """
  217. if self._all_arcs is None:
  218. self._analyze_ast()
  219. return self._all_arcs
  220. def _analyze_ast(self):
  221. """Run the AstArcAnalyzer and save its results.
  222. `_all_arcs` is the set of arcs in the code.
  223. """
  224. aaa = AstArcAnalyzer(self.text, self.raw_statements, self._multiline)
  225. aaa.analyze()
  226. self._all_arcs = set()
  227. for l1, l2 in aaa.arcs:
  228. fl1 = self.first_line(l1)
  229. fl2 = self.first_line(l2)
  230. if fl1 != fl2:
  231. self._all_arcs.add((fl1, fl2))
  232. self._missing_arc_fragments = aaa.missing_arc_fragments
  233. def exit_counts(self):
  234. """Get a count of exits from that each line.
  235. Excluded lines are excluded.
  236. """
  237. exit_counts = collections.defaultdict(int)
  238. for l1, l2 in self.arcs():
  239. if l1 < 0:
  240. # Don't ever report -1 as a line number
  241. continue
  242. if l1 in self.excluded:
  243. # Don't report excluded lines as line numbers.
  244. continue
  245. if l2 in self.excluded:
  246. # Arcs to excluded lines shouldn't count.
  247. continue
  248. exit_counts[l1] += 1
  249. # Class definitions have one extra exit, so remove one for each:
  250. for l in self.raw_classdefs:
  251. # Ensure key is there: class definitions can include excluded lines.
  252. if l in exit_counts:
  253. exit_counts[l] -= 1
  254. return exit_counts
  255. def missing_arc_description(self, start, end, executed_arcs=None):
  256. """Provide an English sentence describing a missing arc."""
  257. if self._missing_arc_fragments is None:
  258. self._analyze_ast()
  259. actual_start = start
  260. if (
  261. executed_arcs and
  262. end < 0 and end == -start and
  263. (end, start) not in executed_arcs and
  264. (end, start) in self._missing_arc_fragments
  265. ):
  266. # It's a one-line callable, and we never even started it,
  267. # and we have a message about not starting it.
  268. start, end = end, start
  269. fragment_pairs = self._missing_arc_fragments.get((start, end), [(None, None)])
  270. msgs = []
  271. for fragment_pair in fragment_pairs:
  272. smsg, emsg = fragment_pair
  273. if emsg is None:
  274. if end < 0:
  275. # Hmm, maybe we have a one-line callable, let's check.
  276. if (-end, end) in self._missing_arc_fragments:
  277. return self.missing_arc_description(-end, end)
  278. emsg = "didn't jump to the function exit"
  279. else:
  280. emsg = "didn't jump to line {lineno}"
  281. emsg = emsg.format(lineno=end)
  282. msg = "line {start} {emsg}".format(start=actual_start, emsg=emsg)
  283. if smsg is not None:
  284. msg += ", because {smsg}".format(smsg=smsg.format(lineno=actual_start))
  285. msgs.append(msg)
  286. return " or ".join(msgs)
  287. class ByteParser(object):
  288. """Parse bytecode to understand the structure of code."""
  289. @contract(text='unicode')
  290. def __init__(self, text, code=None, filename=None):
  291. self.text = text
  292. if code:
  293. self.code = code
  294. else:
  295. try:
  296. self.code = compile_unicode(text, filename, "exec")
  297. except SyntaxError as synerr:
  298. raise NotPython(
  299. u"Couldn't parse '%s' as Python source: '%s' at line %d" % (
  300. filename, synerr.msg, synerr.lineno
  301. )
  302. )
  303. # Alternative Python implementations don't always provide all the
  304. # attributes on code objects that we need to do the analysis.
  305. for attr in ['co_lnotab', 'co_firstlineno', 'co_consts']:
  306. if not hasattr(self.code, attr):
  307. raise CoverageException(
  308. "This implementation of Python doesn't support code analysis.\n"
  309. "Run coverage.py under CPython for this command."
  310. )
  311. def child_parsers(self):
  312. """Iterate over all the code objects nested within this one.
  313. The iteration includes `self` as its first value.
  314. """
  315. children = CodeObjects(self.code)
  316. return (ByteParser(self.text, code=c) for c in children)
  317. def _bytes_lines(self):
  318. """Map byte offsets to line numbers in `code`.
  319. Uses co_lnotab described in Python/compile.c to map byte offsets to
  320. line numbers. Produces a sequence: (b0, l0), (b1, l1), ...
  321. Only byte offsets that correspond to line numbers are included in the
  322. results.
  323. """
  324. # Adapted from dis.py in the standard library.
  325. byte_increments = bytes_to_ints(self.code.co_lnotab[0::2])
  326. line_increments = bytes_to_ints(self.code.co_lnotab[1::2])
  327. last_line_num = None
  328. line_num = self.code.co_firstlineno
  329. byte_num = 0
  330. for byte_incr, line_incr in zip(byte_increments, line_increments):
  331. if byte_incr:
  332. if line_num != last_line_num:
  333. yield (byte_num, line_num)
  334. last_line_num = line_num
  335. byte_num += byte_incr
  336. line_num += line_incr
  337. if line_num != last_line_num:
  338. yield (byte_num, line_num)
  339. def _find_statements(self):
  340. """Find the statements in `self.code`.
  341. Produce a sequence of line numbers that start statements. Recurses
  342. into all code objects reachable from `self.code`.
  343. """
  344. for bp in self.child_parsers():
  345. # Get all of the lineno information from this code.
  346. for _, l in bp._bytes_lines():
  347. yield l
  348. #
  349. # AST analysis
  350. #
  351. class LoopBlock(object):
  352. """A block on the block stack representing a `for` or `while` loop."""
  353. def __init__(self, start):
  354. self.start = start
  355. self.break_exits = set()
  356. class FunctionBlock(object):
  357. """A block on the block stack representing a function definition."""
  358. def __init__(self, start, name):
  359. self.start = start
  360. self.name = name
  361. class TryBlock(object):
  362. """A block on the block stack representing a `try` block."""
  363. def __init__(self, handler_start=None, final_start=None):
  364. self.handler_start = handler_start
  365. self.final_start = final_start
  366. self.break_from = set()
  367. self.continue_from = set()
  368. self.return_from = set()
  369. self.raise_from = set()
  370. class ArcStart(collections.namedtuple("Arc", "lineno, cause")):
  371. """The information needed to start an arc.
  372. `lineno` is the line number the arc starts from. `cause` is a fragment
  373. used as the startmsg for AstArcAnalyzer.missing_arc_fragments.
  374. """
  375. def __new__(cls, lineno, cause=None):
  376. return super(ArcStart, cls).__new__(cls, lineno, cause)
  377. # Define contract words that PyContract doesn't have.
  378. # ArcStarts is for a list or set of ArcStart's.
  379. new_contract('ArcStarts', lambda seq: all(isinstance(x, ArcStart) for x in seq))
  380. class AstArcAnalyzer(object):
  381. """Analyze source text with an AST to find executable code paths."""
  382. @contract(text='unicode', statements=set)
  383. def __init__(self, text, statements, multiline):
  384. self.root_node = ast.parse(neuter_encoding_declaration(text))
  385. # TODO: I think this is happening in too many places.
  386. self.statements = set(multiline.get(l, l) for l in statements)
  387. self.multiline = multiline
  388. if int(os.environ.get("COVERAGE_ASTDUMP", 0)): # pragma: debugging
  389. # Dump the AST so that failing tests have helpful output.
  390. print("Statements: {}".format(self.statements))
  391. print("Multiline map: {}".format(self.multiline))
  392. ast_dump(self.root_node)
  393. self.arcs = set()
  394. # A map from arc pairs to a pair of sentence fragments: (startmsg, endmsg).
  395. # For an arc from line 17, they should be usable like:
  396. # "Line 17 {endmsg}, because {startmsg}"
  397. self.missing_arc_fragments = collections.defaultdict(list)
  398. self.block_stack = []
  399. self.debug = bool(int(os.environ.get("COVERAGE_TRACK_ARCS", 0)))
  400. def analyze(self):
  401. """Examine the AST tree from `root_node` to determine possible arcs.
  402. This sets the `arcs` attribute to be a set of (from, to) line number
  403. pairs.
  404. """
  405. for node in ast.walk(self.root_node):
  406. node_name = node.__class__.__name__
  407. code_object_handler = getattr(self, "_code_object__" + node_name, None)
  408. if code_object_handler is not None:
  409. code_object_handler(node)
  410. def add_arc(self, start, end, smsg=None, emsg=None):
  411. """Add an arc, including message fragments to use if it is missing."""
  412. if self.debug:
  413. print("\nAdding arc: ({}, {}): {!r}, {!r}".format(start, end, smsg, emsg))
  414. print(short_stack(limit=6))
  415. self.arcs.add((start, end))
  416. if smsg is not None or emsg is not None:
  417. self.missing_arc_fragments[(start, end)].append((smsg, emsg))
  418. def nearest_blocks(self):
  419. """Yield the blocks in nearest-to-farthest order."""
  420. return reversed(self.block_stack)
  421. @contract(returns=int)
  422. def line_for_node(self, node):
  423. """What is the right line number to use for this node?
  424. This dispatches to _line__Node functions where needed.
  425. """
  426. node_name = node.__class__.__name__
  427. handler = getattr(self, "_line__" + node_name, None)
  428. if handler is not None:
  429. return handler(node)
  430. else:
  431. return node.lineno
  432. def _line__Assign(self, node):
  433. return self.line_for_node(node.value)
  434. def _line__Dict(self, node):
  435. # Python 3.5 changed how dict literals are made.
  436. if env.PYVERSION >= (3, 5) and node.keys:
  437. if node.keys[0] is not None:
  438. return node.keys[0].lineno
  439. else:
  440. # Unpacked dict literals `{**{'a':1}}` have None as the key,
  441. # use the value in that case.
  442. return node.values[0].lineno
  443. else:
  444. return node.lineno
  445. def _line__List(self, node):
  446. if node.elts:
  447. return self.line_for_node(node.elts[0])
  448. else:
  449. return node.lineno
  450. def _line__Module(self, node):
  451. if node.body:
  452. return self.line_for_node(node.body[0])
  453. else:
  454. # Modules have no line number, they always start at 1.
  455. return 1
  456. OK_TO_DEFAULT = set([
  457. "Assign", "Assert", "AugAssign", "Delete", "Exec", "Expr", "Global",
  458. "Import", "ImportFrom", "Nonlocal", "Pass", "Print",
  459. ])
  460. @contract(returns='ArcStarts')
  461. def add_arcs(self, node):
  462. """Add the arcs for `node`.
  463. Return a set of ArcStarts, exits from this node to the next.
  464. """
  465. node_name = node.__class__.__name__
  466. handler = getattr(self, "_handle__" + node_name, None)
  467. if handler is not None:
  468. return handler(node)
  469. if 0:
  470. node_name = node.__class__.__name__
  471. if node_name not in self.OK_TO_DEFAULT:
  472. print("*** Unhandled: {0}".format(node))
  473. return set([ArcStart(self.line_for_node(node), cause=None)])
  474. @contract(returns='ArcStarts')
  475. def add_body_arcs(self, body, from_start=None, prev_starts=None):
  476. """Add arcs for the body of a compound statement.
  477. `body` is the body node. `from_start` is a single `ArcStart` that can
  478. be the previous line in flow before this body. `prev_starts` is a set
  479. of ArcStarts that can be the previous line. Only one of them should be
  480. given.
  481. Returns a set of ArcStarts, the exits from this body.
  482. """
  483. if prev_starts is None:
  484. prev_starts = set([from_start])
  485. for body_node in body:
  486. lineno = self.line_for_node(body_node)
  487. first_line = self.multiline.get(lineno, lineno)
  488. if first_line not in self.statements:
  489. continue
  490. for prev_start in prev_starts:
  491. self.add_arc(prev_start.lineno, lineno, prev_start.cause)
  492. prev_starts = self.add_arcs(body_node)
  493. return prev_starts
  494. def is_constant_expr(self, node):
  495. """Is this a compile-time constant?"""
  496. node_name = node.__class__.__name__
  497. if node_name in ["NameConstant", "Num"]:
  498. return True
  499. elif node_name == "Name":
  500. if env.PY3 and node.id in ["True", "False", "None"]:
  501. return True
  502. return False
  503. # tests to write:
  504. # TODO: while EXPR:
  505. # TODO: while False:
  506. # TODO: listcomps hidden deep in other expressions
  507. # TODO: listcomps hidden in lists: x = [[i for i in range(10)]]
  508. # TODO: nested function definitions
  509. @contract(exits='ArcStarts')
  510. def process_break_exits(self, exits):
  511. """Add arcs due to jumps from `exits` being breaks."""
  512. for block in self.nearest_blocks():
  513. if isinstance(block, LoopBlock):
  514. block.break_exits.update(exits)
  515. break
  516. elif isinstance(block, TryBlock) and block.final_start is not None:
  517. block.break_from.update(exits)
  518. break
  519. @contract(exits='ArcStarts')
  520. def process_continue_exits(self, exits):
  521. """Add arcs due to jumps from `exits` being continues."""
  522. for block in self.nearest_blocks():
  523. if isinstance(block, LoopBlock):
  524. for xit in exits:
  525. self.add_arc(xit.lineno, block.start, xit.cause)
  526. break
  527. elif isinstance(block, TryBlock) and block.final_start is not None:
  528. block.continue_from.update(exits)
  529. break
  530. @contract(exits='ArcStarts')
  531. def process_raise_exits(self, exits):
  532. """Add arcs due to jumps from `exits` being raises."""
  533. for block in self.nearest_blocks():
  534. if isinstance(block, TryBlock):
  535. if block.handler_start is not None:
  536. for xit in exits:
  537. self.add_arc(xit.lineno, block.handler_start, xit.cause)
  538. break
  539. elif block.final_start is not None:
  540. block.raise_from.update(exits)
  541. break
  542. elif isinstance(block, FunctionBlock):
  543. for xit in exits:
  544. self.add_arc(
  545. xit.lineno, -block.start, xit.cause,
  546. "didn't except from function '{0}'".format(block.name),
  547. )
  548. break
  549. @contract(exits='ArcStarts')
  550. def process_return_exits(self, exits):
  551. """Add arcs due to jumps from `exits` being returns."""
  552. for block in self.nearest_blocks():
  553. if isinstance(block, TryBlock) and block.final_start is not None:
  554. block.return_from.update(exits)
  555. break
  556. elif isinstance(block, FunctionBlock):
  557. for xit in exits:
  558. self.add_arc(
  559. xit.lineno, -block.start, xit.cause,
  560. "didn't return from function '{0}'".format(block.name),
  561. )
  562. break
  563. ## Handlers
  564. @contract(returns='ArcStarts')
  565. def _handle__Break(self, node):
  566. here = self.line_for_node(node)
  567. break_start = ArcStart(here, cause="the break on line {lineno} wasn't executed")
  568. self.process_break_exits([break_start])
  569. return set()
  570. @contract(returns='ArcStarts')
  571. def _handle_decorated(self, node):
  572. """Add arcs for things that can be decorated (classes and functions)."""
  573. last = self.line_for_node(node)
  574. if node.decorator_list:
  575. for dec_node in node.decorator_list:
  576. dec_start = self.line_for_node(dec_node)
  577. if dec_start != last:
  578. self.add_arc(last, dec_start)
  579. last = dec_start
  580. # The definition line may have been missed, but we should have it
  581. # in `self.statements`. For some constructs, `line_for_node` is
  582. # not what we'd think of as the first line in the statement, so map
  583. # it to the first one.
  584. body_start = self.line_for_node(node.body[0])
  585. body_start = self.multiline.get(body_start, body_start)
  586. for lineno in range(last+1, body_start):
  587. if lineno in self.statements:
  588. self.add_arc(last, lineno)
  589. last = lineno
  590. # The body is handled in collect_arcs.
  591. return set([ArcStart(last, cause=None)])
  592. _handle__ClassDef = _handle_decorated
  593. @contract(returns='ArcStarts')
  594. def _handle__Continue(self, node):
  595. here = self.line_for_node(node)
  596. continue_start = ArcStart(here, cause="the continue on line {lineno} wasn't executed")
  597. self.process_continue_exits([continue_start])
  598. return set()
  599. @contract(returns='ArcStarts')
  600. def _handle__For(self, node):
  601. start = self.line_for_node(node.iter)
  602. self.block_stack.append(LoopBlock(start=start))
  603. from_start = ArcStart(start, cause="the loop on line {lineno} never started")
  604. exits = self.add_body_arcs(node.body, from_start=from_start)
  605. # Any exit from the body will go back to the top of the loop.
  606. for xit in exits:
  607. self.add_arc(xit.lineno, start, xit.cause)
  608. my_block = self.block_stack.pop()
  609. exits = my_block.break_exits
  610. from_start = ArcStart(start, cause="the loop on line {lineno} didn't complete")
  611. if node.orelse:
  612. else_exits = self.add_body_arcs(node.orelse, from_start=from_start)
  613. exits |= else_exits
  614. else:
  615. # no else clause: exit from the for line.
  616. exits.add(from_start)
  617. return exits
  618. _handle__AsyncFor = _handle__For
  619. _handle__FunctionDef = _handle_decorated
  620. _handle__AsyncFunctionDef = _handle_decorated
  621. @contract(returns='ArcStarts')
  622. def _handle__If(self, node):
  623. start = self.line_for_node(node.test)
  624. from_start = ArcStart(start, cause="the condition on line {lineno} was never true")
  625. exits = self.add_body_arcs(node.body, from_start=from_start)
  626. from_start = ArcStart(start, cause="the condition on line {lineno} was never false")
  627. exits |= self.add_body_arcs(node.orelse, from_start=from_start)
  628. return exits
  629. @contract(returns='ArcStarts')
  630. def _handle__Raise(self, node):
  631. here = self.line_for_node(node)
  632. raise_start = ArcStart(here, cause="the raise on line {lineno} wasn't executed")
  633. self.process_raise_exits([raise_start])
  634. # `raise` statement jumps away, no exits from here.
  635. return set()
  636. @contract(returns='ArcStarts')
  637. def _handle__Return(self, node):
  638. here = self.line_for_node(node)
  639. return_start = ArcStart(here, cause="the return on line {lineno} wasn't executed")
  640. self.process_return_exits([return_start])
  641. # `return` statement jumps away, no exits from here.
  642. return set()
  643. @contract(returns='ArcStarts')
  644. def _handle__Try(self, node):
  645. if node.handlers:
  646. handler_start = self.line_for_node(node.handlers[0])
  647. else:
  648. handler_start = None
  649. if node.finalbody:
  650. final_start = self.line_for_node(node.finalbody[0])
  651. else:
  652. final_start = None
  653. try_block = TryBlock(handler_start=handler_start, final_start=final_start)
  654. self.block_stack.append(try_block)
  655. start = self.line_for_node(node)
  656. exits = self.add_body_arcs(node.body, from_start=ArcStart(start, cause=None))
  657. # We're done with the `try` body, so this block no longer handles
  658. # exceptions. We keep the block so the `finally` clause can pick up
  659. # flows from the handlers and `else` clause.
  660. if node.finalbody:
  661. try_block.handler_start = None
  662. if node.handlers:
  663. # If there are `except` clauses, then raises in the try body
  664. # will already jump to them. Start this set over for raises in
  665. # `except` and `else`.
  666. try_block.raise_from = set([])
  667. else:
  668. self.block_stack.pop()
  669. handler_exits = set()
  670. if node.handlers:
  671. last_handler_start = None
  672. for handler_node in node.handlers:
  673. handler_start = self.line_for_node(handler_node)
  674. if last_handler_start is not None:
  675. self.add_arc(last_handler_start, handler_start)
  676. last_handler_start = handler_start
  677. from_cause = "the exception caught by line {lineno} didn't happen"
  678. from_start = ArcStart(handler_start, cause=from_cause)
  679. handler_exits |= self.add_body_arcs(handler_node.body, from_start=from_start)
  680. if node.orelse:
  681. exits = self.add_body_arcs(node.orelse, prev_starts=exits)
  682. exits |= handler_exits
  683. if node.finalbody:
  684. self.block_stack.pop()
  685. final_from = ( # You can get to the `finally` clause from:
  686. exits | # the exits of the body or `else` clause,
  687. try_block.break_from | # or a `break`,
  688. try_block.continue_from | # or a `continue`,
  689. try_block.raise_from | # or a `raise`,
  690. try_block.return_from # or a `return`.
  691. )
  692. exits = self.add_body_arcs(node.finalbody, prev_starts=final_from)
  693. if try_block.break_from:
  694. break_exits = self._combine_finally_starts(try_block.break_from, exits)
  695. self.process_break_exits(break_exits)
  696. if try_block.continue_from:
  697. continue_exits = self._combine_finally_starts(try_block.continue_from, exits)
  698. self.process_continue_exits(continue_exits)
  699. if try_block.raise_from:
  700. raise_exits = self._combine_finally_starts(try_block.raise_from, exits)
  701. self.process_raise_exits(raise_exits)
  702. if try_block.return_from:
  703. return_exits = self._combine_finally_starts(try_block.return_from, exits)
  704. self.process_return_exits(return_exits)
  705. return exits
  706. def _combine_finally_starts(self, starts, exits):
  707. """Helper for building the cause of `finally` branches."""
  708. causes = []
  709. for lineno, cause in sorted(starts):
  710. if cause is not None:
  711. causes.append(cause.format(lineno=lineno))
  712. cause = " or ".join(causes)
  713. exits = set(ArcStart(ex.lineno, cause) for ex in exits)
  714. return exits
  715. @contract(returns='ArcStarts')
  716. def _handle__TryExcept(self, node):
  717. # Python 2.7 uses separate TryExcept and TryFinally nodes. If we get
  718. # TryExcept, it means there was no finally, so fake it, and treat as
  719. # a general Try node.
  720. node.finalbody = []
  721. return self._handle__Try(node)
  722. @contract(returns='ArcStarts')
  723. def _handle__TryFinally(self, node):
  724. # Python 2.7 uses separate TryExcept and TryFinally nodes. If we get
  725. # TryFinally, see if there's a TryExcept nested inside. If so, merge
  726. # them. Otherwise, fake fields to complete a Try node.
  727. node.handlers = []
  728. node.orelse = []
  729. first = node.body[0]
  730. if first.__class__.__name__ == "TryExcept" and node.lineno == first.lineno:
  731. assert len(node.body) == 1
  732. node.body = first.body
  733. node.handlers = first.handlers
  734. node.orelse = first.orelse
  735. return self._handle__Try(node)
  736. @contract(returns='ArcStarts')
  737. def _handle__While(self, node):
  738. constant_test = self.is_constant_expr(node.test)
  739. start = to_top = self.line_for_node(node.test)
  740. if constant_test:
  741. to_top = self.line_for_node(node.body[0])
  742. self.block_stack.append(LoopBlock(start=start))
  743. from_start = ArcStart(start, cause="the condition on line {lineno} was never true")
  744. exits = self.add_body_arcs(node.body, from_start=from_start)
  745. for xit in exits:
  746. self.add_arc(xit.lineno, to_top, xit.cause)
  747. exits = set()
  748. my_block = self.block_stack.pop()
  749. exits.update(my_block.break_exits)
  750. from_start = ArcStart(start, cause="the condition on line {lineno} was never false")
  751. if node.orelse:
  752. else_exits = self.add_body_arcs(node.orelse, from_start=from_start)
  753. exits |= else_exits
  754. else:
  755. # No `else` clause: you can exit from the start.
  756. if not constant_test:
  757. exits.add(from_start)
  758. return exits
  759. @contract(returns='ArcStarts')
  760. def _handle__With(self, node):
  761. start = self.line_for_node(node)
  762. exits = self.add_body_arcs(node.body, from_start=ArcStart(start))
  763. return exits
  764. _handle__AsyncWith = _handle__With
  765. def _code_object__Module(self, node):
  766. start = self.line_for_node(node)
  767. if node.body:
  768. exits = self.add_body_arcs(node.body, from_start=ArcStart(-start))
  769. for xit in exits:
  770. self.add_arc(xit.lineno, -start, xit.cause, "didn't exit the module")
  771. else:
  772. # Empty module.
  773. self.add_arc(-start, start)
  774. self.add_arc(start, -start)
  775. def _code_object__FunctionDef(self, node):
  776. start = self.line_for_node(node)
  777. self.block_stack.append(FunctionBlock(start=start, name=node.name))
  778. exits = self.add_body_arcs(node.body, from_start=ArcStart(-start))
  779. self.process_return_exits(exits)
  780. self.block_stack.pop()
  781. _code_object__AsyncFunctionDef = _code_object__FunctionDef
  782. def _code_object__ClassDef(self, node):
  783. start = self.line_for_node(node)
  784. self.add_arc(-start, start)
  785. exits = self.add_body_arcs(node.body, from_start=ArcStart(start))
  786. for xit in exits:
  787. self.add_arc(
  788. xit.lineno, -start, xit.cause,
  789. "didn't exit the body of class '{0}'".format(node.name),
  790. )
  791. def _make_oneline_code_method(noun): # pylint: disable=no-self-argument
  792. """A function to make methods for online callable _code_object__ methods."""
  793. def _code_object__oneline_callable(self, node):
  794. start = self.line_for_node(node)
  795. self.add_arc(-start, start, None, "didn't run the {0} on line {1}".format(noun, start))
  796. self.add_arc(
  797. start, -start, None,
  798. "didn't finish the {0} on line {1}".format(noun, start),
  799. )
  800. return _code_object__oneline_callable
  801. _code_object__Lambda = _make_oneline_code_method("lambda")
  802. _code_object__GeneratorExp = _make_oneline_code_method("generator expression")
  803. _code_object__DictComp = _make_oneline_code_method("dictionary comprehension")
  804. _code_object__SetComp = _make_oneline_code_method("set comprehension")
  805. if env.PY3:
  806. _code_object__ListComp = _make_oneline_code_method("list comprehension")
  807. SKIP_DUMP_FIELDS = ["ctx"]
  808. def _is_simple_value(value):
  809. """Is `value` simple enough to be displayed on a single line?"""
  810. return (
  811. value in [None, [], (), {}, set()] or
  812. isinstance(value, (string_class, int, float))
  813. )
  814. # TODO: a test of ast_dump?
  815. def ast_dump(node, depth=0):
  816. """Dump the AST for `node`.
  817. This recursively walks the AST, printing a readable version.
  818. """
  819. indent = " " * depth
  820. if not isinstance(node, ast.AST):
  821. print("{0}<{1} {2!r}>".format(indent, node.__class__.__name__, node))
  822. return
  823. lineno = getattr(node, "lineno", None)
  824. if lineno is not None:
  825. linemark = " @ {0}".format(node.lineno)
  826. else:
  827. linemark = ""
  828. head = "{0}<{1}{2}".format(indent, node.__class__.__name__, linemark)
  829. named_fields = [
  830. (name, value)
  831. for name, value in ast.iter_fields(node)
  832. if name not in SKIP_DUMP_FIELDS
  833. ]
  834. if not named_fields:
  835. print("{0}>".format(head))
  836. elif len(named_fields) == 1 and _is_simple_value(named_fields[0][1]):
  837. field_name, value = named_fields[0]
  838. print("{0} {1}: {2!r}>".format(head, field_name, value))
  839. else:
  840. print(head)
  841. if 0:
  842. print("{0}# mro: {1}".format(
  843. indent, ", ".join(c.__name__ for c in node.__class__.__mro__[1:]),
  844. ))
  845. next_indent = indent + " "
  846. for field_name, value in named_fields:
  847. prefix = "{0}{1}:".format(next_indent, field_name)
  848. if _is_simple_value(value):
  849. print("{0} {1!r}".format(prefix, value))
  850. elif isinstance(value, list):
  851. print("{0} [".format(prefix))
  852. for n in value:
  853. ast_dump(n, depth + 8)
  854. print("{0}]".format(next_indent))
  855. else:
  856. print(prefix)
  857. ast_dump(value, depth + 8)
  858. print("{0}>".format(indent))