Skip to content

Commit

Permalink
cmd/compile: better recovery after := (rather than =) in declarations
Browse files Browse the repository at this point in the history
Before this fix, a mistaken := in a (const/type/var) declaration
ended that declaration with an error from which the parser didn't
recover well. This low-cost change will provide a better error
message and lets the parser recover perfectly.

Fixes #31092.

Change-Id: Ic4f94dc5e29dd00b7ef6d53a80dded638e3cea80
Reviewed-on: https://go-review.googlesource.com/c/go/+/169958
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
  • Loading branch information
griesemer committed Apr 3, 2019
1 parent 9da6530 commit 4145c5d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/cmd/compile/internal/syntax/parser.go
Expand Up @@ -170,6 +170,20 @@ func (p *parser) want(tok token) {
}
}

// gotAssign is like got(_Assign) but it also accepts ":="
// (and reports an error) for better parser error recovery.
func (p *parser) gotAssign() bool {
switch p.tok {
case _Define:
p.syntaxError("expecting =")
fallthrough
case _Assign:
p.next()
return true
}
return false
}

// ----------------------------------------------------------------------------
// Error handling

Expand Down Expand Up @@ -514,7 +528,7 @@ func (p *parser) constDecl(group *Group) Decl {
d.NameList = p.nameList(p.name())
if p.tok != _EOF && p.tok != _Semi && p.tok != _Rparen {
d.Type = p.typeOrNil()
if p.got(_Assign) {
if p.gotAssign() {
d.Values = p.exprList()
}
}
Expand All @@ -533,7 +547,7 @@ func (p *parser) typeDecl(group *Group) Decl {
d.pos = p.pos()

d.Name = p.name()
d.Alias = p.got(_Assign)
d.Alias = p.gotAssign()
d.Type = p.typeOrNil()
if d.Type == nil {
d.Type = p.bad()
Expand All @@ -556,11 +570,11 @@ func (p *parser) varDecl(group *Group) Decl {
d.pos = p.pos()

d.NameList = p.nameList(p.name())
if p.got(_Assign) {
if p.gotAssign() {
d.Values = p.exprList()
} else {
d.Type = p.type_()
if p.got(_Assign) {
if p.gotAssign() {
d.Values = p.exprList()
}
}
Expand Down
16 changes: 16 additions & 0 deletions src/cmd/compile/internal/syntax/testdata/issue31092.src
@@ -0,0 +1,16 @@
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Test cases for issue 31092: Better synchronization of
// parser after seeing an := rather than an = in a const,
// type, or variable declaration.

package p

const _ /* ERROR unexpected := */ := 0
type _ /* ERROR unexpected := */ := int
var _ /* ERROR unexpected := */ := 0

const _ int /* ERROR unexpected := */ := 0
var _ int /* ERROR unexpected := */ := 0

0 comments on commit 4145c5d

Please sign in to comment.