mypy_synapse_plugin.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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.nodes import ARG_NAMED_OPT
  19. from mypy.plugin import MethodSigContext, Plugin
  20. from mypy.typeops import bind_self
  21. from mypy.types import CallableType, NoneType, UnionType
  22. class SynapsePlugin(Plugin):
  23. def get_method_signature_hook(
  24. self, fullname: str
  25. ) -> Optional[Callable[[MethodSigContext], CallableType]]:
  26. if fullname.startswith(
  27. "synapse.util.caches.descriptors.CachedFunction.__call__"
  28. ) or fullname.startswith(
  29. "synapse.util.caches.descriptors._LruCachedFunction.__call__"
  30. ):
  31. return cached_function_method_signature
  32. return None
  33. def cached_function_method_signature(ctx: MethodSigContext) -> CallableType:
  34. """Fixes the `CachedFunction.__call__` signature to be correct.
  35. It already has *almost* the correct signature, except:
  36. 1. the `self` argument needs to be marked as "bound";
  37. 2. any `cache_context` argument should be removed;
  38. 3. an optional keyword argument `on_invalidated` should be added.
  39. """
  40. # First we mark this as a bound function signature.
  41. signature = bind_self(ctx.default_signature)
  42. # Secondly, we remove any "cache_context" args.
  43. #
  44. # Note: We should be only doing this if `cache_context=True` is set, but if
  45. # it isn't then the code will raise an exception when its called anyway, so
  46. # its not the end of the world.
  47. context_arg_index = None
  48. for idx, name in enumerate(signature.arg_names):
  49. if name == "cache_context":
  50. context_arg_index = idx
  51. break
  52. arg_types = list(signature.arg_types)
  53. arg_names = list(signature.arg_names)
  54. arg_kinds = list(signature.arg_kinds)
  55. if context_arg_index:
  56. arg_types.pop(context_arg_index)
  57. arg_names.pop(context_arg_index)
  58. arg_kinds.pop(context_arg_index)
  59. # Third, we add an optional "on_invalidate" argument.
  60. #
  61. # This is a either
  62. # - a callable which accepts no input and returns nothing, or
  63. # - None.
  64. calltyp = UnionType(
  65. [
  66. NoneType(),
  67. CallableType(
  68. arg_types=[],
  69. arg_kinds=[],
  70. arg_names=[],
  71. ret_type=NoneType(),
  72. fallback=ctx.api.named_generic_type("builtins.function", []),
  73. ),
  74. ]
  75. )
  76. arg_types.append(calltyp)
  77. arg_names.append("on_invalidate")
  78. arg_kinds.append(ARG_NAMED_OPT) # Arg is an optional kwarg.
  79. signature = signature.copy_modified(
  80. arg_types=arg_types,
  81. arg_names=arg_names,
  82. arg_kinds=arg_kinds,
  83. )
  84. return signature
  85. def plugin(version: str) -> Type[SynapsePlugin]:
  86. # This is the entry point of the plugin, and lets us deal with the fact
  87. # that the mypy plugin interface is *not* stable by looking at the version
  88. # string.
  89. #
  90. # However, since we pin the version of mypy Synapse uses in CI, we don't
  91. # really care.
  92. return SynapsePlugin