From ff7986d67029992b6a388a3797c4024d9a4856da Mon Sep 17 00:00:00 2001 From: Mauri de Souza Meneguzzo Date: Tue, 17 Oct 2023 18:36:31 +0000 Subject: [PATCH] go/printer: fix invalid output for empty decls The current output for empty declarations such as var, const, import results in "var", "const", "import" respectively. These are not valid and the parser will promptly reject them as invalid syntax. This CL updates this behavior by adding "()" to the output of empty decls so the syntax becomes valid, e.g "var ()" instead of "var". Fixes #63566 Change-Id: I571b182d9ccf71b159360c8de003ad55d0ff3443 GitHub-Last-Rev: 2720419e364938e9962be71d0e6ed51375fec404 GitHub-Pull-Request: golang/go#63593 Reviewed-on: https://go-review.googlesource.com/c/go/+/535995 Reviewed-by: Robert Griesemer Reviewed-by: Alan Donovan Auto-Submit: Robert Griesemer TryBot-Result: Gopher Robot Run-TryBot: Mauri de Souza Meneguzzo --- src/go/printer/nodes.go | 2 +- src/go/printer/printer_test.go | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/go/printer/nodes.go b/src/go/printer/nodes.go index 0a693b6667..a4651e0608 100644 --- a/src/go/printer/nodes.go +++ b/src/go/printer/nodes.go @@ -1739,7 +1739,7 @@ func (p *printer) genDecl(d *ast.GenDecl) { p.setPos(d.Pos()) p.print(d.Tok, blank) - if d.Lparen.IsValid() || len(d.Specs) > 1 { + if d.Lparen.IsValid() || len(d.Specs) != 1 { // group of parenthesized declarations p.setPos(d.Lparen) p.print(token.LPAREN) diff --git a/src/go/printer/printer_test.go b/src/go/printer/printer_test.go index 8e78bc640e..6d5b559e50 100644 --- a/src/go/printer/printer_test.go +++ b/src/go/printer/printer_test.go @@ -848,3 +848,18 @@ func TestSourcePosNewline(t *testing.T) { t.Errorf("unexpected Fprint output:\n%s", buf.Bytes()) } } + +// TestEmptyDecl tests that empty decls for const, var, import are printed with +// valid syntax e.g "var ()" instead of just "var", which is invalid and cannot +// be parsed. +func TestEmptyDecl(t *testing.T) { // issue 63566 + for _, tok := range []token.Token{token.IMPORT, token.CONST, token.TYPE, token.VAR} { + var buf bytes.Buffer + Fprint(&buf, token.NewFileSet(), &ast.GenDecl{Tok: tok}) + got := buf.String() + want := tok.String() + " ()" + if got != want { + t.Errorf("got %q, want %q", got, want) + } + } +} -- 2.50.0