Debian Codegraph @

typeparams/common.go

raw symbols SCIP
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 // Package typeparams contains common utilities for writing tools that interact
6 // with generic Go code, as introduced with Go 1.18.
7 //
8 // Many of the types and functions in this package are proxies for the new APIs
9 // introduced in the standard library with Go 1.18. For example, the
10 // typeparams.Union type is an alias for go/types.Union, and the ForTypeSpec
11 // function returns the value of the go/ast.TypeSpec.TypeParams field.
12 //
13 // Additionally, this package contains common utilities for working with the
14 // new generic constructs, to supplement the standard library APIs. Notably,
15 // the NormalTerms API computes a minimal representation of the structural
16 // restrictions on a type parameter. In the future, these supplemental APIs may
17 // be available in the standard library..
18 package typeparams
19
20 import (
21 "go/ast"
22 "go/token"
23 "go/types"
24 )
25
26 // Enabled reports whether type parameters are enabled in the current build
27 // environment.
28 //
29 // Deprecated: Type parameters are always enabled. Or use go fix (after go1.26).
30 //
31 //go:fix inline
32 func Enabled() bool {
33 return true
34 }
35
36 // UnpackIndexExpr extracts data from AST nodes that represent index
37 // expressions.
38 //
39 // For an ast.IndexExpr, the resulting indices slice will contain exactly one
40 // index expression. For an ast.IndexListExpr (go1.18+), it may have a variable
41 // number of index expressions.
42 //
43 // For nodes that don't represent index expressions, the first return value of
44 // UnpackIndexExpr will be nil.
45 func UnpackIndexExpr(n ast.Node) (x ast.Expr, lbrack token.Pos, indices []ast.Expr, rbrack token.Pos) {
46 switch e := n.(type) {
47 case *ast.IndexExpr:
48 return e.X, e.Lbrack, []ast.Expr{e.Index}, e.Rbrack
49 case *IndexListExpr:
50 return e.X, e.Lbrack, e.Indices, e.Rbrack
51 }
52 return nil, token.NoPos, nil, token.NoPos
53 }
54
55 // PackIndexExpr returns an *ast.IndexExpr or *ast.IndexListExpr, depending on
56 // the cardinality of indices. Calling PackIndexExpr with len(indices) == 0
57 // will panic.
58 func PackIndexExpr(x ast.Expr, lbrack token.Pos, indices []ast.Expr, rbrack token.Pos) ast.Expr {
59 switch len(indices) {
60 case 0:
61 panic("empty indices")
62 case 1:
63 return &ast.IndexExpr{
64 X: x,
65 Lbrack: lbrack,
66 Index: indices[0],
67 Rbrack: rbrack,
68 }
69 default:
70 return &IndexListExpr{
71 X: x,
72 Lbrack: lbrack,
73 Indices: indices,
74 Rbrack: rbrack,
75 }
76 }
77 }
78
79 // IsTypeParam reports whether t is a type parameter.
80 func IsTypeParam(t types.Type) bool {
81 _, ok := t.(*TypeParam)
82 return ok
83 }
84
85 // OriginMethod returns the origin method associated with the method fn. For
86 // methods on a non-generic receiver base type, this is just fn. However, for
87 // methods with a generic receiver, OriginMethod returns the corresponding
88 // method in the method set of the origin type.
89 //
90 // As a special case, if fn is not a method (has no receiver), OriginMethod
91 // returns fn.
92 func OriginMethod(fn *types.Func) *types.Func {
93 recv := fn.Type().(*types.Signature).Recv()
94 if recv == nil {
95 return fn
96 }
97 base := recv.Type()
98 p, isPtr := base.(*types.Pointer)
99 if isPtr {
100 base = p.Elem()
101 }
102 named, isNamed := base.(*types.Named)
103 if !isNamed {
104 // Receiver is a *types.Interface.
105 return fn
106 }
107 if ForNamed(named).Len() == 0 {
108 // Receiver base has no type parameters, so we can avoid the lookup below.
109 return fn
110 }
111 orig := NamedTypeOrigin(named)
112 gfn, _, _ := types.LookupFieldOrMethod(orig, true, fn.Pkg(), fn.Name())
113 return gfn.(*types.Func)
114 }
115
116 // GenericAssignableTo is a generalization of types.AssignableTo that
117 // implements the following rule for uninstantiated generic types:
118 //
119 // If V and T are generic named types, then V is considered assignable to T if,
120 // for every possible instantiation of V[A_1, ..., A_N], the instantiation
121 // T[A_1, ..., A_N] is valid and V[A_1, ..., A_N] implements T[A_1, ..., A_N].
122 //
123 // If T has structural constraints, they must be satisfied by V.
124 //
125 // For example, consider the following type declarations:
126 //
127 // type Interface[T any] interface {
128 // Accept(T)
129 // }
130 //
131 // type Container[T any] struct {
132 // Element T
133 // }
134 //
135 // func (c Container[T]) Accept(t T) { c.Element = t }
136 //
137 // In this case, GenericAssignableTo reports that instantiations of Container
138 // are assignable to the corresponding instantiation of Interface.
139 func GenericAssignableTo(ctxt *Context, V, T types.Type) bool {
140 // If V and T are not both named, or do not have matching non-empty type
141 // parameter lists, fall back on types.AssignableTo.
142
143 VN, Vnamed := V.(*types.Named)
144 TN, Tnamed := T.(*types.Named)
145 if !Vnamed || !Tnamed {
146 return types.AssignableTo(V, T)
147 }
148
149 vtparams := ForNamed(VN)
150 ttparams := ForNamed(TN)
151 if vtparams.Len() == 0 || vtparams.Len() != ttparams.Len() || NamedTypeArgs(VN).Len() != 0 || NamedTypeArgs(TN).Len() != 0 {
152 return types.AssignableTo(V, T)
153 }
154
155 // V and T have the same (non-zero) number of type params. Instantiate both
156 // with the type parameters of V. This must always succeed for V, and will
157 // succeed for T if and only if the type set of each type parameter of V is a
158 // subset of the type set of the corresponding type parameter of T, meaning
159 // that every instantiation of V corresponds to a valid instantiation of T.
160
161 // Minor optimization: ensure we share a context across the two
162 // instantiations below.
163 if ctxt == nil {
164 ctxt = NewContext()
165 }
166
167 var targs []types.Type
168 for i := 0; i < vtparams.Len(); i++ {
169 targs = append(targs, vtparams.At(i))
170 }
171
172 vinst, err := Instantiate(ctxt, V, targs, true)
173 if err != nil {
174 panic("type parameters should satisfy their own constraints")
175 }
176
177 tinst, err := Instantiate(ctxt, T, targs, true)
178 if err != nil {
179 return false
180 }
181
182 return types.AssignableTo(vinst, tinst)
183 }