spelling.py 16 KB

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