common.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. from __future__ import annotations
  2. from mypy.argmap import map_actuals_to_formals
  3. from mypy.fixup import TypeFixer
  4. from mypy.nodes import (
  5. ARG_POS,
  6. MDEF,
  7. SYMBOL_FUNCBASE_TYPES,
  8. Argument,
  9. Block,
  10. CallExpr,
  11. ClassDef,
  12. Decorator,
  13. Expression,
  14. FuncDef,
  15. JsonDict,
  16. NameExpr,
  17. Node,
  18. PassStmt,
  19. RefExpr,
  20. SymbolTableNode,
  21. Var,
  22. )
  23. from mypy.plugin import CheckerPluginInterface, ClassDefContext, SemanticAnalyzerPluginInterface
  24. from mypy.semanal_shared import (
  25. ALLOW_INCOMPATIBLE_OVERRIDE,
  26. parse_bool,
  27. require_bool_literal_argument,
  28. set_callable_name,
  29. )
  30. from mypy.typeops import try_getting_str_literals as try_getting_str_literals
  31. from mypy.types import (
  32. AnyType,
  33. CallableType,
  34. Instance,
  35. LiteralType,
  36. NoneType,
  37. Overloaded,
  38. Type,
  39. TypeOfAny,
  40. TypeType,
  41. TypeVarType,
  42. deserialize_type,
  43. get_proper_type,
  44. )
  45. from mypy.types_utils import is_optional
  46. from mypy.typevars import fill_typevars
  47. from mypy.util import get_unique_redefinition_name
  48. def _get_decorator_bool_argument(ctx: ClassDefContext, name: str, default: bool) -> bool:
  49. """Return the bool argument for the decorator.
  50. This handles both @decorator(...) and @decorator.
  51. """
  52. if isinstance(ctx.reason, CallExpr):
  53. return _get_bool_argument(ctx, ctx.reason, name, default)
  54. else:
  55. return default
  56. def _get_bool_argument(ctx: ClassDefContext, expr: CallExpr, name: str, default: bool) -> bool:
  57. """Return the boolean value for an argument to a call or the
  58. default if it's not found.
  59. """
  60. attr_value = _get_argument(expr, name)
  61. if attr_value:
  62. return require_bool_literal_argument(ctx.api, attr_value, name, default)
  63. return default
  64. def _get_argument(call: CallExpr, name: str) -> Expression | None:
  65. """Return the expression for the specific argument."""
  66. # To do this we use the CallableType of the callee to find the FormalArgument,
  67. # then walk the actual CallExpr looking for the appropriate argument.
  68. #
  69. # Note: I'm not hard-coding the index so that in the future we can support other
  70. # attrib and class makers.
  71. callee_type = _get_callee_type(call)
  72. if not callee_type:
  73. return None
  74. argument = callee_type.argument_by_name(name)
  75. if not argument:
  76. return None
  77. assert argument.name
  78. for i, (attr_name, attr_value) in enumerate(zip(call.arg_names, call.args)):
  79. if argument.pos is not None and not attr_name and i == argument.pos:
  80. return attr_value
  81. if attr_name == argument.name:
  82. return attr_value
  83. return None
  84. def find_shallow_matching_overload_item(overload: Overloaded, call: CallExpr) -> CallableType:
  85. """Perform limited lookup of a matching overload item.
  86. Full overload resolution is only supported during type checking, but plugins
  87. sometimes need to resolve overloads. This can be used in some such use cases.
  88. Resolve overloads based on these things only:
  89. * Match using argument kinds and names
  90. * If formal argument has type None, only accept the "None" expression in the callee
  91. * If formal argument has type Literal[True] or Literal[False], only accept the
  92. relevant bool literal
  93. Return the first matching overload item, or the last one if nothing matches.
  94. """
  95. for item in overload.items[:-1]:
  96. ok = True
  97. mapped = map_actuals_to_formals(
  98. call.arg_kinds,
  99. call.arg_names,
  100. item.arg_kinds,
  101. item.arg_names,
  102. lambda i: AnyType(TypeOfAny.special_form),
  103. )
  104. # Look for extra actuals
  105. matched_actuals = set()
  106. for actuals in mapped:
  107. matched_actuals.update(actuals)
  108. if any(i not in matched_actuals for i in range(len(call.args))):
  109. ok = False
  110. for arg_type, kind, actuals in zip(item.arg_types, item.arg_kinds, mapped):
  111. if kind.is_required() and not actuals:
  112. # Missing required argument
  113. ok = False
  114. break
  115. elif actuals:
  116. args = [call.args[i] for i in actuals]
  117. arg_type = get_proper_type(arg_type)
  118. arg_none = any(isinstance(arg, NameExpr) and arg.name == "None" for arg in args)
  119. if isinstance(arg_type, NoneType):
  120. if not arg_none:
  121. ok = False
  122. break
  123. elif (
  124. arg_none
  125. and not is_optional(arg_type)
  126. and not (
  127. isinstance(arg_type, Instance)
  128. and arg_type.type.fullname == "builtins.object"
  129. )
  130. and not isinstance(arg_type, AnyType)
  131. ):
  132. ok = False
  133. break
  134. elif isinstance(arg_type, LiteralType) and type(arg_type.value) is bool:
  135. if not any(parse_bool(arg) == arg_type.value for arg in args):
  136. ok = False
  137. break
  138. if ok:
  139. return item
  140. return overload.items[-1]
  141. def _get_callee_type(call: CallExpr) -> CallableType | None:
  142. """Return the type of the callee, regardless of its syntatic form."""
  143. callee_node: Node | None = call.callee
  144. if isinstance(callee_node, RefExpr):
  145. callee_node = callee_node.node
  146. # Some decorators may be using typing.dataclass_transform, which is itself a decorator, so we
  147. # need to unwrap them to get at the true callee
  148. if isinstance(callee_node, Decorator):
  149. callee_node = callee_node.func
  150. if isinstance(callee_node, (Var, SYMBOL_FUNCBASE_TYPES)) and callee_node.type:
  151. callee_node_type = get_proper_type(callee_node.type)
  152. if isinstance(callee_node_type, Overloaded):
  153. return find_shallow_matching_overload_item(callee_node_type, call)
  154. elif isinstance(callee_node_type, CallableType):
  155. return callee_node_type
  156. return None
  157. def add_method(
  158. ctx: ClassDefContext,
  159. name: str,
  160. args: list[Argument],
  161. return_type: Type,
  162. self_type: Type | None = None,
  163. tvar_def: TypeVarType | None = None,
  164. is_classmethod: bool = False,
  165. is_staticmethod: bool = False,
  166. ) -> None:
  167. """
  168. Adds a new method to a class.
  169. Deprecated, use add_method_to_class() instead.
  170. """
  171. add_method_to_class(
  172. ctx.api,
  173. ctx.cls,
  174. name=name,
  175. args=args,
  176. return_type=return_type,
  177. self_type=self_type,
  178. tvar_def=tvar_def,
  179. is_classmethod=is_classmethod,
  180. is_staticmethod=is_staticmethod,
  181. )
  182. def add_method_to_class(
  183. api: SemanticAnalyzerPluginInterface | CheckerPluginInterface,
  184. cls: ClassDef,
  185. name: str,
  186. args: list[Argument],
  187. return_type: Type,
  188. self_type: Type | None = None,
  189. tvar_def: TypeVarType | None = None,
  190. is_classmethod: bool = False,
  191. is_staticmethod: bool = False,
  192. ) -> None:
  193. """Adds a new method to a class definition."""
  194. assert not (
  195. is_classmethod is True and is_staticmethod is True
  196. ), "Can't add a new method that's both staticmethod and classmethod."
  197. info = cls.info
  198. # First remove any previously generated methods with the same name
  199. # to avoid clashes and problems in the semantic analyzer.
  200. if name in info.names:
  201. sym = info.names[name]
  202. if sym.plugin_generated and isinstance(sym.node, FuncDef):
  203. cls.defs.body.remove(sym.node)
  204. if isinstance(api, SemanticAnalyzerPluginInterface):
  205. function_type = api.named_type("builtins.function")
  206. else:
  207. function_type = api.named_generic_type("builtins.function", [])
  208. if is_classmethod:
  209. self_type = self_type or TypeType(fill_typevars(info))
  210. first = [Argument(Var("_cls"), self_type, None, ARG_POS, True)]
  211. elif is_staticmethod:
  212. first = []
  213. else:
  214. self_type = self_type or fill_typevars(info)
  215. first = [Argument(Var("self"), self_type, None, ARG_POS)]
  216. args = first + args
  217. arg_types, arg_names, arg_kinds = [], [], []
  218. for arg in args:
  219. assert arg.type_annotation, "All arguments must be fully typed."
  220. arg_types.append(arg.type_annotation)
  221. arg_names.append(arg.variable.name)
  222. arg_kinds.append(arg.kind)
  223. signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type)
  224. if tvar_def:
  225. signature.variables = [tvar_def]
  226. func = FuncDef(name, args, Block([PassStmt()]))
  227. func.info = info
  228. func.type = set_callable_name(signature, func)
  229. func.is_class = is_classmethod
  230. func.is_static = is_staticmethod
  231. func._fullname = info.fullname + "." + name
  232. func.line = info.line
  233. # NOTE: we would like the plugin generated node to dominate, but we still
  234. # need to keep any existing definitions so they get semantically analyzed.
  235. if name in info.names:
  236. # Get a nice unique name instead.
  237. r_name = get_unique_redefinition_name(name, info.names)
  238. info.names[r_name] = info.names[name]
  239. # Add decorator for is_staticmethod. It's unnecessary for is_classmethod.
  240. if is_staticmethod:
  241. func.is_decorated = True
  242. v = Var(name, func.type)
  243. v.info = info
  244. v._fullname = func._fullname
  245. v.is_staticmethod = True
  246. dec = Decorator(func, [], v)
  247. dec.line = info.line
  248. sym = SymbolTableNode(MDEF, dec)
  249. else:
  250. sym = SymbolTableNode(MDEF, func)
  251. sym.plugin_generated = True
  252. info.names[name] = sym
  253. info.defn.defs.body.append(func)
  254. def add_attribute_to_class(
  255. api: SemanticAnalyzerPluginInterface,
  256. cls: ClassDef,
  257. name: str,
  258. typ: Type,
  259. final: bool = False,
  260. no_serialize: bool = False,
  261. override_allow_incompatible: bool = False,
  262. fullname: str | None = None,
  263. is_classvar: bool = False,
  264. ) -> None:
  265. """
  266. Adds a new attribute to a class definition.
  267. This currently only generates the symbol table entry and no corresponding AssignmentStatement
  268. """
  269. info = cls.info
  270. # NOTE: we would like the plugin generated node to dominate, but we still
  271. # need to keep any existing definitions so they get semantically analyzed.
  272. if name in info.names:
  273. # Get a nice unique name instead.
  274. r_name = get_unique_redefinition_name(name, info.names)
  275. info.names[r_name] = info.names[name]
  276. node = Var(name, typ)
  277. node.info = info
  278. node.is_final = final
  279. node.is_classvar = is_classvar
  280. if name in ALLOW_INCOMPATIBLE_OVERRIDE:
  281. node.allow_incompatible_override = True
  282. else:
  283. node.allow_incompatible_override = override_allow_incompatible
  284. if fullname:
  285. node._fullname = fullname
  286. else:
  287. node._fullname = info.fullname + "." + name
  288. info.names[name] = SymbolTableNode(
  289. MDEF, node, plugin_generated=True, no_serialize=no_serialize
  290. )
  291. def deserialize_and_fixup_type(data: str | JsonDict, api: SemanticAnalyzerPluginInterface) -> Type:
  292. typ = deserialize_type(data)
  293. typ.accept(TypeFixer(api.modules, allow_missing=False))
  294. return typ