spelling.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. # Copyright (c) 2014-2020 Claudiu Popa <pcmanticore@gmail.com>
  2. # Copyright (c) 2014 Michal Nowikowski <godfryd@gmail.com>
  3. # Copyright (c) 2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  4. # Copyright (c) 2015 Pavel Roskin <proski@gnu.org>
  5. # Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
  6. # Copyright (c) 2016-2017, 2020 Pedro Algarvio <pedro@algarvio.me>
  7. # Copyright (c) 2016 Alexander Todorov <atodorov@otb.bg>
  8. # Copyright (c) 2017 Łukasz Rogalski <rogalski.91@gmail.com>
  9. # Copyright (c) 2017 Mikhail Fesenko <proggga@gmail.com>
  10. # Copyright (c) 2018, 2020 Anthony Sottile <asottile@umich.edu>
  11. # Copyright (c) 2018 ssolanki <sushobhitsolanki@gmail.com>
  12. # Copyright (c) 2018 Mike Frysinger <vapier@gmail.com>
  13. # Copyright (c) 2018 Sushobhit <31987769+sushobhit27@users.noreply.github.com>
  14. # Copyright (c) 2019-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
  15. # Copyright (c) 2019 Peter Kolbus <peter.kolbus@gmail.com>
  16. # Copyright (c) 2019 agutole <toldo_carp@hotmail.com>
  17. # Copyright (c) 2020 Ganden Schaffner <gschaffner@pm.me>
  18. # Copyright (c) 2020 hippo91 <guillaume.peillex@gmail.com>
  19. # Copyright (c) 2020 Damien Baty <damien.baty@polyconseil.fr>
  20. # Copyright (c) 2021 Daniël van Noord <13665637+DanielNoord@users.noreply.github.com>
  21. # Copyright (c) 2021 Tushar Sadhwani <tushar.sadhwani000@gmail.com>
  22. # Copyright (c) 2021 Nick Drozd <nicholasdrozd@gmail.com>
  23. # Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com>
  24. # Copyright (c) 2021 bot <bot@noreply.github.com>
  25. # Copyright (c) 2021 Andreas Finkler <andi.finkler@gmail.com>
  26. # Copyright (c) 2021 Eli Fine <ejfine@gmail.com>
  27. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  28. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  29. """Checker for spelling errors in comments and docstrings.
  30. """
  31. import os
  32. import re
  33. import tokenize
  34. from typing import Pattern
  35. from astroid import nodes
  36. from pylint.checkers import BaseTokenChecker
  37. from pylint.checkers.utils import check_messages
  38. from pylint.interfaces import IAstroidChecker, ITokenChecker
  39. try:
  40. import enchant
  41. from enchant.tokenize import (
  42. Chunker,
  43. EmailFilter,
  44. Filter,
  45. URLFilter,
  46. WikiWordFilter,
  47. get_tokenizer,
  48. )
  49. except ImportError:
  50. enchant = None
  51. class EmailFilter: # type: ignore[no-redef]
  52. ...
  53. class URLFilter: # type: ignore[no-redef]
  54. ...
  55. class WikiWordFilter: # type: ignore[no-redef]
  56. ...
  57. class Filter: # type: ignore[no-redef]
  58. def _skip(self, word):
  59. raise NotImplementedError
  60. class Chunker: # type: ignore[no-redef]
  61. pass
  62. def get_tokenizer(
  63. tag=None, chunkers=None, filters=None
  64. ): # pylint: disable=unused-argument
  65. return Filter()
  66. if enchant is not None:
  67. br = enchant.Broker()
  68. dicts = br.list_dicts()
  69. dict_choices = [""] + [d[0] for d in dicts]
  70. dicts = [f"{d[0]} ({d[1].name})" for d in dicts]
  71. dicts = ", ".join(dicts)
  72. instr = ""
  73. else:
  74. dicts = "none"
  75. dict_choices = [""]
  76. instr = " To make it work, install the 'python-enchant' package."
  77. class WordsWithDigitsFilter(Filter):
  78. """Skips words with digits."""
  79. def _skip(self, word):
  80. return any(char.isdigit() for char in word)
  81. class WordsWithUnderscores(Filter):
  82. """Skips words with underscores.
  83. They are probably function parameter names.
  84. """
  85. def _skip(self, word):
  86. return "_" in word
  87. class RegExFilter(Filter):
  88. """Parent class for filters using regular expressions.
  89. This filter skips any words the match the expression
  90. assigned to the class attribute ``_pattern``.
  91. """
  92. _pattern: Pattern[str]
  93. def _skip(self, word) -> bool:
  94. return bool(self._pattern.match(word))
  95. class CamelCasedWord(RegExFilter):
  96. r"""Filter skipping over camelCasedWords.
  97. This filter skips any words matching the following regular expression:
  98. ^([a-z]\w+[A-Z]+\w+)
  99. That is, any words that are camelCasedWords.
  100. """
  101. _pattern = re.compile(r"^([a-z]+([\d]|[A-Z])(?:\w+)?)")
  102. class SphinxDirectives(RegExFilter):
  103. r"""Filter skipping over Sphinx Directives.
  104. This filter skips any words matching the following regular expression:
  105. ^(:([a-z]+)){1,2}:`([^`]+)(`)?
  106. That is, for example, :class:`BaseQuery`
  107. """
  108. # The final ` in the pattern is optional because enchant strips it out
  109. _pattern = re.compile(r"^(:([a-z]+)){1,2}:`([^`]+)(`)?")
  110. class ForwardSlashChunker(Chunker):
  111. """
  112. This chunker allows splitting words like 'before/after' into 'before' and 'after'
  113. """
  114. def next(self):
  115. while True:
  116. if not self._text:
  117. raise StopIteration()
  118. if "/" not in self._text:
  119. text = self._text
  120. self._offset = 0
  121. self._text = ""
  122. return (text, 0)
  123. pre_text, post_text = self._text.split("/", 1)
  124. self._text = post_text
  125. self._offset = 0
  126. if (
  127. not pre_text
  128. or not post_text
  129. or not pre_text[-1].isalpha()
  130. or not post_text[0].isalpha()
  131. ):
  132. self._text = ""
  133. self._offset = 0
  134. return (pre_text + "/" + post_text, 0)
  135. return (pre_text, 0)
  136. def _next(self):
  137. while True:
  138. if "/" not in self._text:
  139. return (self._text, 0)
  140. pre_text, post_text = self._text.split("/", 1)
  141. if not pre_text or not post_text:
  142. break
  143. if not pre_text[-1].isalpha() or not post_text[0].isalpha():
  144. raise StopIteration()
  145. self._text = pre_text + " " + post_text
  146. raise StopIteration()
  147. CODE_FLANKED_IN_BACKTICK_REGEX = re.compile(r"(\s|^)(`{1,2})([^`]+)(\2)([^`]|$)")
  148. def _strip_code_flanked_in_backticks(line: str) -> str:
  149. """Alter line so code flanked in backticks is ignored.
  150. Pyenchant automatically strips backticks when parsing tokens,
  151. so this cannot be done at the individual filter level."""
  152. def replace_code_but_leave_surrounding_characters(match_obj) -> str:
  153. return match_obj.group(1) + match_obj.group(5)
  154. return CODE_FLANKED_IN_BACKTICK_REGEX.sub(
  155. replace_code_but_leave_surrounding_characters, line
  156. )
  157. class SpellingChecker(BaseTokenChecker):
  158. """Check spelling in comments and docstrings"""
  159. __implements__ = (ITokenChecker, IAstroidChecker)
  160. name = "spelling"
  161. msgs = {
  162. "C0401": (
  163. "Wrong spelling of a word '%s' in a comment:\n%s\n"
  164. "%s\nDid you mean: '%s'?",
  165. "wrong-spelling-in-comment",
  166. "Used when a word in comment is not spelled correctly.",
  167. ),
  168. "C0402": (
  169. "Wrong spelling of a word '%s' in a docstring:\n%s\n"
  170. "%s\nDid you mean: '%s'?",
  171. "wrong-spelling-in-docstring",
  172. "Used when a word in docstring is not spelled correctly.",
  173. ),
  174. "C0403": (
  175. "Invalid characters %r in a docstring",
  176. "invalid-characters-in-docstring",
  177. "Used when a word in docstring cannot be checked by enchant.",
  178. ),
  179. }
  180. options = (
  181. (
  182. "spelling-dict",
  183. {
  184. "default": "",
  185. "type": "choice",
  186. "metavar": "<dict name>",
  187. "choices": dict_choices,
  188. "help": "Spelling dictionary name. "
  189. f"Available dictionaries: {dicts}.{instr}",
  190. },
  191. ),
  192. (
  193. "spelling-ignore-words",
  194. {
  195. "default": "",
  196. "type": "string",
  197. "metavar": "<comma separated words>",
  198. "help": "List of comma separated words that should not be checked.",
  199. },
  200. ),
  201. (
  202. "spelling-private-dict-file",
  203. {
  204. "default": "",
  205. "type": "string",
  206. "metavar": "<path to file>",
  207. "help": "A path to a file that contains the private "
  208. "dictionary; one word per line.",
  209. },
  210. ),
  211. (
  212. "spelling-store-unknown-words",
  213. {
  214. "default": "n",
  215. "type": "yn",
  216. "metavar": "<y or n>",
  217. "help": "Tells whether to store unknown words to the "
  218. "private dictionary (see the "
  219. "--spelling-private-dict-file option) instead of "
  220. "raising a message.",
  221. },
  222. ),
  223. (
  224. "max-spelling-suggestions",
  225. {
  226. "default": 4,
  227. "type": "int",
  228. "metavar": "N",
  229. "help": "Limits count of emitted suggestions for spelling mistakes.",
  230. },
  231. ),
  232. (
  233. "spelling-ignore-comment-directives",
  234. {
  235. "default": "fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:",
  236. "type": "string",
  237. "metavar": "<comma separated words>",
  238. "help": "List of comma separated words that should be considered directives if they appear and the beginning of a comment and should not be checked.",
  239. },
  240. ),
  241. )
  242. def open(self):
  243. self.initialized = False
  244. self.private_dict_file = None
  245. if enchant is None:
  246. return
  247. dict_name = self.config.spelling_dict
  248. if not dict_name:
  249. return
  250. self.ignore_list = [
  251. w.strip() for w in self.config.spelling_ignore_words.split(",")
  252. ]
  253. # "param" appears in docstring in param description and
  254. # "pylint" appears in comments in pylint pragmas.
  255. self.ignore_list.extend(["param", "pylint"])
  256. self.ignore_comment_directive_list = [
  257. w.strip() for w in self.config.spelling_ignore_comment_directives.split(",")
  258. ]
  259. # Expand tilde to allow e.g. spelling-private-dict-file = ~/.pylintdict
  260. if self.config.spelling_private_dict_file:
  261. self.config.spelling_private_dict_file = os.path.expanduser(
  262. self.config.spelling_private_dict_file
  263. )
  264. if self.config.spelling_private_dict_file:
  265. self.spelling_dict = enchant.DictWithPWL(
  266. dict_name, self.config.spelling_private_dict_file
  267. )
  268. self.private_dict_file = open( # pylint: disable=consider-using-with
  269. self.config.spelling_private_dict_file, "a", encoding="utf-8"
  270. )
  271. else:
  272. self.spelling_dict = enchant.Dict(dict_name)
  273. if self.config.spelling_store_unknown_words:
  274. self.unknown_words = set()
  275. self.tokenizer = get_tokenizer(
  276. dict_name,
  277. chunkers=[ForwardSlashChunker],
  278. filters=[
  279. EmailFilter,
  280. URLFilter,
  281. WikiWordFilter,
  282. WordsWithDigitsFilter,
  283. WordsWithUnderscores,
  284. CamelCasedWord,
  285. SphinxDirectives,
  286. ],
  287. )
  288. self.initialized = True
  289. def close(self):
  290. if self.private_dict_file:
  291. self.private_dict_file.close()
  292. def _check_spelling(self, msgid, line, line_num):
  293. original_line = line
  294. try:
  295. initial_space = re.search(r"^[^\S]\s*", line).regs[0][1]
  296. except (IndexError, AttributeError):
  297. initial_space = 0
  298. if line.strip().startswith("#") and "docstring" not in msgid:
  299. line = line.strip()[1:]
  300. # A ``Filter`` cannot determine if the directive is at the beginning of a line,
  301. # nor determine if a colon is present or not (``pyenchant`` strips trailing colons).
  302. # So implementing this here.
  303. for iter_directive in self.ignore_comment_directive_list:
  304. if line.startswith(" " + iter_directive):
  305. line = line[(len(iter_directive) + 1) :]
  306. break
  307. starts_with_comment = True
  308. else:
  309. starts_with_comment = False
  310. line = _strip_code_flanked_in_backticks(line)
  311. for word, word_start_at in self.tokenizer(line.strip()):
  312. word_start_at += initial_space
  313. lower_cased_word = word.casefold()
  314. # Skip words from ignore list.
  315. if word in self.ignore_list or lower_cased_word in self.ignore_list:
  316. continue
  317. # Strip starting u' from unicode literals and r' from raw strings.
  318. if word.startswith(("u'", 'u"', "r'", 'r"')) and len(word) > 2:
  319. word = word[2:]
  320. lower_cased_word = lower_cased_word[2:]
  321. # If it is a known word, then continue.
  322. try:
  323. if self.spelling_dict.check(lower_cased_word):
  324. # The lower cased version of word passed spell checking
  325. continue
  326. # If we reached this far, it means there was a spelling mistake.
  327. # Let's retry with the original work because 'unicode' is a
  328. # spelling mistake but 'Unicode' is not
  329. if self.spelling_dict.check(word):
  330. continue
  331. except enchant.errors.Error:
  332. self.add_message(
  333. "invalid-characters-in-docstring", line=line_num, args=(word,)
  334. )
  335. continue
  336. # Store word to private dict or raise a message.
  337. if self.config.spelling_store_unknown_words:
  338. if lower_cased_word not in self.unknown_words:
  339. self.private_dict_file.write(f"{lower_cased_word}\n")
  340. self.unknown_words.add(lower_cased_word)
  341. else:
  342. # Present up to N suggestions.
  343. suggestions = self.spelling_dict.suggest(word)
  344. del suggestions[self.config.max_spelling_suggestions :]
  345. line_segment = line[word_start_at:]
  346. match = re.search(fr"(\W|^)({word})(\W|$)", line_segment)
  347. if match:
  348. # Start position of second group in regex.
  349. col = match.regs[2][0]
  350. else:
  351. col = line_segment.index(word)
  352. col += word_start_at
  353. if starts_with_comment:
  354. col += 1
  355. indicator = (" " * col) + ("^" * len(word))
  356. all_suggestion = "' or '".join(suggestions)
  357. args = (word, original_line, indicator, f"'{all_suggestion}'")
  358. self.add_message(msgid, line=line_num, args=args)
  359. def process_tokens(self, tokens):
  360. if not self.initialized:
  361. return
  362. # Process tokens and look for comments.
  363. for (tok_type, token, (start_row, _), _, _) in tokens:
  364. if tok_type == tokenize.COMMENT:
  365. if start_row == 1 and token.startswith("#!/"):
  366. # Skip shebang lines
  367. continue
  368. if token.startswith("# pylint:"):
  369. # Skip pylint enable/disable comments
  370. continue
  371. self._check_spelling("wrong-spelling-in-comment", token, start_row)
  372. @check_messages("wrong-spelling-in-docstring")
  373. def visit_module(self, node: nodes.Module) -> None:
  374. if not self.initialized:
  375. return
  376. self._check_docstring(node)
  377. @check_messages("wrong-spelling-in-docstring")
  378. def visit_classdef(self, node: nodes.ClassDef) -> None:
  379. if not self.initialized:
  380. return
  381. self._check_docstring(node)
  382. @check_messages("wrong-spelling-in-docstring")
  383. def visit_functiondef(self, node: nodes.FunctionDef) -> None:
  384. if not self.initialized:
  385. return
  386. self._check_docstring(node)
  387. visit_asyncfunctiondef = visit_functiondef
  388. def _check_docstring(self, node):
  389. """check the node has any spelling errors"""
  390. docstring = node.doc
  391. if not docstring:
  392. return
  393. start_line = node.lineno + 1
  394. # Go through lines of docstring
  395. for idx, line in enumerate(docstring.splitlines()):
  396. self._check_spelling("wrong-spelling-in-docstring", line, start_line + idx)
  397. def register(linter):
  398. """required method to auto register this checker"""
  399. linter.register_checker(SpellingChecker(linter))