spelling.py 16 KB

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