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