forked from python/mypy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
constraints.py
249 lines (207 loc) · 9.33 KB
/
constraints.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
from mtypes import (
Callable, Typ, TypeVisitor, UnboundType, Any, Void, NoneTyp, TypeVar,
Instance, TupleType, Overloaded, ErasedType
)
from expandtype import expand_caller_var_args
from subtypes import map_instance_to_supertype
import nodes
Constraint[] infer_constraints_for_callable(
Callable callee, Typ[] arg_types, int[] arg_kinds,
int[][] formal_to_actual):
"""Infer type variable constraints for a callable and actual arguments.
Return a list of constraints.
"""
Constraint[] constraints = []
tuple_counter = [0]
for i, actuals in enumerate(formal_to_actual):
for actual in actuals:
actual_type = get_actual_type(arg_types[actual], arg_kinds[actual],
tuple_counter)
c = infer_constraints(callee.arg_types[i], actual_type,
SUPERTYPE_OF)
constraints.extend(c)
return constraints
Typ get_actual_type(Typ arg_type, int kind, int[] tuple_counter):
"""Return the type of an actual argument with the given kind.
If the argument is a *arg, return the individual argument item.
"""
if kind == nodes.ARG_STAR:
if isinstance(arg_type, Instance) and (
((Instance)arg_type).typ.full_name() == 'builtins.list'):
# List *arg. TODO any iterable
return ((Instance)arg_type).args[0]
elif isinstance(arg_type, TupleType):
# Get the next tuple item of a tuple *arg.
tuplet = (TupleType)arg_type
tuple_counter[0] += 1
return tuplet.items[tuple_counter[0] - 1]
else:
return Any()
elif kind == nodes.ARG_STAR2:
if isinstance(arg_type, Instance) and (
((Instance)arg_type).typ.full_name() == 'builtins.dict'):
# Dict **arg. TODO more general (Mapping)
return ((Instance)arg_type).args[1]
else:
return Any()
else:
# No translation for other kinds.
return arg_type
Constraint[] infer_constraints(Typ template, Typ actual, int direction):
"""Infer type constraints.
Match a template type, which may contain type variable references,
recursively against a type which does not contain (the same) type
variable references. The result is a list of type constrains of
form 'T is a supertype/subtype of x', where T is a type variable
present in the the template and x is a type without reference to
type variables present in the template.
Assume T and S are type variables. Now the following results can be
calculated (read as '(template, actual) --> result'):
(T, X) --> T :> X
(X<T>, X<Y>) --> T <: Y and T :> Y
((T, T), (X, Y)) --> T :> X and T :> Y
((T, S), (X, Y)) --> T :> X and S :> Y
(X<T>, dynamic) --> T <: dynamic and T :> dynamic
The constraints are represented as Constraint objects.
"""
return template.accept(ConstraintBuilderVisitor(actual, direction))
SUBTYPE_OF = 0
SUPERTYPE_OF = 1
class Constraint:
"""A representation of a type constraint, either T <: type or T :>
type (T is a type variable).
"""
int type_var # Type variable id
int op # SUBTYPE_OF or SUPERTYPE_OF
Typ target
str __repr__(self):
op_str = '<:'
if self.op == SUPERTYPE_OF:
op_str = ':>'
return '{} {} {}'.format(self.type_var, op_str, self.target)
void __init__(self, int type_var, int op, Typ target):
self.type_var = type_var
self.op = op
self.target = target
class ConstraintBuilderVisitor(TypeVisitor<Constraint[]>):
"""Visitor class for inferring type constraints."""
Typ actual # The type that is compared against a template
void __init__(self, Typ actual, int direction):
# Direction must be SUBTYPE_OF or SUPERTYPE_OF.
self.actual = actual
self.direction = direction
# Trivial leaf types
Constraint[] visit_unbound_type(self, UnboundType template):
return []
Constraint[] visit_any(self, Any template):
return []
Constraint[] visit_void(self, Void template):
return []
Constraint[] visit_none_type(self, NoneTyp template):
return []
Constraint[] visit_erased_type(self, ErasedType template):
return []
# Non-trivial leaf type
Constraint[] visit_type_var(self, TypeVar template):
return [Constraint(template.id, SUPERTYPE_OF, self.actual)]
# Non-leaf types
Constraint[] visit_instance(self, Instance template):
actual = self.actual
if isinstance(actual, Instance):
res = <Constraint> []
instance = (Instance)actual
if (self.direction == SUBTYPE_OF and
template.typ.has_base(instance.typ.full_name())):
mapped = map_instance_to_supertype(template, instance.typ)
for i in range(len(instance.args)):
# The constraints for generic type parameters are
# invariant. Include the default constraint and its
# negation to achieve the effect.
cb = infer_constraints(mapped.args[i], instance.args[i],
self.direction)
res.extend(cb)
res.extend(negate_constraints(cb))
return res
elif (self.direction == SUPERTYPE_OF and
instance.typ.has_base(template.typ.full_name())):
mapped = map_instance_to_supertype(instance, template.typ)
for j in range(len(template.args)):
# The constraints for generic type parameters are
# invariant.
cb = infer_constraints(template.args[j], mapped.args[j],
self.direction)
res.extend(cb)
res.extend(negate_constraints(cb))
return res
if isinstance(actual, Any):
# IDEA: Include both ways, i.e. add negation as well?
return self.infer_against_any(template.args)
else:
return []
Constraint[] visit_callable(self, Callable template):
if isinstance(self.actual, Callable):
cactual = (Callable)self.actual
# FIX verify argument counts
# FIX what if one of the functions is generic
Constraint[] res = []
for i in range(len(template.arg_types)):
# Negate constraints due function argument type contravariance.
res.extend(negate_constraints(infer_constraints(
template.arg_types[i], cactual.arg_types[i],
self.direction)))
res.extend(infer_constraints(template.ret_type, cactual.ret_type,
self.direction))
return res
elif isinstance(self.actual, Any):
# FIX what if generic
res = self.infer_against_any(template.arg_types)
res.extend(infer_constraints(template.ret_type, Any(),
self.direction))
return res
elif isinstance(self.actual, Overloaded):
return self.infer_against_overloaded((Overloaded)self.actual,
template)
else:
return []
Constraint[] infer_against_overloaded(self, Overloaded overloaded,
Callable template):
# Create constraints by matching an overloaded type against a template.
# This is tricky to do in general. We cheat by only matching against
# the first overload item, and by only matching the return type. This
# seems to work somewhat well, but we should really use a more
# reliable technique.
item = overloaded.items()[0]
return infer_constraints(template.ret_type, item.ret_type,
self.direction)
Constraint[] visit_tuple_type(self, TupleType template):
actual = self.actual
if (isinstance(actual, TupleType) and
len(((TupleType)actual).items) == len(template.items)):
Constraint[] res = []
for i in range(len(template.items)):
res.extend(infer_constraints(template.items[i],
((TupleType)actual).items[i],
self.direction))
return res
elif isinstance(actual, Any):
return self.infer_against_any(template.items)
else:
return []
Constraint[] infer_against_any(self, Typ[] types):
Constraint[] res = []
for t in types:
res.extend(infer_constraints(t, Any(), self.direction))
return res
Constraint[] negate_constraints(Constraint[] constraints):
Constraint[] res = []
for c in constraints:
res.append(Constraint(c.type_var, neg_op(c.op), c.target))
return res
int neg_op(int op):
"""Map SubtypeOf to SupertypeOf and vice versa."""
if op == SUBTYPE_OF:
return SUPERTYPE_OF
elif op == SUPERTYPE_OF:
return SUBTYPE_OF
else:
raise ValueError('Invalid operator {}'.format(op))