checker.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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. """Basic checker for Python code."""
  5. from __future__ import annotations
  6. import argparse
  7. import collections
  8. import itertools
  9. import re
  10. import sys
  11. from collections.abc import Iterable
  12. from enum import Enum, auto
  13. from re import Pattern
  14. from typing import TYPE_CHECKING, Tuple
  15. import astroid
  16. from astroid import nodes
  17. from pylint import constants, interfaces
  18. from pylint.checkers import utils
  19. from pylint.checkers.base.basic_checker import _BasicChecker
  20. from pylint.checkers.base.name_checker.naming_style import (
  21. KNOWN_NAME_TYPES,
  22. KNOWN_NAME_TYPES_WITH_STYLE,
  23. NAMING_STYLES,
  24. _create_naming_options,
  25. )
  26. from pylint.checkers.utils import is_property_deleter, is_property_setter
  27. from pylint.typing import Options
  28. if TYPE_CHECKING:
  29. from pylint.lint.pylinter import PyLinter
  30. _BadNamesTuple = Tuple[nodes.NodeNG, str, str, interfaces.Confidence]
  31. # Default patterns for name types that do not have styles
  32. DEFAULT_PATTERNS = {
  33. "typevar": re.compile(
  34. r"^_{0,2}(?!T[A-Z])(?:[A-Z]+|(?:[A-Z]+[a-z]+)+T?(?<!Type))(?:_co(?:ntra)?)?$"
  35. ),
  36. "typealias": re.compile(
  37. r"^_{0,2}(?!T[A-Z]|Type)[A-Z]+[a-z0-9]+(?:[A-Z][a-z0-9]+)*$"
  38. ),
  39. }
  40. BUILTIN_PROPERTY = "builtins.property"
  41. TYPE_VAR_QNAME = frozenset(
  42. (
  43. "typing.TypeVar",
  44. "typing_extensions.TypeVar",
  45. )
  46. )
  47. class TypeVarVariance(Enum):
  48. invariant = auto()
  49. covariant = auto()
  50. contravariant = auto()
  51. double_variant = auto()
  52. def _get_properties(config: argparse.Namespace) -> tuple[set[str], set[str]]:
  53. """Returns a tuple of property classes and names.
  54. Property classes are fully qualified, such as 'abc.abstractproperty' and
  55. property names are the actual names, such as 'abstract_property'.
  56. """
  57. property_classes = {BUILTIN_PROPERTY}
  58. property_names: set[str] = set() # Not returning 'property', it has its own check.
  59. if config is not None:
  60. property_classes.update(config.property_classes)
  61. property_names.update(
  62. prop.rsplit(".", 1)[-1] for prop in config.property_classes
  63. )
  64. return property_classes, property_names
  65. def _redefines_import(node: nodes.AssignName) -> bool:
  66. """Detect that the given node (AssignName) is inside an
  67. exception handler and redefines an import from the tryexcept body.
  68. Returns True if the node redefines an import, False otherwise.
  69. """
  70. current = node
  71. while current and not isinstance(current.parent, nodes.ExceptHandler):
  72. current = current.parent
  73. if not current or not utils.error_of_type(current.parent, ImportError):
  74. return False
  75. try_block = current.parent.parent
  76. for import_node in try_block.nodes_of_class((nodes.ImportFrom, nodes.Import)):
  77. for name, alias in import_node.names:
  78. if alias:
  79. if alias == node.name:
  80. return True
  81. elif name == node.name:
  82. return True
  83. return False
  84. def _determine_function_name_type(
  85. node: nodes.FunctionDef, config: argparse.Namespace
  86. ) -> str:
  87. """Determine the name type whose regex the function's name should match.
  88. :param node: A function node.
  89. :param config: Configuration from which to pull additional property classes.
  90. :returns: One of ('function', 'method', 'attr')
  91. """
  92. property_classes, property_names = _get_properties(config)
  93. if not node.is_method():
  94. return "function"
  95. if is_property_setter(node) or is_property_deleter(node):
  96. # If the function is decorated using the prop_method.{setter,getter}
  97. # form, treat it like an attribute as well.
  98. return "attr"
  99. decorators = node.decorators.nodes if node.decorators else []
  100. for decorator in decorators:
  101. # If the function is a property (decorated with @property
  102. # or @abc.abstractproperty), the name type is 'attr'.
  103. if isinstance(decorator, nodes.Name) or (
  104. isinstance(decorator, nodes.Attribute)
  105. and decorator.attrname in property_names
  106. ):
  107. inferred = utils.safe_infer(decorator)
  108. if (
  109. inferred
  110. and hasattr(inferred, "qname")
  111. and inferred.qname() in property_classes
  112. ):
  113. return "attr"
  114. return "method"
  115. # Name categories that are always consistent with all naming conventions.
  116. EXEMPT_NAME_CATEGORIES = {"exempt", "ignore"}
  117. def _is_multi_naming_match(
  118. match: re.Match[str] | None, node_type: str, confidence: interfaces.Confidence
  119. ) -> bool:
  120. return (
  121. match is not None
  122. and match.lastgroup is not None
  123. and match.lastgroup not in EXEMPT_NAME_CATEGORIES
  124. and (node_type != "method" or confidence != interfaces.INFERENCE_FAILURE)
  125. )
  126. class NameChecker(_BasicChecker):
  127. msgs = {
  128. "C0103": (
  129. '%s name "%s" doesn\'t conform to %s',
  130. "invalid-name",
  131. "Used when the name doesn't conform to naming rules "
  132. "associated to its type (constant, variable, class...).",
  133. ),
  134. "C0104": (
  135. 'Disallowed name "%s"',
  136. "disallowed-name",
  137. "Used when the name matches bad-names or bad-names-rgxs- (unauthorized names).",
  138. {
  139. "old_names": [
  140. ("C0102", "blacklisted-name"),
  141. ]
  142. },
  143. ),
  144. "C0105": (
  145. "Type variable name does not reflect variance%s",
  146. "typevar-name-incorrect-variance",
  147. "Emitted when a TypeVar name doesn't reflect its type variance. "
  148. "According to PEP8, it is recommended to add suffixes '_co' and "
  149. "'_contra' to the variables used to declare covariant or "
  150. "contravariant behaviour respectively. Invariant (default) variables "
  151. "do not require a suffix. The message is also emitted when invariant "
  152. "variables do have a suffix.",
  153. ),
  154. "C0131": (
  155. "TypeVar cannot be both covariant and contravariant",
  156. "typevar-double-variance",
  157. 'Emitted when both the "covariant" and "contravariant" '
  158. 'keyword arguments are set to "True" in a TypeVar.',
  159. ),
  160. "C0132": (
  161. 'TypeVar name "%s" does not match assigned variable name "%s"',
  162. "typevar-name-mismatch",
  163. "Emitted when a TypeVar is assigned to a variable "
  164. "that does not match its name argument.",
  165. ),
  166. }
  167. _options: Options = (
  168. (
  169. "good-names",
  170. {
  171. "default": ("i", "j", "k", "ex", "Run", "_"),
  172. "type": "csv",
  173. "metavar": "<names>",
  174. "help": "Good variable names which should always be accepted,"
  175. " separated by a comma.",
  176. },
  177. ),
  178. (
  179. "good-names-rgxs",
  180. {
  181. "default": "",
  182. "type": "regexp_csv",
  183. "metavar": "<names>",
  184. "help": "Good variable names regexes, separated by a comma. If names match any regex,"
  185. " they will always be accepted",
  186. },
  187. ),
  188. (
  189. "bad-names",
  190. {
  191. "default": ("foo", "bar", "baz", "toto", "tutu", "tata"),
  192. "type": "csv",
  193. "metavar": "<names>",
  194. "help": "Bad variable names which should always be refused, "
  195. "separated by a comma.",
  196. },
  197. ),
  198. (
  199. "bad-names-rgxs",
  200. {
  201. "default": "",
  202. "type": "regexp_csv",
  203. "metavar": "<names>",
  204. "help": "Bad variable names regexes, separated by a comma. If names match any regex,"
  205. " they will always be refused",
  206. },
  207. ),
  208. (
  209. "name-group",
  210. {
  211. "default": (),
  212. "type": "csv",
  213. "metavar": "<name1:name2>",
  214. "help": (
  215. "Colon-delimited sets of names that determine each"
  216. " other's naming style when the name regexes"
  217. " allow several styles."
  218. ),
  219. },
  220. ),
  221. (
  222. "include-naming-hint",
  223. {
  224. "default": False,
  225. "type": "yn",
  226. "metavar": "<y or n>",
  227. "help": "Include a hint for the correct naming format with invalid-name.",
  228. },
  229. ),
  230. (
  231. "property-classes",
  232. {
  233. "default": ("abc.abstractproperty",),
  234. "type": "csv",
  235. "metavar": "<decorator names>",
  236. "help": "List of decorators that produce properties, such as "
  237. "abc.abstractproperty. Add to this list to register "
  238. "other decorators that produce valid properties. "
  239. "These decorators are taken in consideration only for invalid-name.",
  240. },
  241. ),
  242. )
  243. options: Options = _options + _create_naming_options()
  244. def __init__(self, linter: PyLinter) -> None:
  245. super().__init__(linter)
  246. self._name_group: dict[str, str] = {}
  247. self._bad_names: dict[str, dict[str, list[_BadNamesTuple]]] = {}
  248. self._name_regexps: dict[str, re.Pattern[str]] = {}
  249. self._name_hints: dict[str, str] = {}
  250. self._good_names_rgxs_compiled: list[re.Pattern[str]] = []
  251. self._bad_names_rgxs_compiled: list[re.Pattern[str]] = []
  252. def open(self) -> None:
  253. self.linter.stats.reset_bad_names()
  254. for group in self.linter.config.name_group:
  255. for name_type in group.split(":"):
  256. self._name_group[name_type] = f"group_{group}"
  257. regexps, hints = self._create_naming_rules()
  258. self._name_regexps = regexps
  259. self._name_hints = hints
  260. self._good_names_rgxs_compiled = [
  261. re.compile(rgxp) for rgxp in self.linter.config.good_names_rgxs
  262. ]
  263. self._bad_names_rgxs_compiled = [
  264. re.compile(rgxp) for rgxp in self.linter.config.bad_names_rgxs
  265. ]
  266. def _create_naming_rules(self) -> tuple[dict[str, Pattern[str]], dict[str, str]]:
  267. regexps: dict[str, Pattern[str]] = {}
  268. hints: dict[str, str] = {}
  269. for name_type in KNOWN_NAME_TYPES:
  270. if name_type in KNOWN_NAME_TYPES_WITH_STYLE:
  271. naming_style_name = getattr(
  272. self.linter.config, f"{name_type}_naming_style"
  273. )
  274. regexps[name_type] = NAMING_STYLES[naming_style_name].get_regex(
  275. name_type
  276. )
  277. else:
  278. naming_style_name = "predefined"
  279. regexps[name_type] = DEFAULT_PATTERNS[name_type]
  280. custom_regex_setting_name = f"{name_type}_rgx"
  281. custom_regex = getattr(self.linter.config, custom_regex_setting_name, None)
  282. if custom_regex is not None:
  283. regexps[name_type] = custom_regex
  284. if custom_regex is not None:
  285. hints[name_type] = f"{custom_regex.pattern!r} pattern"
  286. else:
  287. hints[name_type] = f"{naming_style_name} naming style"
  288. return regexps, hints
  289. @utils.only_required_for_messages("disallowed-name", "invalid-name")
  290. def visit_module(self, node: nodes.Module) -> None:
  291. self._check_name("module", node.name.split(".")[-1], node)
  292. self._bad_names = {}
  293. def leave_module(self, _: nodes.Module) -> None:
  294. for all_groups in self._bad_names.values():
  295. if len(all_groups) < 2:
  296. continue
  297. groups: collections.defaultdict[
  298. int, list[list[_BadNamesTuple]]
  299. ] = collections.defaultdict(list)
  300. min_warnings = sys.maxsize
  301. prevalent_group, _ = max(all_groups.items(), key=lambda item: len(item[1]))
  302. for group in all_groups.values():
  303. groups[len(group)].append(group)
  304. min_warnings = min(len(group), min_warnings)
  305. if len(groups[min_warnings]) > 1:
  306. by_line = sorted(
  307. groups[min_warnings],
  308. key=lambda group: min( # type: ignore[no-any-return]
  309. warning[0].lineno
  310. for warning in group
  311. if warning[0].lineno is not None
  312. ),
  313. )
  314. warnings: Iterable[_BadNamesTuple] = itertools.chain(*by_line[1:])
  315. else:
  316. warnings = groups[min_warnings][0]
  317. for args in warnings:
  318. self._raise_name_warning(prevalent_group, *args)
  319. @utils.only_required_for_messages("disallowed-name", "invalid-name")
  320. def visit_classdef(self, node: nodes.ClassDef) -> None:
  321. self._check_name("class", node.name, node)
  322. for attr, anodes in node.instance_attrs.items():
  323. if not any(node.instance_attr_ancestors(attr)):
  324. self._check_name("attr", attr, anodes[0])
  325. @utils.only_required_for_messages("disallowed-name", "invalid-name")
  326. def visit_functiondef(self, node: nodes.FunctionDef) -> None:
  327. # Do not emit any warnings if the method is just an implementation
  328. # of a base class method.
  329. confidence = interfaces.HIGH
  330. if node.is_method():
  331. if utils.overrides_a_method(node.parent.frame(future=True), node.name):
  332. return
  333. confidence = (
  334. interfaces.INFERENCE
  335. if utils.has_known_bases(node.parent.frame(future=True))
  336. else interfaces.INFERENCE_FAILURE
  337. )
  338. self._check_name(
  339. _determine_function_name_type(node, config=self.linter.config),
  340. node.name,
  341. node,
  342. confidence,
  343. )
  344. # Check argument names
  345. args = node.args.args
  346. if args is not None:
  347. self._recursive_check_names(args)
  348. visit_asyncfunctiondef = visit_functiondef
  349. @utils.only_required_for_messages(
  350. "disallowed-name",
  351. "invalid-name",
  352. "typevar-name-incorrect-variance",
  353. "typevar-double-variance",
  354. "typevar-name-mismatch",
  355. )
  356. def visit_assignname( # pylint: disable=too-many-branches
  357. self, node: nodes.AssignName
  358. ) -> None:
  359. """Check module level assigned names."""
  360. frame = node.frame(future=True)
  361. assign_type = node.assign_type()
  362. # Check names defined in comprehensions
  363. if isinstance(assign_type, nodes.Comprehension):
  364. self._check_name("inlinevar", node.name, node)
  365. # Check names defined in module scope
  366. elif isinstance(frame, nodes.Module):
  367. # Check names defined in Assign nodes
  368. if isinstance(assign_type, nodes.Assign):
  369. inferred_assign_type = utils.safe_infer(assign_type.value)
  370. # Check TypeVar's and TypeAliases assigned alone or in tuple assignment
  371. if isinstance(node.parent, nodes.Assign):
  372. if self._assigns_typevar(assign_type.value):
  373. self._check_name("typevar", assign_type.targets[0].name, node)
  374. return
  375. if self._assigns_typealias(assign_type.value):
  376. self._check_name("typealias", assign_type.targets[0].name, node)
  377. return
  378. if (
  379. isinstance(node.parent, nodes.Tuple)
  380. and isinstance(assign_type.value, nodes.Tuple)
  381. # protect against unbalanced tuple unpacking
  382. and node.parent.elts.index(node) < len(assign_type.value.elts)
  383. ):
  384. assigner = assign_type.value.elts[node.parent.elts.index(node)]
  385. if self._assigns_typevar(assigner):
  386. self._check_name(
  387. "typevar",
  388. assign_type.targets[0]
  389. .elts[node.parent.elts.index(node)]
  390. .name,
  391. node,
  392. )
  393. return
  394. if self._assigns_typealias(assigner):
  395. self._check_name(
  396. "typealias",
  397. assign_type.targets[0]
  398. .elts[node.parent.elts.index(node)]
  399. .name,
  400. node,
  401. )
  402. return
  403. # Check classes (TypeVar's are classes so they need to be excluded first)
  404. elif isinstance(inferred_assign_type, nodes.ClassDef):
  405. self._check_name("class", node.name, node)
  406. # Don't emit if the name redefines an import in an ImportError except handler.
  407. elif not _redefines_import(node) and isinstance(
  408. inferred_assign_type, nodes.Const
  409. ):
  410. self._check_name("const", node.name, node)
  411. else:
  412. self._check_name(
  413. "variable", node.name, node, disallowed_check_only=True
  414. )
  415. # Check names defined in AnnAssign nodes
  416. elif isinstance(assign_type, nodes.AnnAssign):
  417. if utils.is_assign_name_annotated_with(node, "Final"):
  418. self._check_name("const", node.name, node)
  419. elif self._assigns_typealias(assign_type.annotation):
  420. self._check_name("typealias", node.name, node)
  421. # Check names defined in function scopes
  422. elif isinstance(frame, nodes.FunctionDef):
  423. # global introduced variable aren't in the function locals
  424. if node.name in frame and node.name not in frame.argnames():
  425. if not _redefines_import(node):
  426. self._check_name("variable", node.name, node)
  427. # Check names defined in class scopes
  428. elif isinstance(frame, nodes.ClassDef):
  429. if not list(frame.local_attr_ancestors(node.name)):
  430. for ancestor in frame.ancestors():
  431. if utils.is_enum(ancestor) or utils.is_assign_name_annotated_with(
  432. node, "Final"
  433. ):
  434. self._check_name("class_const", node.name, node)
  435. break
  436. else:
  437. self._check_name("class_attribute", node.name, node)
  438. def _recursive_check_names(self, args: list[nodes.AssignName]) -> None:
  439. """Check names in a possibly recursive list <arg>."""
  440. for arg in args:
  441. self._check_name("argument", arg.name, arg)
  442. def _find_name_group(self, node_type: str) -> str:
  443. return self._name_group.get(node_type, node_type)
  444. def _raise_name_warning(
  445. self,
  446. prevalent_group: str | None,
  447. node: nodes.NodeNG,
  448. node_type: str,
  449. name: str,
  450. confidence: interfaces.Confidence,
  451. warning: str = "invalid-name",
  452. ) -> None:
  453. type_label = constants.HUMAN_READABLE_TYPES[node_type]
  454. hint = self._name_hints[node_type]
  455. if prevalent_group:
  456. # This happens in the multi naming match case. The expected
  457. # prevalent group needs to be spelled out to make the message
  458. # correct.
  459. hint = f"the `{prevalent_group}` group in the {hint}"
  460. if self.linter.config.include_naming_hint:
  461. hint += f" ({self._name_regexps[node_type].pattern!r} pattern)"
  462. args = (
  463. (type_label.capitalize(), name, hint)
  464. if warning == "invalid-name"
  465. else (type_label.capitalize(), name)
  466. )
  467. self.add_message(warning, node=node, args=args, confidence=confidence)
  468. self.linter.stats.increase_bad_name(node_type, 1)
  469. def _name_allowed_by_regex(self, name: str) -> bool:
  470. return name in self.linter.config.good_names or any(
  471. pattern.match(name) for pattern in self._good_names_rgxs_compiled
  472. )
  473. def _name_disallowed_by_regex(self, name: str) -> bool:
  474. return name in self.linter.config.bad_names or any(
  475. pattern.match(name) for pattern in self._bad_names_rgxs_compiled
  476. )
  477. def _check_name(
  478. self,
  479. node_type: str,
  480. name: str,
  481. node: nodes.NodeNG,
  482. confidence: interfaces.Confidence = interfaces.HIGH,
  483. disallowed_check_only: bool = False,
  484. ) -> None:
  485. """Check for a name using the type's regexp."""
  486. def _should_exempt_from_invalid_name(node: nodes.NodeNG) -> bool:
  487. if node_type == "variable":
  488. inferred = utils.safe_infer(node)
  489. if isinstance(inferred, nodes.ClassDef):
  490. return True
  491. return False
  492. if self._name_allowed_by_regex(name=name):
  493. return
  494. if self._name_disallowed_by_regex(name=name):
  495. self.linter.stats.increase_bad_name(node_type, 1)
  496. self.add_message(
  497. "disallowed-name", node=node, args=name, confidence=interfaces.HIGH
  498. )
  499. return
  500. regexp = self._name_regexps[node_type]
  501. match = regexp.match(name)
  502. if _is_multi_naming_match(match, node_type, confidence):
  503. name_group = self._find_name_group(node_type)
  504. bad_name_group = self._bad_names.setdefault(name_group, {})
  505. # Ignored because this is checked by the if statement
  506. warnings = bad_name_group.setdefault(match.lastgroup, []) # type: ignore[union-attr, arg-type]
  507. warnings.append((node, node_type, name, confidence))
  508. if (
  509. match is None
  510. and not disallowed_check_only
  511. and not _should_exempt_from_invalid_name(node)
  512. ):
  513. self._raise_name_warning(None, node, node_type, name, confidence)
  514. # Check TypeVar names for variance suffixes
  515. if node_type == "typevar":
  516. self._check_typevar(name, node)
  517. @staticmethod
  518. def _assigns_typevar(node: nodes.NodeNG | None) -> bool:
  519. """Check if a node is assigning a TypeVar."""
  520. if isinstance(node, astroid.Call):
  521. inferred = utils.safe_infer(node.func)
  522. if (
  523. isinstance(inferred, astroid.ClassDef)
  524. and inferred.qname() in TYPE_VAR_QNAME
  525. ):
  526. return True
  527. return False
  528. @staticmethod
  529. def _assigns_typealias(node: nodes.NodeNG | None) -> bool:
  530. """Check if a node is assigning a TypeAlias."""
  531. inferred = utils.safe_infer(node)
  532. if isinstance(inferred, nodes.ClassDef):
  533. if inferred.qname() == ".Union":
  534. # Union is a special case because it can be used as a type alias
  535. # or as a type annotation. We only want to check the former.
  536. assert node is not None
  537. return not isinstance(node.parent, nodes.AnnAssign)
  538. elif isinstance(inferred, nodes.FunctionDef):
  539. if inferred.qname() == "typing.TypeAlias":
  540. return True
  541. return False
  542. def _check_typevar(self, name: str, node: nodes.AssignName) -> None:
  543. """Check for TypeVar lint violations."""
  544. if isinstance(node.parent, nodes.Assign):
  545. keywords = node.assign_type().value.keywords
  546. args = node.assign_type().value.args
  547. elif isinstance(node.parent, nodes.Tuple):
  548. keywords = (
  549. node.assign_type().value.elts[node.parent.elts.index(node)].keywords
  550. )
  551. args = node.assign_type().value.elts[node.parent.elts.index(node)].args
  552. variance = TypeVarVariance.invariant
  553. name_arg = None
  554. for kw in keywords:
  555. if variance == TypeVarVariance.double_variant:
  556. pass
  557. elif kw.arg == "covariant" and kw.value.value:
  558. variance = (
  559. TypeVarVariance.covariant
  560. if variance != TypeVarVariance.contravariant
  561. else TypeVarVariance.double_variant
  562. )
  563. elif kw.arg == "contravariant" and kw.value.value:
  564. variance = (
  565. TypeVarVariance.contravariant
  566. if variance != TypeVarVariance.covariant
  567. else TypeVarVariance.double_variant
  568. )
  569. if kw.arg == "name" and isinstance(kw.value, nodes.Const):
  570. name_arg = kw.value.value
  571. if name_arg is None and args and isinstance(args[0], nodes.Const):
  572. name_arg = args[0].value
  573. if variance == TypeVarVariance.double_variant:
  574. self.add_message(
  575. "typevar-double-variance",
  576. node=node,
  577. confidence=interfaces.INFERENCE,
  578. )
  579. self.add_message(
  580. "typevar-name-incorrect-variance",
  581. node=node,
  582. args=("",),
  583. confidence=interfaces.INFERENCE,
  584. )
  585. elif variance == TypeVarVariance.covariant and not name.endswith("_co"):
  586. suggest_name = f"{re.sub('_contra$', '', name)}_co"
  587. self.add_message(
  588. "typevar-name-incorrect-variance",
  589. node=node,
  590. args=(f'. "{name}" is covariant, use "{suggest_name}" instead'),
  591. confidence=interfaces.INFERENCE,
  592. )
  593. elif variance == TypeVarVariance.contravariant and not name.endswith("_contra"):
  594. suggest_name = f"{re.sub('_co$', '', name)}_contra"
  595. self.add_message(
  596. "typevar-name-incorrect-variance",
  597. node=node,
  598. args=(f'. "{name}" is contravariant, use "{suggest_name}" instead'),
  599. confidence=interfaces.INFERENCE,
  600. )
  601. elif variance == TypeVarVariance.invariant and (
  602. name.endswith("_co") or name.endswith("_contra")
  603. ):
  604. suggest_name = re.sub("_contra$|_co$", "", name)
  605. self.add_message(
  606. "typevar-name-incorrect-variance",
  607. node=node,
  608. args=(f'. "{name}" is invariant, use "{suggest_name}" instead'),
  609. confidence=interfaces.INFERENCE,
  610. )
  611. if name_arg is not None and name_arg != name:
  612. self.add_message(
  613. "typevar-name-mismatch",
  614. node=node,
  615. args=(name_arg, name),
  616. confidence=interfaces.INFERENCE,
  617. )