]> 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 // 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         if tpar, _ := t.(*TypeParam); tpar != nil {
53                 return tpar.is(func(t *term) bool { return t != nil && isBasic(t.typ, info) })
54         }
55         return isBasic(t, info)
56 }
57
58 // hasName reports whether t has a name. This includes
59 // predeclared types, defined types, and type parameters.
60 // hasName may be called with types that are not fully set up.
61 func hasName(t Type) bool {
62         switch t.(type) {
63         case *Basic, *Named, *TypeParam:
64                 return true
65         }
66         return false
67 }
68
69 // isTyped reports whether t is typed; i.e., not an untyped
70 // constant or boolean. isTyped may be called with types that
71 // are not fully set up.
72 func isTyped(t Type) bool {
73         // isTyped is called with types that are not fully
74         // set up. Must not call under()!
75         b, _ := t.(*Basic)
76         return b == nil || b.info&IsUntyped == 0
77 }
78
79 // isUntyped(t) is the same as !isTyped(t).
80 func isUntyped(t Type) bool {
81         return !isTyped(t)
82 }
83
84 // IsInterface reports whether t is an interface type.
85 func IsInterface(t Type) bool {
86         _, ok := under(t).(*Interface)
87         return ok
88 }
89
90 // isTypeParam reports whether t is a type parameter.
91 func isTypeParam(t Type) bool {
92         _, ok := t.(*TypeParam)
93         return ok
94 }
95
96 // isGeneric reports whether a type is a generic, uninstantiated type
97 // (generic signatures are not included).
98 // TODO(gri) should we include signatures or assert that they are not present?
99 func isGeneric(t Type) bool {
100         // A parameterized type is only generic if it doesn't have an instantiation already.
101         named, _ := t.(*Named)
102         return named != nil && named.obj != nil && named.targs == nil && named.TypeParams() != nil
103 }
104
105 // Comparable reports whether values of type T are comparable.
106 func Comparable(T Type) bool {
107         return comparable(T, nil)
108 }
109
110 func comparable(T Type, seen map[Type]bool) bool {
111         if seen[T] {
112                 return true
113         }
114         if seen == nil {
115                 seen = make(map[Type]bool)
116         }
117         seen[T] = true
118
119         switch t := under(T).(type) {
120         case *Basic:
121                 // assume invalid types to be comparable
122                 // to avoid follow-up errors
123                 return t.kind != UntypedNil
124         case *Pointer, *Chan:
125                 return true
126         case *Struct:
127                 for _, f := range t.fields {
128                         if !comparable(f.typ, seen) {
129                                 return false
130                         }
131                 }
132                 return true
133         case *Array:
134                 return comparable(t.elem, seen)
135         case *Interface:
136                 return !isTypeParam(T) || t.typeSet().IsComparable(seen)
137         }
138         return false
139 }
140
141 // hasNil reports whether type t includes the nil value.
142 func hasNil(t Type) bool {
143         switch u := under(t).(type) {
144         case *Basic:
145                 return u.kind == UnsafePointer
146         case *Slice, *Pointer, *Signature, *Map, *Chan:
147                 return true
148         case *Interface:
149                 return !isTypeParam(t) || u.typeSet().underIs(func(u Type) bool {
150                         return u != nil && hasNil(u)
151                 })
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                 y, _ := y.(*Signature)
241                 if y == nil {
242                         return false
243                 }
244
245                 // Two function types are identical if they have the same number of
246                 // parameters and result values, corresponding parameter and result types
247                 // are identical, and either both functions are variadic or neither is.
248                 // Parameter and result names are not required to match, and type
249                 // parameters are considered identical modulo renaming.
250
251                 if x.TypeParams().Len() != y.TypeParams().Len() {
252                         return false
253                 }
254
255                 // In the case of generic signatures, we will substitute in yparams and
256                 // yresults.
257                 yparams := y.params
258                 yresults := y.results
259
260                 if x.TypeParams().Len() > 0 {
261                         // We must ignore type parameter names when comparing x and y. The
262                         // easiest way to do this is to substitute x's type parameters for y's.
263                         xtparams := x.TypeParams().list()
264                         ytparams := y.TypeParams().list()
265
266                         var targs []Type
267                         for i := range xtparams {
268                                 targs = append(targs, x.TypeParams().At(i))
269                         }
270                         smap := makeSubstMap(ytparams, targs)
271
272                         var check *Checker // ok to call subst on a nil *Checker
273
274                         // Constraints must be pair-wise identical, after substitution.
275                         for i, xtparam := range xtparams {
276                                 ybound := check.subst(token.NoPos, ytparams[i].bound, smap, nil)
277                                 if !identical(xtparam.bound, ybound, cmpTags, p) {
278                                         return false
279                                 }
280                         }
281
282                         yparams = check.subst(token.NoPos, y.params, smap, nil).(*Tuple)
283                         yresults = check.subst(token.NoPos, y.results, smap, nil).(*Tuple)
284                 }
285
286                 return x.variadic == y.variadic &&
287                         identical(x.params, yparams, cmpTags, p) &&
288                         identical(x.results, yresults, cmpTags, p)
289
290         case *Union:
291                 if y, _ := y.(*Union); y != nil {
292                         // TODO(rfindley): can this be reached during type checking? If so,
293                         // consider passing a type set map.
294                         unionSets := make(map[*Union]*_TypeSet)
295                         xset := computeUnionTypeSet(nil, unionSets, token.NoPos, x)
296                         yset := computeUnionTypeSet(nil, unionSets, token.NoPos, y)
297                         return xset.terms.equal(yset.terms)
298                 }
299
300         case *Interface:
301                 // Two interface types are identical if they describe the same type sets.
302                 // With the existing implementation restriction, this simplifies to:
303                 //
304                 // Two interface types are identical if they have the same set of methods with
305                 // the same names and identical function types, and if any type restrictions
306                 // are the same. Lower-case method names from different packages are always
307                 // different. The order of the methods is irrelevant.
308                 if y, ok := y.(*Interface); ok {
309                         xset := x.typeSet()
310                         yset := y.typeSet()
311                         if xset.comparable != yset.comparable {
312                                 return false
313                         }
314                         if !xset.terms.equal(yset.terms) {
315                                 return false
316                         }
317                         a := xset.methods
318                         b := yset.methods
319                         if len(a) == len(b) {
320                                 // Interface types are the only types where cycles can occur
321                                 // that are not "terminated" via named types; and such cycles
322                                 // can only be created via method parameter types that are
323                                 // anonymous interfaces (directly or indirectly) embedding
324                                 // the current interface. Example:
325                                 //
326                                 //    type T interface {
327                                 //        m() interface{T}
328                                 //    }
329                                 //
330                                 // If two such (differently named) interfaces are compared,
331                                 // endless recursion occurs if the cycle is not detected.
332                                 //
333                                 // If x and y were compared before, they must be equal
334                                 // (if they were not, the recursion would have stopped);
335                                 // search the ifacePair stack for the same pair.
336                                 //
337                                 // This is a quadratic algorithm, but in practice these stacks
338                                 // are extremely short (bounded by the nesting depth of interface
339                                 // type declarations that recur via parameter types, an extremely
340                                 // rare occurrence). An alternative implementation might use a
341                                 // "visited" map, but that is probably less efficient overall.
342                                 q := &ifacePair{x, y, p}
343                                 for p != nil {
344                                         if p.identical(q) {
345                                                 return true // same pair was compared before
346                                         }
347                                         p = p.prev
348                                 }
349                                 if debug {
350                                         assertSortedMethods(a)
351                                         assertSortedMethods(b)
352                                 }
353                                 for i, f := range a {
354                                         g := b[i]
355                                         if f.Id() != g.Id() || !identical(f.typ, g.typ, cmpTags, q) {
356                                                 return false
357                                         }
358                                 }
359                                 return true
360                         }
361                 }
362
363         case *Map:
364                 // Two map types are identical if they have identical key and value types.
365                 if y, ok := y.(*Map); ok {
366                         return identical(x.key, y.key, cmpTags, p) && identical(x.elem, y.elem, cmpTags, p)
367                 }
368
369         case *Chan:
370                 // Two channel types are identical if they have identical value types
371                 // and the same direction.
372                 if y, ok := y.(*Chan); ok {
373                         return x.dir == y.dir && identical(x.elem, y.elem, cmpTags, p)
374                 }
375
376         case *Named:
377                 // Two named types are identical if their type names originate
378                 // in the same type declaration.
379                 if y, ok := y.(*Named); ok {
380                         xargs := x.TypeArgs().list()
381                         yargs := y.TypeArgs().list()
382
383                         if len(xargs) != len(yargs) {
384                                 return false
385                         }
386
387                         if len(xargs) > 0 {
388                                 // Instances are identical if their original type and type arguments
389                                 // are identical.
390                                 if !Identical(x.orig, y.orig) {
391                                         return false
392                                 }
393                                 for i, xa := range xargs {
394                                         if !Identical(xa, yargs[i]) {
395                                                 return false
396                                         }
397                                 }
398                                 return true
399                         }
400
401                         // TODO(gri) Why is x == y not sufficient? And if it is,
402                         //           we can just return false here because x == y
403                         //           is caught in the very beginning of this function.
404                         return x.obj == y.obj
405                 }
406
407         case *TypeParam:
408                 // nothing to do (x and y being equal is caught in the very beginning of this function)
409
410         case nil:
411                 // avoid a crash in case of nil type
412
413         default:
414                 unreachable()
415         }
416
417         return false
418 }
419
420 // identicalInstance reports if two type instantiations are identical.
421 // Instantiations are identical if their origin and type arguments are
422 // identical.
423 func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool {
424         if len(xargs) != len(yargs) {
425                 return false
426         }
427
428         for i, xa := range xargs {
429                 if !Identical(xa, yargs[i]) {
430                         return false
431                 }
432         }
433
434         return Identical(xorig, yorig)
435 }
436
437 // Default returns the default "typed" type for an "untyped" type;
438 // it returns the incoming type for all other types. The default type
439 // for untyped nil is untyped nil.
440 func Default(t Type) Type {
441         if t, ok := t.(*Basic); ok {
442                 switch t.kind {
443                 case UntypedBool:
444                         return Typ[Bool]
445                 case UntypedInt:
446                         return Typ[Int]
447                 case UntypedRune:
448                         return universeRune // use 'rune' name
449                 case UntypedFloat:
450                         return Typ[Float64]
451                 case UntypedComplex:
452                         return Typ[Complex128]
453                 case UntypedString:
454                         return Typ[String]
455                 }
456         }
457         return t
458 }