|
1 | | -from mypy.types import LiteralType, AnyType, TypeOfAny |
2 | | -from mypy.plugin import Plugin |
| 1 | +from mypy.types import LiteralType, AnyType, TypeOfAny, Type |
| 2 | +from mypy.plugin import Plugin, MethodContext |
| 3 | +from typing import Callable |
3 | 4 |
|
4 | 5 | # If radd exists, there shouldn't be an error. If it doesn't exist, then there will be an error |
5 | | -def type_add(ctx, *args): |
6 | | - lhs = ctx.type |
7 | | - rhs = ctx.arg_types[0][0] |
8 | | - ret = lhs.value + rhs.value |
| 6 | +def type_add(ctx: MethodContext, *args) -> Type: |
9 | 7 | ctx.api.fail("test", ctx.context) |
10 | 8 | return AnyType(TypeOfAny.from_error) |
11 | 9 |
|
12 | | -def type_radd(ctx, *args): |
| 10 | +def type_radd(ctx: MethodContext, *args) -> Type: |
13 | 11 | lhs = ctx.type |
14 | | - rhs = ctx.arg_types[0][0] |
| 12 | + rhs = ctx.arg_types[-1][0] |
| 13 | + if not (isinstance(lhs, LiteralType) and isinstance(rhs, LiteralType)): |
| 14 | + ctx.api.fail("operands not literals", ctx.context) |
| 15 | + return AnyType(TypeOfAny.from_error) |
| 16 | + if not (isinstance(lhs.value, int) and isinstance(rhs.value, int)): |
| 17 | + ctx.api.fail("operands not literal ints", ctx.context) |
| 18 | + return AnyType(TypeOfAny.from_error) |
15 | 19 | ret = lhs.value + rhs.value |
16 | 20 | return LiteralType(ret, fallback=ctx.api.named_generic_type('builtins.int', [])) |
17 | 21 |
|
18 | 22 |
|
19 | 23 | class TestPlugin(Plugin): |
| 24 | + def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: |
20 | 25 |
|
21 | | - def get_method_hook(self, fullname): |
22 | 26 | if fullname == 'builtins.int.__add__': |
23 | 27 | return type_add |
24 | 28 | if fullname == 'builtins.int.__radd__': |
25 | 29 | return type_radd |
26 | 30 | return None |
27 | 31 |
|
28 | | -def plugin(version: str): |
| 32 | +def plugin(version: str) -> type[TestPlugin]: |
29 | 33 | return TestPlugin |
0 commit comments