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