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