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(structuralType(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(structuralType(t), info).
51 func allBasic(t Type, info BasicInfo) bool {
52 switch u := under(t).(type) {
54 return u.info&info != 0
56 return u.is(func(t *term) bool { return t != nil && isBasic(t.typ, info) })
61 // hasName reports whether t has a name. This includes
62 // predeclared types, defined types, and type parameters.
63 // hasName may be called with types that are not fully set up.
64 func hasName(t Type) bool {
66 case *Basic, *Named, *TypeParam:
72 // isTyped reports whether t is typed; i.e., not an untyped
73 // constant or boolean. isTyped may be called with types that
74 // are not fully set up.
75 func isTyped(t Type) bool {
76 // isTyped is called with types that are not fully
77 // set up. Must not call under()!
79 return b == nil || b.info&IsUntyped == 0
82 // isUntyped(t) is the same as !isTyped(t).
83 func isUntyped(t Type) bool {
87 // IsInterface reports whether t is an interface type.
88 func IsInterface(t Type) bool {
89 _, ok := under(t).(*Interface)
93 // isTypeParam reports whether t is a type parameter.
94 func isTypeParam(t Type) bool {
95 _, ok := t.(*TypeParam)
99 // isGeneric reports whether a type is a generic, uninstantiated type
100 // (generic signatures are not included).
101 // TODO(gri) should we include signatures or assert that they are not present?
102 func isGeneric(t Type) bool {
103 // A parameterized type is only generic if it doesn't have an instantiation already.
104 named, _ := t.(*Named)
105 return named != nil && named.obj != nil && named.targs == nil && named.TypeParams() != nil
108 // Comparable reports whether values of type T are comparable.
109 func Comparable(T Type) bool {
110 return comparable(T, nil)
113 func comparable(T Type, seen map[Type]bool) bool {
118 seen = make(map[Type]bool)
122 switch t := under(T).(type) {
124 // assume invalid types to be comparable
125 // to avoid follow-up errors
126 return t.kind != UntypedNil
127 case *Pointer, *Interface, *Chan:
130 for _, f := range t.fields {
131 if !comparable(f.typ, seen) {
137 return comparable(t.elem, seen)
139 return t.iface().IsComparable()
144 // hasNil reports whether type t includes the nil value.
145 func hasNil(t Type) bool {
146 switch u := under(t).(type) {
148 return u.kind == UnsafePointer
149 case *Slice, *Pointer, *Signature, *Interface, *Map, *Chan:
152 return u.underIs(func(u Type) bool {
153 return u != nil && hasNil(u)
159 // An ifacePair is a node in a stack of interface type pairs compared for identity.
160 type ifacePair struct {
165 func (p *ifacePair) identical(q *ifacePair) bool {
166 return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
169 // For changes to this code the corresponding changes should be made to unifier.nify.
170 func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
175 switch x := x.(type) {
177 // Basic types are singletons except for the rune and byte
178 // aliases, thus we cannot solely rely on the x == y check
179 // above. See also comment in TypeName.IsAlias.
180 if y, ok := y.(*Basic); ok {
181 return x.kind == y.kind
185 // Two array types are identical if they have identical element types
186 // and the same array length.
187 if y, ok := y.(*Array); ok {
188 // If one or both array lengths are unknown (< 0) due to some error,
189 // assume they are the same to avoid spurious follow-on errors.
190 return (x.len < 0 || y.len < 0 || x.len == y.len) && identical(x.elem, y.elem, cmpTags, p)
194 // Two slice types are identical if they have identical element types.
195 if y, ok := y.(*Slice); ok {
196 return identical(x.elem, y.elem, cmpTags, p)
200 // Two struct types are identical if they have the same sequence of fields,
201 // and if corresponding fields have the same names, and identical types,
202 // and identical tags. Two embedded fields are considered to have the same
203 // name. Lower-case field names from different packages are always different.
204 if y, ok := y.(*Struct); ok {
205 if x.NumFields() == y.NumFields() {
206 for i, f := range x.fields {
208 if f.embedded != g.embedded ||
209 cmpTags && x.Tag(i) != y.Tag(i) ||
210 !f.sameId(g.pkg, g.name) ||
211 !identical(f.typ, g.typ, cmpTags, p) {
220 // Two pointer types are identical if they have identical base types.
221 if y, ok := y.(*Pointer); ok {
222 return identical(x.base, y.base, cmpTags, p)
226 // Two tuples types are identical if they have the same number of elements
227 // and corresponding elements have identical types.
228 if y, ok := y.(*Tuple); ok {
229 if x.Len() == y.Len() {
231 for i, v := range x.vars {
233 if !identical(v.typ, w.typ, cmpTags, p) {
243 // Two function types are identical if they have the same number of parameters
244 // and result values, corresponding parameter and result types are identical,
245 // and either both functions are variadic or neither is. Parameter and result
246 // names are not required to match.
247 // Generic functions must also have matching type parameter lists, but for the
249 if y, ok := y.(*Signature); ok {
250 return x.variadic == y.variadic &&
251 identicalTParams(x.TypeParams().list(), y.TypeParams().list(), cmpTags, p) &&
252 identical(x.params, y.params, cmpTags, p) &&
253 identical(x.results, y.results, cmpTags, p)
257 if y, _ := y.(*Union); y != nil {
258 xset := computeUnionTypeSet(nil, token.NoPos, x)
259 yset := computeUnionTypeSet(nil, token.NoPos, y)
260 return xset.terms.equal(yset.terms)
264 // Two interface types are identical if they describe the same type sets.
265 // With the existing implementation restriction, this simplifies to:
267 // Two interface types are identical if they have the same set of methods with
268 // the same names and identical function types, and if any type restrictions
269 // are the same. Lower-case method names from different packages are always
270 // different. The order of the methods is irrelevant.
271 if y, ok := y.(*Interface); ok {
274 if !xset.terms.equal(yset.terms) {
279 if len(a) == len(b) {
280 // Interface types are the only types where cycles can occur
281 // that are not "terminated" via named types; and such cycles
282 // can only be created via method parameter types that are
283 // anonymous interfaces (directly or indirectly) embedding
284 // the current interface. Example:
286 // type T interface {
290 // If two such (differently named) interfaces are compared,
291 // endless recursion occurs if the cycle is not detected.
293 // If x and y were compared before, they must be equal
294 // (if they were not, the recursion would have stopped);
295 // search the ifacePair stack for the same pair.
297 // This is a quadratic algorithm, but in practice these stacks
298 // are extremely short (bounded by the nesting depth of interface
299 // type declarations that recur via parameter types, an extremely
300 // rare occurrence). An alternative implementation might use a
301 // "visited" map, but that is probably less efficient overall.
302 q := &ifacePair{x, y, p}
305 return true // same pair was compared before
310 assertSortedMethods(a)
311 assertSortedMethods(b)
313 for i, f := range a {
315 if f.Id() != g.Id() || !identical(f.typ, g.typ, cmpTags, q) {
324 // Two map types are identical if they have identical key and value types.
325 if y, ok := y.(*Map); ok {
326 return identical(x.key, y.key, cmpTags, p) && identical(x.elem, y.elem, cmpTags, p)
330 // Two channel types are identical if they have identical value types
331 // and the same direction.
332 if y, ok := y.(*Chan); ok {
333 return x.dir == y.dir && identical(x.elem, y.elem, cmpTags, p)
337 // Two named types are identical if their type names originate
338 // in the same type declaration.
339 if y, ok := y.(*Named); ok {
340 xargs := x.TypeArgs().list()
341 yargs := y.TypeArgs().list()
343 if len(xargs) != len(yargs) {
348 // Instances are identical if their original type and type arguments
350 if !Identical(x.orig, y.orig) {
353 for i, xa := range xargs {
354 if !Identical(xa, yargs[i]) {
361 // TODO(gri) Why is x == y not sufficient? And if it is,
362 // we can just return false here because x == y
363 // is caught in the very beginning of this function.
364 return x.obj == y.obj
368 // nothing to do (x and y being equal is caught in the very beginning of this function)
371 // avoid a crash in case of nil type
380 // identicalInstance reports if two type instantiations are identical.
381 // Instantiations are identical if their origin and type arguments are
383 func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool {
384 if len(xargs) != len(yargs) {
388 for i, xa := range xargs {
389 if !Identical(xa, yargs[i]) {
394 return Identical(xorig, yorig)
397 func identicalTParams(x, y []*TypeParam, cmpTags bool, p *ifacePair) bool {
398 if len(x) != len(y) {
401 for i, x := range x {
403 if !identical(x.bound, y.bound, cmpTags, p) {
410 // Default returns the default "typed" type for an "untyped" type;
411 // it returns the incoming type for all other types. The default type
412 // for untyped nil is untyped nil.
413 func Default(t Type) Type {
414 if t, ok := t.(*Basic); ok {
421 return universeRune // use 'rune' name
425 return Typ[Complex128]