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

     1  // Copyright 2021 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 instantiation of generic types
     6  // through substitution of type parameters by type arguments.
     7  
     8  package types2
     9  
    10  import (
    11  	"cmd/compile/internal/syntax"
    12  	"errors"
    13  	"fmt"
    14  	"internal/buildcfg"
    15  	. "internal/types/errors"
    16  )
    17  
    18  // A genericType implements access to its type parameters.
    19  type genericType interface {
    20  	Type
    21  	TypeParams() *TypeParamList
    22  }
    23  
    24  // Instantiate instantiates the type orig with the given type arguments targs.
    25  // orig must be an *Alias, *Named, or *Signature type. If there is no error,
    26  // the resulting Type is an instantiated type of the same kind (*Alias, *Named
    27  // or *Signature, respectively).
    28  //
    29  // Methods attached to a *Named type are also instantiated, and associated with
    30  // a new *Func that has the same position as the original method, but nil function
    31  // scope.
    32  //
    33  // If ctxt is non-nil, it may be used to de-duplicate the instance against
    34  // previous instances with the same identity. As a special case, generic
    35  // *Signature origin types are only considered identical if they are pointer
    36  // equivalent, so that instantiating distinct (but possibly identical)
    37  // signatures will yield different instances. The use of a shared context does
    38  // not guarantee that identical instances are deduplicated in all cases.
    39  //
    40  // If validate is set, Instantiate verifies that the number of type arguments
    41  // and parameters match, and that the type arguments satisfy their respective
    42  // type constraints. If verification fails, the resulting error may wrap an
    43  // *ArgumentError indicating which type argument did not satisfy its type parameter
    44  // constraint, and why.
    45  //
    46  // If validate is not set, Instantiate does not verify the type argument count
    47  // or whether the type arguments satisfy their constraints. Instantiate is
    48  // guaranteed to not return an error, but may panic. Specifically, for
    49  // *Signature types, Instantiate will panic immediately if the type argument
    50  // count is incorrect; for *Named types, a panic may occur later inside the
    51  // *Named API.
    52  func Instantiate(ctxt *Context, orig Type, targs []Type, validate bool) (Type, error) {
    53  	assert(len(targs) > 0)
    54  	if ctxt == nil {
    55  		ctxt = NewContext()
    56  	}
    57  	orig_ := orig.(genericType) // signature of Instantiate must not change for backward-compatibility
    58  
    59  	if validate {
    60  		tparams := orig_.TypeParams().list()
    61  		assert(len(tparams) > 0)
    62  		if len(targs) != len(tparams) {
    63  			return nil, fmt.Errorf("got %d type arguments but %s has %d type parameters", len(targs), orig, len(tparams))
    64  		}
    65  		if i, err := (*Checker)(nil).verify(nopos, tparams, targs, ctxt); err != nil {
    66  			return nil, &ArgumentError{i, err}
    67  		}
    68  	}
    69  
    70  	inst := (*Checker)(nil).instance(nopos, orig_, targs, nil, ctxt)
    71  	return inst, nil
    72  }
    73  
    74  // instance instantiates the given original (generic) function or type with the
    75  // provided type arguments and returns the resulting instance. If an identical
    76  // instance exists already in the given contexts, it returns that instance,
    77  // otherwise it creates a new one.
    78  //
    79  // If expanding is non-nil, it is the Named instance type currently being
    80  // expanded. If ctxt is non-nil, it is the context associated with the current
    81  // type-checking pass or call to Instantiate. At least one of expanding or ctxt
    82  // must be non-nil.
    83  //
    84  // For Named types the resulting instance may be unexpanded.
    85  //
    86  // check may be nil (when not type-checking syntax); pos is used only only if check is non-nil.
    87  func (check *Checker) instance(pos syntax.Pos, orig genericType, targs []Type, expanding *Named, ctxt *Context) (res Type) {
    88  	// The order of the contexts below matters: we always prefer instances in the
    89  	// expanding instance context in order to preserve reference cycles.
    90  	//
    91  	// Invariant: if expanding != nil, the returned instance will be the instance
    92  	// recorded in expanding.inst.ctxt.
    93  	var ctxts []*Context
    94  	if expanding != nil {
    95  		ctxts = append(ctxts, expanding.inst.ctxt)
    96  	}
    97  	if ctxt != nil {
    98  		ctxts = append(ctxts, ctxt)
    99  	}
   100  	assert(len(ctxts) > 0)
   101  
   102  	// Compute all hashes; hashes may differ across contexts due to different
   103  	// unique IDs for Named types within the hasher.
   104  	hashes := make([]string, len(ctxts))
   105  	for i, ctxt := range ctxts {
   106  		hashes[i] = ctxt.instanceHash(orig, targs)
   107  	}
   108  
   109  	// Record the result in all contexts.
   110  	// Prefer to re-use existing types from expanding context, if it exists, to reduce
   111  	// the memory pinned by the Named type.
   112  	updateContexts := func(res Type) Type {
   113  		for i := len(ctxts) - 1; i >= 0; i-- {
   114  			res = ctxts[i].update(hashes[i], orig, targs, res)
   115  		}
   116  		return res
   117  	}
   118  
   119  	// typ may already have been instantiated with identical type arguments. In
   120  	// that case, re-use the existing instance.
   121  	for i, ctxt := range ctxts {
   122  		if inst := ctxt.lookup(hashes[i], orig, targs); inst != nil {
   123  			return updateContexts(inst)
   124  		}
   125  	}
   126  
   127  	switch orig := orig.(type) {
   128  	case *Named:
   129  		res = check.newNamedInstance(pos, orig, targs, expanding) // substituted lazily
   130  
   131  	case *Alias:
   132  		if !buildcfg.Experiment.AliasTypeParams {
   133  			assert(expanding == nil) // Alias instances cannot be reached from Named types
   134  		}
   135  
   136  		tparams := orig.TypeParams()
   137  		// TODO(gri) investigate if this is needed (type argument and parameter count seem to be correct here)
   138  		if !check.validateTArgLen(pos, orig.String(), tparams.Len(), len(targs)) {
   139  			return Typ[Invalid]
   140  		}
   141  		if tparams.Len() == 0 {
   142  			return orig // nothing to do (minor optimization)
   143  		}
   144  
   145  		res = check.newAliasInstance(pos, orig, targs, expanding, ctxt)
   146  
   147  	case *Signature:
   148  		assert(expanding == nil) // function instances cannot be reached from Named types
   149  
   150  		tparams := orig.TypeParams()
   151  		// TODO(gri) investigate if this is needed (type argument and parameter count seem to be correct here)
   152  		if !check.validateTArgLen(pos, orig.String(), tparams.Len(), len(targs)) {
   153  			return Typ[Invalid]
   154  		}
   155  		if tparams.Len() == 0 {
   156  			return orig // nothing to do (minor optimization)
   157  		}
   158  		sig := check.subst(pos, orig, makeSubstMap(tparams.list(), targs), nil, ctxt).(*Signature)
   159  		// If the signature doesn't use its type parameters, subst
   160  		// will not make a copy. In that case, make a copy now (so
   161  		// we can set tparams to nil w/o causing side-effects).
   162  		if sig == orig {
   163  			copy := *sig
   164  			sig = &copy
   165  		}
   166  		// After instantiating a generic signature, it is not generic
   167  		// anymore; we need to set tparams to nil.
   168  		sig.tparams = nil
   169  		res = sig
   170  
   171  	default:
   172  		// only types and functions can be generic
   173  		panic(fmt.Sprintf("%v: cannot instantiate %v", pos, orig))
   174  	}
   175  
   176  	// Update all contexts; it's possible that we've lost a race.
   177  	return updateContexts(res)
   178  }
   179  
   180  // validateTArgLen checks that the number of type arguments (got) matches the
   181  // number of type parameters (want); if they don't match an error is reported.
   182  // If validation fails and check is nil, validateTArgLen panics.
   183  func (check *Checker) validateTArgLen(pos syntax.Pos, name string, want, got int) bool {
   184  	var qual string
   185  	switch {
   186  	case got < want:
   187  		qual = "not enough"
   188  	case got > want:
   189  		qual = "too many"
   190  	default:
   191  		return true
   192  	}
   193  
   194  	msg := check.sprintf("%s type arguments for type %s: have %d, want %d", qual, name, got, want)
   195  	if check != nil {
   196  		check.error(atPos(pos), WrongTypeArgCount, msg)
   197  		return false
   198  	}
   199  
   200  	panic(fmt.Sprintf("%v: %s", pos, msg))
   201  }
   202  
   203  // check may be nil; pos is used only if check is non-nil.
   204  func (check *Checker) verify(pos syntax.Pos, tparams []*TypeParam, targs []Type, ctxt *Context) (int, error) {
   205  	smap := makeSubstMap(tparams, targs)
   206  	for i, tpar := range tparams {
   207  		// Ensure that we have a (possibly implicit) interface as type bound (go.dev/issue/51048).
   208  		tpar.iface()
   209  		// The type parameter bound is parameterized with the same type parameters
   210  		// as the instantiated type; before we can use it for bounds checking we
   211  		// need to instantiate it with the type arguments with which we instantiated
   212  		// the parameterized type.
   213  		bound := check.subst(pos, tpar.bound, smap, nil, ctxt)
   214  		var cause string
   215  		if !check.implements(targs[i], bound, true, &cause) {
   216  			return i, errors.New(cause)
   217  		}
   218  	}
   219  	return -1, nil
   220  }
   221  
   222  // implements checks if V implements T. The receiver may be nil if implements
   223  // is called through an exported API call such as AssignableTo. If constraint
   224  // is set, T is a type constraint.
   225  //
   226  // If the provided cause is non-nil, it may be set to an error string
   227  // explaining why V does not implement (or satisfy, for constraints) T.
   228  func (check *Checker) implements(V, T Type, constraint bool, cause *string) bool {
   229  	Vu := under(V)
   230  	Tu := under(T)
   231  	if !isValid(Vu) || !isValid(Tu) {
   232  		return true // avoid follow-on errors
   233  	}
   234  	if p, _ := Vu.(*Pointer); p != nil && !isValid(under(p.base)) {
   235  		return true // avoid follow-on errors (see go.dev/issue/49541 for an example)
   236  	}
   237  
   238  	verb := "implement"
   239  	if constraint {
   240  		verb = "satisfy"
   241  	}
   242  
   243  	Ti, _ := Tu.(*Interface)
   244  	if Ti == nil {
   245  		if cause != nil {
   246  			var detail string
   247  			if isInterfacePtr(Tu) {
   248  				detail = check.sprintf("type %s is pointer to interface, not interface", T)
   249  			} else {
   250  				detail = check.sprintf("%s is not an interface", T)
   251  			}
   252  			*cause = check.sprintf("%s does not %s %s (%s)", V, verb, T, detail)
   253  		}
   254  		return false
   255  	}
   256  
   257  	// Every type satisfies the empty interface.
   258  	if Ti.Empty() {
   259  		return true
   260  	}
   261  	// T is not the empty interface (i.e., the type set of T is restricted)
   262  
   263  	// An interface V with an empty type set satisfies any interface.
   264  	// (The empty set is a subset of any set.)
   265  	Vi, _ := Vu.(*Interface)
   266  	if Vi != nil && Vi.typeSet().IsEmpty() {
   267  		return true
   268  	}
   269  	// type set of V is not empty
   270  
   271  	// No type with non-empty type set satisfies the empty type set.
   272  	if Ti.typeSet().IsEmpty() {
   273  		if cause != nil {
   274  			*cause = check.sprintf("cannot %s %s (empty type set)", verb, T)
   275  		}
   276  		return false
   277  	}
   278  
   279  	// V must implement T's methods, if any.
   280  	if !check.hasAllMethods(V, T, true, Identical, cause) /* !Implements(V, T) */ {
   281  		if cause != nil {
   282  			*cause = check.sprintf("%s does not %s %s %s", V, verb, T, *cause)
   283  		}
   284  		return false
   285  	}
   286  
   287  	// Only check comparability if we don't have a more specific error.
   288  	checkComparability := func() bool {
   289  		if !Ti.IsComparable() {
   290  			return true
   291  		}
   292  		// If T is comparable, V must be comparable.
   293  		// If V is strictly comparable, we're done.
   294  		if comparableType(V, false /* strict comparability */, nil, nil) {
   295  			return true
   296  		}
   297  		// For constraint satisfaction, use dynamic (spec) comparability
   298  		// so that ordinary, non-type parameter interfaces implement comparable.
   299  		if constraint && comparableType(V, true /* spec comparability */, nil, nil) {
   300  			// V is comparable if we are at Go 1.20 or higher.
   301  			if check == nil || check.allowVersion(go1_20) {
   302  				return true
   303  			}
   304  			if cause != nil {
   305  				*cause = check.sprintf("%s to %s comparable requires go1.20 or later", V, verb)
   306  			}
   307  			return false
   308  		}
   309  		if cause != nil {
   310  			*cause = check.sprintf("%s does not %s comparable", V, verb)
   311  		}
   312  		return false
   313  	}
   314  
   315  	// V must also be in the set of types of T, if any.
   316  	// Constraints with empty type sets were already excluded above.
   317  	if !Ti.typeSet().hasTerms() {
   318  		return checkComparability() // nothing to do
   319  	}
   320  
   321  	// If V is itself an interface, each of its possible types must be in the set
   322  	// of T types (i.e., the V type set must be a subset of the T type set).
   323  	// Interfaces V with empty type sets were already excluded above.
   324  	if Vi != nil {
   325  		if !Vi.typeSet().subsetOf(Ti.typeSet()) {
   326  			// TODO(gri) report which type is missing
   327  			if cause != nil {
   328  				*cause = check.sprintf("%s does not %s %s", V, verb, T)
   329  			}
   330  			return false
   331  		}
   332  		return checkComparability()
   333  	}
   334  
   335  	// Otherwise, V's type must be included in the iface type set.
   336  	var alt Type
   337  	if Ti.typeSet().is(func(t *term) bool {
   338  		if !t.includes(V) {
   339  			// If V ∉ t.typ but V ∈ ~t.typ then remember this type
   340  			// so we can suggest it as an alternative in the error
   341  			// message.
   342  			if alt == nil && !t.tilde && Identical(t.typ, under(t.typ)) {
   343  				tt := *t
   344  				tt.tilde = true
   345  				if tt.includes(V) {
   346  					alt = t.typ
   347  				}
   348  			}
   349  			return true
   350  		}
   351  		return false
   352  	}) {
   353  		if cause != nil {
   354  			var detail string
   355  			switch {
   356  			case alt != nil:
   357  				detail = check.sprintf("possibly missing ~ for %s in %s", alt, T)
   358  			case mentions(Ti, V):
   359  				detail = check.sprintf("%s mentions %s, but %s is not in the type set of %s", T, V, V, T)
   360  			default:
   361  				detail = check.sprintf("%s missing in %s", V, Ti.typeSet().terms)
   362  			}
   363  			*cause = check.sprintf("%s does not %s %s (%s)", V, verb, T, detail)
   364  		}
   365  		return false
   366  	}
   367  
   368  	return checkComparability()
   369  }
   370  
   371  // mentions reports whether type T "mentions" typ in an (embedded) element or term
   372  // of T (whether typ is in the type set of T or not). For better error messages.
   373  func mentions(T, typ Type) bool {
   374  	switch T := T.(type) {
   375  	case *Interface:
   376  		for _, e := range T.embeddeds {
   377  			if mentions(e, typ) {
   378  				return true
   379  			}
   380  		}
   381  	case *Union:
   382  		for _, t := range T.terms {
   383  			if mentions(t.typ, typ) {
   384  				return true
   385  			}
   386  		}
   387  	default:
   388  		if Identical(T, typ) {
   389  			return true
   390  		}
   391  	}
   392  	return false
   393  }
   394  

View as plain text