cmd/compile/internal/syntax: better error message for erroneous method declaration

Also make error recovery slightly more robust in this case.

Fixes #56022.

Change-Id: I1c01c1465adb48c71367d037b6f0e3fe56f68ec9
Reviewed-on: https://go-review.googlesource.com/c/go/+/438540
Run-TryBot: Robert Griesemer <gri@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
Reviewed-by: Robert Findley <rfindley@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
This commit is contained in:
Robert Griesemer 2022-10-04 10:24:05 -07:00 committed by Robert Griesemer
parent d118743869
commit c591d82ea9
2 changed files with 21 additions and 11 deletions

View File

@ -767,7 +767,9 @@ func (p *parser) funcDeclOrNil() *FuncDecl {
f.pos = p.pos()
f.Pragma = p.takePragma()
var context string
if p.got(_Lparen) {
context = "method"
rcvr := p.paramList(nil, nil, _Rparen, false)
switch len(rcvr) {
case 0:
@ -780,20 +782,18 @@ func (p *parser) funcDeclOrNil() *FuncDecl {
}
}
if p.tok != _Name {
p.syntaxError("expected name or (")
if p.tok == _Name {
f.Name = p.name()
f.TParamList, f.Type = p.funcType(context)
} else {
msg := "expected name or ("
if context != "" {
msg = "expected name"
}
p.syntaxError(msg)
p.advance(_Lbrace, _Semi)
return nil
}
f.Name = p.name()
context := ""
if f.Recv != nil {
context = "method" // don't permit (method) type parameters in funcType
}
f.TParamList, f.Type = p.funcType(context)
if p.tok == _Lbrace {
f.Body = p.funcBody()
}

View File

@ -0,0 +1,10 @@
// Copyright 2022 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.
package p
func /* ERROR unexpected {, expected name or \($ */ {}
func (T) /* ERROR unexpected {, expected name$ */ {}
func (T) /* ERROR unexpected \(, expected name$ */ () {}
func (T) /* ERROR unexpected \(, expected name$ */ ()