Skip to content

Commit ce2a33e

Browse files
golopotgopherbot
authored andcommitted
gopls/internal: fix extract refactor for cases with anonymous functions
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 <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Auto-Submit: Alan Donovan <[email protected]> Reviewed-by: Alan Donovan <[email protected]> Auto-Submit: Robert Findley <[email protected]>
1 parent a2ff832 commit ce2a33e

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

gopls/internal/golang/extract.go

+4
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,10 @@ func extractFunctionMethod(fset *token.FileSet, start, end token.Pos, src []byte
246246
if n.Pos() < start || n.End() > end {
247247
return n.Pos() <= end
248248
}
249+
// exclude return statements in function literals because they don't affect the refactor.
250+
if _, ok := n.(*ast.FuncLit); ok {
251+
return false
252+
}
249253
ret, ok := n.(*ast.ReturnStmt)
250254
if !ok {
251255
return true

gopls/internal/test/marker/testdata/codeaction/functionextraction.txt

+33
Original file line numberDiff line numberDiff line change
@@ -581,3 +581,36 @@ func newFunction() (int, error) {
581581
return u, err
582582
}
583583

584+
-- anonymousfunc.go --
585+
package extract
586+
import "cmp"
587+
import "slices"
588+
589+
// issue go#64821
590+
func _() {
591+
var s []string //@codeaction("var", anonEnd, "refactor.extract.function", anon1)
592+
slices.SortFunc(s, func(a, b string) int {
593+
return cmp.Compare(a, b)
594+
})
595+
println(s) //@loc(anonEnd, ")")
596+
}
597+
598+
-- @anon1/anonymousfunc.go --
599+
package extract
600+
import "cmp"
601+
import "slices"
602+
603+
// issue go#64821
604+
func _() {
605+
//@codeaction("var", anonEnd, "refactor.extract.function", anon1)
606+
newFunction() //@loc(anonEnd, ")")
607+
}
608+
609+
func newFunction() {
610+
var s []string
611+
slices.SortFunc(s, func(a, b string) int {
612+
return cmp.Compare(a, b)
613+
})
614+
println(s)
615+
}
616+

0 commit comments

Comments
 (0)