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