processor.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. """Module containing our file processor that tokenizes a file for checks."""
  2. import argparse
  3. import ast
  4. import contextlib
  5. import logging
  6. import tokenize
  7. from typing import Any
  8. from typing import Dict
  9. from typing import Generator
  10. from typing import List
  11. from typing import Optional
  12. from typing import Tuple
  13. from flake8 import defaults
  14. from flake8 import utils
  15. from flake8.plugins.finder import LoadedPlugin
  16. LOG = logging.getLogger(__name__)
  17. NEWLINE = frozenset([tokenize.NL, tokenize.NEWLINE])
  18. SKIP_TOKENS = frozenset(
  19. [tokenize.NL, tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT]
  20. )
  21. _LogicalMapping = List[Tuple[int, Tuple[int, int]]]
  22. _Logical = Tuple[List[str], List[str], _LogicalMapping]
  23. class FileProcessor:
  24. """Processes a file and holdes state.
  25. This processes a file by generating tokens, logical and physical lines,
  26. and AST trees. This also provides a way of passing state about the file
  27. to checks expecting that state. Any public attribute on this object can
  28. be requested by a plugin. The known public attributes are:
  29. - :attr:`blank_before`
  30. - :attr:`blank_lines`
  31. - :attr:`checker_state`
  32. - :attr:`indent_char`
  33. - :attr:`indent_level`
  34. - :attr:`line_number`
  35. - :attr:`logical_line`
  36. - :attr:`max_line_length`
  37. - :attr:`max_doc_length`
  38. - :attr:`multiline`
  39. - :attr:`noqa`
  40. - :attr:`previous_indent_level`
  41. - :attr:`previous_logical`
  42. - :attr:`previous_unindented_logical_line`
  43. - :attr:`tokens`
  44. - :attr:`file_tokens`
  45. - :attr:`total_lines`
  46. - :attr:`verbose`
  47. """
  48. #: always ``False``, included for compatibility
  49. noqa = False
  50. def __init__(
  51. self,
  52. filename: str,
  53. options: argparse.Namespace,
  54. lines: Optional[List[str]] = None,
  55. ) -> None:
  56. """Initialice our file processor.
  57. :param filename: Name of the file to process
  58. """
  59. self.options = options
  60. self.filename = filename
  61. self.lines = lines if lines is not None else self.read_lines()
  62. self.strip_utf_bom()
  63. # Defaults for public attributes
  64. #: Number of preceding blank lines
  65. self.blank_before = 0
  66. #: Number of blank lines
  67. self.blank_lines = 0
  68. #: Checker states for each plugin?
  69. self._checker_states: Dict[str, Dict[Any, Any]] = {}
  70. #: Current checker state
  71. self.checker_state: Dict[Any, Any] = {}
  72. #: User provided option for hang closing
  73. self.hang_closing = options.hang_closing
  74. #: Character used for indentation
  75. self.indent_char: Optional[str] = None
  76. #: Current level of indentation
  77. self.indent_level = 0
  78. #: Number of spaces used for indentation
  79. self.indent_size = options.indent_size
  80. #: Line number in the file
  81. self.line_number = 0
  82. #: Current logical line
  83. self.logical_line = ""
  84. #: Maximum line length as configured by the user
  85. self.max_line_length = options.max_line_length
  86. #: Maximum docstring / comment line length as configured by the user
  87. self.max_doc_length = options.max_doc_length
  88. #: Whether the current physical line is multiline
  89. self.multiline = False
  90. #: Previous level of indentation
  91. self.previous_indent_level = 0
  92. #: Previous logical line
  93. self.previous_logical = ""
  94. #: Previous unindented (i.e. top-level) logical line
  95. self.previous_unindented_logical_line = ""
  96. #: Current set of tokens
  97. self.tokens: List[tokenize.TokenInfo] = []
  98. #: Total number of lines in the file
  99. self.total_lines = len(self.lines)
  100. #: Verbosity level of Flake8
  101. self.verbose = options.verbose
  102. #: Statistics dictionary
  103. self.statistics = {"logical lines": 0}
  104. self._file_tokens: Optional[List[tokenize.TokenInfo]] = None
  105. # map from line number to the line we'll search for `noqa` in
  106. self._noqa_line_mapping: Optional[Dict[int, str]] = None
  107. @property
  108. def file_tokens(self) -> List[tokenize.TokenInfo]:
  109. """Return the complete set of tokens for a file."""
  110. if self._file_tokens is None:
  111. line_iter = iter(self.lines)
  112. self._file_tokens = list(
  113. tokenize.generate_tokens(lambda: next(line_iter))
  114. )
  115. return self._file_tokens
  116. @contextlib.contextmanager
  117. def inside_multiline(
  118. self, line_number: int
  119. ) -> Generator[None, None, None]:
  120. """Context-manager to toggle the multiline attribute."""
  121. self.line_number = line_number
  122. self.multiline = True
  123. yield
  124. self.multiline = False
  125. def reset_blank_before(self) -> None:
  126. """Reset the blank_before attribute to zero."""
  127. self.blank_before = 0
  128. def delete_first_token(self) -> None:
  129. """Delete the first token in the list of tokens."""
  130. del self.tokens[0]
  131. def visited_new_blank_line(self) -> None:
  132. """Note that we visited a new blank line."""
  133. self.blank_lines += 1
  134. def update_state(self, mapping: _LogicalMapping) -> None:
  135. """Update the indent level based on the logical line mapping."""
  136. (start_row, start_col) = mapping[0][1]
  137. start_line = self.lines[start_row - 1]
  138. self.indent_level = expand_indent(start_line[:start_col])
  139. if self.blank_before < self.blank_lines:
  140. self.blank_before = self.blank_lines
  141. def update_checker_state_for(self, plugin: LoadedPlugin) -> None:
  142. """Update the checker_state attribute for the plugin."""
  143. if "checker_state" in plugin.parameters:
  144. self.checker_state = self._checker_states.setdefault(
  145. plugin.entry_name, {}
  146. )
  147. def next_logical_line(self) -> None:
  148. """Record the previous logical line.
  149. This also resets the tokens list and the blank_lines count.
  150. """
  151. if self.logical_line:
  152. self.previous_indent_level = self.indent_level
  153. self.previous_logical = self.logical_line
  154. if not self.indent_level:
  155. self.previous_unindented_logical_line = self.logical_line
  156. self.blank_lines = 0
  157. self.tokens = []
  158. def build_logical_line_tokens(self) -> _Logical:
  159. """Build the mapping, comments, and logical line lists."""
  160. logical = []
  161. comments = []
  162. mapping: _LogicalMapping = []
  163. length = 0
  164. previous_row = previous_column = None
  165. for token_type, text, start, end, line in self.tokens:
  166. if token_type in SKIP_TOKENS:
  167. continue
  168. if not mapping:
  169. mapping = [(0, start)]
  170. if token_type == tokenize.COMMENT:
  171. comments.append(text)
  172. continue
  173. if token_type == tokenize.STRING:
  174. text = mutate_string(text)
  175. if previous_row:
  176. (start_row, start_column) = start
  177. if previous_row != start_row:
  178. row_index = previous_row - 1
  179. column_index = previous_column - 1
  180. previous_text = self.lines[row_index][column_index]
  181. if previous_text == "," or (
  182. previous_text not in "{[(" and text not in "}])"
  183. ):
  184. text = f" {text}"
  185. elif previous_column != start_column:
  186. text = line[previous_column:start_column] + text
  187. logical.append(text)
  188. length += len(text)
  189. mapping.append((length, end))
  190. (previous_row, previous_column) = end
  191. return comments, logical, mapping
  192. def build_ast(self) -> ast.AST:
  193. """Build an abstract syntax tree from the list of lines."""
  194. return ast.parse("".join(self.lines))
  195. def build_logical_line(self) -> Tuple[str, str, _LogicalMapping]:
  196. """Build a logical line from the current tokens list."""
  197. comments, logical, mapping_list = self.build_logical_line_tokens()
  198. joined_comments = "".join(comments)
  199. self.logical_line = "".join(logical)
  200. self.statistics["logical lines"] += 1
  201. return joined_comments, self.logical_line, mapping_list
  202. def split_line(
  203. self, token: tokenize.TokenInfo
  204. ) -> Generator[str, None, None]:
  205. """Split a physical line's line based on new-lines.
  206. This also auto-increments the line number for the caller.
  207. """
  208. # intentionally don't include the last line, that line will be
  209. # terminated later by a future end-of-line
  210. for line_no in range(token.start[0], token.end[0]):
  211. yield self.lines[line_no - 1]
  212. self.line_number += 1
  213. def keyword_arguments_for(
  214. self,
  215. parameters: Dict[str, bool],
  216. arguments: Dict[str, Any],
  217. ) -> Dict[str, Any]:
  218. """Generate the keyword arguments for a list of parameters."""
  219. ret = {}
  220. for param, required in parameters.items():
  221. if param in arguments:
  222. continue
  223. try:
  224. ret[param] = getattr(self, param)
  225. except AttributeError:
  226. if required:
  227. raise
  228. else:
  229. LOG.warning(
  230. 'Plugin requested optional parameter "%s" '
  231. "but this is not an available parameter.",
  232. param,
  233. )
  234. return ret
  235. def generate_tokens(self) -> Generator[tokenize.TokenInfo, None, None]:
  236. """Tokenize the file and yield the tokens."""
  237. for token in tokenize.generate_tokens(self.next_line):
  238. if token[2][0] > self.total_lines:
  239. break
  240. self.tokens.append(token)
  241. yield token
  242. def _noqa_line_range(self, min_line: int, max_line: int) -> Dict[int, str]:
  243. line_range = range(min_line, max_line + 1)
  244. joined = "".join(self.lines[min_line - 1 : max_line])
  245. return dict.fromkeys(line_range, joined)
  246. def noqa_line_for(self, line_number: int) -> Optional[str]:
  247. """Retrieve the line which will be used to determine noqa."""
  248. if self._noqa_line_mapping is None:
  249. try:
  250. file_tokens = self.file_tokens
  251. except (tokenize.TokenError, SyntaxError):
  252. # if we failed to parse the file tokens, we'll always fail in
  253. # the future, so set this so the code does not try again
  254. self._noqa_line_mapping = {}
  255. else:
  256. ret = {}
  257. min_line = len(self.lines) + 2
  258. max_line = -1
  259. for tp, _, (s_line, _), (e_line, _), _ in file_tokens:
  260. if tp == tokenize.ENDMARKER:
  261. break
  262. min_line = min(min_line, s_line)
  263. max_line = max(max_line, e_line)
  264. if tp in (tokenize.NL, tokenize.NEWLINE):
  265. ret.update(self._noqa_line_range(min_line, max_line))
  266. min_line = len(self.lines) + 2
  267. max_line = -1
  268. # in newer versions of python, a `NEWLINE` token is inserted
  269. # at the end of the file even if it doesn't have one.
  270. # on old pythons, they will not have hit a `NEWLINE`
  271. if max_line != -1:
  272. ret.update(self._noqa_line_range(min_line, max_line))
  273. self._noqa_line_mapping = ret
  274. # NOTE(sigmavirus24): Some plugins choose to report errors for empty
  275. # files on Line 1. In those cases, we shouldn't bother trying to
  276. # retrieve a physical line (since none exist).
  277. return self._noqa_line_mapping.get(line_number)
  278. def next_line(self) -> str:
  279. """Get the next line from the list."""
  280. if self.line_number >= self.total_lines:
  281. return ""
  282. line = self.lines[self.line_number]
  283. self.line_number += 1
  284. if self.indent_char is None and line[:1] in defaults.WHITESPACE:
  285. self.indent_char = line[0]
  286. return line
  287. def read_lines(self) -> List[str]:
  288. """Read the lines for this file checker."""
  289. if self.filename is None or self.filename == "-":
  290. self.filename = self.options.stdin_display_name or "stdin"
  291. lines = self.read_lines_from_stdin()
  292. else:
  293. lines = self.read_lines_from_filename()
  294. return lines
  295. def read_lines_from_filename(self) -> List[str]:
  296. """Read the lines for a file."""
  297. try:
  298. with tokenize.open(self.filename) as fd:
  299. return fd.readlines()
  300. except (SyntaxError, UnicodeError):
  301. # If we can't detect the codec with tokenize.detect_encoding, or
  302. # the detected encoding is incorrect, just fallback to latin-1.
  303. with open(self.filename, encoding="latin-1") as fd:
  304. return fd.readlines()
  305. def read_lines_from_stdin(self) -> List[str]:
  306. """Read the lines from standard in."""
  307. return utils.stdin_get_lines()
  308. def should_ignore_file(self) -> bool:
  309. """Check if ``flake8: noqa`` is in the file to be ignored.
  310. :returns:
  311. True if a line matches :attr:`defaults.NOQA_FILE`,
  312. otherwise False
  313. """
  314. if not self.options.disable_noqa and any(
  315. defaults.NOQA_FILE.match(line) for line in self.lines
  316. ):
  317. return True
  318. elif any(defaults.NOQA_FILE.search(line) for line in self.lines):
  319. LOG.warning(
  320. "Detected `flake8: noqa` on line with code. To ignore an "
  321. "error on a line use `noqa` instead."
  322. )
  323. return False
  324. else:
  325. return False
  326. def strip_utf_bom(self) -> None:
  327. """Strip the UTF bom from the lines of the file."""
  328. if not self.lines:
  329. # If we have nothing to analyze quit early
  330. return
  331. first_byte = ord(self.lines[0][0])
  332. if first_byte not in (0xEF, 0xFEFF):
  333. return
  334. # If the first byte of the file is a UTF-8 BOM, strip it
  335. if first_byte == 0xFEFF:
  336. self.lines[0] = self.lines[0][1:]
  337. elif self.lines[0][:3] == "\xEF\xBB\xBF":
  338. self.lines[0] = self.lines[0][3:]
  339. def is_eol_token(token: tokenize.TokenInfo) -> bool:
  340. """Check if the token is an end-of-line token."""
  341. return token[0] in NEWLINE or token[4][token[3][1] :].lstrip() == "\\\n"
  342. def is_multiline_string(token: tokenize.TokenInfo) -> bool:
  343. """Check if this is a multiline string."""
  344. return token[0] == tokenize.STRING and "\n" in token[1]
  345. def token_is_newline(token: tokenize.TokenInfo) -> bool:
  346. """Check if the token type is a newline token type."""
  347. return token[0] in NEWLINE
  348. def count_parentheses(current_parentheses_count: int, token_text: str) -> int:
  349. """Count the number of parentheses."""
  350. if token_text in "([{": # nosec
  351. return current_parentheses_count + 1
  352. elif token_text in "}])": # nosec
  353. return current_parentheses_count - 1
  354. return current_parentheses_count
  355. def expand_indent(line: str) -> int:
  356. r"""Return the amount of indentation.
  357. Tabs are expanded to the next multiple of 8.
  358. >>> expand_indent(' ')
  359. 4
  360. >>> expand_indent('\t')
  361. 8
  362. >>> expand_indent(' \t')
  363. 8
  364. >>> expand_indent(' \t')
  365. 16
  366. """
  367. return len(line.expandtabs(8))
  368. # NOTE(sigmavirus24): This was taken wholesale from
  369. # https://github.com/PyCQA/pycodestyle. The in-line comments were edited to be
  370. # more descriptive.
  371. def mutate_string(text: str) -> str:
  372. """Replace contents with 'xxx' to prevent syntax matching.
  373. >>> mutate_string('"abc"')
  374. '"xxx"'
  375. >>> mutate_string("'''abc'''")
  376. "'''xxx'''"
  377. >>> mutate_string("r'abc'")
  378. "r'xxx'"
  379. """
  380. # NOTE(sigmavirus24): If there are string modifiers (e.g., b, u, r)
  381. # use the last "character" to determine if we're using single or double
  382. # quotes and then find the first instance of it
  383. start = text.index(text[-1]) + 1
  384. end = len(text) - 1
  385. # Check for triple-quoted strings
  386. if text[-3:] in ('"""', "'''"):
  387. start += 2
  388. end -= 2
  389. return text[:start] + "x" * (end - start) + text[end:]