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