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 // isNonTypeParamInterface reports whether t is an interface type but not a type parameter.
91 func isNonTypeParamInterface(t Type) bool {
92 return !isTypeParam(t) && IsInterface(t)
95 // isTypeParam reports whether t is a type parameter.
96 func isTypeParam(t Type) bool {
97 _, ok := t.(*TypeParam)
101 // isGeneric reports whether a type is a generic, uninstantiated type
102 // (generic signatures are not included).
103 // TODO(gri) should we include signatures or assert that they are not present?
104 func isGeneric(t Type) bool {
105 // A parameterized type is only generic if it doesn't have an instantiation already.
106 named, _ := t.(*Named)
107 return named != nil && named.obj != nil && named.targs == nil && named.TypeParams() != nil
110 // Comparable reports whether values of type T are comparable.
111 func Comparable(T Type) bool {
112 return comparable(T, true, nil, nil)
115 // If dynamic is set, non-type parameter interfaces are always comparable.
116 // If reportf != nil, it may be used to report why T is not comparable.
117 func comparable(T Type, dynamic bool, seen map[Type]bool, reportf func(string, ...interface{})) bool {
122 seen = make(map[Type]bool)
126 switch t := under(T).(type) {
128 // assume invalid types to be comparable
129 // to avoid follow-up errors
130 return t.kind != UntypedNil
131 case *Pointer, *Chan:
134 for _, f := range t.fields {
135 if !comparable(f.typ, dynamic, seen, nil) {
137 reportf("struct containing %s cannot be compared", f.typ)
144 if !comparable(t.elem, dynamic, seen, nil) {
146 reportf("%s cannot be compared", t)
152 return dynamic && !isTypeParam(T) || t.typeSet().IsComparable(seen)
157 // hasNil reports whether type t includes the nil value.
158 func hasNil(t Type) bool {
159 switch u := under(t).(type) {
161 return u.kind == UnsafePointer
162 case *Slice, *Pointer, *Signature, *Map, *Chan:
165 return !isTypeParam(t) || u.typeSet().underIs(func(u Type) bool {
166 return u != nil && hasNil(u)
172 // An ifacePair is a node in a stack of interface type pairs compared for identity.
173 type ifacePair struct {
178 func (p *ifacePair) identical(q *ifacePair) bool {
179 return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
182 // For changes to this code the corresponding changes should be made to unifier.nify.
183 func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
188 switch x := x.(type) {
190 // Basic types are singletons except for the rune and byte
191 // aliases, thus we cannot solely rely on the x == y check
192 // above. See also comment in TypeName.IsAlias.
193 if y, ok := y.(*Basic); ok {
194 return x.kind == y.kind
198 // Two array types are identical if they have identical element types
199 // and the same array length.
200 if y, ok := y.(*Array); ok {
201 // If one or both array lengths are unknown (< 0) due to some error,
202 // assume they are the same to avoid spurious follow-on errors.
203 return (x.len < 0 || y.len < 0 || x.len == y.len) && identical(x.elem, y.elem, cmpTags, p)
207 // Two slice types are identical if they have identical element types.
208 if y, ok := y.(*Slice); ok {
209 return identical(x.elem, y.elem, cmpTags, p)
213 // Two struct types are identical if they have the same sequence of fields,
214 // and if corresponding fields have the same names, and identical types,
215 // and identical tags. Two embedded fields are considered to have the same
216 // name. Lower-case field names from different packages are always different.
217 if y, ok := y.(*Struct); ok {
218 if x.NumFields() == y.NumFields() {
219 for i, f := range x.fields {
221 if f.embedded != g.embedded ||
222 cmpTags && x.Tag(i) != y.Tag(i) ||
223 !f.sameId(g.pkg, g.name) ||
224 !identical(f.typ, g.typ, cmpTags, p) {
233 // Two pointer types are identical if they have identical base types.
234 if y, ok := y.(*Pointer); ok {
235 return identical(x.base, y.base, cmpTags, p)
239 // Two tuples types are identical if they have the same number of elements
240 // and corresponding elements have identical types.
241 if y, ok := y.(*Tuple); ok {
242 if x.Len() == y.Len() {
244 for i, v := range x.vars {
246 if !identical(v.typ, w.typ, cmpTags, p) {
256 y, _ := y.(*Signature)
261 // Two function types are identical if they have the same number of
262 // parameters and result values, corresponding parameter and result types
263 // are identical, and either both functions are variadic or neither is.
264 // Parameter and result names are not required to match, and type
265 // parameters are considered identical modulo renaming.
267 if x.TypeParams().Len() != y.TypeParams().Len() {
271 // In the case of generic signatures, we will substitute in yparams and
274 yresults := y.results
276 if x.TypeParams().Len() > 0 {
277 // We must ignore type parameter names when comparing x and y. The
278 // easiest way to do this is to substitute x's type parameters for y's.
279 xtparams := x.TypeParams().list()
280 ytparams := y.TypeParams().list()
283 for i := range xtparams {
284 targs = append(targs, x.TypeParams().At(i))
286 smap := makeSubstMap(ytparams, targs)
288 var check *Checker // ok to call subst on a nil *Checker
290 // Constraints must be pair-wise identical, after substitution.
291 for i, xtparam := range xtparams {
292 ybound := check.subst(token.NoPos, ytparams[i].bound, smap, nil)
293 if !identical(xtparam.bound, ybound, cmpTags, p) {
298 yparams = check.subst(token.NoPos, y.params, smap, nil).(*Tuple)
299 yresults = check.subst(token.NoPos, y.results, smap, nil).(*Tuple)
302 return x.variadic == y.variadic &&
303 identical(x.params, yparams, cmpTags, p) &&
304 identical(x.results, yresults, cmpTags, p)
307 if y, _ := y.(*Union); y != nil {
308 // TODO(rfindley): can this be reached during type checking? If so,
309 // consider passing a type set map.
310 unionSets := make(map[*Union]*_TypeSet)
311 xset := computeUnionTypeSet(nil, unionSets, token.NoPos, x)
312 yset := computeUnionTypeSet(nil, unionSets, token.NoPos, y)
313 return xset.terms.equal(yset.terms)
317 // Two interface types are identical if they describe the same type sets.
318 // With the existing implementation restriction, this simplifies to:
320 // Two interface types are identical if they have the same set of methods with
321 // the same names and identical function types, and if any type restrictions
322 // are the same. Lower-case method names from different packages are always
323 // different. The order of the methods is irrelevant.
324 if y, ok := y.(*Interface); ok {
327 if xset.comparable != yset.comparable {
330 if !xset.terms.equal(yset.terms) {
335 if len(a) == len(b) {
336 // Interface types are the only types where cycles can occur
337 // that are not "terminated" via named types; and such cycles
338 // can only be created via method parameter types that are
339 // anonymous interfaces (directly or indirectly) embedding
340 // the current interface. Example:
342 // type T interface {
346 // If two such (differently named) interfaces are compared,
347 // endless recursion occurs if the cycle is not detected.
349 // If x and y were compared before, they must be equal
350 // (if they were not, the recursion would have stopped);
351 // search the ifacePair stack for the same pair.
353 // This is a quadratic algorithm, but in practice these stacks
354 // are extremely short (bounded by the nesting depth of interface
355 // type declarations that recur via parameter types, an extremely
356 // rare occurrence). An alternative implementation might use a
357 // "visited" map, but that is probably less efficient overall.
358 q := &ifacePair{x, y, p}
361 return true // same pair was compared before
366 assertSortedMethods(a)
367 assertSortedMethods(b)
369 for i, f := range a {
371 if f.Id() != g.Id() || !identical(f.typ, g.typ, cmpTags, q) {
380 // Two map types are identical if they have identical key and value types.
381 if y, ok := y.(*Map); ok {
382 return identical(x.key, y.key, cmpTags, p) && identical(x.elem, y.elem, cmpTags, p)
386 // Two channel types are identical if they have identical value types
387 // and the same direction.
388 if y, ok := y.(*Chan); ok {
389 return x.dir == y.dir && identical(x.elem, y.elem, cmpTags, p)
393 // Two named types are identical if their type names originate
394 // in the same type declaration.
395 if y, ok := y.(*Named); ok {
396 xargs := x.TypeArgs().list()
397 yargs := y.TypeArgs().list()
399 if len(xargs) != len(yargs) {
404 // Instances are identical if their original type and type arguments
406 if !Identical(x.orig, y.orig) {
409 for i, xa := range xargs {
410 if !Identical(xa, yargs[i]) {
417 // TODO(gri) Why is x == y not sufficient? And if it is,
418 // we can just return false here because x == y
419 // is caught in the very beginning of this function.
420 return x.obj == y.obj
424 // nothing to do (x and y being equal is caught in the very beginning of this function)
427 // avoid a crash in case of nil type
436 // identicalInstance reports if two type instantiations are identical.
437 // Instantiations are identical if their origin and type arguments are
439 func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool {
440 if len(xargs) != len(yargs) {
444 for i, xa := range xargs {
445 if !Identical(xa, yargs[i]) {
450 return Identical(xorig, yorig)
453 // Default returns the default "typed" type for an "untyped" type;
454 // it returns the incoming type for all other types. The default type
455 // for untyped nil is untyped nil.
456 func Default(t Type) Type {
457 if t, ok := t.(*Basic); ok {
464 return universeRune // use 'rune' name
468 return Typ[Complex128]