| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import Callable |
| 4 |
|
| 5 |
from mypy.plugin import AnalyzeTypeContext, Plugin |
| 6 |
|
| 7 |
# The official name changed to NoneType but we have an alias for plugin compat reasons |
| 8 |
# so we'll keep testing that here. |
| 9 |
from mypy.types import AnyType, CallableType, NoneTyp, Type, TypeList, TypeOfAny |
| 10 |
|
| 11 |
|
| 12 |
class TypeAnalyzePlugin(Plugin): |
| 13 |
def get_type_analyze_hook(self, fullname: str) -> Callable[[AnalyzeTypeContext], Type] | None: |
| 14 |
if fullname == "m.Signal": |
| 15 |
return signal_type_analyze_callback |
| 16 |
return None |
| 17 |
|
| 18 |
|
| 19 |
def signal_type_analyze_callback(ctx: AnalyzeTypeContext) -> Type: |
| 20 |
if len(ctx.type.args) != 1 or not isinstance(ctx.type.args[0], TypeList): |
| 21 |
ctx.api.fail('Invalid "Signal" type (expected "Signal[[t, ...]]")', ctx.context) |
| 22 |
return AnyType(TypeOfAny.from_error) |
| 23 |
|
| 24 |
args = ctx.type.args[0] |
| 25 |
assert isinstance(args, TypeList) |
| 26 |
analyzed = ctx.api.analyze_callable_args(args) |
| 27 |
if analyzed is None: |
| 28 |
return AnyType(TypeOfAny.from_error) # Error generated elsewhere |
| 29 |
arg_types, arg_kinds, arg_names = analyzed |
| 30 |
arg_types = [ctx.api.analyze_type(arg) for arg in arg_types] |
| 31 |
type_arg = CallableType( |
| 32 |
arg_types, arg_kinds, arg_names, NoneTyp(), ctx.api.named_type("builtins.function", []) |
| 33 |
) |
| 34 |
return ctx.api.named_type("m.Signal", [type_arg]) |
| 35 |
|
| 36 |
|
| 37 |
def plugin(version: str) -> type[TypeAnalyzePlugin]: |
| 38 |
return TypeAnalyzePlugin |