Skip to content

Commit 0db8f68

Browse files
committed
[release-branch.go1] go/printer: don't crash if ast.FuncType.Params is nil
««« backport 7f6a0510d3c9 go/printer: don't crash if ast.FuncType.Params is nil 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 »»»
1 parent c9cf888 commit 0db8f68

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/pkg/go/printer/nodes.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -325,9 +325,14 @@ func (p *printer) parameters(fields *ast.FieldList) {
325325
}
326326

327327
func (p *printer) signature(params, result *ast.FieldList) {
328-
p.parameters(params)
328+
if params != nil {
329+
p.parameters(params)
330+
} else {
331+
p.print(token.LPAREN, token.RPAREN)
332+
}
329333
n := result.NumFields()
330334
if n > 0 {
335+
// result != nil
331336
p.print(blank)
332337
if n == 1 && result.List[0].Names == nil {
333338
// single anonymous result; no ()'s

src/pkg/go/printer/printer_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,35 @@ func (t *t) foo(a, b, c int) int {
385385
}
386386
}
387387

388+
// TestFuncType tests that an ast.FuncType with a nil Params field
389+
// can be printed (per go/ast specification). Test case for issue 3870.
390+
func TestFuncType(t *testing.T) {
391+
src := &ast.File{
392+
Name: &ast.Ident{Name: "p"},
393+
Decls: []ast.Decl{
394+
&ast.FuncDecl{
395+
Name: &ast.Ident{Name: "f"},
396+
Type: &ast.FuncType{},
397+
},
398+
},
399+
}
400+
401+
var buf bytes.Buffer
402+
if err := Fprint(&buf, fset, src); err != nil {
403+
t.Fatal(err)
404+
}
405+
got := buf.String()
406+
407+
const want = `package p
408+
409+
func f()
410+
`
411+
412+
if got != want {
413+
t.Fatalf("got:\n%s\nwant:\n%s\n", got, want)
414+
}
415+
}
416+
388417
// TextX is a skeleton test that can be filled in for debugging one-off cases.
389418
// Do not remove.
390419
func TestX(t *testing.T) {

0 commit comments

Comments
 (0)