]> Cypherpunks.ru repositories - gostls13.git/commitdiff
go/printer: fix invalid output for empty decls
authorMauri de Souza Meneguzzo <mauri870@gmail.com>
Tue, 17 Oct 2023 18:36:31 +0000 (18:36 +0000)
committerGopher Robot <gobot@golang.org>
Tue, 17 Oct 2023 18:53:17 +0000 (18:53 +0000)
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 <gri@google.com>
Reviewed-by: Alan Donovan <adonovan@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Mauri de Souza Meneguzzo <mauri870@gmail.com>

src/go/printer/nodes.go
src/go/printer/printer_test.go

index 0a693b6667ac314fdcf486d01eb16fefba7784c4..a4651e060868d23c44150bfeb334d8305d6c3848 100644 (file)
@@ -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)
index 8e78bc640e1a230541569d079aff74a246c0c6ca..6d5b559e50e493494a4ebe590cc8c6c2e8e3ff3f 100644 (file)
@@ -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)
+               }
+       }
+}