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 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)
110 func comparable(T Type, seen map[Type]bool) bool {
115 seen = make(map[Type]bool)
119 switch t := under(T).(type) {
121 // assume invalid types to be comparable
122 // to avoid follow-up errors
123 return t.kind != UntypedNil
124 case *Pointer, *Chan:
127 for _, f := range t.fields {
128 if !comparable(f.typ, seen) {
134 return comparable(t.elem, seen)
136 return !isTypeParam(T) || t.IsComparable()
141 // hasNil reports whether type t includes the nil value.
142 func hasNil(t Type) bool {
143 switch u := under(t).(type) {
145 return u.kind == UnsafePointer
146 case *Slice, *Pointer, *Signature, *Map, *Chan:
149 return !isTypeParam(t) || u.typeSet().underIs(func(u Type) bool {
150 return u != nil && hasNil(u)
156 // An ifacePair is a node in a stack of interface type pairs compared for identity.
157 type ifacePair struct {
162 func (p *ifacePair) identical(q *ifacePair) bool {
163 return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
166 // For changes to this code the corresponding changes should be made to unifier.nify.
167 func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
172 switch x := x.(type) {
174 // Basic types are singletons except for the rune and byte
175 // aliases, thus we cannot solely rely on the x == y check
176 // above. See also comment in TypeName.IsAlias.
177 if y, ok := y.(*Basic); ok {
178 return x.kind == y.kind
182 // Two array types are identical if they have identical element types
183 // and the same array length.
184 if y, ok := y.(*Array); ok {
185 // If one or both array lengths are unknown (< 0) due to some error,
186 // assume they are the same to avoid spurious follow-on errors.
187 return (x.len < 0 || y.len < 0 || x.len == y.len) && identical(x.elem, y.elem, cmpTags, p)
191 // Two slice types are identical if they have identical element types.
192 if y, ok := y.(*Slice); ok {
193 return identical(x.elem, y.elem, cmpTags, p)
197 // Two struct types are identical if they have the same sequence of fields,
198 // and if corresponding fields have the same names, and identical types,
199 // and identical tags. Two embedded fields are considered to have the same
200 // name. Lower-case field names from different packages are always different.
201 if y, ok := y.(*Struct); ok {
202 if x.NumFields() == y.NumFields() {
203 for i, f := range x.fields {
205 if f.embedded != g.embedded ||
206 cmpTags && x.Tag(i) != y.Tag(i) ||
207 !f.sameId(g.pkg, g.name) ||
208 !identical(f.typ, g.typ, cmpTags, p) {
217 // Two pointer types are identical if they have identical base types.
218 if y, ok := y.(*Pointer); ok {
219 return identical(x.base, y.base, cmpTags, p)
223 // Two tuples types are identical if they have the same number of elements
224 // and corresponding elements have identical types.
225 if y, ok := y.(*Tuple); ok {
226 if x.Len() == y.Len() {
228 for i, v := range x.vars {
230 if !identical(v.typ, w.typ, cmpTags, p) {
240 y, _ := y.(*Signature)
245 // Two function types are identical if they have the same number of
246 // parameters and result values, corresponding parameter and result types
247 // are identical, and either both functions are variadic or neither is.
248 // Parameter and result names are not required to match, and type
249 // parameters are considered identical modulo renaming.
251 if x.TypeParams().Len() != y.TypeParams().Len() {
255 // In the case of generic signatures, we will substitute in yparams and
258 yresults := y.results
260 if x.TypeParams().Len() > 0 {
261 // We must ignore type parameter names when comparing x and y. The
262 // easiest way to do this is to substitute x's type parameters for y's.
263 xtparams := x.TypeParams().list()
264 ytparams := y.TypeParams().list()
267 for i := range xtparams {
268 targs = append(targs, x.TypeParams().At(i))
270 smap := makeSubstMap(ytparams, targs)
272 var check *Checker // ok to call subst on a nil *Checker
274 // Constraints must be pair-wise identical, after substitution.
275 for i, xtparam := range xtparams {
276 ybound := check.subst(token.NoPos, ytparams[i].bound, smap, nil)
277 if !identical(xtparam.bound, ybound, cmpTags, p) {
282 yparams = check.subst(token.NoPos, y.params, smap, nil).(*Tuple)
283 yresults = check.subst(token.NoPos, y.results, smap, nil).(*Tuple)
286 return x.variadic == y.variadic &&
287 identical(x.params, yparams, cmpTags, p) &&
288 identical(x.results, yresults, cmpTags, p)
291 if y, _ := y.(*Union); y != nil {
292 // TODO(rfindley): can this be reached during type checking? If so,
293 // consider passing a type set map.
294 unionSets := make(map[*Union]*_TypeSet)
295 xset := computeUnionTypeSet(nil, unionSets, token.NoPos, x)
296 yset := computeUnionTypeSet(nil, unionSets, token.NoPos, y)
297 return xset.terms.equal(yset.terms)
301 // Two interface types are identical if they describe the same type sets.
302 // With the existing implementation restriction, this simplifies to:
304 // Two interface types are identical if they have the same set of methods with
305 // the same names and identical function types, and if any type restrictions
306 // are the same. Lower-case method names from different packages are always
307 // different. The order of the methods is irrelevant.
308 if y, ok := y.(*Interface); ok {
311 if !xset.terms.equal(yset.terms) {
316 if len(a) == len(b) {
317 // Interface types are the only types where cycles can occur
318 // that are not "terminated" via named types; and such cycles
319 // can only be created via method parameter types that are
320 // anonymous interfaces (directly or indirectly) embedding
321 // the current interface. Example:
323 // type T interface {
327 // If two such (differently named) interfaces are compared,
328 // endless recursion occurs if the cycle is not detected.
330 // If x and y were compared before, they must be equal
331 // (if they were not, the recursion would have stopped);
332 // search the ifacePair stack for the same pair.
334 // This is a quadratic algorithm, but in practice these stacks
335 // are extremely short (bounded by the nesting depth of interface
336 // type declarations that recur via parameter types, an extremely
337 // rare occurrence). An alternative implementation might use a
338 // "visited" map, but that is probably less efficient overall.
339 q := &ifacePair{x, y, p}
342 return true // same pair was compared before
347 assertSortedMethods(a)
348 assertSortedMethods(b)
350 for i, f := range a {
352 if f.Id() != g.Id() || !identical(f.typ, g.typ, cmpTags, q) {
361 // Two map types are identical if they have identical key and value types.
362 if y, ok := y.(*Map); ok {
363 return identical(x.key, y.key, cmpTags, p) && identical(x.elem, y.elem, cmpTags, p)
367 // Two channel types are identical if they have identical value types
368 // and the same direction.
369 if y, ok := y.(*Chan); ok {
370 return x.dir == y.dir && identical(x.elem, y.elem, cmpTags, p)
374 // Two named types are identical if their type names originate
375 // in the same type declaration.
376 if y, ok := y.(*Named); ok {
377 xargs := x.TypeArgs().list()
378 yargs := y.TypeArgs().list()
380 if len(xargs) != len(yargs) {
385 // Instances are identical if their original type and type arguments
387 if !Identical(x.orig, y.orig) {
390 for i, xa := range xargs {
391 if !Identical(xa, yargs[i]) {
398 // TODO(gri) Why is x == y not sufficient? And if it is,
399 // we can just return false here because x == y
400 // is caught in the very beginning of this function.
401 return x.obj == y.obj
405 // nothing to do (x and y being equal is caught in the very beginning of this function)
408 // avoid a crash in case of nil type
417 // identicalInstance reports if two type instantiations are identical.
418 // Instantiations are identical if their origin and type arguments are
420 func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool {
421 if len(xargs) != len(yargs) {
425 for i, xa := range xargs {
426 if !Identical(xa, yargs[i]) {
431 return Identical(xorig, yorig)
434 // Default returns the default "typed" type for an "untyped" type;
435 // it returns the incoming type for all other types. The default type
436 // for untyped nil is untyped nil.
437 func Default(t Type) Type {
438 if t, ok := t.(*Basic); ok {
445 return universeRune // use 'rune' name
449 return Typ[Complex128]