go/format: possible internal error in format.Node when source contains //go:build directive
Reproducer:
func TestBuildDirectiveFormat(t *testing.T) {
const src = "package A\nimport()\nfunc A(){0//go:build\n0}"
fs := token.NewFileSet()
f, err := parser.ParseFile(fs, "test.go", src, parser.ParseComments|parser.SkipObjectResolution)
if err != nil {
t.Fatal(err)
}
if err := printer.Fprint(io.Discard, fs, f); err != nil {
t.Fatal(err) // no error
}
if err := format.Node(io.Discard, fs, f); err != nil {
t.Fatal(err) // format.Node internal error (8:5: expected ';', found 0 (and 1 more errors))
}
}
printer.Fprint does not return an error for the same source, only the format.Node errors. It happens here:
https://github.com/golang/go/blob/994d1d446663873dd593846a0b94147410e5922a/src/go/format/format.go#L76-L80
CC @griesemer
This happens because, the config.Fprint here:
https://github.com/golang/go/blob/994d1d446663873dd593846a0b94147410e5922a/src/go/format/format.go#L71-L81
formats the source as:
"//go:build\n\npackage A\n\nimport ()\n\nfunc A() {\n\t0 0\n}\n"
This wrong formatting happens here:
https://github.com/golang/go/blob/994d1d446663873dd593846a0b94147410e5922a/src/go/printer/printer.go#L1371-L1373
Change https://go.dev/cl/609055 mentions this issue: go/printer: correctly print trailing //go:build and //+build
Related Issues and Documentation
- go/format: format.Node internal error (1:13: expected ';', found '-') #30950 (closed)
- go/format: doesn't format source when source has comment after package name #26931 (closed)
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)