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