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