1
0

mypy_synapse_plugin.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. # Copyright 2020 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """This is a mypy plugin for Synpase to deal with some of the funky typing that
  15. can crop up, e.g the cache descriptors.
  16. """
  17. from typing import Callable, Optional, Tuple, Type, Union
  18. import mypy.types
  19. from mypy.erasetype import remove_instance_last_known_values
  20. from mypy.errorcodes import ErrorCode
  21. from mypy.nodes import ARG_NAMED_OPT, TempNode, Var
  22. from mypy.plugin import FunctionSigContext, MethodSigContext, Plugin
  23. from mypy.typeops import bind_self
  24. from mypy.types import (
  25. AnyType,
  26. CallableType,
  27. Instance,
  28. NoneType,
  29. TupleType,
  30. TypeAliasType,
  31. UninhabitedType,
  32. UnionType,
  33. )
  34. class SynapsePlugin(Plugin):
  35. def get_method_signature_hook(
  36. self, fullname: str
  37. ) -> Optional[Callable[[MethodSigContext], CallableType]]:
  38. if fullname.startswith(
  39. (
  40. "synapse.util.caches.descriptors.CachedFunction.__call__",
  41. "synapse.util.caches.descriptors._LruCachedFunction.__call__",
  42. )
  43. ):
  44. return cached_function_method_signature
  45. if fullname in (
  46. "synapse.util.caches.descriptors._CachedFunctionDescriptor.__call__",
  47. "synapse.util.caches.descriptors._CachedListFunctionDescriptor.__call__",
  48. ):
  49. return check_is_cacheable_wrapper
  50. return None
  51. def _get_true_return_type(signature: CallableType) -> mypy.types.Type:
  52. """
  53. Get the "final" return type of a callable which might return an Awaitable/Deferred.
  54. """
  55. if isinstance(signature.ret_type, Instance):
  56. # If a coroutine, unwrap the coroutine's return type.
  57. if signature.ret_type.type.fullname == "typing.Coroutine":
  58. return signature.ret_type.args[2]
  59. # If an awaitable, unwrap the awaitable's final value.
  60. elif signature.ret_type.type.fullname == "typing.Awaitable":
  61. return signature.ret_type.args[0]
  62. # If a Deferred, unwrap the Deferred's final value.
  63. elif signature.ret_type.type.fullname == "twisted.internet.defer.Deferred":
  64. return signature.ret_type.args[0]
  65. # Otherwise, return the raw value of the function.
  66. return signature.ret_type
  67. def cached_function_method_signature(ctx: MethodSigContext) -> CallableType:
  68. """Fixes the `CachedFunction.__call__` signature to be correct.
  69. It already has *almost* the correct signature, except:
  70. 1. the `self` argument needs to be marked as "bound";
  71. 2. any `cache_context` argument should be removed;
  72. 3. an optional keyword argument `on_invalidated` should be added.
  73. 4. Wrap the return type to always be a Deferred.
  74. """
  75. # 1. Mark this as a bound function signature.
  76. signature: CallableType = bind_self(ctx.default_signature)
  77. # 2. Remove any "cache_context" args.
  78. #
  79. # Note: We should be only doing this if `cache_context=True` is set, but if
  80. # it isn't then the code will raise an exception when its called anyway, so
  81. # it's not the end of the world.
  82. context_arg_index = None
  83. for idx, name in enumerate(signature.arg_names):
  84. if name == "cache_context":
  85. context_arg_index = idx
  86. break
  87. arg_types = list(signature.arg_types)
  88. arg_names = list(signature.arg_names)
  89. arg_kinds = list(signature.arg_kinds)
  90. if context_arg_index:
  91. arg_types.pop(context_arg_index)
  92. arg_names.pop(context_arg_index)
  93. arg_kinds.pop(context_arg_index)
  94. # 3. Add an optional "on_invalidate" argument.
  95. #
  96. # This is a either
  97. # - a callable which accepts no input and returns nothing, or
  98. # - None.
  99. calltyp = UnionType(
  100. [
  101. NoneType(),
  102. CallableType(
  103. arg_types=[],
  104. arg_kinds=[],
  105. arg_names=[],
  106. ret_type=NoneType(),
  107. fallback=ctx.api.named_generic_type("builtins.function", []),
  108. ),
  109. ]
  110. )
  111. arg_types.append(calltyp)
  112. arg_names.append("on_invalidate")
  113. arg_kinds.append(ARG_NAMED_OPT) # Arg is an optional kwarg.
  114. # 4. Ensure the return type is a Deferred.
  115. ret_arg = _get_true_return_type(signature)
  116. # This should be able to use ctx.api.named_generic_type, but that doesn't seem
  117. # to find the correct symbol for anything more than 1 module deep.
  118. #
  119. # modules is not part of CheckerPluginInterface. The following is a combination
  120. # of TypeChecker.named_generic_type and TypeChecker.lookup_typeinfo.
  121. sym = ctx.api.modules["twisted.internet.defer"].names.get("Deferred") # type: ignore[attr-defined]
  122. ret_type = Instance(sym.node, [remove_instance_last_known_values(ret_arg)])
  123. signature = signature.copy_modified(
  124. arg_types=arg_types,
  125. arg_names=arg_names,
  126. arg_kinds=arg_kinds,
  127. ret_type=ret_type,
  128. )
  129. return signature
  130. def check_is_cacheable_wrapper(ctx: MethodSigContext) -> CallableType:
  131. """Asserts that the signature of a method returns a value which can be cached.
  132. Makes no changes to the provided method signature.
  133. """
  134. # The true signature, this isn't being modified so this is what will be returned.
  135. signature: CallableType = ctx.default_signature
  136. if not isinstance(ctx.args[0][0], TempNode):
  137. ctx.api.note("Cached function is not a TempNode?!", ctx.context) # type: ignore[attr-defined]
  138. return signature
  139. orig_sig = ctx.args[0][0].type
  140. if not isinstance(orig_sig, CallableType):
  141. ctx.api.fail("Cached 'function' is not a callable", ctx.context)
  142. return signature
  143. check_is_cacheable(orig_sig, ctx)
  144. return signature
  145. def check_is_cacheable(
  146. signature: CallableType,
  147. ctx: Union[MethodSigContext, FunctionSigContext],
  148. ) -> None:
  149. """
  150. Check if a callable returns a type which can be cached.
  151. Args:
  152. signature: The callable to check.
  153. ctx: The signature context, used for error reporting.
  154. """
  155. # Unwrap the true return type from the cached function.
  156. return_type = _get_true_return_type(signature)
  157. verbose = ctx.api.options.verbosity >= 1
  158. # TODO Technically a cachedList only needs immutable values, but forcing them
  159. # to return Mapping instead of Dict is fine.
  160. ok, note = is_cacheable(return_type, signature, verbose)
  161. if ok:
  162. message = f"function {signature.name} is @cached, returning {return_type}"
  163. else:
  164. message = f"function {signature.name} is @cached, but has mutable return value {return_type}"
  165. if note:
  166. message += f" ({note})"
  167. message = message.replace("builtins.", "").replace("typing.", "")
  168. if ok and note:
  169. ctx.api.note(message, ctx.context) # type: ignore[attr-defined]
  170. elif not ok:
  171. ctx.api.fail(message, ctx.context, code=AT_CACHED_MUTABLE_RETURN)
  172. # Immutable simple values.
  173. IMMUTABLE_VALUE_TYPES = {
  174. "builtins.bool",
  175. "builtins.int",
  176. "builtins.float",
  177. "builtins.str",
  178. "builtins.bytes",
  179. }
  180. # Types defined in Synapse which are known to be immutable.
  181. IMMUTABLE_CUSTOM_TYPES = {
  182. "synapse.synapse_rust.acl.ServerAclEvaluator",
  183. "synapse.synapse_rust.push.FilteredPushRules",
  184. # This is technically not immutable, but close enough.
  185. "signedjson.types.VerifyKey",
  186. }
  187. # Immutable containers only if the values are also immutable.
  188. IMMUTABLE_CONTAINER_TYPES_REQUIRING_IMMUTABLE_ELEMENTS = {
  189. "builtins.frozenset",
  190. "builtins.tuple",
  191. "typing.AbstractSet",
  192. "typing.Sequence",
  193. "immutabledict.immutabledict",
  194. }
  195. MUTABLE_CONTAINER_TYPES = {
  196. "builtins.set",
  197. "builtins.list",
  198. "builtins.dict",
  199. }
  200. AT_CACHED_MUTABLE_RETURN = ErrorCode(
  201. "synapse-@cached-mutable",
  202. "@cached() should have an immutable return type",
  203. "General",
  204. )
  205. def is_cacheable(
  206. rt: mypy.types.Type, signature: CallableType, verbose: bool
  207. ) -> Tuple[bool, Optional[str]]:
  208. """
  209. Check if a particular type is cachable.
  210. A type is cachable if it is immutable; for complex types this recurses to
  211. check each type parameter.
  212. Returns: a 2-tuple (cacheable, message).
  213. - cachable: False means the type is definitely not cacheable;
  214. true means anything else.
  215. - Optional message.
  216. """
  217. # This should probably be done via a TypeVisitor. Apologies to the reader!
  218. if isinstance(rt, AnyType):
  219. return True, ("may be mutable" if verbose else None)
  220. elif isinstance(rt, Instance):
  221. if (
  222. rt.type.fullname in IMMUTABLE_VALUE_TYPES
  223. or rt.type.fullname in IMMUTABLE_CUSTOM_TYPES
  224. ):
  225. # "Simple" types are generally immutable.
  226. return True, None
  227. elif rt.type.fullname == "typing.Mapping":
  228. # Generally mapping keys are immutable, but they only *have* to be
  229. # hashable, which doesn't imply immutability. E.g. Mapping[K, V]
  230. # is cachable iff K and V are cachable.
  231. return is_cacheable(rt.args[0], signature, verbose) and is_cacheable(
  232. rt.args[1], signature, verbose
  233. )
  234. elif rt.type.fullname in IMMUTABLE_CONTAINER_TYPES_REQUIRING_IMMUTABLE_ELEMENTS:
  235. # E.g. Collection[T] is cachable iff T is cachable.
  236. return is_cacheable(rt.args[0], signature, verbose)
  237. elif rt.type.fullname in MUTABLE_CONTAINER_TYPES:
  238. # Mutable containers are mutable regardless of their underlying type.
  239. return False, None
  240. elif "attrs" in rt.type.metadata:
  241. # attrs classes are only cachable iff it is frozen (immutable itself)
  242. # and all attributes are cachable.
  243. frozen = rt.type.metadata["attrs"]["frozen"]
  244. if frozen:
  245. for attribute in rt.type.metadata["attrs"]["attributes"]:
  246. attribute_name = attribute["name"]
  247. symbol_node = rt.type.names[attribute_name].node
  248. assert isinstance(symbol_node, Var)
  249. assert symbol_node.type is not None
  250. ok, note = is_cacheable(symbol_node.type, signature, verbose)
  251. if not ok:
  252. return False, f"non-frozen attrs property: {attribute_name}"
  253. # All attributes were frozen.
  254. return True, None
  255. else:
  256. return False, "non-frozen attrs class"
  257. else:
  258. # Ensure we fail for unknown types, these generally means that the
  259. # above code is not complete.
  260. return (
  261. False,
  262. f"Don't know how to handle {rt.type.fullname} return type instance",
  263. )
  264. elif isinstance(rt, NoneType):
  265. # None is cachable.
  266. return True, None
  267. elif isinstance(rt, (TupleType, UnionType)):
  268. # Tuples and unions are cachable iff all their items are cachable.
  269. for item in rt.items:
  270. ok, note = is_cacheable(item, signature, verbose)
  271. if not ok:
  272. return False, note
  273. # This discards notes but that's probably fine
  274. return True, None
  275. elif isinstance(rt, TypeAliasType):
  276. # For a type alias, check if the underlying real type is cachable.
  277. return is_cacheable(mypy.types.get_proper_type(rt), signature, verbose)
  278. elif isinstance(rt, UninhabitedType) and rt.is_noreturn:
  279. # There is no return value, just consider it cachable. This is only used
  280. # in tests.
  281. return True, None
  282. else:
  283. # Ensure we fail for unknown types, these generally means that the
  284. # above code is not complete.
  285. return False, f"Don't know how to handle {type(rt).__qualname__} return type"
  286. def plugin(version: str) -> Type[SynapsePlugin]:
  287. # This is the entry point of the plugin, and lets us deal with the fact
  288. # that the mypy plugin interface is *not* stable by looking at the version
  289. # string.
  290. #
  291. # However, since we pin the version of mypy Synapse uses in CI, we don't
  292. # really care.
  293. return SynapsePlugin