Debian Codegraph @

gopls/internal/analysis/fillswitch/fillswitch.go

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