go icon indicating copy to clipboard operation
go copied to clipboard

go/format: possible internal error in format.Node when source contains //go:build directive

Open mateusz834 opened this issue 1 year ago • 1 comments

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

mateusz834 avatar Aug 27 '24 17:08 mateusz834

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

mateusz834 avatar Aug 27 '24 17:08 mateusz834

Change https://go.dev/cl/609055 mentions this issue: go/printer: correctly print trailing //go:build and //+build

gopherbot avatar Aug 28 '24 12:08 gopherbot

Related Issues and Documentation

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

gabyhelp avatar Aug 28 '24 21:08 gabyhelp