]> Cypherpunks repositories - gostls13.git/commitdiff
go/printer: don't crash if ast.FuncType.Params is nil
authorRobert Griesemer <gri@golang.org>
Fri, 27 Jul 2012 00:09:11 +0000 (17:09 -0700)
committerRobert Griesemer <gri@golang.org>
Fri, 27 Jul 2012 00:09:11 +0000 (17:09 -0700)
The go/ast comment for FuncType.Params says that the field may be nil.
Make sure the printer accepts such a value. The go/parser always sets
the field (to provide parenthesis position information), but a program
creating a Go AST from scatch may not.

Added corresponding test case.

Fixes #3870.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/6448060

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

index 138f3eee604992975cb8dc6df2f0629cd536b0ce..04f2adbd87b8fabfe5322bb629879bf9e19b01b1 100644 (file)
@@ -325,9 +325,14 @@ func (p *printer) parameters(fields *ast.FieldList) {
 }
 
 func (p *printer) signature(params, result *ast.FieldList) {
-       p.parameters(params)
+       if params != nil {
+               p.parameters(params)
+       } else {
+               p.print(token.LPAREN, token.RPAREN)
+       }
        n := result.NumFields()
        if n > 0 {
+               // result != nil
                p.print(blank)
                if n == 1 && result.List[0].Names == nil {
                        // single anonymous result; no ()'s
index 497d671f240bd06fe71c0ddc7fa6288d47087cc0..ab9e9b2ec8cefc02f0f74bbb1d43dbba86fa8216 100644 (file)
@@ -385,6 +385,35 @@ func (t *t) foo(a, b, c int) int {
        }
 }
 
+// TestFuncType tests that an ast.FuncType with a nil Params field
+// can be printed (per go/ast specification). Test case for issue 3870.
+func TestFuncType(t *testing.T) {
+       src := &ast.File{
+               Name: &ast.Ident{Name: "p"},
+               Decls: []ast.Decl{
+                       &ast.FuncDecl{
+                               Name: &ast.Ident{Name: "f"},
+                               Type: &ast.FuncType{},
+                       },
+               },
+       }
+
+       var buf bytes.Buffer
+       if err := Fprint(&buf, fset, src); err != nil {
+               t.Fatal(err)
+       }
+       got := buf.String()
+
+       const want = `package p
+
+func f()
+`
+
+       if got != want {
+               t.Fatalf("got:\n%s\nwant:\n%s\n", got, want)
+       }
+}
+
 // TextX is a skeleton test that can be filled in for debugging one-off cases.
 // Do not remove.
 func TestX(t *testing.T) {