go icon indicating copy to clipboard operation
go copied to clipboard

go/printer: Invalid reformatting of slice type with a /* comment.

Open JonasUnderscore opened this issue 1 year ago • 5 comments

Go version

devel go1.23-7492290887

Output of go env in your module/workspace:

set GO111MODULE=
set GOARCH=amd64
set GOBIN=
set GOEXE=.exe
set GOEXPERIMENT=
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GOOS=windows
set GOTOOLCHAIN=auto
set GOVERSION=devel go1.23-...

What did you do?

https://go.dev/play/p/ndVJVdo9nIW Click format.

A realistic example could be formatting var s [/*<10*/]byte

What did you see happen?

Formatting code with a "/*" comment and line break inside "[" "]" of a slice either fails or produces invalid code. Clicking format fails with "24:16: expected type, found newline (and 1 more errors)".

Having multiple comments moves them 2 lines down (no error). Line comments and multi-line comments are moved to the next position after "]" where line breaks don't insert a ";".

Setting a fake position to the same line as the element type before writing "]" changes the behavior. "go/printer/nodes.go:1049"

ast.ArrayType lacks position information about "]". The closing "]" must be on the same line as the array length ends. On a slice type this implicit positioning spans multiple lines and the chosen line affects ;'s.

What did you expect to see?

Comments not moving across tokens when formatted. I would also like the ast types to have positions for more tokens. Guessing the position requires different logic for different types: last line for slice "]", first line for map "]", first line for type assert ".", unknown for <- chan "chan".

JonasUnderscore avatar Jun 07 '24 00:06 JonasUnderscore

Specifically, gofmt turns this valid Go code

type Slice = [
	/*a*/]any

into this invalid code:

type Slice = []
/*a*/ any

CC @griesemer

ianlancetaylor avatar Jun 07 '24 00:06 ianlancetaylor

CC @mvdan as well, via https://dev.golang.org/owners

mknyszek avatar Jun 07 '24 20:06 mknyszek

Similar Issues

  • https://github.com/golang/go/issues/66439

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

gabyhelp avatar Jun 08 '24 03:06 gabyhelp

Fixing this will require additional position information in the go/ast.ArrayType node (position of the ], trivial but requires API change) or better "guessing" of the position of "]" based on the available comment and node positions (hard).

griesemer avatar Jun 10 '24 18:06 griesemer

Even with bad position information it seems like the formatter should understand when it is safe to insert a line break and when it isn't; we should always emit valid Go code.

rsc avatar Jun 28 '24 18:06 rsc