cmd/gofmt: trailing comments in composite literals are misaligned
Go version
go version go1.25.5 darwin/arm64
Description
I noticed that gofmt produces the following formatting for a byte slice literal:
fr.Write([]byte{
0x00, // Preamble
0x00, 0xFF, // Start code
dlen, // LEN
^dlen + 1, // LCS
tfi, // Type of Frame Identifier
})
My expectation was that comments would remain aligned consistently. Is this a known limitation or intended behavior of gofmt? Apologies if this was already reported.
(Go 1.24 produces the same output: https://go.dev/play/p/jxcnuqd6IsA?v=goprev)
Related Issues
- cmd/gofmt: Invalid `go fmt` comment formatting after unicode string #73105 (closed)
- cmd/gofmt: comments in empty composite literals cannot be indented #22355 (closed)
- cmd/gofmt: odd comment alignment #9064 (closed)
- cmd/gofmt: Faulty Comment Re-Arrangement in Argument Lists #13113
- cmd/gofmt: Slice literal condensed to one line and comment moved outside if comment is last line #18599
- cmd/gofmt: strange indentation in slice literal #23655 (closed)
- cmd/gofmt: strange indentation with trailing comments #20874 (closed)
- cmd/gofmt: slice of structs not consistently formatted #34582
- cmd/gofmt: Comments are incorrectly moved across commas #68190 (closed)
- cmd/gofmt: indent comments in otherwise-empty slice, array, and map literals #16140 (closed)
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)
CC @griesemer, @mvdan.
My guess is that between the second and third comment, the line length decreases enough where it starts a new "comment alignment chunk", which just happens to be one character to the left, as the fourth comment is the longest of that second chunk.
This is more apparent if you increase the difference:
package main
func main() {
fr.Write([]byte{
0x00, // Preamble
0x00, 0xFF, 0xFF, 0xFF, // Start code
dlen, // LEN
^dlen + 1, // LCS
tfi, // Type of Frame Identifier
})
}
I guess you could try tweaking the heuristic so that it doesn't split comment alignment chunks if the difference is very small. However, note that this could have surprising knock-on effects; what if we have ten consecutive chunks which each decrease the alignment level by one? Should they all gain whitespace with the change?
It's easier to see the desired behavior when the difference in length is larger: https://go.dev/play/p/n0dnfZkATl3?v=goprev
I'm sure there are unfortunate edge cases (like yours) where the behavior is a little unexpected, but changes to the formatter are very disruptive for the whole Go community, so I don't see a compelling reason to change the algorithm here.