|
| 1 | +from mypy.messages import format_type |
| 2 | +from mypy.plugins.common import add_method_to_class |
| 3 | +from mypy.nodes import ( |
| 4 | + ARG_POS, Argument, Block, ClassDef, SymbolTable, TypeInfo, Var, ARG_STAR, ARG_OPT, Context |
| 5 | +) |
| 6 | +from mypy.subtypes import is_subtype |
| 7 | +from mypy.types import ( |
| 8 | + AnyType, CallableType, Instance, NoneType, Overloaded, Type, TypeOfAny, get_proper_type, |
| 9 | + FunctionLike |
| 10 | +) |
| 11 | +from mypy.plugin import CheckerPluginInterface, FunctionContext, MethodContext, MethodSigContext |
| 12 | +from typing import List, NamedTuple, Optional, Sequence, TypeVar, Union |
| 13 | +from typing_extensions import Final |
| 14 | + |
| 15 | +SingledispatchTypeVars = NamedTuple('SingledispatchTypeVars', [ |
| 16 | + ('return_type', Type), |
| 17 | + ('fallback', CallableType), |
| 18 | +]) |
| 19 | + |
| 20 | +RegisterCallableInfo = NamedTuple('RegisterCallableInfo', [ |
| 21 | + ('register_type', Type), |
| 22 | + ('singledispatch_obj', Instance), |
| 23 | +]) |
| 24 | + |
| 25 | +SINGLEDISPATCH_TYPE = 'functools._SingleDispatchCallable' |
| 26 | + |
| 27 | +SINGLEDISPATCH_REGISTER_METHOD = '{}.register'.format(SINGLEDISPATCH_TYPE) # type: Final |
| 28 | + |
| 29 | +SINGLEDISPATCH_CALLABLE_CALL_METHOD = '{}.__call__'.format(SINGLEDISPATCH_TYPE) # type: Final |
| 30 | + |
| 31 | + |
| 32 | +def get_singledispatch_info(typ: Instance) -> SingledispatchTypeVars: |
| 33 | + return SingledispatchTypeVars(*typ.args) # type: ignore |
| 34 | + |
| 35 | + |
| 36 | +T = TypeVar('T') |
| 37 | + |
| 38 | + |
| 39 | +def get_first_arg(args: List[List[T]]) -> Optional[T]: |
| 40 | + """Get the element that corresponds to the first argument passed to the function""" |
| 41 | + if args and args[0]: |
| 42 | + return args[0][0] |
| 43 | + return None |
| 44 | + |
| 45 | + |
| 46 | +REGISTER_RETURN_CLASS = '_SingleDispatchRegisterCallable' |
| 47 | + |
| 48 | +REGISTER_CALLABLE_CALL_METHOD = 'functools.{}.__call__'.format( |
| 49 | + REGISTER_RETURN_CLASS |
| 50 | +) # type: Final |
| 51 | + |
| 52 | + |
| 53 | +def make_fake_register_class_instance(api: CheckerPluginInterface, type_args: Sequence[Type] |
| 54 | + ) -> Instance: |
| 55 | + defn = ClassDef(REGISTER_RETURN_CLASS, Block([])) |
| 56 | + defn.fullname = 'functools.{}'.format(REGISTER_RETURN_CLASS) |
| 57 | + info = TypeInfo(SymbolTable(), defn, "functools") |
| 58 | + obj_type = api.named_generic_type('builtins.object', []).type |
| 59 | + info.bases = [Instance(obj_type, [])] |
| 60 | + info.mro = [info, obj_type] |
| 61 | + defn.info = info |
| 62 | + |
| 63 | + func_arg = Argument(Var('name'), AnyType(TypeOfAny.implementation_artifact), None, ARG_POS) |
| 64 | + add_method_to_class(api, defn, '__call__', [func_arg], NoneType()) |
| 65 | + |
| 66 | + return Instance(info, type_args) |
| 67 | + |
| 68 | + |
| 69 | +PluginContext = Union[FunctionContext, MethodContext] |
| 70 | + |
| 71 | + |
| 72 | +def fail(ctx: PluginContext, msg: str, context: Optional[Context]) -> None: |
| 73 | + """Emit an error message. |
| 74 | +
|
| 75 | + This tries to emit an error message at the location specified by `context`, falling back to the |
| 76 | + location specified by `ctx.context`. This is helpful when the only context information about |
| 77 | + where you want to put the error message may be None (like it is for `CallableType.definition`) |
| 78 | + and falling back to the location of the calling function is fine.""" |
| 79 | + # TODO: figure out if there is some more reliable way of getting context information, so this |
| 80 | + # function isn't necessary |
| 81 | + if context is not None: |
| 82 | + err_context = context |
| 83 | + else: |
| 84 | + err_context = ctx.context |
| 85 | + ctx.api.fail(msg, err_context) |
| 86 | + |
| 87 | + |
| 88 | +def create_singledispatch_function_callback(ctx: FunctionContext) -> Type: |
| 89 | + """Called for functools.singledispatch""" |
| 90 | + func_type = get_proper_type(get_first_arg(ctx.arg_types)) |
| 91 | + if isinstance(func_type, CallableType): |
| 92 | + |
| 93 | + if len(func_type.arg_kinds) < 1: |
| 94 | + fail( |
| 95 | + ctx, |
| 96 | + 'Singledispatch function requires at least one argument', |
| 97 | + func_type.definition, |
| 98 | + ) |
| 99 | + return ctx.default_return_type |
| 100 | + |
| 101 | + elif func_type.arg_kinds[0] not in (ARG_POS, ARG_OPT, ARG_STAR): |
| 102 | + fail( |
| 103 | + ctx, |
| 104 | + 'First argument to singledispatch function must be a positional argument', |
| 105 | + func_type.definition, |
| 106 | + ) |
| 107 | + return ctx.default_return_type |
| 108 | + |
| 109 | + # singledispatch returns an instance of functools._SingleDispatchCallable according to |
| 110 | + # typeshed |
| 111 | + singledispatch_obj = get_proper_type(ctx.default_return_type) |
| 112 | + assert isinstance(singledispatch_obj, Instance) |
| 113 | + singledispatch_obj.args += (func_type,) |
| 114 | + |
| 115 | + return ctx.default_return_type |
| 116 | + |
| 117 | + |
| 118 | +def singledispatch_register_callback(ctx: MethodContext) -> Type: |
| 119 | + """Called for functools._SingleDispatchCallable.register""" |
| 120 | + assert isinstance(ctx.type, Instance) |
| 121 | + # TODO: check that there's only one argument |
| 122 | + first_arg_type = get_proper_type(get_first_arg(ctx.arg_types)) |
| 123 | + if isinstance(first_arg_type, (CallableType, Overloaded)) and first_arg_type.is_type_obj(): |
| 124 | + # HACK: We receieved a class as an argument to register. We need to be able |
| 125 | + # to access the function that register is being applied to, and the typeshed definition |
| 126 | + # of register has it return a generic Callable, so we create a new |
| 127 | + # SingleDispatchRegisterCallable class, define a __call__ method, and then add a |
| 128 | + # plugin hook for that. |
| 129 | + |
| 130 | + # is_subtype doesn't work when the right type is Overloaded, so we need the |
| 131 | + # actual type |
| 132 | + register_type = first_arg_type.items()[0].ret_type |
| 133 | + type_args = RegisterCallableInfo(register_type, ctx.type) |
| 134 | + register_callable = make_fake_register_class_instance( |
| 135 | + ctx.api, |
| 136 | + type_args |
| 137 | + ) |
| 138 | + return register_callable |
| 139 | + elif isinstance(first_arg_type, CallableType): |
| 140 | + # TODO: do more checking for registered functions |
| 141 | + register_function(ctx, ctx.type, first_arg_type) |
| 142 | + |
| 143 | + # register doesn't modify the function it's used on |
| 144 | + return ctx.default_return_type |
| 145 | + |
| 146 | + |
| 147 | +def register_function(ctx: PluginContext, singledispatch_obj: Instance, func: Type, |
| 148 | + register_arg: Optional[Type] = None) -> None: |
| 149 | + |
| 150 | + func = get_proper_type(func) |
| 151 | + if not isinstance(func, CallableType): |
| 152 | + return |
| 153 | + metadata = get_singledispatch_info(singledispatch_obj) |
| 154 | + dispatch_type = get_dispatch_type(func, register_arg) |
| 155 | + if dispatch_type is None: |
| 156 | + # TODO: report an error here that singledispatch requires at least one argument |
| 157 | + # (might want to do the error reporting in get_dispatch_type) |
| 158 | + return |
| 159 | + fallback = metadata.fallback |
| 160 | + |
| 161 | + fallback_dispatch_type = fallback.arg_types[0] |
| 162 | + if not is_subtype(dispatch_type, fallback_dispatch_type): |
| 163 | + |
| 164 | + fail(ctx, 'Dispatch type {} must be subtype of fallback function first argument {}'.format( |
| 165 | + format_type(dispatch_type), format_type(fallback_dispatch_type) |
| 166 | + ), func.definition) |
| 167 | + return |
| 168 | + |
| 169 | + |
| 170 | +def get_dispatch_type(func: CallableType, register_arg: Optional[Type]) -> Optional[Type]: |
| 171 | + if register_arg is not None: |
| 172 | + return register_arg |
| 173 | + if func.arg_types: |
| 174 | + return func.arg_types[0] |
| 175 | + return None |
| 176 | + |
| 177 | + |
| 178 | +def call_singledispatch_function_after_register_argument(ctx: MethodContext) -> Type: |
| 179 | + """Called on the function after passing a type to register""" |
| 180 | + register_callable = ctx.type |
| 181 | + if isinstance(register_callable, Instance): |
| 182 | + type_args = RegisterCallableInfo(*register_callable.args) # type: ignore |
| 183 | + func = get_first_arg(ctx.arg_types) |
| 184 | + if func is not None: |
| 185 | + register_function(ctx, type_args.singledispatch_obj, func, type_args.register_type) |
| 186 | + return ctx.default_return_type |
| 187 | + |
| 188 | + |
| 189 | +def rename_func(func: CallableType, new_name: CallableType) -> CallableType: |
| 190 | + """Return a new CallableType that is `function` with the name of `new_name`""" |
| 191 | + if new_name.name is not None: |
| 192 | + signature_used = func.with_name(new_name.name) |
| 193 | + else: |
| 194 | + signature_used = func |
| 195 | + return signature_used |
| 196 | + |
| 197 | + |
| 198 | +def call_singledispatch_function_callback(ctx: MethodSigContext) -> FunctionLike: |
| 199 | + """Called for functools._SingleDispatchCallable.__call__""" |
| 200 | + if not isinstance(ctx.type, Instance): |
| 201 | + return ctx.default_signature |
| 202 | + metadata = get_singledispatch_info(ctx.type) |
| 203 | + return metadata.fallback |
0 commit comments