-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Better callable: Callable[[Arg('x', int), VarArg(str)], int]
now a thing you can do
#2607
Changes from 32 commits
249d70f
7ecdcc1
066bd5e
213944b
0e19070
3f2f617
0b69630
f4ccf92
967bb5a
bb5134e
d4a83e1
54a5da9
e79c527
52ffe5c
06416f7
398fbad
2c9ce02
51c6f56
5e679a3
0926fe9
288a8be
6e67ab2
97a859b
1c7d4c6
f153850
be954f5
07ae917
1b97362
552f49e
f2e3663
27e2a9d
793a663
3d212b3
0780149
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,10 +19,12 @@ | |
StarExpr, YieldFromExpr, NonlocalDecl, DictionaryComprehension, | ||
SetComprehension, ComplexExpr, EllipsisExpr, YieldExpr, Argument, | ||
AwaitExpr, TempNode, Expression, Statement, | ||
ARG_POS, ARG_OPT, ARG_STAR, ARG_NAMED, ARG_NAMED_OPT, ARG_STAR2 | ||
ARG_POS, ARG_OPT, ARG_STAR, ARG_NAMED, ARG_NAMED_OPT, ARG_STAR2, | ||
check_arg_names, | ||
) | ||
from mypy.types import ( | ||
Type, CallableType, AnyType, UnboundType, TupleType, TypeList, EllipsisType, | ||
CallableArgument, | ||
) | ||
from mypy import defaults | ||
from mypy import experiments | ||
|
@@ -444,24 +446,12 @@ def make_argument(arg: ast3.arg, default: Optional[ast3.expr], kind: int) -> Arg | |
new_args.append(make_argument(args.kwarg, None, ARG_STAR2)) | ||
names.append(args.kwarg) | ||
|
||
seen_names = set() # type: Set[str] | ||
for name in names: | ||
if name.arg in seen_names: | ||
self.fail("duplicate argument '{}' in function definition".format(name.arg), | ||
name.lineno, name.col_offset) | ||
break | ||
seen_names.add(name.arg) | ||
def fail_arg(msg: str, arg: ast3.arg) -> None: | ||
self.fail(msg, arg.lineno, arg.col_offset) | ||
|
||
return new_args | ||
check_arg_names([name.arg for name in names], names, fail_arg) | ||
|
||
def stringify_name(self, n: ast3.AST) -> str: | ||
if isinstance(n, ast3.Name): | ||
return n.id | ||
elif isinstance(n, ast3.Attribute): | ||
sv = self.stringify_name(n.value) | ||
if sv is not None: | ||
return "{}.{}".format(sv, n.attr) | ||
return None # Can't do it. | ||
return new_args | ||
|
||
# ClassDef(identifier name, | ||
# expr* bases, | ||
|
@@ -474,7 +464,7 @@ def visit_ClassDef(self, n: ast3.ClassDef) -> ClassDef: | |
metaclass_arg = find(lambda x: x.arg == 'metaclass', n.keywords) | ||
metaclass = None | ||
if metaclass_arg: | ||
metaclass = self.stringify_name(metaclass_arg.value) | ||
metaclass = stringify_name(metaclass_arg.value) | ||
if metaclass is None: | ||
metaclass = '<error>' # To be reported later | ||
|
||
|
@@ -965,6 +955,21 @@ class TypeConverter(ast3.NodeTransformer): # type: ignore # typeshed PR #931 | |
def __init__(self, errors: Errors, line: int = -1) -> None: | ||
self.errors = errors | ||
self.line = line | ||
self.node_stack = [] # type: List[ast3.AST] | ||
|
||
def visit(self, node: ast3.AST) -> Type: | ||
"""Modified visit -- keep track of the stack of nodes""" | ||
self.node_stack.append(node) | ||
try: | ||
return super().visit(node) | ||
finally: | ||
self.node_stack.pop() | ||
|
||
def parent(self) -> ast3.AST: | ||
"""Return the AST node above the one we are processing""" | ||
if len(self.node_stack) < 2: | ||
return None | ||
return self.node_stack[-2] | ||
|
||
def fail(self, msg: str, line: int, column: int) -> None: | ||
self.errors.report(line, column, msg) | ||
|
@@ -985,6 +990,55 @@ def visit_NoneType(self, n: Any) -> Type: | |
def translate_expr_list(self, l: Sequence[ast3.AST]) -> List[Type]: | ||
return [self.visit(e) for e in l] | ||
|
||
def visit_Call(self, e: ast3.Call) -> Type: | ||
# Parse the arg constructor | ||
if not isinstance(self.parent(), ast3.List): | ||
return self.generic_visit(e) | ||
f = e.func | ||
constructor = stringify_name(f) | ||
if not constructor: | ||
self.fail("Expected arg constructor name", e.lineno, e.col_offset) | ||
name = None # type: Optional[str] | ||
default_type = AnyType(implicit=True) | ||
typ = default_type # type: Type | ||
for i, arg in enumerate(e.args): | ||
if i == 0: | ||
typ = self.visit(arg) | ||
elif i == 1: | ||
name = self._extract_argument_name(arg) | ||
else: | ||
self.fail("Too many arguments for argument constructor", | ||
f.lineno, f.col_offset) | ||
for k in e.keywords: | ||
value = k.value | ||
if k.arg == "name": | ||
if name is not None: | ||
self.fail('"{}" gets multiple values for keyword argument "name"'.format( | ||
constructor), f.lineno, f.col_offset) | ||
name = self._extract_argument_name(value) | ||
elif k.arg == "type": | ||
if typ is not default_type: | ||
self.fail('"{}" gets multiple values for keyword argument "type"'.format( | ||
constructor), f.lineno, f.col_offset) | ||
typ = self.visit(value) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Make an error if we re-set |
||
else: | ||
self.fail( | ||
'Unexpected argument "{}" for argument constructor'.format(k.arg), | ||
value.lineno, value.col_offset) | ||
return CallableArgument(typ, name, constructor, e.lineno, e.col_offset) | ||
|
||
def translate_argument_list(self, l: Sequence[ast3.AST]) -> TypeList: | ||
return TypeList([self.visit(e) for e in l], line=self.line) | ||
|
||
def _extract_argument_name(self, n: ast3.expr) -> str: | ||
if isinstance(n, ast3.Str): | ||
return n.s.strip() | ||
elif isinstance(n, ast3.NameConstant) and str(n.value) == 'None': | ||
return None | ||
self.fail('Expected string literal for argument name, got {}'.format( | ||
type(n).__name__), self.line, 0) | ||
return None | ||
|
||
def visit_Name(self, n: ast3.Name) -> Type: | ||
return UnboundType(n.id, line=self.line) | ||
|
||
|
@@ -1036,4 +1090,14 @@ def visit_Ellipsis(self, n: ast3.Ellipsis) -> Type: | |
|
||
# List(expr* elts, expr_context ctx) | ||
def visit_List(self, n: ast3.List) -> Type: | ||
return TypeList(self.translate_expr_list(n.elts), line=self.line) | ||
return self.translate_argument_list(n.elts) | ||
|
||
|
||
def stringify_name(n: ast3.AST) -> Optional[str]: | ||
if isinstance(n, ast3.Name): | ||
return n.id | ||
elif isinstance(n, ast3.Attribute): | ||
sv = stringify_name(n.value) | ||
if sv is not None: | ||
return "{}.{}".format(sv, n.attr) | ||
return None # Can't do it. |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,7 +4,7 @@ | |
from abc import abstractmethod | ||
|
||
from typing import ( | ||
Any, TypeVar, List, Tuple, cast, Set, Dict, Union, Optional | ||
Any, TypeVar, List, Tuple, cast, Set, Dict, Union, Optional, Callable, | ||
) | ||
|
||
import mypy.strconv | ||
|
@@ -2424,3 +2424,44 @@ def get_member_expr_fullname(expr: MemberExpr) -> str: | |
for key, obj in globals().items() | ||
if isinstance(obj, type) and issubclass(obj, SymbolNode) and obj is not SymbolNode | ||
} | ||
|
||
|
||
def check_arg_kinds(arg_kinds: List[int], nodes: List[T], fail: Callable[[str, T], None]) -> None: | ||
is_var_arg = False | ||
is_kw_arg = False | ||
seen_named = False | ||
seen_opt = False | ||
for kind, node in zip(arg_kinds, nodes): | ||
if kind == ARG_POS: | ||
if is_var_arg or is_kw_arg or seen_named or seen_opt: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Change messaging to refer to "var args" |
||
fail("Required positional args may not appear " | ||
"after default, named or var args", | ||
node) | ||
break | ||
elif kind == ARG_OPT: | ||
if is_var_arg or is_kw_arg or seen_named: | ||
fail("Positional default args may not appear after named or var args", node) | ||
break | ||
seen_opt = True | ||
elif kind == ARG_STAR: | ||
if is_var_arg or is_kw_arg or seen_named: | ||
fail("Var args may not appear after named or var args", node) | ||
break | ||
is_var_arg = True | ||
elif kind == ARG_NAMED or kind == ARG_NAMED_OPT: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe we shouldn't allow these after There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done |
||
seen_named = True | ||
elif kind == ARG_STAR2: | ||
if is_kw_arg: | ||
fail("You may only have one **kwargs argument", node) | ||
break | ||
is_kw_arg = True | ||
|
||
|
||
def check_arg_names(names: List[str], nodes: List[T], fail: Callable[[str, T], None], | ||
description: str = 'function definition') -> None: | ||
seen_names = set() # type: Set[str] | ||
for name, node in zip(names, nodes): | ||
if name is not None and name in seen_names: | ||
fail("Duplicate argument '{}' in {}".format(name, description), node) | ||
break | ||
seen_names.add(name) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Support MemberExpr