Debian Codegraph @

gopls/internal/golang/extract.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/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 // extractVariableOne implements the refactor.extract.{variable,constant} CodeAction command.
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 // extractVariableAll implements the refactor.extract.{variable,constant}-all CodeAction command.
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 // extractVariable replaces one or all occurrences of a specified
45 // expression within the same function with newVar. If 'all' is true,
46 // it replaces all occurrences of the same expression; otherwise, it
47 // only replaces the selected expression.
48 //
49 // The new variable/constant is declared as close as possible to the first found expression
50 // within the deepest common scope accessible to all candidate occurrences.
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 // innermost scope enclosing ith expression
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 // Generate name(s) for new declaration.
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 // conversion or single-valued call:
87 // treat it the same as our standard extract variable case.
88 name, _ := generateName(0, baseName, hasCollision)
89 lhsNames = append(lhsNames, name)
90
91 } else {
92 // call with multiple results
93 idx := 0
94 for range tup.Len() {
95 // Generate a unique variable for each result.
96 var name string
97 name, idx = generateName(idx, baseName, hasCollision)
98 lhsNames = append(lhsNames, name)
99 }
100 }
101
102 default:
103 // TODO: stricter rules for selectorExpr.
104 name, _ := generateName(0, baseName, hasCollision)
105 lhsNames = append(lhsNames, name)
106 }
107
108 // Where all the extractable positions can see variable being declared.
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 // A scope whose count is len(scopes) is common to all ancestor paths.
117 // Stop at the first (innermost) one.
118 commonScope = s
119 break Outer
120 }
121 }
122 }
123
124 visible := curExprs[0] // Insert newVar inside commonScope before the first occurrence of the expression.
125 if commonScope != exprScopes[0] {
126 // This means the first expr within function body is not the largest scope,
127 // we need to find the scope immediately follow the common
128 // scope where we will insert the statement before.
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 // TODO: There is a bug here: for a variable declared in a labeled
144 // switch/for statement it returns the for/switch statement itself
145 // which produces the below code which is a compiler error. e.g.
146 // label:
147 // switch r1 := r() { ... break label ... }
148 // On extracting "r()" to a variable
149 // label:
150 // x := r()
151 // switch r1 := x { ... break label ... } // compiler error
152 //
153 var (
154 insertPos token.Pos
155 indentation string
156 stmtOK bool // ok to use ":=" instead of var/const decl?
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 // Within function: compute appropriate statement indentation.
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 // Currently, we always extract a constant expression
174 // to a const declaration (and logic in CodeAction
175 // assumes that we do so); this is conservative because
176 // it preserves its constant-ness.
177 //
178 // In future, constant expressions used only in
179 // contexts where constant-ness isn't important could
180 // be profitably extracted to a var declaration or :=
181 // statement, especially if the latter is the Init of
182 // an {If,For,Switch}Stmt.
183 stmtOK = !constant
184 } else {
185 // Outside any statement: insert before the current
186 // top-level declaration, without indentation.
187 for curDecl := range visible.Enclosing((*ast.FuncDecl)(nil), (*ast.GenDecl)(nil)) {
188 insertPos = curDecl.Node().Pos()
189 }
190 indentation = "\n"
191 }
192
193 // Create statement to declare extracted var/const.
194 //
195 // TODO(adonovan): beware the const decls are not valid short
196 // statements, so if fixing #70563 causes
197 // StmtToInsertVarBefore to evolve to permit declarations in
198 // the "pre" part of an IfStmt, like so:
199 // Before:
200 // if cond {
201 // } else if «1 + 2» > 0 {
202 // }
203 // After:
204 // if x := 1 + 2; cond {
205 // } else if x > 0 {
206 // }
207 // then it will need to become aware that this is invalid
208 // for constants.
209 //
210 // Conversely, a short var decl stmt is not valid at top level,
211 // so when we fix #70665, we'll need to use a var decl.
212 var newNode ast.Node
213 if !stmtOK {
214 // var/const x1, ..., xn = expr
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 // var: x1, ... xn := expr
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 // Format and indent the declaration.
243 var buf bytes.Buffer
244 if err := format.Node(&buf, fset, newNode); err != nil {
245 return nil, nil, err
246 }
247 // TODO(adonovan): not sound for `...` string literals containing newlines.
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 // stmtToInsertVarBefore returns the ast.Stmt before which we can safely insert a new variable,
268 // and ensures that the new declaration is inserted at a point where all free variables are declared before.
269 // Some examples:
270 //
271 // Basic Example:
272 //
273 // z := 1
274 // y := z + x
275 //
276 // If x is undeclared, then this function would return `y := z + x`, so that we
277 // can insert `x := ` on the line before `y := z + x`.
278 //
279 // valid IfStmt example:
280 //
281 // if z == 1 {
282 // } else if z == y {}
283 //
284 // If y is undeclared, then this function would return `if z == 1 {`, because we cannot
285 // insert a statement between an if and an else if statement. As a result, we need to find
286 // the top of the if chain to insert `y := ` before.
287 //
288 // invalid IfStmt example:
289 //
290 // if x := 1; true {
291 // } else if y := x + 1; true { //apply refactor.extract.variable to x
292 // }
293 //
294 // `x` is a free variable defined in the IfStmt, we should not insert
295 // the extracted expression outside the IfStmt scope, instead, return an error.
296 func stmtToInsertVarBefore(cur inspector.Cursor, variables []*variable) (token.Pos, error) {
297 // Walk up to enclosing statement.
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 // hasFreeVar reports if any free variables is defined inside stmt (which may be nil).
313 // If true, indicates that the insertion point will sit before the variable declaration.
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 // baseIfStmt walks up the if/else-if chain until we get to
327 // the top of the current if chain.
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 // stmt is inside of the if declaration.
345 // We need to check if we are in an else-if stmt and
346 // get the base if statement.
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 // Check if the enclosing statement is inside another node.
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 // canExtractVariable reports whether the code in the given range can
396 // be extracted to a variable (or constant). It returns (cursors for)
397 // the selected expression or, if 'all', all structurally equivalent
398 // expressions within the same function body, in lexical order.
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 // e.g. type, builtin, x.(type), 2-valued m[k], or ill-typed
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 // Find all expressions in the same function body that
425 // are equal to the selected expression.
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 // The two identifiers must resolve to the same object,
431 // or to a declaration within the candidate expression.
432 // (This allows two copies of "func (x int) { print(x) }"
433 // to match.)
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 // Use info.Uses to avoid including declaration, for example,
439 // when extractnig x:
440 //
441 // x := 1 // should not include x
442 // y := x // include x
443 // z := x // include x
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 // Disallow any expr that sits in lhs of an AssignStmt or ValueSpec for now.
456 //
457 // TODO(golang/go#70784): In such cases, exprs are operated in "variable" mode (L-value mode in C).
458 // In contrast, exprs in the RHS operate in "value" mode (R-value mode in C).
459 // L-value mode refers to exprs that represent storage locations,
460 // while R-value mode refers to exprs that represent values.
461 // There are a number of expressions that may have L-value mode, given by:
462 //
463 // lvalue = ident -- Ident such that info.Uses[id] is a *Var
464 // | '(' lvalue ') ' -- ParenExpr
465 // | lvalue '[' expr ']' -- IndexExpr
466 // | lvalue '.' ident -- SelectorExpr.
467 //
468 // For example:
469 //
470 // type foo struct {
471 // bar int
472 // }
473 // f := foo{bar: 1}
474 // x := f.bar + 1 // f.bar operates in "value" mode.
475 // f.bar = 2 // f.bar operates in "variable" mode.
476 //
477 // When extracting exprs in variable mode, we must be cautious. Any such extraction
478 // may require capturing the address of the expression and replacing its uses with dereferenced access.
479 // The type checker records this information in info.Types[id].{IsValue,Addressable}().
480 // The correct result should be:
481 //
482 // newVar := &f.bar
483 // x := *newVar + 1
484 // *newVar = 2
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 // freshName returns an identifier based on prefix (perhaps with a
498 // numeric suffix) that is not in scope at the specified position
499 // within the file. It returns the next numeric suffix to use.
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 // freshNameOutsideRange is like [freshName], but ignores names
509 // declared between start and end for the purposes of detecting conflicts.
510 //
511 // This is used for function extraction, where [start, end) will be extracted
512 // to a new scope.
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 // Only report a collision if the object declaration
517 // was outside the extracted range.
518 for scope != nil {
519 obj, declScope := scope.LookupParent(name, pos)
520 if obj == nil {
521 return false // undeclared
522 }
523 if !(start <= obj.Pos() && obj.Pos() < end) {
524 return true // declared outside ignored range
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 // returnVariable keeps track of the information we need to properly introduce a new variable
545 // that we will return in the extracted function.
546 type returnVariable struct {
547 // name is the identifier that is used on the left-hand side of the call to
548 // the extracted function.
549 name *ast.Ident
550 // decl is the declaration of the variable. It is used in the type signature of the
551 // extracted function and for variable declarations.
552 decl *ast.Field
553 // zeroVal is the "zero value" of the type of the variable. It is used in a return
554 // statement in the extracted function.
555 zeroVal ast.Expr
556 }
557
558 // extractMethod refactors the selected block of code into a new method.
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 // extractFunction refactors the selected block of code into a new function.
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 // extractFunctionMethod refactors the selected block of code into a new function/method.
571 // It also replaces the selected block of code with a call to the extracted
572 // function. First, we manually adjust the selection range. We remove trailing
573 // and leading whitespace characters to ensure the range is precisely bounded
574 // by AST nodes. Next, we determine the variables that will be the parameters
575 // and return values of the extracted function/method. Lastly, we construct the call
576 // of the function/method and insert this call as well as the extracted function/method into
577 // their proper locations.
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 // Narrow (start, end) to the located nodes.
600 start, end = curStart.Node().Pos(), curEnd.Node().End()
601 outer := curFuncDecl.Node().(*ast.FuncDecl)
602
603 // Labeled statements have un-intuitive ranges.
604 // Technically they end at the end of the statement
605 // that they label, but user expectation is that the label
606 // is a pseudo-statement by itself. This is especially confusing when
607 // the statement that's labeled is a multi-line block statement.
608 //
609 // If the end cursor is the identifier in a labeled statement,
610 // we expand the range to include the colon.
611 // That way, we include the label, but not the statement being labeled
612 if curEnd.ParentEdgeKind() == edge.LabeledStmt_Label {
613 end = curEnd.Parent().Node().(*ast.LabeledStmt).Colon + 1
614 }
615
616 // A return statement is non-nested if its parent node is equal to the parent node
617 // of the first node in the selection. These cases must be handled separately because
618 // non-nested return statements are guaranteed to execute.
619 var hasNonNestedReturn bool
620
621 // Determine whether all return statements in the selection are
622 // error-handling return statements. They must be of the form:
623 // if err != nil {
624 // return ..., err
625 // }
626 // If all return statements in the extracted block have a non-nil error, we
627 // can replace the "shouldReturn" check with an error check to produce a
628 // more concise output.
629 var (
630 allReturnsFinalErr = true // all ReturnStmts have final 'err' expression
631 hasReturn = false // selection contains a ReturnStmt
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 // Exclude return statements in function literals because they don't affect the refactor.
637 // Keep descending into func lits whose declaration is not included in the extracted block.
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 // not part of the extracted block
643 }
644 hasReturn = true
645
646 if cur.Parent() == curStart.Parent() {
647 hasNonNestedReturn = true
648 }
649
650 if !allReturnsFinalErr {
651 // Stop the traversal if we have already found a non error-handling return statement.
652 return false
653 }
654 // Check if the return statement returns a non-nil error as the last value.
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 // Have: return ..., err
659 // Check for enclosing "if err != nil { return ..., err }".
660 // In that case, we can lift the error return to the caller.
661 if ifstmt, ok := cur.Parent().Parent().Node().(*ast.IfStmt); ok {
662 // Only handle the case where the if statement body contains a single statement.
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 // allReturnsErrHandling remains true
671 return false
672 }
673 }
674 }
675 }
676 }
677 }
678 allReturnsFinalErr = false
679 return false
680 })
681
682 allReturnsFinalErr = hasReturn && allReturnsFinalErr
683
684 // Now that we have determined the correct range for the selection block,
685 // we must determine the signature of the extracted function. We will then replace
686 // the block with an assignment statement that calls the extracted function with
687 // the appropriate parameters and return values.
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 // used when calling the extracted function
714 paramTypes, returnTypes []*ast.Field // used in the signature of the extracted function
715 uninitialized []types.Object // vars we will need to initialize before the call
716 )
717
718 // Avoid duplicates while traversing vars and uninitialized.
719 seenVars := make(map[types.Object]ast.Expr)
720 seenUninitialized := make(map[types.Object]struct{})
721
722 // Some variables on the left-hand side of our assignment statement may be free. If our
723 // selection begins in the same scope in which the free variable is defined, we can
724 // redefine it in our assignment statement. See the following example, where 'b' and
725 // 'err' (both free variables) can be redefined in the second funcCall() while maintaining
726 // correctness.
727 //
728 //
729 // Not Redefined:
730 //
731 // a, err := funcCall()
732 // var b int
733 // b, err = funcCall()
734 //
735 // Redefined:
736 //
737 // a, err := funcCall()
738 // b, err := funcCall()
739 //
740 // We track the number of free variables that can be redefined to maintain our preference
741 // of using "x, y, z := fn()" style assignment statements.
742 var canRedefineCount int
743
744 qual := typesinternal.FileQualifier(file, pkg)
745
746 // Each identifier in the selected block must become (1) a parameter to the
747 // extracted function, (2) a return value of the extracted function, or (3) a local
748 // variable in the extracted function. Determine the outcome(s) for each variable
749 // based on whether it is free, altered within the selected block, and used outside
750 // of the selected block.
751 for _, v := range variables {
752 if _, ok := seenVars[v.obj]; ok {
753 continue
754 }
755 if v.obj.Name() == "_" {
756 // The blank identifier is always a local variable
757 continue
758 }
759 typ := typesinternal.TypeExpr(v.obj.Type(), qual)
760 seenVars[v.obj] = typ
761 identifier := ast.NewIdent(v.obj.Name())
762 // An identifier must meet three conditions to become a return value of the
763 // extracted function. (1) its value must be defined or reassigned within
764 // the selection (isAssigned), (2) it must be used at least once after the
765 // selection (isUsed), and (3) its first use after the selection
766 // cannot be its own reassignment or redefinition (objOverriden).
767 vscope := v.obj.Parent()
768 if vscope == nil {
769 // v.obj could be a field on an anonymous struct. We'll examine the
770 // struct in a different iteration so don't return an error here.
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 // In go1.22, Scope.Pos for function scopes changed (#60752):
782 // it used to start at the body ('{'), now it starts at "func".
783 //
784 // The second condition below handles the case when
785 // v's block is the FuncDecl.Body itself.
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 // An identifier must meet two conditions to become a parameter of the
794 // extracted function. (1) it must be free (isFree), and (2) its first
795 // use within the selection cannot be its own definition (isDefined).
796 if v.free && !v.defined {
797 // Skip the selector for a method.
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 // Find the function literal that encloses the selection. The enclosing function literal
813 // may not be the enclosing function declaration (i.e. 'outer'). For example, in the
814 // following block:
815 //
816 // func main() {
817 // ast.Inspect(node, func(n ast.Node) bool {
818 // v := 1 // this line extracted
819 // return true
820 // })
821 // }
822 //
823 // 'outer' is main(). However, the extracted selection most directly belongs to
824 // the anonymous function literal, the second argument of ast.Inspect(). We use the
825 // enclosing function literal to determine the proper return types for return statements
826 // within the selection. We still need the enclosing function declaration because this is
827 // the top-level declaration. We inspect the top-level declaration to look for variables
828 // as well as for code replacement.
829 enclosing := outer.Type
830 if funcLit, _ := cursorutil.FirstEnclosing[*ast.FuncLit](curEnclosing); funcLit != nil {
831 enclosing = funcLit.Type
832 }
833
834 // We put the selection in a constructed file. We can then traverse and edit
835 // the extracted selection without modifying the original AST.
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 // We need to account for return statements in the selected block, as they will complicate
848 // the logical flow of the extracted function. See the following example, where ** denotes
849 // the range to be extracted.
850 //
851 // Before:
852 //
853 // func _() int {
854 // a := 1
855 // b := 2
856 // **if a == b {
857 // return a
858 // }**
859 // ...
860 // }
861 //
862 // After:
863 //
864 // func _() int {
865 // a := 1
866 // b := 2
867 // cond0, ret0 := x0(a, b)
868 // if cond0 {
869 // return ret0
870 // }
871 // ...
872 // }
873 //
874 // func x0(a int, b int) (bool, int) {
875 // if a == b {
876 // return true, a
877 // }
878 // return false, 0
879 // }
880 //
881 // We handle returns by adding an additional boolean return value to the extracted function.
882 // This bool reports whether the original function would have returned. Because the
883 // extracted selection contains a return statement, we must also add the types in the
884 // return signature of the enclosing function to the return signature of the
885 // extracted function. We then add an extra if statement checking this boolean value
886 // in the original function. If the condition is met, the original function should
887 // return a value, mimicking the functionality of the original return statement(s)
888 // in the selection.
889 //
890 // If there is a return that is guaranteed to execute (hasNonNestedReturns=true), then
891 // we don't need to include this additional condition check and can simply return.
892 //
893 // Before:
894 //
895 // func _() int {
896 // a := 1
897 // b := 2
898 // **if a == b {
899 // return a
900 // }
901 // return b**
902 // }
903 //
904 // After:
905 //
906 // func _() int {
907 // a := 1
908 // b := 2
909 // return x0(a, b)
910 // }
911 //
912 // func x0(a int, b int) int {
913 // if a == b {
914 // return a
915 // }
916 // return b
917 // }
918
919 var retVars []*returnVariable
920 var ifReturn *ast.IfStmt
921
922 // Determine if the extracted block contains any free branch statements, for
923 // example: "continue label" where "label" is declared outside of the
924 // extracted block, or continue inside a "for" statement where the for
925 // statement is declared outside of the extracted block. These will be
926 // handled below, after adjusting return statements and generating return
927 // info.
928 curSel, _ := pgf.Cursor().FindByPos(start, end) // since canExtractFunction succeeded, this will always return a valid cursor
929 freeBranches := freeBranches(info, curSel, start, end)
930
931 // All return statements in the extracted block are error handling returns, and there are no free control statements.
932 isErrHandlingReturnsCase := allReturnsFinalErr && len(freeBranches) == 0
933
934 if hasReturn {
935 if !hasNonNestedReturn {
936 // The selected block contained return statements, so we have to modify the
937 // signature of the extracted function as described above. Adjust all of
938 // the return statements in the extracted function to reflect this change in
939 // signature.
940 if err := adjustReturnStatements(returnTypes, seenVars, extractedBlock, qual, isErrHandlingReturnsCase); err != nil {
941 return nil, nil, err
942 }
943 }
944 // Collect the additional return values and types needed to accommodate return
945 // statements in the selection. Update the type signature of the extracted
946 // function and construct the if statement that will be inserted in the enclosing
947 // function.
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 // If the extracted block contains free branch statements, we add another
955 // return value "ctrl" to the extracted function that will be used to
956 // determine the control flow. See the following example, where === denotes
957 // the range to be extracted.
958 //
959 // Before:
960 // func f(cond bool) {
961 // for range "abc" {
962 // ==============
963 // if cond {
964 // continue
965 // }
966 // ==============
967 // println(0)
968 // }
969 // }
970
971 // After:
972 // func f(cond bool) {
973 // for range "abc" {
974 // ctrl := newFunction(cond)
975 // switch ctrl {
976 // case 1:
977 // continue
978 // }
979 // println(0)
980 // }
981 // }
982 //
983 // func newFunction(cond bool) int {
984 // if cond {
985 // return 1
986 // }
987 // return 0
988 // }
989 //
990
991 // Generate an unused identifier for the control value.
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 // Add the zero "ctrl" value to each return statement in the extracted block.
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 // Collect a list of branch statements in the extracted block to examine later.
1007 if isFreeBranchStmt(append(stack, n), extractedBlock) {
1008 branchStmts = append(branchStmts, n)
1009 }
1010 case *ast.FuncLit:
1011 // Don't descend into nested functions.
1012 return false
1013 }
1014 return true
1015 })
1016
1017 // Construct a return statement to replace each free branch statement in the extracted block. It should have
1018 // zero values for all return parameters except one, "ctrl", which dictates which continuation to follow.
1019 var freeCtrlStmtReturns []ast.Expr
1020 // Create "zero values" for each type.
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), // start with 1 because 0 is reserved for base case
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 // Add a return statement to the end of the new function. This return statement must include
1054 // the values for the types of the original extracted function signature and (if a return
1055 // statement is present in the selection) enclosing function signature.
1056 // This only needs to be done if the selections does not have a non-nested return, otherwise
1057 // it already terminates with a return statement.
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 // Construct the appropriate call to the extracted function.
1066 // We must meet two conditions to use ":=" instead of '='. (1) there must be at least
1067 // one variable on the lhs that is uninitialized (non-free) prior to the assignment.
1068 // (2) all of the initialized (free) variables on the lhs must be able to be redefined.
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 // TODO(suzmue): generate a name that does not conflict for "newMethod".
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 // Create variable declarations for any identifiers that need to be initialized prior to
1086 // calling the extracted function. We do not manually initialize variables if every return
1087 // value is uninitialized. We can use := to initialize the variables in this situation.
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 // Build the extracted function. We format the function declaration and body
1117 // separately, so that comments are printed relative to the extracted
1118 // BlockStmt.
1119 //
1120 // In other words, extractedBlock and extractedComments were parsed from a
1121 // synthetic function declaration of the form func _() { ... }. If we now
1122 // print the real function declaration, the length of the signature will have
1123 // grown, causing some comment positions to be computed as inside the
1124 // signature itself.
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 // Body handled separately -- see above.
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 // Write a space between the end of the function signature and opening '{'.
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 // We're going to replace the whole enclosing function,
1161 // so preserve the text before and after the selected block.
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 { // add any initializations, if needed
1181 initializations := strings.ReplaceAll(declBuf.String(), "\n", newLineIndent) +
1182 newLineIndent
1183 fullReplacement.WriteString(initializations)
1184 }
1185 fullReplacement.Write(replaceBuf.Bytes()) // call the extracted function
1186 if ifBuf.Len() > 0 { // add the if statement below the function call, if needed
1187 ifstatement := newLineIndent +
1188 strings.ReplaceAll(ifBuf.String(), "\n", newLineIndent)
1189 fullReplacement.WriteString(ifstatement)
1190 }
1191
1192 // Add the switch statement for free branch statements after the new function call.
1193 if len(freeBranches) > 0 {
1194 fmt.Fprintf(&fullReplacement, "%[1]sswitch %[2]s {%[1]s", newLineIndent, ctrlVar)
1195 for i, br := range freeBranches {
1196 // Preserve spacing at the beginning of the line containing the branch statement.
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") // add newlines after the enclosing function
1209 fullReplacement.Write(newFuncBuf.Bytes()) // insert the extracted function
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 // isSelector reports if e is the selector expr <x>, <sel>. It works for pointer and non-pointer selector expressions.
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 // reorderParams reorders the given parameters in-place to follow common Go conventions.
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 // Move Context parameter (if any) to front.
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 // variable describes the status of a variable within a selection.
1258 type variable struct {
1259 obj types.Object
1260
1261 // free reports whether the variable is a free variable, meaning it should
1262 // be a parameter to the extracted function.
1263 free bool
1264
1265 // assigned reports whether the variable is assigned to in the selection.
1266 assigned bool
1267
1268 // defined reports whether the variable is defined in the selection.
1269 defined bool
1270 }
1271
1272 // collectFreeVars maps each identifier in the given range to whether it is "free."
1273 // Given a range, a variable in that range is defined as "free" if it is declared
1274 // outside of the range and neither at the file scope nor package scope. These free
1275 // variables will be used as arguments in the extracted function. It also returns a
1276 // list of identifiers that may need to be returned by the extracted function.
1277 // Some of the code in this function has been adapted from tools/cmd/guru/freevars.go.
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 // id returns non-nil if n denotes an object that is referenced by the span
1288 // and defined either within the span or in the lexical environment. The bool
1289 // return value acts as an indicator for where it was defined.
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 // exclude objects denoting '_'
1297 }
1298 if _, ok := obj.(*types.PkgName); ok {
1299 return nil, false // imported package
1300 }
1301 if !(file.FileStart <= obj.Pos() && obj.Pos() <= file.FileEnd) {
1302 return nil, false // not defined in this file
1303 }
1304 scope := obj.Parent()
1305 if scope == nil {
1306 return nil, false // e.g. interface method, struct field
1307 }
1308 if scope == fileScope || scope == pkgScope {
1309 return nil, false // defined at file or package scope
1310 }
1311 if start <= obj.Pos() && obj.Pos() <= end {
1312 return obj, false // defined within selection => not free
1313 }
1314 return obj, true
1315 }
1316 // sel returns non-nil if n denotes a selection o.x.y that is referenced by the
1317 // span and defined either within the span or in the lexical environment. The bool
1318 // return value acts as an indicator for where it was defined.
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 // Avoid including labels attached to branch statements.
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 // Find the first time that the object is used in the selection.
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 // Find identifiers that are initialized or whose values are altered at some
1369 // point in the selected block. For example, in a selected block from lines 2-4,
1370 // variables x, y, and z are included in assigned. However, in a selected block
1371 // from lines 3-4, only variables y and z are included in assigned.
1372 //
1373 // 1: var a int
1374 // 2: var x int
1375 // 3: y := 3
1376 // 4: z := x + a
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 // Find identifiers that are defined prior to being used
1404 // elsewhere in the selection.
1405 // TODO: Include identifiers that are assigned prior to being
1406 // used elsewhere in the selection. Then, change the assignment
1407 // to a definition in the extracted function.
1408 if firstUseIn[obj] != lhs.Pos() {
1409 continue
1410 }
1411 // Ensure that the object is not used in its own re-definition.
1412 // For example:
1413 // var f float64
1414 // f, e := math.Frexp(f)
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 // referencesObj checks whether the given object appears in the given expression.
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 // first and last nodes wholly enclosed by selection
1503 curEnclosing inspector.Cursor // node that encloses selection (e.g. a BlockStmt)
1504 curFuncDecl inspector.Cursor // enclosing *ast.FuncDecl
1505 }
1506
1507 // canExtractFunction reports whether the code in the given range can be
1508 // extracted to a function.
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 // Node that encloses the selection must be a statement.
1520 // TODO: Support function extraction for an expression.
1521 if !is[ast.Stmt](curEnclosing.Node()) {
1522 return nil, false, false, fmt.Errorf("node is not a statement")
1523 }
1524
1525 // Find the function declaration that encloses the selection.
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 // If the selection is a block statement, use its first and last statements.
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 // objUsed checks if the object is used within the range. It returns the first
1554 // occurrence of the object in the range, if it exists.
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 // varOverridden traverses the given AST node until we find the given identifier. Then, we
1572 // examine the occurrence of the given identifier and check for (1) whether the identifier
1573 // is being redefined. If the identifier is free, we also check for (2) whether the identifier
1574 // is being reassigned. We will not include an identifier in the return statement of the
1575 // extracted function if it meets one of the above conditions.
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 // A free variable is initialized prior to the selection. We can always reassign
1587 // this variable after the selection because it has already been defined.
1588 // Conversely, a non-free variable is initialized within the selection. Thus, we
1589 // cannot reassign this variable after the selection unless it is initialized and
1590 // returned by the extracted function.
1591 if !isFree && assignment.Tok == token.ASSIGN {
1592 return false
1593 }
1594 for _, assigned := range assignment.Lhs {
1595 ident, ok := assigned.(*ast.Ident)
1596 // Check if we found the first use of the identifier.
1597 if !ok || ident != firstUse {
1598 continue
1599 }
1600 objUse := info.Uses[ident]
1601 if objUse == nil || objUse != obj {
1602 continue
1603 }
1604 // Ensure that the object is not used in its own definition.
1605 // For example:
1606 // var f float64
1607 // f, e := math.Frexp(f)
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 // parseStmts parses the specified source (a list of statements) and
1622 // returns them as a BlockStmt along with any associated comments.
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 // generateReturnInfo generates the information we need to adjust the return statements and
1643 // signature of the extracted function. We prepare names, signatures, and "zero values" that
1644 // represent the new variables. We also use this information to construct the if statement that
1645 // is inserted below the call to the extracted function.
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 // Generate information for the values in the return signature of the enclosing function.
1650 if enclosing.Results != nil {
1651 nameIdx := make(map[string]int) // last integral suffixes of generated names
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 // Generate information for the added bool value.
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 // conventionalVarNames specifies conventional names for variables with various
1713 // standard library types.
1714 //
1715 // Keep this up to date with completion.conventionalAcronyms.
1716 //
1717 // TODO(rfindley): consider factoring out a "conventions" library.
1718 var conventionalVarNames = map[objKey]string{
1719 {"", "error"}: "err",
1720 {"context", "Context"}: "ctx",
1721 {"sql", "Tx"}: "tx",
1722 {"http", "ResponseWriter"}: "rw", // Note: same as [AbbreviateVarName].
1723 }
1724
1725 // varNameForType chooses a "good" name for a variable with the given type,
1726 // if possible. Otherwise, it returns "", false.
1727 //
1728 // For special types, it uses known conventional names.
1729 func varNameForType(t types.Type) (string, bool) {
1730 tname := typesinternal.TypeNameFor(t)
1731 if tname == nil {
1732 return "", false
1733 }
1734
1735 // Have Alias, Basic, Named, or TypeParam.
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 // adjustReturnStatements adds "zero values" of the given types to each return
1748 // statement in the given AST node.
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 // Create "zero values" for each type.
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 // Add "zero values" to each return statement.
1767 // The bool reports whether the enclosing function should return after calling the
1768 // extracted function. We set the bool to 'true' because, if these return statements
1769 // execute, the extracted function terminates early, and the enclosing function must
1770 // return as well.
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 // Don't modify return statements inside anonymous functions.
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 // generateFuncCall constructs a call expression for the extracted function, described by the
1794 // given parameters and return variables.
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 // Create a return statement that returns the result of the function call.
1813 replace = &ast.ReturnStmt{
1814 Return: 0,
1815 Results: []ast.Expr{callExpr},
1816 }
1817 } else {
1818 // Assign the result of the function call.
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 // initializeVars creates variable declarations, if needed.
1832 // Our preference is to replace the selected block with an "x, y, z := fn()" style
1833 // assignment statement. We can use this style when all of the variables in the
1834 // extracted function's return statement are either not defined prior to the extracted block
1835 // or can be safely redefined. However, for example, if z is already defined
1836 // in a different scope, we replace the selected block with:
1837 //
1838 // var x int
1839 // var y string
1840 // x, y, z = fn()
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 // Each variable added from a return statement in the selection
1859 // must be initialized.
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 // getNames returns the names from the given list of returnVariable.
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 // getZeroVals returns the "zero values" from the given list of returnVariable.
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 // getDecls returns the declarations from the given list of returnVariable.
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 // replaceBranchStmtWithReturnStmt modifies the ast node to replace the given
1910 // branch statement with the given return statement.
1911 func replaceBranchStmtWithReturnStmt(block ast.Node, br *ast.BranchStmt, ret *ast.ReturnStmt) {
1912 ast.Inspect(block, func(n ast.Node) bool {
1913 // Look for the branch statement within a BlockStmt or CaseClause.
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 // freeBranches returns all branch statements beneath cur whose continuation
1935 // lies outside the (start, end) range.
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 // Find innermost relevant ancestor for break/continue.
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 // isFreeBranchStmt returns true if the relevant ancestor for the branch
1984 // statement at stack[len(stack)-1] cannot be found in the stack (for
1985 // break/continue) or the extracted block (for goto). This is used when we are
1986 // examining the extracted block, since type information isn't available. We
1987 // need to find the location of the label without using types.Info.
1988 // We treat goto and break/continue separately because while break/continue
1989 // must be used within a for, range, switch, or select, goto's use is
1990 // less restrictive within a function body.
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 // We found the label in the extracted block, so it's not a free branch stmt.
2001 return false
2002 }
2003 }
2004 return true
2005 }
2006 case token.BREAK, token.CONTINUE:
2007 // Find innermost relevant ancestor for break/continue.
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 // We didn't find the relevant ancestor on the path, so this must be a free branch statement.
2024 return true
2025 }