golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
122.93k stars 17.53k forks source link

x/tools/gopls: Extract function not handle anonymous functions correctly #64821

Open rogeryk opened 9 months ago

rogeryk commented 9 months ago

gopls version

v14.2

go env

unimportant

What did you do?

In the following example, select all main function body, then toggle "Extract function"

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

What did you expect to see?

func main() {
    newFunction()
}

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

What did you see instead?

func main() {
    shouldReturn := newFunction()
    if shouldReturn {
        return
    }
}

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

Editor and settings

No response

Logs

No response

adonovan commented 9 months ago

The bad news is that "extract function" has a lot of serious bugs that make it a use-at-your-own-peril sort of feature: notably, it discards all comments in the code that migrates. The good news is that it is a priority for our team in 2024 to improve all of our refactoring tools.