Debian Codegraph @

gopls/internal/util/typesutil/typesutil.go

raw symbols SCIP
1 // Copyright 2023 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 typesutil
6
7 import (
8 "bytes"
9 "go/ast"
10 "go/token"
11 "go/types"
12 "strings"
13
14 "golang.org/x/tools/go/ast/edge"
15 "golang.org/x/tools/go/ast/inspector"
16 )
17
18 // FormatTypeParams turns TypeParamList into its Go representation, such as:
19 // [T, Y]. Note that it does not print constraints as this is mainly used for
20 // formatting type params in method receivers.
21 func FormatTypeParams(tparams *types.TypeParamList) string {
22 if tparams == nil || tparams.Len() == 0 {
23 return ""
24 }
25 var buf bytes.Buffer
26 buf.WriteByte('[')
27 for i := 0; i < tparams.Len(); i++ {
28 if i > 0 {
29 buf.WriteString(", ")
30 }
31 buf.WriteString(tparams.At(i).Obj().Name())
32 }
33 buf.WriteByte(']')
34 return buf.String()
35 }
36
37 // TypesFromContext returns the type (or perhaps zero or multiple types)
38 // of the "hole" into which the expression identified by path must fit.
39 //
40 // For example, given
41 //
42 // s, i := "", 0
43 // s, i = EXPR
44 //
45 // the hole that must be filled by EXPR has type (string, int).
46 //
47 // It returns nil on failure.
48 func TypesFromContext(info *types.Info, cur inspector.Cursor) []types.Type {
49 anyType := types.Universe.Lookup("any").Type()
50 var typs []types.Type
51
52 // TODO: do cur = unparenEnclosing(cur), once CL 701035 lands.
53 for cur.ParentEdgeKind() == edge.ParenExpr_X {
54 cur = cur.Parent()
55 }
56
57 validType := func(t types.Type) types.Type {
58 if t != nil && !containsInvalid(t) {
59 return types.Default(t)
60 } else {
61 return anyType
62 }
63 }
64
65 ek, idx := cur.ParentEdge()
66 switch ek {
67 case edge.AssignStmt_Lhs, edge.AssignStmt_Rhs:
68 assign := cur.Parent().Node().(*ast.AssignStmt)
69 // Append all lhs's type
70 if len(assign.Rhs) == 1 {
71 for _, lhs := range assign.Lhs {
72 t := info.TypeOf(lhs)
73 typs = append(typs, validType(t))
74 }
75 break
76 }
77 // Lhs and Rhs counts do not match, give up
78 if len(assign.Lhs) != len(assign.Rhs) {
79 break
80 }
81 // Append corresponding index of lhs's type
82 if ek == edge.AssignStmt_Rhs {
83 t := info.TypeOf(assign.Lhs[idx])
84 typs = append(typs, validType(t))
85 }
86 case edge.ValueSpec_Names, edge.ValueSpec_Type, edge.ValueSpec_Values:
87 spec := cur.Parent().Node().(*ast.ValueSpec)
88 if len(spec.Values) == 1 {
89 for _, lhs := range spec.Names {
90 t := info.TypeOf(lhs)
91 typs = append(typs, validType(t))
92 }
93 break
94 }
95 if len(spec.Values) != len(spec.Names) {
96 break
97 }
98 t := info.TypeOf(spec.Type)
99 typs = append(typs, validType(t))
100 case edge.ReturnStmt_Results:
101 returnstmt := cur.Parent().Node().(*ast.ReturnStmt)
102 sig := EnclosingSignature(cur, info)
103 if sig == nil || sig.Results() == nil {
104 break
105 }
106 retsig := sig.Results()
107 // Append all return declarations' type
108 if len(returnstmt.Results) == 1 {
109 for v := range retsig.Variables() {
110 t := v.Type()
111 typs = append(typs, validType(t))
112 }
113 break
114 }
115 // Return declaration and actual return counts do not match, give up
116 if retsig.Len() != len(returnstmt.Results) {
117 break
118 }
119 // Append corresponding index of return declaration's type
120 t := retsig.At(idx).Type()
121 typs = append(typs, validType(t))
122
123 case edge.CallExpr_Args:
124 call := cur.Parent().Node().(*ast.CallExpr)
125 t := info.TypeOf(call.Fun)
126 if t == nil {
127 break
128 }
129
130 if sig, ok := t.Underlying().(*types.Signature); ok {
131 var paramType types.Type
132 if sig.Variadic() && idx >= sig.Params().Len()-1 {
133 v := sig.Params().At(sig.Params().Len() - 1)
134 if s, _ := v.Type().(*types.Slice); s != nil {
135 paramType = s.Elem()
136 }
137 } else if idx < sig.Params().Len() {
138 paramType = sig.Params().At(idx).Type()
139 } else {
140 break
141 }
142 if paramType == nil || containsInvalid(paramType) {
143 paramType = anyType
144 }
145 typs = append(typs, paramType)
146 }
147 case edge.IfStmt_Cond:
148 typs = append(typs, types.Typ[types.Bool])
149 case edge.ForStmt_Cond:
150 typs = append(typs, types.Typ[types.Bool])
151 case edge.UnaryExpr_X:
152 unexpr := cur.Parent().Node().(*ast.UnaryExpr)
153 var t types.Type
154 switch unexpr.Op {
155 case token.NOT:
156 t = types.Typ[types.Bool]
157 case token.ADD, token.SUB, token.XOR:
158 t = types.Typ[types.Int]
159 default:
160 t = anyType
161 }
162 typs = append(typs, t)
163 case edge.BinaryExpr_X, edge.BinaryExpr_Y:
164 binexpr := cur.Parent().Node().(*ast.BinaryExpr)
165 switch ek {
166 case edge.BinaryExpr_X:
167 t := info.TypeOf(binexpr.Y)
168 typs = append(typs, validType(t))
169 case edge.BinaryExpr_Y:
170 t := info.TypeOf(binexpr.X)
171 typs = append(typs, validType(t))
172 }
173 default:
174 // TODO: support other kinds of "holes" as the need arises.
175 }
176 return typs
177 }
178
179 // containsInvalid checks if the type name contains "invalid type",
180 // which is not a valid syntax to generate.
181 func containsInvalid(t types.Type) bool {
182 typeString := types.TypeString(t, nil)
183 return strings.Contains(typeString, types.Typ[types.Invalid].String())
184 }
185
186 // EnclosingSignature returns the signature of the innermost
187 // function enclosing the syntax node denoted by cur.
188 // It returns nil if the node is not within a function,
189 // or the function's type information is missing
190 // (for example because there are duplicate func declarations).
191 func EnclosingSignature(cur inspector.Cursor, info *types.Info) *types.Signature {
192 for c := range cur.Enclosing((*ast.FuncDecl)(nil), (*ast.FuncLit)(nil)) {
193 switch n := c.Node().(type) {
194 case *ast.FuncDecl:
195 if f, ok := info.Defs[n.Name]; ok {
196 return f.Type().(*types.Signature)
197 }
198 // FuncDecl defines no types.Func (#70666).
199 // Example:
200 // func f(); func f()
201 // The same name is defined twice, but only
202 // one results in a symbol being inserted into
203 // the package scope.
204 //
205 // (It is tempting to change the type checker
206 // to populate Defs with a second Func f that is
207 // not in the Package scope, but this would only
208 // lead to different inconsistencies.)
209 return nil
210
211 case *ast.FuncLit:
212 if f, ok := info.Types[n]; ok {
213 return f.Type.(*types.Signature)
214 }
215 // Presumably this is also reachable in case
216 // of missing type information.
217 return nil
218 }
219 }
220 return nil
221 }