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

View as plain text