Source file src/go/types/instantiate.go

     1  // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
     2  // Source: ../../cmd/compile/internal/types2/instantiate.go
     3  
     4  // Copyright 2021 The Go Authors. All rights reserved.
     5  // Use of this source code is governed by a BSD-style
     6  // license that can be found in the LICENSE file.
     7  
     8  // This file implements instantiation of generic types
     9  // through substitution of type parameters by type arguments.
    10  
    11  package types
    12  
    13  import (
    14  	"errors"
    15  	"fmt"
    16  	"go/token"
    17  	"internal/buildcfg"
    18  	. "internal/types/errors"
    19  )
    20  
    21  // A genericType implements access to its type parameters.
    22  type genericType interface {
    23  	Type
    24  	TypeParams() *TypeParamList
    25  }
    26  
    27  // Instantiate instantiates the type orig with the given type arguments targs.
    28  // orig must be an *Alias, *Named, or *Signature type. If there is no error,
    29  // the resulting Type is an instantiated type of the same kind (*Alias, *Named
    30  // or *Signature, respectively).
    31  //
    32  // Methods attached to a *Named type are also instantiated, and associated with
    33  // a new *Func that has the same position as the original method, but nil function
    34  // scope.
    35  //
    36  // If ctxt is non-nil, it may be used to de-duplicate the instance against
    37  // previous instances with the same identity. As a special case, generic
    38  // *Signature origin types are only considered identical if they are pointer
    39  // equivalent, so that instantiating distinct (but possibly identical)
    40  // signatures will yield different instances. The use of a shared context does
    41  // not guarantee that identical instances are deduplicated in all cases.
    42  //
    43  // If validate is set, Instantiate verifies that the number of type arguments
    44  // and parameters match, and that the type arguments satisfy their respective
    45  // type constraints. If verification fails, the resulting error may wrap an
    46  // *ArgumentError indicating which type argument did not satisfy its type parameter
    47  // constraint, and why.
    48  //
    49  // If validate is not set, Instantiate does not verify the type argument count
    50  // or whether the type arguments satisfy their constraints. Instantiate is
    51  // guaranteed to not return an error, but may panic. Specifically, for
    52  // *Signature types, Instantiate will panic immediately if the type argument
    53  // count is incorrect; for *Named types, a panic may occur later inside the
    54  // *Named API.
    55  func Instantiate(ctxt *Context, orig Type, targs []Type, validate bool) (Type, error) {
    56  	assert(len(targs) > 0)
    57  	if ctxt == nil {
    58  		ctxt = NewContext()
    59  	}
    60  	orig_ := orig.(genericType) // signature of Instantiate must not change for backward-compatibility
    61  
    62  	if validate {
    63  		tparams := orig_.TypeParams().list()
    64  		assert(len(tparams) > 0)
    65  		if len(targs) != len(tparams) {
    66  			return nil, fmt.Errorf("got %d type arguments but %s has %d type parameters", len(targs), orig, len(tparams))
    67  		}
    68  		if i, err := (*Checker)(nil).verify(nopos, tparams, targs, ctxt); err != nil {
    69  			return nil, &ArgumentError{i, err}
    70  		}
    71  	}
    72  
    73  	inst := (*Checker)(nil).instance(nopos, orig_, targs, nil, ctxt)
    74  	return inst, nil
    75  }
    76  
    77  // instance instantiates the given original (generic) function or type with the
    78  // provided type arguments and returns the resulting instance. If an identical
    79  // instance exists already in the given contexts, it returns that instance,
    80  // otherwise it creates a new one.
    81  //
    82  // If expanding is non-nil, it is the Named instance type currently being
    83  // expanded. If ctxt is non-nil, it is the context associated with the current
    84  // type-checking pass or call to Instantiate. At least one of expanding or ctxt
    85  // must be non-nil.
    86  //
    87  // For Named types the resulting instance may be unexpanded.
    88  func (check *Checker) instance(pos token.Pos, orig genericType, targs []Type, expanding *Named, ctxt *Context) (res Type) {
    89  	// The order of the contexts below matters: we always prefer instances in the
    90  	// expanding instance context in order to preserve reference cycles.
    91  	//
    92  	// Invariant: if expanding != nil, the returned instance will be the instance
    93  	// recorded in expanding.inst.ctxt.
    94  	var ctxts []*Context
    95  	if expanding != nil {
    96  		ctxts = append(ctxts, expanding.inst.ctxt)
    97  	}
    98  	if ctxt != nil {
    99  		ctxts = append(ctxts, ctxt)
   100  	}
   101  	assert(len(ctxts) > 0)
   102  
   103  	// Compute all hashes; hashes may differ across contexts due to different
   104  	// unique IDs for Named types within the hasher.
   105  	hashes := make([]string, len(ctxts))
   106  	for i, ctxt := range ctxts {
   107  		hashes[i] = ctxt.instanceHash(orig, targs)
   108  	}
   109  
   110  	// Record the result in all contexts.
   111  	// Prefer to re-use existing types from expanding context, if it exists, to reduce
   112  	// the memory pinned by the Named type.
   113  	updateContexts := func(res Type) Type {
   114  		for i := len(ctxts) - 1; i >= 0; i-- {
   115  			res = ctxts[i].update(hashes[i], orig, targs, res)
   116  		}
   117  		return res
   118  	}
   119  
   120  	// typ may already have been instantiated with identical type arguments. In
   121  	// that case, re-use the existing instance.
   122  	for i, ctxt := range ctxts {
   123  		if inst := ctxt.lookup(hashes[i], orig, targs); inst != nil {
   124  			return updateContexts(inst)
   125  		}
   126  	}
   127  
   128  	switch orig := orig.(type) {
   129  	case *Named:
   130  		res = check.newNamedInstance(pos, orig, targs, expanding) // substituted lazily
   131  
   132  	case *Alias:
   133  		if !buildcfg.Experiment.AliasTypeParams {
   134  			assert(expanding == nil) // Alias instances cannot be reached from Named types
   135  		}
   136  
   137  		tparams := orig.TypeParams()
   138  		// TODO(gri) investigate if this is needed (type argument and parameter count seem to be correct here)
   139  		if !check.validateTArgLen(pos, orig.String(), tparams.Len(), len(targs)) {
   140  			return Typ[Invalid]
   141  		}
   142  		if tparams.Len() == 0 {
   143  			return orig // nothing to do (minor optimization)
   144  		}
   145  
   146  		return check.newAliasInstance(pos, orig, targs, expanding, ctxt)
   147  
   148  	case *Signature:
   149  		assert(expanding == nil) // function instances cannot be reached from Named types
   150  
   151  		tparams := orig.TypeParams()
   152  		// TODO(gri) investigate if this is needed (type argument and parameter count seem to be correct here)
   153  		if !check.validateTArgLen(pos, orig.String(), tparams.Len(), len(targs)) {
   154  			return Typ[Invalid]
   155  		}
   156  		if tparams.Len() == 0 {
   157  			return orig // nothing to do (minor optimization)
   158  		}
   159  		sig := check.subst(pos, orig, makeSubstMap(tparams.list(), targs), nil, ctxt).(*Signature)
   160  		// If the signature doesn't use its type parameters, subst
   161  		// will not make a copy. In that case, make a copy now (so
   162  		// we can set tparams to nil w/o causing side-effects).
   163  		if sig == orig {
   164  			copy := *sig
   165  			sig = &copy
   166  		}
   167  		// After instantiating a generic signature, it is not generic
   168  		// anymore; we need to set tparams to nil.
   169  		sig.tparams = nil
   170  		res = sig
   171  
   172  	default:
   173  		// only types and functions can be generic
   174  		panic(fmt.Sprintf("%v: cannot instantiate %v", pos, orig))
   175  	}
   176  
   177  	// Update all contexts; it's possible that we've lost a race.
   178  	return updateContexts(res)
   179  }
   180  
   181  // validateTArgLen checks that the number of type arguments (got) matches the
   182  // number of type parameters (want); if they don't match an error is reported.
   183  // If validation fails and check is nil, validateTArgLen panics.
   184  func (check *Checker) validateTArgLen(pos token.Pos, name string, want, got int) bool {
   185  	var qual string
   186  	switch {
   187  	case got < want:
   188  		qual = "not enough"
   189  	case got > want:
   190  		qual = "too many"
   191  	default:
   192  		return true
   193  	}
   194  
   195  	msg := check.sprintf("%s type arguments for type %s: have %d, want %d", qual, name, got, want)
   196  	if check != nil {
   197  		check.error(atPos(pos), WrongTypeArgCount, msg)
   198  		return false
   199  	}
   200  
   201  	panic(fmt.Sprintf("%v: %s", pos, msg))
   202  }
   203  
   204  func (check *Checker) verify(pos token.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(pos, 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(pos token.Pos, 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 m, _ := check.missingMethod(V, T, true, Identical, cause); m != nil /* !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 comparable(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 && comparable(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(atPos(pos), go1_20) { // atPos needed so that go/types generate passes
   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