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 // isNamed reports whether typ has a name.
10 // isNamed may be called with types that are not fully set up.
11 func isNamed(typ Type) bool {
13 case *Basic, *Named, *TypeParam, *instance:
19 // isGeneric reports whether a type is a generic, uninstantiated type (generic
20 // signatures are not included).
21 func isGeneric(typ Type) bool {
22 // A parameterized type is only instantiated if it doesn't have an instantiation already.
23 named, _ := typ.(*Named)
24 return named != nil && named.obj != nil && named.TParams() != nil && named.targs == nil
27 func is(typ Type, what BasicInfo) bool {
28 switch t := under(typ).(type) {
30 return t.info&what != 0
32 return t.underIs(func(t Type) bool { return is(t, what) })
37 func isBoolean(typ Type) bool { return is(typ, IsBoolean) }
38 func isInteger(typ Type) bool { return is(typ, IsInteger) }
39 func isUnsigned(typ Type) bool { return is(typ, IsUnsigned) }
40 func isFloat(typ Type) bool { return is(typ, IsFloat) }
41 func isComplex(typ Type) bool { return is(typ, IsComplex) }
42 func isNumeric(typ Type) bool { return is(typ, IsNumeric) }
43 func isString(typ Type) bool { return is(typ, IsString) }
45 // Note that if typ is a type parameter, isInteger(typ) || isFloat(typ) does not
46 // produce the expected result because a type list that contains both an integer
47 // and a floating-point type is neither (all) integers, nor (all) floats.
48 // Use isIntegerOrFloat instead.
49 func isIntegerOrFloat(typ Type) bool { return is(typ, IsInteger|IsFloat) }
51 // isNumericOrString is the equivalent of isIntegerOrFloat for isNumeric(typ) || isString(typ).
52 func isNumericOrString(typ Type) bool { return is(typ, IsNumeric|IsString) }
54 // isTyped reports whether typ is typed; i.e., not an untyped
55 // constant or boolean. isTyped may be called with types that
56 // are not fully set up.
57 func isTyped(typ Type) bool {
58 // isTyped is called with types that are not fully
59 // set up. Must not call asBasic()!
60 // A *Named or *instance type is always typed, so
61 // we only need to check if we have a true *Basic
64 return t == nil || t.info&IsUntyped == 0
67 // isUntyped(typ) is the same as !isTyped(typ).
68 func isUntyped(typ Type) bool {
72 func isOrdered(typ Type) bool { return is(typ, IsOrdered) }
74 func isConstType(typ Type) bool {
75 // Type parameters are never const types.
76 t, _ := under(typ).(*Basic)
77 return t != nil && t.info&IsConstType != 0
80 // IsInterface reports whether typ is an interface type.
81 func IsInterface(typ Type) bool {
82 return asInterface(typ) != nil
85 // Comparable reports whether values of type T are comparable.
86 func Comparable(T Type) bool {
87 return comparable(T, nil)
90 func comparable(T Type, seen map[Type]bool) bool {
95 seen = make(map[Type]bool)
99 // If T is a type parameter not constrained by any type
100 // (i.e., it's operational type is the top type),
101 // T is comparable if it has the == method. Otherwise,
102 // the operational type "wins". For instance
104 // interface{ comparable; type []byte }
106 // is not comparable because []byte is not comparable.
107 // TODO(gri) this code is not 100% correct (see comment for TypeSet.IsComparable)
108 if t := asTypeParam(T); t != nil && optype(t) == theTop {
109 return t.Bound().IsComparable()
112 switch t := under(T).(type) {
114 // assume invalid types to be comparable
115 // to avoid follow-up errors
116 return t.kind != UntypedNil
117 case *Pointer, *Interface, *Chan:
120 for _, f := range t.fields {
121 if !comparable(f.typ, seen) {
127 return comparable(t.elem, seen)
129 return t.underIs(func(t Type) bool {
130 return comparable(t, seen)
136 // hasNil reports whether a type includes the nil value.
137 func hasNil(typ Type) bool {
138 switch t := under(typ).(type) {
140 return t.kind == UnsafePointer
141 case *Slice, *Pointer, *Signature, *Interface, *Map, *Chan:
144 return t.underIs(hasNil)
149 // An ifacePair is a node in a stack of interface type pairs compared for identity.
150 type ifacePair struct {
155 func (p *ifacePair) identical(q *ifacePair) bool {
156 return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
159 // For changes to this code the corresponding changes should be made to unifier.nify.
160 func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
161 // types must be expanded for comparison
169 switch x := x.(type) {
171 // Basic types are singletons except for the rune and byte
172 // aliases, thus we cannot solely rely on the x == y check
173 // above. See also comment in TypeName.IsAlias.
174 if y, ok := y.(*Basic); ok {
175 return x.kind == y.kind
179 // Two array types are identical if they have identical element types
180 // and the same array length.
181 if y, ok := y.(*Array); ok {
182 // If one or both array lengths are unknown (< 0) due to some error,
183 // assume they are the same to avoid spurious follow-on errors.
184 return (x.len < 0 || y.len < 0 || x.len == y.len) && identical(x.elem, y.elem, cmpTags, p)
188 // Two slice types are identical if they have identical element types.
189 if y, ok := y.(*Slice); ok {
190 return identical(x.elem, y.elem, cmpTags, p)
194 // Two struct types are identical if they have the same sequence of fields,
195 // and if corresponding fields have the same names, and identical types,
196 // and identical tags. Two embedded fields are considered to have the same
197 // name. Lower-case field names from different packages are always different.
198 if y, ok := y.(*Struct); ok {
199 if x.NumFields() == y.NumFields() {
200 for i, f := range x.fields {
202 if f.embedded != g.embedded ||
203 cmpTags && x.Tag(i) != y.Tag(i) ||
204 !f.sameId(g.pkg, g.name) ||
205 !identical(f.typ, g.typ, cmpTags, p) {
214 // Two pointer types are identical if they have identical base types.
215 if y, ok := y.(*Pointer); ok {
216 return identical(x.base, y.base, cmpTags, p)
220 // Two tuples types are identical if they have the same number of elements
221 // and corresponding elements have identical types.
222 if y, ok := y.(*Tuple); ok {
223 if x.Len() == y.Len() {
225 for i, v := range x.vars {
227 if !identical(v.typ, w.typ, cmpTags, p) {
237 // Two function types are identical if they have the same number of parameters
238 // and result values, corresponding parameter and result types are identical,
239 // and either both functions are variadic or neither is. Parameter and result
240 // names are not required to match.
241 // Generic functions must also have matching type parameter lists, but for the
243 if y, ok := y.(*Signature); ok {
244 return x.variadic == y.variadic &&
245 identicalTParams(x.tparams, y.tparams, cmpTags, p) &&
246 identical(x.params, y.params, cmpTags, p) &&
247 identical(x.results, y.results, cmpTags, p)
251 // Two union types are identical if they contain the same terms.
252 // The set (list) of types in a union type consists of unique
253 // types - each type appears exactly once. Thus, two union types
254 // must contain the same number of types to have chance of
256 if y, ok := y.(*Union); ok && x.NumTerms() == y.NumTerms() {
257 // Every type in x.types must be in y.types.
258 // Quadratic algorithm, but probably good enough for now.
259 // TODO(gri) we need a fast quick type ID/hash for all types.
261 for i, xt := range x.types {
262 for j, yt := range y.types {
263 if Identical(xt, yt) && x.tilde[i] == y.tilde[j] {
264 continue L // x is in y.types
267 return false // x is not in y.types
273 // Two interface types are identical if they describe the same type sets.
274 // With the existing implementation restriction, this simplifies to:
276 // Two interface types are identical if they have the same set of methods with
277 // the same names and identical function types, and if any type restrictions
278 // are the same. Lower-case method names from different packages are always
279 // different. The order of the methods is irrelevant.
280 if y, ok := y.(*Interface); ok {
283 if !Identical(xset.types, yset.types) {
288 if len(a) == len(b) {
289 // Interface types are the only types where cycles can occur
290 // that are not "terminated" via named types; and such cycles
291 // can only be created via method parameter types that are
292 // anonymous interfaces (directly or indirectly) embedding
293 // the current interface. Example:
295 // type T interface {
299 // If two such (differently named) interfaces are compared,
300 // endless recursion occurs if the cycle is not detected.
302 // If x and y were compared before, they must be equal
303 // (if they were not, the recursion would have stopped);
304 // search the ifacePair stack for the same pair.
306 // This is a quadratic algorithm, but in practice these stacks
307 // are extremely short (bounded by the nesting depth of interface
308 // type declarations that recur via parameter types, an extremely
309 // rare occurrence). An alternative implementation might use a
310 // "visited" map, but that is probably less efficient overall.
311 q := &ifacePair{x, y, p}
314 return true // same pair was compared before
319 assertSortedMethods(a)
320 assertSortedMethods(b)
322 for i, f := range a {
324 if f.Id() != g.Id() || !identical(f.typ, g.typ, cmpTags, q) {
333 // Two map types are identical if they have identical key and value types.
334 if y, ok := y.(*Map); ok {
335 return identical(x.key, y.key, cmpTags, p) && identical(x.elem, y.elem, cmpTags, p)
339 // Two channel types are identical if they have identical value types
340 // and the same direction.
341 if y, ok := y.(*Chan); ok {
342 return x.dir == y.dir && identical(x.elem, y.elem, cmpTags, p)
346 // Two named types are identical if their type names originate
347 // in the same type declaration.
348 if y, ok := y.(*Named); ok {
349 // TODO(gri) Why is x == y not sufficient? And if it is,
350 // we can just return false here because x == y
351 // is caught in the very beginning of this function.
352 return x.obj == y.obj
356 // nothing to do (x and y being equal is caught in the very beginning of this function)
359 // unreachable since types are expanded
362 // Either both types are theTop in which case the initial x == y check
363 // will have caught them. Otherwise they are not identical.
366 // avoid a crash in case of nil type
375 func identicalTParams(x, y []*TypeName, cmpTags bool, p *ifacePair) bool {
376 if len(x) != len(y) {
379 for i, x := range x {
381 if !identical(x.typ.(*TypeParam).bound, y.typ.(*TypeParam).bound, cmpTags, p) {
388 // Default returns the default "typed" type for an "untyped" type;
389 // it returns the incoming type for all other types. The default type
390 // for untyped nil is untyped nil.
392 func Default(typ Type) Type {
393 if t, ok := typ.(*Basic); ok {
400 return universeRune // use 'rune' name
404 return Typ[Complex128]