| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package golang |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"fmt" |
| 10 |
"go/ast" |
| 11 |
"go/format" |
| 12 |
"go/parser" |
| 13 |
"go/printer" |
| 14 |
"go/token" |
| 15 |
"go/types" |
| 16 |
"slices" |
| 17 |
"strconv" |
| 18 |
"strings" |
| 19 |
|
| 20 |
"golang.org/x/tools/go/analysis" |
| 21 |
"golang.org/x/tools/go/ast/edge" |
| 22 |
"golang.org/x/tools/go/ast/inspector" |
| 23 |
"golang.org/x/tools/gopls/internal/cache" |
| 24 |
"golang.org/x/tools/gopls/internal/cache/parsego" |
| 25 |
"golang.org/x/tools/gopls/internal/util/bug" |
| 26 |
"golang.org/x/tools/gopls/internal/util/cursorutil" |
| 27 |
"golang.org/x/tools/gopls/internal/util/safetoken" |
| 28 |
"golang.org/x/tools/internal/astutil" |
| 29 |
"golang.org/x/tools/internal/typesinternal" |
| 30 |
) |
| 31 |
|
| 32 |
|
| 33 |
func extractVariableOne(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) { |
| 34 |
countExtractVariable.Inc() |
| 35 |
return extractVariable(pkg, pgf, start, end, false) |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
func extractVariableAll(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) { |
| 40 |
countExtractVariableAll.Inc() |
| 41 |
return extractVariable(pkg, pgf, start, end, true) |
| 42 |
} |
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
func extractVariable(pkg *cache.Package, pgf *parsego.File, start, end token.Pos, all bool) (*token.FileSet, *analysis.SuggestedFix, error) { |
| 52 |
var ( |
| 53 |
fset = pkg.FileSet() |
| 54 |
info = pkg.TypesInfo() |
| 55 |
file = pgf.File |
| 56 |
) |
| 57 |
curExprs, err := canExtractVariable(info, pgf.Cursor(), start, end, all) |
| 58 |
if err != nil { |
| 59 |
return nil, nil, fmt.Errorf("cannot extract: %v", err) |
| 60 |
} |
| 61 |
expr0 := curExprs[0].Node().(ast.Expr) |
| 62 |
|
| 63 |
|
| 64 |
exprScopes := make([]*types.Scope, len(curExprs)) |
| 65 |
for i, curExpr := range curExprs { |
| 66 |
exprScopes[i] = info.Scopes[file].Innermost(curExpr.Node().Pos()) |
| 67 |
} |
| 68 |
|
| 69 |
hasCollision := func(name string) bool { |
| 70 |
for _, scope := range exprScopes { |
| 71 |
if s, _ := scope.LookupParent(name, token.NoPos); s != nil { |
| 72 |
return true |
| 73 |
} |
| 74 |
} |
| 75 |
return false |
| 76 |
} |
| 77 |
constant := info.Types[expr0].Value != nil |
| 78 |
|
| 79 |
|
| 80 |
baseName := cond(constant, "newConst", "newVar") |
| 81 |
var lhsNames []string |
| 82 |
switch expr := expr0.(type) { |
| 83 |
case *ast.CallExpr: |
| 84 |
tup, ok := info.TypeOf(expr).(*types.Tuple) |
| 85 |
if !ok { |
| 86 |
|
| 87 |
|
| 88 |
name, _ := generateName(0, baseName, hasCollision) |
| 89 |
lhsNames = append(lhsNames, name) |
| 90 |
|
| 91 |
} else { |
| 92 |
|
| 93 |
idx := 0 |
| 94 |
for range tup.Len() { |
| 95 |
|
| 96 |
var name string |
| 97 |
name, idx = generateName(idx, baseName, hasCollision) |
| 98 |
lhsNames = append(lhsNames, name) |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
default: |
| 103 |
|
| 104 |
name, _ := generateName(0, baseName, hasCollision) |
| 105 |
lhsNames = append(lhsNames, name) |
| 106 |
} |
| 107 |
|
| 108 |
|
| 109 |
var commonScope *types.Scope |
| 110 |
counter := make(map[*types.Scope]int) |
| 111 |
Outer: |
| 112 |
for _, scope := range exprScopes { |
| 113 |
for s := scope; s != nil; s = s.Parent() { |
| 114 |
counter[s]++ |
| 115 |
if counter[s] == len(exprScopes) { |
| 116 |
|
| 117 |
|
| 118 |
commonScope = s |
| 119 |
break Outer |
| 120 |
} |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
visible := curExprs[0] |
| 125 |
if commonScope != exprScopes[0] { |
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
child := exprScopes[0] |
| 130 |
for p := child; p != nil; p = p.Parent() { |
| 131 |
if p == commonScope { |
| 132 |
break |
| 133 |
} |
| 134 |
child = p |
| 135 |
} |
| 136 |
visible, _ = pgf.Cursor().FindByPos(child.Pos(), child.End()) |
| 137 |
} |
| 138 |
variables, err := collectFreeVars(info, file, expr0.Pos(), expr0.End(), expr0) |
| 139 |
if err != nil { |
| 140 |
return nil, nil, err |
| 141 |
} |
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
var ( |
| 154 |
insertPos token.Pos |
| 155 |
indentation string |
| 156 |
stmtOK bool |
| 157 |
) |
| 158 |
if funcDecl, _ := cursorutil.FirstEnclosing[*ast.FuncDecl](visible); funcDecl != nil && |
| 159 |
astutil.NodeContainsPos(funcDecl.Body, start) { |
| 160 |
|
| 161 |
beforePos, err := stmtToInsertVarBefore(visible, variables) |
| 162 |
if err != nil { |
| 163 |
return nil, nil, fmt.Errorf("cannot find location to insert extraction: %v", err) |
| 164 |
} |
| 165 |
|
| 166 |
indent, err := pgf.Indentation(beforePos) |
| 167 |
if err != nil { |
| 168 |
return nil, nil, err |
| 169 |
} |
| 170 |
insertPos = beforePos |
| 171 |
indentation = "\n" + indent |
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
|
| 182 |
|
| 183 |
stmtOK = !constant |
| 184 |
} else { |
| 185 |
|
| 186 |
|
| 187 |
for curDecl := range visible.Enclosing((*ast.FuncDecl)(nil), (*ast.GenDecl)(nil)) { |
| 188 |
insertPos = curDecl.Node().Pos() |
| 189 |
} |
| 190 |
indentation = "\n" |
| 191 |
} |
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
{ |
| 202 |
|
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
var newNode ast.Node |
| 213 |
if !stmtOK { |
| 214 |
|
| 215 |
var names []*ast.Ident |
| 216 |
for _, name := range lhsNames { |
| 217 |
names = append(names, ast.NewIdent(name)) |
| 218 |
} |
| 219 |
newNode = &ast.GenDecl{ |
| 220 |
Tok: cond(constant, token.CONST, token.VAR), |
| 221 |
Specs: []ast.Spec{ |
| 222 |
&ast.ValueSpec{ |
| 223 |
Names: names, |
| 224 |
Values: []ast.Expr{expr0}, |
| 225 |
}, |
| 226 |
}, |
| 227 |
} |
| 228 |
|
| 229 |
} else { |
| 230 |
|
| 231 |
var lhs []ast.Expr |
| 232 |
for _, name := range lhsNames { |
| 233 |
lhs = append(lhs, ast.NewIdent(name)) |
| 234 |
} |
| 235 |
newNode = &ast.AssignStmt{ |
| 236 |
Tok: token.DEFINE, |
| 237 |
Lhs: lhs, |
| 238 |
Rhs: []ast.Expr{expr0}, |
| 239 |
} |
| 240 |
} |
| 241 |
|
| 242 |
|
| 243 |
var buf bytes.Buffer |
| 244 |
if err := format.Node(&buf, fset, newNode); err != nil { |
| 245 |
return nil, nil, err |
| 246 |
} |
| 247 |
|
| 248 |
assignment := strings.ReplaceAll(buf.String(), "\n", indentation) + indentation |
| 249 |
textEdits := []analysis.TextEdit{{ |
| 250 |
Pos: insertPos, |
| 251 |
End: insertPos, |
| 252 |
NewText: []byte(assignment), |
| 253 |
}} |
| 254 |
for _, curExpr := range curExprs { |
| 255 |
e := curExpr.Node() |
| 256 |
textEdits = append(textEdits, analysis.TextEdit{ |
| 257 |
Pos: e.Pos(), |
| 258 |
End: e.End(), |
| 259 |
NewText: []byte(strings.Join(lhsNames, ", ")), |
| 260 |
}) |
| 261 |
} |
| 262 |
return fset, &analysis.SuggestedFix{ |
| 263 |
TextEdits: textEdits, |
| 264 |
}, nil |
| 265 |
} |
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
|
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
func stmtToInsertVarBefore(cur inspector.Cursor, variables []*variable) (token.Pos, error) { |
| 297 |
|
| 298 |
{ |
| 299 |
var curStmt inspector.Cursor |
| 300 |
for cur := range cur.Enclosing() { |
| 301 |
if is[ast.Stmt](cur.Node()) { |
| 302 |
curStmt = cur |
| 303 |
break |
| 304 |
} |
| 305 |
} |
| 306 |
if !curStmt.Valid() { |
| 307 |
return 0, fmt.Errorf("no enclosing statement") |
| 308 |
} |
| 309 |
cur = curStmt |
| 310 |
} |
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
hasFreeVar := func(stmt ast.Stmt) bool { |
| 315 |
if stmt == nil { |
| 316 |
return false |
| 317 |
} |
| 318 |
for _, v := range variables { |
| 319 |
if astutil.NodeContainsPos(stmt, v.obj.Pos()) { |
| 320 |
return true |
| 321 |
} |
| 322 |
} |
| 323 |
return false |
| 324 |
} |
| 325 |
|
| 326 |
|
| 327 |
|
| 328 |
baseIfStmt := func(curIf inspector.Cursor) (token.Pos, error) { |
| 329 |
for curIf.ParentEdgeKind() == edge.IfStmt_Else { |
| 330 |
curIf = curIf.Parent() |
| 331 |
if hasFreeVar(curIf.Node().(*ast.IfStmt).Init) { |
| 332 |
return 0, fmt.Errorf("else-if's init has free variable") |
| 333 |
} |
| 334 |
} |
| 335 |
return curIf.Node().Pos(), nil |
| 336 |
} |
| 337 |
|
| 338 |
stmt := cur.Node() |
| 339 |
switch stmt := stmt.(type) { |
| 340 |
case *ast.IfStmt: |
| 341 |
if hasFreeVar(stmt.Init) { |
| 342 |
return 0, fmt.Errorf("if statement's init has free variable") |
| 343 |
} |
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
return baseIfStmt(cur) |
| 348 |
|
| 349 |
case *ast.CaseClause: |
| 350 |
for curSwitch := range cur.Enclosing((*ast.SwitchStmt)(nil), (*ast.TypeSwitchStmt)(nil)) { |
| 351 |
swtch := curSwitch.Node() |
| 352 |
var init ast.Stmt |
| 353 |
switch swtch := swtch.(type) { |
| 354 |
case *ast.SwitchStmt: |
| 355 |
init = swtch.Init |
| 356 |
case *ast.TypeSwitchStmt: |
| 357 |
init = swtch.Init |
| 358 |
} |
| 359 |
if hasFreeVar(init) { |
| 360 |
return 0, fmt.Errorf("switch's init has free variable") |
| 361 |
} |
| 362 |
return swtch.Pos(), nil |
| 363 |
} |
| 364 |
} |
| 365 |
|
| 366 |
|
| 367 |
switch parent := cur.Parent().Node().(type) { |
| 368 |
case *ast.IfStmt: |
| 369 |
if hasFreeVar(parent.Init) { |
| 370 |
return 0, fmt.Errorf("if-statement's init has free variable") |
| 371 |
} |
| 372 |
return baseIfStmt(cur.Parent()) |
| 373 |
|
| 374 |
case *ast.ForStmt: |
| 375 |
switch cur.Node() { |
| 376 |
case parent.Init, parent.Post: |
| 377 |
return parent.Pos(), nil |
| 378 |
} |
| 379 |
|
| 380 |
case *ast.SwitchStmt: |
| 381 |
if hasFreeVar(parent.Init) { |
| 382 |
return 0, fmt.Errorf("switch's init has free variable") |
| 383 |
} |
| 384 |
return parent.Pos(), nil |
| 385 |
|
| 386 |
case *ast.TypeSwitchStmt: |
| 387 |
if hasFreeVar(parent.Init) { |
| 388 |
return 0, fmt.Errorf("switch's init has free variable") |
| 389 |
} |
| 390 |
return parent.Pos(), nil |
| 391 |
} |
| 392 |
return stmt.Pos(), nil |
| 393 |
} |
| 394 |
|
| 395 |
|
| 396 |
|
| 397 |
|
| 398 |
|
| 399 |
func canExtractVariable(info *types.Info, curFile inspector.Cursor, start, end token.Pos, all bool) ([]inspector.Cursor, error) { |
| 400 |
if start == end { |
| 401 |
return nil, fmt.Errorf("empty selection") |
| 402 |
} |
| 403 |
|
| 404 |
_, curStart, curEnd, err := astutil.Select(curFile, start, end) |
| 405 |
if err != nil { |
| 406 |
return nil, err |
| 407 |
} |
| 408 |
expr, ok := curStart.Node().(ast.Expr) |
| 409 |
if !ok || curEnd != curStart { |
| 410 |
return nil, fmt.Errorf("selection is not an expression") |
| 411 |
} |
| 412 |
if imp, _ := cursorutil.FirstEnclosing[*ast.ImportSpec](curStart); imp != nil { |
| 413 |
return nil, fmt.Errorf("cannot extract variable or constant in an import block") |
| 414 |
} |
| 415 |
if tv, ok := info.Types[expr]; !ok || !tv.IsValue() || tv.Type == nil || tv.HasOk() { |
| 416 |
|
| 417 |
return nil, fmt.Errorf("selection is not a single-valued expression") |
| 418 |
} |
| 419 |
|
| 420 |
var curExprs []inspector.Cursor |
| 421 |
if !all { |
| 422 |
curExprs = append(curExprs, curStart) |
| 423 |
} else if funcDecl, curFuncDecl := cursorutil.FirstEnclosing[*ast.FuncDecl](curStart); funcDecl != nil && funcDecl.Body != nil { |
| 424 |
|
| 425 |
|
| 426 |
for cur := range curFuncDecl.ChildAt(edge.FuncDecl_Body, -1).Preorder() { |
| 427 |
if e, ok := cur.Node().(ast.Expr); ok { |
| 428 |
if astutil.Equal(e, expr, func(x, y *ast.Ident) bool { |
| 429 |
xobj, yobj := info.ObjectOf(x), info.ObjectOf(y) |
| 430 |
|
| 431 |
|
| 432 |
|
| 433 |
|
| 434 |
if xobj != nil && astutil.NodeContainsPos(e, xobj.Pos()) && |
| 435 |
yobj != nil && astutil.NodeContainsPos(expr, yobj.Pos()) { |
| 436 |
return x.Name == y.Name |
| 437 |
} |
| 438 |
|
| 439 |
|
| 440 |
|
| 441 |
|
| 442 |
|
| 443 |
|
| 444 |
xuse := info.Uses[x] |
| 445 |
return xuse != nil && xuse == info.Uses[y] |
| 446 |
}) { |
| 447 |
curExprs = append(curExprs, cur) |
| 448 |
} |
| 449 |
} |
| 450 |
} |
| 451 |
} else { |
| 452 |
return nil, fmt.Errorf("node %T is not inside a function", expr) |
| 453 |
} |
| 454 |
|
| 455 |
|
| 456 |
|
| 457 |
|
| 458 |
|
| 459 |
|
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
|
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
|
| 470 |
|
| 471 |
|
| 472 |
|
| 473 |
|
| 474 |
|
| 475 |
|
| 476 |
|
| 477 |
|
| 478 |
|
| 479 |
|
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
|
| 484 |
|
| 485 |
for _, curExpr := range curExprs { |
| 486 |
switch curExpr.ParentEdgeKind() { |
| 487 |
case edge.AssignStmt_Lhs: |
| 488 |
return nil, fmt.Errorf("node %T is in LHS of an AssignStmt", expr) |
| 489 |
case edge.ValueSpec_Names: |
| 490 |
return nil, fmt.Errorf("node %T is in LHS of a ValueSpec", expr) |
| 491 |
} |
| 492 |
} |
| 493 |
|
| 494 |
return curExprs, nil |
| 495 |
} |
| 496 |
|
| 497 |
|
| 498 |
|
| 499 |
|
| 500 |
func freshName(info *types.Info, file *ast.File, pos token.Pos, prefix string, idx int) (string, int) { |
| 501 |
scope := info.Scopes[file].Innermost(pos) |
| 502 |
return generateName(idx, prefix, func(name string) bool { |
| 503 |
obj, _ := scope.LookupParent(name, pos) |
| 504 |
return obj != nil |
| 505 |
}) |
| 506 |
} |
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
|
| 512 |
|
| 513 |
func freshNameOutsideRange(info *types.Info, file *ast.File, pos, start, end token.Pos, prefix string, idx int) (string, int) { |
| 514 |
scope := info.Scopes[file].Innermost(pos) |
| 515 |
return generateName(idx, prefix, func(name string) bool { |
| 516 |
|
| 517 |
|
| 518 |
for scope != nil { |
| 519 |
obj, declScope := scope.LookupParent(name, pos) |
| 520 |
if obj == nil { |
| 521 |
return false |
| 522 |
} |
| 523 |
if !(start <= obj.Pos() && obj.Pos() < end) { |
| 524 |
return true |
| 525 |
} |
| 526 |
scope = declScope.Parent() |
| 527 |
} |
| 528 |
return false |
| 529 |
}) |
| 530 |
} |
| 531 |
|
| 532 |
func generateName(idx int, prefix string, hasCollision func(string) bool) (string, int) { |
| 533 |
name := prefix |
| 534 |
if idx != 0 { |
| 535 |
name += fmt.Sprintf("%d", idx) |
| 536 |
} |
| 537 |
for hasCollision(name) { |
| 538 |
idx++ |
| 539 |
name = fmt.Sprintf("%v%d", prefix, idx) |
| 540 |
} |
| 541 |
return name, idx + 1 |
| 542 |
} |
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
type returnVariable struct { |
| 547 |
|
| 548 |
|
| 549 |
name *ast.Ident |
| 550 |
|
| 551 |
|
| 552 |
decl *ast.Field |
| 553 |
|
| 554 |
|
| 555 |
zeroVal ast.Expr |
| 556 |
} |
| 557 |
|
| 558 |
|
| 559 |
func extractMethod(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) { |
| 560 |
countExtractMethod.Inc() |
| 561 |
return extractFunctionMethod(pkg, pgf, start, end, true) |
| 562 |
} |
| 563 |
|
| 564 |
|
| 565 |
func extractFunction(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) { |
| 566 |
countExtractFunction.Inc() |
| 567 |
return extractFunctionMethod(pkg, pgf, start, end, false) |
| 568 |
} |
| 569 |
|
| 570 |
|
| 571 |
|
| 572 |
|
| 573 |
|
| 574 |
|
| 575 |
|
| 576 |
|
| 577 |
|
| 578 |
func extractFunctionMethod(cpkg *cache.Package, pgf *parsego.File, start, end token.Pos, isMethod bool) (*token.FileSet, *analysis.SuggestedFix, error) { |
| 579 |
var ( |
| 580 |
fset = cpkg.FileSet() |
| 581 |
pkg = cpkg.Types() |
| 582 |
info = cpkg.TypesInfo() |
| 583 |
src = pgf.Src |
| 584 |
file = pgf.File |
| 585 |
) |
| 586 |
|
| 587 |
errorPrefix := "extractFunction" |
| 588 |
if isMethod { |
| 589 |
errorPrefix = "extractMethod" |
| 590 |
} |
| 591 |
|
| 592 |
p, ok, methodOk, err := canExtractFunction(pgf.Cursor(), start, end) |
| 593 |
if (!ok && !isMethod) || (!methodOk && isMethod) { |
| 594 |
return nil, nil, fmt.Errorf("%s: cannot extract %s: %v", errorPrefix, |
| 595 |
safetoken.StartPosition(fset, start), err) |
| 596 |
} |
| 597 |
curEnclosing, curStart, curEnd, curFuncDecl := p.curEnclosing, p.curStart, p.curEnd, p.curFuncDecl |
| 598 |
|
| 599 |
|
| 600 |
start, end = curStart.Node().Pos(), curEnd.Node().End() |
| 601 |
outer := curFuncDecl.Node().(*ast.FuncDecl) |
| 602 |
|
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
|
| 608 |
|
| 609 |
|
| 610 |
|
| 611 |
|
| 612 |
if curEnd.ParentEdgeKind() == edge.LabeledStmt_Label { |
| 613 |
end = curEnd.Parent().Node().(*ast.LabeledStmt).Colon + 1 |
| 614 |
} |
| 615 |
|
| 616 |
|
| 617 |
|
| 618 |
|
| 619 |
var hasNonNestedReturn bool |
| 620 |
|
| 621 |
|
| 622 |
|
| 623 |
|
| 624 |
|
| 625 |
|
| 626 |
|
| 627 |
|
| 628 |
|
| 629 |
var ( |
| 630 |
allReturnsFinalErr = true |
| 631 |
hasReturn = false |
| 632 |
filter = []ast.Node{(*ast.ReturnStmt)(nil), (*ast.FuncLit)(nil)} |
| 633 |
) |
| 634 |
curEnclosing.Inspect(filter, func(cur inspector.Cursor) (descend bool) { |
| 635 |
if funcLit, ok := cur.Node().(*ast.FuncLit); ok { |
| 636 |
|
| 637 |
|
| 638 |
return !(start < funcLit.Pos() && funcLit.End() < end) |
| 639 |
} |
| 640 |
ret := cur.Node().(*ast.ReturnStmt) |
| 641 |
if ret.Pos() < start || ret.End() > end { |
| 642 |
return false |
| 643 |
} |
| 644 |
hasReturn = true |
| 645 |
|
| 646 |
if cur.Parent() == curStart.Parent() { |
| 647 |
hasNonNestedReturn = true |
| 648 |
} |
| 649 |
|
| 650 |
if !allReturnsFinalErr { |
| 651 |
|
| 652 |
return false |
| 653 |
} |
| 654 |
|
| 655 |
if len(ret.Results) > 0 { |
| 656 |
typ := info.TypeOf(ret.Results[len(ret.Results)-1]) |
| 657 |
if typ != nil && types.Identical(typ, errorType) { |
| 658 |
|
| 659 |
|
| 660 |
|
| 661 |
if ifstmt, ok := cur.Parent().Parent().Node().(*ast.IfStmt); ok { |
| 662 |
|
| 663 |
if body, ok := cur.Parent().Node().(*ast.BlockStmt); ok && len(body.List) <= 1 { |
| 664 |
if cond, ok := ifstmt.Cond.(*ast.BinaryExpr); ok { |
| 665 |
tx := info.TypeOf(cond.X) |
| 666 |
ty := info.TypeOf(cond.Y) |
| 667 |
isErr := tx != nil && types.Identical(tx, errorType) |
| 668 |
isNil := ty != nil && types.Identical(ty, types.Typ[types.UntypedNil]) |
| 669 |
if cond.Op == token.NEQ && isErr && isNil { |
| 670 |
|
| 671 |
return false |
| 672 |
} |
| 673 |
} |
| 674 |
} |
| 675 |
} |
| 676 |
} |
| 677 |
} |
| 678 |
allReturnsFinalErr = false |
| 679 |
return false |
| 680 |
}) |
| 681 |
|
| 682 |
allReturnsFinalErr = hasReturn && allReturnsFinalErr |
| 683 |
|
| 684 |
|
| 685 |
|
| 686 |
|
| 687 |
|
| 688 |
variables, err := collectFreeVars(info, file, start, end, curEnclosing.Node()) |
| 689 |
if err != nil { |
| 690 |
return nil, nil, err |
| 691 |
} |
| 692 |
|
| 693 |
var ( |
| 694 |
receiverUsed bool |
| 695 |
receiver *ast.Field |
| 696 |
receiverName string |
| 697 |
receiverObj types.Object |
| 698 |
) |
| 699 |
if isMethod { |
| 700 |
if outer.Recv == nil || len(outer.Recv.List) == 0 { |
| 701 |
return nil, nil, fmt.Errorf("%s: cannot extract need method receiver", errorPrefix) |
| 702 |
} |
| 703 |
receiver = outer.Recv.List[0] |
| 704 |
if len(receiver.Names) == 0 || receiver.Names[0] == nil { |
| 705 |
return nil, nil, fmt.Errorf("%s: cannot extract need method receiver name", errorPrefix) |
| 706 |
} |
| 707 |
recvName := receiver.Names[0] |
| 708 |
receiverName = recvName.Name |
| 709 |
receiverObj = info.ObjectOf(recvName) |
| 710 |
} |
| 711 |
|
| 712 |
var ( |
| 713 |
params, returns []ast.Expr |
| 714 |
paramTypes, returnTypes []*ast.Field |
| 715 |
uninitialized []types.Object |
| 716 |
) |
| 717 |
|
| 718 |
|
| 719 |
seenVars := make(map[types.Object]ast.Expr) |
| 720 |
seenUninitialized := make(map[types.Object]struct{}) |
| 721 |
|
| 722 |
|
| 723 |
|
| 724 |
|
| 725 |
|
| 726 |
|
| 727 |
|
| 728 |
|
| 729 |
|
| 730 |
|
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
|
| 735 |
|
| 736 |
|
| 737 |
|
| 738 |
|
| 739 |
|
| 740 |
|
| 741 |
|
| 742 |
var canRedefineCount int |
| 743 |
|
| 744 |
qual := typesinternal.FileQualifier(file, pkg) |
| 745 |
|
| 746 |
|
| 747 |
|
| 748 |
|
| 749 |
|
| 750 |
|
| 751 |
for _, v := range variables { |
| 752 |
if _, ok := seenVars[v.obj]; ok { |
| 753 |
continue |
| 754 |
} |
| 755 |
if v.obj.Name() == "_" { |
| 756 |
|
| 757 |
continue |
| 758 |
} |
| 759 |
typ := typesinternal.TypeExpr(v.obj.Type(), qual) |
| 760 |
seenVars[v.obj] = typ |
| 761 |
identifier := ast.NewIdent(v.obj.Name()) |
| 762 |
|
| 763 |
|
| 764 |
|
| 765 |
|
| 766 |
|
| 767 |
vscope := v.obj.Parent() |
| 768 |
if vscope == nil { |
| 769 |
|
| 770 |
|
| 771 |
continue |
| 772 |
} |
| 773 |
isUsed, firstUseAfter := objUsed(info, end, vscope.End(), v.obj) |
| 774 |
if v.assigned && isUsed && !varOverridden(info, firstUseAfter, v.obj, v.free, outer) { |
| 775 |
returnTypes = append(returnTypes, &ast.Field{Type: typ}) |
| 776 |
returns = append(returns, identifier) |
| 777 |
if !v.free { |
| 778 |
uninitialized = append(uninitialized, v.obj) |
| 779 |
|
| 780 |
} else { |
| 781 |
|
| 782 |
|
| 783 |
|
| 784 |
|
| 785 |
|
| 786 |
startParent := curStart.Parent().Node() |
| 787 |
if vscope.Pos() == startParent.Pos() || |
| 788 |
startParent == outer.Body && vscope == info.Scopes[outer.Type] { |
| 789 |
canRedefineCount++ |
| 790 |
} |
| 791 |
} |
| 792 |
} |
| 793 |
|
| 794 |
|
| 795 |
|
| 796 |
if v.free && !v.defined { |
| 797 |
|
| 798 |
if isMethod && v.obj == receiverObj { |
| 799 |
receiverUsed = true |
| 800 |
continue |
| 801 |
} |
| 802 |
params = append(params, identifier) |
| 803 |
paramTypes = append(paramTypes, &ast.Field{ |
| 804 |
Names: []*ast.Ident{identifier}, |
| 805 |
Type: typ, |
| 806 |
}) |
| 807 |
} |
| 808 |
} |
| 809 |
|
| 810 |
reorderParams(params, paramTypes) |
| 811 |
|
| 812 |
|
| 813 |
|
| 814 |
|
| 815 |
|
| 816 |
|
| 817 |
|
| 818 |
|
| 819 |
|
| 820 |
|
| 821 |
|
| 822 |
|
| 823 |
|
| 824 |
|
| 825 |
|
| 826 |
|
| 827 |
|
| 828 |
|
| 829 |
enclosing := outer.Type |
| 830 |
if funcLit, _ := cursorutil.FirstEnclosing[*ast.FuncLit](curEnclosing); funcLit != nil { |
| 831 |
enclosing = funcLit.Type |
| 832 |
} |
| 833 |
|
| 834 |
|
| 835 |
|
| 836 |
startOffset, endOffset, err := safetoken.Offsets(pgf.Tok, start, end) |
| 837 |
if err != nil { |
| 838 |
return nil, nil, err |
| 839 |
} |
| 840 |
selection := src[startOffset:endOffset] |
| 841 |
|
| 842 |
extractedBlock, extractedComments, err := parseStmts(fset, selection) |
| 843 |
if err != nil { |
| 844 |
return nil, nil, err |
| 845 |
} |
| 846 |
|
| 847 |
|
| 848 |
|
| 849 |
|
| 850 |
|
| 851 |
|
| 852 |
|
| 853 |
|
| 854 |
|
| 855 |
|
| 856 |
|
| 857 |
|
| 858 |
|
| 859 |
|
| 860 |
|
| 861 |
|
| 862 |
|
| 863 |
|
| 864 |
|
| 865 |
|
| 866 |
|
| 867 |
|
| 868 |
|
| 869 |
|
| 870 |
|
| 871 |
|
| 872 |
|
| 873 |
|
| 874 |
|
| 875 |
|
| 876 |
|
| 877 |
|
| 878 |
|
| 879 |
|
| 880 |
|
| 881 |
|
| 882 |
|
| 883 |
|
| 884 |
|
| 885 |
|
| 886 |
|
| 887 |
|
| 888 |
|
| 889 |
|
| 890 |
|
| 891 |
|
| 892 |
|
| 893 |
|
| 894 |
|
| 895 |
|
| 896 |
|
| 897 |
|
| 898 |
|
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
|
| 904 |
|
| 905 |
|
| 906 |
|
| 907 |
|
| 908 |
|
| 909 |
|
| 910 |
|
| 911 |
|
| 912 |
|
| 913 |
|
| 914 |
|
| 915 |
|
| 916 |
|
| 917 |
|
| 918 |
|
| 919 |
var retVars []*returnVariable |
| 920 |
var ifReturn *ast.IfStmt |
| 921 |
|
| 922 |
|
| 923 |
|
| 924 |
|
| 925 |
|
| 926 |
|
| 927 |
|
| 928 |
curSel, _ := pgf.Cursor().FindByPos(start, end) |
| 929 |
freeBranches := freeBranches(info, curSel, start, end) |
| 930 |
|
| 931 |
|
| 932 |
isErrHandlingReturnsCase := allReturnsFinalErr && len(freeBranches) == 0 |
| 933 |
|
| 934 |
if hasReturn { |
| 935 |
if !hasNonNestedReturn { |
| 936 |
|
| 937 |
|
| 938 |
|
| 939 |
|
| 940 |
if err := adjustReturnStatements(returnTypes, seenVars, extractedBlock, qual, isErrHandlingReturnsCase); err != nil { |
| 941 |
return nil, nil, err |
| 942 |
} |
| 943 |
} |
| 944 |
|
| 945 |
|
| 946 |
|
| 947 |
|
| 948 |
retVars, ifReturn, err = generateReturnInfo(enclosing, pkg, curEnclosing.Node().Pos(), file, info, start, end, hasNonNestedReturn, isErrHandlingReturnsCase) |
| 949 |
if err != nil { |
| 950 |
return nil, nil, err |
| 951 |
} |
| 952 |
} |
| 953 |
|
| 954 |
|
| 955 |
|
| 956 |
|
| 957 |
|
| 958 |
|
| 959 |
|
| 960 |
|
| 961 |
|
| 962 |
|
| 963 |
|
| 964 |
|
| 965 |
|
| 966 |
|
| 967 |
|
| 968 |
|
| 969 |
|
| 970 |
|
| 971 |
|
| 972 |
|
| 973 |
|
| 974 |
|
| 975 |
|
| 976 |
|
| 977 |
|
| 978 |
|
| 979 |
|
| 980 |
|
| 981 |
|
| 982 |
|
| 983 |
|
| 984 |
|
| 985 |
|
| 986 |
|
| 987 |
|
| 988 |
|
| 989 |
|
| 990 |
|
| 991 |
|
| 992 |
ctrlVar, _ := freshName(info, file, start, "ctrl", 0) |
| 993 |
if len(freeBranches) > 0 { |
| 994 |
|
| 995 |
zeroValExpr := &ast.BasicLit{ |
| 996 |
Kind: token.INT, |
| 997 |
Value: "0", |
| 998 |
} |
| 999 |
var branchStmts []*ast.BranchStmt |
| 1000 |
|
| 1001 |
ast.PreorderStack(extractedBlock, nil, func(n ast.Node, stack []ast.Node) bool { |
| 1002 |
switch n := n.(type) { |
| 1003 |
case *ast.ReturnStmt: |
| 1004 |
n.Results = append(n.Results, zeroValExpr) |
| 1005 |
case *ast.BranchStmt: |
| 1006 |
|
| 1007 |
if isFreeBranchStmt(append(stack, n), extractedBlock) { |
| 1008 |
branchStmts = append(branchStmts, n) |
| 1009 |
} |
| 1010 |
case *ast.FuncLit: |
| 1011 |
|
| 1012 |
return false |
| 1013 |
} |
| 1014 |
return true |
| 1015 |
}) |
| 1016 |
|
| 1017 |
|
| 1018 |
|
| 1019 |
var freeCtrlStmtReturns []ast.Expr |
| 1020 |
|
| 1021 |
for _, returnType := range returnTypes { |
| 1022 |
var val ast.Expr |
| 1023 |
var isValid bool |
| 1024 |
for obj, typ := range seenVars { |
| 1025 |
if typ == returnType.Type { |
| 1026 |
val, isValid = typesinternal.ZeroExpr(obj.Type(), qual) |
| 1027 |
break |
| 1028 |
} |
| 1029 |
} |
| 1030 |
if !isValid { |
| 1031 |
return nil, nil, fmt.Errorf("could not find matching AST expression for %T", returnType.Type) |
| 1032 |
} |
| 1033 |
freeCtrlStmtReturns = append(freeCtrlStmtReturns, val) |
| 1034 |
} |
| 1035 |
freeCtrlStmtReturns = append(freeCtrlStmtReturns, getZeroVals(retVars)...) |
| 1036 |
|
| 1037 |
for i, branchStmt := range branchStmts { |
| 1038 |
replaceBranchStmtWithReturnStmt(extractedBlock, branchStmt, &ast.ReturnStmt{ |
| 1039 |
Return: branchStmt.Pos(), |
| 1040 |
Results: append(slices.Clip(freeCtrlStmtReturns), &ast.BasicLit{ |
| 1041 |
Kind: token.INT, |
| 1042 |
Value: strconv.Itoa(i + 1), |
| 1043 |
}), |
| 1044 |
}) |
| 1045 |
} |
| 1046 |
retVars = append(retVars, &returnVariable{ |
| 1047 |
name: ast.NewIdent(ctrlVar), |
| 1048 |
decl: &ast.Field{Type: ast.NewIdent("int")}, |
| 1049 |
zeroVal: zeroValExpr, |
| 1050 |
}) |
| 1051 |
} |
| 1052 |
|
| 1053 |
|
| 1054 |
|
| 1055 |
|
| 1056 |
|
| 1057 |
|
| 1058 |
hasReturnValues := len(returns)+len(retVars) > 0 |
| 1059 |
if hasReturnValues && !hasNonNestedReturn { |
| 1060 |
extractedBlock.List = append(extractedBlock.List, &ast.ReturnStmt{ |
| 1061 |
Results: append(returns, getZeroVals(retVars)...), |
| 1062 |
}) |
| 1063 |
} |
| 1064 |
|
| 1065 |
|
| 1066 |
|
| 1067 |
|
| 1068 |
|
| 1069 |
sym := token.ASSIGN |
| 1070 |
canDefineCount := len(uninitialized) + canRedefineCount |
| 1071 |
canDefine := len(uninitialized)+len(retVars) > 0 && canDefineCount == len(returns) |
| 1072 |
if canDefine { |
| 1073 |
sym = token.DEFINE |
| 1074 |
} |
| 1075 |
var funName string |
| 1076 |
if isMethod { |
| 1077 |
|
| 1078 |
funName = "newMethod" |
| 1079 |
} else { |
| 1080 |
funName, _ = freshName(info, file, start, "newFunction", 0) |
| 1081 |
} |
| 1082 |
extractedFunCall := generateFuncCall(hasNonNestedReturn, hasReturnValues, params, |
| 1083 |
append(returns, getNames(retVars)...), funName, sym, receiverName) |
| 1084 |
|
| 1085 |
|
| 1086 |
|
| 1087 |
|
| 1088 |
var declarations []ast.Stmt |
| 1089 |
if canDefineCount != len(returns) { |
| 1090 |
declarations = initializeVars(uninitialized, retVars, seenUninitialized, seenVars) |
| 1091 |
} |
| 1092 |
|
| 1093 |
var declBuf, replaceBuf, newFuncBuf, ifBuf, commentBuf bytes.Buffer |
| 1094 |
if err := format.Node(&declBuf, fset, declarations); err != nil { |
| 1095 |
return nil, nil, err |
| 1096 |
} |
| 1097 |
if err := format.Node(&replaceBuf, fset, extractedFunCall); err != nil { |
| 1098 |
return nil, nil, err |
| 1099 |
} |
| 1100 |
if ifReturn != nil { |
| 1101 |
if isErrHandlingReturnsCase { |
| 1102 |
if len(retVars) > 0 { |
| 1103 |
errName := retVars[len(retVars)-1] |
| 1104 |
fmt.Fprintf(&ifBuf, "if %s != nil ", errName.name.String()) |
| 1105 |
if err := format.Node(&ifBuf, fset, ifReturn.Body); err != nil { |
| 1106 |
return nil, nil, err |
| 1107 |
} |
| 1108 |
} |
| 1109 |
} else { |
| 1110 |
if err := format.Node(&ifBuf, fset, ifReturn); err != nil { |
| 1111 |
return nil, nil, err |
| 1112 |
} |
| 1113 |
} |
| 1114 |
} |
| 1115 |
|
| 1116 |
|
| 1117 |
|
| 1118 |
|
| 1119 |
|
| 1120 |
|
| 1121 |
|
| 1122 |
|
| 1123 |
|
| 1124 |
|
| 1125 |
newFunc := &ast.FuncDecl{ |
| 1126 |
Name: ast.NewIdent(funName), |
| 1127 |
Type: &ast.FuncType{ |
| 1128 |
Params: &ast.FieldList{List: paramTypes}, |
| 1129 |
Results: &ast.FieldList{List: append(returnTypes, getDecls(retVars)...)}, |
| 1130 |
}, |
| 1131 |
|
| 1132 |
} |
| 1133 |
if isMethod { |
| 1134 |
var names []*ast.Ident |
| 1135 |
if receiverUsed { |
| 1136 |
names = append(names, ast.NewIdent(receiverName)) |
| 1137 |
} |
| 1138 |
newFunc.Recv = &ast.FieldList{ |
| 1139 |
List: []*ast.Field{{ |
| 1140 |
Names: names, |
| 1141 |
Type: receiver.Type, |
| 1142 |
}}, |
| 1143 |
} |
| 1144 |
} |
| 1145 |
if err := format.Node(&newFuncBuf, fset, newFunc); err != nil { |
| 1146 |
return nil, nil, err |
| 1147 |
} |
| 1148 |
|
| 1149 |
if err := newFuncBuf.WriteByte(' '); err != nil { |
| 1150 |
return nil, nil, err |
| 1151 |
} |
| 1152 |
commentedNode := &printer.CommentedNode{ |
| 1153 |
Node: extractedBlock, |
| 1154 |
Comments: extractedComments, |
| 1155 |
} |
| 1156 |
if err := format.Node(&newFuncBuf, fset, commentedNode); err != nil { |
| 1157 |
return nil, nil, err |
| 1158 |
} |
| 1159 |
|
| 1160 |
|
| 1161 |
|
| 1162 |
outerStart, outerEnd, err := pgf.NodeOffsets(outer) |
| 1163 |
if err != nil { |
| 1164 |
return nil, nil, err |
| 1165 |
} |
| 1166 |
before := src[outerStart:startOffset] |
| 1167 |
after := src[endOffset:outerEnd] |
| 1168 |
indent, err := pgf.Indentation(start) |
| 1169 |
if err != nil { |
| 1170 |
return nil, nil, err |
| 1171 |
} |
| 1172 |
newLineIndent := "\n" + indent |
| 1173 |
|
| 1174 |
var fullReplacement strings.Builder |
| 1175 |
fullReplacement.Write(before) |
| 1176 |
if commentBuf.Len() > 0 { |
| 1177 |
comments := strings.ReplaceAll(commentBuf.String(), "\n", newLineIndent) |
| 1178 |
fullReplacement.WriteString(comments) |
| 1179 |
} |
| 1180 |
if declBuf.Len() > 0 { |
| 1181 |
initializations := strings.ReplaceAll(declBuf.String(), "\n", newLineIndent) + |
| 1182 |
newLineIndent |
| 1183 |
fullReplacement.WriteString(initializations) |
| 1184 |
} |
| 1185 |
fullReplacement.Write(replaceBuf.Bytes()) |
| 1186 |
if ifBuf.Len() > 0 { |
| 1187 |
ifstatement := newLineIndent + |
| 1188 |
strings.ReplaceAll(ifBuf.String(), "\n", newLineIndent) |
| 1189 |
fullReplacement.WriteString(ifstatement) |
| 1190 |
} |
| 1191 |
|
| 1192 |
|
| 1193 |
if len(freeBranches) > 0 { |
| 1194 |
fmt.Fprintf(&fullReplacement, "%[1]sswitch %[2]s {%[1]s", newLineIndent, ctrlVar) |
| 1195 |
for i, br := range freeBranches { |
| 1196 |
|
| 1197 |
startPos := pgf.Tok.LineStart(safetoken.Line(pgf.Tok, br.Pos())) |
| 1198 |
text, err := pgf.PosText(startPos, br.End()) |
| 1199 |
if err != nil { |
| 1200 |
return nil, nil, err |
| 1201 |
} |
| 1202 |
fmt.Fprintf(&fullReplacement, "case %d:\n%s%s", i+1, text, newLineIndent) |
| 1203 |
} |
| 1204 |
fullReplacement.WriteString("}") |
| 1205 |
} |
| 1206 |
|
| 1207 |
fullReplacement.Write(after) |
| 1208 |
fullReplacement.WriteString("\n\n") |
| 1209 |
fullReplacement.Write(newFuncBuf.Bytes()) |
| 1210 |
|
| 1211 |
return fset, &analysis.SuggestedFix{ |
| 1212 |
TextEdits: []analysis.TextEdit{{ |
| 1213 |
Pos: outer.Pos(), |
| 1214 |
End: outer.End(), |
| 1215 |
NewText: []byte(fullReplacement.String()), |
| 1216 |
}}, |
| 1217 |
}, nil |
| 1218 |
} |
| 1219 |
|
| 1220 |
|
| 1221 |
func isSelector(e ast.Expr, x, sel string) bool { |
| 1222 |
unary, ok := e.(*ast.UnaryExpr) |
| 1223 |
if ok && unary.Op == token.MUL { |
| 1224 |
e = unary.X |
| 1225 |
} |
| 1226 |
selectorExpr, ok := e.(*ast.SelectorExpr) |
| 1227 |
if !ok { |
| 1228 |
return false |
| 1229 |
} |
| 1230 |
ident, ok := selectorExpr.X.(*ast.Ident) |
| 1231 |
if !ok { |
| 1232 |
return false |
| 1233 |
} |
| 1234 |
return ident.Name == x && selectorExpr.Sel.Name == sel |
| 1235 |
} |
| 1236 |
|
| 1237 |
|
| 1238 |
func reorderParams(params []ast.Expr, paramTypes []*ast.Field) { |
| 1239 |
moveParamToFrontIfFound(params, paramTypes, "testing", "T") |
| 1240 |
moveParamToFrontIfFound(params, paramTypes, "testing", "B") |
| 1241 |
moveParamToFrontIfFound(params, paramTypes, "context", "Context") |
| 1242 |
} |
| 1243 |
|
| 1244 |
func moveParamToFrontIfFound(params []ast.Expr, paramTypes []*ast.Field, x, sel string) { |
| 1245 |
|
| 1246 |
for i, t := range paramTypes { |
| 1247 |
if isSelector(t.Type, x, sel) { |
| 1248 |
p, t := params[i], paramTypes[i] |
| 1249 |
copy(params[1:], params[:i]) |
| 1250 |
copy(paramTypes[1:], paramTypes[:i]) |
| 1251 |
params[0], paramTypes[0] = p, t |
| 1252 |
break |
| 1253 |
} |
| 1254 |
} |
| 1255 |
} |
| 1256 |
|
| 1257 |
|
| 1258 |
type variable struct { |
| 1259 |
obj types.Object |
| 1260 |
|
| 1261 |
|
| 1262 |
|
| 1263 |
free bool |
| 1264 |
|
| 1265 |
|
| 1266 |
assigned bool |
| 1267 |
|
| 1268 |
|
| 1269 |
defined bool |
| 1270 |
} |
| 1271 |
|
| 1272 |
|
| 1273 |
|
| 1274 |
|
| 1275 |
|
| 1276 |
|
| 1277 |
|
| 1278 |
func collectFreeVars(info *types.Info, file *ast.File, start, end token.Pos, node ast.Node) ([]*variable, error) { |
| 1279 |
fileScope := info.Scopes[file] |
| 1280 |
if fileScope == nil { |
| 1281 |
return nil, bug.Errorf("file scope is empty") |
| 1282 |
} |
| 1283 |
pkgScope := fileScope.Parent() |
| 1284 |
if pkgScope == nil { |
| 1285 |
return nil, bug.Errorf("package scope is empty") |
| 1286 |
} |
| 1287 |
|
| 1288 |
|
| 1289 |
|
| 1290 |
id := func(n *ast.Ident) (types.Object, bool) { |
| 1291 |
obj := info.Uses[n] |
| 1292 |
if obj == nil { |
| 1293 |
return info.Defs[n], false |
| 1294 |
} |
| 1295 |
if obj.Name() == "_" { |
| 1296 |
return nil, false |
| 1297 |
} |
| 1298 |
if _, ok := obj.(*types.PkgName); ok { |
| 1299 |
return nil, false |
| 1300 |
} |
| 1301 |
if !(file.FileStart <= obj.Pos() && obj.Pos() <= file.FileEnd) { |
| 1302 |
return nil, false |
| 1303 |
} |
| 1304 |
scope := obj.Parent() |
| 1305 |
if scope == nil { |
| 1306 |
return nil, false |
| 1307 |
} |
| 1308 |
if scope == fileScope || scope == pkgScope { |
| 1309 |
return nil, false |
| 1310 |
} |
| 1311 |
if start <= obj.Pos() && obj.Pos() <= end { |
| 1312 |
return obj, false |
| 1313 |
} |
| 1314 |
return obj, true |
| 1315 |
} |
| 1316 |
|
| 1317 |
|
| 1318 |
|
| 1319 |
var sel func(n *ast.SelectorExpr) (types.Object, bool) |
| 1320 |
sel = func(n *ast.SelectorExpr) (types.Object, bool) { |
| 1321 |
switch x := ast.Unparen(n.X).(type) { |
| 1322 |
case *ast.SelectorExpr: |
| 1323 |
return sel(x) |
| 1324 |
case *ast.Ident: |
| 1325 |
return id(x) |
| 1326 |
} |
| 1327 |
return nil, false |
| 1328 |
} |
| 1329 |
seen := make(map[types.Object]*variable) |
| 1330 |
firstUseIn := make(map[types.Object]token.Pos) |
| 1331 |
var vars []types.Object |
| 1332 |
ast.Inspect(node, func(n ast.Node) bool { |
| 1333 |
if n == nil { |
| 1334 |
return false |
| 1335 |
} |
| 1336 |
if start <= n.Pos() && n.End() <= end { |
| 1337 |
var obj types.Object |
| 1338 |
var isFree, prune bool |
| 1339 |
switch n := n.(type) { |
| 1340 |
case *ast.BranchStmt: |
| 1341 |
|
| 1342 |
return false |
| 1343 |
case *ast.Ident: |
| 1344 |
obj, isFree = id(n) |
| 1345 |
case *ast.SelectorExpr: |
| 1346 |
obj, isFree = sel(n) |
| 1347 |
prune = true |
| 1348 |
} |
| 1349 |
if obj != nil { |
| 1350 |
seen[obj] = &variable{ |
| 1351 |
obj: obj, |
| 1352 |
free: isFree, |
| 1353 |
} |
| 1354 |
vars = append(vars, obj) |
| 1355 |
|
| 1356 |
first, ok := firstUseIn[obj] |
| 1357 |
if !ok || n.Pos() < first { |
| 1358 |
firstUseIn[obj] = n.Pos() |
| 1359 |
} |
| 1360 |
if prune { |
| 1361 |
return false |
| 1362 |
} |
| 1363 |
} |
| 1364 |
} |
| 1365 |
return n.Pos() <= end |
| 1366 |
}) |
| 1367 |
|
| 1368 |
|
| 1369 |
|
| 1370 |
|
| 1371 |
|
| 1372 |
|
| 1373 |
|
| 1374 |
|
| 1375 |
|
| 1376 |
|
| 1377 |
|
| 1378 |
ast.Inspect(node, func(n ast.Node) bool { |
| 1379 |
if n == nil { |
| 1380 |
return false |
| 1381 |
} |
| 1382 |
if n.Pos() < start || n.End() > end { |
| 1383 |
return n.Pos() <= end |
| 1384 |
} |
| 1385 |
switch n := n.(type) { |
| 1386 |
case *ast.AssignStmt: |
| 1387 |
for _, assignment := range n.Lhs { |
| 1388 |
lhs, ok := assignment.(*ast.Ident) |
| 1389 |
if !ok { |
| 1390 |
continue |
| 1391 |
} |
| 1392 |
obj, _ := id(lhs) |
| 1393 |
if obj == nil { |
| 1394 |
continue |
| 1395 |
} |
| 1396 |
if _, ok := seen[obj]; !ok { |
| 1397 |
continue |
| 1398 |
} |
| 1399 |
seen[obj].assigned = true |
| 1400 |
if n.Tok != token.DEFINE { |
| 1401 |
continue |
| 1402 |
} |
| 1403 |
|
| 1404 |
|
| 1405 |
|
| 1406 |
|
| 1407 |
|
| 1408 |
if firstUseIn[obj] != lhs.Pos() { |
| 1409 |
continue |
| 1410 |
} |
| 1411 |
|
| 1412 |
|
| 1413 |
|
| 1414 |
|
| 1415 |
for _, expr := range n.Rhs { |
| 1416 |
if referencesObj(info, expr, obj) { |
| 1417 |
continue |
| 1418 |
} |
| 1419 |
if _, ok := seen[obj]; !ok { |
| 1420 |
continue |
| 1421 |
} |
| 1422 |
seen[obj].defined = true |
| 1423 |
break |
| 1424 |
} |
| 1425 |
} |
| 1426 |
return false |
| 1427 |
case *ast.DeclStmt: |
| 1428 |
gen, ok := n.Decl.(*ast.GenDecl) |
| 1429 |
if !ok { |
| 1430 |
return false |
| 1431 |
} |
| 1432 |
for _, spec := range gen.Specs { |
| 1433 |
vSpecs, ok := spec.(*ast.ValueSpec) |
| 1434 |
if !ok { |
| 1435 |
continue |
| 1436 |
} |
| 1437 |
for _, vSpec := range vSpecs.Names { |
| 1438 |
obj, _ := id(vSpec) |
| 1439 |
if obj == nil { |
| 1440 |
continue |
| 1441 |
} |
| 1442 |
if _, ok := seen[obj]; !ok { |
| 1443 |
continue |
| 1444 |
} |
| 1445 |
seen[obj].assigned = true |
| 1446 |
} |
| 1447 |
} |
| 1448 |
return false |
| 1449 |
case *ast.IncDecStmt: |
| 1450 |
if ident, ok := n.X.(*ast.Ident); !ok { |
| 1451 |
return false |
| 1452 |
} else if obj, _ := id(ident); obj == nil { |
| 1453 |
return false |
| 1454 |
} else { |
| 1455 |
if _, ok := seen[obj]; !ok { |
| 1456 |
return false |
| 1457 |
} |
| 1458 |
seen[obj].assigned = true |
| 1459 |
} |
| 1460 |
} |
| 1461 |
return true |
| 1462 |
}) |
| 1463 |
var variables []*variable |
| 1464 |
for _, obj := range vars { |
| 1465 |
v, ok := seen[obj] |
| 1466 |
if !ok { |
| 1467 |
return nil, fmt.Errorf("no seen types.Object for %v", obj) |
| 1468 |
} |
| 1469 |
if named, ok := v.obj.Type().(typesinternal.NamedOrAlias); ok { |
| 1470 |
namedPos := named.Obj().Pos() |
| 1471 |
if isLocal(named.Obj()) && !(start <= namedPos && namedPos <= end) { |
| 1472 |
return nil, fmt.Errorf("Cannot extract selection: the code refers to a local type whose definition lies outside the extracted block") |
| 1473 |
} |
| 1474 |
} |
| 1475 |
variables = append(variables, v) |
| 1476 |
} |
| 1477 |
return variables, nil |
| 1478 |
} |
| 1479 |
|
| 1480 |
|
| 1481 |
func referencesObj(info *types.Info, expr ast.Expr, obj types.Object) bool { |
| 1482 |
var hasObj bool |
| 1483 |
ast.Inspect(expr, func(n ast.Node) bool { |
| 1484 |
if n == nil { |
| 1485 |
return false |
| 1486 |
} |
| 1487 |
ident, ok := n.(*ast.Ident) |
| 1488 |
if !ok { |
| 1489 |
return true |
| 1490 |
} |
| 1491 |
objUse := info.Uses[ident] |
| 1492 |
if obj == objUse { |
| 1493 |
hasObj = true |
| 1494 |
return false |
| 1495 |
} |
| 1496 |
return false |
| 1497 |
}) |
| 1498 |
return hasObj |
| 1499 |
} |
| 1500 |
|
| 1501 |
type fnExtractParams struct { |
| 1502 |
curStart, curEnd inspector.Cursor |
| 1503 |
curEnclosing inspector.Cursor |
| 1504 |
curFuncDecl inspector.Cursor |
| 1505 |
} |
| 1506 |
|
| 1507 |
|
| 1508 |
|
| 1509 |
func canExtractFunction(curFile inspector.Cursor, start, end token.Pos) (*fnExtractParams, bool, bool, error) { |
| 1510 |
if start == end { |
| 1511 |
return nil, false, false, fmt.Errorf("start and end are equal") |
| 1512 |
} |
| 1513 |
|
| 1514 |
curEnclosing, curStart, curEnd, err := astutil.Select(curFile, start, end) |
| 1515 |
if err != nil { |
| 1516 |
return nil, false, false, err |
| 1517 |
} |
| 1518 |
|
| 1519 |
|
| 1520 |
|
| 1521 |
if !is[ast.Stmt](curEnclosing.Node()) { |
| 1522 |
return nil, false, false, fmt.Errorf("node is not a statement") |
| 1523 |
} |
| 1524 |
|
| 1525 |
|
| 1526 |
funcDecl, curFuncDecl := cursorutil.FirstEnclosing[*ast.FuncDecl](curEnclosing) |
| 1527 |
if funcDecl == nil { |
| 1528 |
return nil, false, false, fmt.Errorf("no enclosing function") |
| 1529 |
} |
| 1530 |
|
| 1531 |
|
| 1532 |
» } |
| 1533 |
if is[*ast.BlockStmt](curStart.Node()) && curStart == curEnd { |
| 1534 |
var ( |
| 1535 |
first, ok1 = curStart.FirstChild() |
| 1536 |
last, ok2 = curStart.LastChild() |
| 1537 |
) |
| 1538 |
if !(ok1 && ok2) { |
| 1539 |
return nil, false, false, fmt.Errorf("range maps to empty block statement") |
| 1540 |
} |
| 1541 |
curStart = first |
| 1542 |
curEnd = last |
| 1543 |
} |
| 1544 |
|
| 1545 |
return &fnExtractParams{ |
| 1546 |
curStart: curStart, |
| 1547 |
curEnd: curEnd, |
| 1548 |
curEnclosing: curEnclosing, |
| 1549 |
curFuncDecl: curFuncDecl, |
| 1550 |
}, true, funcDecl.Recv != nil, nil |
| 1551 |
} |
| 1552 |
|
| 1553 |
|
| 1554 |
|
| 1555 |
func objUsed(info *types.Info, start, end token.Pos, obj types.Object) (bool, *ast.Ident) { |
| 1556 |
var firstUse *ast.Ident |
| 1557 |
for id, objUse := range info.Uses { |
| 1558 |
if obj != objUse { |
| 1559 |
continue |
| 1560 |
} |
| 1561 |
if id.Pos() < start || id.End() > end { |
| 1562 |
continue |
| 1563 |
} |
| 1564 |
if firstUse == nil || id.Pos() < firstUse.Pos() { |
| 1565 |
firstUse = id |
| 1566 |
} |
| 1567 |
} |
| 1568 |
return firstUse != nil, firstUse |
| 1569 |
} |
| 1570 |
|
| 1571 |
|
| 1572 |
|
| 1573 |
|
| 1574 |
|
| 1575 |
|
| 1576 |
func varOverridden(info *types.Info, firstUse *ast.Ident, obj types.Object, isFree bool, node ast.Node) bool { |
| 1577 |
var isOverriden bool |
| 1578 |
ast.Inspect(node, func(n ast.Node) bool { |
| 1579 |
if n == nil { |
| 1580 |
return false |
| 1581 |
} |
| 1582 |
assignment, ok := n.(*ast.AssignStmt) |
| 1583 |
if !ok { |
| 1584 |
return true |
| 1585 |
} |
| 1586 |
|
| 1587 |
|
| 1588 |
|
| 1589 |
|
| 1590 |
|
| 1591 |
if !isFree && assignment.Tok == token.ASSIGN { |
| 1592 |
return false |
| 1593 |
} |
| 1594 |
for _, assigned := range assignment.Lhs { |
| 1595 |
ident, ok := assigned.(*ast.Ident) |
| 1596 |
|
| 1597 |
if !ok || ident != firstUse { |
| 1598 |
continue |
| 1599 |
} |
| 1600 |
objUse := info.Uses[ident] |
| 1601 |
if objUse == nil || objUse != obj { |
| 1602 |
continue |
| 1603 |
} |
| 1604 |
|
| 1605 |
|
| 1606 |
|
| 1607 |
|
| 1608 |
for _, expr := range assignment.Rhs { |
| 1609 |
if referencesObj(info, expr, obj) { |
| 1610 |
return false |
| 1611 |
} |
| 1612 |
} |
| 1613 |
isOverriden = true |
| 1614 |
return false |
| 1615 |
} |
| 1616 |
return false |
| 1617 |
}) |
| 1618 |
return isOverriden |
| 1619 |
} |
| 1620 |
|
| 1621 |
|
| 1622 |
|
| 1623 |
func parseStmts(fset *token.FileSet, src []byte) (*ast.BlockStmt, []*ast.CommentGroup, error) { |
| 1624 |
text := "package main\nfunc _() { " + string(src) + " }" |
| 1625 |
file, err := parser.ParseFile(fset, "", text, parser.ParseComments|parser.SkipObjectResolution) |
| 1626 |
if err != nil { |
| 1627 |
return nil, nil, err |
| 1628 |
} |
| 1629 |
if len(file.Decls) != 1 { |
| 1630 |
return nil, nil, fmt.Errorf("got %d declarations, want 1", len(file.Decls)) |
| 1631 |
} |
| 1632 |
decl, ok := file.Decls[0].(*ast.FuncDecl) |
| 1633 |
if !ok { |
| 1634 |
return nil, nil, bug.Errorf("parsed file does not contain expected function declaration") |
| 1635 |
} |
| 1636 |
if decl.Body == nil { |
| 1637 |
return nil, nil, bug.Errorf("extracted function has no body") |
| 1638 |
} |
| 1639 |
return decl.Body, file.Comments, nil |
| 1640 |
} |
| 1641 |
|
| 1642 |
|
| 1643 |
|
| 1644 |
|
| 1645 |
|
| 1646 |
func generateReturnInfo(enclosing *ast.FuncType, pkg *types.Package, at token.Pos, file *ast.File, info *types.Info, start, end token.Pos, hasNonNestedReturns bool, isErrHandlingReturnsCase bool) ([]*returnVariable, *ast.IfStmt, error) { |
| 1647 |
var retVars []*returnVariable |
| 1648 |
var cond *ast.Ident |
| 1649 |
|
| 1650 |
if enclosing.Results != nil { |
| 1651 |
nameIdx := make(map[string]int) |
| 1652 |
qual := typesinternal.FileQualifier(file, pkg) |
| 1653 |
for _, field := range enclosing.Results.List { |
| 1654 |
typ := info.TypeOf(field.Type) |
| 1655 |
if typ == nil { |
| 1656 |
return nil, nil, fmt.Errorf( |
| 1657 |
"failed type conversion, AST expression: %T", field.Type) |
| 1658 |
} |
| 1659 |
names := []string{""} |
| 1660 |
if len(field.Names) > 0 { |
| 1661 |
names = nil |
| 1662 |
for _, n := range field.Names { |
| 1663 |
names = append(names, n.Name) |
| 1664 |
} |
| 1665 |
} |
| 1666 |
for _, name := range names { |
| 1667 |
bestName := "result" |
| 1668 |
if name != "" && name != "_" { |
| 1669 |
bestName = name |
| 1670 |
} else if n, ok := varNameForType(typ); ok { |
| 1671 |
bestName = n |
| 1672 |
} |
| 1673 |
retName, idx := freshNameOutsideRange(info, file, at, start, end, bestName, nameIdx[bestName]) |
| 1674 |
nameIdx[bestName] = idx |
| 1675 |
z, isValid := typesinternal.ZeroExpr(typ, qual) |
| 1676 |
if !isValid { |
| 1677 |
return nil, nil, fmt.Errorf("can't generate zero value for %T", typ) |
| 1678 |
} |
| 1679 |
retVars = append(retVars, &returnVariable{ |
| 1680 |
name: ast.NewIdent(retName), |
| 1681 |
decl: &ast.Field{Type: typesinternal.TypeExpr(typ, qual)}, |
| 1682 |
zeroVal: z, |
| 1683 |
}) |
| 1684 |
} |
| 1685 |
} |
| 1686 |
} |
| 1687 |
var ifReturn *ast.IfStmt |
| 1688 |
if !hasNonNestedReturns { |
| 1689 |
results := getNames(retVars) |
| 1690 |
if !isErrHandlingReturnsCase { |
| 1691 |
|
| 1692 |
name, _ := freshNameOutsideRange(info, file, at, start, end, "shouldReturn", 0) |
| 1693 |
cond = &ast.Ident{Name: name} |
| 1694 |
retVars = append(retVars, &returnVariable{ |
| 1695 |
name: cond, |
| 1696 |
decl: &ast.Field{Type: ast.NewIdent("bool")}, |
| 1697 |
zeroVal: ast.NewIdent("false"), |
| 1698 |
}) |
| 1699 |
} |
| 1700 |
ifReturn = &ast.IfStmt{ |
| 1701 |
Cond: cond, |
| 1702 |
Body: &ast.BlockStmt{ |
| 1703 |
List: []ast.Stmt{&ast.ReturnStmt{Results: results}}, |
| 1704 |
}, |
| 1705 |
} |
| 1706 |
} |
| 1707 |
return retVars, ifReturn, nil |
| 1708 |
} |
| 1709 |
|
| 1710 |
type objKey struct{ pkg, name string } |
| 1711 |
|
| 1712 |
|
| 1713 |
|
| 1714 |
|
| 1715 |
|
| 1716 |
|
| 1717 |
|
| 1718 |
var conventionalVarNames = map[objKey]string{ |
| 1719 |
{"", "error"}: "err", |
| 1720 |
{"context", "Context"}: "ctx", |
| 1721 |
{"sql", "Tx"}: "tx", |
| 1722 |
{"http", "ResponseWriter"}: "rw", |
| 1723 |
} |
| 1724 |
|
| 1725 |
|
| 1726 |
|
| 1727 |
|
| 1728 |
|
| 1729 |
func varNameForType(t types.Type) (string, bool) { |
| 1730 |
tname := typesinternal.TypeNameFor(t) |
| 1731 |
if tname == nil { |
| 1732 |
return "", false |
| 1733 |
} |
| 1734 |
|
| 1735 |
|
| 1736 |
k := objKey{name: tname.Name()} |
| 1737 |
if tname.Pkg() != nil { |
| 1738 |
k.pkg = tname.Pkg().Name() |
| 1739 |
} |
| 1740 |
if name, ok := conventionalVarNames[k]; ok { |
| 1741 |
return name, true |
| 1742 |
} |
| 1743 |
|
| 1744 |
return AbbreviateVarName(tname.Name()), true |
| 1745 |
} |
| 1746 |
|
| 1747 |
|
| 1748 |
|
| 1749 |
func adjustReturnStatements(returnTypes []*ast.Field, seenVars map[types.Object]ast.Expr, extractedBlock *ast.BlockStmt, qual types.Qualifier, isErrHandlingReturnsCase bool) error { |
| 1750 |
var zeroVals []ast.Expr |
| 1751 |
|
| 1752 |
for _, returnType := range returnTypes { |
| 1753 |
var val ast.Expr |
| 1754 |
var isValid bool |
| 1755 |
for obj, typ := range seenVars { |
| 1756 |
if typ == returnType.Type { |
| 1757 |
val, isValid = typesinternal.ZeroExpr(obj.Type(), qual) |
| 1758 |
break |
| 1759 |
} |
| 1760 |
} |
| 1761 |
if !isValid { |
| 1762 |
return fmt.Errorf("could not find matching AST expression for %T", returnType.Type) |
| 1763 |
} |
| 1764 |
zeroVals = append(zeroVals, val) |
| 1765 |
} |
| 1766 |
|
| 1767 |
|
| 1768 |
|
| 1769 |
|
| 1770 |
|
| 1771 |
var shouldReturnCond []ast.Expr |
| 1772 |
if !isErrHandlingReturnsCase { |
| 1773 |
shouldReturnCond = append(shouldReturnCond, ast.NewIdent("true")) |
| 1774 |
} |
| 1775 |
|
| 1776 |
ast.Inspect(extractedBlock, func(n ast.Node) bool { |
| 1777 |
if n == nil { |
| 1778 |
return false |
| 1779 |
} |
| 1780 |
|
| 1781 |
if _, ok := n.(*ast.FuncLit); ok { |
| 1782 |
return false |
| 1783 |
} |
| 1784 |
if n, ok := n.(*ast.ReturnStmt); ok { |
| 1785 |
n.Results = slices.Concat(zeroVals, n.Results, shouldReturnCond) |
| 1786 |
return false |
| 1787 |
} |
| 1788 |
return true |
| 1789 |
}) |
| 1790 |
return nil |
| 1791 |
} |
| 1792 |
|
| 1793 |
|
| 1794 |
|
| 1795 |
func generateFuncCall(hasNonNestedReturn, hasReturnVals bool, params, returns []ast.Expr, name string, token token.Token, selector string) ast.Node { |
| 1796 |
var replace ast.Node |
| 1797 |
callExpr := &ast.CallExpr{ |
| 1798 |
Fun: ast.NewIdent(name), |
| 1799 |
Args: params, |
| 1800 |
} |
| 1801 |
if selector != "" { |
| 1802 |
callExpr = &ast.CallExpr{ |
| 1803 |
Fun: &ast.SelectorExpr{ |
| 1804 |
X: ast.NewIdent(selector), |
| 1805 |
Sel: ast.NewIdent(name), |
| 1806 |
}, |
| 1807 |
Args: params, |
| 1808 |
} |
| 1809 |
} |
| 1810 |
if hasReturnVals { |
| 1811 |
if hasNonNestedReturn { |
| 1812 |
|
| 1813 |
replace = &ast.ReturnStmt{ |
| 1814 |
Return: 0, |
| 1815 |
Results: []ast.Expr{callExpr}, |
| 1816 |
} |
| 1817 |
} else { |
| 1818 |
|
| 1819 |
replace = &ast.AssignStmt{ |
| 1820 |
Lhs: returns, |
| 1821 |
Tok: token, |
| 1822 |
Rhs: []ast.Expr{callExpr}, |
| 1823 |
} |
| 1824 |
} |
| 1825 |
} else { |
| 1826 |
replace = callExpr |
| 1827 |
} |
| 1828 |
return replace |
| 1829 |
} |
| 1830 |
|
| 1831 |
|
| 1832 |
|
| 1833 |
|
| 1834 |
|
| 1835 |
|
| 1836 |
|
| 1837 |
|
| 1838 |
|
| 1839 |
|
| 1840 |
|
| 1841 |
func initializeVars(uninitialized []types.Object, retVars []*returnVariable, seenUninitialized map[types.Object]struct{}, seenVars map[types.Object]ast.Expr) []ast.Stmt { |
| 1842 |
var declarations []ast.Stmt |
| 1843 |
for _, obj := range uninitialized { |
| 1844 |
if _, ok := seenUninitialized[obj]; ok { |
| 1845 |
continue |
| 1846 |
} |
| 1847 |
seenUninitialized[obj] = struct{}{} |
| 1848 |
valSpec := &ast.ValueSpec{ |
| 1849 |
Names: []*ast.Ident{ast.NewIdent(obj.Name())}, |
| 1850 |
Type: seenVars[obj], |
| 1851 |
} |
| 1852 |
genDecl := &ast.GenDecl{ |
| 1853 |
Tok: token.VAR, |
| 1854 |
Specs: []ast.Spec{valSpec}, |
| 1855 |
} |
| 1856 |
declarations = append(declarations, &ast.DeclStmt{Decl: genDecl}) |
| 1857 |
} |
| 1858 |
|
| 1859 |
|
| 1860 |
for i, retVar := range retVars { |
| 1861 |
valSpec := &ast.ValueSpec{ |
| 1862 |
Names: []*ast.Ident{retVar.name}, |
| 1863 |
Type: retVars[i].decl.Type, |
| 1864 |
} |
| 1865 |
genDecl := &ast.GenDecl{ |
| 1866 |
Tok: token.VAR, |
| 1867 |
Specs: []ast.Spec{valSpec}, |
| 1868 |
} |
| 1869 |
declarations = append(declarations, &ast.DeclStmt{Decl: genDecl}) |
| 1870 |
} |
| 1871 |
return declarations |
| 1872 |
} |
| 1873 |
|
| 1874 |
|
| 1875 |
func getNames(retVars []*returnVariable) []ast.Expr { |
| 1876 |
var names []ast.Expr |
| 1877 |
for _, retVar := range retVars { |
| 1878 |
names = append(names, retVar.name) |
| 1879 |
} |
| 1880 |
return names |
| 1881 |
} |
| 1882 |
|
| 1883 |
|
| 1884 |
func getZeroVals(retVars []*returnVariable) []ast.Expr { |
| 1885 |
var zvs []ast.Expr |
| 1886 |
for _, retVar := range retVars { |
| 1887 |
zvs = append(zvs, retVar.zeroVal) |
| 1888 |
} |
| 1889 |
return zvs |
| 1890 |
} |
| 1891 |
|
| 1892 |
|
| 1893 |
func getDecls(retVars []*returnVariable) []*ast.Field { |
| 1894 |
var decls []*ast.Field |
| 1895 |
for _, retVar := range retVars { |
| 1896 |
decls = append(decls, retVar.decl) |
| 1897 |
} |
| 1898 |
return decls |
| 1899 |
} |
| 1900 |
|
| 1901 |
func cond[T any](cond bool, t, f T) T { |
| 1902 |
if cond { |
| 1903 |
return t |
| 1904 |
} else { |
| 1905 |
return f |
| 1906 |
} |
| 1907 |
} |
| 1908 |
|
| 1909 |
|
| 1910 |
|
| 1911 |
func replaceBranchStmtWithReturnStmt(block ast.Node, br *ast.BranchStmt, ret *ast.ReturnStmt) { |
| 1912 |
ast.Inspect(block, func(n ast.Node) bool { |
| 1913 |
|
| 1914 |
switch n := n.(type) { |
| 1915 |
case *ast.BlockStmt: |
| 1916 |
for i, stmt := range n.List { |
| 1917 |
if stmt == br { |
| 1918 |
n.List[i] = ret |
| 1919 |
return false |
| 1920 |
} |
| 1921 |
} |
| 1922 |
case *ast.CaseClause: |
| 1923 |
for i, stmt := range n.Body { |
| 1924 |
if stmt.Pos() == br.Pos() { |
| 1925 |
n.Body[i] = ret |
| 1926 |
return false |
| 1927 |
} |
| 1928 |
} |
| 1929 |
} |
| 1930 |
return true |
| 1931 |
}) |
| 1932 |
} |
| 1933 |
|
| 1934 |
|
| 1935 |
|
| 1936 |
func freeBranches(info *types.Info, cur inspector.Cursor, start, end token.Pos) (free []*ast.BranchStmt) { |
| 1937 |
nextBranch: |
| 1938 |
for curBr := range cur.Preorder((*ast.BranchStmt)(nil)) { |
| 1939 |
br := curBr.Node().(*ast.BranchStmt) |
| 1940 |
if br.End() < start || br.Pos() > end { |
| 1941 |
continue |
| 1942 |
} |
| 1943 |
label, _ := info.Uses[br.Label].(*types.Label) |
| 1944 |
if label != nil && !(start <= label.Pos() && label.Pos() <= end) { |
| 1945 |
free = append(free, br) |
| 1946 |
continue |
| 1947 |
} |
| 1948 |
if br.Tok == token.BREAK || br.Tok == token.CONTINUE { |
| 1949 |
filter := []ast.Node{ |
| 1950 |
(*ast.ForStmt)(nil), |
| 1951 |
(*ast.RangeStmt)(nil), |
| 1952 |
(*ast.SwitchStmt)(nil), |
| 1953 |
(*ast.TypeSwitchStmt)(nil), |
| 1954 |
(*ast.SelectStmt)(nil), |
| 1955 |
} |
| 1956 |
|
| 1957 |
for curAncestor := range curBr.Parent().Enclosing(filter...) { |
| 1958 |
if l, ok := curAncestor.Parent().Node().(*ast.LabeledStmt); ok && |
| 1959 |
label != nil && |
| 1960 |
l.Label.Name == label.Name() { |
| 1961 |
continue |
| 1962 |
} |
| 1963 |
switch n := curAncestor.Node().(type) { |
| 1964 |
case *ast.ForStmt, *ast.RangeStmt: |
| 1965 |
if n.Pos() < start { |
| 1966 |
free = append(free, br) |
| 1967 |
} |
| 1968 |
continue nextBranch |
| 1969 |
case *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt: |
| 1970 |
if br.Tok == token.BREAK { |
| 1971 |
if n.Pos() < start { |
| 1972 |
free = append(free, br) |
| 1973 |
} |
| 1974 |
continue nextBranch |
| 1975 |
} |
| 1976 |
} |
| 1977 |
} |
| 1978 |
} |
| 1979 |
} |
| 1980 |
return |
| 1981 |
} |
| 1982 |
|
| 1983 |
|
| 1984 |
|
| 1985 |
|
| 1986 |
|
| 1987 |
|
| 1988 |
|
| 1989 |
|
| 1990 |
|
| 1991 |
func isFreeBranchStmt(stack []ast.Node, extractedBlock *ast.BlockStmt) bool { |
| 1992 |
switch node := stack[len(stack)-1].(type) { |
| 1993 |
case *ast.BranchStmt: |
| 1994 |
isLabeled := node.Label != nil |
| 1995 |
switch node.Tok { |
| 1996 |
case token.GOTO: |
| 1997 |
if isLabeled { |
| 1998 |
for _, stmt := range extractedBlock.List { |
| 1999 |
if l, ok := stmt.(*ast.LabeledStmt); ok && l.Label != nil && l.Label.Name == node.Label.Name { |
| 2000 |
|
| 2001 |
return false |
| 2002 |
} |
| 2003 |
} |
| 2004 |
return true |
| 2005 |
} |
| 2006 |
case token.BREAK, token.CONTINUE: |
| 2007 |
|
| 2008 |
for i := len(stack) - 2; i >= 0; i-- { |
| 2009 |
n := stack[i] |
| 2010 |
if isLabeled { |
| 2011 |
l, ok := n.(*ast.LabeledStmt) |
| 2012 |
if !(ok && l.Label.Name == node.Label.Name) { |
| 2013 |
continue |
| 2014 |
} |
| 2015 |
} |
| 2016 |
switch n.(type) { |
| 2017 |
case *ast.ForStmt, *ast.RangeStmt, *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt: |
| 2018 |
return false |
| 2019 |
} |
| 2020 |
} |
| 2021 |
} |
| 2022 |
} |
| 2023 |
|
| 2024 |
return true |
| 2025 |
} |