Skip to content

x/tools/gopls/internal/analysis/modernize: slices.Delete modernizer is unsound (clears out s[len:cap]) #73686

Description

@gandrejczuk

gopls version

The issue is for latest modernize

go env

See below

What did you do?

$ cat test.go
// You can edit this code!
// Click here and start typing.
package main

import (
        "fmt"
)

func p(v int) *int {
        return &v
}

func main() {
        fmt.Println("Hello, 世界")
        x := []*int{p(1), p(2), p(3), p(4)}

        for i, member := range x {
                println(i)
                if *member == 2 {
                        x = append(x[:i], x[i+1:]...)
                        // Modernize will generate following code which will panic
                        // when last elemeny will be accessed
                        // x = slices.Delete(x, i, i+1)
                }
        }

        fmt.Printf("%v\n", x)
}
$ go run test.go
Hello, 世界
0
1
2
3
[0xc0000120f0 0xc000012100 0xc000012108]
$ go run golang.org/x/tools/gopls/internal/analysis/modernize/cmd/modernize@latest -fix test.go
$ cat test.go
// You can edit this code!
// Click here and start typing.
package main

import (
        "fmt"
        "slices"
)

func p(v int) *int {
        return &v
}

func main() {
        fmt.Println("Hello, 世界")
        x := []*int{p(1), p(2), p(3), p(4)}

        for i, member := range x {
                println(i)
                if *member == 2 {
                        x = slices.Delete(x, i, i+1)
                        // Modernize will generate following code which will panic
                        // when last elemeny will be accessed
                        // x = slices.Delete(x, i, i+1)
                }
        }

        fmt.Printf("%v\n", x)
}
$ go run test.go
Hello, 世界
0
1
2
3
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4912d7]

goroutine 1 [running]:
main.main()
        test.go:20 +0x1d7
exit status 2

What did you see happen?

Hello, 世界
0
1
2
3
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4930b7]

goroutine 1 [running]:
main.main()
	/tmp/sandbox3797330105/prog.go:20 +0x1d7

What did you expect to see?

Hello, 世界
0
1
2
3
[0xc000010080 0xc000010090 0xc000010098]

Program exited.

Editor and settings

No response

Logs

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

BugReportIssues describing a possible bug in the Go implementation.FrozenDueToAgeToolsThis label describes issues relating to any tools in the x/tools repository.goplsIssues related to the Go language server, gopls.

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions