parser.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  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, join_regex, new_contract, nice_pair, one_of
  16. from coverage.misc import NoSource, NotPython, StopEverything
  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. combined = combined.decode("utf8")
  86. regex_c = re.compile(combined)
  87. matches = set()
  88. for i, ltext in enumerate(self.lines, start=1):
  89. if regex_c.search(ltext):
  90. matches.add(i)
  91. return matches
  92. def _raw_parse(self):
  93. """Parse the source to find the interesting facts about its lines.
  94. A handful of attributes are updated.
  95. """
  96. # Find lines which match an exclusion pattern.
  97. if self.exclude:
  98. self.raw_excluded = self.lines_matching(self.exclude)
  99. # Tokenize, to find excluded suites, to find docstrings, and to find
  100. # multi-line statements.
  101. indent = 0
  102. exclude_indent = 0
  103. excluding = False
  104. excluding_decorators = False
  105. prev_toktype = token.INDENT
  106. first_line = None
  107. empty = True
  108. first_on_line = True
  109. tokgen = generate_tokens(self.text)
  110. for toktype, ttext, (slineno, _), (elineno, _), ltext in tokgen:
  111. if self.show_tokens: # pragma: debugging
  112. print("%10s %5s %-20r %r" % (
  113. tokenize.tok_name.get(toktype, toktype),
  114. nice_pair((slineno, elineno)), ttext, ltext
  115. ))
  116. if toktype == token.INDENT:
  117. indent += 1
  118. elif toktype == token.DEDENT:
  119. indent -= 1
  120. elif toktype == token.NAME:
  121. if ttext == 'class':
  122. # Class definitions look like branches in the bytecode, so
  123. # we need to exclude them. The simplest way is to note the
  124. # lines with the 'class' keyword.
  125. self.raw_classdefs.add(slineno)
  126. elif toktype == token.OP:
  127. if ttext == ':':
  128. should_exclude = (elineno in self.raw_excluded) or excluding_decorators
  129. if not excluding and should_exclude:
  130. # Start excluding a suite. We trigger off of the colon
  131. # token so that the #pragma comment will be recognized on
  132. # the same line as the colon.
  133. self.raw_excluded.add(elineno)
  134. exclude_indent = indent
  135. excluding = True
  136. excluding_decorators = False
  137. elif ttext == '@' and first_on_line:
  138. # A decorator.
  139. if elineno in self.raw_excluded:
  140. excluding_decorators = True
  141. if excluding_decorators:
  142. self.raw_excluded.add(elineno)
  143. elif toktype == token.STRING and prev_toktype == token.INDENT:
  144. # Strings that are first on an indented line are docstrings.
  145. # (a trick from trace.py in the stdlib.) This works for
  146. # 99.9999% of cases. For the rest (!) see:
  147. # http://stackoverflow.com/questions/1769332/x/1769794#1769794
  148. self.raw_docstrings.update(range(slineno, elineno+1))
  149. elif toktype == token.NEWLINE:
  150. if first_line is not None and elineno != first_line:
  151. # We're at the end of a line, and we've ended on a
  152. # different line than the first line of the statement,
  153. # so record a multi-line range.
  154. for l in range(first_line, elineno+1):
  155. self._multiline[l] = first_line
  156. first_line = None
  157. first_on_line = True
  158. if ttext.strip() and toktype != tokenize.COMMENT:
  159. # A non-whitespace token.
  160. empty = False
  161. if first_line is None:
  162. # The token is not whitespace, and is the first in a
  163. # statement.
  164. first_line = slineno
  165. # Check whether to end an excluded suite.
  166. if excluding and indent <= exclude_indent:
  167. excluding = False
  168. if excluding:
  169. self.raw_excluded.add(elineno)
  170. first_on_line = False
  171. prev_toktype = toktype
  172. # Find the starts of the executable statements.
  173. if not empty:
  174. self.raw_statements.update(self.byte_parser._find_statements())
  175. def first_line(self, line):
  176. """Return the first line number of the statement including `line`."""
  177. return self._multiline.get(line, line)
  178. def first_lines(self, lines):
  179. """Map the line numbers in `lines` to the correct first line of the
  180. statement.
  181. Returns a set of the first lines.
  182. """
  183. return set(self.first_line(l) for l in lines)
  184. def translate_lines(self, lines):
  185. """Implement `FileReporter.translate_lines`."""
  186. return self.first_lines(lines)
  187. def translate_arcs(self, arcs):
  188. """Implement `FileReporter.translate_arcs`."""
  189. return [(self.first_line(a), self.first_line(b)) for (a, b) in arcs]
  190. def parse_source(self):
  191. """Parse source text to find executable lines, excluded lines, etc.
  192. Sets the .excluded and .statements attributes, normalized to the first
  193. line of multi-line statements.
  194. """
  195. try:
  196. self._raw_parse()
  197. except (tokenize.TokenError, IndentationError) as err:
  198. if hasattr(err, "lineno"):
  199. lineno = err.lineno # IndentationError
  200. else:
  201. lineno = err.args[1][0] # TokenError
  202. raise NotPython(
  203. u"Couldn't parse '%s' as Python source: '%s' at line %d" % (
  204. self.filename, err.args[0], lineno
  205. )
  206. )
  207. self.excluded = self.first_lines(self.raw_excluded)
  208. ignore = self.excluded | self.raw_docstrings
  209. starts = self.raw_statements - ignore
  210. self.statements = self.first_lines(starts) - ignore
  211. def arcs(self):
  212. """Get information about the arcs available in the code.
  213. Returns a set of line number pairs. Line numbers have been normalized
  214. to the first line of multi-line statements.
  215. """
  216. if self._all_arcs is None:
  217. self._analyze_ast()
  218. return self._all_arcs
  219. def _analyze_ast(self):
  220. """Run the AstArcAnalyzer and save its results.
  221. `_all_arcs` is the set of arcs in the code.
  222. """
  223. aaa = AstArcAnalyzer(self.text, self.raw_statements, self._multiline)
  224. aaa.analyze()
  225. self._all_arcs = set()
  226. for l1, l2 in aaa.arcs:
  227. fl1 = self.first_line(l1)
  228. fl2 = self.first_line(l2)
  229. if fl1 != fl2:
  230. self._all_arcs.add((fl1, fl2))
  231. self._missing_arc_fragments = aaa.missing_arc_fragments
  232. def exit_counts(self):
  233. """Get a count of exits from that each line.
  234. Excluded lines are excluded.
  235. """
  236. exit_counts = collections.defaultdict(int)
  237. for l1, l2 in self.arcs():
  238. if l1 < 0:
  239. # Don't ever report -1 as a line number
  240. continue
  241. if l1 in self.excluded:
  242. # Don't report excluded lines as line numbers.
  243. continue
  244. if l2 in self.excluded:
  245. # Arcs to excluded lines shouldn't count.
  246. continue
  247. exit_counts[l1] += 1
  248. # Class definitions have one extra exit, so remove one for each:
  249. for l in self.raw_classdefs:
  250. # Ensure key is there: class definitions can include excluded lines.
  251. if l in exit_counts:
  252. exit_counts[l] -= 1
  253. return exit_counts
  254. def missing_arc_description(self, start, end, executed_arcs=None):
  255. """Provide an English sentence describing a missing arc."""
  256. if self._missing_arc_fragments is None:
  257. self._analyze_ast()
  258. actual_start = start
  259. if (
  260. executed_arcs and
  261. end < 0 and end == -start and
  262. (end, start) not in executed_arcs and
  263. (end, start) in self._missing_arc_fragments
  264. ):
  265. # It's a one-line callable, and we never even started it,
  266. # and we have a message about not starting it.
  267. start, end = end, start
  268. fragment_pairs = self._missing_arc_fragments.get((start, end), [(None, None)])
  269. msgs = []
  270. for fragment_pair in fragment_pairs:
  271. smsg, emsg = fragment_pair
  272. if emsg is None:
  273. if end < 0:
  274. # Hmm, maybe we have a one-line callable, let's check.
  275. if (-end, end) in self._missing_arc_fragments:
  276. return self.missing_arc_description(-end, end)
  277. emsg = "didn't jump to the function exit"
  278. else:
  279. emsg = "didn't jump to line {lineno}"
  280. emsg = emsg.format(lineno=end)
  281. msg = "line {start} {emsg}".format(start=actual_start, emsg=emsg)
  282. if smsg is not None:
  283. msg += ", because {smsg}".format(smsg=smsg.format(lineno=actual_start))
  284. msgs.append(msg)
  285. return " or ".join(msgs)
  286. class ByteParser(object):
  287. """Parse bytecode to understand the structure of code."""
  288. @contract(text='unicode')
  289. def __init__(self, text, code=None, filename=None):
  290. self.text = text
  291. if code:
  292. self.code = code
  293. else:
  294. try:
  295. self.code = compile_unicode(text, filename, "exec")
  296. except SyntaxError as synerr:
  297. raise NotPython(
  298. u"Couldn't parse '%s' as Python source: '%s' at line %d" % (
  299. filename, synerr.msg, synerr.lineno
  300. )
  301. )
  302. # Alternative Python implementations don't always provide all the
  303. # attributes on code objects that we need to do the analysis.
  304. for attr in ['co_lnotab', 'co_firstlineno']:
  305. if not hasattr(self.code, attr):
  306. raise StopEverything( # pragma: only jython
  307. "This implementation of Python doesn't support code analysis.\n"
  308. "Run coverage.py under another Python for this command."
  309. )
  310. def child_parsers(self):
  311. """Iterate over all the code objects nested within this one.
  312. The iteration includes `self` as its first value.
  313. """
  314. children = CodeObjects(self.code)
  315. return (ByteParser(self.text, code=c) for c in children)
  316. def _bytes_lines(self):
  317. """Map byte offsets to line numbers in `code`.
  318. Uses co_lnotab described in Python/compile.c to map byte offsets to
  319. line numbers. Produces a sequence: (b0, l0), (b1, l1), ...
  320. Only byte offsets that correspond to line numbers are included in the
  321. results.
  322. """
  323. # Adapted from dis.py in the standard library.
  324. byte_increments = bytes_to_ints(self.code.co_lnotab[0::2])
  325. line_increments = bytes_to_ints(self.code.co_lnotab[1::2])
  326. last_line_num = None
  327. line_num = self.code.co_firstlineno
  328. byte_num = 0
  329. for byte_incr, line_incr in zip(byte_increments, line_increments):
  330. if byte_incr:
  331. if line_num != last_line_num:
  332. yield (byte_num, line_num)
  333. last_line_num = line_num
  334. byte_num += byte_incr
  335. line_num += line_incr
  336. if line_num != last_line_num:
  337. yield (byte_num, line_num)
  338. def _find_statements(self):
  339. """Find the statements in `self.code`.
  340. Produce a sequence of line numbers that start statements. Recurses
  341. into all code objects reachable from `self.code`.
  342. """
  343. for bp in self.child_parsers():
  344. # Get all of the lineno information from this code.
  345. for _, l in bp._bytes_lines():
  346. yield l
  347. #
  348. # AST analysis
  349. #
  350. class LoopBlock(object):
  351. """A block on the block stack representing a `for` or `while` loop."""
  352. @contract(start=int)
  353. def __init__(self, start):
  354. # The line number where the loop starts.
  355. self.start = start
  356. # A set of ArcStarts, the arcs from break statements exiting this loop.
  357. self.break_exits = set()
  358. class FunctionBlock(object):
  359. """A block on the block stack representing a function definition."""
  360. @contract(start=int, name=str)
  361. def __init__(self, start, name):
  362. # The line number where the function starts.
  363. self.start = start
  364. # The name of the function.
  365. self.name = name
  366. class TryBlock(object):
  367. """A block on the block stack representing a `try` block."""
  368. @contract(handler_start='int|None', final_start='int|None')
  369. def __init__(self, handler_start, final_start):
  370. # The line number of the first "except" handler, if any.
  371. self.handler_start = handler_start
  372. # The line number of the "finally:" clause, if any.
  373. self.final_start = final_start
  374. # The ArcStarts for breaks/continues/returns/raises inside the "try:"
  375. # that need to route through the "finally:" clause.
  376. self.break_from = set()
  377. self.continue_from = set()
  378. self.return_from = set()
  379. self.raise_from = set()
  380. class ArcStart(collections.namedtuple("Arc", "lineno, cause")):
  381. """The information needed to start an arc.
  382. `lineno` is the line number the arc starts from.
  383. `cause` is an English text fragment used as the `startmsg` for
  384. AstArcAnalyzer.missing_arc_fragments. It will be used to describe why an
  385. arc wasn't executed, so should fit well into a sentence of the form,
  386. "Line 17 didn't run because {cause}." The fragment can include "{lineno}"
  387. to have `lineno` interpolated into it.
  388. """
  389. def __new__(cls, lineno, cause=None):
  390. return super(ArcStart, cls).__new__(cls, lineno, cause)
  391. # Define contract words that PyContract doesn't have.
  392. # ArcStarts is for a list or set of ArcStart's.
  393. new_contract('ArcStarts', lambda seq: all(isinstance(x, ArcStart) for x in seq))
  394. # Turn on AST dumps with an environment variable.
  395. AST_DUMP = bool(int(os.environ.get("COVERAGE_AST_DUMP", 0)))
  396. class NodeList(object):
  397. """A synthetic fictitious node, containing a sequence of nodes.
  398. This is used when collapsing optimized if-statements, to represent the
  399. unconditional execution of one of the clauses.
  400. """
  401. def __init__(self, body):
  402. self.body = body
  403. self.lineno = body[0].lineno
  404. class AstArcAnalyzer(object):
  405. """Analyze source text with an AST to find executable code paths."""
  406. @contract(text='unicode', statements=set)
  407. def __init__(self, text, statements, multiline):
  408. self.root_node = ast.parse(neuter_encoding_declaration(text))
  409. # TODO: I think this is happening in too many places.
  410. self.statements = set(multiline.get(l, l) for l in statements)
  411. self.multiline = multiline
  412. if AST_DUMP: # pragma: debugging
  413. # Dump the AST so that failing tests have helpful output.
  414. print("Statements: {0}".format(self.statements))
  415. print("Multiline map: {0}".format(self.multiline))
  416. ast_dump(self.root_node)
  417. self.arcs = set()
  418. # A map from arc pairs to a list of pairs of sentence fragments:
  419. # { (start, end): [(startmsg, endmsg), ...], }
  420. #
  421. # For an arc from line 17, they should be usable like:
  422. # "Line 17 {endmsg}, because {startmsg}"
  423. self.missing_arc_fragments = collections.defaultdict(list)
  424. self.block_stack = []
  425. self.debug = bool(int(os.environ.get("COVERAGE_TRACK_ARCS", 0)))
  426. def analyze(self):
  427. """Examine the AST tree from `root_node` to determine possible arcs.
  428. This sets the `arcs` attribute to be a set of (from, to) line number
  429. pairs.
  430. """
  431. for node in ast.walk(self.root_node):
  432. node_name = node.__class__.__name__
  433. code_object_handler = getattr(self, "_code_object__" + node_name, None)
  434. if code_object_handler is not None:
  435. code_object_handler(node)
  436. def add_arc(self, start, end, smsg=None, emsg=None):
  437. """Add an arc, including message fragments to use if it is missing."""
  438. if self.debug: # pragma: debugging
  439. print("\nAdding arc: ({}, {}): {!r}, {!r}".format(start, end, smsg, emsg))
  440. print(short_stack(limit=6))
  441. self.arcs.add((start, end))
  442. if smsg is not None or emsg is not None:
  443. self.missing_arc_fragments[(start, end)].append((smsg, emsg))
  444. def nearest_blocks(self):
  445. """Yield the blocks in nearest-to-farthest order."""
  446. return reversed(self.block_stack)
  447. @contract(returns=int)
  448. def line_for_node(self, node):
  449. """What is the right line number to use for this node?
  450. This dispatches to _line__Node functions where needed.
  451. """
  452. node_name = node.__class__.__name__
  453. handler = getattr(self, "_line__" + node_name, None)
  454. if handler is not None:
  455. return handler(node)
  456. else:
  457. return node.lineno
  458. def _line__Assign(self, node):
  459. return self.line_for_node(node.value)
  460. def _line__Dict(self, node):
  461. # Python 3.5 changed how dict literals are made.
  462. if env.PYVERSION >= (3, 5) and node.keys:
  463. if node.keys[0] is not None:
  464. return node.keys[0].lineno
  465. else:
  466. # Unpacked dict literals `{**{'a':1}}` have None as the key,
  467. # use the value in that case.
  468. return node.values[0].lineno
  469. else:
  470. return node.lineno
  471. def _line__List(self, node):
  472. if node.elts:
  473. return self.line_for_node(node.elts[0])
  474. else:
  475. return node.lineno
  476. def _line__Module(self, node):
  477. if node.body:
  478. return self.line_for_node(node.body[0])
  479. else:
  480. # Empty modules have no line number, they always start at 1.
  481. return 1
  482. # The node types that just flow to the next node with no complications.
  483. OK_TO_DEFAULT = set([
  484. "Assign", "Assert", "AugAssign", "Delete", "Exec", "Expr", "Global",
  485. "Import", "ImportFrom", "Nonlocal", "Pass", "Print",
  486. ])
  487. @contract(returns='ArcStarts')
  488. def add_arcs(self, node):
  489. """Add the arcs for `node`.
  490. Return a set of ArcStarts, exits from this node to the next. Because a
  491. node represents an entire sub-tree (including its children), the exits
  492. from a node can be arbitrarily complex::
  493. if something(1):
  494. if other(2):
  495. doit(3)
  496. else:
  497. doit(5)
  498. There are two exits from line 1: they start at line 3 and line 5.
  499. """
  500. node_name = node.__class__.__name__
  501. handler = getattr(self, "_handle__" + node_name, None)
  502. if handler is not None:
  503. return handler(node)
  504. else:
  505. # No handler: either it's something that's ok to default (a simple
  506. # statement), or it's something we overlooked. Change this 0 to 1
  507. # to see if it's overlooked.
  508. if 0:
  509. if node_name not in self.OK_TO_DEFAULT:
  510. print("*** Unhandled: {0}".format(node))
  511. # Default for simple statements: one exit from this node.
  512. return set([ArcStart(self.line_for_node(node))])
  513. @one_of("from_start, prev_starts")
  514. @contract(returns='ArcStarts')
  515. def add_body_arcs(self, body, from_start=None, prev_starts=None):
  516. """Add arcs for the body of a compound statement.
  517. `body` is the body node. `from_start` is a single `ArcStart` that can
  518. be the previous line in flow before this body. `prev_starts` is a set
  519. of ArcStarts that can be the previous line. Only one of them should be
  520. given.
  521. Returns a set of ArcStarts, the exits from this body.
  522. """
  523. if prev_starts is None:
  524. prev_starts = set([from_start])
  525. for body_node in body:
  526. lineno = self.line_for_node(body_node)
  527. first_line = self.multiline.get(lineno, lineno)
  528. if first_line not in self.statements:
  529. body_node = self.find_non_missing_node(body_node)
  530. if body_node is None:
  531. continue
  532. lineno = self.line_for_node(body_node)
  533. for prev_start in prev_starts:
  534. self.add_arc(prev_start.lineno, lineno, prev_start.cause)
  535. prev_starts = self.add_arcs(body_node)
  536. return prev_starts
  537. def find_non_missing_node(self, node):
  538. """Search `node` looking for a child that has not been optimized away.
  539. This might return the node you started with, or it will work recursively
  540. to find a child node in self.statements.
  541. Returns a node, or None if none of the node remains.
  542. """
  543. # This repeats work just done in add_body_arcs, but this duplication
  544. # means we can avoid a function call in the 99.9999% case of not
  545. # optimizing away statements.
  546. lineno = self.line_for_node(node)
  547. first_line = self.multiline.get(lineno, lineno)
  548. if first_line in self.statements:
  549. return node
  550. missing_fn = getattr(self, "_missing__" + node.__class__.__name__, None)
  551. if missing_fn:
  552. node = missing_fn(node)
  553. else:
  554. node = None
  555. return node
  556. def _missing__If(self, node):
  557. # If the if-node is missing, then one of its children might still be
  558. # here, but not both. So return the first of the two that isn't missing.
  559. # Use a NodeList to hold the clauses as a single node.
  560. non_missing = self.find_non_missing_node(NodeList(node.body))
  561. if non_missing:
  562. return non_missing
  563. if node.orelse:
  564. return self.find_non_missing_node(NodeList(node.orelse))
  565. return None
  566. def _missing__NodeList(self, node):
  567. # A NodeList might be a mixture of missing and present nodes. Find the
  568. # ones that are present.
  569. non_missing_children = []
  570. for child in node.body:
  571. child = self.find_non_missing_node(child)
  572. if child is not None:
  573. non_missing_children.append(child)
  574. # Return the simplest representation of the present children.
  575. if not non_missing_children:
  576. return None
  577. if len(non_missing_children) == 1:
  578. return non_missing_children[0]
  579. return NodeList(non_missing_children)
  580. def is_constant_expr(self, node):
  581. """Is this a compile-time constant?"""
  582. node_name = node.__class__.__name__
  583. if node_name in ["NameConstant", "Num"]:
  584. return "Num"
  585. elif node_name == "Name":
  586. if node.id in ["True", "False", "None", "__debug__"]:
  587. return "Name"
  588. return None
  589. # In the fullness of time, these might be good tests to write:
  590. # while EXPR:
  591. # while False:
  592. # listcomps hidden deep in other expressions
  593. # listcomps hidden in lists: x = [[i for i in range(10)]]
  594. # nested function definitions
  595. # Exit processing: process_*_exits
  596. #
  597. # These functions process the four kinds of jump exits: break, continue,
  598. # raise, and return. To figure out where an exit goes, we have to look at
  599. # the block stack context. For example, a break will jump to the nearest
  600. # enclosing loop block, or the nearest enclosing finally block, whichever
  601. # is nearer.
  602. @contract(exits='ArcStarts')
  603. def process_break_exits(self, exits):
  604. """Add arcs due to jumps from `exits` being breaks."""
  605. for block in self.nearest_blocks():
  606. if isinstance(block, LoopBlock):
  607. block.break_exits.update(exits)
  608. break
  609. elif isinstance(block, TryBlock) and block.final_start is not None:
  610. block.break_from.update(exits)
  611. break
  612. @contract(exits='ArcStarts')
  613. def process_continue_exits(self, exits):
  614. """Add arcs due to jumps from `exits` being continues."""
  615. for block in self.nearest_blocks():
  616. if isinstance(block, LoopBlock):
  617. for xit in exits:
  618. self.add_arc(xit.lineno, block.start, xit.cause)
  619. break
  620. elif isinstance(block, TryBlock) and block.final_start is not None:
  621. block.continue_from.update(exits)
  622. break
  623. @contract(exits='ArcStarts')
  624. def process_raise_exits(self, exits):
  625. """Add arcs due to jumps from `exits` being raises."""
  626. for block in self.nearest_blocks():
  627. if isinstance(block, TryBlock):
  628. if block.handler_start is not None:
  629. for xit in exits:
  630. self.add_arc(xit.lineno, block.handler_start, xit.cause)
  631. break
  632. elif block.final_start is not None:
  633. block.raise_from.update(exits)
  634. break
  635. elif isinstance(block, FunctionBlock):
  636. for xit in exits:
  637. self.add_arc(
  638. xit.lineno, -block.start, xit.cause,
  639. "didn't except from function '{0}'".format(block.name),
  640. )
  641. break
  642. @contract(exits='ArcStarts')
  643. def process_return_exits(self, exits):
  644. """Add arcs due to jumps from `exits` being returns."""
  645. for block in self.nearest_blocks():
  646. if isinstance(block, TryBlock) and block.final_start is not None:
  647. block.return_from.update(exits)
  648. break
  649. elif isinstance(block, FunctionBlock):
  650. for xit in exits:
  651. self.add_arc(
  652. xit.lineno, -block.start, xit.cause,
  653. "didn't return from function '{0}'".format(block.name),
  654. )
  655. break
  656. # Handlers: _handle__*
  657. #
  658. # Each handler deals with a specific AST node type, dispatched from
  659. # add_arcs. Each deals with a particular kind of node type, and returns
  660. # the set of exits from that node. These functions mirror the Python
  661. # semantics of each syntactic construct. See the docstring for add_arcs to
  662. # understand the concept of exits from a node.
  663. @contract(returns='ArcStarts')
  664. def _handle__Break(self, node):
  665. here = self.line_for_node(node)
  666. break_start = ArcStart(here, cause="the break on line {lineno} wasn't executed")
  667. self.process_break_exits([break_start])
  668. return set()
  669. @contract(returns='ArcStarts')
  670. def _handle_decorated(self, node):
  671. """Add arcs for things that can be decorated (classes and functions)."""
  672. last = self.line_for_node(node)
  673. if node.decorator_list:
  674. for dec_node in node.decorator_list:
  675. dec_start = self.line_for_node(dec_node)
  676. if dec_start != last:
  677. self.add_arc(last, dec_start)
  678. last = dec_start
  679. # The definition line may have been missed, but we should have it
  680. # in `self.statements`. For some constructs, `line_for_node` is
  681. # not what we'd think of as the first line in the statement, so map
  682. # it to the first one.
  683. body_start = self.line_for_node(node.body[0])
  684. body_start = self.multiline.get(body_start, body_start)
  685. for lineno in range(last+1, body_start):
  686. if lineno in self.statements:
  687. self.add_arc(last, lineno)
  688. last = lineno
  689. # The body is handled in collect_arcs.
  690. return set([ArcStart(last)])
  691. _handle__ClassDef = _handle_decorated
  692. @contract(returns='ArcStarts')
  693. def _handle__Continue(self, node):
  694. here = self.line_for_node(node)
  695. continue_start = ArcStart(here, cause="the continue on line {lineno} wasn't executed")
  696. self.process_continue_exits([continue_start])
  697. return set()
  698. @contract(returns='ArcStarts')
  699. def _handle__For(self, node):
  700. start = self.line_for_node(node.iter)
  701. self.block_stack.append(LoopBlock(start=start))
  702. from_start = ArcStart(start, cause="the loop on line {lineno} never started")
  703. exits = self.add_body_arcs(node.body, from_start=from_start)
  704. # Any exit from the body will go back to the top of the loop.
  705. for xit in exits:
  706. self.add_arc(xit.lineno, start, xit.cause)
  707. my_block = self.block_stack.pop()
  708. exits = my_block.break_exits
  709. from_start = ArcStart(start, cause="the loop on line {lineno} didn't complete")
  710. if node.orelse:
  711. else_exits = self.add_body_arcs(node.orelse, from_start=from_start)
  712. exits |= else_exits
  713. else:
  714. # No else clause: exit from the for line.
  715. exits.add(from_start)
  716. return exits
  717. _handle__AsyncFor = _handle__For
  718. _handle__FunctionDef = _handle_decorated
  719. _handle__AsyncFunctionDef = _handle_decorated
  720. @contract(returns='ArcStarts')
  721. def _handle__If(self, node):
  722. start = self.line_for_node(node.test)
  723. from_start = ArcStart(start, cause="the condition on line {lineno} was never true")
  724. exits = self.add_body_arcs(node.body, from_start=from_start)
  725. from_start = ArcStart(start, cause="the condition on line {lineno} was never false")
  726. exits |= self.add_body_arcs(node.orelse, from_start=from_start)
  727. return exits
  728. @contract(returns='ArcStarts')
  729. def _handle__NodeList(self, node):
  730. start = self.line_for_node(node)
  731. exits = self.add_body_arcs(node.body, from_start=ArcStart(start))
  732. return exits
  733. @contract(returns='ArcStarts')
  734. def _handle__Raise(self, node):
  735. here = self.line_for_node(node)
  736. raise_start = ArcStart(here, cause="the raise on line {lineno} wasn't executed")
  737. self.process_raise_exits([raise_start])
  738. # `raise` statement jumps away, no exits from here.
  739. return set()
  740. @contract(returns='ArcStarts')
  741. def _handle__Return(self, node):
  742. here = self.line_for_node(node)
  743. return_start = ArcStart(here, cause="the return on line {lineno} wasn't executed")
  744. self.process_return_exits([return_start])
  745. # `return` statement jumps away, no exits from here.
  746. return set()
  747. @contract(returns='ArcStarts')
  748. def _handle__Try(self, node):
  749. if node.handlers:
  750. handler_start = self.line_for_node(node.handlers[0])
  751. else:
  752. handler_start = None
  753. if node.finalbody:
  754. final_start = self.line_for_node(node.finalbody[0])
  755. else:
  756. final_start = None
  757. try_block = TryBlock(handler_start, final_start)
  758. self.block_stack.append(try_block)
  759. start = self.line_for_node(node)
  760. exits = self.add_body_arcs(node.body, from_start=ArcStart(start))
  761. # We're done with the `try` body, so this block no longer handles
  762. # exceptions. We keep the block so the `finally` clause can pick up
  763. # flows from the handlers and `else` clause.
  764. if node.finalbody:
  765. try_block.handler_start = None
  766. if node.handlers:
  767. # If there are `except` clauses, then raises in the try body
  768. # will already jump to them. Start this set over for raises in
  769. # `except` and `else`.
  770. try_block.raise_from = set([])
  771. else:
  772. self.block_stack.pop()
  773. handler_exits = set()
  774. if node.handlers:
  775. last_handler_start = None
  776. for handler_node in node.handlers:
  777. handler_start = self.line_for_node(handler_node)
  778. if last_handler_start is not None:
  779. self.add_arc(last_handler_start, handler_start)
  780. last_handler_start = handler_start
  781. from_cause = "the exception caught by line {lineno} didn't happen"
  782. from_start = ArcStart(handler_start, cause=from_cause)
  783. handler_exits |= self.add_body_arcs(handler_node.body, from_start=from_start)
  784. if node.orelse:
  785. exits = self.add_body_arcs(node.orelse, prev_starts=exits)
  786. exits |= handler_exits
  787. if node.finalbody:
  788. self.block_stack.pop()
  789. final_from = ( # You can get to the `finally` clause from:
  790. exits | # the exits of the body or `else` clause,
  791. try_block.break_from | # or a `break`,
  792. try_block.continue_from | # or a `continue`,
  793. try_block.raise_from | # or a `raise`,
  794. try_block.return_from # or a `return`.
  795. )
  796. final_exits = self.add_body_arcs(node.finalbody, prev_starts=final_from)
  797. if try_block.break_from:
  798. self.process_break_exits(
  799. self._combine_finally_starts(try_block.break_from, final_exits)
  800. )
  801. if try_block.continue_from:
  802. self.process_continue_exits(
  803. self._combine_finally_starts(try_block.continue_from, final_exits)
  804. )
  805. if try_block.raise_from:
  806. self.process_raise_exits(
  807. self._combine_finally_starts(try_block.raise_from, final_exits)
  808. )
  809. if try_block.return_from:
  810. self.process_return_exits(
  811. self._combine_finally_starts(try_block.return_from, final_exits)
  812. )
  813. if exits:
  814. # The finally clause's exits are only exits for the try block
  815. # as a whole if the try block had some exits to begin with.
  816. exits = final_exits
  817. return exits
  818. @contract(starts='ArcStarts', exits='ArcStarts', returns='ArcStarts')
  819. def _combine_finally_starts(self, starts, exits):
  820. """Helper for building the cause of `finally` branches.
  821. "finally" clauses might not execute their exits, and the causes could
  822. be due to a failure to execute any of the exits in the try block. So
  823. we use the causes from `starts` as the causes for `exits`.
  824. """
  825. causes = []
  826. for start in sorted(starts):
  827. if start.cause is not None:
  828. causes.append(start.cause.format(lineno=start.lineno))
  829. cause = " or ".join(causes)
  830. exits = set(ArcStart(xit.lineno, cause) for xit in exits)
  831. return exits
  832. @contract(returns='ArcStarts')
  833. def _handle__TryExcept(self, node):
  834. # Python 2.7 uses separate TryExcept and TryFinally nodes. If we get
  835. # TryExcept, it means there was no finally, so fake it, and treat as
  836. # a general Try node.
  837. node.finalbody = []
  838. return self._handle__Try(node)
  839. @contract(returns='ArcStarts')
  840. def _handle__TryFinally(self, node):
  841. # Python 2.7 uses separate TryExcept and TryFinally nodes. If we get
  842. # TryFinally, see if there's a TryExcept nested inside. If so, merge
  843. # them. Otherwise, fake fields to complete a Try node.
  844. node.handlers = []
  845. node.orelse = []
  846. first = node.body[0]
  847. if first.__class__.__name__ == "TryExcept" and node.lineno == first.lineno:
  848. assert len(node.body) == 1
  849. node.body = first.body
  850. node.handlers = first.handlers
  851. node.orelse = first.orelse
  852. return self._handle__Try(node)
  853. @contract(returns='ArcStarts')
  854. def _handle__While(self, node):
  855. constant_test = self.is_constant_expr(node.test)
  856. start = to_top = self.line_for_node(node.test)
  857. if constant_test and (env.PY3 or constant_test == "Num"):
  858. to_top = self.line_for_node(node.body[0])
  859. self.block_stack.append(LoopBlock(start=to_top))
  860. from_start = ArcStart(start, cause="the condition on line {lineno} was never true")
  861. exits = self.add_body_arcs(node.body, from_start=from_start)
  862. for xit in exits:
  863. self.add_arc(xit.lineno, to_top, xit.cause)
  864. exits = set()
  865. my_block = self.block_stack.pop()
  866. exits.update(my_block.break_exits)
  867. from_start = ArcStart(start, cause="the condition on line {lineno} was never false")
  868. if node.orelse:
  869. else_exits = self.add_body_arcs(node.orelse, from_start=from_start)
  870. exits |= else_exits
  871. else:
  872. # No `else` clause: you can exit from the start.
  873. if not constant_test:
  874. exits.add(from_start)
  875. return exits
  876. @contract(returns='ArcStarts')
  877. def _handle__With(self, node):
  878. start = self.line_for_node(node)
  879. exits = self.add_body_arcs(node.body, from_start=ArcStart(start))
  880. return exits
  881. _handle__AsyncWith = _handle__With
  882. def _code_object__Module(self, node):
  883. start = self.line_for_node(node)
  884. if node.body:
  885. exits = self.add_body_arcs(node.body, from_start=ArcStart(-start))
  886. for xit in exits:
  887. self.add_arc(xit.lineno, -start, xit.cause, "didn't exit the module")
  888. else:
  889. # Empty module.
  890. self.add_arc(-start, start)
  891. self.add_arc(start, -start)
  892. def _code_object__FunctionDef(self, node):
  893. start = self.line_for_node(node)
  894. self.block_stack.append(FunctionBlock(start=start, name=node.name))
  895. exits = self.add_body_arcs(node.body, from_start=ArcStart(-start))
  896. self.process_return_exits(exits)
  897. self.block_stack.pop()
  898. _code_object__AsyncFunctionDef = _code_object__FunctionDef
  899. def _code_object__ClassDef(self, node):
  900. start = self.line_for_node(node)
  901. self.add_arc(-start, start)
  902. exits = self.add_body_arcs(node.body, from_start=ArcStart(start))
  903. for xit in exits:
  904. self.add_arc(
  905. xit.lineno, -start, xit.cause,
  906. "didn't exit the body of class '{0}'".format(node.name),
  907. )
  908. def _make_oneline_code_method(noun): # pylint: disable=no-self-argument
  909. """A function to make methods for online callable _code_object__ methods."""
  910. def _code_object__oneline_callable(self, node):
  911. start = self.line_for_node(node)
  912. self.add_arc(-start, start, None, "didn't run the {0} on line {1}".format(noun, start))
  913. self.add_arc(
  914. start, -start, None,
  915. "didn't finish the {0} on line {1}".format(noun, start),
  916. )
  917. return _code_object__oneline_callable
  918. _code_object__Lambda = _make_oneline_code_method("lambda")
  919. _code_object__GeneratorExp = _make_oneline_code_method("generator expression")
  920. _code_object__DictComp = _make_oneline_code_method("dictionary comprehension")
  921. _code_object__SetComp = _make_oneline_code_method("set comprehension")
  922. if env.PY3:
  923. _code_object__ListComp = _make_oneline_code_method("list comprehension")
  924. if AST_DUMP: # pragma: debugging
  925. # Code only used when dumping the AST for debugging.
  926. SKIP_DUMP_FIELDS = ["ctx"]
  927. def _is_simple_value(value):
  928. """Is `value` simple enough to be displayed on a single line?"""
  929. return (
  930. value in [None, [], (), {}, set()] or
  931. isinstance(value, (string_class, int, float))
  932. )
  933. def ast_dump(node, depth=0):
  934. """Dump the AST for `node`.
  935. This recursively walks the AST, printing a readable version.
  936. """
  937. indent = " " * depth
  938. if not isinstance(node, ast.AST):
  939. print("{0}<{1} {2!r}>".format(indent, node.__class__.__name__, node))
  940. return
  941. lineno = getattr(node, "lineno", None)
  942. if lineno is not None:
  943. linemark = " @ {0}".format(node.lineno)
  944. else:
  945. linemark = ""
  946. head = "{0}<{1}{2}".format(indent, node.__class__.__name__, linemark)
  947. named_fields = [
  948. (name, value)
  949. for name, value in ast.iter_fields(node)
  950. if name not in SKIP_DUMP_FIELDS
  951. ]
  952. if not named_fields:
  953. print("{0}>".format(head))
  954. elif len(named_fields) == 1 and _is_simple_value(named_fields[0][1]):
  955. field_name, value = named_fields[0]
  956. print("{0} {1}: {2!r}>".format(head, field_name, value))
  957. else:
  958. print(head)
  959. if 0:
  960. print("{0}# mro: {1}".format(
  961. indent, ", ".join(c.__name__ for c in node.__class__.__mro__[1:]),
  962. ))
  963. next_indent = indent + " "
  964. for field_name, value in named_fields:
  965. prefix = "{0}{1}:".format(next_indent, field_name)
  966. if _is_simple_value(value):
  967. print("{0} {1!r}".format(prefix, value))
  968. elif isinstance(value, list):
  969. print("{0} [".format(prefix))
  970. for n in value:
  971. ast_dump(n, depth + 8)
  972. print("{0}]".format(next_indent))
  973. else:
  974. print(prefix)
  975. ast_dump(value, depth + 8)
  976. print("{0}>".format(indent))