]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/predicates.go
[dev.typeparams] go/types: remove typeparams wrappers and aliases
[gostls13.git] / src / go / types / predicates.go
1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // This file implements commonly used type predicates.
6
7 package types
8
9 // isNamed reports whether typ has a name.
10 // isNamed may be called with types that are not fully set up.
11 func isNamed(typ Type) bool {
12         switch typ.(type) {
13         case *Basic, *Named, *TypeParam, *instance:
14                 return true
15         }
16         return false
17 }
18
19 // isGeneric reports whether a type is a generic, uninstantiated type (generic
20 // signatures are not included).
21 func isGeneric(typ Type) bool {
22         // A parameterized type is only instantiated if it doesn't have an instantiation already.
23         named, _ := typ.(*Named)
24         return named != nil && named.obj != nil && named.TParams() != nil && named.targs == nil
25 }
26
27 func is(typ Type, what BasicInfo) bool {
28         switch t := optype(typ).(type) {
29         case *Basic:
30                 return t.info&what != 0
31         case *Union:
32                 return t.underIs(func(typ Type) bool { return is(typ, what) })
33         }
34         return false
35 }
36
37 func isBoolean(typ Type) bool  { return is(typ, IsBoolean) }
38 func isInteger(typ Type) bool  { return is(typ, IsInteger) }
39 func isUnsigned(typ Type) bool { return is(typ, IsUnsigned) }
40 func isFloat(typ Type) bool    { return is(typ, IsFloat) }
41 func isComplex(typ Type) bool  { return is(typ, IsComplex) }
42 func isNumeric(typ Type) bool  { return is(typ, IsNumeric) }
43 func isString(typ Type) bool   { return is(typ, IsString) }
44
45 // Note that if typ is a type parameter, isInteger(typ) || isFloat(typ) does not
46 // produce the expected result because a type list that contains both an integer
47 // and a floating-point type is neither (all) integers, nor (all) floats.
48 // Use isIntegerOrFloat instead.
49 func isIntegerOrFloat(typ Type) bool { return is(typ, IsInteger|IsFloat) }
50
51 // isNumericOrString is the equivalent of isIntegerOrFloat for isNumeric(typ) || isString(typ).
52 func isNumericOrString(typ Type) bool { return is(typ, IsNumeric|IsString) }
53
54 // isTyped reports whether typ is typed; i.e., not an untyped
55 // constant or boolean. isTyped may be called with types that
56 // are not fully set up.
57 func isTyped(typ Type) bool {
58         // isTyped is called with types that are not fully
59         // set up. Must not call asBasic()!
60         // A *Named or *instance type is always typed, so
61         // we only need to check if we have a true *Basic
62         // type.
63         t, _ := typ.(*Basic)
64         return t == nil || t.info&IsUntyped == 0
65 }
66
67 // isUntyped(typ) is the same as !isTyped(typ).
68 func isUntyped(typ Type) bool {
69         return !isTyped(typ)
70 }
71
72 func isOrdered(typ Type) bool { return is(typ, IsOrdered) }
73
74 func isConstType(typ Type) bool {
75         // Type parameters are never const types.
76         t, _ := under(typ).(*Basic)
77         return t != nil && t.info&IsConstType != 0
78 }
79
80 // IsInterface reports whether typ is an interface type.
81 func IsInterface(typ Type) bool {
82         return asInterface(typ) != nil
83 }
84
85 // Comparable reports whether values of type T are comparable.
86 func Comparable(T Type) bool {
87         return comparable(T, nil)
88 }
89
90 func comparable(T Type, seen map[Type]bool) bool {
91         if seen[T] {
92                 return true
93         }
94         if seen == nil {
95                 seen = make(map[Type]bool)
96         }
97         seen[T] = true
98
99         // If T is a type parameter not constrained by any type
100         // list (i.e., it's operational type is the top type),
101         // T is comparable if it has the == method. Otherwise,
102         // the operational type "wins". For instance
103         //
104         //     interface{ comparable; type []byte }
105         //
106         // is not comparable because []byte is not comparable.
107         if t := asTypeParam(T); t != nil && optype(t) == theTop {
108                 return t.Bound().IsComparable()
109         }
110
111         switch t := optype(T).(type) {
112         case *Basic:
113                 // assume invalid types to be comparable
114                 // to avoid follow-up errors
115                 return t.kind != UntypedNil
116         case *Pointer, *Interface, *Chan:
117                 return true
118         case *Struct:
119                 for _, f := range t.fields {
120                         if !comparable(f.typ, seen) {
121                                 return false
122                         }
123                 }
124                 return true
125         case *Array:
126                 return comparable(t.elem, seen)
127         case *Union:
128                 return t.underIs(func(t Type) bool {
129                         return comparable(t, seen)
130                 })
131         case *TypeParam:
132                 return t.Bound().IsComparable()
133         }
134         return false
135 }
136
137 // hasNil reports whether a type includes the nil value.
138 func hasNil(typ Type) bool {
139         switch t := optype(typ).(type) {
140         case *Basic:
141                 return t.kind == UnsafePointer
142         case *Slice, *Pointer, *Signature, *Interface, *Map, *Chan:
143                 return true
144         case *Union:
145                 return t.underIs(hasNil)
146         }
147         return false
148 }
149
150 // identical reports whether x and y are identical types.
151 // Receivers of Signature types are ignored.
152 func (check *Checker) identical(x, y Type) bool {
153         return check.identical0(x, y, true, nil)
154 }
155
156 // identicalIgnoreTags reports whether x and y are identical types if tags are ignored.
157 // Receivers of Signature types are ignored.
158 func (check *Checker) identicalIgnoreTags(x, y Type) bool {
159         return check.identical0(x, y, false, nil)
160 }
161
162 // An ifacePair is a node in a stack of interface type pairs compared for identity.
163 type ifacePair struct {
164         x, y *Interface
165         prev *ifacePair
166 }
167
168 func (p *ifacePair) identical(q *ifacePair) bool {
169         return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
170 }
171
172 // For changes to this code the corresponding changes should be made to unifier.nify.
173 func (check *Checker) identical0(x, y Type, cmpTags bool, p *ifacePair) bool {
174         // types must be expanded for comparison
175         x = expandf(x)
176         y = expandf(y)
177
178         if x == y {
179                 return true
180         }
181
182         switch x := x.(type) {
183         case *Basic:
184                 // Basic types are singletons except for the rune and byte
185                 // aliases, thus we cannot solely rely on the x == y check
186                 // above. See also comment in TypeName.IsAlias.
187                 if y, ok := y.(*Basic); ok {
188                         return x.kind == y.kind
189                 }
190
191         case *Array:
192                 // Two array types are identical if they have identical element types
193                 // and the same array length.
194                 if y, ok := y.(*Array); ok {
195                         // If one or both array lengths are unknown (< 0) due to some error,
196                         // assume they are the same to avoid spurious follow-on errors.
197                         return (x.len < 0 || y.len < 0 || x.len == y.len) && check.identical0(x.elem, y.elem, cmpTags, p)
198                 }
199
200         case *Slice:
201                 // Two slice types are identical if they have identical element types.
202                 if y, ok := y.(*Slice); ok {
203                         return check.identical0(x.elem, y.elem, cmpTags, p)
204                 }
205
206         case *Struct:
207                 // Two struct types are identical if they have the same sequence of fields,
208                 // and if corresponding fields have the same names, and identical types,
209                 // and identical tags. Two embedded fields are considered to have the same
210                 // name. Lower-case field names from different packages are always different.
211                 if y, ok := y.(*Struct); ok {
212                         if x.NumFields() == y.NumFields() {
213                                 for i, f := range x.fields {
214                                         g := y.fields[i]
215                                         if f.embedded != g.embedded ||
216                                                 cmpTags && x.Tag(i) != y.Tag(i) ||
217                                                 !f.sameId(g.pkg, g.name) ||
218                                                 !check.identical0(f.typ, g.typ, cmpTags, p) {
219                                                 return false
220                                         }
221                                 }
222                                 return true
223                         }
224                 }
225
226         case *Pointer:
227                 // Two pointer types are identical if they have identical base types.
228                 if y, ok := y.(*Pointer); ok {
229                         return check.identical0(x.base, y.base, cmpTags, p)
230                 }
231
232         case *Tuple:
233                 // Two tuples types are identical if they have the same number of elements
234                 // and corresponding elements have identical types.
235                 if y, ok := y.(*Tuple); ok {
236                         if x.Len() == y.Len() {
237                                 if x != nil {
238                                         for i, v := range x.vars {
239                                                 w := y.vars[i]
240                                                 if !check.identical0(v.typ, w.typ, cmpTags, p) {
241                                                         return false
242                                                 }
243                                         }
244                                 }
245                                 return true
246                         }
247                 }
248
249         case *Signature:
250                 // Two function types are identical if they have the same number of parameters
251                 // and result values, corresponding parameter and result types are identical,
252                 // and either both functions are variadic or neither is. Parameter and result
253                 // names are not required to match.
254                 // Generic functions must also have matching type parameter lists, but for the
255                 // parameter names.
256                 if y, ok := y.(*Signature); ok {
257                         return x.variadic == y.variadic &&
258                                 check.identicalTParams(x.tparams, y.tparams, cmpTags, p) &&
259                                 check.identical0(x.params, y.params, cmpTags, p) &&
260                                 check.identical0(x.results, y.results, cmpTags, p)
261                 }
262
263         case *Union:
264                 // Two union types are identical if they contain the same terms.
265                 // The set (list) of types in a union type consists of unique
266                 // types - each type appears exactly once. Thus, two union types
267                 // must contain the same number of types to have chance of
268                 // being equal.
269                 if y, ok := y.(*Union); ok && x.NumTerms() == y.NumTerms() {
270                         // Every type in x.types must be in y.types.
271                         // Quadratic algorithm, but probably good enough for now.
272                         // TODO(gri) we need a fast quick type ID/hash for all types.
273                 L:
274                         for i, xt := range x.types {
275                                 for j, yt := range y.types {
276                                         if Identical(xt, yt) && x.tilde[i] == y.tilde[j] {
277                                                 continue L // x is in y.types
278                                         }
279                                 }
280                                 return false // x is not in y.types
281                         }
282                         return true
283                 }
284
285         case *Interface:
286                 // Two interface types are identical if they have the same set of methods with
287                 // the same names and identical function types. Lower-case method names from
288                 // different packages are always different. The order of the methods is irrelevant.
289                 if y, ok := y.(*Interface); ok {
290                         a := x.typeSet().methods
291                         b := y.typeSet().methods
292                         if len(a) == len(b) {
293                                 // Interface types are the only types where cycles can occur
294                                 // that are not "terminated" via named types; and such cycles
295                                 // can only be created via method parameter types that are
296                                 // anonymous interfaces (directly or indirectly) embedding
297                                 // the current interface. Example:
298                                 //
299                                 //    type T interface {
300                                 //        m() interface{T}
301                                 //    }
302                                 //
303                                 // If two such (differently named) interfaces are compared,
304                                 // endless recursion occurs if the cycle is not detected.
305                                 //
306                                 // If x and y were compared before, they must be equal
307                                 // (if they were not, the recursion would have stopped);
308                                 // search the ifacePair stack for the same pair.
309                                 //
310                                 // This is a quadratic algorithm, but in practice these stacks
311                                 // are extremely short (bounded by the nesting depth of interface
312                                 // type declarations that recur via parameter types, an extremely
313                                 // rare occurrence). An alternative implementation might use a
314                                 // "visited" map, but that is probably less efficient overall.
315                                 q := &ifacePair{x, y, p}
316                                 for p != nil {
317                                         if p.identical(q) {
318                                                 return true // same pair was compared before
319                                         }
320                                         p = p.prev
321                                 }
322                                 if debug {
323                                         assertSortedMethods(a)
324                                         assertSortedMethods(b)
325                                 }
326                                 for i, f := range a {
327                                         g := b[i]
328                                         if f.Id() != g.Id() || !check.identical0(f.typ, g.typ, cmpTags, q) {
329                                                 return false
330                                         }
331                                 }
332                                 return true
333                         }
334                 }
335
336         case *Map:
337                 // Two map types are identical if they have identical key and value types.
338                 if y, ok := y.(*Map); ok {
339                         return check.identical0(x.key, y.key, cmpTags, p) && check.identical0(x.elem, y.elem, cmpTags, p)
340                 }
341
342         case *Chan:
343                 // Two channel types are identical if they have identical value types
344                 // and the same direction.
345                 if y, ok := y.(*Chan); ok {
346                         return x.dir == y.dir && check.identical0(x.elem, y.elem, cmpTags, p)
347                 }
348
349         case *Named:
350                 // Two named types are identical if their type names originate
351                 // in the same type declaration.
352                 if y, ok := y.(*Named); ok {
353                         // TODO(gri) Why is x == y not sufficient? And if it is,
354                         //           we can just return false here because x == y
355                         //           is caught in the very beginning of this function.
356                         return x.obj == y.obj
357                 }
358
359         case *TypeParam:
360                 // nothing to do (x and y being equal is caught in the very beginning of this function)
361
362         // case *instance:
363         //      unreachable since types are expanded
364
365         case *top:
366                 // Either both types are theTop in which case the initial x == y check
367                 // will have caught them. Otherwise they are not identical.
368
369         case nil:
370                 // avoid a crash in case of nil type
371
372         default:
373                 unreachable()
374         }
375
376         return false
377 }
378
379 func (check *Checker) identicalTParams(x, y []*TypeName, cmpTags bool, p *ifacePair) bool {
380         if len(x) != len(y) {
381                 return false
382         }
383         for i, x := range x {
384                 y := y[i]
385                 if !check.identical0(x.typ.(*TypeParam).bound, y.typ.(*TypeParam).bound, cmpTags, p) {
386                         return false
387                 }
388         }
389         return true
390 }
391
392 // Default returns the default "typed" type for an "untyped" type;
393 // it returns the incoming type for all other types. The default type
394 // for untyped nil is untyped nil.
395 //
396 func Default(typ Type) Type {
397         if t, ok := typ.(*Basic); ok {
398                 switch t.kind {
399                 case UntypedBool:
400                         return Typ[Bool]
401                 case UntypedInt:
402                         return Typ[Int]
403                 case UntypedRune:
404                         return universeRune // use 'rune' name
405                 case UntypedFloat:
406                         return Typ[Float64]
407                 case UntypedComplex:
408                         return Typ[Complex128]
409                 case UntypedString:
410                         return Typ[String]
411                 }
412         }
413         return typ
414 }