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

View as plain text