-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Better callable: Callable[[Arg('x', int), VarArg(str)], int]
now a thing you can do
#2607
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
Changes from 21 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 |
---|---|---|
|
@@ -2,17 +2,28 @@ | |
|
||
from mypy.nodes import ( | ||
Expression, NameExpr, MemberExpr, IndexExpr, TupleExpr, | ||
ListExpr, StrExpr, BytesExpr, UnicodeExpr, EllipsisExpr, | ||
get_member_expr_fullname | ||
ListExpr, StrExpr, BytesExpr, UnicodeExpr, EllipsisExpr, CallExpr, | ||
ARG_POS, ARG_NAMED, get_member_expr_fullname | ||
) | ||
from mypy.fastparse import parse_type_comment | ||
from mypy.types import Type, UnboundType, TypeList, EllipsisType | ||
from mypy.types import ( | ||
Type, UnboundType, TypeList, EllipsisType, AnyType, Optional, CallableArgument, | ||
) | ||
|
||
|
||
class TypeTranslationError(Exception): | ||
"""Exception raised when an expression is not valid as a type.""" | ||
|
||
|
||
def _extract_str(expr: Expression) -> Optional[str]: | ||
if isinstance(expr, NameExpr) and expr.name == 'None': | ||
return None | ||
elif isinstance(expr, StrExpr): | ||
return expr.value | ||
else: | ||
raise TypeTranslationError() | ||
|
||
|
||
def expr_to_unanalyzed_type(expr: Expression) -> Type: | ||
"""Translate an expression to the corresponding type. | ||
|
||
|
@@ -43,6 +54,29 @@ def expr_to_unanalyzed_type(expr: Expression) -> Type: | |
return base | ||
else: | ||
raise TypeTranslationError() | ||
elif isinstance(expr, CallExpr): | ||
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. Support MemberExpr |
||
if not isinstance(expr.callee, NameExpr): | ||
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. Also support |
||
raise TypeTranslationError() | ||
arg_const = expr.callee.name | ||
name = None | ||
typ = AnyType(implicit=True) # type: Type | ||
for i, arg in enumerate(expr.args): | ||
if expr.arg_names[i] is not None: | ||
if expr.arg_names[i] == "name": | ||
name = _extract_str(arg) | ||
continue | ||
elif expr.arg_names[i] == "typ": | ||
typ = expr_to_unanalyzed_type(arg) | ||
continue | ||
else: | ||
raise TypeTranslationError() | ||
elif i == 0: | ||
typ = expr_to_unanalyzed_type(arg) | ||
elif i == 1: | ||
name = _extract_str(arg) | ||
else: | ||
raise TypeTranslationError() | ||
return CallableArgument(typ, name, arg_const, expr.line, expr.column) | ||
elif isinstance(expr, ListExpr): | ||
return TypeList([expr_to_unanalyzed_type(t) for t in expr.items], | ||
line=expr.line, column=expr.column) | ||
|
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,49 @@ 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) | ||
constructor = "BadArgConstructor" | ||
name = None # type: Optional[str] | ||
typ = AnyType(implicit=True) # type: Type | ||
for i, arg in enumerate(e.args): | ||
if i == 0: | ||
typ = self.visit(arg) | ||
elif i == 1: | ||
name = self._extract_str(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": | ||
name = self._extract_str(value) | ||
elif k.arg == "typ": | ||
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. Use |
||
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_str(self, n: ast3.expr) -> str: | ||
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. Rename this to be like Figure out handling unicode in python2:
|
||
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 +1084,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 |
---|---|---|
|
@@ -11,7 +11,7 @@ | |
from mypy.types import ( | ||
CallableType, EllipsisType, Instance, Overloaded, TupleType, TypedDictType, | ||
TypeList, TypeVarType, UnboundType, UnionType, TypeVisitor, | ||
TypeType | ||
TypeType, CallableArgument, | ||
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. Remove from imports |
||
) | ||
from mypy.visitor import NodeVisitor | ||
|
||
|
@@ -177,9 +177,6 @@ def visit_callable_type(self, ct: CallableType) -> None: | |
val.accept(self) | ||
v.upper_bound.accept(self) | ||
|
||
def visit_ellipsis_type(self, e: EllipsisType) -> None: | ||
pass # Nothing to descend into. | ||
|
||
def visit_overloaded(self, t: Overloaded) -> None: | ||
for ct in t.items(): | ||
ct.accept(self) | ||
|
@@ -210,10 +207,6 @@ def visit_typeddict_type(self, tdt: TypedDictType) -> None: | |
if tdt.fallback is not None: | ||
tdt.fallback.accept(self) | ||
|
||
def visit_type_list(self, tl: TypeList) -> None: | ||
for t in tl.items: | ||
t.accept(self) | ||
|
||
def visit_type_var(self, tvt: TypeVarType) -> None: | ||
if tvt.values: | ||
for vt in tvt.values: | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,8 +4,8 @@ | |
from mypy.join import is_similar_callables, combine_similar_callables, join_type_list | ||
from mypy.types import ( | ||
Type, AnyType, TypeVisitor, UnboundType, NoneTyp, TypeVarType, | ||
Instance, CallableType, TupleType, TypedDictType, ErasedType, TypeList, UnionType, PartialType, | ||
DeletedType, UninhabitedType, TypeType | ||
Instance, CallableType, TupleType, TypedDictType, ErasedType, TypeList, UnionType, | ||
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. Undo change to import lines |
||
PartialType, DeletedType, UninhabitedType, TypeType | ||
) | ||
from mypy.subtypes import is_equivalent, is_subtype | ||
|
||
|
@@ -139,9 +139,6 @@ def visit_unbound_type(self, t: UnboundType) -> Type: | |
else: | ||
return AnyType() | ||
|
||
def visit_type_list(self, t: TypeList) -> Type: | ||
assert False, 'Not supported' | ||
|
||
def visit_any(self, t: AnyType) -> Type: | ||
return self.s | ||
|
||
|
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.
Add comment about why it makes sense to just return
typ
here and elsewhere in this file.