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  func (check *Checker) instance(pos syntax.Pos, orig genericType, targs []Type, expanding *Named, ctxt *Context) (res Type) {
    86  	// The order of the contexts below matters: we always prefer instances in the
    87  	// expanding instance context in order to preserve reference cycles.
    88  	//
    89  	// Invariant: if expanding != nil, the returned instance will be the instance
    90  	// recorded in expanding.inst.ctxt.
    91  	var ctxts []*Context
    92  	if expanding != nil {
    93  		ctxts = append(ctxts, expanding.inst.ctxt)
    94  	}
    95  	if ctxt != nil {
    96  		ctxts = append(ctxts, ctxt)
    97  	}
    98  	assert(len(ctxts) > 0)
    99  
   100  	// Compute all hashes; hashes may differ across contexts due to different
   101  	// unique IDs for Named types within the hasher.
   102  	hashes := make([]string, len(ctxts))
   103  	for i, ctxt := range ctxts {
   104  		hashes[i] = ctxt.instanceHash(orig, targs)
   105  	}
   106  
   107  	// Record the result in all contexts.
   108  	// Prefer to re-use existing types from expanding context, if it exists, to reduce
   109  	// the memory pinned by the Named type.
   110  	updateContexts := func(res Type) Type {
   111  		for i := len(ctxts) - 1; i >= 0; i-- {
   112  			res = ctxts[i].update(hashes[i], orig, targs, res)
   113  		}
   114  		return res
   115  	}
   116  
   117  	// typ may already have been instantiated with identical type arguments. In
   118  	// that case, re-use the existing instance.
   119  	for i, ctxt := range ctxts {
   120  		if inst := ctxt.lookup(hashes[i], orig, targs); inst != nil {
   121  			return updateContexts(inst)
   122  		}
   123  	}
   124  
   125  	switch orig := orig.(type) {
   126  	case *Named:
   127  		res = check.newNamedInstance(pos, orig, targs, expanding) // substituted lazily
   128  
   129  	case *Alias:
   130  		if !buildcfg.Experiment.AliasTypeParams {
   131  			assert(expanding == nil) // Alias instances cannot be reached from Named types
   132  		}
   133  
   134  		tparams := orig.TypeParams()
   135  		// TODO(gri) investigate if this is needed (type argument and parameter count seem to be correct here)
   136  		if !check.validateTArgLen(pos, orig.String(), tparams.Len(), len(targs)) {
   137  			return Typ[Invalid]
   138  		}
   139  		if tparams.Len() == 0 {
   140  			return orig // nothing to do (minor optimization)
   141  		}
   142  
   143  		return check.newAliasInstance(pos, orig, targs, expanding, ctxt)
   144  
   145  	case *Signature:
   146  		assert(expanding == nil) // function instances cannot be reached from Named types
   147  
   148  		tparams := orig.TypeParams()
   149  		// TODO(gri) investigate if this is needed (type argument and parameter count seem to be correct here)
   150  		if !check.validateTArgLen(pos, orig.String(), tparams.Len(), len(targs)) {
   151  			return Typ[Invalid]
   152  		}
   153  		if tparams.Len() == 0 {
   154  			return orig // nothing to do (minor optimization)
   155  		}
   156  		sig := check.subst(pos, orig, makeSubstMap(tparams.list(), targs), nil, ctxt).(*Signature)
   157  		// If the signature doesn't use its type parameters, subst
   158  		// will not make a copy. In that case, make a copy now (so
   159  		// we can set tparams to nil w/o causing side-effects).
   160  		if sig == orig {
   161  			copy := *sig
   162  			sig = &copy
   163  		}
   164  		// After instantiating a generic signature, it is not generic
   165  		// anymore; we need to set tparams to nil.
   166  		sig.tparams = nil
   167  		res = sig
   168  
   169  	default:
   170  		// only types and functions can be generic
   171  		panic(fmt.Sprintf("%v: cannot instantiate %v", pos, orig))
   172  	}
   173  
   174  	// Update all contexts; it's possible that we've lost a race.
   175  	return updateContexts(res)
   176  }
   177  
   178  // validateTArgLen checks that the number of type arguments (got) matches the
   179  // number of type parameters (want); if they don't match an error is reported.
   180  // If validation fails and check is nil, validateTArgLen panics.
   181  func (check *Checker) validateTArgLen(pos syntax.Pos, name string, want, got int) bool {
   182  	var qual string
   183  	switch {
   184  	case got < want:
   185  		qual = "not enough"
   186  	case got > want:
   187  		qual = "too many"
   188  	default:
   189  		return true
   190  	}
   191  
   192  	msg := check.sprintf("%s type arguments for type %s: have %d, want %d", qual, name, got, want)
   193  	if check != nil {
   194  		check.error(atPos(pos), WrongTypeArgCount, msg)
   195  		return false
   196  	}
   197  
   198  	panic(fmt.Sprintf("%v: %s", pos, msg))
   199  }
   200  
   201  func (check *Checker) verify(pos syntax.Pos, tparams []*TypeParam, targs []Type, ctxt *Context) (int, error) {
   202  	smap := makeSubstMap(tparams, targs)
   203  	for i, tpar := range tparams {
   204  		// Ensure that we have a (possibly implicit) interface as type bound (go.dev/issue/51048).
   205  		tpar.iface()
   206  		// The type parameter bound is parameterized with the same type parameters
   207  		// as the instantiated type; before we can use it for bounds checking we
   208  		// need to instantiate it with the type arguments with which we instantiated
   209  		// the parameterized type.
   210  		bound := check.subst(pos, tpar.bound, smap, nil, ctxt)
   211  		var cause string
   212  		if !check.implements(pos, targs[i], bound, true, &cause) {
   213  			return i, errors.New(cause)
   214  		}
   215  	}
   216  	return -1, nil
   217  }
   218  
   219  // implements checks if V implements T. The receiver may be nil if implements
   220  // is called through an exported API call such as AssignableTo. If constraint
   221  // is set, T is a type constraint.
   222  //
   223  // If the provided cause is non-nil, it may be set to an error string
   224  // explaining why V does not implement (or satisfy, for constraints) T.
   225  func (check *Checker) implements(pos syntax.Pos, V, T Type, constraint bool, cause *string) bool {
   226  	Vu := under(V)
   227  	Tu := under(T)
   228  	if !isValid(Vu) || !isValid(Tu) {
   229  		return true // avoid follow-on errors
   230  	}
   231  	if p, _ := Vu.(*Pointer); p != nil && !isValid(under(p.base)) {
   232  		return true // avoid follow-on errors (see go.dev/issue/49541 for an example)
   233  	}
   234  
   235  	verb := "implement"
   236  	if constraint {
   237  		verb = "satisfy"
   238  	}
   239  
   240  	Ti, _ := Tu.(*Interface)
   241  	if Ti == nil {
   242  		if cause != nil {
   243  			var detail string
   244  			if isInterfacePtr(Tu) {
   245  				detail = check.sprintf("type %s is pointer to interface, not interface", T)
   246  			} else {
   247  				detail = check.sprintf("%s is not an interface", T)
   248  			}
   249  			*cause = check.sprintf("%s does not %s %s (%s)", V, verb, T, detail)
   250  		}
   251  		return false
   252  	}
   253  
   254  	// Every type satisfies the empty interface.
   255  	if Ti.Empty() {
   256  		return true
   257  	}
   258  	// T is not the empty interface (i.e., the type set of T is restricted)
   259  
   260  	// An interface V with an empty type set satisfies any interface.
   261  	// (The empty set is a subset of any set.)
   262  	Vi, _ := Vu.(*Interface)
   263  	if Vi != nil && Vi.typeSet().IsEmpty() {
   264  		return true
   265  	}
   266  	// type set of V is not empty
   267  
   268  	// No type with non-empty type set satisfies the empty type set.
   269  	if Ti.typeSet().IsEmpty() {
   270  		if cause != nil {
   271  			*cause = check.sprintf("cannot %s %s (empty type set)", verb, T)
   272  		}
   273  		return false
   274  	}
   275  
   276  	// V must implement T's methods, if any.
   277  	if m, _ := check.missingMethod(V, T, true, Identical, cause); m != nil /* !Implements(V, T) */ {
   278  		if cause != nil {
   279  			*cause = check.sprintf("%s does not %s %s %s", V, verb, T, *cause)
   280  		}
   281  		return false
   282  	}
   283  
   284  	// Only check comparability if we don't have a more specific error.
   285  	checkComparability := func() bool {
   286  		if !Ti.IsComparable() {
   287  			return true
   288  		}
   289  		// If T is comparable, V must be comparable.
   290  		// If V is strictly comparable, we're done.
   291  		if comparable(V, false /* strict comparability */, nil, nil) {
   292  			return true
   293  		}
   294  		// For constraint satisfaction, use dynamic (spec) comparability
   295  		// so that ordinary, non-type parameter interfaces implement comparable.
   296  		if constraint && comparable(V, true /* spec comparability */, nil, nil) {
   297  			// V is comparable if we are at Go 1.20 or higher.
   298  			if check == nil || check.allowVersion(atPos(pos), go1_20) { // atPos needed so that go/types generate passes
   299  				return true
   300  			}
   301  			if cause != nil {
   302  				*cause = check.sprintf("%s to %s comparable requires go1.20 or later", V, verb)
   303  			}
   304  			return false
   305  		}
   306  		if cause != nil {
   307  			*cause = check.sprintf("%s does not %s comparable", V, verb)
   308  		}
   309  		return false
   310  	}
   311  
   312  	// V must also be in the set of types of T, if any.
   313  	// Constraints with empty type sets were already excluded above.
   314  	if !Ti.typeSet().hasTerms() {
   315  		return checkComparability() // nothing to do
   316  	}
   317  
   318  	// If V is itself an interface, each of its possible types must be in the set
   319  	// of T types (i.e., the V type set must be a subset of the T type set).
   320  	// Interfaces V with empty type sets were already excluded above.
   321  	if Vi != nil {
   322  		if !Vi.typeSet().subsetOf(Ti.typeSet()) {
   323  			// TODO(gri) report which type is missing
   324  			if cause != nil {
   325  				*cause = check.sprintf("%s does not %s %s", V, verb, T)
   326  			}
   327  			return false
   328  		}
   329  		return checkComparability()
   330  	}
   331  
   332  	// Otherwise, V's type must be included in the iface type set.
   333  	var alt Type
   334  	if Ti.typeSet().is(func(t *term) bool {
   335  		if !t.includes(V) {
   336  			// If V ∉ t.typ but V ∈ ~t.typ then remember this type
   337  			// so we can suggest it as an alternative in the error
   338  			// message.
   339  			if alt == nil && !t.tilde && Identical(t.typ, under(t.typ)) {
   340  				tt := *t
   341  				tt.tilde = true
   342  				if tt.includes(V) {
   343  					alt = t.typ
   344  				}
   345  			}
   346  			return true
   347  		}
   348  		return false
   349  	}) {
   350  		if cause != nil {
   351  			var detail string
   352  			switch {
   353  			case alt != nil:
   354  				detail = check.sprintf("possibly missing ~ for %s in %s", alt, T)
   355  			case mentions(Ti, V):
   356  				detail = check.sprintf("%s mentions %s, but %s is not in the type set of %s", T, V, V, T)
   357  			default:
   358  				detail = check.sprintf("%s missing in %s", V, Ti.typeSet().terms)
   359  			}
   360  			*cause = check.sprintf("%s does not %s %s (%s)", V, verb, T, detail)
   361  		}
   362  		return false
   363  	}
   364  
   365  	return checkComparability()
   366  }
   367  
   368  // mentions reports whether type T "mentions" typ in an (embedded) element or term
   369  // of T (whether typ is in the type set of T or not). For better error messages.
   370  func mentions(T, typ Type) bool {
   371  	switch T := T.(type) {
   372  	case *Interface:
   373  		for _, e := range T.embeddeds {
   374  			if mentions(e, typ) {
   375  				return true
   376  			}
   377  		}
   378  	case *Union:
   379  		for _, t := range T.terms {
   380  			if mentions(t.typ, typ) {
   381  				return true
   382  			}
   383  		}
   384  	default:
   385  		if Identical(T, typ) {
   386  			return true
   387  		}
   388  	}
   389  	return false
   390  }
   391  

View as plain text