Debian Codegraph @

gopls/internal/analysis/maprange/maprange.go

raw symbols SCIP
1 // Copyright 2025 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 maprange
6
7 import (
8 _ "embed"
9 "fmt"
10 "go/ast"
11 "go/types"
12
13 "golang.org/x/tools/go/analysis"
14 "golang.org/x/tools/go/ast/edge"
15 "golang.org/x/tools/go/ast/inspector"
16 "golang.org/x/tools/internal/analysis/analyzerutil"
17 typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex"
18 "golang.org/x/tools/internal/astutil"
19 "golang.org/x/tools/internal/typesinternal/typeindex"
20 "golang.org/x/tools/internal/versions"
21 )
22
23 //go:embed doc.go
24 var doc string
25
26 var Analyzer = &analysis.Analyzer{
27 Name: "maprange",
28 Doc: analyzerutil.MustExtractDoc(doc, "maprange"),
29 URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/maprange",
30 Requires: []*analysis.Analyzer{typeindexanalyzer.Analyzer},
31 Run: run,
32 }
33
34 // This is a variable because the package name is different in Google's code base.
35 var xmaps = "golang.org/x/exp/maps"
36
37 func run(pass *analysis.Pass) (any, error) {
38 switch pass.Pkg.Path() {
39 case "maps", xmaps:
40 // These packages know how to use their own APIs.
41 return nil, nil
42 }
43 var (
44 index = pass.ResultOf[typeindexanalyzer.Analyzer].(*typeindex.Index)
45 mapsKeys = index.Object("maps", "Keys")
46 mapsValues = index.Object("maps", "Values")
47 xmapsKeys = index.Object(xmaps, "Keys")
48 xmapsValues = index.Object(xmaps, "Values")
49 )
50 for _, callee := range []types.Object{mapsKeys, mapsValues, xmapsKeys, xmapsValues} {
51 for curCall := range index.Calls(callee) {
52 if curCall.ParentEdgeKind() == edge.RangeStmt_X {
53 analyzeRangeStmt(pass, callee, curCall)
54 }
55 }
56 }
57 return nil, nil
58 }
59
60 // analyzeRangeStmt analyzes range statements iterating over calls to maps.Keys
61 // or maps.Values (from the standard library "maps" or "golang.org/x/exp/maps").
62 //
63 // It reports a diagnostic with a suggested fix to simplify the loop by removing
64 // the unnecessary function call and adjusting range variables, if possible.
65 // For certain patterns involving x/exp/maps.Keys before Go 1.22, it reports
66 // a diagnostic about potential incorrect usage without a suggested fix.
67 // No diagnostic is reported if the range statement doesn't require changes.
68 func analyzeRangeStmt(pass *analysis.Pass, callee types.Object, curCall inspector.Cursor) {
69 var (
70 call = curCall.Node().(*ast.CallExpr)
71 rangeStmt = curCall.Parent().Node().(*ast.RangeStmt)
72 pkg = callee.Pkg().Path()
73 fn = callee.Name()
74 )
75 var edits []analysis.TextEdit
76
77 // Check if the call to maps.Keys or maps.Values can be removed/replaced.
78 // Example:
79 // for range maps.Keys(m)
80 // ^^^^^^^^^ removeCall
81 // for i, _ := range maps.Keys(m)
82 // ^^^^^^^^^ replace with `len`
83 //
84 // If we have: for i, k := range maps.Keys(m) (only possible using x/exp/maps)
85 // or: for i, v = range maps.Values(m)
86 // do not remove the call.
87 removeCall := !isSet(rangeStmt.Key) || !isSet(rangeStmt.Value)
88 replace := ""
89 if pkg == xmaps && isSet(rangeStmt.Key) && rangeStmt.Value == nil {
90 // If we have: for i := range maps.Keys(m) (using x/exp/maps),
91 // Replace with: for i := range len(m)
92 // (This requires Go 1.22.)
93 replace = "len"
94 if !analyzerutil.FileUsesGoVersion(pass, astutil.EnclosingFile(curCall), versions.Go1_22) {
95 pass.Report(analysis.Diagnostic{
96 Pos: call.Pos(),
97 End: call.End(),
98 Message: fmt.Sprintf("likely incorrect use of %s.%s (returns a slice)", pkg, fn),
99 })
100 return
101 }
102 }
103 if removeCall {
104 edits = append(edits, analysis.TextEdit{
105 Pos: call.Fun.Pos(),
106 End: call.Fun.End(),
107 NewText: []byte(replace)})
108 }
109 // Check if the key of the range statement should be removed.
110 // Example:
111 // for _, k := range maps.Keys(m)
112 // ^^^ removeKey ^^^^^^^^^ removeCall
113 removeKey := pkg == xmaps && fn == "Keys" && !isSet(rangeStmt.Key) && isSet(rangeStmt.Value)
114 if removeKey {
115 edits = append(edits, analysis.TextEdit{
116 Pos: rangeStmt.Key.Pos(),
117 End: rangeStmt.Value.Pos(),
118 })
119 }
120 // Check if a key should be inserted to the range statement.
121 // Example:
122 // for _, v := range maps.Values(m)
123 // ^^^ addKey ^^^^^^^^^^^ removeCall
124 addKey := pkg == "maps" && fn == "Values" && isSet(rangeStmt.Key)
125 if addKey {
126 edits = append(edits, analysis.TextEdit{
127 Pos: rangeStmt.Key.Pos(),
128 End: rangeStmt.Key.Pos(),
129 NewText: []byte("_, "),
130 })
131 }
132
133 if len(edits) > 0 {
134 pass.Report(analysis.Diagnostic{
135 Pos: call.Pos(),
136 End: call.End(),
137 Message: fmt.Sprintf("unnecessary and inefficient call of %s.%s", pkg, fn),
138 SuggestedFixes: []analysis.SuggestedFix{{
139 Message: fmt.Sprintf("Remove unnecessary call to %s.%s", pkg, fn),
140 TextEdits: edits,
141 }},
142 })
143 }
144 }
145
146 // isSet reports whether an ast.Expr is a non-nil expression that is not the blank identifier.
147 func isSet(expr ast.Expr) bool {
148 ident, ok := expr.(*ast.Ident)
149 return expr != nil && (!ok || ident.Name != "_")
150 }