From ce2a33e35d87bb317bcd526328efd39ec6671405 Mon Sep 17 00:00:00 2001 From: Chiawen Chen Date: Wed, 2 Oct 2024 15:58:39 +0800 Subject: [PATCH] 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 LUCI-TryBot-Result: Go LUCI Auto-Submit: Alan Donovan Reviewed-by: Alan Donovan Auto-Submit: Robert Findley --- gopls/internal/golang/extract.go | 4 +++ .../codeaction/functionextraction.txt | 33 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/gopls/internal/golang/extract.go b/gopls/internal/golang/extract.go index d1092d85409..6ea011e220e 100644 --- a/gopls/internal/golang/extract.go +++ b/gopls/internal/golang/extract.go @@ -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 diff --git a/gopls/internal/test/marker/testdata/codeaction/functionextraction.txt b/gopls/internal/test/marker/testdata/codeaction/functionextraction.txt index 1c65fcd2329..1b9f487c49d 100644 --- a/gopls/internal/test/marker/testdata/codeaction/functionextraction.txt +++ b/gopls/internal/test/marker/testdata/codeaction/functionextraction.txt @@ -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) +} +