Debian Codegraph @

typeparams/example/README.md

raw symbols SCIP
1 <!-- Autogenerated by weave; DO NOT EDIT -->
2 <!-- To regenerate the readme, run: -->
3 <!-- go run golang.org/x/example/gotypes@latest generic-go-types.md -->
4
5 # Updating tools to support type parameters.
6
7 This guide is maintained by Rob Findley (`[email protected]`).
8
9 **status**: this document is currently a rough-draft. See [golang/go#50447](https://go.dev/issues/50447) for more details.
10
11 1. [Who should read this guide](#who-should-read-this-guide)
12 1. [Introduction](#introduction)
13 1. [Summary of new language features and their APIs](#summary-of-new-language-features-and-their-apis)
14 1. [Examples](#examples)
15 1. [Generic types: type parameters](#generic-types:-type-parameters)
16 1. [Constraint Interfaces](#constraint-interfaces)
17 1. [Instantiation](#instantiation)
18 1. [Generic types continued: method sets and predicates](#generic-types-continued:-method-sets-and-predicates)
19 1. [Updating tools while building at older Go versions](#updating-tools-while-building-at-older-go-versions)
20 1. [Further help](#further-help)
21
22 # Who should read this guide
23
24 Read this guide if you are a tool author seeking to update your tools to
25 support generics Go code. Generics introduce significant new complexity to the
26 Go type system, because types can now be _parameterized_. While the
27 fundamentals of the `go/types` APIs remain the same, some previously valid
28 assumptions no longer hold. For example:
29
30 - Type declarations need not correspond 1:1 with the types they define.
31 - Interfaces are no longer determined entirely by their method set.
32 - The set of concrete types implementing `types.Type` has grown to include
33 `types.TypeParam` and `types.Union`.
34
35 # Introduction
36
37 With Go 1.18, Go now supports generic programming via type parameters. This
38 document is a guide for tool authors that want to update their tools to support
39 the new language constructs.
40
41 This guide assumes knowledge of the language changes to support generics. See
42 the following references for more information:
43
44 - The [original proposal](https://go.dev/issue/43651) for type parameters.
45 - The [addendum for type sets](https://go.dev/issue/45346).
46 - The [latest language specification](https://tip.golang.org/ref/spec) (still in-progress as of 2021-01-11).
47 - The proposals for new APIs in
48 [go/token and go/ast](https://go.dev/issue/47781), and in
49 [go/types](https://go.dev/issue/47916).
50
51 It also assumes knowledge of `go/ast` and `go/types`. If you're just getting
52 started,
53 [x/example/gotypes](https://github.com/golang/example/tree/master/gotypes) is
54 a great introduction (and was the inspiration for this guide).
55
56 # Summary of new language features and their APIs
57
58 The introduction of of generic features appears as a large change to the
59 language, but a high level introduces only a few new concepts. We can break
60 down our discussion into the following three broad categories: generic types,
61 constraint interfaces, and instantiation. In each category below, the relevant
62 new APIs are listed (some constructors and getters/setters may be elided where
63 they are trivial):
64
65 **Generic types**. Types and functions may be _generic_, meaning their
66 declaration may have a non-empty _type parameter list_, as in
67 `type List[T any] ...` or `func f[T1, T2 any]() { ... }`. Type parameter lists
68 define placeholder types (_type parameters_), scoped to the declaration, which
69 may be substituted by any type satisfying their corresponding _constraint
70 interface_ to _instantiate_ a new type or function.
71
72 Generic types may have methods, which declare `receiver type parameters` via
73 their receiver type expression: `func (r T[P1, ..., PN]) method(...) (...)
74 {...}`.
75
76 _New APIs_:
77 - The field `ast.TypeSpec.TypeParams` holds the type parameter list syntax for
78 type declarations.
79 - The field `ast.FuncType.TypeParams` holds the type parameter list syntax for
80 function declarations.
81 - The type `types.TypeParam` is a `types.Type` representing a type parameter.
82 On this type, the `Constraint` and `SetConstraint` methods allow
83 getting/setting the constraint, the `Index` method returns the numeric index
84 of the type parameter in the type parameter list that declares it, and the
85 `Obj` method returns the object in the scope a for the type parameter (a
86 `types.TypeName`). Generic type declarations have a new `*types.Scope` for
87 type parameter declarations.
88 - The type `types.TypeParamList` holds a list of type parameters.
89 - The method `types.Named.TypeParams` returns the type parameters for a type
90 declaration.
91 - The method `types.Named.SetTypeParams` sets type parameters on a defined
92 type.
93 - The function `types.NewSignatureType` creates a new (possibly generic)
94 signature type.
95 - The method `types.Signature.RecvTypeParams` returns the receiver type
96 parameters for a method.
97 - The method `types.Signature.TypeParams` returns the type parameters for
98 a function.
99
100 **Constraint Interfaces**: type parameter constraints are interfaces, expressed
101 by an interface type expression. Interfaces that are only used in constraint
102 position are permitted new embedded elements composed of tilde expressions
103 (`~T`) and unions (`A | B | ~C`). The new builtin interface type `comparable`
104 is implemented by types for which `==` and `!=` are valid (note that interfaces
105 must be statically comparable in this case, i.e., each type in the interface's
106 type set must be comparable). As a special case, the `interface` keyword may be
107 omitted from constraint expressions if it may be implied (in which case we say
108 the interface is _implicit_).
109
110 _New APIs_:
111 - The constant `token.TILDE` is used to represent tilde expressions as an
112 `ast.UnaryExpr`.
113 - Union expressions are represented as an `ast.BinaryExpr` using `|`. This
114 means that `ast.BinaryExpr` may now be both a type and value expression.
115 - The method `types.Interface.IsImplicit` reports whether the `interface`
116 keyword was elided from this interface.
117 - The method `types.Interface.MarkImplicit` marks an interface as being
118 implicit.
119 - The method `types.Interface.IsComparable` reports whether every type in an
120 interface's type set is comparable.
121 - The method `types.Interface.IsMethodSet` reports whether an interface is
122 defined entirely by its methods (has no _specific types_).
123 - The type `types.Union` is a type that represents an embedded union
124 expression in an interface. May only appear as an embedded element in
125 interfaces.
126 - The type `types.Term` represents a (possibly tilde) term of a union.
127
128 **Instantiation**: generic types and functions may be _instantiated_ to create
129 non-generic types and functions by providing _type arguments_ (`var x T[int]`).
130 Function type arguments may be _inferred_ via function arguments, or via
131 type parameter constraints.
132
133 _New APIs_:
134 - The type `ast.IndexListExpr` holds index expressions with multiple indices,
135 as in instantiation expressions with multiple type arguments or in receivers
136 declaring multiple type parameters.
137 - The function `types.Instantiate` instantiates a generic type with type arguments.
138 - The type `types.Context` is an opaque instantiation context that may be
139 shared to reduce duplicate instances.
140 - The field `types.Config.Context` holds a shared `Context` to use for
141 instantiation while type-checking.
142 - The type `types.TypeList` holds a list of types.
143 - The type `types.ArgumentError` holds an error associated with a specific
144 type argument index. Used to represent instantiation errors.
145 - The field `types.Info.Instances` maps instantiated identifiers to information
146 about the resulting type instance.
147 - The type `types.Instance` holds information about a type or function
148 instance.
149 - The method `types.Named.TypeArgs` reports the type arguments used to
150 instantiate a named type.
151
152 # Examples
153
154 The following examples demonstrate the new APIs, and discuss their properties.
155 All examples are runnable, contained in subdirectories of the directory holding
156 this README.
157
158 ## Generic types: type parameters
159
160 We say that a type is _generic_ if it has type parameters but no type
161 arguments. This section explains how we can inspect generic types with the new
162 `go/types` APIs.
163
164 ### Type parameter lists
165
166 Suppose we want to understand the generic library below, which defines a generic
167 `Pair`, a constraint interface `Constraint`, and a generic function `MakePair`.
168
169 ```
170 package main
171
172 type Constraint interface {
173 Value() any
174 }
175
176 type Pair[L, R any] struct {
177 left L
178 right R
179 }
180
181 func MakePair[L, R Constraint](l L, r R) Pair[L, R] {
182 return Pair[L, R]{l, r}
183 }
184 ```
185
186 We can use the new `TypeParams` fields in `ast.TypeSpec` and `ast.FuncType` to
187 access the type parameter list. From there, we can access type parameter types
188 in at least three ways:
189 - by looking up type parameter definitions in `types.Info`
190 - by calling `TypeParams()` on `types.Named` or `types.Signature`
191 - by looking up type parameter objects in the declaration scope. Note that
192 there now may be a scope associated with an `ast.TypeSpec` node.
193
194 ```
195 func PrintTypeParams(fset *token.FileSet, file *ast.File) error {
196 conf := types.Config{Importer: importer.Default()}
197 info := &types.Info{
198 Scopes: make(map[ast.Node]*types.Scope),
199 Defs: make(map[*ast.Ident]types.Object),
200 }
201 _, err := conf.Check("hello", fset, []*ast.File{file}, info)
202 if err != nil {
203 return err
204 }
205
206 // For convenience, we can use ast.Inspect to find the nodes we want to
207 // investigate.
208 ast.Inspect(file, func(n ast.Node) bool {
209 var name *ast.Ident // the name of the generic object, or nil
210 var tparamFields *ast.FieldList // the list of type parameter fields
211 var tparams *types.TypeParamList // the list of type parameter types
212 var scopeNode ast.Node // the node associated with the declaration scope
213
214 switch n := n.(type) {
215 case *ast.TypeSpec:
216 name = n.Name
217 tparamFields = n.TypeParams
218 tparams = info.Defs[name].Type().(*types.Named).TypeParams()
219 scopeNode = n
220 case *ast.FuncDecl:
221 name = n.Name
222 tparamFields = n.Type.TypeParams
223 tparams = info.Defs[name].Type().(*types.Signature).TypeParams()
224 scopeNode = n.Type
225 default:
226 // Not a type or function declaration.
227 return true
228 }
229
230 // Option 1: find type parameters by looking at their declaring field list.
231 if tparamFields != nil {
232 fmt.Printf("%s has a type parameter field list with %d fields\n", name.Name, tparamFields.NumFields())
233 for _, field := range tparamFields.List {
234 for _, name := range field.Names {
235 tparam := info.Defs[name]
236 fmt.Printf(" field %s defines an object %q\n", name.Name, tparam)
237 }
238 }
239 } else {
240 fmt.Printf("%s does not have a type parameter list\n", name.Name)
241 }
242
243 // Option 2: find type parameters via the TypeParams() method on the
244 // generic type.
245 if tparams.Len() > 0 {
246 fmt.Printf("%s has %d type parameters:\n", name.Name, tparams.Len())
247 for i := 0; i < tparams.Len(); i++ {
248 tparam := tparams.At(i)
249 fmt.Printf(" %s has constraint %s\n", tparam, tparam.Constraint())
250 }
251 } else {
252 fmt.Printf("%s does not have type parameters\n", name.Name)
253 }
254
255 // Option 3: find type parameters by looking in the declaration scope.
256 scope, ok := info.Scopes[scopeNode]
257 if ok {
258 fmt.Printf("%s has a scope with %d objects:\n", name.Name, scope.Len())
259 for _, name := range scope.Names() {
260 fmt.Printf(" %s is a %T\n", name, scope.Lookup(name))
261 }
262 } else {
263 fmt.Printf("%s does not have a scope\n", name.Name)
264 }
265
266 return true
267 })
268 return nil
269 }
270 ```
271
272 This program produces the following output. Note that not every type spec has
273 a scope.
274
275 ```
276 > go run golang.org/x/tools/internal/typeparams/example/findtypeparams
277 Constraint does not have a type parameter list
278 Constraint does not have type parameters
279 Constraint does not have a scope
280 Pair has a type parameter field list with 2 fields
281 field L defines an object "type parameter L any"
282 field R defines an object "type parameter R any"
283 Pair has 2 type parameters:
284 L has constraint any
285 R has constraint any
286 Pair has a scope with 2 objects:
287 L is a *types.TypeName
288 R is a *types.TypeName
289 MakePair has a type parameter field list with 2 fields
290 field L defines an object "type parameter L hello.Constraint"
291 field R defines an object "type parameter R hello.Constraint"
292 MakePair has 2 type parameters:
293 L has constraint hello.Constraint
294 R has constraint hello.Constraint
295 MakePair has a scope with 4 objects:
296 L is a *types.TypeName
297 R is a *types.TypeName
298 l is a *types.Var
299 r is a *types.Var
300 ```
301
302 ## Constraint Interfaces
303
304 In order to allow operations on type parameters, Go 1.18 introduces the notion
305 of [_type sets_](https://tip.golang.org/ref/spec#Interface_types), which is
306 abstractly the set of types that implement an interface. This section discusses
307 the new syntax for restrictions on interface type sets, and the APIs we can use
308 to understand them.
309
310 ### New interface elements
311
312 Consider the generic library below:
313
314 ```
315 package p
316
317 type Numeric interface{
318 ~int | ~float64 // etc...
319 }
320
321 func Square[N Numeric](n N) N {
322 return n*n
323 }
324
325 type Findable interface {
326 comparable
327 }
328
329 func Find[T Findable](s []T, v T) int {
330 for i, v2 := range s {
331 if v2 == v {
332 return i
333 }
334 }
335 return -1
336 }
337 ```
338
339 In this library, we can see a few new features added in Go 1.18. The first is
340 the new syntax in the `Numeric` type: unions of tilde-terms, specifying that
341 the numeric type may only be satisfied by types whose underlying type is `int`
342 or `float64`.
343
344 The `go/ast` package parses this new syntax as a combination of unary and
345 binary expressions, which we can see using the following program:
346
347 ```
348 func PrintNumericSyntax(fset *token.FileSet, file *ast.File) {
349 // node is the AST node corresponding to the declaration for "Numeric."
350 node := file.Scope.Lookup("Numeric").Decl.(*ast.TypeSpec)
351 // Find the embedded syntax node.
352 embedded := node.Type.(*ast.InterfaceType).Methods.List[0].Type
353 // Use go/ast's built-in Print function to inspect the parsed syntax.
354 ast.Print(fset, embedded)
355 }
356 ```
357
358 Output:
359
360 ```
361 0 *ast.BinaryExpr {
362 1 . X: *ast.UnaryExpr {
363 2 . . OpPos: p.go:6:2
364 3 . . Op: ~
365 4 . . X: *ast.Ident {
366 5 . . . NamePos: p.go:6:3
367 6 . . . Name: "int"
368 7 . . }
369 8 . }
370 9 . OpPos: p.go:6:7
371 10 . Op: |
372 11 . Y: *ast.UnaryExpr {
373 12 . . OpPos: p.go:6:9
374 13 . . Op: ~
375 14 . . X: *ast.Ident {
376 15 . . . NamePos: p.go:6:10
377 16 . . . Name: "float64"
378 17 . . }
379 18 . }
380 19 }
381 ```
382
383 Once type-checked, these embedded expressions are represented using the new
384 `types.Union` type, which flattens the expression into a list of `*types.Term`.
385 We can also investigate two new methods of interface:
386 `types.Interface.IsComparable`, which reports whether the type set of an
387 interface is comparable, and `types.Interface.IsMethodSet`, which reports
388 whether an interface is expressible using methods alone.
389
390 ```
391 func PrintInterfaceTypes(fset *token.FileSet, file *ast.File) error {
392 conf := types.Config{}
393 pkg, err := conf.Check("hello", fset, []*ast.File{file}, nil)
394 if err != nil {
395 return err
396 }
397
398 PrintIface(pkg, "Numeric")
399 PrintIface(pkg, "Findable")
400
401 return nil
402 }
403
404 func PrintIface(pkg *types.Package, name string) {
405 obj := pkg.Scope().Lookup(name)
406 fmt.Println(obj)
407 iface := obj.Type().Underlying().(*types.Interface)
408 for i := 0; i < iface.NumEmbeddeds(); i++ {
409 fmt.Printf("\tembeded: %s\n", iface.EmbeddedType(i))
410 }
411 for i := 0; i < iface.NumMethods(); i++ {
412 fmt.Printf("\tembeded: %s\n", iface.EmbeddedType(i))
413 }
414 fmt.Printf("\tIsComparable(): %t\n", iface.IsComparable())
415 fmt.Printf("\tIsMethodSet(): %t\n", iface.IsMethodSet())
416 }
417 ```
418
419 Output:
420
421 ```
422 type hello.Numeric interface{~int|~float64}
423 embeded: ~int|~float64
424 IsComparable(): true
425 IsMethodSet(): false
426 type hello.Findable interface{comparable}
427 embeded: comparable
428 IsComparable(): true
429 IsMethodSet(): false
430 ```
431
432 The `Findable` type demonstrates another new feature of Go 1.18: the comparable
433 built-in. Comparable is a special interface type, not expressible using
434 ordinary Go syntax, whose type-set consists of all comparable types.
435
436 ### Implicit interfaces
437
438 For interfaces that do not have methods, we can inline them in constraints and
439 elide the `interface` keyword. In the example above, we could have done this
440 for the `Square` function:
441
442 ```
443 package p
444
445 func Square[N ~int|~float64](n N) N {
446 return n*n
447 }
448 ```
449
450 In such cases, the `types.Interface.IsImplicit` method reports whether the
451 interface type was implicit. This does not affect the behavior of the
452 interface, but is captured for more accurate type strings:
453
454 ```
455 func ShowImplicit(pkg *types.Package) {
456 Square := pkg.Scope().Lookup("Square").Type().(*types.Signature)
457 N := Square.TypeParams().At(0)
458 constraint := N.Constraint().(*types.Interface)
459 fmt.Println(constraint)
460 fmt.Println("IsImplicit:", constraint.IsImplicit())
461 }
462 ```
463
464 Output:
465
466 ```
467 ~int|~float64
468 IsImplicit: true
469 ```
470
471 The `types.Interface.MarkImplicit` method is used to mark interfaces as
472 implicit by the importer.
473
474 ### Type sets
475
476 The examples above demonstrate the new APIs for _accessing_ information about
477 the new interface elements, but how do we understand
478 [_type sets_](https://tip.golang.org/ref/spec#Interface_types), the new
479 abstraction that these elements help define? Type sets may be arbitrarily
480 complex, as in the following example:
481
482 ```
483 package complex
484
485 type A interface{ ~string|~[]byte }
486
487 type B interface{ int|string }
488
489 type C interface { ~string|~int }
490
491 type D interface{ A|B; C }
492 ```
493
494 Here, the type set of `D` simplifies to `~string|int`, but the current
495 `go/types` APIs do not expose this information. This will likely be added to
496 `go/types` in future versions of Go, but in the meantime we can use the
497 `typeparams.NormalTerms` helper:
498
499 ```
500 func PrintNormalTerms(pkg *types.Package) error {
501 D := pkg.Scope().Lookup("D").Type()
502 terms, err := typeparams.NormalTerms(D)
503 if err != nil {
504 return err
505 }
506 for i, term := range terms {
507 if i > 0 {
508 fmt.Print("|")
509 }
510 fmt.Print(term)
511 }
512 fmt.Println()
513 return nil
514 }
515 ```
516
517 which outputs:
518
519 ```
520 ~string|int
521 ```
522
523 See the documentation for `typeparams.NormalTerms` for more information on how
524 this calculation proceeds.
525
526 ## Instantiation
527
528 We say that a type is _instantiated_ if it is created from a generic type by
529 substituting type arguments for type parameters. Instantiation can occur via
530 explicitly provided type arguments, as in the expression `T[A_1, ..., A_n]`, or
531 implicitly, through type inference.. This section describes how to find and
532 understand instantiated types.
533
534 ### Finding instantiated types
535
536 Certain applications may find it useful to locate all instantiated types in
537 a package. For this purpose, `go/types` provides a new `types.Info.Instances`
538 field that maps instantiated identifiers to information about their instance.
539
540 For example, consider the following code:
541
542 ```
543 package p
544
545 type Pair[L, R comparable] struct {
546 left L
547 right R
548 }
549
550 func (p Pair[L, _]) Left() L {
551 return p.left
552 }
553
554 func Equal[L, R comparable](x, y Pair[L, R]) bool {
555 return x.left == y.left && x.right == y.right
556 }
557
558 var X Pair[int, string]
559 var Y Pair[string, int]
560
561 var E = Equal[int, string]
562 ```
563
564 We can find instances by type-checking with the `types.Info.Instances` map
565 initialized:
566
567 ```
568 func CheckInstances(fset *token.FileSet, file *ast.File) (*types.Package, error) {
569 conf := types.Config{}
570 info := &types.Info{
571 Instances: make(map[*ast.Ident]types.Instance),
572 }
573 pkg, err := conf.Check("p", fset, []*ast.File{file}, info)
574 for id, inst := range info.Instances {
575 posn := fset.Position(id.Pos())
576 fmt.Printf("%s: %s instantiated with %s: %s\n", posn, id.Name, FormatTypeList(inst.TypeArgs), inst.Type)
577 }
578 return pkg, err
579 }
580 ```
581
582 Output:
583
584 ```
585 hello.go:21:9: Equal instantiated with [int, string]: func(x p.Pair[int, string], y p.Pair[int, string]) bool
586 hello.go:10:9: Pair instantiated with [L, _]: p.Pair[L, _]
587 hello.go:14:34: Pair instantiated with [L, R]: p.Pair[L, R]
588 hello.go:18:7: Pair instantiated with [int, string]: p.Pair[int, string]
589 hello.go:19:7: Pair instantiated with [string, int]: p.Pair[string, int]
590 ```
591
592 The `types.Instance` type provides information about the (possibly inferred)
593 type arguments that were used to instantiate the generic type, and the
594 resulting type. Notably, it does not include the _generic_ type that was
595 instantiated, because this type can be found using `types.Info.Uses[id].Type()`
596 (where `id` is the identifier node being instantiated).
597
598 Note that the receiver type of method `Left` also appears in the `Instances`
599 map. This may be counterintuitive -- more on this below.
600
601 ### Creating new instantiated types
602
603 `go/types` also provides an API for creating type instances:
604 `types.Instantiate`. This function accepts a generic type and type arguments,
605 and returns an instantiated type (or an error). The resulting instance may be
606 a newly constructed type, or a previously created instance with the same type
607 identity. To facilitate the reuse of frequently used instances,
608 `types.Instantiate` accepts a `types.Context` as its first argument, which
609 records instances.
610
611 If the final `validate` argument to `types.Instantiate` is set, the provided
612 type arguments will be verified against their corresponding type parameter
613 constraint; i.e., `types.Instantiate` will check that each type arguments
614 implements the corresponding type parameter constraint. If a type arguments
615 does not implement the respective constraint, the resulting error will wrap
616 a new `ArgumentError` type indicating which type argument index was bad.
617
618 ```
619 func Instantiate(pkg *types.Package) error {
620 Pair := pkg.Scope().Lookup("Pair").Type()
621 X := pkg.Scope().Lookup("X").Type()
622 Y := pkg.Scope().Lookup("Y").Type()
623
624 // X and Y have different types, because their type arguments are different.
625 Compare("X", "Y", X, Y)
626
627 // Create a shared context for the subsequent instantiations.
628 ctxt := types.NewContext()
629
630 // Instantiating with [int, string] yields an instance that is identical (but
631 // not equal) to X.
632 Int, String := types.Typ[types.Int], types.Typ[types.String]
633 inst1, _ := types.Instantiate(ctxt, Pair, []types.Type{Int, String}, true)
634 Compare("X", "inst1", X, inst1)
635
636 // Instantiating again returns the same exact instance, because of the shared
637 // Context.
638 inst2, _ := types.Instantiate(ctxt, Pair, []types.Type{Int, String}, true)
639 Compare("inst1", "inst2", inst1, inst2)
640
641 // Instantiating with 'any' is an error, because any is not comparable.
642 Any := types.Universe.Lookup("any").Type()
643 _, err := types.Instantiate(ctxt, Pair, []types.Type{Int, Any}, true)
644 var argErr *types.ArgumentError
645 if errors.As(err, &argErr) {
646 fmt.Printf("Argument %d: %v\n", argErr.Index, argErr.Err)
647 }
648
649 return nil
650 }
651
652 func Compare(leftName, rightName string, left, right types.Type) {
653 fmt.Printf("Identical(%s, %s) : %t\n", leftName, rightName, types.Identical(left, right))
654 fmt.Printf("%s == %s : %t\n\n", leftName, rightName, left == right)
655 }
656 ```
657
658 Output:
659
660 ```
661 Identical(p.Pair[int, string], p.Pair[string, int]) : false
662 p.Pair[int, string] == p.Pair[string, int] : false
663
664 Identical(p.Pair[int, string], p.Pair[int, string]) : true
665 p.Pair[int, string] == p.Pair[int, string] : false
666
667 Identical(p.Pair[string, int], p.Pair[int, string]) : false
668 p.Pair[string, int] == p.Pair[int, string] : false
669
670 Identical(p.Pair[int, string], p.Pair[int, string]) : true
671 p.Pair[int, string] == p.Pair[int, string] : true
672
673 Argument 1: any does not implement comparable
674 ```
675
676 ### Using a shared context while type checking
677
678 To share a common `types.Context` argument with a type-checking pass, set the
679 new `types.Config.Context` field.
680
681 ## Generic types continued: method sets and predicates
682
683 Generic types are fundamentally different from ordinary types, in that they may
684 not be used without instantiation. In some senses they are not really types:
685 the go spec defines [types](https://tip.golang.org/ref/spec#Types) as "a set of
686 values, together with operations and methods", but uninstantiated generic types
687 do not define a set of values. Rather, they define a set of _types_. In that
688 sense, they are a "meta type", or a "type template" (disclaimer: I am using
689 these terms imprecisely).
690
691 However, for the purposes of `go/types` it is convenient to treat generic types
692 as a `types.Type`. This section explains how generic types behave in existing
693 `go/types` APIs.
694
695 ### Method Sets
696
697 Methods on uninstantiated generic types are different from methods on an
698 ordinary type. Consider that for an ordinary type `T`, the receiver base type
699 of each method in its method set is `T`. However, this can't be the case for
700 a generic type: generic types cannot be used without instantiation, and neither
701 can the type of the receiver variable. Instead, the receiver base type is an
702 _instantiated_ type, instantiated with the method's receiver type parameters.
703
704 This has some surprising consequences, which we observed in the section on
705 instantiation above: for a generic type `G`, each of its methods will define
706 a unique instantiation of `G`, as each method has distinct receiver type
707 parameters.
708
709 To see this, consider the following example:
710
711 ```
712 package p
713
714 type Pair[L, R any] struct {
715 left L
716 right R
717 }
718
719 func (p Pair[L, _]) Left() L {
720 return p.left
721 }
722
723 func (p Pair[_, R]) Right() R {
724 return p.right
725 }
726
727 var IntPair Pair[int, int]
728 ```
729
730 Let's inspect the method sets of the types in this library:
731
732 ```
733 func PrintMethods(pkg *types.Package) {
734 // Look up *Named types in the package scope.
735 lookup := func(name string) *types.Named {
736 return pkg.Scope().Lookup(name).Type().(*types.Named)
737 }
738
739 Pair := lookup("Pair")
740 IntPair := lookup("IntPair")
741 PrintMethodSet("Pair", Pair)
742 PrintMethodSet("Pair[int, int]", IntPair)
743 LeftObj, _, _ := types.LookupFieldOrMethod(Pair, false, pkg, "Left")
744 LeftRecvType := LeftObj.Type().(*types.Signature).Recv().Type()
745 PrintMethodSet("Pair[L, _]", LeftRecvType)
746 }
747
748 func PrintMethodSet(name string, typ types.Type) {
749 fmt.Println(name + ":")
750 methodSet := types.NewMethodSet(typ)
751 for i := 0; i < methodSet.Len(); i++ {
752 method := methodSet.At(i).Obj()
753 fmt.Println(method)
754 }
755 fmt.Println()
756 }
757 ```
758
759 Output:
760
761 ```
762 Pair:
763 func (p.Pair[L, _]).Left() L
764 func (p.Pair[_, R]).Right() R
765
766 Pair[int, int]:
767 func (p.Pair[int, int]).Left() int
768 func (p.Pair[int, int]).Right() int
769
770 Pair[L, _]:
771 func (p.Pair[L, _]).Left() L
772 func (p.Pair[L, _]).Right() _
773 ```
774
775 In this example, we can see that all of `Pair`, `Pair[int, int]`, and
776 `Pair[L, _]` have distinct method sets, though the method set of `Pair` and
777 `Pair[L, _]` intersect in the `Left` method.
778
779 Only the objects in `Pair`'s method set are recorded in `types.Info.Defs`. To
780 get back to this "canonical" method object, the `typeparams` package provides
781 the `OriginMethod` helper:
782
783 ```
784 func CompareOrigins(pkg *types.Package) {
785 Pair := pkg.Scope().Lookup("Pair").Type().(*types.Named)
786 IntPair := pkg.Scope().Lookup("IntPair").Type().(*types.Named)
787 Left, _, _ := types.LookupFieldOrMethod(Pair, false, pkg, "Left")
788 LeftInt, _, _ := types.LookupFieldOrMethod(IntPair, false, pkg, "Left")
789
790 fmt.Println("Pair.Left == Pair[int, int].Left:", Left == LeftInt)
791 origin := typeparams.OriginMethod(LeftInt.(*types.Func))
792 fmt.Println("Pair.Left == OriginMethod(Pair[int, int].Left):", Left == origin)
793 }
794 ```
795
796 Output:
797
798 ```
799 Pair.Left == Pair[int, int].Left: false
800 Pair.Left == OriginMethod(Pair[int, int].Left): true
801 ```
802
803 ### Predicates
804
805 Predicates on generic types are not defined by the spec. As a consequence,
806 using e.g. `types.AssignableTo` with operands of generic types leads to an
807 undefined result.
808
809 The behavior of predicates on generic `*types.Named` types may generally be
810 derived from the fact that type parameters bound to different names are
811 different types. This means that most predicates involving generic types will
812 return `false`.
813
814 `*types.Signature` types are treated differently. Two signatures are considered
815 identical if they are identical after substituting one's set of type parameters
816 for the other's, including having identical type parameter constraints. This is
817 analogous to the treatment of ordinary value parameters, whose names do not
818 affect type identity.
819
820 Consider the following code:
821
822 ```
823 func OrdinaryPredicates(pkg *types.Package) {
824 var (
825 Pair = pkg.Scope().Lookup("Pair").Type()
826 LeftRighter = pkg.Scope().Lookup("LeftRighter").Type()
827 Mer = pkg.Scope().Lookup("Mer").Type()
828 F = pkg.Scope().Lookup("F").Type()
829 G = pkg.Scope().Lookup("G").Type()
830 H = pkg.Scope().Lookup("H").Type()
831 )
832
833 fmt.Println("AssignableTo(Pair, LeftRighter)", types.AssignableTo(Pair, LeftRighter))
834 fmt.Println("AssignableTo(Pair, Mer): ", types.AssignableTo(Pair, Mer))
835 fmt.Println("Identical(F, G)", types.Identical(F, G))
836 fmt.Println("Identical(F, H)", types.Identical(F, H))
837 }
838 ```
839
840 Output:
841
842 ```
843 AssignableTo(Pair, LeftRighter) false
844 AssignableTo(Pair, Mer): true
845 Identical(F, G) true
846 Identical(F, H) false
847 ```
848
849 In this example, we see that despite their similarity the generic `Pair` type
850 is not assignable to the generic `LeftRighter` type. We also see the rules for
851 signature identity in practice.
852
853 This begs the question: how does one ask questions about the relationship
854 between generic types? In order to phrase such questions we need more
855 information: how does one relate the type parameters of `Pair` to the type
856 parameters of `LeftRighter`? Does it suffice for the predicate to hold for one
857 element of the type sets, or must it hold for all elements of the type sets?
858
859 We can use instantiation to answer some of these questions. In particular, by
860 instantiating both `Pair` and `LeftRighter` with the type parameters of `Pair`,
861 we can determine if, for all type arguments `[X, Y]` that are valid for `Pair`,
862 `[X, Y]` are also valid type arguments of `LeftRighter`, and `Pair[X, Y]` is
863 assignable to `LeftRighter[X, Y]`. The `typeparams.GenericAssignableTo`
864 function implements exactly this predicate:
865
866 ```
867 func GenericPredicates(pkg *types.Package) {
868 var (
869 Pair = pkg.Scope().Lookup("Pair").Type()
870 LeftRighter = pkg.Scope().Lookup("LeftRighter").Type()
871 )
872 fmt.Println("GenericAssignableTo(Pair, LeftRighter)", typeparams.GenericAssignableTo(nil, Pair, LeftRighter))
873 }
874 ```
875
876 Output:
877
878 ```
879 GenericAssignableTo(Pair, LeftRighter) true
880 ```
881
882 # Updating tools while building at older Go versions
883
884 In the examples above, we can see how a lot of the new APIs integrate with
885 existing usage of `go/ast` or `go/types`. However, most tools still need to
886 build at older Go versions, and handling the new language constructs in-line
887 will break builds at older Go versions.
888
889 For this purpose, the `x/exp/typeparams` package provides functions and types
890 that proxy the new APIs (with stub implementations at older Go versions).
891
892 # Further help
893
894 If you're working on updating a tool to support generics, and need help, please
895 feel free to reach out for help in any of the following ways:
896 - By mailing the [golang-tools](https://groups.google.com/g/golang-tools) mailing list.
897 - Directly to me via email (`[email protected]`).
898 - For bugs, you can [file an issue](https://github.com/golang/go/issues/new/choose).