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