Skip to content

Commit

Permalink
gopls/internal: fix extract refactor for cases with anonymous functions
Browse files Browse the repository at this point in the history
This fix ignores return statements inside anonymous functions. These
return statements can be ignored because they does not meddle with
the control flow of the outer function.

Fixes golang/go#64821

Change-Id: I21f82f8663bf3343412d5b537802a56efc34495f
Reviewed-on: https://go-review.googlesource.com/c/tools/+/617335
Reviewed-by: Robert Findley <rfindley@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Alan Donovan <adonovan@google.com>
Reviewed-by: Alan Donovan <adonovan@google.com>
Auto-Submit: Robert Findley <rfindley@google.com>
  • Loading branch information
golopot authored and gopherbot committed Oct 2, 2024
1 parent a2ff832 commit ce2a33e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
4 changes: 4 additions & 0 deletions gopls/internal/golang/extract.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,10 @@ func extractFunctionMethod(fset *token.FileSet, start, end token.Pos, src []byte
if n.Pos() < start || n.End() > end {
return n.Pos() <= end
}
// exclude return statements in function literals because they don't affect the refactor.
if _, ok := n.(*ast.FuncLit); ok {
return false
}
ret, ok := n.(*ast.ReturnStmt)
if !ok {
return true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -581,3 +581,36 @@ func newFunction() (int, error) {
return u, err
}

-- anonymousfunc.go --
package extract
import "cmp"
import "slices"

// issue go#64821
func _() {
var s []string //@codeaction("var", anonEnd, "refactor.extract.function", anon1)
slices.SortFunc(s, func(a, b string) int {
return cmp.Compare(a, b)
})
println(s) //@loc(anonEnd, ")")
}

-- @anon1/anonymousfunc.go --
package extract
import "cmp"
import "slices"

// issue go#64821
func _() {
//@codeaction("var", anonEnd, "refactor.extract.function", anon1)
newFunction() //@loc(anonEnd, ")")
}

func newFunction() {
var s []string
slices.SortFunc(s, func(a, b string) int {
return cmp.Compare(a, b)
})
println(s)
}

0 comments on commit ce2a33e

Please sign in to comment.