Source file src/cmd/compile/internal/types2/predicates.go

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

View as plain text