Source file src/go/types/predicates.go

     1  // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
     2  // Source: ../../cmd/compile/internal/types2/predicates.go
     3  
     4  // Copyright 2012 The Go Authors. All rights reserved.
     5  // Use of this source code is governed by a BSD-style
     6  // license that can be found in the LICENSE file.
     7  
     8  // This file implements commonly used type predicates.
     9  
    10  package types
    11  
    12  // isValid reports whether t is a valid type.
    13  func isValid(t Type) bool { return Unalias(t) != Typ[Invalid] }
    14  
    15  // The isX predicates below report whether t is an X.
    16  // If t is a type parameter the result is false; i.e.,
    17  // these predicates don't look inside a type parameter.
    18  
    19  func isBoolean(t Type) bool        { return isBasic(t, IsBoolean) }
    20  func isInteger(t Type) bool        { return isBasic(t, IsInteger) }
    21  func isUnsigned(t Type) bool       { return isBasic(t, IsUnsigned) }
    22  func isFloat(t Type) bool          { return isBasic(t, IsFloat) }
    23  func isComplex(t Type) bool        { return isBasic(t, IsComplex) }
    24  func isNumeric(t Type) bool        { return isBasic(t, IsNumeric) }
    25  func isString(t Type) bool         { return isBasic(t, IsString) }
    26  func isIntegerOrFloat(t Type) bool { return isBasic(t, IsInteger|IsFloat) }
    27  func isConstType(t Type) bool      { return isBasic(t, IsConstType) }
    28  
    29  // isBasic reports whether under(t) is a basic type with the specified info.
    30  // If t is a type parameter the result is false; i.e.,
    31  // isBasic does not look inside a type parameter.
    32  func isBasic(t Type, info BasicInfo) bool {
    33  	u, _ := under(t).(*Basic)
    34  	return u != nil && u.info&info != 0
    35  }
    36  
    37  // The allX predicates below report whether t is an X.
    38  // If t is a type parameter the result is true if isX is true
    39  // for all specified types of the type parameter's type set.
    40  // allX is an optimized version of isX(coreType(t)) (which
    41  // is the same as underIs(t, isX)).
    42  
    43  func allBoolean(t Type) bool         { return allBasic(t, IsBoolean) }
    44  func allInteger(t Type) bool         { return allBasic(t, IsInteger) }
    45  func allUnsigned(t Type) bool        { return allBasic(t, IsUnsigned) }
    46  func allNumeric(t Type) bool         { return allBasic(t, IsNumeric) }
    47  func allString(t Type) bool          { return allBasic(t, IsString) }
    48  func allOrdered(t Type) bool         { return allBasic(t, IsOrdered) }
    49  func allNumericOrString(t Type) bool { return allBasic(t, IsNumeric|IsString) }
    50  
    51  // allBasic reports whether under(t) is a basic type with the specified info.
    52  // If t is a type parameter, the result is true if isBasic(t, info) is true
    53  // for all specific types of the type parameter's type set.
    54  // allBasic(t, info) is an optimized version of isBasic(coreType(t), info).
    55  func allBasic(t Type, info BasicInfo) bool {
    56  	if tpar, _ := Unalias(t).(*TypeParam); tpar != nil {
    57  		return tpar.is(func(t *term) bool { return t != nil && isBasic(t.typ, info) })
    58  	}
    59  	return isBasic(t, info)
    60  }
    61  
    62  // hasName reports whether t has a name. This includes
    63  // predeclared types, defined types, and type parameters.
    64  // hasName may be called with types that are not fully set up.
    65  func hasName(t Type) bool {
    66  	switch Unalias(t).(type) {
    67  	case *Basic, *Named, *TypeParam:
    68  		return true
    69  	}
    70  	return false
    71  }
    72  
    73  // isTypeLit reports whether t is a type literal.
    74  // This includes all non-defined types, but also basic types.
    75  // isTypeLit may be called with types that are not fully set up.
    76  func isTypeLit(t Type) bool {
    77  	switch Unalias(t).(type) {
    78  	case *Named, *TypeParam:
    79  		return false
    80  	}
    81  	return true
    82  }
    83  
    84  // isTyped reports whether t is typed; i.e., not an untyped
    85  // constant or boolean.
    86  // Safe to call from types that are not fully set up.
    87  func isTyped(t Type) bool {
    88  	// Alias and named types cannot denote untyped types
    89  	// so there's no need to call Unalias or under, below.
    90  	b, _ := t.(*Basic)
    91  	return b == nil || b.info&IsUntyped == 0
    92  }
    93  
    94  // isUntyped(t) is the same as !isTyped(t).
    95  // Safe to call from types that are not fully set up.
    96  func isUntyped(t Type) bool {
    97  	return !isTyped(t)
    98  }
    99  
   100  // isUntypedNumeric reports whether t is an untyped numeric type.
   101  // Safe to call from types that are not fully set up.
   102  func isUntypedNumeric(t Type) bool {
   103  	// Alias and named types cannot denote untyped types
   104  	// so there's no need to call Unalias or under, below.
   105  	b, _ := t.(*Basic)
   106  	return b != nil && b.info&IsUntyped != 0 && b.info&IsNumeric != 0
   107  }
   108  
   109  // IsInterface reports whether t is an interface type.
   110  func IsInterface(t Type) bool {
   111  	_, ok := under(t).(*Interface)
   112  	return ok
   113  }
   114  
   115  // isNonTypeParamInterface reports whether t is an interface type but not a type parameter.
   116  func isNonTypeParamInterface(t Type) bool {
   117  	return !isTypeParam(t) && IsInterface(t)
   118  }
   119  
   120  // isTypeParam reports whether t is a type parameter.
   121  func isTypeParam(t Type) bool {
   122  	_, ok := Unalias(t).(*TypeParam)
   123  	return ok
   124  }
   125  
   126  // hasEmptyTypeset reports whether t is a type parameter with an empty type set.
   127  // The function does not force the computation of the type set and so is safe to
   128  // use anywhere, but it may report a false negative if the type set has not been
   129  // computed yet.
   130  func hasEmptyTypeset(t Type) bool {
   131  	if tpar, _ := Unalias(t).(*TypeParam); tpar != nil && tpar.bound != nil {
   132  		iface, _ := safeUnderlying(tpar.bound).(*Interface)
   133  		return iface != nil && iface.tset != nil && iface.tset.IsEmpty()
   134  	}
   135  	return false
   136  }
   137  
   138  // isGeneric reports whether a type is a generic, uninstantiated type
   139  // (generic signatures are not included).
   140  // TODO(gri) should we include signatures or assert that they are not present?
   141  func isGeneric(t Type) bool {
   142  	// A parameterized type is only generic if it doesn't have an instantiation already.
   143  	if alias, _ := t.(*Alias); alias != nil && alias.tparams != nil && alias.targs == nil {
   144  		return true
   145  	}
   146  	named := asNamed(t)
   147  	return named != nil && named.obj != nil && named.inst == nil && named.TypeParams().Len() > 0
   148  }
   149  
   150  // Comparable reports whether values of type T are comparable.
   151  func Comparable(T Type) bool {
   152  	return comparable(T, true, nil, nil)
   153  }
   154  
   155  // If dynamic is set, non-type parameter interfaces are always comparable.
   156  // If reportf != nil, it may be used to report why T is not comparable.
   157  func comparable(T Type, dynamic bool, seen map[Type]bool, reportf func(string, ...interface{})) bool {
   158  	if seen[T] {
   159  		return true
   160  	}
   161  	if seen == nil {
   162  		seen = make(map[Type]bool)
   163  	}
   164  	seen[T] = true
   165  
   166  	switch t := under(T).(type) {
   167  	case *Basic:
   168  		// assume invalid types to be comparable
   169  		// to avoid follow-up errors
   170  		return t.kind != UntypedNil
   171  	case *Pointer, *Chan:
   172  		return true
   173  	case *Struct:
   174  		for _, f := range t.fields {
   175  			if !comparable(f.typ, dynamic, seen, nil) {
   176  				if reportf != nil {
   177  					reportf("struct containing %s cannot be compared", f.typ)
   178  				}
   179  				return false
   180  			}
   181  		}
   182  		return true
   183  	case *Array:
   184  		if !comparable(t.elem, dynamic, seen, nil) {
   185  			if reportf != nil {
   186  				reportf("%s cannot be compared", t)
   187  			}
   188  			return false
   189  		}
   190  		return true
   191  	case *Interface:
   192  		if dynamic && !isTypeParam(T) || t.typeSet().IsComparable(seen) {
   193  			return true
   194  		}
   195  		if reportf != nil {
   196  			if t.typeSet().IsEmpty() {
   197  				reportf("empty type set")
   198  			} else {
   199  				reportf("incomparable types in type set")
   200  			}
   201  		}
   202  		// fallthrough
   203  	}
   204  	return false
   205  }
   206  
   207  // hasNil reports whether type t includes the nil value.
   208  func hasNil(t Type) bool {
   209  	switch u := under(t).(type) {
   210  	case *Basic:
   211  		return u.kind == UnsafePointer
   212  	case *Slice, *Pointer, *Signature, *Map, *Chan:
   213  		return true
   214  	case *Interface:
   215  		return !isTypeParam(t) || u.typeSet().underIs(func(u Type) bool {
   216  			return u != nil && hasNil(u)
   217  		})
   218  	}
   219  	return false
   220  }
   221  
   222  // samePkg reports whether packages a and b are the same.
   223  func samePkg(a, b *Package) bool {
   224  	// package is nil for objects in universe scope
   225  	if a == nil || b == nil {
   226  		return a == b
   227  	}
   228  	// a != nil && b != nil
   229  	return a.path == b.path
   230  }
   231  
   232  // An ifacePair is a node in a stack of interface type pairs compared for identity.
   233  type ifacePair struct {
   234  	x, y *Interface
   235  	prev *ifacePair
   236  }
   237  
   238  func (p *ifacePair) identical(q *ifacePair) bool {
   239  	return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
   240  }
   241  
   242  // A comparer is used to compare types.
   243  type comparer struct {
   244  	ignoreTags     bool // if set, identical ignores struct tags
   245  	ignoreInvalids bool // if set, identical treats an invalid type as identical to any type
   246  }
   247  
   248  // For changes to this code the corresponding changes should be made to unifier.nify.
   249  func (c *comparer) identical(x, y Type, p *ifacePair) bool {
   250  	x = Unalias(x)
   251  	y = Unalias(y)
   252  
   253  	if x == y {
   254  		return true
   255  	}
   256  
   257  	if c.ignoreInvalids && (!isValid(x) || !isValid(y)) {
   258  		return true
   259  	}
   260  
   261  	switch x := x.(type) {
   262  	case *Basic:
   263  		// Basic types are singletons except for the rune and byte
   264  		// aliases, thus we cannot solely rely on the x == y check
   265  		// above. See also comment in TypeName.IsAlias.
   266  		if y, ok := y.(*Basic); ok {
   267  			return x.kind == y.kind
   268  		}
   269  
   270  	case *Array:
   271  		// Two array types are identical if they have identical element types
   272  		// and the same array length.
   273  		if y, ok := y.(*Array); ok {
   274  			// If one or both array lengths are unknown (< 0) due to some error,
   275  			// assume they are the same to avoid spurious follow-on errors.
   276  			return (x.len < 0 || y.len < 0 || x.len == y.len) && c.identical(x.elem, y.elem, p)
   277  		}
   278  
   279  	case *Slice:
   280  		// Two slice types are identical if they have identical element types.
   281  		if y, ok := y.(*Slice); ok {
   282  			return c.identical(x.elem, y.elem, p)
   283  		}
   284  
   285  	case *Struct:
   286  		// Two struct types are identical if they have the same sequence of fields,
   287  		// and if corresponding fields have the same names, and identical types,
   288  		// and identical tags. Two embedded fields are considered to have the same
   289  		// name. Lower-case field names from different packages are always different.
   290  		if y, ok := y.(*Struct); ok {
   291  			if x.NumFields() == y.NumFields() {
   292  				for i, f := range x.fields {
   293  					g := y.fields[i]
   294  					if f.embedded != g.embedded ||
   295  						!c.ignoreTags && x.Tag(i) != y.Tag(i) ||
   296  						!f.sameId(g.pkg, g.name, false) ||
   297  						!c.identical(f.typ, g.typ, p) {
   298  						return false
   299  					}
   300  				}
   301  				return true
   302  			}
   303  		}
   304  
   305  	case *Pointer:
   306  		// Two pointer types are identical if they have identical base types.
   307  		if y, ok := y.(*Pointer); ok {
   308  			return c.identical(x.base, y.base, p)
   309  		}
   310  
   311  	case *Tuple:
   312  		// Two tuples types are identical if they have the same number of elements
   313  		// and corresponding elements have identical types.
   314  		if y, ok := y.(*Tuple); ok {
   315  			if x.Len() == y.Len() {
   316  				if x != nil {
   317  					for i, v := range x.vars {
   318  						w := y.vars[i]
   319  						if !c.identical(v.typ, w.typ, p) {
   320  							return false
   321  						}
   322  					}
   323  				}
   324  				return true
   325  			}
   326  		}
   327  
   328  	case *Signature:
   329  		y, _ := y.(*Signature)
   330  		if y == nil {
   331  			return false
   332  		}
   333  
   334  		// Two function types are identical if they have the same number of
   335  		// parameters and result values, corresponding parameter and result types
   336  		// are identical, and either both functions are variadic or neither is.
   337  		// Parameter and result names are not required to match, and type
   338  		// parameters are considered identical modulo renaming.
   339  
   340  		if x.TypeParams().Len() != y.TypeParams().Len() {
   341  			return false
   342  		}
   343  
   344  		// In the case of generic signatures, we will substitute in yparams and
   345  		// yresults.
   346  		yparams := y.params
   347  		yresults := y.results
   348  
   349  		if x.TypeParams().Len() > 0 {
   350  			// We must ignore type parameter names when comparing x and y. The
   351  			// easiest way to do this is to substitute x's type parameters for y's.
   352  			xtparams := x.TypeParams().list()
   353  			ytparams := y.TypeParams().list()
   354  
   355  			var targs []Type
   356  			for i := range xtparams {
   357  				targs = append(targs, x.TypeParams().At(i))
   358  			}
   359  			smap := makeSubstMap(ytparams, targs)
   360  
   361  			var check *Checker   // ok to call subst on a nil *Checker
   362  			ctxt := NewContext() // need a non-nil Context for the substitution below
   363  
   364  			// Constraints must be pair-wise identical, after substitution.
   365  			for i, xtparam := range xtparams {
   366  				ybound := check.subst(nopos, ytparams[i].bound, smap, nil, ctxt)
   367  				if !c.identical(xtparam.bound, ybound, p) {
   368  					return false
   369  				}
   370  			}
   371  
   372  			yparams = check.subst(nopos, y.params, smap, nil, ctxt).(*Tuple)
   373  			yresults = check.subst(nopos, y.results, smap, nil, ctxt).(*Tuple)
   374  		}
   375  
   376  		return x.variadic == y.variadic &&
   377  			c.identical(x.params, yparams, p) &&
   378  			c.identical(x.results, yresults, p)
   379  
   380  	case *Union:
   381  		if y, _ := y.(*Union); y != nil {
   382  			// TODO(rfindley): can this be reached during type checking? If so,
   383  			// consider passing a type set map.
   384  			unionSets := make(map[*Union]*_TypeSet)
   385  			xset := computeUnionTypeSet(nil, unionSets, nopos, x)
   386  			yset := computeUnionTypeSet(nil, unionSets, nopos, y)
   387  			return xset.terms.equal(yset.terms)
   388  		}
   389  
   390  	case *Interface:
   391  		// Two interface types are identical if they describe the same type sets.
   392  		// With the existing implementation restriction, this simplifies to:
   393  		//
   394  		// Two interface types are identical if they have the same set of methods with
   395  		// the same names and identical function types, and if any type restrictions
   396  		// are the same. Lower-case method names from different packages are always
   397  		// different. The order of the methods is irrelevant.
   398  		if y, ok := y.(*Interface); ok {
   399  			xset := x.typeSet()
   400  			yset := y.typeSet()
   401  			if xset.comparable != yset.comparable {
   402  				return false
   403  			}
   404  			if !xset.terms.equal(yset.terms) {
   405  				return false
   406  			}
   407  			a := xset.methods
   408  			b := yset.methods
   409  			if len(a) == len(b) {
   410  				// Interface types are the only types where cycles can occur
   411  				// that are not "terminated" via named types; and such cycles
   412  				// can only be created via method parameter types that are
   413  				// anonymous interfaces (directly or indirectly) embedding
   414  				// the current interface. Example:
   415  				//
   416  				//    type T interface {
   417  				//        m() interface{T}
   418  				//    }
   419  				//
   420  				// If two such (differently named) interfaces are compared,
   421  				// endless recursion occurs if the cycle is not detected.
   422  				//
   423  				// If x and y were compared before, they must be equal
   424  				// (if they were not, the recursion would have stopped);
   425  				// search the ifacePair stack for the same pair.
   426  				//
   427  				// This is a quadratic algorithm, but in practice these stacks
   428  				// are extremely short (bounded by the nesting depth of interface
   429  				// type declarations that recur via parameter types, an extremely
   430  				// rare occurrence). An alternative implementation might use a
   431  				// "visited" map, but that is probably less efficient overall.
   432  				q := &ifacePair{x, y, p}
   433  				for p != nil {
   434  					if p.identical(q) {
   435  						return true // same pair was compared before
   436  					}
   437  					p = p.prev
   438  				}
   439  				if debug {
   440  					assertSortedMethods(a)
   441  					assertSortedMethods(b)
   442  				}
   443  				for i, f := range a {
   444  					g := b[i]
   445  					if f.Id() != g.Id() || !c.identical(f.typ, g.typ, q) {
   446  						return false
   447  					}
   448  				}
   449  				return true
   450  			}
   451  		}
   452  
   453  	case *Map:
   454  		// Two map types are identical if they have identical key and value types.
   455  		if y, ok := y.(*Map); ok {
   456  			return c.identical(x.key, y.key, p) && c.identical(x.elem, y.elem, p)
   457  		}
   458  
   459  	case *Chan:
   460  		// Two channel types are identical if they have identical value types
   461  		// and the same direction.
   462  		if y, ok := y.(*Chan); ok {
   463  			return x.dir == y.dir && c.identical(x.elem, y.elem, p)
   464  		}
   465  
   466  	case *Named:
   467  		// Two named types are identical if their type names originate
   468  		// in the same type declaration; if they are instantiated they
   469  		// must have identical type argument lists.
   470  		if y := asNamed(y); y != nil {
   471  			// check type arguments before origins to match unifier
   472  			// (for correct source code we need to do all checks so
   473  			// order doesn't matter)
   474  			xargs := x.TypeArgs().list()
   475  			yargs := y.TypeArgs().list()
   476  			if len(xargs) != len(yargs) {
   477  				return false
   478  			}
   479  			for i, xarg := range xargs {
   480  				if !Identical(xarg, yargs[i]) {
   481  					return false
   482  				}
   483  			}
   484  			return identicalOrigin(x, y)
   485  		}
   486  
   487  	case *TypeParam:
   488  		// nothing to do (x and y being equal is caught in the very beginning of this function)
   489  
   490  	case nil:
   491  		// avoid a crash in case of nil type
   492  
   493  	default:
   494  		panic("unreachable")
   495  	}
   496  
   497  	return false
   498  }
   499  
   500  // identicalOrigin reports whether x and y originated in the same declaration.
   501  func identicalOrigin(x, y *Named) bool {
   502  	// TODO(gri) is this correct?
   503  	return x.Origin().obj == y.Origin().obj
   504  }
   505  
   506  // identicalInstance reports if two type instantiations are identical.
   507  // Instantiations are identical if their origin and type arguments are
   508  // identical.
   509  func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool {
   510  	if len(xargs) != len(yargs) {
   511  		return false
   512  	}
   513  
   514  	for i, xa := range xargs {
   515  		if !Identical(xa, yargs[i]) {
   516  			return false
   517  		}
   518  	}
   519  
   520  	return Identical(xorig, yorig)
   521  }
   522  
   523  // Default returns the default "typed" type for an "untyped" type;
   524  // it returns the incoming type for all other types. The default type
   525  // for untyped nil is untyped nil.
   526  func Default(t Type) Type {
   527  	// Alias and named types cannot denote untyped types
   528  	// so there's no need to call Unalias or under, below.
   529  	if t, _ := t.(*Basic); t != nil {
   530  		switch t.kind {
   531  		case UntypedBool:
   532  			return Typ[Bool]
   533  		case UntypedInt:
   534  			return Typ[Int]
   535  		case UntypedRune:
   536  			return universeRune // use 'rune' name
   537  		case UntypedFloat:
   538  			return Typ[Float64]
   539  		case UntypedComplex:
   540  			return Typ[Complex128]
   541  		case UntypedString:
   542  			return Typ[String]
   543  		}
   544  	}
   545  	return t
   546  }
   547  
   548  // maxType returns the "largest" type that encompasses both x and y.
   549  // If x and y are different untyped numeric types, the result is the type of x or y
   550  // that appears later in this list: integer, rune, floating-point, complex.
   551  // Otherwise, if x != y, the result is nil.
   552  func maxType(x, y Type) Type {
   553  	// We only care about untyped types (for now), so == is good enough.
   554  	// TODO(gri) investigate generalizing this function to simplify code elsewhere
   555  	if x == y {
   556  		return x
   557  	}
   558  	if isUntypedNumeric(x) && isUntypedNumeric(y) {
   559  		// untyped types are basic types
   560  		if x.(*Basic).kind > y.(*Basic).kind {
   561  			return x
   562  		}
   563  		return y
   564  	}
   565  	return nil
   566  }
   567  
   568  // clone makes a "flat copy" of *p and returns a pointer to the copy.
   569  func clone[P *T, T any](p P) P {
   570  	c := *p
   571  	return &c
   572  }
   573  

View as plain text