Commit dcb37f94 authored by Robert Griesemer's avatar Robert Griesemer

go/parser: report error for var/const decls with missing init exprs

Fixes #9639.

Change-Id: I311045d3df26b29b9380c159ef4727e85650d13b
Reviewed-on: https://go-review.googlesource.com/3211Reviewed-by: default avatarAlan Donovan <adonovan@google.com>
parent c242fbc9
......@@ -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.
......
......@@ -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) {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment