1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
|
// Copyright 2024 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 fillswitch
import (
"bytes"
"fmt"
"go/ast"
"go/token"
"go/types"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/internal/typesinternal"
)
// Diagnose computes diagnostics for switch statements with missing cases
// overlapping with the provided start and end position of file f.
//
// If either start or end is invalid, the entire file is inspected.
func Diagnose(f *ast.File, start, end token.Pos, pkg *types.Package, info *types.Info) []analysis.Diagnostic {
var diags []analysis.Diagnostic
ast.Inspect(f, func(n ast.Node) bool {
if n == nil {
return true // pop
}
if start.IsValid() && n.End() < start ||
end.IsValid() && n.Pos() > end {
return false // skip non-overlapping subtree
}
var fix *analysis.SuggestedFix
switch n := n.(type) {
case *ast.SwitchStmt:
fix = suggestedFixSwitch(n, pkg, info)
case *ast.TypeSwitchStmt:
fix = suggestedFixTypeSwitch(n, pkg, info)
}
if fix != nil {
diags = append(diags, analysis.Diagnostic{
Message: fix.Message,
Pos: n.Pos(),
End: n.Pos() + token.Pos(len("switch")),
SuggestedFixes: []analysis.SuggestedFix{*fix},
})
}
return true
})
return diags
}
func suggestedFixTypeSwitch(stmt *ast.TypeSwitchStmt, pkg *types.Package, info *types.Info) *analysis.SuggestedFix {
if hasDefaultCase(stmt.Body) {
return nil
}
namedType := namedTypeFromTypeSwitch(stmt, info)
if namedType == nil {
return nil
}
existingCases := caseTypes(stmt.Body, info)
// Gather accessible package-level concrete types
// that implement the switch interface type.
scope := namedType.Obj().Pkg().Scope()
var buf bytes.Buffer
for _, name := range scope.Names() {
obj := scope.Lookup(name)
if tname, ok := obj.(*types.TypeName); !ok || tname.IsAlias() {
continue // not a defined type
}
if types.IsInterface(obj.Type()) {
continue
}
samePkg := obj.Pkg() == pkg
if !samePkg && !obj.Exported() {
continue // inaccessible
}
var key caseType
if types.AssignableTo(obj.Type(), namedType.Obj().Type()) {
key.named = obj.Type().(*types.Named)
} else if ptr := types.NewPointer(obj.Type()); types.AssignableTo(ptr, namedType.Obj().Type()) {
key.named = obj.Type().(*types.Named)
key.ptr = true
}
if key.named != nil {
if existingCases[key] {
continue
}
if buf.Len() > 0 {
buf.WriteString("\t")
}
buf.WriteString("case ")
if key.ptr {
buf.WriteByte('*')
}
if p := key.named.Obj().Pkg(); p != pkg {
// TODO: use the correct package name when the import is renamed
buf.WriteString(p.Name())
buf.WriteByte('.')
}
buf.WriteString(key.named.Obj().Name())
buf.WriteString(":\n")
}
}
if buf.Len() == 0 {
return nil
}
switch assign := stmt.Assign.(type) {
case *ast.AssignStmt:
addDefaultCase(&buf, namedType, assign.Lhs[0])
case *ast.ExprStmt:
if assert, ok := assign.X.(*ast.TypeAssertExpr); ok {
addDefaultCase(&buf, namedType, assert.X)
}
}
return &analysis.SuggestedFix{
Message: "Add cases for " + types.TypeString(namedType, typesinternal.NameRelativeTo(pkg)),
TextEdits: []analysis.TextEdit{{
Pos: stmt.End() - token.Pos(len("}")),
End: stmt.End() - token.Pos(len("}")),
NewText: buf.Bytes(),
}},
}
}
func suggestedFixSwitch(stmt *ast.SwitchStmt, pkg *types.Package, info *types.Info) *analysis.SuggestedFix {
if hasDefaultCase(stmt.Body) {
return nil
}
namedType, ok := info.TypeOf(stmt.Tag).(*types.Named)
if !ok {
return nil
}
existingCases := caseConsts(stmt.Body, info)
// Gather accessible named constants of the same type as the switch value.
scope := namedType.Obj().Pkg().Scope()
var buf bytes.Buffer
for _, name := range scope.Names() {
obj := scope.Lookup(name)
if c, ok := obj.(*types.Const); ok &&
(obj.Pkg() == pkg || obj.Exported()) && // accessible
types.Identical(obj.Type(), namedType.Obj().Type()) &&
!existingCases[c] {
if buf.Len() > 0 {
buf.WriteString("\t")
}
buf.WriteString("case ")
if c.Pkg() != pkg {
buf.WriteString(c.Pkg().Name())
buf.WriteByte('.')
}
buf.WriteString(c.Name())
buf.WriteString(":\n")
}
}
if buf.Len() == 0 {
return nil
}
addDefaultCase(&buf, namedType, stmt.Tag)
return &analysis.SuggestedFix{
Message: "Add cases for " + types.TypeString(namedType, typesinternal.NameRelativeTo(pkg)),
TextEdits: []analysis.TextEdit{{
Pos: stmt.End() - token.Pos(len("}")),
End: stmt.End() - token.Pos(len("}")),
NewText: buf.Bytes(),
}},
}
}
func addDefaultCase(buf *bytes.Buffer, named *types.Named, expr ast.Expr) {
var dottedBuf bytes.Buffer
// writeDotted emits a dotted path a.b.c.
var writeDotted func(e ast.Expr) bool
writeDotted = func(e ast.Expr) bool {
switch e := e.(type) {
case *ast.SelectorExpr:
if !writeDotted(e.X) {
return false
}
dottedBuf.WriteByte('.')
dottedBuf.WriteString(e.Sel.Name)
return true
case *ast.Ident:
dottedBuf.WriteString(e.Name)
return true
}
return false
}
buf.WriteString("\tdefault:\n")
typeName := fmt.Sprintf("%s.%s", named.Obj().Pkg().Name(), named.Obj().Name())
if writeDotted(expr) {
// Switch tag expression is a dotted path.
// It is safe to re-evaluate it in the default case.
format := fmt.Sprintf("unexpected %s: %%#v", typeName)
fmt.Fprintf(buf, "\t\tpanic(fmt.Sprintf(%q, %s))\n\t", format, dottedBuf.String())
} else {
// Emit simpler message, without re-evaluating tag expression.
fmt.Fprintf(buf, "\t\tpanic(%q)\n\t", "unexpected "+typeName)
}
}
func namedTypeFromTypeSwitch(stmt *ast.TypeSwitchStmt, info *types.Info) *types.Named {
switch assign := stmt.Assign.(type) {
case *ast.ExprStmt:
if typ, ok := assign.X.(*ast.TypeAssertExpr); ok {
if named, ok := info.TypeOf(typ.X).(*types.Named); ok {
return named
}
}
case *ast.AssignStmt:
if typ, ok := assign.Rhs[0].(*ast.TypeAssertExpr); ok {
if named, ok := info.TypeOf(typ.X).(*types.Named); ok {
return named
}
}
}
return nil
}
func hasDefaultCase(body *ast.BlockStmt) bool {
for _, clause := range body.List {
if len(clause.(*ast.CaseClause).List) == 0 {
return true
}
}
return false
}
func caseConsts(body *ast.BlockStmt, info *types.Info) map[*types.Const]bool {
out := map[*types.Const]bool{}
for _, stmt := range body.List {
for _, e := range stmt.(*ast.CaseClause).List {
if info.Types[e].Value == nil {
continue // not a constant
}
if sel, ok := e.(*ast.SelectorExpr); ok {
e = sel.Sel // replace pkg.C with C
}
if e, ok := e.(*ast.Ident); ok {
if c, ok := info.Uses[e].(*types.Const); ok {
out[c] = true
}
}
}
}
return out
}
type caseType struct {
named *types.Named
ptr bool
}
func caseTypes(body *ast.BlockStmt, info *types.Info) map[caseType]bool {
out := map[caseType]bool{}
for _, stmt := range body.List {
for _, e := range stmt.(*ast.CaseClause).List {
if tv, ok := info.Types[e]; ok && tv.IsType() {
t := tv.Type
ptr := false
if p, ok := t.(*types.Pointer); ok {
t = p.Elem()
ptr = true
}
if named, ok := t.(*types.Named); ok {
out[caseType{named, ptr}] = true
}
}
}
}
return out
}
|