go/types, types2: don't crash if comp. literal element type has no core type

Instead, report a suitable error.

Fixes #51335.

Change-Id: Ifce90cb7487b1e99c6b4221c0d43bacc0c39dca8
Reviewed-on: https://go-review.googlesource.com/c/go/+/387676
Trust: Robert Griesemer <gri@golang.org>
Run-TryBot: Robert Griesemer <gri@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Robert Findley <rfindley@google.com>
This commit is contained in:
Robert Griesemer 2022-02-23 14:26:07 -08:00
parent e94f7df957
commit 78e99761fc
4 changed files with 40 additions and 0 deletions

View file

@ -1360,6 +1360,10 @@ func (check *Checker) exprInternal(x *operand, e syntax.Expr, hint Type) exprKin
// no composite literal type present - use hint (element type of enclosing type)
typ = hint
base, _ = deref(coreType(typ)) // *T implies &T{}
if base == nil {
check.errorf(e, "invalid composite literal element type %s: no core type", typ)
goto Error
}
default:
// TODO(gri) provide better error messages depending on context

View file

@ -0,0 +1,16 @@
// 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
type S1 struct{}
type S2 struct{}
func _[P *S1|*S2]() {
_= []P{{ /* ERROR invalid composite literal element type P: no core type */ }}
}
func _[P *S1|S1]() {
_= []P{{ /* ERROR invalid composite literal element type P: no core type */ }}
}

View file

@ -1339,6 +1339,10 @@ func (check *Checker) exprInternal(x *operand, e ast.Expr, hint Type) exprKind {
// no composite literal type present - use hint (element type of enclosing type)
typ = hint
base, _ = deref(coreType(typ)) // *T implies &T{}
if base == nil {
check.errorf(e, _InvalidLit, "invalid composite literal element type %s: no core type", typ)
goto Error
}
default:
// TODO(gri) provide better error messages depending on context

View file

@ -0,0 +1,16 @@
// 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
type S1 struct{}
type S2 struct{}
func _[P *S1|*S2]() {
_= []P{{ /* ERROR invalid composite literal element type P: no core type */ }}
}
func _[P *S1|S1]() {
_= []P{{ /* ERROR invalid composite literal element type P: no core type */ }}
}