]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/predicates.go
[dev.cmdgo] all: merge master (912f075) into dev.cmdgo
[gostls13.git] / src / cmd / compile / internal / types2 / 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 types2
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 *Sum:
32                 return t.is(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 Basic()!
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 underlying type is the top type),
101         // T is comparable if it has the == method. Otherwise,
102         // the underlying 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 *Sum:
128                 pred := func(t Type) bool {
129                         return comparable(t, seen)
130                 }
131                 return t.is(pred)
132         case *TypeParam:
133                 return t.Bound().IsComparable()
134         }
135         return false
136 }
137
138 // hasNil reports whether a type includes the nil value.
139 func hasNil(typ Type) bool {
140         switch t := optype(typ).(type) {
141         case *Basic:
142                 return t.kind == UnsafePointer
143         case *Slice, *Pointer, *Signature, *Interface, *Map, *Chan:
144                 return true
145         case *Sum:
146                 return t.is(hasNil)
147         }
148         return false
149 }
150
151 // identical reports whether x and y are identical types.
152 // Receivers of Signature types are ignored.
153 func (check *Checker) identical(x, y Type) bool {
154         return check.identical0(x, y, true, nil)
155 }
156
157 // identicalIgnoreTags reports whether x and y are identical types if tags are ignored.
158 // Receivers of Signature types are ignored.
159 func (check *Checker) identicalIgnoreTags(x, y Type) bool {
160         return check.identical0(x, y, false, nil)
161 }
162
163 // An ifacePair is a node in a stack of interface type pairs compared for identity.
164 type ifacePair struct {
165         x, y *Interface
166         prev *ifacePair
167 }
168
169 func (p *ifacePair) identical(q *ifacePair) bool {
170         return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
171 }
172
173 // For changes to this code the corresponding changes should be made to unifier.nify.
174 func (check *Checker) identical0(x, y Type, cmpTags bool, p *ifacePair) bool {
175         // types must be expanded for comparison
176         x = expandf(x)
177         y = expandf(y)
178
179         if x == y {
180                 return true
181         }
182
183         switch x := x.(type) {
184         case *Basic:
185                 // Basic types are singletons except for the rune and byte
186                 // aliases, thus we cannot solely rely on the x == y check
187                 // above. See also comment in TypeName.IsAlias.
188                 if y, ok := y.(*Basic); ok {
189                         return x.kind == y.kind
190                 }
191
192         case *Array:
193                 // Two array types are identical if they have identical element types
194                 // and the same array length.
195                 if y, ok := y.(*Array); ok {
196                         // If one or both array lengths are unknown (< 0) due to some error,
197                         // assume they are the same to avoid spurious follow-on errors.
198                         return (x.len < 0 || y.len < 0 || x.len == y.len) && check.identical0(x.elem, y.elem, cmpTags, p)
199                 }
200
201         case *Slice:
202                 // Two slice types are identical if they have identical element types.
203                 if y, ok := y.(*Slice); ok {
204                         return check.identical0(x.elem, y.elem, cmpTags, p)
205                 }
206
207         case *Struct:
208                 // Two struct types are identical if they have the same sequence of fields,
209                 // and if corresponding fields have the same names, and identical types,
210                 // and identical tags. Two embedded fields are considered to have the same
211                 // name. Lower-case field names from different packages are always different.
212                 if y, ok := y.(*Struct); ok {
213                         if x.NumFields() == y.NumFields() {
214                                 for i, f := range x.fields {
215                                         g := y.fields[i]
216                                         if f.embedded != g.embedded ||
217                                                 cmpTags && x.Tag(i) != y.Tag(i) ||
218                                                 !f.sameId(g.pkg, g.name) ||
219                                                 !check.identical0(f.typ, g.typ, cmpTags, p) {
220                                                 return false
221                                         }
222                                 }
223                                 return true
224                         }
225                 }
226
227         case *Pointer:
228                 // Two pointer types are identical if they have identical base types.
229                 if y, ok := y.(*Pointer); ok {
230                         return check.identical0(x.base, y.base, cmpTags, p)
231                 }
232
233         case *Tuple:
234                 // Two tuples types are identical if they have the same number of elements
235                 // and corresponding elements have identical types.
236                 if y, ok := y.(*Tuple); ok {
237                         if x.Len() == y.Len() {
238                                 if x != nil {
239                                         for i, v := range x.vars {
240                                                 w := y.vars[i]
241                                                 if !check.identical0(v.typ, w.typ, cmpTags, p) {
242                                                         return false
243                                                 }
244                                         }
245                                 }
246                                 return true
247                         }
248                 }
249
250         case *Signature:
251                 // Two function types are identical if they have the same number of parameters
252                 // and result values, corresponding parameter and result types are identical,
253                 // and either both functions are variadic or neither is. Parameter and result
254                 // names are not required to match.
255                 // Generic functions must also have matching type parameter lists, but for the
256                 // parameter names.
257                 if y, ok := y.(*Signature); ok {
258                         return x.variadic == y.variadic &&
259                                 check.identicalTParams(x.tparams, y.tparams, cmpTags, p) &&
260                                 check.identical0(x.params, y.params, cmpTags, p) &&
261                                 check.identical0(x.results, y.results, cmpTags, p)
262                 }
263
264         case *Sum:
265                 // Two sum types are identical if they contain the same types.
266                 // (Sum types always consist of at least two types. Also, the
267                 // the set (list) of types in a sum type consists of unique
268                 // types - each type appears exactly once. Thus, two sum types
269                 // must contain the same number of types to have chance of
270                 // being equal.
271                 if y, ok := y.(*Sum); ok && len(x.types) == len(y.types) {
272                         // Every type in x.types must be in y.types.
273                         // Quadratic algorithm, but probably good enough for now.
274                         // TODO(gri) we need a fast quick type ID/hash for all types.
275                 L:
276                         for _, x := range x.types {
277                                 for _, y := range y.types {
278                                         if Identical(x, y) {
279                                                 continue L // x is in y.types
280                                         }
281                                 }
282                                 return false // x is not in y.types
283                         }
284                         return true
285                 }
286
287         case *Interface:
288                 // Two interface types are identical if they have the same set of methods with
289                 // the same names and identical function types. Lower-case method names from
290                 // different packages are always different. The order of the methods is irrelevant.
291                 if y, ok := y.(*Interface); ok {
292                         // If identical0 is called (indirectly) via an external API entry point
293                         // (such as Identical, IdenticalIgnoreTags, etc.), check is nil. But in
294                         // that case, interfaces are expected to be complete and lazy completion
295                         // here is not needed.
296                         if check != nil {
297                                 check.completeInterface(nopos, x)
298                                 check.completeInterface(nopos, y)
299                         }
300                         a := x.allMethods
301                         b := y.allMethods
302                         if len(a) == len(b) {
303                                 // Interface types are the only types where cycles can occur
304                                 // that are not "terminated" via named types; and such cycles
305                                 // can only be created via method parameter types that are
306                                 // anonymous interfaces (directly or indirectly) embedding
307                                 // the current interface. Example:
308                                 //
309                                 //    type T interface {
310                                 //        m() interface{T}
311                                 //    }
312                                 //
313                                 // If two such (differently named) interfaces are compared,
314                                 // endless recursion occurs if the cycle is not detected.
315                                 //
316                                 // If x and y were compared before, they must be equal
317                                 // (if they were not, the recursion would have stopped);
318                                 // search the ifacePair stack for the same pair.
319                                 //
320                                 // This is a quadratic algorithm, but in practice these stacks
321                                 // are extremely short (bounded by the nesting depth of interface
322                                 // type declarations that recur via parameter types, an extremely
323                                 // rare occurrence). An alternative implementation might use a
324                                 // "visited" map, but that is probably less efficient overall.
325                                 q := &ifacePair{x, y, p}
326                                 for p != nil {
327                                         if p.identical(q) {
328                                                 return true // same pair was compared before
329                                         }
330                                         p = p.prev
331                                 }
332                                 if debug {
333                                         assertSortedMethods(a)
334                                         assertSortedMethods(b)
335                                 }
336                                 for i, f := range a {
337                                         g := b[i]
338                                         if f.Id() != g.Id() || !check.identical0(f.typ, g.typ, cmpTags, q) {
339                                                 return false
340                                         }
341                                 }
342                                 return true
343                         }
344                 }
345
346         case *Map:
347                 // Two map types are identical if they have identical key and value types.
348                 if y, ok := y.(*Map); ok {
349                         return check.identical0(x.key, y.key, cmpTags, p) && check.identical0(x.elem, y.elem, cmpTags, p)
350                 }
351
352         case *Chan:
353                 // Two channel types are identical if they have identical value types
354                 // and the same direction.
355                 if y, ok := y.(*Chan); ok {
356                         return x.dir == y.dir && check.identical0(x.elem, y.elem, cmpTags, p)
357                 }
358
359         case *Named:
360                 // Two named types are identical if their type names originate
361                 // in the same type declaration.
362                 if y, ok := y.(*Named); ok {
363                         // TODO(gri) Why is x == y not sufficient? And if it is,
364                         //           we can just return false here because x == y
365                         //           is caught in the very beginning of this function.
366                         return x.obj == y.obj
367                 }
368
369         case *TypeParam:
370                 // nothing to do (x and y being equal is caught in the very beginning of this function)
371
372         // case *instance:
373         //      unreachable since types are expanded
374
375         case *bottom, *top:
376                 // Either both types are theBottom, or both are theTop in which
377                 // case the initial x == y check will have caught them. Otherwise
378                 // they are not identical.
379
380         case nil:
381                 // avoid a crash in case of nil type
382
383         default:
384                 unreachable()
385         }
386
387         return false
388 }
389
390 func (check *Checker) identicalTParams(x, y []*TypeName, cmpTags bool, p *ifacePair) bool {
391         if len(x) != len(y) {
392                 return false
393         }
394         for i, x := range x {
395                 y := y[i]
396                 if !check.identical0(x.typ.(*TypeParam).bound, y.typ.(*TypeParam).bound, cmpTags, p) {
397                         return false
398                 }
399         }
400         return true
401 }
402
403 // Default returns the default "typed" type for an "untyped" type;
404 // it returns the incoming type for all other types. The default type
405 // for untyped nil is untyped nil.
406 //
407 func Default(typ Type) Type {
408         if t, ok := typ.(*Basic); ok {
409                 switch t.kind {
410                 case UntypedBool:
411                         return Typ[Bool]
412                 case UntypedInt:
413                         return Typ[Int]
414                 case UntypedRune:
415                         return universeRune // use 'rune' name
416                 case UntypedFloat:
417                         return Typ[Float64]
418                 case UntypedComplex:
419                         return Typ[Complex128]
420                 case UntypedString:
421                         return Typ[String]
422                 }
423         }
424         return typ
425 }