You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

145 lines
5.2 KiB

  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, Type
  18. from mypy.erasetype import remove_instance_last_known_values
  19. from mypy.nodes import ARG_NAMED_OPT
  20. from mypy.plugin import MethodSigContext, Plugin
  21. from mypy.typeops import bind_self
  22. from mypy.types import CallableType, Instance, NoneType, UnionType
  23. class SynapsePlugin(Plugin):
  24. def get_method_signature_hook(
  25. self, fullname: str
  26. ) -> Optional[Callable[[MethodSigContext], CallableType]]:
  27. if fullname.startswith(
  28. (
  29. "synapse.util.caches.descriptors.CachedFunction.__call__",
  30. "synapse.util.caches.descriptors._LruCachedFunction.__call__",
  31. )
  32. ):
  33. return cached_function_method_signature
  34. return None
  35. def cached_function_method_signature(ctx: MethodSigContext) -> CallableType:
  36. """Fixes the `CachedFunction.__call__` signature to be correct.
  37. It already has *almost* the correct signature, except:
  38. 1. the `self` argument needs to be marked as "bound";
  39. 2. any `cache_context` argument should be removed;
  40. 3. an optional keyword argument `on_invalidated` should be added.
  41. """
  42. # First we mark this as a bound function signature.
  43. signature = bind_self(ctx.default_signature)
  44. # Secondly, we remove any "cache_context" args.
  45. #
  46. # Note: We should be only doing this if `cache_context=True` is set, but if
  47. # it isn't then the code will raise an exception when its called anyway, so
  48. # its not the end of the world.
  49. context_arg_index = None
  50. for idx, name in enumerate(signature.arg_names):
  51. if name == "cache_context":
  52. context_arg_index = idx
  53. break
  54. arg_types = list(signature.arg_types)
  55. arg_names = list(signature.arg_names)
  56. arg_kinds = list(signature.arg_kinds)
  57. if context_arg_index:
  58. arg_types.pop(context_arg_index)
  59. arg_names.pop(context_arg_index)
  60. arg_kinds.pop(context_arg_index)
  61. # Third, we add an optional "on_invalidate" argument.
  62. #
  63. # This is a either
  64. # - a callable which accepts no input and returns nothing, or
  65. # - None.
  66. calltyp = UnionType(
  67. [
  68. NoneType(),
  69. CallableType(
  70. arg_types=[],
  71. arg_kinds=[],
  72. arg_names=[],
  73. ret_type=NoneType(),
  74. fallback=ctx.api.named_generic_type("builtins.function", []),
  75. ),
  76. ]
  77. )
  78. arg_types.append(calltyp)
  79. arg_names.append("on_invalidate")
  80. arg_kinds.append(ARG_NAMED_OPT) # Arg is an optional kwarg.
  81. # Finally we ensure the return type is a Deferred.
  82. if (
  83. isinstance(signature.ret_type, Instance)
  84. and signature.ret_type.type.fullname == "twisted.internet.defer.Deferred"
  85. ):
  86. # If it is already a Deferred, nothing to do.
  87. ret_type = signature.ret_type
  88. else:
  89. ret_arg = None
  90. if isinstance(signature.ret_type, Instance):
  91. # If a coroutine, wrap the coroutine's return type in a Deferred.
  92. if signature.ret_type.type.fullname == "typing.Coroutine":
  93. ret_arg = signature.ret_type.args[2]
  94. # If an awaitable, wrap the awaitable's final value in a Deferred.
  95. elif signature.ret_type.type.fullname == "typing.Awaitable":
  96. ret_arg = signature.ret_type.args[0]
  97. # Otherwise, wrap the return value in a Deferred.
  98. if ret_arg is None:
  99. ret_arg = signature.ret_type
  100. # This should be able to use ctx.api.named_generic_type, but that doesn't seem
  101. # to find the correct symbol for anything more than 1 module deep.
  102. #
  103. # modules is not part of CheckerPluginInterface. The following is a combination
  104. # of TypeChecker.named_generic_type and TypeChecker.lookup_typeinfo.
  105. sym = ctx.api.modules["twisted.internet.defer"].names.get("Deferred") # type: ignore[attr-defined]
  106. ret_type = Instance(sym.node, [remove_instance_last_known_values(ret_arg)])
  107. signature = signature.copy_modified(
  108. arg_types=arg_types,
  109. arg_names=arg_names,
  110. arg_kinds=arg_kinds,
  111. ret_type=ret_type,
  112. )
  113. return signature
  114. def plugin(version: str) -> Type[SynapsePlugin]:
  115. # This is the entry point of the plugin, and lets us deal with the fact
  116. # that the mypy plugin interface is *not* stable by looking at the version
  117. # string.
  118. #
  119. # However, since we pin the version of mypy Synapse uses in CI, we don't
  120. # really care.
  121. return SynapsePlugin