From dcb37f94e0a981b322f4c15c343695c70cca09d1 Mon Sep 17 00:00:00 2001 From: Robert Griesemer Date: Thu, 22 Jan 2015 21:54:26 -0800 Subject: [PATCH] go/parser: report error for var/const decls with missing init exprs Fixes #9639. Change-Id: I311045d3df26b29b9380c159ef4727e85650d13b Reviewed-on: https://go-review.googlesource.com/3211 Reviewed-by: Alan Donovan --- src/go/parser/parser.go | 12 ++++++++++++ src/go/parser/short_test.go | 7 ++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/go/parser/parser.go b/src/go/parser/parser.go index c9dbd06ad2..0409122c81 100644 --- a/src/go/parser/parser.go +++ b/src/go/parser/parser.go @@ -2228,6 +2228,7 @@ func (p *parser) parseValueSpec(doc *ast.CommentGroup, keyword token.Token, iota defer un(trace(p, keyword.String()+"Spec")) } + pos := p.pos idents := p.parseIdentList() typ := p.tryType() var values []ast.Expr @@ -2238,6 +2239,17 @@ func (p *parser) parseValueSpec(doc *ast.CommentGroup, keyword token.Token, iota } p.expectSemi() // call before accessing p.linecomment + switch keyword { + case token.VAR: + if typ == nil && values == nil { + p.error(pos, "missing variable type or initialization") + } + case token.CONST: + if values == nil && (iota == 0 || typ != nil) { + p.error(pos, "missing constant value") + } + } + // Go spec: The scope of a constant or variable identifier declared inside // a function begins at the end of the ConstSpec or VarSpec and ends at // the end of the innermost containing block. diff --git a/src/go/parser/short_test.go b/src/go/parser/short_test.go index 7d12170c0e..14a14d5a59 100644 --- a/src/go/parser/short_test.go +++ b/src/go/parser/short_test.go @@ -43,6 +43,7 @@ var valids = []string{ `package p; func _() { map[int]int{}[0]++; map[int]int{}[0] += 1 }`, `package p; func _(x interface{f()}) { interface{f()}(x).f() }`, `package p; func _(x chan int) { chan int(x) <- 0 }`, + `package p; const (x = 0; y; z)`, // issue 9639 } func TestValid(t *testing.T) { @@ -97,7 +98,11 @@ var invalids = []string{ `package p; func f() { go f /* ERROR HERE "function must be invoked" */ }`, `package p; func f() { defer func() {} /* ERROR HERE "function must be invoked" */ }`, `package p; func f() { go func() { func() { f(x func /* ERROR "expected '\)'" */ (){}) } } }`, - `package p; func f() (a b string /* ERROR "expected '\)'" */ , ok bool) // issue 8656`, + `package p; func f() (a b string /* ERROR "expected '\)'" */ , ok bool)`, // issue 8656 + `package p; var x /* ERROR "missing variable type or initialization" */ , y, z;`, // issue 9639 + `package p; const x /* ERROR "missing constant value" */ ;`, // issue 9639 + `package p; const x /* ERROR "missing constant value" */ int;`, // issue 9639 + `package p; const (x = 0; y; z /* ERROR "missing constant value" */ int);`, // issue 9639 } func TestInvalid(t *testing.T) { -- 2.50.0