From e601c079082658399445c2698f7e5cb60d23db29 Mon Sep 17 00:00:00 2001 From: Matthew Dempsky Date: Tue, 13 Mar 2018 14:26:45 -0700 Subject: [PATCH] cmd/compile: reject type switch with guarded declaration and no cases Fixes #23116. Change-Id: I5db5c5c39bbb50148ffa18c9393b045f255f80a3 Reviewed-on: https://go-review.googlesource.com/100459 Run-TryBot: Matthew Dempsky TryBot-Result: Gobot Gobot Reviewed-by: Robert Griesemer --- src/cmd/compile/internal/gc/swt.go | 6 ++++++ test/fixedbugs/issue23116.go | 15 +++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 test/fixedbugs/issue23116.go diff --git a/src/cmd/compile/internal/gc/swt.go b/src/cmd/compile/internal/gc/swt.go index c9fb67e916..404a88444a 100644 --- a/src/cmd/compile/internal/gc/swt.go +++ b/src/cmd/compile/internal/gc/swt.go @@ -70,6 +70,12 @@ func typecheckswitch(n *Node) { if t != nil && !t.IsInterface() { yyerrorl(n.Pos, "cannot type switch on non-interface value %L", n.Left.Right) } + if v := n.Left.Left; v != nil && !isblank(v) && n.List.Len() == 0 { + // We don't actually declare the type switch's guarded + // declaration itself. So if there are no cases, we + // won't notice that it went unused. + yyerrorl(v.Pos, "%v declared and not used", v.Sym) + } } else { // expression switch top = Erv diff --git a/test/fixedbugs/issue23116.go b/test/fixedbugs/issue23116.go new file mode 100644 index 0000000000..1737fee2c8 --- /dev/null +++ b/test/fixedbugs/issue23116.go @@ -0,0 +1,15 @@ +// errorcheck + +// Copyright 2018 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 f(x interface{}) { + switch x.(type) { + } + + switch t := x.(type) { // ERROR "declared and not used" + } +} -- 2.50.0