From 85f59b34291a9e16bf3a2e7db586cd824a121825 Mon Sep 17 00:00:00 2001 From: Robert Griesemer Date: Wed, 26 Feb 2014 09:54:01 -0800 Subject: [PATCH] go/parser: report error if ParseExpr argument contains extra tokens This partly addresses issue 6099 where a gofmt rewrite is behaving unexpectedly because the provided rewrite term is not a valid expression but is silently consumed anyway. LGTM=bradfitz R=golang-codereviews, bradfitz CC=golang-codereviews https://golang.org/cl/68920044 --- src/pkg/go/parser/interface.go | 7 +++++++ src/pkg/go/parser/parser_test.go | 15 +++++++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/pkg/go/parser/interface.go b/src/pkg/go/parser/interface.go index 0f83ca9314..57da4ddcd9 100644 --- a/src/pkg/go/parser/interface.go +++ b/src/pkg/go/parser/interface.go @@ -182,6 +182,13 @@ func ParseExpr(x string) (ast.Expr, error) { p.closeScope() assert(p.topScope == nil, "unbalanced scopes") + // If a semicolon was inserted, consume it; + // report an error if there's more tokens. + if p.tok == token.SEMICOLON { + p.next() + } + p.expect(token.EOF) + if p.errors.Len() > 0 { p.errors.Sort() return nil, p.errors.Err() diff --git a/src/pkg/go/parser/parser_test.go b/src/pkg/go/parser/parser_test.go index 0a34b7e505..2797ea518b 100644 --- a/src/pkg/go/parser/parser_test.go +++ b/src/pkg/go/parser/parser_test.go @@ -78,7 +78,7 @@ func TestParseExpr(t *testing.T) { } // sanity check if _, ok := x.(*ast.BinaryExpr); !ok { - t.Errorf("ParseExpr(%s): got %T, expected *ast.BinaryExpr", src, x) + t.Errorf("ParseExpr(%s): got %T, want *ast.BinaryExpr", src, x) } // a valid type expression @@ -89,17 +89,24 @@ func TestParseExpr(t *testing.T) { } // sanity check if _, ok := x.(*ast.StructType); !ok { - t.Errorf("ParseExpr(%s): got %T, expected *ast.StructType", src, x) + t.Errorf("ParseExpr(%s): got %T, want *ast.StructType", src, x) } // an invalid expression src = "a + *" _, err = ParseExpr(src) if err == nil { - t.Fatalf("ParseExpr(%s): %v", src, err) + t.Fatalf("ParseExpr(%s): got no error", src) + } + + // a valid expression followed by extra tokens is invalid + src = "a[i] := x" + _, err = ParseExpr(src) + if err == nil { + t.Fatalf("ParseExpr(%s): got no error", src) } - // it must not crash + // ParseExpr must not crash for _, src := range valids { ParseExpr(src) } -- 2.48.1