| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 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 |
| 49 |
} |
| 50 |
_, start, end, ok := typesinternal.ErrorCodeStartEnd(typeErr) |
| 51 |
if !ok { |
| 52 |
continue |
| 53 |
} |
| 54 |
curErr, ok := inspect.Root().FindByPos(start, end) |
| 55 |
if !ok { |
| 56 |
continue |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
ret, curRet := cursorutil.FirstEnclosing[*ast.ReturnStmt](curErr) |
| 61 |
if ret == nil { |
| 62 |
continue |
| 63 |
} |
| 64 |
|
| 65 |
|
| 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 |
|
| 77 |
var funcType *ast.FuncType |
| 78 |
curFunc, _ := enclosingFunc(curRet) |
| 79 |
switch fn := curFunc.Node().(type) { |
| 80 |
case *ast.FuncLit: |
| 81 |
funcType = fn.Type |
| 82 |
case *ast.FuncDecl: |
| 83 |
funcType = fn.Type |
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
if funcType.TypeParams.NumFields() > 0 { |
| 89 |
continue |
| 90 |
} |
| 91 |
} |
| 92 |
if funcType.Results == nil { |
| 93 |
continue |
| 94 |
} |
| 95 |
|
| 96 |
|
| 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 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 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 |
|
| 130 |
|
| 131 |
|
| 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 |
|
| 144 |
|
| 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 |
|
| 156 |
var nonZeroRemaining []ast.Expr |
| 157 |
for _, expr := range remaining { |
| 158 |
if !isZeroExpr(expr) { |
| 159 |
nonZeroRemaining = append(nonZeroRemaining, expr) |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
fixed = append(fixed, nonZeroRemaining...) |
| 164 |
|
| 165 |
newRet := &ast.ReturnStmt{ |
| 166 |
Return: ret.Pos(), |
| 167 |
Results: fixed, |
| 168 |
} |
| 169 |
|
| 170 |
|
| 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 |
|
| 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 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
|
| 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 |
|
| 228 |
|
| 229 |
func enclosingFunc(c inspector.Cursor) (inspector.Cursor, bool) { |
| 230 |
return moreiters.First(c.Enclosing((*ast.FuncDecl)(nil), (*ast.FuncLit)(nil))) |
| 231 |
} |
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 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 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
func MatchingIdents(typs []types.Type, node ast.Node, pos token.Pos, info *types.Info, pkg *types.Package) map[types.Type][]string { |
| 254 |
|
| 255 |
|
| 256 |
matches := make(map[types.Type][]string) |
| 257 |
for _, typ := range typs { |
| 258 |
if typ == nil { |
| 259 |
continue |
| 260 |
} |
| 261 |
matches[typ] = nil |
| 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 |
|
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
|
| 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 |
|
| 293 |
if _, ok = seen[obj]; ok { |
| 294 |
return true |
| 295 |
} |
| 296 |
seen[obj] = struct{}{} |
| 297 |
|
| 298 |
|
| 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 |
|
| 308 |
|
| 309 |
if names, ok := matches[obj.Type()]; ok { |
| 310 |
matches[obj.Type()] = append(names, ident.Name) |
| 311 |
} else { |
| 312 |
|
| 313 |
|
| 314 |
|
| 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 |
|
| 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 |
} |