]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/predicates.go
go/types, types2: introduce `isValid` predicate and use throughout
[gostls13.git] / src / cmd / compile / internal / types2 / 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 types2
8
9 // isValid reports whether t is a valid type.
10 func isValid(t Type) bool { return t != Typ[Invalid] }
11
12 // The isX predicates below report whether t is an X.
13 // If t is a type parameter the result is false; i.e.,
14 // these predicates don't look inside a type parameter.
15
16 func isBoolean(t Type) bool        { return isBasic(t, IsBoolean) }
17 func isInteger(t Type) bool        { return isBasic(t, IsInteger) }
18 func isUnsigned(t Type) bool       { return isBasic(t, IsUnsigned) }
19 func isFloat(t Type) bool          { return isBasic(t, IsFloat) }
20 func isComplex(t Type) bool        { return isBasic(t, IsComplex) }
21 func isNumeric(t Type) bool        { return isBasic(t, IsNumeric) }
22 func isString(t Type) bool         { return isBasic(t, IsString) }
23 func isIntegerOrFloat(t Type) bool { return isBasic(t, IsInteger|IsFloat) }
24 func isConstType(t Type) bool      { return isBasic(t, IsConstType) }
25
26 // isBasic reports whether under(t) is a basic type with the specified info.
27 // If t is a type parameter the result is false; i.e.,
28 // isBasic does not look inside a type parameter.
29 func isBasic(t Type, info BasicInfo) bool {
30         u, _ := under(t).(*Basic)
31         return u != nil && u.info&info != 0
32 }
33
34 // The allX predicates below report whether t is an X.
35 // If t is a type parameter the result is true if isX is true
36 // for all specified types of the type parameter's type set.
37 // allX is an optimized version of isX(coreType(t)) (which
38 // is the same as underIs(t, isX)).
39
40 func allBoolean(t Type) bool         { return allBasic(t, IsBoolean) }
41 func allInteger(t Type) bool         { return allBasic(t, IsInteger) }
42 func allUnsigned(t Type) bool        { return allBasic(t, IsUnsigned) }
43 func allNumeric(t Type) bool         { return allBasic(t, IsNumeric) }
44 func allString(t Type) bool          { return allBasic(t, IsString) }
45 func allOrdered(t Type) bool         { return allBasic(t, IsOrdered) }
46 func allNumericOrString(t Type) bool { return allBasic(t, IsNumeric|IsString) }
47
48 // allBasic reports whether under(t) is a basic type with the specified info.
49 // If t is a type parameter, the result is true if isBasic(t, info) is true
50 // for all specific types of the type parameter's type set.
51 // allBasic(t, info) is an optimized version of isBasic(coreType(t), info).
52 func allBasic(t Type, info BasicInfo) bool {
53         if tpar, _ := t.(*TypeParam); tpar != nil {
54                 return tpar.is(func(t *term) bool { return t != nil && isBasic(t.typ, info) })
55         }
56         return isBasic(t, info)
57 }
58
59 // hasName reports whether t has a name. This includes
60 // predeclared types, defined types, and type parameters.
61 // hasName may be called with types that are not fully set up.
62 func hasName(t Type) bool {
63         switch t.(type) {
64         case *Basic, *Named, *TypeParam:
65                 return true
66         }
67         return false
68 }
69
70 // isTypeLit reports whether t is a type literal.
71 // This includes all non-defined types, but also basic types.
72 // isTypeLit may be called with types that are not fully set up.
73 func isTypeLit(t Type) bool {
74         switch t.(type) {
75         case *Named, *TypeParam:
76                 return false
77         }
78         return true
79 }
80
81 // isTyped reports whether t is typed; i.e., not an untyped
82 // constant or boolean. isTyped may be called with types that
83 // are not fully set up.
84 func isTyped(t Type) bool {
85         // isTyped is called with types that are not fully
86         // set up. Must not call under()!
87         b, _ := t.(*Basic)
88         return b == nil || b.info&IsUntyped == 0
89 }
90
91 // isUntyped(t) is the same as !isTyped(t).
92 func isUntyped(t Type) bool {
93         return !isTyped(t)
94 }
95
96 // IsInterface reports whether t is an interface type.
97 func IsInterface(t Type) bool {
98         _, ok := under(t).(*Interface)
99         return ok
100 }
101
102 // isNonTypeParamInterface reports whether t is an interface type but not a type parameter.
103 func isNonTypeParamInterface(t Type) bool {
104         return !isTypeParam(t) && IsInterface(t)
105 }
106
107 // isTypeParam reports whether t is a type parameter.
108 func isTypeParam(t Type) bool {
109         _, ok := t.(*TypeParam)
110         return ok
111 }
112
113 // hasEmptyTypeset reports whether t is a type parameter with an empty type set.
114 // The function does not force the computation of the type set and so is safe to
115 // use anywhere, but it may report a false negative if the type set has not been
116 // computed yet.
117 func hasEmptyTypeset(t Type) bool {
118         if tpar, _ := t.(*TypeParam); tpar != nil && tpar.bound != nil {
119                 iface, _ := safeUnderlying(tpar.bound).(*Interface)
120                 return iface != nil && iface.tset != nil && iface.tset.IsEmpty()
121         }
122         return false
123 }
124
125 // isGeneric reports whether a type is a generic, uninstantiated type
126 // (generic signatures are not included).
127 // TODO(gri) should we include signatures or assert that they are not present?
128 func isGeneric(t Type) bool {
129         // A parameterized type is only generic if it doesn't have an instantiation already.
130         named := asNamed(t)
131         return named != nil && named.obj != nil && named.inst == nil && named.TypeParams().Len() > 0
132 }
133
134 // Comparable reports whether values of type T are comparable.
135 func Comparable(T Type) bool {
136         return comparable(T, true, nil, nil)
137 }
138
139 // If dynamic is set, non-type parameter interfaces are always comparable.
140 // If reportf != nil, it may be used to report why T is not comparable.
141 func comparable(T Type, dynamic bool, seen map[Type]bool, reportf func(string, ...interface{})) bool {
142         if seen[T] {
143                 return true
144         }
145         if seen == nil {
146                 seen = make(map[Type]bool)
147         }
148         seen[T] = true
149
150         switch t := under(T).(type) {
151         case *Basic:
152                 // assume invalid types to be comparable
153                 // to avoid follow-up errors
154                 return t.kind != UntypedNil
155         case *Pointer, *Chan:
156                 return true
157         case *Struct:
158                 for _, f := range t.fields {
159                         if !comparable(f.typ, dynamic, seen, nil) {
160                                 if reportf != nil {
161                                         reportf("struct containing %s cannot be compared", f.typ)
162                                 }
163                                 return false
164                         }
165                 }
166                 return true
167         case *Array:
168                 if !comparable(t.elem, dynamic, seen, nil) {
169                         if reportf != nil {
170                                 reportf("%s cannot be compared", t)
171                         }
172                         return false
173                 }
174                 return true
175         case *Interface:
176                 if dynamic && !isTypeParam(T) || t.typeSet().IsComparable(seen) {
177                         return true
178                 }
179                 if reportf != nil {
180                         if t.typeSet().IsEmpty() {
181                                 reportf("empty type set")
182                         } else {
183                                 reportf("incomparable types in type set")
184                         }
185                 }
186                 // fallthrough
187         }
188         return false
189 }
190
191 // hasNil reports whether type t includes the nil value.
192 func hasNil(t Type) bool {
193         switch u := under(t).(type) {
194         case *Basic:
195                 return u.kind == UnsafePointer
196         case *Slice, *Pointer, *Signature, *Map, *Chan:
197                 return true
198         case *Interface:
199                 return !isTypeParam(t) || u.typeSet().underIs(func(u Type) bool {
200                         return u != nil && hasNil(u)
201                 })
202         }
203         return false
204 }
205
206 // An ifacePair is a node in a stack of interface type pairs compared for identity.
207 type ifacePair struct {
208         x, y *Interface
209         prev *ifacePair
210 }
211
212 func (p *ifacePair) identical(q *ifacePair) bool {
213         return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
214 }
215
216 // A comparer is used to compare types.
217 type comparer struct {
218         ignoreTags     bool // if set, identical ignores struct tags
219         ignoreInvalids bool // if set, identical treats an invalid type as identical to any type
220 }
221
222 // For changes to this code the corresponding changes should be made to unifier.nify.
223 func (c *comparer) identical(x, y Type, p *ifacePair) bool {
224         if x == y {
225                 return true
226         }
227
228         if c.ignoreInvalids && (!isValid(x) || !isValid(y)) {
229                 return true
230         }
231
232         switch x := x.(type) {
233         case *Basic:
234                 // Basic types are singletons except for the rune and byte
235                 // aliases, thus we cannot solely rely on the x == y check
236                 // above. See also comment in TypeName.IsAlias.
237                 if y, ok := y.(*Basic); ok {
238                         return x.kind == y.kind
239                 }
240
241         case *Array:
242                 // Two array types are identical if they have identical element types
243                 // and the same array length.
244                 if y, ok := y.(*Array); ok {
245                         // If one or both array lengths are unknown (< 0) due to some error,
246                         // assume they are the same to avoid spurious follow-on errors.
247                         return (x.len < 0 || y.len < 0 || x.len == y.len) && c.identical(x.elem, y.elem, p)
248                 }
249
250         case *Slice:
251                 // Two slice types are identical if they have identical element types.
252                 if y, ok := y.(*Slice); ok {
253                         return c.identical(x.elem, y.elem, p)
254                 }
255
256         case *Struct:
257                 // Two struct types are identical if they have the same sequence of fields,
258                 // and if corresponding fields have the same names, and identical types,
259                 // and identical tags. Two embedded fields are considered to have the same
260                 // name. Lower-case field names from different packages are always different.
261                 if y, ok := y.(*Struct); ok {
262                         if x.NumFields() == y.NumFields() {
263                                 for i, f := range x.fields {
264                                         g := y.fields[i]
265                                         if f.embedded != g.embedded ||
266                                                 !c.ignoreTags && x.Tag(i) != y.Tag(i) ||
267                                                 !f.sameId(g.pkg, g.name) ||
268                                                 !c.identical(f.typ, g.typ, p) {
269                                                 return false
270                                         }
271                                 }
272                                 return true
273                         }
274                 }
275
276         case *Pointer:
277                 // Two pointer types are identical if they have identical base types.
278                 if y, ok := y.(*Pointer); ok {
279                         return c.identical(x.base, y.base, p)
280                 }
281
282         case *Tuple:
283                 // Two tuples types are identical if they have the same number of elements
284                 // and corresponding elements have identical types.
285                 if y, ok := y.(*Tuple); ok {
286                         if x.Len() == y.Len() {
287                                 if x != nil {
288                                         for i, v := range x.vars {
289                                                 w := y.vars[i]
290                                                 if !c.identical(v.typ, w.typ, p) {
291                                                         return false
292                                                 }
293                                         }
294                                 }
295                                 return true
296                         }
297                 }
298
299         case *Signature:
300                 y, _ := y.(*Signature)
301                 if y == nil {
302                         return false
303                 }
304
305                 // Two function types are identical if they have the same number of
306                 // parameters and result values, corresponding parameter and result types
307                 // are identical, and either both functions are variadic or neither is.
308                 // Parameter and result names are not required to match, and type
309                 // parameters are considered identical modulo renaming.
310
311                 if x.TypeParams().Len() != y.TypeParams().Len() {
312                         return false
313                 }
314
315                 // In the case of generic signatures, we will substitute in yparams and
316                 // yresults.
317                 yparams := y.params
318                 yresults := y.results
319
320                 if x.TypeParams().Len() > 0 {
321                         // We must ignore type parameter names when comparing x and y. The
322                         // easiest way to do this is to substitute x's type parameters for y's.
323                         xtparams := x.TypeParams().list()
324                         ytparams := y.TypeParams().list()
325
326                         var targs []Type
327                         for i := range xtparams {
328                                 targs = append(targs, x.TypeParams().At(i))
329                         }
330                         smap := makeSubstMap(ytparams, targs)
331
332                         var check *Checker   // ok to call subst on a nil *Checker
333                         ctxt := NewContext() // need a non-nil Context for the substitution below
334
335                         // Constraints must be pair-wise identical, after substitution.
336                         for i, xtparam := range xtparams {
337                                 ybound := check.subst(nopos, ytparams[i].bound, smap, nil, ctxt)
338                                 if !c.identical(xtparam.bound, ybound, p) {
339                                         return false
340                                 }
341                         }
342
343                         yparams = check.subst(nopos, y.params, smap, nil, ctxt).(*Tuple)
344                         yresults = check.subst(nopos, y.results, smap, nil, ctxt).(*Tuple)
345                 }
346
347                 return x.variadic == y.variadic &&
348                         c.identical(x.params, yparams, p) &&
349                         c.identical(x.results, yresults, p)
350
351         case *Union:
352                 if y, _ := y.(*Union); y != nil {
353                         // TODO(rfindley): can this be reached during type checking? If so,
354                         // consider passing a type set map.
355                         unionSets := make(map[*Union]*_TypeSet)
356                         xset := computeUnionTypeSet(nil, unionSets, nopos, x)
357                         yset := computeUnionTypeSet(nil, unionSets, nopos, y)
358                         return xset.terms.equal(yset.terms)
359                 }
360
361         case *Interface:
362                 // Two interface types are identical if they describe the same type sets.
363                 // With the existing implementation restriction, this simplifies to:
364                 //
365                 // Two interface types are identical if they have the same set of methods with
366                 // the same names and identical function types, and if any type restrictions
367                 // are the same. Lower-case method names from different packages are always
368                 // different. The order of the methods is irrelevant.
369                 if y, ok := y.(*Interface); ok {
370                         xset := x.typeSet()
371                         yset := y.typeSet()
372                         if xset.comparable != yset.comparable {
373                                 return false
374                         }
375                         if !xset.terms.equal(yset.terms) {
376                                 return false
377                         }
378                         a := xset.methods
379                         b := yset.methods
380                         if len(a) == len(b) {
381                                 // Interface types are the only types where cycles can occur
382                                 // that are not "terminated" via named types; and such cycles
383                                 // can only be created via method parameter types that are
384                                 // anonymous interfaces (directly or indirectly) embedding
385                                 // the current interface. Example:
386                                 //
387                                 //    type T interface {
388                                 //        m() interface{T}
389                                 //    }
390                                 //
391                                 // If two such (differently named) interfaces are compared,
392                                 // endless recursion occurs if the cycle is not detected.
393                                 //
394                                 // If x and y were compared before, they must be equal
395                                 // (if they were not, the recursion would have stopped);
396                                 // search the ifacePair stack for the same pair.
397                                 //
398                                 // This is a quadratic algorithm, but in practice these stacks
399                                 // are extremely short (bounded by the nesting depth of interface
400                                 // type declarations that recur via parameter types, an extremely
401                                 // rare occurrence). An alternative implementation might use a
402                                 // "visited" map, but that is probably less efficient overall.
403                                 q := &ifacePair{x, y, p}
404                                 for p != nil {
405                                         if p.identical(q) {
406                                                 return true // same pair was compared before
407                                         }
408                                         p = p.prev
409                                 }
410                                 if debug {
411                                         assertSortedMethods(a)
412                                         assertSortedMethods(b)
413                                 }
414                                 for i, f := range a {
415                                         g := b[i]
416                                         if f.Id() != g.Id() || !c.identical(f.typ, g.typ, q) {
417                                                 return false
418                                         }
419                                 }
420                                 return true
421                         }
422                 }
423
424         case *Map:
425                 // Two map types are identical if they have identical key and value types.
426                 if y, ok := y.(*Map); ok {
427                         return c.identical(x.key, y.key, p) && c.identical(x.elem, y.elem, p)
428                 }
429
430         case *Chan:
431                 // Two channel types are identical if they have identical value types
432                 // and the same direction.
433                 if y, ok := y.(*Chan); ok {
434                         return x.dir == y.dir && c.identical(x.elem, y.elem, p)
435                 }
436
437         case *Named:
438                 // Two named types are identical if their type names originate
439                 // in the same type declaration; if they are instantiated they
440                 // must have identical type argument lists.
441                 if y := asNamed(y); y != nil {
442                         // check type arguments before origins to match unifier
443                         // (for correct source code we need to do all checks so
444                         // order doesn't matter)
445                         xargs := x.TypeArgs().list()
446                         yargs := y.TypeArgs().list()
447                         if len(xargs) != len(yargs) {
448                                 return false
449                         }
450                         for i, xarg := range xargs {
451                                 if !Identical(xarg, yargs[i]) {
452                                         return false
453                                 }
454                         }
455                         return identicalOrigin(x, y)
456                 }
457
458         case *TypeParam:
459                 // nothing to do (x and y being equal is caught in the very beginning of this function)
460
461         case nil:
462                 // avoid a crash in case of nil type
463
464         default:
465                 unreachable()
466         }
467
468         return false
469 }
470
471 // identicalOrigin reports whether x and y originated in the same declaration.
472 func identicalOrigin(x, y *Named) bool {
473         // TODO(gri) is this correct?
474         return x.Origin().obj == y.Origin().obj
475 }
476
477 // identicalInstance reports if two type instantiations are identical.
478 // Instantiations are identical if their origin and type arguments are
479 // identical.
480 func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool {
481         if len(xargs) != len(yargs) {
482                 return false
483         }
484
485         for i, xa := range xargs {
486                 if !Identical(xa, yargs[i]) {
487                         return false
488                 }
489         }
490
491         return Identical(xorig, yorig)
492 }
493
494 // Default returns the default "typed" type for an "untyped" type;
495 // it returns the incoming type for all other types. The default type
496 // for untyped nil is untyped nil.
497 func Default(t Type) Type {
498         if t, ok := t.(*Basic); ok {
499                 switch t.kind {
500                 case UntypedBool:
501                         return Typ[Bool]
502                 case UntypedInt:
503                         return Typ[Int]
504                 case UntypedRune:
505                         return universeRune // use 'rune' name
506                 case UntypedFloat:
507                         return Typ[Float64]
508                 case UntypedComplex:
509                         return Typ[Complex128]
510                 case UntypedString:
511                         return Typ[String]
512                 }
513         }
514         return t
515 }
516
517 // maxType returns the "largest" type that encompasses both x and y.
518 // If x and y are different untyped numeric types, the result is the type of x or y
519 // that appears later in this list: integer, rune, floating-point, complex.
520 // Otherwise, if x != y, the result is nil.
521 func maxType(x, y Type) Type {
522         // We only care about untyped types (for now), so == is good enough.
523         // TODO(gri) investigate generalizing this function to simplify code elsewhere
524         if x == y {
525                 return x
526         }
527         if isUntyped(x) && isUntyped(y) && isNumeric(x) && isNumeric(y) {
528                 // untyped types are basic types
529                 if x.(*Basic).kind > y.(*Basic).kind {
530                         return x
531                 }
532                 return y
533         }
534         return nil
535 }