]> Cypherpunks repositories - gostls13.git/commitdiff
go/parser: better error message for incorrect type switch header
authorRobert Griesemer <gri@golang.org>
Mon, 14 Sep 2015 23:59:15 +0000 (16:59 -0700)
committerRobert Griesemer <gri@golang.org>
Wed, 16 Sep 2015 20:06:38 +0000 (20:06 +0000)
Fixes 11829.

Change-Id: I2e39f61e12953147b0cd6a11d29179c500c94964
Reviewed-on: https://go-review.googlesource.com/14566
Reviewed-by: Chris Manghane <cmang@golang.org>
src/go/parser/parser.go
src/go/parser/short_test.go

index 521bdce1ddf0eed3b3d9377adb74752de3e4b53e..73edaa0ab34cfa6aff9f44106ee1eefe977a402c 100644 (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 {
index 6ef3b0725595636ee2c37e014b5b815e6a0edb52..e05ae8e9e98ae80e7ac9e3494033b223925533c9 100644 (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;`,