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