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.
5 // This file implements commonly used type predicates.
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.
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) }
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
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)).
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) }
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) })
55 return isBasic(t, info)
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 {
63 case *Basic, *Named, *TypeParam:
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()!
76 return b == nil || b.info&IsUntyped == 0
79 // isUntyped(t) is the same as !isTyped(t).
80 func isUntyped(t Type) bool {
84 // IsInterface reports whether t is an interface type.
85 func IsInterface(t Type) bool {
86 _, ok := under(t).(*Interface)
90 // isTypeParam reports whether t is a type parameter.
91 func isTypeParam(t Type) bool {
92 _, ok := t.(*TypeParam)
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
105 // Comparable reports whether values of type T are comparable.
106 func Comparable(T Type) bool {
107 return comparable(T, nil, nil)
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 {
116 seen = make(map[Type]bool)
120 switch t := under(T).(type) {
122 // assume invalid types to be comparable
123 // to avoid follow-up errors
124 return t.kind != UntypedNil
125 case *Pointer, *Chan:
128 for _, f := range t.fields {
129 if !comparable(f.typ, seen, nil) {
131 reportf("struct containing %s cannot be compared", f.typ)
138 if !comparable(t.elem, seen, nil) {
140 reportf("%s cannot be compared", t)
146 return !isTypeParam(T) || t.typeSet().IsComparable(seen)
151 // hasNil reports whether type t includes the nil value.
152 func hasNil(t Type) bool {
153 switch u := under(t).(type) {
155 return u.kind == UnsafePointer
156 case *Slice, *Pointer, *Signature, *Map, *Chan:
159 return !isTypeParam(t) || u.typeSet().underIs(func(u Type) bool {
160 return u != nil && hasNil(u)
166 // An ifacePair is a node in a stack of interface type pairs compared for identity.
167 type ifacePair struct {
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
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 {
182 switch x := x.(type) {
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
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)
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)
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 {
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) {
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)
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() {
238 for i, v := range x.vars {
240 if !identical(v.typ, w.typ, cmpTags, p) {
250 y, _ := y.(*Signature)
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.
261 if x.TypeParams().Len() != y.TypeParams().Len() {
265 // In the case of generic signatures, we will substitute in yparams and
268 yresults := y.results
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()
277 for i := range xtparams {
278 targs = append(targs, x.TypeParams().At(i))
280 smap := makeSubstMap(ytparams, targs)
282 var check *Checker // ok to call subst on a nil *Checker
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) {
292 yparams = check.subst(token.NoPos, y.params, smap, nil).(*Tuple)
293 yresults = check.subst(token.NoPos, y.results, smap, nil).(*Tuple)
296 return x.variadic == y.variadic &&
297 identical(x.params, yparams, cmpTags, p) &&
298 identical(x.results, yresults, cmpTags, p)
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)
311 // Two interface types are identical if they describe the same type sets.
312 // With the existing implementation restriction, this simplifies to:
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 {
321 if xset.comparable != yset.comparable {
324 if !xset.terms.equal(yset.terms) {
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:
336 // type T interface {
340 // If two such (differently named) interfaces are compared,
341 // endless recursion occurs if the cycle is not detected.
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.
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}
355 return true // same pair was compared before
360 assertSortedMethods(a)
361 assertSortedMethods(b)
363 for i, f := range a {
365 if f.Id() != g.Id() || !identical(f.typ, g.typ, cmpTags, q) {
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)
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)
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()
393 if len(xargs) != len(yargs) {
398 // Instances are identical if their original type and type arguments
400 if !Identical(x.orig, y.orig) {
403 for i, xa := range xargs {
404 if !Identical(xa, yargs[i]) {
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
418 // nothing to do (x and y being equal is caught in the very beginning of this function)
421 // avoid a crash in case of nil type
430 // identicalInstance reports if two type instantiations are identical.
431 // Instantiations are identical if their origin and type arguments are
433 func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool {
434 if len(xargs) != len(yargs) {
438 for i, xa := range xargs {
439 if !Identical(xa, yargs[i]) {
444 return Identical(xorig, yorig)
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 {
458 return universeRune // use 'rune' name
462 return Typ[Complex128]