1
0
mirror of https://github.com/golang/go synced 2024-11-18 00:44:47 -07:00

go/parser: better error message for incorrect type switch header

Fixes 11829.

Change-Id: I2e39f61e12953147b0cd6a11d29179c500c94964
Reviewed-on: https://go-review.googlesource.com/14566
Reviewed-by: Chris Manghane <cmang@golang.org>
This commit is contained in:
Robert Griesemer 2015-09-14 16:59:15 -07:00
parent 5b3f29a2e7
commit b0507f1579
2 changed files with 15 additions and 6 deletions

View File

@ -1910,14 +1910,23 @@ func isTypeSwitchAssert(x ast.Expr) bool {
return ok && a.Type == nil
}
func isTypeSwitchGuard(s ast.Stmt) bool {
func (p *parser) isTypeSwitchGuard(s ast.Stmt) bool {
switch t := s.(type) {
case *ast.ExprStmt:
// x.(nil)
// x.(type)
return isTypeSwitchAssert(t.X)
case *ast.AssignStmt:
// v := x.(nil)
return len(t.Lhs) == 1 && t.Tok == token.DEFINE && len(t.Rhs) == 1 && isTypeSwitchAssert(t.Rhs[0])
// v := x.(type)
if len(t.Lhs) == 1 && len(t.Rhs) == 1 && isTypeSwitchAssert(t.Rhs[0]) {
switch t.Tok {
case token.ASSIGN:
// permit v = x.(type) but complain
p.error(t.TokPos, "expected ':=', found '='")
fallthrough
case token.DEFINE:
return true
}
}
}
return false
}
@ -1963,7 +1972,7 @@ func (p *parser) parseSwitchStmt() ast.Stmt {
p.exprLev = prevLev
}
typeSwitch := isTypeSwitchGuard(s2)
typeSwitch := p.isTypeSwitchGuard(s2)
lbrace := p.expect(token.LBRACE)
var list []ast.Stmt
for p.tok == token.CASE || p.tok == token.DEFAULT {

View File

@ -64,7 +64,7 @@ var invalids = []string{
`package p; func f() { for _ = range x ; /* ERROR "expected '{'" */ ; {} };`,
`package p; func f() { for ; ; _ = range /* ERROR "expected operand" */ x {} };`,
`package p; func f() { for ; _ /* ERROR "expected boolean or range expression" */ = range x ; {} };`,
`package p; func f() { switch t /* ERROR "expected switch expression" */ = t.(type) {} };`,
`package p; func f() { switch t = /* ERROR "expected ':=', found '='" */ t.(type) {} };`,
`package p; func f() { switch t /* ERROR "expected switch expression" */ , t = t.(type) {} };`,
`package p; func f() { switch t /* ERROR "expected switch expression" */ = t.(type), t {} };`,
`package p; var a = [ /* ERROR "expected expression" */ 1]int;`,