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(hasNil)
157 // An ifacePair is a node in a stack of interface type pairs compared for identity.
158 type ifacePair struct {
163 func (p *ifacePair) identical(q *ifacePair) bool {
164 return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
167 // For changes to this code the corresponding changes should be made to unifier.nify.
168 func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
173 switch x := x.(type) {
175 // Basic types are singletons except for the rune and byte
176 // aliases, thus we cannot solely rely on the x == y check
177 // above. See also comment in TypeName.IsAlias.
178 if y, ok := y.(*Basic); ok {
179 return x.kind == y.kind
183 // Two array types are identical if they have identical element types
184 // and the same array length.
185 if y, ok := y.(*Array); ok {
186 // If one or both array lengths are unknown (< 0) due to some error,
187 // assume they are the same to avoid spurious follow-on errors.
188 return (x.len < 0 || y.len < 0 || x.len == y.len) && identical(x.elem, y.elem, cmpTags, p)
192 // Two slice types are identical if they have identical element types.
193 if y, ok := y.(*Slice); ok {
194 return identical(x.elem, y.elem, cmpTags, p)
198 // Two struct types are identical if they have the same sequence of fields,
199 // and if corresponding fields have the same names, and identical types,
200 // and identical tags. Two embedded fields are considered to have the same
201 // name. Lower-case field names from different packages are always different.
202 if y, ok := y.(*Struct); ok {
203 if x.NumFields() == y.NumFields() {
204 for i, f := range x.fields {
206 if f.embedded != g.embedded ||
207 cmpTags && x.Tag(i) != y.Tag(i) ||
208 !f.sameId(g.pkg, g.name) ||
209 !identical(f.typ, g.typ, cmpTags, p) {
218 // Two pointer types are identical if they have identical base types.
219 if y, ok := y.(*Pointer); ok {
220 return identical(x.base, y.base, cmpTags, p)
224 // Two tuples types are identical if they have the same number of elements
225 // and corresponding elements have identical types.
226 if y, ok := y.(*Tuple); ok {
227 if x.Len() == y.Len() {
229 for i, v := range x.vars {
231 if !identical(v.typ, w.typ, cmpTags, p) {
241 // Two function types are identical if they have the same number of parameters
242 // and result values, corresponding parameter and result types are identical,
243 // and either both functions are variadic or neither is. Parameter and result
244 // names are not required to match.
245 // Generic functions must also have matching type parameter lists, but for the
247 if y, ok := y.(*Signature); ok {
248 return x.variadic == y.variadic &&
249 identicalTParams(x.TypeParams().list(), y.TypeParams().list(), cmpTags, p) &&
250 identical(x.params, y.params, cmpTags, p) &&
251 identical(x.results, y.results, cmpTags, p)
255 if y, _ := y.(*Union); y != nil {
256 xset := computeUnionTypeSet(nil, token.NoPos, x)
257 yset := computeUnionTypeSet(nil, token.NoPos, y)
258 return xset.terms.equal(yset.terms)
262 // Two interface types are identical if they describe the same type sets.
263 // With the existing implementation restriction, this simplifies to:
265 // Two interface types are identical if they have the same set of methods with
266 // the same names and identical function types, and if any type restrictions
267 // are the same. Lower-case method names from different packages are always
268 // different. The order of the methods is irrelevant.
269 if y, ok := y.(*Interface); ok {
272 if !xset.terms.equal(yset.terms) {
277 if len(a) == len(b) {
278 // Interface types are the only types where cycles can occur
279 // that are not "terminated" via named types; and such cycles
280 // can only be created via method parameter types that are
281 // anonymous interfaces (directly or indirectly) embedding
282 // the current interface. Example:
284 // type T interface {
288 // If two such (differently named) interfaces are compared,
289 // endless recursion occurs if the cycle is not detected.
291 // If x and y were compared before, they must be equal
292 // (if they were not, the recursion would have stopped);
293 // search the ifacePair stack for the same pair.
295 // This is a quadratic algorithm, but in practice these stacks
296 // are extremely short (bounded by the nesting depth of interface
297 // type declarations that recur via parameter types, an extremely
298 // rare occurrence). An alternative implementation might use a
299 // "visited" map, but that is probably less efficient overall.
300 q := &ifacePair{x, y, p}
303 return true // same pair was compared before
308 assertSortedMethods(a)
309 assertSortedMethods(b)
311 for i, f := range a {
313 if f.Id() != g.Id() || !identical(f.typ, g.typ, cmpTags, q) {
322 // Two map types are identical if they have identical key and value types.
323 if y, ok := y.(*Map); ok {
324 return identical(x.key, y.key, cmpTags, p) && identical(x.elem, y.elem, cmpTags, p)
328 // Two channel types are identical if they have identical value types
329 // and the same direction.
330 if y, ok := y.(*Chan); ok {
331 return x.dir == y.dir && identical(x.elem, y.elem, cmpTags, p)
335 // Two named types are identical if their type names originate
336 // in the same type declaration.
337 if y, ok := y.(*Named); ok {
338 xargs := x.TypeArgs().list()
339 yargs := y.TypeArgs().list()
341 if len(xargs) != len(yargs) {
346 // Instances are identical if their original type and type arguments
348 if !Identical(x.orig, y.orig) {
351 for i, xa := range xargs {
352 if !Identical(xa, yargs[i]) {
359 // TODO(gri) Why is x == y not sufficient? And if it is,
360 // we can just return false here because x == y
361 // is caught in the very beginning of this function.
362 return x.obj == y.obj
366 // nothing to do (x and y being equal is caught in the very beginning of this function)
369 // avoid a crash in case of nil type
378 // identicalInstance reports if two type instantiations are identical.
379 // Instantiations are identical if their origin and type arguments are
381 func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool {
382 if len(xargs) != len(yargs) {
386 for i, xa := range xargs {
387 if !Identical(xa, yargs[i]) {
392 return Identical(xorig, yorig)
395 func identicalTParams(x, y []*TypeParam, cmpTags bool, p *ifacePair) bool {
396 if len(x) != len(y) {
399 for i, x := range x {
401 if !identical(x.bound, y.bound, cmpTags, p) {
408 // Default returns the default "typed" type for an "untyped" type;
409 // it returns the incoming type for all other types. The default type
410 // for untyped nil is untyped nil.
411 func Default(t Type) Type {
412 if t, ok := t.(*Basic); ok {
419 return universeRune // use 'rune' name
423 return Typ[Complex128]