# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
"""Checker for spelling errors in comments and docstrings."""
from __future__ import annotations
import re
import sys
import tokenize
from re import Pattern
from typing import TYPE_CHECKING, Any
from astroid import nodes
from pylint.checkers import BaseTokenChecker
from pylint.checkers.utils import only_required_for_messages
if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal
if TYPE_CHECKING:
from pylint.lint import PyLinter
try:
import enchant
from enchant.tokenize import (
Chunker,
EmailFilter,
Filter,
URLFilter,
WikiWordFilter,
get_tokenizer,
)
PYENCHANT_AVAILABLE = True
except ImportError: # pragma: no cover
enchant = None
PYENCHANT_AVAILABLE = False
class EmailFilter: # type: ignore[no-redef]
...
class URLFilter: # type: ignore[no-redef]
...
class WikiWordFilter: # type: ignore[no-redef]
...
class Filter: # type: ignore[no-redef]
def _skip(self, word: str) -> bool:
raise NotImplementedError
class Chunker: # type: ignore[no-redef]
pass
def get_tokenizer(
tag: str | None = None, # pylint: disable=unused-argument
chunkers: list[Chunker] | None = None, # pylint: disable=unused-argument
filters: list[Filter] | None = None, # pylint: disable=unused-argument
) -> Filter:
return Filter()
def _get_enchant_dicts() -> list[tuple[Any, enchant.ProviderDesc]]:
# Broker().list_dicts() is not typed in enchant, but it does return tuples
return enchant.Broker().list_dicts() if PYENCHANT_AVAILABLE else [] # type: ignore[no-any-return]
def _get_enchant_dict_choices(
inner_enchant_dicts: list[tuple[Any, enchant.ProviderDesc]]
) -> list[str]:
return [""] + [d[0] for d in inner_enchant_dicts]
def _get_enchant_dict_help(
inner_enchant_dicts: list[tuple[Any, enchant.ProviderDesc]],
pyenchant_available: bool,
) -> str:
if inner_enchant_dicts:
dict_as_str = [f"{d[0]} ({d[1].name})" for d in inner_enchant_dicts]
enchant_help = f"Available dictionaries: {', '.join(dict_as_str)}"
else:
enchant_help = "No available dictionaries : You need to install "
if not pyenchant_available:
enchant_help += "both the python package and "
enchant_help += "the system dependency for enchant to work."
return f"Spelling dictionary name. {enchant_help}."
enchant_dicts = _get_enchant_dicts()
class WordsWithDigitsFilter(Filter): # type: ignore[misc]
"""Skips words with digits."""
def _skip(self, word: str) -> bool:
return any(char.isdigit() for char in word)
class WordsWithUnderscores(Filter): # type: ignore[misc]
"""Skips words with underscores.
They are probably function parameter names.
"""
def _skip(self, word: str) -> bool:
return "_" in word
class RegExFilter(Filter): # type: ignore[misc]
"""Parent class for filters using regular expressions.
This filter skips any words the match the expression
assigned to the class attribute ``_pattern``.
"""
_pattern: Pattern[str]
def _skip(self, word: str) -> bool:
return bool(self._pattern.match(word))
class CamelCasedWord(RegExFilter):
r"""Filter skipping over camelCasedWords.
This filter skips any words matching the following regular expression:
^([a-z]\w+[A-Z]+\w+)
That is, any words that are camelCasedWords.
"""
_pattern = re.compile(r"^([a-z]+(\d|[A-Z])(?:\w+)?)")
class SphinxDirectives(RegExFilter):
r"""Filter skipping over Sphinx Directives.
This filter skips any words matching the following regular expression:
^(:([a-z]+)){1,2}:`([^`]+)(`)?
That is, for example, :class:`BaseQuery`
"""
# The final ` in the pattern is optional because enchant strips it out
_pattern = re.compile(r"^(:([a-z]+)){1,2}:`([^`]+)(`)?")
class ForwardSlashChunker(Chunker): # type: ignore[misc]
"""This chunker allows splitting words like 'before/after' into 'before' and
'after'.
"""
_text: str
def next(self) -> tuple[str, int]:
while True:
if not self._text:
raise StopIteration()
if "/" not in self._text:
text = self._text
self._offset = 0
self._text = ""
return text, 0
pre_text, post_text = self._text.split("/", 1)
self._text = post_text
self._offset = 0
if (
not pre_text
or not post_text
or not pre_text[-1].isalpha()
or not post_text[0].isalpha()
):
self._text = ""
self._offset = 0
return f"{pre_text}/{post_text}", 0
return pre_text, 0
def _next(self) -> tuple[str, Literal[0]]:
while True:
if "/" not in self._text:
return self._text, 0
pre_text, post_text = self._text.split("/", 1)
if not pre_text or not post_text:
break
if not pre_text[-1].isalpha() or not post_text[0].isalpha():
raise StopIteration()
self._text = pre_text + " " + post_text
raise StopIteration()
CODE_FLANKED_IN_BACKTICK_REGEX = re.compile(r"(\s|^)(`{1,2})([^`]+)(\2)([^`]|$)")
def _strip_code_flanked_in_backticks(line: str) -> str:
"""Alter line so code flanked in back-ticks is ignored.
Pyenchant automatically strips back-ticks when parsing tokens,
so this cannot be done at the individual filter level.
"""
def replace_code_but_leave_surrounding_characters(match_obj: re.Match[str]) -> str:
return match_obj.group(1) + match_obj.group(5)
return CODE_FLANKED_IN_BACKTICK_REGEX.sub(
replace_code_but_leave_surrounding_characters, line
)
class SpellingChecker(BaseTokenChecker):
"""Check spelling in comments and docstrings."""
name = "spelling"
msgs = {
"C0401": (
"Wrong spelling of a word '%s' in a comment:\n%s\n"
"%s\nDid you mean: '%s'?",
"wrong-spelling-in-comment",
"Used when a word in comment is not spelled correctly.",
),
"C0402": (
"Wrong spelling of a word '%s' in a docstring:\n%s\n"
"%s\nDid you mean: '%s'?",
"wrong-spelling-in-docstring",
"Used when a word in docstring is not spelled correctly.",
),
"C0403": (
"Invalid characters %r in a docstring",
"invalid-characters-in-docstring",
"Used when a word in docstring cannot be checked by enchant.",
),
}
options = (
(
"spelling-dict",
{
"default": "",
"type": "choice",
"metavar": "