1# Copyright 2021 The Duet Authors
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#     https://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
15"""Mypy plugin to provide better typechecking of duet functions.
16
17For more information about mypy plugins see:
18https://mypy.readthedocs.io/en/stable/extending_mypy.html#extending-mypy-using-plugins
19"""
20
21from typing import Callable, Optional
22
23from mypy.plugin import FunctionContext, Plugin
24from mypy.types import CallableType, get_proper_type, Instance, Type
25
26
27def duet_sync_callback(ctx: FunctionContext) -> Type:
28    """Callback to provide an accurate signature for duet.sync.
29
30    The duet.sync function wraps an async callable in a synchronous wrapper:
31
32        def sync(f: Callable[..., Awaitable[T]]) -> Callable[..., T]:
33
34    This plugin basically tells mypy that the two ellipses are exactly the same,
35    that is, that the new synchronous callable accepts exactly the same args as
36    the original function. This allows for precise typechecking of calls to
37    functions wrapped by duet.sync.
38    """
39    func_type = get_proper_type(ctx.arg_types[0][0])
40    if not isinstance(func_type, CallableType):
41        ctx.api.msg.fail(f"expected Callable[..., Awaitable[T]], got {func_type}", ctx.context)
42        return ctx.default_return_type
43
44    # Note that the return type of an async function is Coroutine[Any, Any, T],
45    # which is a subtype of Awaitable[T]. See:
46    # https://mypy.readthedocs.io/en/stable/more_types.html#typing-async-await
47    ret_type = get_proper_type(func_type.ret_type)
48    if not (isinstance(ret_type, Instance) and ret_type.type.name == "Coroutine"):
49        if not func_type.implicit:
50            ctx.api.msg.fail(f"expected return type Awaitable[T], got {ret_type}", ctx.context)
51        return ctx.default_return_type
52
53    result_type = ret_type.args[-1]
54    return func_type.copy_modified(ret_type=result_type)
55
56
57class DuetPlugin(Plugin):
58    def get_function_hook(self, fullname: str) -> Optional[Callable[[FunctionContext], Type]]:
59        if fullname == "duet.api.sync":
60            return duet_sync_callback
61        return None
62
63
64def plugin(version: str):
65    return DuetPlugin
66