Debian Codegraph @

gopls/internal/golang/undeclared.go

raw symbols SCIP
1 // Copyright 2020 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 golang
6
7 import (
8 "bytes"
9 "fmt"
10 "go/ast"
11 "go/format"
12 "go/token"
13 "go/types"
14 "strings"
15 "unicode"
16
17 "golang.org/x/tools/go/analysis"
18 "golang.org/x/tools/go/ast/edge"
19 "golang.org/x/tools/go/ast/inspector"
20 "golang.org/x/tools/gopls/internal/cache"
21 "golang.org/x/tools/gopls/internal/cache/parsego"
22 "golang.org/x/tools/gopls/internal/util/cursorutil"
23 "golang.org/x/tools/gopls/internal/util/typesutil"
24 "golang.org/x/tools/internal/typesinternal"
25 )
26
27 // The prefix for this error message changed in Go 1.20.
28 var undeclaredNamePrefixes = []string{"undeclared name: ", "undefined: "}
29
30 // undeclaredFixTitle generates a code action title for "undeclared name" errors,
31 // suggesting the creation of the missing variable or function if applicable.
32 func undeclaredFixTitle(curId inspector.Cursor, errMsg string) string {
33 // Extract symbol name from error.
34 var name string
35 for _, prefix := range undeclaredNamePrefixes {
36 if !strings.HasPrefix(errMsg, prefix) {
37 continue
38 }
39 name = strings.TrimPrefix(errMsg, prefix)
40 }
41 ident, ok := curId.Node().(*ast.Ident)
42 if !ok || ident.Name != name {
43 return ""
44 }
45 // TODO: support create undeclared field
46 if _, ok := curId.Parent().Node().(*ast.SelectorExpr); ok {
47 return ""
48 }
49
50 // Undeclared quick fixes only work in function bodies.
51 block, _ := cursorutil.FirstEnclosing[*ast.BlockStmt](curId)
52 if block == nil {
53 return ""
54 }
55
56 // Offer a fix.
57 noun := cond(curId.ParentEdgeKind() == edge.CallExpr_Fun, "function", "variable")
58 return fmt.Sprintf("Create %s %s", noun, name)
59 }
60
61 // createUndeclared generates a suggested declaration for an undeclared variable or function.
62 func createUndeclared(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) {
63 var (
64 fset = pkg.FileSet()
65 info = pkg.TypesInfo()
66 file = pgf.File
67 pos = start // don't use end
68 )
69 curId, _ := pgf.Cursor().FindByPos(pos, pos)
70 ident, ok := curId.Node().(*ast.Ident)
71 if !ok {
72 return nil, nil, fmt.Errorf("no identifier found")
73 }
74
75 // Check for a possible call expression, in which case we should add a
76 // new function declaration.
77 if curId.ParentEdgeKind() == edge.CallExpr_Fun {
78 return newFunctionDeclaration(curId, file, pkg.Types(), info, fset)
79 }
80 // We should insert the new declaration before the
81 // first occurrence of the undefined ident.
82 var curFirstRef inspector.Cursor // *ast.Ident
83
84 // Search from enclosing FuncDecl to first use, since we can not use := syntax outside function.
85 // Adds the missing colon under the following conditions:
86 // 1) parent node must be an *ast.AssignStmt with Tok set to token.ASSIGN.
87 // 2) ident must not be self assignment.
88 //
89 // For example, we should not add a colon when
90 // a = a + 1
91 // ^ ^ cursor here
92 _, curFuncDecl := cursorutil.FirstEnclosing[*ast.FuncDecl](curId)
93 for curRef := range curFuncDecl.Preorder((*ast.Ident)(nil)) {
94 n := curRef.Node().(*ast.Ident)
95 if n.Name == ident.Name && info.ObjectOf(n) == nil {
96 if curRef.ParentEdgeKind() == edge.AssignStmt_Lhs {
97 assign := curRef.Parent().Node().(*ast.AssignStmt)
98 if assign.Tok == token.ASSIGN && !referencesIdent(info, assign, ident) {
99 // replace = with :=
100 return fset, &analysis.SuggestedFix{
101 TextEdits: []analysis.TextEdit{{
102 Pos: assign.TokPos,
103 End: assign.TokPos,
104 NewText: []byte(":"),
105 }},
106 }, nil
107 }
108 }
109 curFirstRef = curRef
110 break
111 }
112 }
113
114 // firstRef should never be nil; at least one ident at cursor
115 // position should be found. But be defensive.
116 if !curFirstRef.Valid() {
117 return nil, nil, fmt.Errorf("no identifier found")
118 }
119 insertPos, err := stmtToInsertVarBefore(curFirstRef, nil)
120 if err != nil {
121 return nil, nil, fmt.Errorf("could not locate insertion point: %v", err)
122 }
123 indent, err := pgf.Indentation(insertPos)
124 if err != nil {
125 return nil, nil, err
126 }
127 typs := typesutil.TypesFromContext(info, curId)
128 if typs == nil {
129 // Default to 0.
130 typs = []types.Type{types.Typ[types.Int]}
131 }
132 expr, _ := typesinternal.ZeroExpr(typs[0], typesinternal.FileQualifier(file, pkg.Types()))
133 assignStmt := &ast.AssignStmt{
134 Lhs: []ast.Expr{ast.NewIdent(ident.Name)},
135 Tok: token.DEFINE,
136 Rhs: []ast.Expr{expr},
137 }
138 var buf bytes.Buffer
139 if err := format.Node(&buf, fset, assignStmt); err != nil {
140 return nil, nil, err
141 }
142 newLineIndent := "\n" + indent
143 assignment := strings.ReplaceAll(buf.String(), "\n", newLineIndent) + newLineIndent
144
145 return fset, &analysis.SuggestedFix{
146 TextEdits: []analysis.TextEdit{
147 {
148 Pos: insertPos,
149 End: insertPos,
150 NewText: []byte(assignment),
151 },
152 },
153 }, nil
154 }
155
156 // referencesIdent checks whether the given undefined ident appears in the right-hand side
157 // of an assign statement
158 func referencesIdent(info *types.Info, assign *ast.AssignStmt, ident *ast.Ident) bool {
159 for _, rhs := range assign.Rhs {
160 for n := range ast.Preorder(rhs) {
161 if id, ok := n.(*ast.Ident); ok &&
162 id.Name == ident.Name && info.Uses[id] == nil {
163 return true
164 }
165 }
166 }
167 return false
168 }
169
170 // newFunctionDeclaration returns a suggested declaration for the ident identified by curId
171 // curId always points at an ast.Ident at the CallExpr_Fun edge.
172 func newFunctionDeclaration(curId inspector.Cursor, file *ast.File, pkg *types.Package, info *types.Info, fset *token.FileSet) (*token.FileSet, *analysis.SuggestedFix, error) {
173
174 id := curId.Node().(*ast.Ident)
175 call := curId.Parent().Node().(*ast.CallExpr)
176
177 // Find the enclosing function, so that we can add the new declaration
178 // below.
179 funcdecl, _ := cursorutil.FirstEnclosing[*ast.FuncDecl](curId)
180 if funcdecl == nil {
181 // TODO(rstambler): Support the situation when there is no enclosing
182 // function.
183 return nil, nil, fmt.Errorf("no enclosing function found: %v", curId)
184 }
185
186 pos := funcdecl.End()
187
188 var paramNames []string
189 var paramTypes []types.Type
190 // keep track of all param names to later ensure uniqueness
191 nameCounts := map[string]int{}
192 for _, arg := range call.Args {
193 typ := info.TypeOf(arg)
194 if typ == nil {
195 return nil, nil, fmt.Errorf("unable to determine type for %s", arg)
196 }
197
198 switch t := typ.(type) {
199 // this is the case where another function call returning multiple
200 // results is used as an argument
201 case *types.Tuple:
202 n := t.Len()
203 for i := range n {
204 name := typeToArgName(t.At(i).Type())
205 nameCounts[name]++
206
207 paramNames = append(paramNames, name)
208 paramTypes = append(paramTypes, types.Default(t.At(i).Type()))
209 }
210
211 default:
212 // does the argument have a name we can reuse?
213 // only happens in case of a *ast.Ident
214 var name string
215 if ident, ok := arg.(*ast.Ident); ok {
216 name = ident.Name
217 }
218
219 if name == "" {
220 name = typeToArgName(typ)
221 }
222
223 nameCounts[name]++
224
225 paramNames = append(paramNames, name)
226 paramTypes = append(paramTypes, types.Default(typ))
227 }
228 }
229
230 for n, c := range nameCounts {
231 // Any names we saw more than once will need a unique suffix added
232 // on. Reset the count to 1 to act as the suffix for the first
233 // occurrence of that name.
234 if c >= 2 {
235 nameCounts[n] = 1
236 } else {
237 delete(nameCounts, n)
238 }
239 }
240
241 params := &ast.FieldList{}
242 qual := typesinternal.FileQualifier(file, pkg)
243 for i, name := range paramNames {
244 if suffix, repeats := nameCounts[name]; repeats {
245 nameCounts[name]++
246 name = fmt.Sprintf("%s%d", name, suffix)
247 }
248
249 // only worth checking after previous param in the list
250 if i > 0 {
251 // if type of parameter at hand is the same as the previous one,
252 // add it to the previous param list of identifiers so to have:
253 // (s1, s2 string)
254 // and not
255 // (s1 string, s2 string)
256 if paramTypes[i] == paramTypes[i-1] {
257 params.List[len(params.List)-1].Names = append(params.List[len(params.List)-1].Names, ast.NewIdent(name))
258 continue
259 }
260 }
261
262 params.List = append(params.List, &ast.Field{
263 Names: []*ast.Ident{
264 ast.NewIdent(name),
265 },
266 Type: typesinternal.TypeExpr(paramTypes[i], qual),
267 })
268 }
269
270 rets := &ast.FieldList{}
271 retTypes := typesutil.TypesFromContext(info, curId.Parent())
272 for _, rt := range retTypes {
273 rets.List = append(rets.List, &ast.Field{
274 Type: typesinternal.TypeExpr(rt, qual),
275 })
276 }
277
278 decl := &ast.FuncDecl{
279 Name: ast.NewIdent(id.Name),
280 Type: &ast.FuncType{
281 Params: params,
282 Results: rets,
283 },
284 Body: &ast.BlockStmt{
285 List: []ast.Stmt{
286 &ast.ExprStmt{
287 X: &ast.CallExpr{
288 Fun: ast.NewIdent("panic"),
289 Args: []ast.Expr{
290 &ast.BasicLit{
291 Value: `"unimplemented"`,
292 },
293 },
294 },
295 },
296 },
297 },
298 }
299
300 b := bytes.NewBufferString("\n\n")
301 if err := format.Node(b, fset, decl); err != nil {
302 return nil, nil, err
303 }
304 return fset, &analysis.SuggestedFix{
305 TextEdits: []analysis.TextEdit{{
306 Pos: pos,
307 End: pos,
308 NewText: b.Bytes(),
309 }},
310 }, nil
311 }
312
313 func typeToArgName(ty types.Type) string {
314 s := types.Default(ty).String()
315
316 switch t := types.Unalias(ty).(type) {
317 case *types.Basic:
318 // use first letter in type name for basic types
319 return s[0:1]
320 case *types.Slice:
321 // use element type to decide var name for slices
322 return typeToArgName(t.Elem())
323 case *types.Array:
324 // use element type to decide var name for arrays
325 return typeToArgName(t.Elem())
326 case *types.Chan:
327 return "ch"
328 }
329
330 s = strings.TrimFunc(s, func(r rune) bool {
331 return !unicode.IsLetter(r)
332 })
333
334 if s == "error" {
335 return "err"
336 }
337
338 // remove package (if present)
339 // and make first letter lowercase
340 a := []rune(s[strings.LastIndexByte(s, '.')+1:])
341 a[0] = unicode.ToLower(a[0])
342 return string(a)
343 }