message_registry.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. """Message constants for generating error messages during type checking.
  2. Literal messages should be defined as constants in this module so they won't get out of sync
  3. if used in more than one place, and so that they can be easily introspected. These messages are
  4. ultimately consumed by messages.MessageBuilder.fail(). For more non-trivial message generation,
  5. add a method to MessageBuilder and call this instead.
  6. """
  7. from __future__ import annotations
  8. from typing import Final, NamedTuple
  9. from mypy import errorcodes as codes
  10. class ErrorMessage(NamedTuple):
  11. value: str
  12. code: codes.ErrorCode | None = None
  13. def format(self, *args: object, **kwargs: object) -> ErrorMessage:
  14. return ErrorMessage(self.value.format(*args, **kwargs), code=self.code)
  15. def with_additional_msg(self, info: str) -> ErrorMessage:
  16. return ErrorMessage(self.value + info, code=self.code)
  17. # Invalid types
  18. INVALID_TYPE_RAW_ENUM_VALUE: Final = ErrorMessage(
  19. "Invalid type: try using Literal[{}.{}] instead?", codes.VALID_TYPE
  20. )
  21. # Type checker error message constants
  22. NO_RETURN_VALUE_EXPECTED: Final = ErrorMessage("No return value expected", codes.RETURN_VALUE)
  23. MISSING_RETURN_STATEMENT: Final = ErrorMessage("Missing return statement", codes.RETURN)
  24. EMPTY_BODY_ABSTRACT: Final = ErrorMessage(
  25. "If the method is meant to be abstract, use @abc.abstractmethod", codes.EMPTY_BODY
  26. )
  27. INVALID_IMPLICIT_RETURN: Final = ErrorMessage("Implicit return in function which does not return")
  28. INCOMPATIBLE_RETURN_VALUE_TYPE: Final = ErrorMessage(
  29. "Incompatible return value type", codes.RETURN_VALUE
  30. )
  31. RETURN_VALUE_EXPECTED: Final = ErrorMessage("Return value expected", codes.RETURN_VALUE)
  32. NO_RETURN_EXPECTED: Final = ErrorMessage("Return statement in function which does not return")
  33. INVALID_EXCEPTION: Final = ErrorMessage("Exception must be derived from BaseException")
  34. INVALID_EXCEPTION_TYPE: Final = ErrorMessage(
  35. "Exception type must be derived from BaseException (or be a tuple of exception classes)"
  36. )
  37. INVALID_EXCEPTION_GROUP: Final = ErrorMessage(
  38. "Exception type in except* cannot derive from BaseExceptionGroup"
  39. )
  40. RETURN_IN_ASYNC_GENERATOR: Final = ErrorMessage(
  41. '"return" with value in async generator is not allowed'
  42. )
  43. INVALID_RETURN_TYPE_FOR_GENERATOR: Final = ErrorMessage(
  44. 'The return type of a generator function should be "Generator"' " or one of its supertypes"
  45. )
  46. INVALID_RETURN_TYPE_FOR_ASYNC_GENERATOR: Final = ErrorMessage(
  47. 'The return type of an async generator function should be "AsyncGenerator" or one of its '
  48. "supertypes"
  49. )
  50. YIELD_VALUE_EXPECTED: Final = ErrorMessage("Yield value expected")
  51. INCOMPATIBLE_TYPES: Final = ErrorMessage("Incompatible types")
  52. INCOMPATIBLE_TYPES_IN_ASSIGNMENT: Final = ErrorMessage(
  53. "Incompatible types in assignment", code=codes.ASSIGNMENT
  54. )
  55. INCOMPATIBLE_TYPES_IN_AWAIT: Final = ErrorMessage('Incompatible types in "await"')
  56. INCOMPATIBLE_REDEFINITION: Final = ErrorMessage("Incompatible redefinition")
  57. INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AENTER: Final = (
  58. 'Incompatible types in "async with" for "__aenter__"'
  59. )
  60. INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AEXIT: Final = (
  61. 'Incompatible types in "async with" for "__aexit__"'
  62. )
  63. INCOMPATIBLE_TYPES_IN_ASYNC_FOR: Final = 'Incompatible types in "async for"'
  64. INVALID_TYPE_FOR_SLOTS: Final = 'Invalid type for "__slots__"'
  65. ASYNC_FOR_OUTSIDE_COROUTINE: Final = '"async for" outside async function'
  66. ASYNC_WITH_OUTSIDE_COROUTINE: Final = '"async with" outside async function'
  67. INCOMPATIBLE_TYPES_IN_YIELD: Final = ErrorMessage('Incompatible types in "yield"')
  68. INCOMPATIBLE_TYPES_IN_YIELD_FROM: Final = ErrorMessage('Incompatible types in "yield from"')
  69. INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION: Final = "Incompatible types in string interpolation"
  70. INCOMPATIBLE_TYPES_IN_CAPTURE: Final = ErrorMessage("Incompatible types in capture pattern")
  71. MUST_HAVE_NONE_RETURN_TYPE: Final = ErrorMessage('The return type of "{}" must be None')
  72. TUPLE_INDEX_OUT_OF_RANGE: Final = ErrorMessage("Tuple index out of range")
  73. INVALID_SLICE_INDEX: Final = ErrorMessage("Slice index must be an integer, SupportsIndex or None")
  74. CANNOT_INFER_LAMBDA_TYPE: Final = ErrorMessage("Cannot infer type of lambda")
  75. CANNOT_ACCESS_INIT: Final = (
  76. 'Accessing "__init__" on an instance is unsound, since instance.__init__ could be from'
  77. " an incompatible subclass"
  78. )
  79. NON_INSTANCE_NEW_TYPE: Final = ErrorMessage('"__new__" must return a class instance (got {})')
  80. INVALID_NEW_TYPE: Final = ErrorMessage('Incompatible return type for "__new__"')
  81. BAD_CONSTRUCTOR_TYPE: Final = ErrorMessage("Unsupported decorated constructor type")
  82. CANNOT_ASSIGN_TO_METHOD: Final = "Cannot assign to a method"
  83. CANNOT_ASSIGN_TO_TYPE: Final = "Cannot assign to a type"
  84. INCONSISTENT_ABSTRACT_OVERLOAD: Final = ErrorMessage(
  85. "Overloaded method has both abstract and non-abstract variants"
  86. )
  87. MULTIPLE_OVERLOADS_REQUIRED: Final = ErrorMessage("Single overload definition, multiple required")
  88. READ_ONLY_PROPERTY_OVERRIDES_READ_WRITE: Final = ErrorMessage(
  89. "Read-only property cannot override read-write property"
  90. )
  91. FORMAT_REQUIRES_MAPPING: Final = "Format requires a mapping"
  92. RETURN_TYPE_CANNOT_BE_CONTRAVARIANT: Final = ErrorMessage(
  93. "Cannot use a contravariant type variable as return type"
  94. )
  95. FUNCTION_PARAMETER_CANNOT_BE_COVARIANT: Final = ErrorMessage(
  96. "Cannot use a covariant type variable as a parameter"
  97. )
  98. INCOMPATIBLE_IMPORT_OF: Final = ErrorMessage('Incompatible import of "{}"', code=codes.ASSIGNMENT)
  99. FUNCTION_TYPE_EXPECTED: Final = ErrorMessage(
  100. "Function is missing a type annotation", codes.NO_UNTYPED_DEF
  101. )
  102. ONLY_CLASS_APPLICATION: Final = ErrorMessage(
  103. "Type application is only supported for generic classes"
  104. )
  105. RETURN_TYPE_EXPECTED: Final = ErrorMessage(
  106. "Function is missing a return type annotation", codes.NO_UNTYPED_DEF
  107. )
  108. ARGUMENT_TYPE_EXPECTED: Final = ErrorMessage(
  109. "Function is missing a type annotation for one or more arguments", codes.NO_UNTYPED_DEF
  110. )
  111. KEYWORD_ARGUMENT_REQUIRES_STR_KEY_TYPE: Final = ErrorMessage(
  112. 'Keyword argument only valid with "str" key type in call to "dict"'
  113. )
  114. ALL_MUST_BE_SEQ_STR: Final = ErrorMessage("Type of __all__ must be {}, not {}")
  115. INVALID_TYPEDDICT_ARGS: Final = ErrorMessage(
  116. "Expected keyword arguments, {...}, or dict(...) in TypedDict constructor"
  117. )
  118. TYPEDDICT_KEY_MUST_BE_STRING_LITERAL: Final = ErrorMessage(
  119. "Expected TypedDict key to be string literal"
  120. )
  121. MALFORMED_ASSERT: Final = ErrorMessage("Assertion is always true, perhaps remove parentheses?")
  122. DUPLICATE_TYPE_SIGNATURES: Final = ErrorMessage("Function has duplicate type signatures")
  123. DESCRIPTOR_SET_NOT_CALLABLE: Final = ErrorMessage("{}.__set__ is not callable")
  124. DESCRIPTOR_GET_NOT_CALLABLE: Final = "{}.__get__ is not callable"
  125. MODULE_LEVEL_GETATTRIBUTE: Final = ErrorMessage(
  126. "__getattribute__ is not valid at the module level"
  127. )
  128. CLASS_VAR_CONFLICTS_SLOTS: Final = '"{}" in __slots__ conflicts with class variable access'
  129. NAME_NOT_IN_SLOTS: Final = ErrorMessage(
  130. 'Trying to assign name "{}" that is not in "__slots__" of type "{}"'
  131. )
  132. TYPE_ALWAYS_TRUE: Final = ErrorMessage(
  133. "{} which does not implement __bool__ or __len__ "
  134. "so it could always be true in boolean context",
  135. code=codes.TRUTHY_BOOL,
  136. )
  137. TYPE_ALWAYS_TRUE_UNIONTYPE: Final = ErrorMessage(
  138. "{} of which no members implement __bool__ or __len__ "
  139. "so it could always be true in boolean context",
  140. code=codes.TRUTHY_BOOL,
  141. )
  142. FUNCTION_ALWAYS_TRUE: Final = ErrorMessage(
  143. "Function {} could always be true in boolean context", code=codes.TRUTHY_FUNCTION
  144. )
  145. ITERABLE_ALWAYS_TRUE: Final = ErrorMessage(
  146. "{} which can always be true in boolean context. Consider using {} instead.",
  147. code=codes.TRUTHY_ITERABLE,
  148. )
  149. NOT_CALLABLE: Final = "{} not callable"
  150. TYPE_MUST_BE_USED: Final = "Value of type {} must be used"
  151. # Generic
  152. GENERIC_INSTANCE_VAR_CLASS_ACCESS: Final = (
  153. "Access to generic instance variables via class is ambiguous"
  154. )
  155. GENERIC_CLASS_VAR_ACCESS: Final = "Access to generic class variables is ambiguous"
  156. BARE_GENERIC: Final = "Missing type parameters for generic type {}"
  157. IMPLICIT_GENERIC_ANY_BUILTIN: Final = (
  158. 'Implicit generic "Any". Use "{}" and specify generic parameters'
  159. )
  160. INVALID_UNPACK = "{} cannot be unpacked (must be tuple or TypeVarTuple)"
  161. # TypeVar
  162. INCOMPATIBLE_TYPEVAR_VALUE: Final = 'Value of type variable "{}" of {} cannot be {}'
  163. CANNOT_USE_TYPEVAR_AS_EXPRESSION: Final = 'Type variable "{}.{}" cannot be used as an expression'
  164. INVALID_TYPEVAR_AS_TYPEARG: Final = 'Type variable "{}" not valid as type argument value for "{}"'
  165. INVALID_TYPEVAR_ARG_BOUND: Final = 'Type argument {} of "{}" must be a subtype of {}'
  166. INVALID_TYPEVAR_ARG_VALUE: Final = 'Invalid type argument value for "{}"'
  167. TYPEVAR_VARIANCE_DEF: Final = 'TypeVar "{}" may only be a literal bool'
  168. TYPEVAR_ARG_MUST_BE_TYPE: Final = '{} "{}" must be a type'
  169. TYPEVAR_UNEXPECTED_ARGUMENT: Final = 'Unexpected argument to "TypeVar()"'
  170. UNBOUND_TYPEVAR: Final = (
  171. "A function returning TypeVar should receive at least "
  172. "one argument containing the same TypeVar"
  173. )
  174. # Super
  175. TOO_MANY_ARGS_FOR_SUPER: Final = ErrorMessage('Too many arguments for "super"')
  176. SUPER_WITH_SINGLE_ARG_NOT_SUPPORTED: Final = ErrorMessage(
  177. '"super" with a single argument not supported'
  178. )
  179. UNSUPPORTED_ARG_1_FOR_SUPER: Final = ErrorMessage('Unsupported argument 1 for "super"')
  180. UNSUPPORTED_ARG_2_FOR_SUPER: Final = ErrorMessage('Unsupported argument 2 for "super"')
  181. SUPER_VARARGS_NOT_SUPPORTED: Final = ErrorMessage('Varargs not supported with "super"')
  182. SUPER_POSITIONAL_ARGS_REQUIRED: Final = ErrorMessage('"super" only accepts positional arguments')
  183. SUPER_ARG_2_NOT_INSTANCE_OF_ARG_1: Final = ErrorMessage(
  184. 'Argument 2 for "super" not an instance of argument 1'
  185. )
  186. TARGET_CLASS_HAS_NO_BASE_CLASS: Final = ErrorMessage("Target class has no base class")
  187. SUPER_OUTSIDE_OF_METHOD_NOT_SUPPORTED: Final = ErrorMessage(
  188. "super() outside of a method is not supported"
  189. )
  190. SUPER_ENCLOSING_POSITIONAL_ARGS_REQUIRED: Final = ErrorMessage(
  191. "super() requires one or more positional arguments in enclosing function"
  192. )
  193. # Self-type
  194. MISSING_OR_INVALID_SELF_TYPE: Final = ErrorMessage(
  195. "Self argument missing for a non-static method (or an invalid type for self)"
  196. )
  197. ERASED_SELF_TYPE_NOT_SUPERTYPE: Final = ErrorMessage(
  198. 'The erased type of self "{}" is not a supertype of its class "{}"'
  199. )
  200. # Final
  201. CANNOT_INHERIT_FROM_FINAL: Final = ErrorMessage('Cannot inherit from final class "{}"')
  202. DEPENDENT_FINAL_IN_CLASS_BODY: Final = ErrorMessage(
  203. "Final name declared in class body cannot depend on type variables"
  204. )
  205. CANNOT_ACCESS_FINAL_INSTANCE_ATTR: Final = (
  206. 'Cannot access final instance attribute "{}" on class object'
  207. )
  208. CANNOT_MAKE_DELETABLE_FINAL: Final = ErrorMessage("Deletable attribute cannot be final")
  209. # Enum
  210. ENUM_MEMBERS_ATTR_WILL_BE_OVERRIDEN: Final = ErrorMessage(
  211. 'Assigned "__members__" will be overridden by "Enum" internally'
  212. )
  213. # ClassVar
  214. CANNOT_OVERRIDE_INSTANCE_VAR: Final = ErrorMessage(
  215. 'Cannot override instance variable (previously declared on base class "{}") with class '
  216. "variable"
  217. )
  218. CANNOT_OVERRIDE_CLASS_VAR: Final = ErrorMessage(
  219. 'Cannot override class variable (previously declared on base class "{}") with instance '
  220. "variable"
  221. )
  222. CLASS_VAR_WITH_TYPEVARS: Final = "ClassVar cannot contain type variables"
  223. CLASS_VAR_WITH_GENERIC_SELF: Final = "ClassVar cannot contain Self type in generic classes"
  224. CLASS_VAR_OUTSIDE_OF_CLASS: Final = "ClassVar can only be used for assignments in class body"
  225. # Protocol
  226. RUNTIME_PROTOCOL_EXPECTED: Final = ErrorMessage(
  227. "Only @runtime_checkable protocols can be used with instance and class checks"
  228. )
  229. CANNOT_INSTANTIATE_PROTOCOL: Final = ErrorMessage('Cannot instantiate protocol class "{}"')
  230. TOO_MANY_UNION_COMBINATIONS: Final = ErrorMessage(
  231. "Not all union combinations were tried because there are too many unions"
  232. )
  233. CONTIGUOUS_ITERABLE_EXPECTED: Final = ErrorMessage("Contiguous iterable with same type expected")
  234. ITERABLE_TYPE_EXPECTED: Final = ErrorMessage("Invalid type '{}' for *expr (iterable expected)")
  235. TYPE_GUARD_POS_ARG_REQUIRED: Final = ErrorMessage("Type guard requires positional argument")
  236. # Match Statement
  237. MISSING_MATCH_ARGS: Final = 'Class "{}" doesn\'t define "__match_args__"'
  238. OR_PATTERN_ALTERNATIVE_NAMES: Final = "Alternative patterns bind different names"
  239. CLASS_PATTERN_GENERIC_TYPE_ALIAS: Final = (
  240. "Class pattern class must not be a type alias with type parameters"
  241. )
  242. CLASS_PATTERN_TYPE_REQUIRED: Final = 'Expected type in class pattern; found "{}"'
  243. CLASS_PATTERN_TOO_MANY_POSITIONAL_ARGS: Final = "Too many positional patterns for class pattern"
  244. CLASS_PATTERN_KEYWORD_MATCHES_POSITIONAL: Final = (
  245. 'Keyword "{}" already matches a positional pattern'
  246. )
  247. CLASS_PATTERN_DUPLICATE_KEYWORD_PATTERN: Final = 'Duplicate keyword pattern "{}"'
  248. CLASS_PATTERN_UNKNOWN_KEYWORD: Final = 'Class "{}" has no attribute "{}"'
  249. CLASS_PATTERN_CLASS_OR_STATIC_METHOD: Final = "Cannot have both classmethod and staticmethod"
  250. MULTIPLE_ASSIGNMENTS_IN_PATTERN: Final = 'Multiple assignments to name "{}" in pattern'
  251. CANNOT_MODIFY_MATCH_ARGS: Final = 'Cannot assign to "__match_args__"'
  252. DATACLASS_FIELD_ALIAS_MUST_BE_LITERAL: Final = (
  253. '"alias" argument to dataclass field must be a string literal'
  254. )
  255. DATACLASS_POST_INIT_MUST_BE_A_FUNCTION: Final = '"__post_init__" method must be an instance method'
  256. # fastparse
  257. FAILED_TO_MERGE_OVERLOADS: Final = ErrorMessage(
  258. "Condition can't be inferred, unable to merge overloads"
  259. )
  260. TYPE_IGNORE_WITH_ERRCODE_ON_MODULE: Final = ErrorMessage(
  261. "type ignore with error code is not supported for modules; "
  262. 'use `# mypy: disable-error-code="{}"`',
  263. codes.SYNTAX,
  264. )
  265. INVALID_TYPE_IGNORE: Final = ErrorMessage('Invalid "type: ignore" comment', codes.SYNTAX)
  266. TYPE_COMMENT_SYNTAX_ERROR_VALUE: Final = ErrorMessage(
  267. 'Syntax error in type comment "{}"', codes.SYNTAX
  268. )
  269. ELLIPSIS_WITH_OTHER_TYPEARGS: Final = ErrorMessage(
  270. "Ellipses cannot accompany other argument types in function type signature", codes.SYNTAX
  271. )
  272. TYPE_SIGNATURE_TOO_MANY_ARGS: Final = ErrorMessage(
  273. "Type signature has too many arguments", codes.SYNTAX
  274. )
  275. TYPE_SIGNATURE_TOO_FEW_ARGS: Final = ErrorMessage(
  276. "Type signature has too few arguments", codes.SYNTAX
  277. )
  278. ARG_CONSTRUCTOR_NAME_EXPECTED: Final = ErrorMessage("Expected arg constructor name", codes.SYNTAX)
  279. ARG_CONSTRUCTOR_TOO_MANY_ARGS: Final = ErrorMessage(
  280. "Too many arguments for argument constructor", codes.SYNTAX
  281. )
  282. MULTIPLE_VALUES_FOR_NAME_KWARG: Final = ErrorMessage(
  283. '"{}" gets multiple values for keyword argument "name"', codes.SYNTAX
  284. )
  285. MULTIPLE_VALUES_FOR_TYPE_KWARG: Final = ErrorMessage(
  286. '"{}" gets multiple values for keyword argument "type"', codes.SYNTAX
  287. )
  288. ARG_CONSTRUCTOR_UNEXPECTED_ARG: Final = ErrorMessage(
  289. 'Unexpected argument "{}" for argument constructor', codes.SYNTAX
  290. )
  291. ARG_NAME_EXPECTED_STRING_LITERAL: Final = ErrorMessage(
  292. "Expected string literal for argument name, got {}", codes.SYNTAX
  293. )