common.py 11 KB

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