| 1 | <!-- To regenerate the readme, run: --> |
| 2 | <!-- go run golang.org/x/example/gotypes@latest generic-go-types.md --> |
| 3 | |
| 4 | # Updating tools to support type parameters. |
| 5 | |
| 6 | This guide is maintained by Rob Findley (`[email protected]`). |
| 7 | |
| 8 | **status**: this document is currently a rough-draft. See [golang/go#50447](https://go.dev/issues/50447) for more details. |
| 9 | |
| 10 | %toc |
| 11 | |
| 12 | # Who should read this guide |
| 13 | |
| 14 | Read this guide if you are a tool author seeking to update your tools to |
| 15 | support generics Go code. Generics introduce significant new complexity to the |
| 16 | Go type system, because types can now be _parameterized_. While the |
| 17 | fundamentals of the `go/types` APIs remain the same, some previously valid |
| 18 | assumptions no longer hold. For example: |
| 19 | |
| 20 | - Type declarations need not correspond 1:1 with the types they define. |
| 21 | - Interfaces are no longer determined entirely by their method set. |
| 22 | - The set of concrete types implementing `types.Type` has grown to include |
| 23 | `types.TypeParam` and `types.Union`. |
| 24 | |
| 25 | # Introduction |
| 26 | |
| 27 | With Go 1.18, Go now supports generic programming via type parameters. This |
| 28 | document is a guide for tool authors that want to update their tools to support |
| 29 | the new language constructs. |
| 30 | |
| 31 | This guide assumes knowledge of the language changes to support generics. See |
| 32 | the following references for more information: |
| 33 | |
| 34 | - The [original proposal](https://go.dev/issue/43651) for type parameters. |
| 35 | - The [addendum for type sets](https://go.dev/issue/45346). |
| 36 | - The [latest language specification](https://tip.golang.org/ref/spec) (still in-progress as of 2021-01-11). |
| 37 | - The proposals for new APIs in |
| 38 | [go/token and go/ast](https://go.dev/issue/47781), and in |
| 39 | [go/types](https://go.dev/issue/47916). |
| 40 | |
| 41 | It also assumes knowledge of `go/ast` and `go/types`. If you're just getting |
| 42 | started, |
| 43 | [x/example/gotypes](https://github.com/golang/example/tree/master/gotypes) is |
| 44 | a great introduction (and was the inspiration for this guide). |
| 45 | |
| 46 | # Summary of new language features and their APIs |
| 47 | |
| 48 | The introduction of of generic features appears as a large change to the |
| 49 | language, but a high level introduces only a few new concepts. We can break |
| 50 | down our discussion into the following three broad categories: generic types, |
| 51 | constraint interfaces, and instantiation. In each category below, the relevant |
| 52 | new APIs are listed (some constructors and getters/setters may be elided where |
| 53 | they are trivial): |
| 54 | |
| 55 | **Generic types**. Types and functions may be _generic_, meaning their |
| 56 | declaration may have a non-empty _type parameter list_, as in |
| 57 | `type List[T any] ...` or `func f[T1, T2 any]() { ... }`. Type parameter lists |
| 58 | define placeholder types (_type parameters_), scoped to the declaration, which |
| 59 | may be substituted by any type satisfying their corresponding _constraint |
| 60 | interface_ to _instantiate_ a new type or function. |
| 61 | |
| 62 | Generic types may have methods, which declare `receiver type parameters` via |
| 63 | their receiver type expression: `func (r T[P1, ..., PN]) method(...) (...) |
| 64 | {...}`. |
| 65 | |
| 66 | _New APIs_: |
| 67 | - The field `ast.TypeSpec.TypeParams` holds the type parameter list syntax for |
| 68 | type declarations. |
| 69 | - The field `ast.FuncType.TypeParams` holds the type parameter list syntax for |
| 70 | function declarations. |
| 71 | - The type `types.TypeParam` is a `types.Type` representing a type parameter. |
| 72 | On this type, the `Constraint` and `SetConstraint` methods allow |
| 73 | getting/setting the constraint, the `Index` method returns the numeric index |
| 74 | of the type parameter in the type parameter list that declares it, and the |
| 75 | `Obj` method returns the object in the scope a for the type parameter (a |
| 76 | `types.TypeName`). Generic type declarations have a new `*types.Scope` for |
| 77 | type parameter declarations. |
| 78 | - The type `types.TypeParamList` holds a list of type parameters. |
| 79 | - The method `types.Named.TypeParams` returns the type parameters for a type |
| 80 | declaration. |
| 81 | - The method `types.Named.SetTypeParams` sets type parameters on a defined |
| 82 | type. |
| 83 | - The function `types.NewSignatureType` creates a new (possibly generic) |
| 84 | signature type. |
| 85 | - The method `types.Signature.RecvTypeParams` returns the receiver type |
| 86 | parameters for a method. |
| 87 | - The method `types.Signature.TypeParams` returns the type parameters for |
| 88 | a function. |
| 89 | |
| 90 | **Constraint Interfaces**: type parameter constraints are interfaces, expressed |
| 91 | by an interface type expression. Interfaces that are only used in constraint |
| 92 | position are permitted new embedded elements composed of tilde expressions |
| 93 | (`~T`) and unions (`A | B | ~C`). The new builtin interface type `comparable` |
| 94 | is implemented by types for which `==` and `!=` are valid (note that interfaces |
| 95 | must be statically comparable in this case, i.e., each type in the interface's |
| 96 | type set must be comparable). As a special case, the `interface` keyword may be |
| 97 | omitted from constraint expressions if it may be implied (in which case we say |
| 98 | the interface is _implicit_). |
| 99 | |
| 100 | _New APIs_: |
| 101 | - The constant `token.TILDE` is used to represent tilde expressions as an |
| 102 | `ast.UnaryExpr`. |
| 103 | - Union expressions are represented as an `ast.BinaryExpr` using `|`. This |
| 104 | means that `ast.BinaryExpr` may now be both a type and value expression. |
| 105 | - The method `types.Interface.IsImplicit` reports whether the `interface` |
| 106 | keyword was elided from this interface. |
| 107 | - The method `types.Interface.MarkImplicit` marks an interface as being |
| 108 | implicit. |
| 109 | - The method `types.Interface.IsComparable` reports whether every type in an |
| 110 | interface's type set is comparable. |
| 111 | - The method `types.Interface.IsMethodSet` reports whether an interface is |
| 112 | defined entirely by its methods (has no _specific types_). |
| 113 | - The type `types.Union` is a type that represents an embedded union |
| 114 | expression in an interface. May only appear as an embedded element in |
| 115 | interfaces. |
| 116 | - The type `types.Term` represents a (possibly tilde) term of a union. |
| 117 | |
| 118 | **Instantiation**: generic types and functions may be _instantiated_ to create |
| 119 | non-generic types and functions by providing _type arguments_ (`var x T[int]`). |
| 120 | Function type arguments may be _inferred_ via function arguments, or via |
| 121 | type parameter constraints. |
| 122 | |
| 123 | _New APIs_: |
| 124 | - The type `ast.IndexListExpr` holds index expressions with multiple indices, |
| 125 | as in instantiation expressions with multiple type arguments or in receivers |
| 126 | declaring multiple type parameters. |
| 127 | - The function `types.Instantiate` instantiates a generic type with type arguments. |
| 128 | - The type `types.Context` is an opaque instantiation context that may be |
| 129 | shared to reduce duplicate instances. |
| 130 | - The field `types.Config.Context` holds a shared `Context` to use for |
| 131 | instantiation while type-checking. |
| 132 | - The type `types.TypeList` holds a list of types. |
| 133 | - The type `types.ArgumentError` holds an error associated with a specific |
| 134 | type argument index. Used to represent instantiation errors. |
| 135 | - The field `types.Info.Instances` maps instantiated identifiers to information |
| 136 | about the resulting type instance. |
| 137 | - The type `types.Instance` holds information about a type or function |
| 138 | instance. |
| 139 | - The method `types.Named.TypeArgs` reports the type arguments used to |
| 140 | instantiate a named type. |
| 141 | |
| 142 | # Examples |
| 143 | |
| 144 | The following examples demonstrate the new APIs, and discuss their properties. |
| 145 | All examples are runnable, contained in subdirectories of the directory holding |
| 146 | this README. |
| 147 | |
| 148 | ## Generic types: type parameters |
| 149 | |
| 150 | We say that a type is _generic_ if it has type parameters but no type |
| 151 | arguments. This section explains how we can inspect generic types with the new |
| 152 | `go/types` APIs. |
| 153 | |
| 154 | ### Type parameter lists |
| 155 | |
| 156 | Suppose we want to understand the generic library below, which defines a generic |
| 157 | `Pair`, a constraint interface `Constraint`, and a generic function `MakePair`. |
| 158 | |
| 159 | %include findtypeparams/main.go input - |
| 160 | |
| 161 | We can use the new `TypeParams` fields in `ast.TypeSpec` and `ast.FuncType` to |
| 162 | access the type parameter list. From there, we can access type parameter types |
| 163 | in at least three ways: |
| 164 | - by looking up type parameter definitions in `types.Info` |
| 165 | - by calling `TypeParams()` on `types.Named` or `types.Signature` |
| 166 | - by looking up type parameter objects in the declaration scope. Note that |
| 167 | there now may be a scope associated with an `ast.TypeSpec` node. |
| 168 | |
| 169 | %include findtypeparams/main.go print - |
| 170 | |
| 171 | This program produces the following output. Note that not every type spec has |
| 172 | a scope. |
| 173 | |
| 174 | %include findtypeparams/main.go output - |
| 175 | |
| 176 | ## Constraint Interfaces |
| 177 | |
| 178 | In order to allow operations on type parameters, Go 1.18 introduces the notion |
| 179 | of [_type sets_](https://tip.golang.org/ref/spec#Interface_types), which is |
| 180 | abstractly the set of types that implement an interface. This section discusses |
| 181 | the new syntax for restrictions on interface type sets, and the APIs we can use |
| 182 | to understand them. |
| 183 | |
| 184 | ### New interface elements |
| 185 | |
| 186 | Consider the generic library below: |
| 187 | |
| 188 | %include interfaces/main.go input - |
| 189 | |
| 190 | In this library, we can see a few new features added in Go 1.18. The first is |
| 191 | the new syntax in the `Numeric` type: unions of tilde-terms, specifying that |
| 192 | the numeric type may only be satisfied by types whose underlying type is `int` |
| 193 | or `float64`. |
| 194 | |
| 195 | The `go/ast` package parses this new syntax as a combination of unary and |
| 196 | binary expressions, which we can see using the following program: |
| 197 | |
| 198 | %include interfaces/main.go printsyntax - |
| 199 | |
| 200 | Output: |
| 201 | |
| 202 | %include interfaces/main.go outputsyntax - |
| 203 | |
| 204 | Once type-checked, these embedded expressions are represented using the new |
| 205 | `types.Union` type, which flattens the expression into a list of `*types.Term`. |
| 206 | We can also investigate two new methods of interface: |
| 207 | `types.Interface.IsComparable`, which reports whether the type set of an |
| 208 | interface is comparable, and `types.Interface.IsMethodSet`, which reports |
| 209 | whether an interface is expressible using methods alone. |
| 210 | |
| 211 | %include interfaces/main.go printtypes - |
| 212 | |
| 213 | Output: |
| 214 | |
| 215 | %include interfaces/main.go outputtypes - |
| 216 | |
| 217 | The `Findable` type demonstrates another new feature of Go 1.18: the comparable |
| 218 | built-in. Comparable is a special interface type, not expressible using |
| 219 | ordinary Go syntax, whose type-set consists of all comparable types. |
| 220 | |
| 221 | ### Implicit interfaces |
| 222 | |
| 223 | For interfaces that do not have methods, we can inline them in constraints and |
| 224 | elide the `interface` keyword. In the example above, we could have done this |
| 225 | for the `Square` function: |
| 226 | |
| 227 | %include implicit/main.go input - |
| 228 | |
| 229 | In such cases, the `types.Interface.IsImplicit` method reports whether the |
| 230 | interface type was implicit. This does not affect the behavior of the |
| 231 | interface, but is captured for more accurate type strings: |
| 232 | |
| 233 | %include implicit/main.go show - |
| 234 | |
| 235 | Output: |
| 236 | |
| 237 | %include implicit/main.go output - |
| 238 | |
| 239 | The `types.Interface.MarkImplicit` method is used to mark interfaces as |
| 240 | implicit by the importer. |
| 241 | |
| 242 | ### Type sets |
| 243 | |
| 244 | The examples above demonstrate the new APIs for _accessing_ information about |
| 245 | the new interface elements, but how do we understand |
| 246 | [_type sets_](https://tip.golang.org/ref/spec#Interface_types), the new |
| 247 | abstraction that these elements help define? Type sets may be arbitrarily |
| 248 | complex, as in the following example: |
| 249 | |
| 250 | %include typesets/main.go input - |
| 251 | |
| 252 | Here, the type set of `D` simplifies to `~string|int`, but the current |
| 253 | `go/types` APIs do not expose this information. This will likely be added to |
| 254 | `go/types` in future versions of Go, but in the meantime we can use the |
| 255 | `typeparams.NormalTerms` helper: |
| 256 | |
| 257 | %include typesets/main.go print - |
| 258 | |
| 259 | which outputs: |
| 260 | |
| 261 | %include typesets/main.go output - |
| 262 | |
| 263 | See the documentation for `typeparams.NormalTerms` for more information on how |
| 264 | this calculation proceeds. |
| 265 | |
| 266 | ## Instantiation |
| 267 | |
| 268 | We say that a type is _instantiated_ if it is created from a generic type by |
| 269 | substituting type arguments for type parameters. Instantiation can occur via |
| 270 | explicitly provided type arguments, as in the expression `T[A_1, ..., A_n]`, or |
| 271 | implicitly, through type inference.. This section describes how to find and |
| 272 | understand instantiated types. |
| 273 | |
| 274 | ### Finding instantiated types |
| 275 | |
| 276 | Certain applications may find it useful to locate all instantiated types in |
| 277 | a package. For this purpose, `go/types` provides a new `types.Info.Instances` |
| 278 | field that maps instantiated identifiers to information about their instance. |
| 279 | |
| 280 | For example, consider the following code: |
| 281 | |
| 282 | %include instantiation/main.go input - |
| 283 | |
| 284 | We can find instances by type-checking with the `types.Info.Instances` map |
| 285 | initialized: |
| 286 | |
| 287 | %include instantiation/main.go check - |
| 288 | |
| 289 | Output: |
| 290 | |
| 291 | %include instantiation/main.go checkoutput - |
| 292 | |
| 293 | The `types.Instance` type provides information about the (possibly inferred) |
| 294 | type arguments that were used to instantiate the generic type, and the |
| 295 | resulting type. Notably, it does not include the _generic_ type that was |
| 296 | instantiated, because this type can be found using `types.Info.Uses[id].Type()` |
| 297 | (where `id` is the identifier node being instantiated). |
| 298 | |
| 299 | Note that the receiver type of method `Left` also appears in the `Instances` |
| 300 | map. This may be counterintuitive -- more on this below. |
| 301 | |
| 302 | ### Creating new instantiated types |
| 303 | |
| 304 | `go/types` also provides an API for creating type instances: |
| 305 | `types.Instantiate`. This function accepts a generic type and type arguments, |
| 306 | and returns an instantiated type (or an error). The resulting instance may be |
| 307 | a newly constructed type, or a previously created instance with the same type |
| 308 | identity. To facilitate the reuse of frequently used instances, |
| 309 | `types.Instantiate` accepts a `types.Context` as its first argument, which |
| 310 | records instances. |
| 311 | |
| 312 | If the final `validate` argument to `types.Instantiate` is set, the provided |
| 313 | type arguments will be verified against their corresponding type parameter |
| 314 | constraint; i.e., `types.Instantiate` will check that each type arguments |
| 315 | implements the corresponding type parameter constraint. If a type arguments |
| 316 | does not implement the respective constraint, the resulting error will wrap |
| 317 | a new `ArgumentError` type indicating which type argument index was bad. |
| 318 | |
| 319 | %include instantiation/main.go instantiate - |
| 320 | |
| 321 | Output: |
| 322 | |
| 323 | %include instantiation/main.go instantiateoutput - |
| 324 | |
| 325 | ### Using a shared context while type checking |
| 326 | |
| 327 | To share a common `types.Context` argument with a type-checking pass, set the |
| 328 | new `types.Config.Context` field. |
| 329 | |
| 330 | ## Generic types continued: method sets and predicates |
| 331 | |
| 332 | Generic types are fundamentally different from ordinary types, in that they may |
| 333 | not be used without instantiation. In some senses they are not really types: |
| 334 | the go spec defines [types](https://tip.golang.org/ref/spec#Types) as "a set of |
| 335 | values, together with operations and methods", but uninstantiated generic types |
| 336 | do not define a set of values. Rather, they define a set of _types_. In that |
| 337 | sense, they are a "meta type", or a "type template" (disclaimer: I am using |
| 338 | these terms imprecisely). |
| 339 | |
| 340 | However, for the purposes of `go/types` it is convenient to treat generic types |
| 341 | as a `types.Type`. This section explains how generic types behave in existing |
| 342 | `go/types` APIs. |
| 343 | |
| 344 | ### Method Sets |
| 345 | |
| 346 | Methods on uninstantiated generic types are different from methods on an |
| 347 | ordinary type. Consider that for an ordinary type `T`, the receiver base type |
| 348 | of each method in its method set is `T`. However, this can't be the case for |
| 349 | a generic type: generic types cannot be used without instantiation, and neither |
| 350 | can the type of the receiver variable. Instead, the receiver base type is an |
| 351 | _instantiated_ type, instantiated with the method's receiver type parameters. |
| 352 | |
| 353 | This has some surprising consequences, which we observed in the section on |
| 354 | instantiation above: for a generic type `G`, each of its methods will define |
| 355 | a unique instantiation of `G`, as each method has distinct receiver type |
| 356 | parameters. |
| 357 | |
| 358 | To see this, consider the following example: |
| 359 | |
| 360 | %include genericmethods/main.go input - |
| 361 | |
| 362 | Let's inspect the method sets of the types in this library: |
| 363 | |
| 364 | %include genericmethods/main.go printmethods - |
| 365 | |
| 366 | Output: |
| 367 | |
| 368 | %include genericmethods/main.go printoutput - |
| 369 | |
| 370 | In this example, we can see that all of `Pair`, `Pair[int, int]`, and |
| 371 | `Pair[L, _]` have distinct method sets, though the method set of `Pair` and |
| 372 | `Pair[L, _]` intersect in the `Left` method. |
| 373 | |
| 374 | Only the objects in `Pair`'s method set are recorded in `types.Info.Defs`. To |
| 375 | get back to this "canonical" method object, the `typeparams` package provides |
| 376 | the `OriginMethod` helper: |
| 377 | |
| 378 | %include genericmethods/main.go compareorigins - |
| 379 | |
| 380 | Output: |
| 381 | |
| 382 | %include genericmethods/main.go compareoutput - |
| 383 | |
| 384 | ### Predicates |
| 385 | |
| 386 | Predicates on generic types are not defined by the spec. As a consequence, |
| 387 | using e.g. `types.AssignableTo` with operands of generic types leads to an |
| 388 | undefined result. |
| 389 | |
| 390 | The behavior of predicates on generic `*types.Named` types may generally be |
| 391 | derived from the fact that type parameters bound to different names are |
| 392 | different types. This means that most predicates involving generic types will |
| 393 | return `false`. |
| 394 | |
| 395 | `*types.Signature` types are treated differently. Two signatures are considered |
| 396 | identical if they are identical after substituting one's set of type parameters |
| 397 | for the other's, including having identical type parameter constraints. This is |
| 398 | analogous to the treatment of ordinary value parameters, whose names do not |
| 399 | affect type identity. |
| 400 | |
| 401 | Consider the following code: |
| 402 | |
| 403 | %include predicates/main.go ordinary - |
| 404 | |
| 405 | Output: |
| 406 | |
| 407 | %include predicates/main.go ordinaryoutput - |
| 408 | |
| 409 | In this example, we see that despite their similarity the generic `Pair` type |
| 410 | is not assignable to the generic `LeftRighter` type. We also see the rules for |
| 411 | signature identity in practice. |
| 412 | |
| 413 | This begs the question: how does one ask questions about the relationship |
| 414 | between generic types? In order to phrase such questions we need more |
| 415 | information: how does one relate the type parameters of `Pair` to the type |
| 416 | parameters of `LeftRighter`? Does it suffice for the predicate to hold for one |
| 417 | element of the type sets, or must it hold for all elements of the type sets? |
| 418 | |
| 419 | We can use instantiation to answer some of these questions. In particular, by |
| 420 | instantiating both `Pair` and `LeftRighter` with the type parameters of `Pair`, |
| 421 | we can determine if, for all type arguments `[X, Y]` that are valid for `Pair`, |
| 422 | `[X, Y]` are also valid type arguments of `LeftRighter`, and `Pair[X, Y]` is |
| 423 | assignable to `LeftRighter[X, Y]`. The `typeparams.GenericAssignableTo` |
| 424 | function implements exactly this predicate: |
| 425 | |
| 426 | %include predicates/main.go generic - |
| 427 | |
| 428 | Output: |
| 429 | |
| 430 | %include predicates/main.go genericoutput - |
| 431 | |
| 432 | # Updating tools while building at older Go versions |
| 433 | |
| 434 | In the examples above, we can see how a lot of the new APIs integrate with |
| 435 | existing usage of `go/ast` or `go/types`. However, most tools still need to |
| 436 | build at older Go versions, and handling the new language constructs in-line |
| 437 | will break builds at older Go versions. |
| 438 | |
| 439 | For this purpose, the `x/exp/typeparams` package provides functions and types |
| 440 | that proxy the new APIs (with stub implementations at older Go versions). |
| 441 | |
| 442 | # Further help |
| 443 | |
| 444 | If you're working on updating a tool to support generics, and need help, please |
| 445 | feel free to reach out for help in any of the following ways: |
| 446 | - By mailing the [golang-tools](https://groups.google.com/g/golang-tools) mailing list. |
| 447 | - Directly to me via email (`[email protected]`). |
| 448 | - For bugs, you can [file an issue](https://github.com/golang/go/issues/new/choose). |