1 // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
3 // Copyright 2012 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
7 // This file implements commonly used type predicates.
11 // isValid reports whether t is a valid type.
12 func isValid(t Type) bool { return t != Typ[Invalid] }
14 // The isX predicates below report whether t is an X.
15 // If t is a type parameter the result is false; i.e.,
16 // these predicates don't look inside a type parameter.
18 func isBoolean(t Type) bool { return isBasic(t, IsBoolean) }
19 func isInteger(t Type) bool { return isBasic(t, IsInteger) }
20 func isUnsigned(t Type) bool { return isBasic(t, IsUnsigned) }
21 func isFloat(t Type) bool { return isBasic(t, IsFloat) }
22 func isComplex(t Type) bool { return isBasic(t, IsComplex) }
23 func isNumeric(t Type) bool { return isBasic(t, IsNumeric) }
24 func isString(t Type) bool { return isBasic(t, IsString) }
25 func isIntegerOrFloat(t Type) bool { return isBasic(t, IsInteger|IsFloat) }
26 func isConstType(t Type) bool { return isBasic(t, IsConstType) }
28 // isBasic reports whether under(t) is a basic type with the specified info.
29 // If t is a type parameter the result is false; i.e.,
30 // isBasic does not look inside a type parameter.
31 func isBasic(t Type, info BasicInfo) bool {
32 u, _ := under(t).(*Basic)
33 return u != nil && u.info&info != 0
36 // The allX predicates below report whether t is an X.
37 // If t is a type parameter the result is true if isX is true
38 // for all specified types of the type parameter's type set.
39 // allX is an optimized version of isX(coreType(t)) (which
40 // is the same as underIs(t, isX)).
42 func allBoolean(t Type) bool { return allBasic(t, IsBoolean) }
43 func allInteger(t Type) bool { return allBasic(t, IsInteger) }
44 func allUnsigned(t Type) bool { return allBasic(t, IsUnsigned) }
45 func allNumeric(t Type) bool { return allBasic(t, IsNumeric) }
46 func allString(t Type) bool { return allBasic(t, IsString) }
47 func allOrdered(t Type) bool { return allBasic(t, IsOrdered) }
48 func allNumericOrString(t Type) bool { return allBasic(t, IsNumeric|IsString) }
50 // allBasic reports whether under(t) is a basic type with the specified info.
51 // If t is a type parameter, the result is true if isBasic(t, info) is true
52 // for all specific types of the type parameter's type set.
53 // allBasic(t, info) is an optimized version of isBasic(coreType(t), info).
54 func allBasic(t Type, info BasicInfo) bool {
55 if tpar, _ := t.(*TypeParam); tpar != nil {
56 return tpar.is(func(t *term) bool { return t != nil && isBasic(t.typ, info) })
58 return isBasic(t, info)
61 // hasName reports whether t has a name. This includes
62 // predeclared types, defined types, and type parameters.
63 // hasName may be called with types that are not fully set up.
64 func hasName(t Type) bool {
66 case *Basic, *Named, *TypeParam:
72 // isTypeLit reports whether t is a type literal.
73 // This includes all non-defined types, but also basic types.
74 // isTypeLit may be called with types that are not fully set up.
75 func isTypeLit(t Type) bool {
77 case *Named, *TypeParam:
83 // isTyped reports whether t is typed; i.e., not an untyped
84 // constant or boolean. isTyped may be called with types that
85 // are not fully set up.
86 func isTyped(t Type) bool {
87 // isTyped is called with types that are not fully
88 // set up. Must not call under()!
90 return b == nil || b.info&IsUntyped == 0
93 // isUntyped(t) is the same as !isTyped(t).
94 func isUntyped(t Type) bool {
98 // IsInterface reports whether t is an interface type.
99 func IsInterface(t Type) bool {
100 _, ok := under(t).(*Interface)
104 // isNonTypeParamInterface reports whether t is an interface type but not a type parameter.
105 func isNonTypeParamInterface(t Type) bool {
106 return !isTypeParam(t) && IsInterface(t)
109 // isTypeParam reports whether t is a type parameter.
110 func isTypeParam(t Type) bool {
111 _, ok := t.(*TypeParam)
115 // hasEmptyTypeset reports whether t is a type parameter with an empty type set.
116 // The function does not force the computation of the type set and so is safe to
117 // use anywhere, but it may report a false negative if the type set has not been
119 func hasEmptyTypeset(t Type) bool {
120 if tpar, _ := t.(*TypeParam); tpar != nil && tpar.bound != nil {
121 iface, _ := safeUnderlying(tpar.bound).(*Interface)
122 return iface != nil && iface.tset != nil && iface.tset.IsEmpty()
127 // isGeneric reports whether a type is a generic, uninstantiated type
128 // (generic signatures are not included).
129 // TODO(gri) should we include signatures or assert that they are not present?
130 func isGeneric(t Type) bool {
131 // A parameterized type is only generic if it doesn't have an instantiation already.
133 return named != nil && named.obj != nil && named.inst == nil && named.TypeParams().Len() > 0
136 // Comparable reports whether values of type T are comparable.
137 func Comparable(T Type) bool {
138 return comparable(T, true, nil, nil)
141 // If dynamic is set, non-type parameter interfaces are always comparable.
142 // If reportf != nil, it may be used to report why T is not comparable.
143 func comparable(T Type, dynamic bool, seen map[Type]bool, reportf func(string, ...interface{})) bool {
148 seen = make(map[Type]bool)
152 switch t := under(T).(type) {
154 // assume invalid types to be comparable
155 // to avoid follow-up errors
156 return t.kind != UntypedNil
157 case *Pointer, *Chan:
160 for _, f := range t.fields {
161 if !comparable(f.typ, dynamic, seen, nil) {
163 reportf("struct containing %s cannot be compared", f.typ)
170 if !comparable(t.elem, dynamic, seen, nil) {
172 reportf("%s cannot be compared", t)
178 if dynamic && !isTypeParam(T) || t.typeSet().IsComparable(seen) {
182 if t.typeSet().IsEmpty() {
183 reportf("empty type set")
185 reportf("incomparable types in type set")
193 // hasNil reports whether type t includes the nil value.
194 func hasNil(t Type) bool {
195 switch u := under(t).(type) {
197 return u.kind == UnsafePointer
198 case *Slice, *Pointer, *Signature, *Map, *Chan:
201 return !isTypeParam(t) || u.typeSet().underIs(func(u Type) bool {
202 return u != nil && hasNil(u)
208 // An ifacePair is a node in a stack of interface type pairs compared for identity.
209 type ifacePair struct {
214 func (p *ifacePair) identical(q *ifacePair) bool {
215 return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
218 // A comparer is used to compare types.
219 type comparer struct {
220 ignoreTags bool // if set, identical ignores struct tags
221 ignoreInvalids bool // if set, identical treats an invalid type as identical to any type
224 // For changes to this code the corresponding changes should be made to unifier.nify.
225 func (c *comparer) identical(x, y Type, p *ifacePair) bool {
230 if c.ignoreInvalids && (!isValid(x) || !isValid(y)) {
234 switch x := x.(type) {
236 // Basic types are singletons except for the rune and byte
237 // aliases, thus we cannot solely rely on the x == y check
238 // above. See also comment in TypeName.IsAlias.
239 if y, ok := y.(*Basic); ok {
240 return x.kind == y.kind
244 // Two array types are identical if they have identical element types
245 // and the same array length.
246 if y, ok := y.(*Array); ok {
247 // If one or both array lengths are unknown (< 0) due to some error,
248 // assume they are the same to avoid spurious follow-on errors.
249 return (x.len < 0 || y.len < 0 || x.len == y.len) && c.identical(x.elem, y.elem, p)
253 // Two slice types are identical if they have identical element types.
254 if y, ok := y.(*Slice); ok {
255 return c.identical(x.elem, y.elem, p)
259 // Two struct types are identical if they have the same sequence of fields,
260 // and if corresponding fields have the same names, and identical types,
261 // and identical tags. Two embedded fields are considered to have the same
262 // name. Lower-case field names from different packages are always different.
263 if y, ok := y.(*Struct); ok {
264 if x.NumFields() == y.NumFields() {
265 for i, f := range x.fields {
267 if f.embedded != g.embedded ||
268 !c.ignoreTags && x.Tag(i) != y.Tag(i) ||
269 !f.sameId(g.pkg, g.name) ||
270 !c.identical(f.typ, g.typ, p) {
279 // Two pointer types are identical if they have identical base types.
280 if y, ok := y.(*Pointer); ok {
281 return c.identical(x.base, y.base, p)
285 // Two tuples types are identical if they have the same number of elements
286 // and corresponding elements have identical types.
287 if y, ok := y.(*Tuple); ok {
288 if x.Len() == y.Len() {
290 for i, v := range x.vars {
292 if !c.identical(v.typ, w.typ, p) {
302 y, _ := y.(*Signature)
307 // Two function types are identical if they have the same number of
308 // parameters and result values, corresponding parameter and result types
309 // are identical, and either both functions are variadic or neither is.
310 // Parameter and result names are not required to match, and type
311 // parameters are considered identical modulo renaming.
313 if x.TypeParams().Len() != y.TypeParams().Len() {
317 // In the case of generic signatures, we will substitute in yparams and
320 yresults := y.results
322 if x.TypeParams().Len() > 0 {
323 // We must ignore type parameter names when comparing x and y. The
324 // easiest way to do this is to substitute x's type parameters for y's.
325 xtparams := x.TypeParams().list()
326 ytparams := y.TypeParams().list()
329 for i := range xtparams {
330 targs = append(targs, x.TypeParams().At(i))
332 smap := makeSubstMap(ytparams, targs)
334 var check *Checker // ok to call subst on a nil *Checker
335 ctxt := NewContext() // need a non-nil Context for the substitution below
337 // Constraints must be pair-wise identical, after substitution.
338 for i, xtparam := range xtparams {
339 ybound := check.subst(nopos, ytparams[i].bound, smap, nil, ctxt)
340 if !c.identical(xtparam.bound, ybound, p) {
345 yparams = check.subst(nopos, y.params, smap, nil, ctxt).(*Tuple)
346 yresults = check.subst(nopos, y.results, smap, nil, ctxt).(*Tuple)
349 return x.variadic == y.variadic &&
350 c.identical(x.params, yparams, p) &&
351 c.identical(x.results, yresults, p)
354 if y, _ := y.(*Union); y != nil {
355 // TODO(rfindley): can this be reached during type checking? If so,
356 // consider passing a type set map.
357 unionSets := make(map[*Union]*_TypeSet)
358 xset := computeUnionTypeSet(nil, unionSets, nopos, x)
359 yset := computeUnionTypeSet(nil, unionSets, nopos, y)
360 return xset.terms.equal(yset.terms)
364 // Two interface types are identical if they describe the same type sets.
365 // With the existing implementation restriction, this simplifies to:
367 // Two interface types are identical if they have the same set of methods with
368 // the same names and identical function types, and if any type restrictions
369 // are the same. Lower-case method names from different packages are always
370 // different. The order of the methods is irrelevant.
371 if y, ok := y.(*Interface); ok {
374 if xset.comparable != yset.comparable {
377 if !xset.terms.equal(yset.terms) {
382 if len(a) == len(b) {
383 // Interface types are the only types where cycles can occur
384 // that are not "terminated" via named types; and such cycles
385 // can only be created via method parameter types that are
386 // anonymous interfaces (directly or indirectly) embedding
387 // the current interface. Example:
389 // type T interface {
393 // If two such (differently named) interfaces are compared,
394 // endless recursion occurs if the cycle is not detected.
396 // If x and y were compared before, they must be equal
397 // (if they were not, the recursion would have stopped);
398 // search the ifacePair stack for the same pair.
400 // This is a quadratic algorithm, but in practice these stacks
401 // are extremely short (bounded by the nesting depth of interface
402 // type declarations that recur via parameter types, an extremely
403 // rare occurrence). An alternative implementation might use a
404 // "visited" map, but that is probably less efficient overall.
405 q := &ifacePair{x, y, p}
408 return true // same pair was compared before
413 assertSortedMethods(a)
414 assertSortedMethods(b)
416 for i, f := range a {
418 if f.Id() != g.Id() || !c.identical(f.typ, g.typ, q) {
427 // Two map types are identical if they have identical key and value types.
428 if y, ok := y.(*Map); ok {
429 return c.identical(x.key, y.key, p) && c.identical(x.elem, y.elem, p)
433 // Two channel types are identical if they have identical value types
434 // and the same direction.
435 if y, ok := y.(*Chan); ok {
436 return x.dir == y.dir && c.identical(x.elem, y.elem, p)
440 // Two named types are identical if their type names originate
441 // in the same type declaration; if they are instantiated they
442 // must have identical type argument lists.
443 if y := asNamed(y); y != nil {
444 // check type arguments before origins to match unifier
445 // (for correct source code we need to do all checks so
446 // order doesn't matter)
447 xargs := x.TypeArgs().list()
448 yargs := y.TypeArgs().list()
449 if len(xargs) != len(yargs) {
452 for i, xarg := range xargs {
453 if !Identical(xarg, yargs[i]) {
457 return identicalOrigin(x, y)
461 // nothing to do (x and y being equal is caught in the very beginning of this function)
464 // avoid a crash in case of nil type
473 // identicalOrigin reports whether x and y originated in the same declaration.
474 func identicalOrigin(x, y *Named) bool {
475 // TODO(gri) is this correct?
476 return x.Origin().obj == y.Origin().obj
479 // identicalInstance reports if two type instantiations are identical.
480 // Instantiations are identical if their origin and type arguments are
482 func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool {
483 if len(xargs) != len(yargs) {
487 for i, xa := range xargs {
488 if !Identical(xa, yargs[i]) {
493 return Identical(xorig, yorig)
496 // Default returns the default "typed" type for an "untyped" type;
497 // it returns the incoming type for all other types. The default type
498 // for untyped nil is untyped nil.
499 func Default(t Type) Type {
500 if t, ok := t.(*Basic); ok {
507 return universeRune // use 'rune' name
511 return Typ[Complex128]
519 // maxType returns the "largest" type that encompasses both x and y.
520 // If x and y are different untyped numeric types, the result is the type of x or y
521 // that appears later in this list: integer, rune, floating-point, complex.
522 // Otherwise, if x != y, the result is nil.
523 func maxType(x, y Type) Type {
524 // We only care about untyped types (for now), so == is good enough.
525 // TODO(gri) investigate generalizing this function to simplify code elsewhere
529 if isUntyped(x) && isUntyped(y) && isNumeric(x) && isNumeric(y) {
530 // untyped types are basic types
531 if x.(*Basic).kind > y.(*Basic).kind {
539 // clone makes a "flat copy" of *p and returns a pointer to the copy.
540 func clone[P *T, T any](p P) P {