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