go/types, types2: report struct type for literals with too few/many elements

This change essentially matches the 1.17 compiler error message for
this error.

Fixes #51877.

Change-Id: I24ec2f9cc93d8cd2283d097332a39bc1a0eed3a1
Reviewed-on: https://go-review.googlesource.com/c/go/+/394914
Trust: Robert Griesemer <gri@golang.org>
Reviewed-by: Robert Findley <rfindley@google.com>
This commit is contained in:
Robert Griesemer 2022-03-22 21:28:32 -07:00
parent dd211cf039
commit f9747b7f73
4 changed files with 40 additions and 4 deletions

View file

@ -1429,7 +1429,7 @@ func (check *Checker) exprInternal(x *operand, e syntax.Expr, hint Type) exprKin
}
check.expr(x, e)
if i >= len(fields) {
check.error(x, "too many values in struct literal")
check.errorf(x, "too many values in %s{…}", base)
break // cannot continue
}
// i < len(fields)
@ -1442,7 +1442,7 @@ func (check *Checker) exprInternal(x *operand, e syntax.Expr, hint Type) exprKin
check.assignment(x, etyp, "struct literal")
}
if len(e.ElemList) < len(fields) {
check.error(e.Rbrace, "too few values in struct literal")
check.errorf(e.Rbrace, "too few values in %s{…}", base)
// ok to continue
}
}

View file

@ -0,0 +1,18 @@
// Copyright 2013 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
type S struct {
f1 int
f2 bool
}
var (
_ = S{0} /* ERROR too few values in S{…} */
_ = struct{ f1, f2 int }{0} /* ERROR too few values in struct{f1 int; f2 int}{…} */
_ = S{0, true, "foo" /* ERROR too many values in S{…} */}
_ = struct{ f1, f2 int }{0, 1, 2 /* ERROR too many values in struct{f1 int; f2 int}{…} */}
)

View file

@ -1404,7 +1404,7 @@ func (check *Checker) exprInternal(x *operand, e ast.Expr, hint Type) exprKind {
}
check.expr(x, e)
if i >= len(fields) {
check.error(x, _InvalidStructLit, "too many values in struct literal")
check.errorf(x, _InvalidStructLit, "too many values in %s{…}", base)
break // cannot continue
}
// i < len(fields)
@ -1419,7 +1419,7 @@ func (check *Checker) exprInternal(x *operand, e ast.Expr, hint Type) exprKind {
check.assignment(x, etyp, "struct literal")
}
if len(e.Elts) < len(fields) {
check.error(inNode(e, e.Rbrace), _InvalidStructLit, "too few values in struct literal")
check.errorf(inNode(e, e.Rbrace), _InvalidStructLit, "too few values in %s{…}", base)
// ok to continue
}
}

View file

@ -0,0 +1,18 @@
// Copyright 2013 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
type S struct {
f1 int
f2 bool
}
var (
_ = S{0} /* ERROR too few values in S{…} */
_ = struct{ f1, f2 int }{0} /* ERROR too few values in struct{f1 int; f2 int}{…} */
_ = S{0, true, "foo" /* ERROR too many values in S{…} */}
_ = struct{ f1, f2 int }{0, 1, 2 /* ERROR too many values in struct{f1 int; f2 int}{…} */}
)