1
0

mypy_synapse_plugin.py 5.2 KB

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