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.
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.
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) }
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
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)).
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) }
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) })
53 return isBasic(t, info)
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 {
61 case *Basic, *Named, *TypeParam:
67 // isTyped reports whether t is typed; i.e., not an untyped
68 // constant or boolean. isTyped may be called with types that
69 // are not fully set up.
70 func isTyped(t Type) bool {
71 // isTyped is called with types that are not fully
72 // set up. Must not call under()!
74 return b == nil || b.info&IsUntyped == 0
77 // isUntyped(t) is the same as !isTyped(t).
78 func isUntyped(t Type) bool {
82 // IsInterface reports whether t is an interface type.
83 func IsInterface(t Type) bool {
84 _, ok := under(t).(*Interface)
88 // isNonTypeParamInterface reports whether t is an interface type but not a type parameter.
89 func isNonTypeParamInterface(t Type) bool {
90 return !isTypeParam(t) && IsInterface(t)
93 // isTypeParam reports whether t is a type parameter.
94 func isTypeParam(t Type) bool {
95 _, ok := t.(*TypeParam)
99 // hasEmptyTypeset reports whether t is a type parameter with an empty type set.
100 // The function does not force the computation of the type set and so is safe to
101 // use anywhere, but it may report a false negative if the type set has not been
103 func hasEmptyTypeset(t Type) bool {
104 if tpar, _ := t.(*TypeParam); tpar != nil && tpar.bound != nil {
105 iface, _ := safeUnderlying(tpar.bound).(*Interface)
106 return iface != nil && iface.tset != nil && iface.tset.IsEmpty()
111 // isGeneric reports whether a type is a generic, uninstantiated type
112 // (generic signatures are not included).
113 // TODO(gri) should we include signatures or assert that they are not present?
114 func isGeneric(t Type) bool {
115 // A parameterized type is only generic if it doesn't have an instantiation already.
116 named, _ := t.(*Named)
117 return named != nil && named.obj != nil && named.inst == nil && named.TypeParams().Len() > 0
120 // Comparable reports whether values of type T are comparable.
121 func Comparable(T Type) bool {
122 return comparable(T, true, nil, nil)
125 // If dynamic is set, non-type parameter interfaces are always comparable.
126 // If reportf != nil, it may be used to report why T is not comparable.
127 func comparable(T Type, dynamic bool, seen map[Type]bool, reportf func(string, ...interface{})) bool {
132 seen = make(map[Type]bool)
136 switch t := under(T).(type) {
138 // assume invalid types to be comparable
139 // to avoid follow-up errors
140 return t.kind != UntypedNil
141 case *Pointer, *Chan:
144 for _, f := range t.fields {
145 if !comparable(f.typ, dynamic, seen, nil) {
147 reportf("struct containing %s cannot be compared", f.typ)
154 if !comparable(t.elem, dynamic, seen, nil) {
156 reportf("%s cannot be compared", t)
162 if dynamic && !isTypeParam(T) || t.typeSet().IsComparable(seen) {
166 if t.typeSet().IsEmpty() {
167 reportf("empty type set")
169 reportf("incomparable types in type set")
177 // hasNil reports whether type t includes the nil value.
178 func hasNil(t Type) bool {
179 switch u := under(t).(type) {
181 return u.kind == UnsafePointer
182 case *Slice, *Pointer, *Signature, *Map, *Chan:
185 return !isTypeParam(t) || u.typeSet().underIs(func(u Type) bool {
186 return u != nil && hasNil(u)
192 // An ifacePair is a node in a stack of interface type pairs compared for identity.
193 type ifacePair struct {
198 func (p *ifacePair) identical(q *ifacePair) bool {
199 return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
202 // A comparer is used to compare types.
203 type comparer struct {
204 ignoreTags bool // if set, identical ignores struct tags
205 ignoreInvalids bool // if set, identical treats an invalid type as identical to any type
208 // For changes to this code the corresponding changes should be made to unifier.nify.
209 func (c *comparer) identical(x, y Type, p *ifacePair) bool {
214 if c.ignoreInvalids && (x == Typ[Invalid] || y == Typ[Invalid]) {
218 switch x := x.(type) {
220 // Basic types are singletons except for the rune and byte
221 // aliases, thus we cannot solely rely on the x == y check
222 // above. See also comment in TypeName.IsAlias.
223 if y, ok := y.(*Basic); ok {
224 return x.kind == y.kind
228 // Two array types are identical if they have identical element types
229 // and the same array length.
230 if y, ok := y.(*Array); ok {
231 // If one or both array lengths are unknown (< 0) due to some error,
232 // assume they are the same to avoid spurious follow-on errors.
233 return (x.len < 0 || y.len < 0 || x.len == y.len) && c.identical(x.elem, y.elem, p)
237 // Two slice types are identical if they have identical element types.
238 if y, ok := y.(*Slice); ok {
239 return c.identical(x.elem, y.elem, p)
243 // Two struct types are identical if they have the same sequence of fields,
244 // and if corresponding fields have the same names, and identical types,
245 // and identical tags. Two embedded fields are considered to have the same
246 // name. Lower-case field names from different packages are always different.
247 if y, ok := y.(*Struct); ok {
248 if x.NumFields() == y.NumFields() {
249 for i, f := range x.fields {
251 if f.embedded != g.embedded ||
252 !c.ignoreTags && x.Tag(i) != y.Tag(i) ||
253 !f.sameId(g.pkg, g.name) ||
254 !c.identical(f.typ, g.typ, p) {
263 // Two pointer types are identical if they have identical base types.
264 if y, ok := y.(*Pointer); ok {
265 return c.identical(x.base, y.base, p)
269 // Two tuples types are identical if they have the same number of elements
270 // and corresponding elements have identical types.
271 if y, ok := y.(*Tuple); ok {
272 if x.Len() == y.Len() {
274 for i, v := range x.vars {
276 if !c.identical(v.typ, w.typ, p) {
286 y, _ := y.(*Signature)
291 // Two function types are identical if they have the same number of
292 // parameters and result values, corresponding parameter and result types
293 // are identical, and either both functions are variadic or neither is.
294 // Parameter and result names are not required to match, and type
295 // parameters are considered identical modulo renaming.
297 if x.TypeParams().Len() != y.TypeParams().Len() {
301 // In the case of generic signatures, we will substitute in yparams and
304 yresults := y.results
306 if x.TypeParams().Len() > 0 {
307 // We must ignore type parameter names when comparing x and y. The
308 // easiest way to do this is to substitute x's type parameters for y's.
309 xtparams := x.TypeParams().list()
310 ytparams := y.TypeParams().list()
313 for i := range xtparams {
314 targs = append(targs, x.TypeParams().At(i))
316 smap := makeSubstMap(ytparams, targs)
318 var check *Checker // ok to call subst on a nil *Checker
319 ctxt := NewContext() // need a non-nil Context for the substitution below
321 // Constraints must be pair-wise identical, after substitution.
322 for i, xtparam := range xtparams {
323 ybound := check.subst(nopos, ytparams[i].bound, smap, nil, ctxt)
324 if !c.identical(xtparam.bound, ybound, p) {
329 yparams = check.subst(nopos, y.params, smap, nil, ctxt).(*Tuple)
330 yresults = check.subst(nopos, y.results, smap, nil, ctxt).(*Tuple)
333 return x.variadic == y.variadic &&
334 c.identical(x.params, yparams, p) &&
335 c.identical(x.results, yresults, p)
338 if y, _ := y.(*Union); y != nil {
339 // TODO(rfindley): can this be reached during type checking? If so,
340 // consider passing a type set map.
341 unionSets := make(map[*Union]*_TypeSet)
342 xset := computeUnionTypeSet(nil, unionSets, nopos, x)
343 yset := computeUnionTypeSet(nil, unionSets, nopos, y)
344 return xset.terms.equal(yset.terms)
348 // Two interface types are identical if they describe the same type sets.
349 // With the existing implementation restriction, this simplifies to:
351 // Two interface types are identical if they have the same set of methods with
352 // the same names and identical function types, and if any type restrictions
353 // are the same. Lower-case method names from different packages are always
354 // different. The order of the methods is irrelevant.
355 if y, ok := y.(*Interface); ok {
358 if xset.comparable != yset.comparable {
361 if !xset.terms.equal(yset.terms) {
366 if len(a) == len(b) {
367 // Interface types are the only types where cycles can occur
368 // that are not "terminated" via named types; and such cycles
369 // can only be created via method parameter types that are
370 // anonymous interfaces (directly or indirectly) embedding
371 // the current interface. Example:
373 // type T interface {
377 // If two such (differently named) interfaces are compared,
378 // endless recursion occurs if the cycle is not detected.
380 // If x and y were compared before, they must be equal
381 // (if they were not, the recursion would have stopped);
382 // search the ifacePair stack for the same pair.
384 // This is a quadratic algorithm, but in practice these stacks
385 // are extremely short (bounded by the nesting depth of interface
386 // type declarations that recur via parameter types, an extremely
387 // rare occurrence). An alternative implementation might use a
388 // "visited" map, but that is probably less efficient overall.
389 q := &ifacePair{x, y, p}
392 return true // same pair was compared before
397 assertSortedMethods(a)
398 assertSortedMethods(b)
400 for i, f := range a {
402 if f.Id() != g.Id() || !c.identical(f.typ, g.typ, q) {
411 // Two map types are identical if they have identical key and value types.
412 if y, ok := y.(*Map); ok {
413 return c.identical(x.key, y.key, p) && c.identical(x.elem, y.elem, p)
417 // Two channel types are identical if they have identical value types
418 // and the same direction.
419 if y, ok := y.(*Chan); ok {
420 return x.dir == y.dir && c.identical(x.elem, y.elem, p)
424 // Two named types are identical if their type names originate
425 // in the same type declaration.
426 if y, ok := y.(*Named); ok {
427 xargs := x.TypeArgs().list()
428 yargs := y.TypeArgs().list()
430 if len(xargs) != len(yargs) {
435 // Instances are identical if their original type and type arguments
437 if !Identical(x.Origin(), y.Origin()) {
440 for i, xa := range xargs {
441 if !Identical(xa, yargs[i]) {
448 // TODO(gri) Why is x == y not sufficient? And if it is,
449 // we can just return false here because x == y
450 // is caught in the very beginning of this function.
451 return x.obj == y.obj
455 // nothing to do (x and y being equal is caught in the very beginning of this function)
458 // avoid a crash in case of nil type
467 // identicalInstance reports if two type instantiations are identical.
468 // Instantiations are identical if their origin and type arguments are
470 func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool {
471 if len(xargs) != len(yargs) {
475 for i, xa := range xargs {
476 if !Identical(xa, yargs[i]) {
481 return Identical(xorig, yorig)
484 // Default returns the default "typed" type for an "untyped" type;
485 // it returns the incoming type for all other types. The default type
486 // for untyped nil is untyped nil.
487 func Default(t Type) Type {
488 if t, ok := t.(*Basic); ok {
495 return universeRune // use 'rune' name
499 return Typ[Complex128]