We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Typing for @contextmanager doesn't play well with generic functions
```
from contextlib import contextmanager
from typing import TypeVar, Iterator

_T = TypeVar('_T')

@contextmanager
def yield_id(item):
    # type: (_T) -> Iterator[_T]
    yield item

with yield_id(1):
    pass
```

... results in...

`example.py:11: error: Argument 1 to "yield_id" has incompatible type "int"; expected "_T"`


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mypy/plugin.py`
Content:
```
1 """Plugin system for extending mypy."""
2 
3 from abc import abstractmethod
4 from typing import Callable, List, Tuple, Optional, NamedTuple, TypeVar
5 
6 from mypy.nodes import Expression, StrExpr, IntExpr, UnaryExpr, Context
7 from mypy.types import (
8     Type, Instance, CallableType, TypedDictType, UnionType, NoneTyp, FunctionLike, TypeVarType,
9     AnyType, TypeList, UnboundType
10 )
11 from mypy.messages import MessageBuilder
12 from mypy.options import Options
13 
14 
15 class AnalyzerPluginInterface:
16     """Interface for accessing semantic analyzer functionality in plugins."""
17 
18     @abstractmethod
19     def fail(self, msg: str, ctx: Context) -> None:
20         raise NotImplementedError
21 
22     @abstractmethod
23     def named_type(self, name: str, args: List[Type]) -> Instance:
24         raise NotImplementedError
25 
26     @abstractmethod
27     def analyze_type(self, typ: Type) -> Type:
28         raise NotImplementedError
29 
30     @abstractmethod
31     def analyze_callable_args(self, arglist: TypeList) -> Optional[Tuple[List[Type],
32                                                                          List[int],
33                                                                          List[Optional[str]]]]:
34         raise NotImplementedError
35 
36 
37 # A context for a hook that semantically analyzes an unbound type.
38 AnalyzeTypeContext = NamedTuple(
39     'AnalyzeTypeContext', [
40         ('type', UnboundType),  # Type to analyze
41         ('context', Context),
42         ('api', AnalyzerPluginInterface)])
43 
44 
45 class CheckerPluginInterface:
46     """Interface for accessing type checker functionality in plugins."""
47 
48     msg = None  # type: MessageBuilder
49 
50     @abstractmethod
51     def named_generic_type(self, name: str, args: List[Type]) -> Instance:
52         raise NotImplementedError
53 
54 
55 # A context for a function hook that infers the return type of a function with
56 # a special signature.
57 #
58 # A no-op callback would just return the inferred return type, but a useful
59 # callback at least sometimes can infer a more precise type.
60 FunctionContext = NamedTuple(
61     'FunctionContext', [
62         ('arg_types', List[List[Type]]),   # List of actual caller types for each formal argument
63         ('default_return_type', Type),     # Return type inferred from signature
64         ('args', List[List[Expression]]),  # Actual expressions for each formal argument
65         ('context', Context),
66         ('api', CheckerPluginInterface)])
67 
68 # A context for a method signature hook that infers a better signature for a
69 # method.  Note that argument types aren't available yet.  If you need them,
70 # you have to use a method hook instead.
71 MethodSigContext = NamedTuple(
72     'MethodSigContext', [
73         ('type', Type),                       # Base object type for method call
74         ('args', List[List[Expression]]),     # Actual expressions for each formal argument
75         ('default_signature', CallableType),  # Original signature of the method
76         ('context', Context),
77         ('api', CheckerPluginInterface)])
78 
79 # A context for a method hook that infers the return type of a method with a
80 # special signature.
81 #
82 # This is very similar to FunctionContext (only differences are documented).
83 MethodContext = NamedTuple(
84     'MethodContext', [
85         ('type', Type),                    # Base object type for method call
86         ('arg_types', List[List[Type]]),
87         ('default_return_type', Type),
88         ('args', List[List[Expression]]),
89         ('context', Context),
90         ('api', CheckerPluginInterface)])
91 
92 # A context for an attribute type hook that infers the type of an attribute.
93 AttributeContext = NamedTuple(
94     'AttributeContext', [
95         ('type', Type),                # Type of object with attribute
96         ('default_attr_type', Type),  # Original attribute type
97         ('context', Context),
98         ('api', CheckerPluginInterface)])
99 
100 
101 class Plugin:
102     """Base class of all type checker plugins.
103 
104     This defines a no-op plugin.  Subclasses can override some methods to
105     provide some actual functionality.
106 
107     All get_ methods are treated as pure functions (you should assume that
108     results might be cached).
109 
110     Look at the comments of various *Context objects for descriptions of
111     various hooks.
112     """
113 
114     def __init__(self, options: Options) -> None:
115         self.options = options
116         self.python_version = options.python_version
117 
118     def get_type_analyze_hook(self, fullname: str
119                               ) -> Optional[Callable[[AnalyzeTypeContext], Type]]:
120         return None
121 
122     def get_function_hook(self, fullname: str
123                           ) -> Optional[Callable[[FunctionContext], Type]]:
124         return None
125 
126     def get_method_signature_hook(self, fullname: str
127                                   ) -> Optional[Callable[[MethodSigContext], CallableType]]:
128         return None
129 
130     def get_method_hook(self, fullname: str
131                         ) -> Optional[Callable[[MethodContext], Type]]:
132         return None
133 
134     def get_attribute_hook(self, fullname: str
135                            ) -> Optional[Callable[[AttributeContext], Type]]:
136         return None
137 
138     # TODO: metaclass / class decorator hook
139 
140 
141 T = TypeVar('T')
142 
143 
144 class ChainedPlugin(Plugin):
145     """A plugin that represents a sequence of chained plugins.
146 
147     Each lookup method returns the hook for the first plugin that
148     reports a match.
149 
150     This class should not be subclassed -- use Plugin as the base class
151     for all plugins.
152     """
153 
154     # TODO: Support caching of lookup results (through a LRU cache, for example).
155 
156     def __init__(self, options: Options, plugins: List[Plugin]) -> None:
157         """Initialize chained plugin.
158 
159         Assume that the child plugins aren't mutated (results may be cached).
160         """
161         super().__init__(options)
162         self._plugins = plugins
163 
164     def get_type_analyze_hook(self, fullname: str
165                               ) -> Optional[Callable[[AnalyzeTypeContext], Type]]:
166         return self._find_hook(lambda plugin: plugin.get_type_analyze_hook(fullname))
167 
168     def get_function_hook(self, fullname: str
169                           ) -> Optional[Callable[[FunctionContext], Type]]:
170         return self._find_hook(lambda plugin: plugin.get_function_hook(fullname))
171 
172     def get_method_signature_hook(self, fullname: str
173                                   ) -> Optional[Callable[[MethodSigContext], CallableType]]:
174         return self._find_hook(lambda plugin: plugin.get_method_signature_hook(fullname))
175 
176     def get_method_hook(self, fullname: str
177                         ) -> Optional[Callable[[MethodContext], Type]]:
178         return self._find_hook(lambda plugin: plugin.get_method_hook(fullname))
179 
180     def get_attribute_hook(self, fullname: str
181                            ) -> Optional[Callable[[AttributeContext], Type]]:
182         return self._find_hook(lambda plugin: plugin.get_attribute_hook(fullname))
183 
184     def _find_hook(self, lookup: Callable[[Plugin], T]) -> Optional[T]:
185         for plugin in self._plugins:
186             hook = lookup(plugin)
187             if hook:
188                 return hook
189         return None
190 
191 
192 class DefaultPlugin(Plugin):
193     """Type checker plugin that is enabled by default."""
194 
195     def get_function_hook(self, fullname: str
196                           ) -> Optional[Callable[[FunctionContext], Type]]:
197         if fullname == 'contextlib.contextmanager':
198             return contextmanager_callback
199         elif fullname == 'builtins.open' and self.python_version[0] == 3:
200             return open_callback
201         return None
202 
203     def get_method_signature_hook(self, fullname: str
204                                   ) -> Optional[Callable[[MethodSigContext], CallableType]]:
205         if fullname == 'typing.Mapping.get':
206             return typed_dict_get_signature_callback
207         return None
208 
209     def get_method_hook(self, fullname: str
210                         ) -> Optional[Callable[[MethodContext], Type]]:
211         if fullname == 'typing.Mapping.get':
212             return typed_dict_get_callback
213         elif fullname == 'builtins.int.__pow__':
214             return int_pow_callback
215         return None
216 
217 
218 def open_callback(ctx: FunctionContext) -> Type:
219     """Infer a better return type for 'open'.
220 
221     Infer TextIO or BinaryIO as the return value if the mode argument is not
222     given or is a literal.
223     """
224     mode = None
225     if not ctx.arg_types or len(ctx.arg_types[1]) != 1:
226         mode = 'r'
227     elif isinstance(ctx.args[1][0], StrExpr):
228         mode = ctx.args[1][0].value
229     if mode is not None:
230         assert isinstance(ctx.default_return_type, Instance)
231         if 'b' in mode:
232             return ctx.api.named_generic_type('typing.BinaryIO', [])
233         else:
234             return ctx.api.named_generic_type('typing.TextIO', [])
235     return ctx.default_return_type
236 
237 
238 def contextmanager_callback(ctx: FunctionContext) -> Type:
239     """Infer a better return type for 'contextlib.contextmanager'."""
240     # Be defensive, just in case.
241     if ctx.arg_types and len(ctx.arg_types[0]) == 1:
242         arg_type = ctx.arg_types[0][0]
243         if (isinstance(arg_type, CallableType)
244                 and isinstance(ctx.default_return_type, CallableType)):
245             # The stub signature doesn't preserve information about arguments so
246             # add them back here.
247             return ctx.default_return_type.copy_modified(
248                 arg_types=arg_type.arg_types,
249                 arg_kinds=arg_type.arg_kinds,
250                 arg_names=arg_type.arg_names)
251     return ctx.default_return_type
252 
253 
254 def typed_dict_get_signature_callback(ctx: MethodSigContext) -> CallableType:
255     """Try to infer a better signature type for TypedDict.get.
256 
257     This is used to get better type context for the second argument that
258     depends on a TypedDict value type.
259     """
260     signature = ctx.default_signature
261     if (isinstance(ctx.type, TypedDictType)
262             and len(ctx.args) == 2
263             and len(ctx.args[0]) == 1
264             and isinstance(ctx.args[0][0], StrExpr)
265             and len(signature.arg_types) == 2
266             and len(signature.variables) == 1):
267         key = ctx.args[0][0].value
268         value_type = ctx.type.items.get(key)
269         if value_type:
270             # Tweak the signature to include the value type as context. It's
271             # only needed for type inference since there's a union with a type
272             # variable that accepts everything.
273             tv = TypeVarType(signature.variables[0])
274             return signature.copy_modified(
275                 arg_types=[signature.arg_types[0],
276                            UnionType.make_simplified_union([value_type, tv])])
277     return signature
278 
279 
280 def typed_dict_get_callback(ctx: MethodContext) -> Type:
281     """Infer a precise return type for TypedDict.get with literal first argument."""
282     if (isinstance(ctx.type, TypedDictType)
283             and len(ctx.arg_types) >= 1
284             and len(ctx.arg_types[0]) == 1):
285         if isinstance(ctx.args[0][0], StrExpr):
286             key = ctx.args[0][0].value
287             value_type = ctx.type.items.get(key)
288             if value_type:
289                 if len(ctx.arg_types) == 1:
290                     return UnionType.make_simplified_union([value_type, NoneTyp()])
291                 elif len(ctx.arg_types) == 2 and len(ctx.arg_types[1]) == 1:
292                     return UnionType.make_simplified_union([value_type, ctx.arg_types[1][0]])
293             else:
294                 ctx.api.msg.typeddict_item_name_not_found(ctx.type, key, ctx.context)
295                 return AnyType()
296     return ctx.default_return_type
297 
298 
299 def int_pow_callback(ctx: MethodContext) -> Type:
300     """Infer a more precise return type for int.__pow__."""
301     if (len(ctx.arg_types) == 1
302             and len(ctx.arg_types[0]) == 1):
303         arg = ctx.args[0][0]
304         if isinstance(arg, IntExpr):
305             exponent = arg.value
306         elif isinstance(arg, UnaryExpr) and arg.op == '-' and isinstance(arg.expr, IntExpr):
307             exponent = -arg.expr.value
308         else:
309             # Right operand not an int literal or a negated literal -- give up.
310             return ctx.default_return_type
311         if exponent >= 0:
312             return ctx.api.named_generic_type('builtins.int', [])
313         else:
314             return ctx.api.named_generic_type('builtins.float', [])
315     return ctx.default_return_type
316
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mypy/plugin.py b/mypy/plugin.py
--- a/mypy/plugin.py
+++ b/mypy/plugin.py
@@ -247,7 +247,9 @@
             return ctx.default_return_type.copy_modified(
                 arg_types=arg_type.arg_types,
                 arg_kinds=arg_type.arg_kinds,
-                arg_names=arg_type.arg_names)
+                arg_names=arg_type.arg_names,
+                variables=arg_type.variables,
+                is_ellipsis_args=arg_type.is_ellipsis_args)
     return ctx.default_return_type

{"golden_diff": "diff --git a/mypy/plugin.py b/mypy/plugin.py\n--- a/mypy/plugin.py\n+++ b/mypy/plugin.py\n@@ -247,7 +247,9 @@\n             return ctx.default_return_type.copy_modified(\n                 arg_types=arg_type.arg_types,\n                 arg_kinds=arg_type.arg_kinds,\n-                arg_names=arg_type.arg_names)\n+                arg_names=arg_type.arg_names,\n+                variables=arg_type.variables,\n+                is_ellipsis_args=arg_type.is_ellipsis_args)\n     return ctx.default_return_type\n", "issue": "Typing for @contextmanager doesn't play well with generic functions\n```\r\nfrom contextlib import contextmanager\r\nfrom typing import TypeVar, Iterator\r\n\r\n_T = TypeVar('_T')\r\n\r\n@contextmanager\r\ndef yield_id(item):\r\n    # type: (_T) -> Iterator[_T]\r\n    yield item\r\n\r\nwith yield_id(1):\r\n    pass\r\n```\r\n\r\n... results in...\r\n\r\n`example.py:11: error: Argument 1 to \"yield_id\" has incompatible type \"int\"; expected \"_T\"`\r\n\n", "before_files": [{"content": "\"\"\"Plugin system for extending mypy.\"\"\"\n\nfrom abc import abstractmethod\nfrom typing import Callable, List, Tuple, Optional, NamedTuple, TypeVar\n\nfrom mypy.nodes import Expression, StrExpr, IntExpr, UnaryExpr, Context\nfrom mypy.types import (\n    Type, Instance, CallableType, TypedDictType, UnionType, NoneTyp, FunctionLike, TypeVarType,\n    AnyType, TypeList, UnboundType\n)\nfrom mypy.messages import MessageBuilder\nfrom mypy.options import Options\n\n\nclass AnalyzerPluginInterface:\n    \"\"\"Interface for accessing semantic analyzer functionality in plugins.\"\"\"\n\n    @abstractmethod\n    def fail(self, msg: str, ctx: Context) -> None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def named_type(self, name: str, args: List[Type]) -> Instance:\n        raise NotImplementedError\n\n    @abstractmethod\n    def analyze_type(self, typ: Type) -> Type:\n        raise NotImplementedError\n\n    @abstractmethod\n    def analyze_callable_args(self, arglist: TypeList) -> Optional[Tuple[List[Type],\n                                                                         List[int],\n                                                                         List[Optional[str]]]]:\n        raise NotImplementedError\n\n\n# A context for a hook that semantically analyzes an unbound type.\nAnalyzeTypeContext = NamedTuple(\n    'AnalyzeTypeContext', [\n        ('type', UnboundType),  # Type to analyze\n        ('context', Context),\n        ('api', AnalyzerPluginInterface)])\n\n\nclass CheckerPluginInterface:\n    \"\"\"Interface for accessing type checker functionality in plugins.\"\"\"\n\n    msg = None  # type: MessageBuilder\n\n    @abstractmethod\n    def named_generic_type(self, name: str, args: List[Type]) -> Instance:\n        raise NotImplementedError\n\n\n# A context for a function hook that infers the return type of a function with\n# a special signature.\n#\n# A no-op callback would just return the inferred return type, but a useful\n# callback at least sometimes can infer a more precise type.\nFunctionContext = NamedTuple(\n    'FunctionContext', [\n        ('arg_types', List[List[Type]]),   # List of actual caller types for each formal argument\n        ('default_return_type', Type),     # Return type inferred from signature\n        ('args', List[List[Expression]]),  # Actual expressions for each formal argument\n        ('context', Context),\n        ('api', CheckerPluginInterface)])\n\n# A context for a method signature hook that infers a better signature for a\n# method.  Note that argument types aren't available yet.  If you need them,\n# you have to use a method hook instead.\nMethodSigContext = NamedTuple(\n    'MethodSigContext', [\n        ('type', Type),                       # Base object type for method call\n        ('args', List[List[Expression]]),     # Actual expressions for each formal argument\n        ('default_signature', CallableType),  # Original signature of the method\n        ('context', Context),\n        ('api', CheckerPluginInterface)])\n\n# A context for a method hook that infers the return type of a method with a\n# special signature.\n#\n# This is very similar to FunctionContext (only differences are documented).\nMethodContext = NamedTuple(\n    'MethodContext', [\n        ('type', Type),                    # Base object type for method call\n        ('arg_types', List[List[Type]]),\n        ('default_return_type', Type),\n        ('args', List[List[Expression]]),\n        ('context', Context),\n        ('api', CheckerPluginInterface)])\n\n# A context for an attribute type hook that infers the type of an attribute.\nAttributeContext = NamedTuple(\n    'AttributeContext', [\n        ('type', Type),                # Type of object with attribute\n        ('default_attr_type', Type),  # Original attribute type\n        ('context', Context),\n        ('api', CheckerPluginInterface)])\n\n\nclass Plugin:\n    \"\"\"Base class of all type checker plugins.\n\n    This defines a no-op plugin.  Subclasses can override some methods to\n    provide some actual functionality.\n\n    All get_ methods are treated as pure functions (you should assume that\n    results might be cached).\n\n    Look at the comments of various *Context objects for descriptions of\n    various hooks.\n    \"\"\"\n\n    def __init__(self, options: Options) -> None:\n        self.options = options\n        self.python_version = options.python_version\n\n    def get_type_analyze_hook(self, fullname: str\n                              ) -> Optional[Callable[[AnalyzeTypeContext], Type]]:\n        return None\n\n    def get_function_hook(self, fullname: str\n                          ) -> Optional[Callable[[FunctionContext], Type]]:\n        return None\n\n    def get_method_signature_hook(self, fullname: str\n                                  ) -> Optional[Callable[[MethodSigContext], CallableType]]:\n        return None\n\n    def get_method_hook(self, fullname: str\n                        ) -> Optional[Callable[[MethodContext], Type]]:\n        return None\n\n    def get_attribute_hook(self, fullname: str\n                           ) -> Optional[Callable[[AttributeContext], Type]]:\n        return None\n\n    # TODO: metaclass / class decorator hook\n\n\nT = TypeVar('T')\n\n\nclass ChainedPlugin(Plugin):\n    \"\"\"A plugin that represents a sequence of chained plugins.\n\n    Each lookup method returns the hook for the first plugin that\n    reports a match.\n\n    This class should not be subclassed -- use Plugin as the base class\n    for all plugins.\n    \"\"\"\n\n    # TODO: Support caching of lookup results (through a LRU cache, for example).\n\n    def __init__(self, options: Options, plugins: List[Plugin]) -> None:\n        \"\"\"Initialize chained plugin.\n\n        Assume that the child plugins aren't mutated (results may be cached).\n        \"\"\"\n        super().__init__(options)\n        self._plugins = plugins\n\n    def get_type_analyze_hook(self, fullname: str\n                              ) -> Optional[Callable[[AnalyzeTypeContext], Type]]:\n        return self._find_hook(lambda plugin: plugin.get_type_analyze_hook(fullname))\n\n    def get_function_hook(self, fullname: str\n                          ) -> Optional[Callable[[FunctionContext], Type]]:\n        return self._find_hook(lambda plugin: plugin.get_function_hook(fullname))\n\n    def get_method_signature_hook(self, fullname: str\n                                  ) -> Optional[Callable[[MethodSigContext], CallableType]]:\n        return self._find_hook(lambda plugin: plugin.get_method_signature_hook(fullname))\n\n    def get_method_hook(self, fullname: str\n                        ) -> Optional[Callable[[MethodContext], Type]]:\n        return self._find_hook(lambda plugin: plugin.get_method_hook(fullname))\n\n    def get_attribute_hook(self, fullname: str\n                           ) -> Optional[Callable[[AttributeContext], Type]]:\n        return self._find_hook(lambda plugin: plugin.get_attribute_hook(fullname))\n\n    def _find_hook(self, lookup: Callable[[Plugin], T]) -> Optional[T]:\n        for plugin in self._plugins:\n            hook = lookup(plugin)\n            if hook:\n                return hook\n        return None\n\n\nclass DefaultPlugin(Plugin):\n    \"\"\"Type checker plugin that is enabled by default.\"\"\"\n\n    def get_function_hook(self, fullname: str\n                          ) -> Optional[Callable[[FunctionContext], Type]]:\n        if fullname == 'contextlib.contextmanager':\n            return contextmanager_callback\n        elif fullname == 'builtins.open' and self.python_version[0] == 3:\n            return open_callback\n        return None\n\n    def get_method_signature_hook(self, fullname: str\n                                  ) -> Optional[Callable[[MethodSigContext], CallableType]]:\n        if fullname == 'typing.Mapping.get':\n            return typed_dict_get_signature_callback\n        return None\n\n    def get_method_hook(self, fullname: str\n                        ) -> Optional[Callable[[MethodContext], Type]]:\n        if fullname == 'typing.Mapping.get':\n            return typed_dict_get_callback\n        elif fullname == 'builtins.int.__pow__':\n            return int_pow_callback\n        return None\n\n\ndef open_callback(ctx: FunctionContext) -> Type:\n    \"\"\"Infer a better return type for 'open'.\n\n    Infer TextIO or BinaryIO as the return value if the mode argument is not\n    given or is a literal.\n    \"\"\"\n    mode = None\n    if not ctx.arg_types or len(ctx.arg_types[1]) != 1:\n        mode = 'r'\n    elif isinstance(ctx.args[1][0], StrExpr):\n        mode = ctx.args[1][0].value\n    if mode is not None:\n        assert isinstance(ctx.default_return_type, Instance)\n        if 'b' in mode:\n            return ctx.api.named_generic_type('typing.BinaryIO', [])\n        else:\n            return ctx.api.named_generic_type('typing.TextIO', [])\n    return ctx.default_return_type\n\n\ndef contextmanager_callback(ctx: FunctionContext) -> Type:\n    \"\"\"Infer a better return type for 'contextlib.contextmanager'.\"\"\"\n    # Be defensive, just in case.\n    if ctx.arg_types and len(ctx.arg_types[0]) == 1:\n        arg_type = ctx.arg_types[0][0]\n        if (isinstance(arg_type, CallableType)\n                and isinstance(ctx.default_return_type, CallableType)):\n            # The stub signature doesn't preserve information about arguments so\n            # add them back here.\n            return ctx.default_return_type.copy_modified(\n                arg_types=arg_type.arg_types,\n                arg_kinds=arg_type.arg_kinds,\n                arg_names=arg_type.arg_names)\n    return ctx.default_return_type\n\n\ndef typed_dict_get_signature_callback(ctx: MethodSigContext) -> CallableType:\n    \"\"\"Try to infer a better signature type for TypedDict.get.\n\n    This is used to get better type context for the second argument that\n    depends on a TypedDict value type.\n    \"\"\"\n    signature = ctx.default_signature\n    if (isinstance(ctx.type, TypedDictType)\n            and len(ctx.args) == 2\n            and len(ctx.args[0]) == 1\n            and isinstance(ctx.args[0][0], StrExpr)\n            and len(signature.arg_types) == 2\n            and len(signature.variables) == 1):\n        key = ctx.args[0][0].value\n        value_type = ctx.type.items.get(key)\n        if value_type:\n            # Tweak the signature to include the value type as context. It's\n            # only needed for type inference since there's a union with a type\n            # variable that accepts everything.\n            tv = TypeVarType(signature.variables[0])\n            return signature.copy_modified(\n                arg_types=[signature.arg_types[0],\n                           UnionType.make_simplified_union([value_type, tv])])\n    return signature\n\n\ndef typed_dict_get_callback(ctx: MethodContext) -> Type:\n    \"\"\"Infer a precise return type for TypedDict.get with literal first argument.\"\"\"\n    if (isinstance(ctx.type, TypedDictType)\n            and len(ctx.arg_types) >= 1\n            and len(ctx.arg_types[0]) == 1):\n        if isinstance(ctx.args[0][0], StrExpr):\n            key = ctx.args[0][0].value\n            value_type = ctx.type.items.get(key)\n            if value_type:\n                if len(ctx.arg_types) == 1:\n                    return UnionType.make_simplified_union([value_type, NoneTyp()])\n                elif len(ctx.arg_types) == 2 and len(ctx.arg_types[1]) == 1:\n                    return UnionType.make_simplified_union([value_type, ctx.arg_types[1][0]])\n            else:\n                ctx.api.msg.typeddict_item_name_not_found(ctx.type, key, ctx.context)\n                return AnyType()\n    return ctx.default_return_type\n\n\ndef int_pow_callback(ctx: MethodContext) -> Type:\n    \"\"\"Infer a more precise return type for int.__pow__.\"\"\"\n    if (len(ctx.arg_types) == 1\n            and len(ctx.arg_types[0]) == 1):\n        arg = ctx.args[0][0]\n        if isinstance(arg, IntExpr):\n            exponent = arg.value\n        elif isinstance(arg, UnaryExpr) and arg.op == '-' and isinstance(arg.expr, IntExpr):\n            exponent = -arg.expr.value\n        else:\n            # Right operand not an int literal or a negated literal -- give up.\n            return ctx.default_return_type\n        if exponent >= 0:\n            return ctx.api.named_generic_type('builtins.int', [])\n        else:\n            return ctx.api.named_generic_type('builtins.float', [])\n    return ctx.default_return_type\n", "path": "mypy/plugin.py"}], "after_files": [{"content": "\"\"\"Plugin system for extending mypy.\"\"\"\n\nfrom abc import abstractmethod\nfrom typing import Callable, List, Tuple, Optional, NamedTuple, TypeVar\n\nfrom mypy.nodes import Expression, StrExpr, IntExpr, UnaryExpr, Context\nfrom mypy.types import (\n    Type, Instance, CallableType, TypedDictType, UnionType, NoneTyp, FunctionLike, TypeVarType,\n    AnyType, TypeList, UnboundType\n)\nfrom mypy.messages import MessageBuilder\nfrom mypy.options import Options\n\n\nclass AnalyzerPluginInterface:\n    \"\"\"Interface for accessing semantic analyzer functionality in plugins.\"\"\"\n\n    @abstractmethod\n    def fail(self, msg: str, ctx: Context) -> None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def named_type(self, name: str, args: List[Type]) -> Instance:\n        raise NotImplementedError\n\n    @abstractmethod\n    def analyze_type(self, typ: Type) -> Type:\n        raise NotImplementedError\n\n    @abstractmethod\n    def analyze_callable_args(self, arglist: TypeList) -> Optional[Tuple[List[Type],\n                                                                         List[int],\n                                                                         List[Optional[str]]]]:\n        raise NotImplementedError\n\n\n# A context for a hook that semantically analyzes an unbound type.\nAnalyzeTypeContext = NamedTuple(\n    'AnalyzeTypeContext', [\n        ('type', UnboundType),  # Type to analyze\n        ('context', Context),\n        ('api', AnalyzerPluginInterface)])\n\n\nclass CheckerPluginInterface:\n    \"\"\"Interface for accessing type checker functionality in plugins.\"\"\"\n\n    msg = None  # type: MessageBuilder\n\n    @abstractmethod\n    def named_generic_type(self, name: str, args: List[Type]) -> Instance:\n        raise NotImplementedError\n\n\n# A context for a function hook that infers the return type of a function with\n# a special signature.\n#\n# A no-op callback would just return the inferred return type, but a useful\n# callback at least sometimes can infer a more precise type.\nFunctionContext = NamedTuple(\n    'FunctionContext', [\n        ('arg_types', List[List[Type]]),   # List of actual caller types for each formal argument\n        ('default_return_type', Type),     # Return type inferred from signature\n        ('args', List[List[Expression]]),  # Actual expressions for each formal argument\n        ('context', Context),\n        ('api', CheckerPluginInterface)])\n\n# A context for a method signature hook that infers a better signature for a\n# method.  Note that argument types aren't available yet.  If you need them,\n# you have to use a method hook instead.\nMethodSigContext = NamedTuple(\n    'MethodSigContext', [\n        ('type', Type),                       # Base object type for method call\n        ('args', List[List[Expression]]),     # Actual expressions for each formal argument\n        ('default_signature', CallableType),  # Original signature of the method\n        ('context', Context),\n        ('api', CheckerPluginInterface)])\n\n# A context for a method hook that infers the return type of a method with a\n# special signature.\n#\n# This is very similar to FunctionContext (only differences are documented).\nMethodContext = NamedTuple(\n    'MethodContext', [\n        ('type', Type),                    # Base object type for method call\n        ('arg_types', List[List[Type]]),\n        ('default_return_type', Type),\n        ('args', List[List[Expression]]),\n        ('context', Context),\n        ('api', CheckerPluginInterface)])\n\n# A context for an attribute type hook that infers the type of an attribute.\nAttributeContext = NamedTuple(\n    'AttributeContext', [\n        ('type', Type),                # Type of object with attribute\n        ('default_attr_type', Type),  # Original attribute type\n        ('context', Context),\n        ('api', CheckerPluginInterface)])\n\n\nclass Plugin:\n    \"\"\"Base class of all type checker plugins.\n\n    This defines a no-op plugin.  Subclasses can override some methods to\n    provide some actual functionality.\n\n    All get_ methods are treated as pure functions (you should assume that\n    results might be cached).\n\n    Look at the comments of various *Context objects for descriptions of\n    various hooks.\n    \"\"\"\n\n    def __init__(self, options: Options) -> None:\n        self.options = options\n        self.python_version = options.python_version\n\n    def get_type_analyze_hook(self, fullname: str\n                              ) -> Optional[Callable[[AnalyzeTypeContext], Type]]:\n        return None\n\n    def get_function_hook(self, fullname: str\n                          ) -> Optional[Callable[[FunctionContext], Type]]:\n        return None\n\n    def get_method_signature_hook(self, fullname: str\n                                  ) -> Optional[Callable[[MethodSigContext], CallableType]]:\n        return None\n\n    def get_method_hook(self, fullname: str\n                        ) -> Optional[Callable[[MethodContext], Type]]:\n        return None\n\n    def get_attribute_hook(self, fullname: str\n                           ) -> Optional[Callable[[AttributeContext], Type]]:\n        return None\n\n    # TODO: metaclass / class decorator hook\n\n\nT = TypeVar('T')\n\n\nclass ChainedPlugin(Plugin):\n    \"\"\"A plugin that represents a sequence of chained plugins.\n\n    Each lookup method returns the hook for the first plugin that\n    reports a match.\n\n    This class should not be subclassed -- use Plugin as the base class\n    for all plugins.\n    \"\"\"\n\n    # TODO: Support caching of lookup results (through a LRU cache, for example).\n\n    def __init__(self, options: Options, plugins: List[Plugin]) -> None:\n        \"\"\"Initialize chained plugin.\n\n        Assume that the child plugins aren't mutated (results may be cached).\n        \"\"\"\n        super().__init__(options)\n        self._plugins = plugins\n\n    def get_type_analyze_hook(self, fullname: str\n                              ) -> Optional[Callable[[AnalyzeTypeContext], Type]]:\n        return self._find_hook(lambda plugin: plugin.get_type_analyze_hook(fullname))\n\n    def get_function_hook(self, fullname: str\n                          ) -> Optional[Callable[[FunctionContext], Type]]:\n        return self._find_hook(lambda plugin: plugin.get_function_hook(fullname))\n\n    def get_method_signature_hook(self, fullname: str\n                                  ) -> Optional[Callable[[MethodSigContext], CallableType]]:\n        return self._find_hook(lambda plugin: plugin.get_method_signature_hook(fullname))\n\n    def get_method_hook(self, fullname: str\n                        ) -> Optional[Callable[[MethodContext], Type]]:\n        return self._find_hook(lambda plugin: plugin.get_method_hook(fullname))\n\n    def get_attribute_hook(self, fullname: str\n                           ) -> Optional[Callable[[AttributeContext], Type]]:\n        return self._find_hook(lambda plugin: plugin.get_attribute_hook(fullname))\n\n    def _find_hook(self, lookup: Callable[[Plugin], T]) -> Optional[T]:\n        for plugin in self._plugins:\n            hook = lookup(plugin)\n            if hook:\n                return hook\n        return None\n\n\nclass DefaultPlugin(Plugin):\n    \"\"\"Type checker plugin that is enabled by default.\"\"\"\n\n    def get_function_hook(self, fullname: str\n                          ) -> Optional[Callable[[FunctionContext], Type]]:\n        if fullname == 'contextlib.contextmanager':\n            return contextmanager_callback\n        elif fullname == 'builtins.open' and self.python_version[0] == 3:\n            return open_callback\n        return None\n\n    def get_method_signature_hook(self, fullname: str\n                                  ) -> Optional[Callable[[MethodSigContext], CallableType]]:\n        if fullname == 'typing.Mapping.get':\n            return typed_dict_get_signature_callback\n        return None\n\n    def get_method_hook(self, fullname: str\n                        ) -> Optional[Callable[[MethodContext], Type]]:\n        if fullname == 'typing.Mapping.get':\n            return typed_dict_get_callback\n        elif fullname == 'builtins.int.__pow__':\n            return int_pow_callback\n        return None\n\n\ndef open_callback(ctx: FunctionContext) -> Type:\n    \"\"\"Infer a better return type for 'open'.\n\n    Infer TextIO or BinaryIO as the return value if the mode argument is not\n    given or is a literal.\n    \"\"\"\n    mode = None\n    if not ctx.arg_types or len(ctx.arg_types[1]) != 1:\n        mode = 'r'\n    elif isinstance(ctx.args[1][0], StrExpr):\n        mode = ctx.args[1][0].value\n    if mode is not None:\n        assert isinstance(ctx.default_return_type, Instance)\n        if 'b' in mode:\n            return ctx.api.named_generic_type('typing.BinaryIO', [])\n        else:\n            return ctx.api.named_generic_type('typing.TextIO', [])\n    return ctx.default_return_type\n\n\ndef contextmanager_callback(ctx: FunctionContext) -> Type:\n    \"\"\"Infer a better return type for 'contextlib.contextmanager'.\"\"\"\n    # Be defensive, just in case.\n    if ctx.arg_types and len(ctx.arg_types[0]) == 1:\n        arg_type = ctx.arg_types[0][0]\n        if (isinstance(arg_type, CallableType)\n                and isinstance(ctx.default_return_type, CallableType)):\n            # The stub signature doesn't preserve information about arguments so\n            # add them back here.\n            return ctx.default_return_type.copy_modified(\n                arg_types=arg_type.arg_types,\n                arg_kinds=arg_type.arg_kinds,\n                arg_names=arg_type.arg_names,\n                variables=arg_type.variables,\n                is_ellipsis_args=arg_type.is_ellipsis_args)\n    return ctx.default_return_type\n\n\ndef typed_dict_get_signature_callback(ctx: MethodSigContext) -> CallableType:\n    \"\"\"Try to infer a better signature type for TypedDict.get.\n\n    This is used to get better type context for the second argument that\n    depends on a TypedDict value type.\n    \"\"\"\n    signature = ctx.default_signature\n    if (isinstance(ctx.type, TypedDictType)\n            and len(ctx.args) == 2\n            and len(ctx.args[0]) == 1\n            and isinstance(ctx.args[0][0], StrExpr)\n            and len(signature.arg_types) == 2\n            and len(signature.variables) == 1):\n        key = ctx.args[0][0].value\n        value_type = ctx.type.items.get(key)\n        if value_type:\n            # Tweak the signature to include the value type as context. It's\n            # only needed for type inference since there's a union with a type\n            # variable that accepts everything.\n            tv = TypeVarType(signature.variables[0])\n            return signature.copy_modified(\n                arg_types=[signature.arg_types[0],\n                           UnionType.make_simplified_union([value_type, tv])])\n    return signature\n\n\ndef typed_dict_get_callback(ctx: MethodContext) -> Type:\n    \"\"\"Infer a precise return type for TypedDict.get with literal first argument.\"\"\"\n    if (isinstance(ctx.type, TypedDictType)\n            and len(ctx.arg_types) >= 1\n            and len(ctx.arg_types[0]) == 1):\n        if isinstance(ctx.args[0][0], StrExpr):\n            key = ctx.args[0][0].value\n            value_type = ctx.type.items.get(key)\n            if value_type:\n                if len(ctx.arg_types) == 1:\n                    return UnionType.make_simplified_union([value_type, NoneTyp()])\n                elif len(ctx.arg_types) == 2 and len(ctx.arg_types[1]) == 1:\n                    return UnionType.make_simplified_union([value_type, ctx.arg_types[1][0]])\n            else:\n                ctx.api.msg.typeddict_item_name_not_found(ctx.type, key, ctx.context)\n                return AnyType()\n    return ctx.default_return_type\n\n\ndef int_pow_callback(ctx: MethodContext) -> Type:\n    \"\"\"Infer a more precise return type for int.__pow__.\"\"\"\n    if (len(ctx.arg_types) == 1\n            and len(ctx.arg_types[0]) == 1):\n        arg = ctx.args[0][0]\n        if isinstance(arg, IntExpr):\n            exponent = arg.value\n        elif isinstance(arg, UnaryExpr) and arg.op == '-' and isinstance(arg.expr, IntExpr):\n            exponent = -arg.expr.value\n        else:\n            # Right operand not an int literal or a negated literal -- give up.\n            return ctx.default_return_type\n        if exponent >= 0:\n            return ctx.api.named_generic_type('builtins.int', [])\n        else:\n            return ctx.api.named_generic_type('builtins.float', [])\n    return ctx.default_return_type\n", "path": "mypy/plugin.py"}]}