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