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