mypy_synapse_plugin.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2020 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """This is a mypy plugin for Synpase to deal with some of the funky typing that
  16. can crop up, e.g the cache descriptors.
  17. """
  18. from typing import Callable, Optional
  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, NoneType
  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 callable which accepts no input and returns nothing.
  63. calltyp = CallableType(
  64. arg_types=[],
  65. arg_kinds=[],
  66. arg_names=[],
  67. ret_type=NoneType(),
  68. fallback=ctx.api.named_generic_type("builtins.function", []),
  69. )
  70. arg_types.append(calltyp)
  71. arg_names.append("on_invalidate")
  72. arg_kinds.append(ARG_NAMED_OPT) # Arg is an optional kwarg.
  73. signature = signature.copy_modified(
  74. arg_types=arg_types,
  75. arg_names=arg_names,
  76. arg_kinds=arg_kinds,
  77. )
  78. return signature
  79. def plugin(version: str):
  80. # This is the entry point of the plugin, and let's us deal with the fact
  81. # that the mypy plugin interface is *not* stable by looking at the version
  82. # string.
  83. #
  84. # However, since we pin the version of mypy Synapse uses in CI, we don't
  85. # really care.
  86. return SynapsePlugin