Skip to content

Commit

Permalink
go/parser: allow trailing commas in embedded instantiated types
Browse files Browse the repository at this point in the history
go/parser can correctly parse interfaces that instantiate and embed
generic interfaces, but not structs. This is because in the case of
structs, it does not expect RBRACK as a token trailing COMMA in the type
argument, even though it is allowed by the spec.

For example, go/parser produces an error for the type declaration below:

type A struct {
    B[byte, []byte,]
}

Fixes #56748

Change-Id: Ibb2addd6cf9b381d8470a6d20eedb93f13f93cd6
Reviewed-on: https://go-review.googlesource.com/c/go/+/450175
Run-TryBot: Robert Griesemer <[email protected]>
Reviewed-by: Robert Findley <[email protected]>
TryBot-Result: Gopher Robot <[email protected]>
Auto-Submit: Robert Griesemer <[email protected]>
Reviewed-by: Robert Griesemer <[email protected]>
  • Loading branch information
cia-rana authored and Robert Griesemer committed Nov 17, 2022
1 parent f3ae7ac commit cafb49a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/go/parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -587,15 +587,19 @@ func (p *parser) parseArrayFieldOrTypeInstance(x *ast.Ident) (*ast.Ident, ast.Ex
defer un(trace(p, "ArrayFieldOrTypeInstance"))
}

// TODO(gri) Should we allow a trailing comma in a type argument
// list such as T[P,]? (We do in parseTypeInstance).
lbrack := p.expect(token.LBRACK)
trailingComma := token.NoPos // if valid, the position of a trailing comma preceding the ']'
var args []ast.Expr
if p.tok != token.RBRACK {
p.exprLev++
args = append(args, p.parseRhs())
for p.tok == token.COMMA {
comma := p.pos
p.next()
if p.tok == token.RBRACK {
trailingComma = comma
break
}
args = append(args, p.parseRhs())
}
p.exprLev--
Expand All @@ -613,6 +617,10 @@ func (p *parser) parseArrayFieldOrTypeInstance(x *ast.Ident) (*ast.Ident, ast.Ex
elt := p.tryIdentOrType()
if elt != nil {
// x [P]E
if trailingComma.IsValid() {
// Trailing commas are invalid in array type fields.
p.error(trailingComma, "unexpected comma; expecting ]")
}
return x, &ast.ArrayType{Lbrack: lbrack, Len: args[0], Elt: elt}
}
}
Expand Down
7 changes: 7 additions & 0 deletions src/go/parser/testdata/tparams.go2
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,19 @@ type _[a t, b t, c /* ERROR "type parameters must be named" */ ] struct{}
type _ struct {
t [n]byte
t[a]
t[a,]
t[a, b]
t[a, b,]
}
type _ struct {
t [n, /* ERROR "unexpected comma; expecting ]" */ ]byte
}
type _ interface {
t[a]
t[a,]
m[ /* ERROR "method must have no type parameters" */ _ _, /* ERROR mixed */ _]()
t[a, b]
t[a, b,]
}

func _[] /* ERROR "empty type parameter list" */ ()
Expand Down

0 comments on commit cafb49a

Please sign in to comment.