Skip to content

Commit 4083a6f

Browse files
committed
go/types: better error for type assertion/switch on type parameter value
This is a port of CL 363439 from types2 to go/types. Change-Id: Ic71871874345e1d0a4a42703e3673aadd11f2bfc Reviewed-on: https://go-review.googlesource.com/c/go/+/364378 Trust: Robert Findley <[email protected]> Run-TryBot: Robert Findley <[email protected]> TryBot-Result: Go Bot <[email protected]> Reviewed-by: Robert Griesemer <[email protected]>
1 parent 1d004fa commit 4083a6f

File tree

3 files changed

+14
-4
lines changed

3 files changed

+14
-4
lines changed

src/go/types/expr.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1432,6 +1432,11 @@ func (check *Checker) exprInternal(x *operand, e ast.Expr, hint Type) exprKind {
14321432
if x.mode == invalid {
14331433
goto Error
14341434
}
1435+
// TODO(gri) we may want to permit type assertions on type parameter values at some point
1436+
if isTypeParam(x.typ) {
1437+
check.invalidOp(x, _InvalidAssert, "cannot use type assertion on type parameter value %s", x)
1438+
goto Error
1439+
}
14351440
xtyp, _ := under(x.typ).(*Interface)
14361441
if xtyp == nil {
14371442
check.invalidOp(x, _InvalidAssert, "%s is not an interface", x)

src/go/types/stmt.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -685,6 +685,11 @@ func (check *Checker) stmt(ctxt stmtContext, s ast.Stmt) {
685685
if x.mode == invalid {
686686
return
687687
}
688+
// TODO(gri) we may want to permit type switches on type parameter values at some point
689+
if isTypeParam(x.typ) {
690+
check.errorf(&x, _InvalidTypeSwitch, "cannot use type switch on type parameter value %s", &x)
691+
return
692+
}
688693
xtyp, _ := under(x.typ).(*Interface)
689694
if xtyp == nil {
690695
check.errorf(&x, _InvalidTypeSwitch, "%s is not an interface", &x)

src/go/types/testdata/check/typeparams.go2

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -481,8 +481,8 @@ func (_ R2[X, Y]) m2(X) Y
481481
// type assertions and type switches over generic types lead to errors for now
482482

483483
func _[T any](x T) {
484-
_ = x /* ERROR not an interface */ .(int)
485-
switch x /* ERROR not an interface */ .(type) {
484+
_ = x /* ERROR cannot use type assertion */ .(int)
485+
switch x /* ERROR cannot use type switch */ .(type) {
486486
}
487487

488488
// work-around
@@ -493,8 +493,8 @@ func _[T any](x T) {
493493
}
494494

495495
func _[T interface{~int}](x T) {
496-
_ = x /* ERROR not an interface */ .(int)
497-
switch x /* ERROR not an interface */ .(type) {
496+
_ = x /* ERROR cannot use type assertion */ .(int)
497+
switch x /* ERROR cannot use type switch */ .(type) {
498498
}
499499

500500
// work-around

0 commit comments

Comments
 (0)