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