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.
13 // isNamed reports whether typ has a name.
14 // isNamed may be called with types that are not fully set up.
15 func isNamed(typ Type) bool {
17 case *Basic, *Named, *_TypeParam, *instance:
23 // isGeneric reports whether a type is a generic, uninstantiated type (generic
24 // signatures are not included).
25 func isGeneric(typ Type) bool {
26 // A parameterized type is only instantiated if it doesn't have an instantiation already.
27 named, _ := typ.(*Named)
28 return named != nil && named.obj != nil && named.tparams != nil && named.targs == nil
31 func is(typ Type, what BasicInfo) bool {
32 switch t := optype(typ).(type) {
34 return t.info&what != 0
36 return t.underIs(func(typ Type) bool { return is(typ, what) })
41 func isBoolean(typ Type) bool { return is(typ, IsBoolean) }
42 func isInteger(typ Type) bool { return is(typ, IsInteger) }
43 func isUnsigned(typ Type) bool { return is(typ, IsUnsigned) }
44 func isFloat(typ Type) bool { return is(typ, IsFloat) }
45 func isComplex(typ Type) bool { return is(typ, IsComplex) }
46 func isNumeric(typ Type) bool { return is(typ, IsNumeric) }
47 func isString(typ Type) bool { return is(typ, IsString) }
49 // Note that if typ is a type parameter, isInteger(typ) || isFloat(typ) does not
50 // produce the expected result because a type list that contains both an integer
51 // and a floating-point type is neither (all) integers, nor (all) floats.
52 // Use isIntegerOrFloat instead.
53 func isIntegerOrFloat(typ Type) bool { return is(typ, IsInteger|IsFloat) }
55 // isNumericOrString is the equivalent of isIntegerOrFloat for isNumeric(typ) || isString(typ).
56 func isNumericOrString(typ Type) bool { return is(typ, IsNumeric|IsString) }
58 // isTyped reports whether typ is typed; i.e., not an untyped
59 // constant or boolean. isTyped may be called with types that
60 // are not fully set up.
61 func isTyped(typ Type) bool {
62 // isTyped is called with types that are not fully
63 // set up. Must not call asBasic()!
64 // A *Named or *instance type is always typed, so
65 // we only need to check if we have a true *Basic
68 return t == nil || t.info&IsUntyped == 0
71 // isUntyped(typ) is the same as !isTyped(typ).
72 func isUntyped(typ Type) bool {
76 func isOrdered(typ Type) bool { return is(typ, IsOrdered) }
78 func isConstType(typ Type) bool {
79 // Type parameters are never const types.
80 t, _ := under(typ).(*Basic)
81 return t != nil && t.info&IsConstType != 0
84 // IsInterface reports whether typ is an interface type.
85 func IsInterface(typ Type) bool {
86 return asInterface(typ) != nil
89 // Comparable reports whether values of type T are comparable.
90 func Comparable(T Type) bool {
91 return comparable(T, nil)
94 func comparable(T Type, seen map[Type]bool) bool {
99 seen = make(map[Type]bool)
103 // If T is a type parameter not constrained by any type
104 // list (i.e., it's operational type is the top type),
105 // T is comparable if it has the == method. Otherwise,
106 // the operational type "wins". For instance
108 // interface{ comparable; type []byte }
110 // is not comparable because []byte is not comparable.
111 if t := asTypeParam(T); t != nil && optype(t) == theTop {
112 return t.Bound()._IsComparable()
115 switch t := optype(T).(type) {
117 // assume invalid types to be comparable
118 // to avoid follow-up errors
119 return t.kind != UntypedNil
120 case *Pointer, *Interface, *Chan:
123 for _, f := range t.fields {
124 if !comparable(f.typ, seen) {
130 return comparable(t.elem, seen)
132 return t.underIs(func(t Type) bool {
133 return comparable(t, seen)
136 return t.Bound()._IsComparable()
141 // hasNil reports whether a type includes the nil value.
142 func hasNil(typ Type) bool {
143 switch t := optype(typ).(type) {
145 return t.kind == UnsafePointer
146 case *Slice, *Pointer, *Signature, *Interface, *Map, *Chan:
149 return t.underIs(hasNil)
154 // identical reports whether x and y are identical types.
155 // Receivers of Signature types are ignored.
156 func (check *Checker) identical(x, y Type) bool {
157 return check.identical0(x, y, true, nil)
160 // identicalIgnoreTags reports whether x and y are identical types if tags are ignored.
161 // Receivers of Signature types are ignored.
162 func (check *Checker) identicalIgnoreTags(x, y Type) bool {
163 return check.identical0(x, y, false, nil)
166 // An ifacePair is a node in a stack of interface type pairs compared for identity.
167 type ifacePair struct {
172 func (p *ifacePair) identical(q *ifacePair) bool {
173 return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
176 // For changes to this code the corresponding changes should be made to unifier.nify.
177 func (check *Checker) identical0(x, y Type, cmpTags bool, p *ifacePair) bool {
178 // types must be expanded for comparison
186 switch x := x.(type) {
188 // Basic types are singletons except for the rune and byte
189 // aliases, thus we cannot solely rely on the x == y check
190 // above. See also comment in TypeName.IsAlias.
191 if y, ok := y.(*Basic); ok {
192 return x.kind == y.kind
196 // Two array types are identical if they have identical element types
197 // and the same array length.
198 if y, ok := y.(*Array); ok {
199 // If one or both array lengths are unknown (< 0) due to some error,
200 // assume they are the same to avoid spurious follow-on errors.
201 return (x.len < 0 || y.len < 0 || x.len == y.len) && check.identical0(x.elem, y.elem, cmpTags, p)
205 // Two slice types are identical if they have identical element types.
206 if y, ok := y.(*Slice); ok {
207 return check.identical0(x.elem, y.elem, cmpTags, p)
211 // Two struct types are identical if they have the same sequence of fields,
212 // and if corresponding fields have the same names, and identical types,
213 // and identical tags. Two embedded fields are considered to have the same
214 // name. Lower-case field names from different packages are always different.
215 if y, ok := y.(*Struct); ok {
216 if x.NumFields() == y.NumFields() {
217 for i, f := range x.fields {
219 if f.embedded != g.embedded ||
220 cmpTags && x.Tag(i) != y.Tag(i) ||
221 !f.sameId(g.pkg, g.name) ||
222 !check.identical0(f.typ, g.typ, cmpTags, p) {
231 // Two pointer types are identical if they have identical base types.
232 if y, ok := y.(*Pointer); ok {
233 return check.identical0(x.base, y.base, cmpTags, p)
237 // Two tuples types are identical if they have the same number of elements
238 // and corresponding elements have identical types.
239 if y, ok := y.(*Tuple); ok {
240 if x.Len() == y.Len() {
242 for i, v := range x.vars {
244 if !check.identical0(v.typ, w.typ, cmpTags, p) {
254 // Two function types are identical if they have the same number of parameters
255 // and result values, corresponding parameter and result types are identical,
256 // and either both functions are variadic or neither is. Parameter and result
257 // names are not required to match.
258 // Generic functions must also have matching type parameter lists, but for the
260 if y, ok := y.(*Signature); ok {
261 return x.variadic == y.variadic &&
262 check.identicalTParams(x.tparams, y.tparams, cmpTags, p) &&
263 check.identical0(x.params, y.params, cmpTags, p) &&
264 check.identical0(x.results, y.results, cmpTags, p)
268 // Two union types are identical if they contain the same terms.
269 // The set (list) of types in a union type consists of unique
270 // types - each type appears exactly once. Thus, two union types
271 // must contain the same number of types to have chance of
273 if y, ok := y.(*Union); ok && x.NumTerms() == y.NumTerms() {
274 // Every type in x.types must be in y.types.
275 // Quadratic algorithm, but probably good enough for now.
276 // TODO(gri) we need a fast quick type ID/hash for all types.
278 for i, xt := range x.types {
279 for j, yt := range y.types {
280 if Identical(xt, yt) && x.tilde[i] == y.tilde[j] {
281 continue L // x is in y.types
284 return false // x is not in y.types
290 // Two interface types are identical if they have the same set of methods with
291 // the same names and identical function types. Lower-case method names from
292 // different packages are always different. The order of the methods is irrelevant.
293 if y, ok := y.(*Interface); ok {
294 // If identical0 is called (indirectly) via an external API entry point
295 // (such as Identical, IdenticalIgnoreTags, etc.), check is nil. But in
296 // that case, interfaces are expected to be complete and lazy completion
297 // here is not needed.
299 check.completeInterface(token.NoPos, x)
300 check.completeInterface(token.NoPos, y)
304 if len(a) == len(b) {
305 // Interface types are the only types where cycles can occur
306 // that are not "terminated" via named types; and such cycles
307 // can only be created via method parameter types that are
308 // anonymous interfaces (directly or indirectly) embedding
309 // the current interface. Example:
311 // type T interface {
315 // If two such (differently named) interfaces are compared,
316 // endless recursion occurs if the cycle is not detected.
318 // If x and y were compared before, they must be equal
319 // (if they were not, the recursion would have stopped);
320 // search the ifacePair stack for the same pair.
322 // This is a quadratic algorithm, but in practice these stacks
323 // are extremely short (bounded by the nesting depth of interface
324 // type declarations that recur via parameter types, an extremely
325 // rare occurrence). An alternative implementation might use a
326 // "visited" map, but that is probably less efficient overall.
327 q := &ifacePair{x, y, p}
330 return true // same pair was compared before
335 assertSortedMethods(a)
336 assertSortedMethods(b)
338 for i, f := range a {
340 if f.Id() != g.Id() || !check.identical0(f.typ, g.typ, cmpTags, q) {
349 // Two map types are identical if they have identical key and value types.
350 if y, ok := y.(*Map); ok {
351 return check.identical0(x.key, y.key, cmpTags, p) && check.identical0(x.elem, y.elem, cmpTags, p)
355 // Two channel types are identical if they have identical value types
356 // and the same direction.
357 if y, ok := y.(*Chan); ok {
358 return x.dir == y.dir && check.identical0(x.elem, y.elem, cmpTags, p)
362 // Two named types are identical if their type names originate
363 // in the same type declaration.
364 if y, ok := y.(*Named); ok {
365 // TODO(gri) Why is x == y not sufficient? And if it is,
366 // we can just return false here because x == y
367 // is caught in the very beginning of this function.
368 return x.obj == y.obj
372 // nothing to do (x and y being equal is caught in the very beginning of this function)
375 // unreachable since types are expanded
378 // Either both types are theTop in which case the initial x == y check
379 // will have caught them. Otherwise they are not identical.
382 // avoid a crash in case of nil type
391 func (check *Checker) identicalTParams(x, y []*TypeName, cmpTags bool, p *ifacePair) bool {
392 if len(x) != len(y) {
395 for i, x := range x {
397 if !check.identical0(x.typ.(*_TypeParam).bound, y.typ.(*_TypeParam).bound, cmpTags, p) {
404 // Default returns the default "typed" type for an "untyped" type;
405 // it returns the incoming type for all other types. The default type
406 // for untyped nil is untyped nil.
408 func Default(typ Type) Type {
409 if t, ok := typ.(*Basic); ok {
416 return universeRune // use 'rune' name
420 return Typ[Complex128]