Debian Codegraph @

gopls/internal/analysis/fillreturns/fillreturns.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 fillreturns
6
7 import (
8 "bytes"
9 _ "embed"
10 "fmt"
11 "go/ast"
12 "go/format"
13 "go/token"
14 "go/types"
15 "regexp"
16 "slices"
17 "strings"
18
19 "golang.org/x/tools/go/analysis"
20 "golang.org/x/tools/go/analysis/passes/inspect"
21 "golang.org/x/tools/go/ast/inspector"
22 "golang.org/x/tools/gopls/internal/fuzzy"
23 "golang.org/x/tools/gopls/internal/util/cursorutil"
24 "golang.org/x/tools/internal/analysis/analyzerutil"
25 "golang.org/x/tools/internal/moreiters"
26 "golang.org/x/tools/internal/typesinternal"
27 )
28
29 //go:embed doc.go
30 var doc string
31
32 var Analyzer = &analysis.Analyzer{
33 Name: "fillreturns",
34 Doc: analyzerutil.MustExtractDoc(doc, "fillreturns"),
35 Requires: []*analysis.Analyzer{inspect.Analyzer},
36 Run: run,
37 RunDespiteErrors: true,
38 URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/fillreturns",
39 }
40
41 func run(pass *analysis.Pass) (any, error) {
42 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
43 info := pass.TypesInfo
44
45 outer:
46 for _, typeErr := range pass.TypeErrors {
47 if !fixesError(typeErr) {
48 continue // irrelevant type error
49 }
50 _, start, end, ok := typesinternal.ErrorCodeStartEnd(typeErr)
51 if !ok {
52 continue // no position information
53 }
54 curErr, ok := inspect.Root().FindByPos(start, end)
55 if !ok {
56 continue // can't find node
57 }
58
59 // Find cursor for enclosing return statement (which may be curErr itself).
60 ret, curRet := cursorutil.FirstEnclosing[*ast.ReturnStmt](curErr)
61 if ret == nil {
62 continue // no enclosing return
63 }
64
65 // Skip if any return argument is a tuple-valued function call.
66 for _, expr := range ret.Results {
67 e, ok := expr.(*ast.CallExpr)
68 if !ok {
69 continue
70 }
71 if tup, ok := info.TypeOf(e).(*types.Tuple); ok && tup.Len() > 1 {
72 continue outer
73 }
74 }
75
76 // Get type of innermost enclosing function.
77 var funcType *ast.FuncType
78 curFunc, _ := enclosingFunc(curRet) // can't fail
79 switch fn := curFunc.Node().(type) {
80 case *ast.FuncLit:
81 funcType = fn.Type
82 case *ast.FuncDecl:
83 funcType = fn.Type
84
85 // Skip generic functions since type parameters don't have zero values.
86 // TODO(rfindley): We should be able to handle this if the return
87 // values are all concrete types.
88 if funcType.TypeParams.NumFields() > 0 {
89 continue
90 }
91 }
92 if funcType.Results == nil {
93 continue
94 }
95
96 // Duplicate the return values to track which values have been matched.
97 remaining := make([]ast.Expr, len(ret.Results))
98 copy(remaining, ret.Results)
99
100 fixed := make([]ast.Expr, len(funcType.Results.List))
101
102 // For each value in the return function declaration, find the leftmost element
103 // in the return statement that has the desired type. If no such element exists,
104 // fill in the missing value with the appropriate "zero" value.
105 // Beware that type information may be incomplete.
106 var retTyps []types.Type
107 for _, ret := range funcType.Results.List {
108 retTyp := info.TypeOf(ret.Type)
109 if retTyp == nil {
110 return nil, nil
111 }
112 retTyps = append(retTyps, retTyp)
113 }
114
115 file, _ := cursorutil.FirstEnclosing[*ast.File](curRet)
116 matches := MatchingIdents(retTyps, file, ret.Pos(), info, pass.Pkg)
117 qual := typesinternal.FileQualifier(file, pass.Pkg)
118 for i, retTyp := range retTyps {
119 var match ast.Expr
120 var idx int
121 for j, val := range remaining {
122 if t := info.TypeOf(val); t == nil || !matchingTypes(t, retTyp) {
123 continue
124 }
125 if !isZeroExpr(val) {
126 match, idx = val, j
127 break
128 }
129 // If the current match is a "zero" value, we keep searching in
130 // case we find a non-"zero" value match. If we do not find a
131 // non-"zero" value, we will use the "zero" value.
132 match, idx = val, j
133 }
134
135 if match != nil {
136 fixed[i] = match
137 remaining = slices.Delete(remaining, idx, idx+1)
138 } else {
139 names, ok := matches[retTyp]
140 if !ok {
141 return nil, fmt.Errorf("invalid return type: %v", retTyp)
142 }
143 // Find the identifier most similar to the return type.
144 // If no identifier matches the pattern, generate a zero value.
145 if best := fuzzy.BestMatch(retTyp.String(), names); best != "" {
146 fixed[i] = ast.NewIdent(best)
147 } else if zero, isValid := typesinternal.ZeroExpr(retTyp, qual); isValid {
148 fixed[i] = zero
149 } else {
150 return nil, nil
151 }
152 }
153 }
154
155 // Remove any non-matching "zero values" from the leftover values.
156 var nonZeroRemaining []ast.Expr
157 for _, expr := range remaining {
158 if !isZeroExpr(expr) {
159 nonZeroRemaining = append(nonZeroRemaining, expr)
160 }
161 }
162 // Append leftover return values to end of new return statement.
163 fixed = append(fixed, nonZeroRemaining...)
164
165 newRet := &ast.ReturnStmt{
166 Return: ret.Pos(),
167 Results: fixed,
168 }
169
170 // Convert the new return statement AST to text.
171 var newBuf bytes.Buffer
172 if err := format.Node(&newBuf, pass.Fset, newRet); err != nil {
173 return nil, err
174 }
175
176 pass.Report(analysis.Diagnostic{
177 Pos: start,
178 End: end,
179 Message: typeErr.Msg,
180 SuggestedFixes: []analysis.SuggestedFix{{
181 Message: "Fill in return values",
182 TextEdits: []analysis.TextEdit{{
183 Pos: ret.Pos(),
184 End: ret.End(),
185 NewText: newBuf.Bytes(),
186 }},
187 }},
188 })
189 }
190 return nil, nil
191 }
192
193 func matchingTypes(want, got types.Type) bool {
194 if want == got || types.Identical(want, got) {
195 return true
196 }
197 // Code segment to help check for untyped equality from (golang/go#32146).
198 if rhs, ok := want.(*types.Basic); ok && rhs.Info()&types.IsUntyped > 0 {
199 if lhs, ok := got.Underlying().(*types.Basic); ok {
200 return rhs.Info()&types.IsConstType == lhs.Info()&types.IsConstType
201 }
202 }
203 return types.AssignableTo(want, got) || types.ConvertibleTo(want, got)
204 }
205
206 // Error messages have changed across Go versions. These regexps capture recent
207 // incarnations.
208 //
209 // TODO(rfindley): once error codes are exported and exposed via go/packages,
210 // use error codes rather than string matching here.
211 var wrongReturnNumRegexes = []*regexp.Regexp{
212 regexp.MustCompile(`wrong number of return values \(want (\d+), got (\d+)\)`),
213 regexp.MustCompile(`too many return values`),
214 regexp.MustCompile(`not enough return values`),
215 }
216
217 func fixesError(err types.Error) bool {
218 msg := strings.TrimSpace(err.Msg)
219 for _, rx := range wrongReturnNumRegexes {
220 if rx.MatchString(msg) {
221 return true
222 }
223 }
224 return false
225 }
226
227 // enclosingFunc returns the cursor for the innermost Func{Decl,Lit}
228 // that encloses c, if any.
229 func enclosingFunc(c inspector.Cursor) (inspector.Cursor, bool) {
230 return moreiters.First(c.Enclosing((*ast.FuncDecl)(nil), (*ast.FuncLit)(nil)))
231 }
232
233 // isZeroExpr uses simple syntactic heuristics to report whether expr
234 // is a obvious zero value, such as 0, "", nil, or false.
235 // It cannot do better without type information.
236 func isZeroExpr(expr ast.Expr) bool {
237 switch e := expr.(type) {
238 case *ast.BasicLit:
239 return e.Value == "0" || e.Value == `""`
240 case *ast.Ident:
241 return e.Name == "nil" || e.Name == "false"
242 default:
243 return false
244 }
245 }
246
247 // MatchingIdents finds the names of all identifiers in 'node' that match any of the given types.
248 // 'pos' represents the position at which the identifiers may be inserted. 'pos' must be within
249 // the scope of each of identifier we select. Otherwise, we will insert a variable at 'pos' that
250 // is unrecognized.
251 //
252 // This function is shared with the 'fillstruct' analyzer.
253 func MatchingIdents(typs []types.Type, node ast.Node, pos token.Pos, info *types.Info, pkg *types.Package) map[types.Type][]string {
254
255 // Initialize matches to contain the variable types we are searching for.
256 matches := make(map[types.Type][]string)
257 for _, typ := range typs {
258 if typ == nil {
259 continue // TODO(adonovan): is this reachable?
260 }
261 matches[typ] = nil // create entry
262 }
263
264 seen := map[types.Object]struct{}{}
265 ast.Inspect(node, func(n ast.Node) bool {
266 if n == nil {
267 return false
268 }
269 // Prevent circular definitions. If 'pos' is within an assignment statement, do not
270 // allow any identifiers in that assignment statement to be selected. Otherwise,
271 // we could do the following, where 'x' satisfies the type of 'f0':
272 //
273 // x := fakeStruct{f0: x}
274 //
275 if assign, ok := n.(*ast.AssignStmt); ok && pos > assign.Pos() && pos <= assign.End() {
276 return false
277 }
278 if n.End() > pos {
279 return n.Pos() <= pos
280 }
281 ident, ok := n.(*ast.Ident)
282 if !ok || ident.Name == "_" {
283 return true
284 }
285 obj := info.Defs[ident]
286 if obj == nil || obj.Type() == nil {
287 return true
288 }
289 if _, ok := obj.(*types.TypeName); ok {
290 return true
291 }
292 // Prevent duplicates in matches' values.
293 if _, ok = seen[obj]; ok {
294 return true
295 }
296 seen[obj] = struct{}{}
297 // Find the scope for the given position. Then, check whether the object
298 // exists within the scope.
299 innerScope := pkg.Scope().Innermost(pos)
300 if innerScope == nil {
301 return true
302 }
303 _, foundObj := innerScope.LookupParent(ident.Name, pos)
304 if foundObj != obj {
305 return true
306 }
307 // The object must match one of the types that we are searching for.
308 // TODO(adonovan): opt: use typeutil.Map?
309 if names, ok := matches[obj.Type()]; ok {
310 matches[obj.Type()] = append(names, ident.Name)
311 } else {
312 // If the object type does not exactly match
313 // any of the target types, greedily find the first
314 // target type that the object type can satisfy.
315 for typ := range matches {
316 if equivalentTypes(obj.Type(), typ) {
317 matches[typ] = append(matches[typ], ident.Name)
318 }
319 }
320 }
321 return true
322 })
323 return matches
324 }
325
326 func equivalentTypes(want, got types.Type) bool {
327 if types.Identical(want, got) {
328 return true
329 }
330 // Code segment to help check for untyped equality from (golang/go#32146).
331 if rhs, ok := want.(*types.Basic); ok && rhs.Info()&types.IsUntyped > 0 {
332 if lhs, ok := got.Underlying().(*types.Basic); ok {
333 return rhs.Info()&types.IsConstType == lhs.Info()&types.IsConstType
334 }
335 }
336 return types.AssignableTo(want, got)
337 }