Debian Codegraph @

go/analysis/passes/modernize/stringscut.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 modernizescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/
6
7 import (
8 "fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/"
9 "go/astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/"
10 "go/constantscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/"
11 "go/tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/"
12 "go/typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/"
13 "iterscip-go gomod github.com/golang/go/src go1.25.0 iter/"
14 "strconvscip-go gomod github.com/golang/go/src go1.25.0 strconv/"
15
16 "golang.org/x/tools/go/analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/"
17 "golang.org/x/tools/go/analysis/passes/inspectscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/inspect`/"
18 "golang.org/x/tools/go/ast/edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/"
19 "golang.org/x/tools/go/ast/inspectorscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/"
20 "golang.org/x/tools/go/types/typeutilscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/types/typeutil`/"
21 "golang.org/x/tools/internal/analysis/analyzerutilscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/analysis/analyzerutil`/"
22 typeindexanalyzerscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/analysis/typeindex`/ "golang.org/x/tools/internal/analysis/typeindexscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/analysis/typeindex`/"
23 "golang.org/x/tools/internal/astutilscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/astutil`/"
24 "golang.org/x/tools/internal/moreitersscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/moreiters`/"
25 "golang.org/x/tools/internal/typesinternalscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal`/"
26 "golang.org/x/tools/internal/typesinternal/typeindexscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/"
27 "golang.org/x/tools/internal/versionsscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/versions`/"
28 )
29
30 var StringsCutAnalyzerscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/StringsCutAnalyzer. = &analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.Analyzerscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Analyzer#{
31 Namescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Analyzer#Name.: "stringscut",
32 Docscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Analyzer#Doc.: analyzerutilscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/analysis/analyzerutil`/.MustExtractDocscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/analysis/analyzerutil`/MustExtractDoc().(docscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/doc., "stringscut"),
33 Requiresscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Analyzer#Requires.: []*analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.Analyzerscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Analyzer#{
34 inspectscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/inspect`/.Analyzerscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/inspect`/Analyzer.,
35 typeindexanalyzerscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/analysis/typeindex`/.Analyzerscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/analysis/typeindex`/Analyzer.,
36 },
37 Runscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Analyzer#Run.: stringscutscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/stringscut().,
38 URLscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Analyzer#URL.: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#stringscut",
39 }
40
41 // stringscut offers a fix to replace an occurrence of strings.Index{,Byte} with
42 // strings.{Cut,Contains}, and similar fixes for functions in the bytes package.
43 // Consider some candidate for replacement i := strings.Index(s, substr).
44 // The following must hold for a replacement to occur:
45 //
46 // 1. All instances of i and s must be in one of these forms.
47 //
48 // Binary expressions must be inequalities equivalent to
49 // "Index failed" (e.g. i < 0) or "Index succeeded" (i >= 0),
50 // or identities such as these (and their negations):
51 //
52 // 0 > i (flips left and right)
53 // i <= -1, -1 >= i (replace strict inequality by non-strict)
54 // i == -1, -1 == i (Index() guarantees i < 0 => i == -1)
55 //
56 // Slice expressions:
57 // a: s[:i], s[0:i]
58 // b: s[i+len(substr):], s[len(substr) + i:], s[i + const], s[k + i] (where k = len(substr))
59 //
60 // 2. There can be no uses of s, substr, or i where they are
61 // potentially modified (i.e. in assignments, or function calls with unknown side
62 // effects).
63 //
64 // Then, the replacement involves the following substitutions:
65 //
66 // 1. Replace "i := strings.Index(s, substr)" with "before, after, ok := strings.Cut(s, substr)"
67 //
68 // 2. Replace instances of binary expressions (a) with !ok and binary expressions (b) with ok.
69 //
70 // 3. Replace slice expressions (a) with "before" and slice expressions (b) with after.
71 //
72 // 4. The assignments to before, after, and ok may use the blank identifier "_" if they are unused.
73 //
74 // For example:
75 //
76 // i := strings.Index(s, substr)
77 // if i >= 0 {
78 // use(s[:i], s[i+len(substr):])
79 // }
80 //
81 // Would become:
82 //
83 // before, after, ok := strings.Cut(s, substr)
84 // if ok {
85 // use(before, after)
86 // }
87 //
88 // If the condition involving `i` is equivalent to i >= 0, then we replace it with
89 // `if ok`.
90 // If the condition is negated (e.g. equivalent to `i < 0`), we use `if !ok` instead.
91 // If the slices of `s` match `s[:i]` or `s[i+len(substr):]` or their variants listed above,
92 // then we replace them with before and after.
93 //
94 // When the index `i` is used only to check for the presence of the substring or byte slice,
95 // the suggested fix uses Contains() instead of Cut.
96 //
97 // For example:
98 //
99 // i := strings.Index(s, substr)
100 // if i >= 0 {
101 // return
102 // }
103 //
104 // Would become:
105 //
106 // found := strings.Contains(s, substr)
107 // if found {
108 // return
109 // }
110 func stringscutscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/stringscut().(pass *analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.Passscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Pass#) (any, error) {
111 var (
112 index = pass.ResultOfscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Pass#ResultOf.[typeindexanalyzerscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/analysis/typeindex`/.Analyzerscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/analysis/typeindex`/Analyzer.].(*typeindexscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/.Indexscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/Index#)
113 info = pass.TypesInfoscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Pass#TypesInfo.
114
115 stringsIndex = index.Objectscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/Index#Object().("strings", "Index")
116 stringsIndexByte = index.Objectscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/Index#Object().("strings", "IndexByte")
117 bytesIndex = index.Objectscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/Index#Object().("bytes", "Index")
118 bytesIndexByte = index.Objectscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/Index#Object().("bytes", "IndexByte")
119 )
120
121 stringsplitCutscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/stringsplitCut().(pass, index)
122
123 scopeFixCount := make(map[*typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Scopescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Scope#]int) // the number of times we have offered a fix within a given scope in the current pass
124
125 for _, obj := range []typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Objectscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#{
126 stringsIndex,
127 stringsIndexByte,
128 bytesIndex,
129 bytesIndexByte,
130 } {
131 // (obj may be nil)
132 nextcall:
133 for curCall := range index.Callsscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/Index#Calls().(obj) {
134 // Check file version.
135 if !analyzerutilscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/analysis/analyzerutil`/.FileUsesGoVersionscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/analysis/analyzerutil`/FileUsesGoVersion().(pass, astutilscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/astutil`/.EnclosingFilescip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/astutil`/EnclosingFile().(curCall), versionsscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/versions`/.Go1_18scip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/versions`/Go1_18.) {
136 continue // strings.Index not available in this file
137 }
138 indexCall := curCall.Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().().(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.CallExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#) // the call to strings.Index, etc.
139 obj := typeutilscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/types/typeutil`/.Calleescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/types/typeutil`/Callee().(info, indexCall)
140 if obj == nil {
141 continue
142 }
143
144 var iIdent *astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Identscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident# // defining identifier of i var
145 switch ek, idx := curCall.ParentEdgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#ParentEdge().(); ek {
146 case edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.ValueSpec_Valuesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/ValueSpec_Values.:
147 // Have: var i = strings.Index(...)
148 // If the call occurs in a multi-value declaration or assignment, don't suggest a fix because it would produce invalid code (See golang/go#78643).
149 spec := curCall.Parentscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Parent().().Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().().(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.ValueSpecscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/ValueSpec#)
150 if len(spec.Namesscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/ValueSpec#Names.) != 1 {
151 continue
152 }
153 curName := curCall.Parentscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Parent().().ChildAtscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#ChildAt().(edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.ValueSpec_Namesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/ValueSpec_Names., idx)
154 iIdent = curName.Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().().(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Identscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#)
155 case edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.AssignStmt_Rhsscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/AssignStmt_Rhs.:
156 // Have: i := strings.Index(...)
157 // (Must be i's definition.)
158 assign := curCall.Parentscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Parent().().Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().().(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.AssignStmtscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/AssignStmt#)
159 if len(assign.Lhsscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/AssignStmt#Lhs.) != 1 {
160 continue
161 }
162 curLhs := curCall.Parentscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Parent().().ChildAtscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#ChildAt().(edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.AssignStmt_Lhsscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/AssignStmt_Lhs., idx)
163 iIdent, _ = curLhs.Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().().(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Identscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#) // may be nil
164 }
165
166 if iIdent == nil {
167 continue
168 }
169 // Inv: iIdent is i's definition. The following would be skipped: 'var i int; i = strings.Index(...)'
170 // Get uses of i.
171 iObj := info.ObjectOfscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#ObjectOf().(iIdent)
172 if iObj == nil {
173 continue
174 }
175
176 var (
177 s = indexCall.Argsscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Args.[0]
178 substr = indexCall.Argsscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Args.[1]
179 )
180
181 // Check that there are no statements that alter the value of s
182 // or substr after the call to Index().
183 if !indexArgValidscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/indexArgValid().(info, index, s, indexCall.Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Pos().()) ||
184 !indexArgValidscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/indexArgValid().(info, index, substr, indexCall.Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Pos().()) {
185 continue nextcall
186 }
187
188 // Next, examine all uses of i. If the only uses are of the
189 // forms mentioned above (e.g. i < 0, i >= 0, s[:i] and s[i +
190 // len(substr)]), then we can replace the call to Index()
191 // with a call to Cut() and use the returned ok, before,
192 // and after variables accordingly.
193 negative, nonnegative, beforeSlice, afterSlice := checkIdxUsesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/checkIdxUses().(pass.TypesInfoscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Pass#TypesInfo., index.Usesscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/Index#Uses().(iObj), s, substr, iObj)
194
195 // Either there are no uses of before, after, or ok, or some use
196 // of i does not match our criteria - don't suggest a fix.
197 if negative == nil && nonnegative == nil && beforeSlice == nil && afterSlice == nil {
198 continue
199 }
200
201 // If the only uses are ok and !ok, don't suggest a Cut() fix - these should be using Contains()
202 isContains := (len(negative) > 0 || len(nonnegative) > 0) && len(beforeSlice) == 0 && len(afterSlice) == 0
203
204 enclosingBlock, ok := moreitersscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/moreiters`/.Firstscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/moreiters`/First().(curCall.Enclosingscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Enclosing().((*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.BlockStmtscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BlockStmt#)(nil)))
205 if !ok {
206 continue
207 }
208 scope := iObj.Parentscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#Parent().()
209 // Generate fresh names for ok, before, after, found, but only if
210 // they are defined by the end of the enclosing block and used
211 // within the enclosing block after the Index call. We need a Cursor
212 // for the end of the enclosing block, but we can't just find the
213 // Cursor at scope.End() because it corresponds to the entire
214 // enclosingBlock. Instead, get the last child of the enclosing
215 // block.
216 lastStmtCur, _ := enclosingBlock.LastChildscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#LastChild().()
217 lastStmt := lastStmtCur.Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().()
218
219 fresh := func(preferred string) string {
220 return freshNamescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/freshName().(info, index, scope, lastStmt.Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#End().(), lastStmtCur, enclosingBlock, iIdent.Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#Pos().(), preferred)
221 }
222
223 var okVarName, beforeVarName, afterVarName, foundVarName string
224 if isContains {
225 foundVarName = fresh("found")
226 } else {
227 okVarName = fresh("ok")
228 beforeVarName = fresh("before")
229 afterVarName = fresh("after")
230 }
231
232 // If we are already suggesting a fix within the index's scope, we
233 // must get fresh names for before, after and ok.
234 // This is a specific symptom of the general problem that analyzers
235 // can generate conflicting fixes.
236 if scopeFixCount[scope] > 0 {
237 suffix := scopeFixCount[scope] - 1 // start at 0
238 if isContains {
239 foundVarName = fresh(fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Sprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Sprintf().("%s%d", foundVarName, suffix))
240 } else {
241 okVarName = fresh(fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Sprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Sprintf().("%s%d", okVarName, suffix))
242 beforeVarName = fresh(fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Sprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Sprintf().("%s%d", beforeVarName, suffix))
243 afterVarName = fresh(fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Sprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Sprintf().("%s%d", afterVarName, suffix))
244 }
245 }
246
247 // If there will be no uses of ok, before, or after, use the
248 // blank identifier instead.
249 if len(negative) == 0 && len(nonnegative) == 0 {
250 okVarName = "_"
251 }
252 if len(beforeSlice) == 0 {
253 beforeVarName = "_"
254 }
255 if len(afterSlice) == 0 {
256 afterVarName = "_"
257 }
258
259 var edits []analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.TextEditscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#
260 replace := func(exprs []astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Exprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Expr#, new string) {
261 for _, expr := range exprs {
262 edits = append(edits, analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.TextEditscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#{
263 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#Pos.: expr.Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#Pos().(),
264 Endscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#End.: expr.Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#End().(),
265 NewTextscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#NewText.: []byte(new),
266 })
267 }
268 }
269 // Get the ident for the call to strings.Index, which could just be
270 // "Index" if the strings package is dot imported.
271 indexCallId := typesinternalscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal`/.UsedIdentscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal`/UsedIdent().(info, indexCall.Funscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Fun.)
272 replacedFunc := "Cut"
273 if isContains {
274 replacedFunc = "Contains"
275 replace(negative, "!"+foundVarName) // idx < 0 -> !found
276 replace(nonnegative, foundVarName) // idx > -1 -> found
277
278 // Replace the assignment with found, and replace the call to
279 // Index or IndexByte with a call to Contains.
280 // i := strings.Index (...)
281 // ----- --------
282 // found := strings.Contains(...)
283 edits = append(edits, analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.TextEditscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#{
284 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#Pos.: iIdent.Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#Pos().(),
285 Endscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#End.: iIdent.Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#End().(),
286 NewTextscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#NewText.: []byte(foundVarName),
287 }, analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.TextEditscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#{
288 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#Pos.: indexCallId.Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#Pos().(),
289 Endscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#End.: indexCallId.Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#End().(),
290 NewTextscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#NewText.: []byte("Contains"),
291 })
292 } else {
293 replace(negative, "!"+okVarName) // idx < 0 -> !ok
294 replace(nonnegative, okVarName) // idx > -1 -> ok
295 replace(beforeSlice, beforeVarName) // s[:idx] -> before
296 replace(afterSlice, afterVarName) // s[idx+k:] -> after
297
298 // Replace the assignment with before, after, ok, and replace
299 // the call to Index or IndexByte with a call to Cut.
300 // i := strings.Index(...)
301 // ----------------- -----
302 // before, after, ok := strings.Cut (...)
303 edits = append(edits, analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.TextEditscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#{
304 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#Pos.: iIdent.Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#Pos().(),
305 Endscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#End.: iIdent.Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#End().(),
306 NewTextscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#NewText.: fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Appendfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Appendf().(nil, "%s, %s, %s", beforeVarName, afterVarName, okVarName),
307 }, analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.TextEditscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#{
308 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#Pos.: indexCallId.Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#Pos().(),
309 Endscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#End.: indexCallId.Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#End().(),
310 NewTextscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#NewText.: []byte("Cut"),
311 })
312 }
313
314 // Calls to IndexByte have a byte as their second arg, which
315 // must be converted to a string or []byte to be a valid arg for Cut/Contains.
316 if obj.Namescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#Name().() == "IndexByte" {
317 switch obj.Pkgscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#Pkg().().Namescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Package#Name().() {
318 case "strings":
319 searchByteVal := info.Typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#Types.[substr].Valuescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/TypeAndValue#Value.
320 if searchByteVal == nil {
321 // substr is a variable, e.g. substr := byte('b')
322 // use string(substr)
323 edits = append(edits, []analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.TextEditscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#{
324 {
325 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#Pos.: substr.Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#Pos().(),
326 NewTextscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#NewText.: []byte("string("),
327 },
328 {
329 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#Pos.: substr.Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#End().(),
330 NewTextscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#NewText.: []byte(")"),
331 },
332 }...)
333 } else {
334 // substr is a byte constant
335 val, _ := constantscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/.Int64Valscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/Int64Val().(searchByteVal) // inv: must be a valid byte
336 // strings.Cut/Contains requires a string, so convert byte literal to string literal; e.g. 'a' -> "a", 55 -> "7"
337 edits = append(edits, analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.TextEditscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#{
338 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#Pos.: substr.Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#Pos().(),
339 Endscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#End.: substr.Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#End().(),
340 NewTextscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#NewText.: strconvscip-go gomod github.com/golang/go/src go1.25.0 strconv/.AppendQuotescip-go gomod github.com/golang/go/src go1.25.0 strconv/AppendQuote().(nil, string(byte(val))),
341 })
342 }
343 case "bytes":
344 // bytes.Cut/Contains requires a []byte, so wrap substr in a []byte{}
345 edits = append(edits, []analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.TextEditscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#{
346 {
347 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#Pos.: substr.Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#Pos().(),
348 NewTextscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#NewText.: []byte("[]byte{"),
349 },
350 {
351 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#Pos.: substr.Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#End().(),
352 NewTextscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#NewText.: []byte("}"),
353 },
354 }...)
355 }
356 }
357 scopeFixCount[scope]++
358 pass.Reportscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Pass#Report.(analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.Diagnosticscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Diagnostic#{
359 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Diagnostic#Pos.: indexCall.Funscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Fun..Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#Pos().(),
360 Endscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Diagnostic#End.: indexCall.Funscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Fun..Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#End().(),
361 Messagescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Diagnostic#Message.: fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Sprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Sprintf().("%s.%s can be simplified using %s.%s",
362 obj.Pkgscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#Pkg().().Namescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Package#Name().(), obj.Namescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#Name().(), obj.Pkgscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#Pkg().().Namescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Package#Name().(), replacedFunc),
363 Categoryscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Diagnostic#Category.: "stringscut",
364 SuggestedFixesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Diagnostic#SuggestedFixes.: []analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.SuggestedFixscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/SuggestedFix#{{
365 Messagescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/SuggestedFix#Message.: fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Sprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Sprintf().("Simplify %s.%s call using %s.%s", obj.Pkgscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#Pkg().().Namescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Package#Name().(), obj.Namescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#Name().(), obj.Pkgscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#Pkg().().Namescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Package#Name().(), replacedFunc),
366 TextEditsscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/SuggestedFix#TextEdits.: edits,
367 }},
368 })
369 }
370 }
371
372 return nil, nil
373 }
374
375 // stringsplitCut reports patterns where strings.Split or strings.SplitN with
376 // n=2 is immediately indexed at [0], which can be simplified to strings.Cut,
377 // when sep is a non-empty string constant. The transformation is
378 // semantics-preserving only for non-empty sep: strings.Split(s, "")[0]
379 // returns the first character of s, but strings.Cut(s, "").before is "".
380 // For variable sep the value is unknown at analysis time, so we conservatively
381 // skip those cases too.
382 //
383 // For example:
384 //
385 // x := strings.SplitN(s, ",", 2)[0]
386 // ------ --
387 // x, _, _ := strings.Cut(s, ",")
388 //
389 // Requires Go 1.18 (when strings.Cut was added).
390 func stringsplitCutscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/stringsplitCut().(pass *analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.Passscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Pass#, index *typeindexscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/.Indexscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/Index#) {
391 info := pass.TypesInfoscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Pass#TypesInfo.
392
393 stringsSplit := index.Objectscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/Index#Object().("strings", "Split")
394 stringsSplitN := index.Objectscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/Index#Object().("strings", "SplitN")
395
396 for _, obj := range []typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Objectscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#{stringsSplit, stringsSplitN} {
397 for curCall := range index.Callsscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/Index#Calls().(obj) {
398 callExpr := curCall.Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().().(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.CallExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#)
399
400 // For SplitN, the third argument must be the integer constant 2.
401 if obj.Namescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#Name().() == "SplitN" && !isIntLiteralscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isIntLiteral().(info, callExpr.Argsscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Args.[2], 2) {
402 continue
403 }
404
405 // Sep must be a non-empty constant string.
406 // strings.Split(s, "")[0] returns the first character of s, but
407 // strings.Cut(s, "").before is "", so the semantics differ for
408 // an empty sep. For a variable sep we cannot rule out "" at
409 // analysis time, so we conservatively skip those cases too.
410 sepTV := info.Typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#Types.[callExpr.Argsscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Args.[1]]
411 if sepTV.Valuescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/TypeAndValue#Value. == nil || constantscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/.StringValscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/StringVal().(sepTV.Valuescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/TypeAndValue#Value.) == "" {
412 continue
413 }
414
415 // The call must be the X of an IndexExpr.
416 if curCall.ParentEdgeKindscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#ParentEdgeKind().() != edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.IndexExpr_Xscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/IndexExpr_X. {
417 continue
418 }
419 parent := curCall.Parentscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Parent().()
420 indexExpr := parent.Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().().(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.IndexExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/IndexExpr#)
421
422 // The index must be the integer constant 0.
423 if !isZeroIntConstscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isZeroIntConst().(info, indexExpr.Indexscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/IndexExpr#Index.) {
424 continue
425 }
426
427 // The IndexExpr must be the sole RHS of an assignment statement.
428 if parent.ParentEdgeKindscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#ParentEdgeKind().() != edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.AssignStmt_Rhsscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/AssignStmt_Rhs. {
429 continue
430 }
431 assign := parent.Parentscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Parent().().Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().().(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.AssignStmtscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/AssignStmt#)
432 if assign.Tokscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/AssignStmt#Tok. != tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.DEFINEscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/DEFINE. || len(assign.Lhsscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/AssignStmt#Lhs.) != 1 {
433 continue
434 }
435
436 // The LHS must be a single non-blank identifier.
437 lhsIdent, ok := assign.Lhsscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/AssignStmt#Lhs.[0].(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Identscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#)
438 if !ok || lhsIdent.Namescip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#Name. == "_" {
439 continue
440 }
441
442 // strings.Cut requires Go 1.18.
443 if !analyzerutilscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/analysis/analyzerutil`/.FileUsesGoVersionscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/analysis/analyzerutil`/FileUsesGoVersion().(pass, astutilscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/astutil`/.EnclosingFilescip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/astutil`/EnclosingFile().(curCall), versionsscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/versions`/.Go1_18scip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/versions`/Go1_18.) {
444 continue
445 }
446
447 // Build the fix.
448 //
449 // x := strings.SplitN(s, sep, 2)[0]
450 // --- ------ ---
451 // x, _, _ := strings.Cut(s, sep)
452 callFunIdent := typesinternalscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal`/.UsedIdentscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal`/UsedIdent().(info, callExpr.Funscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Fun.)
453
454 var edits []analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.TextEditscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#
455
456 // LHS: insert ", _, _" after x
457 edits = append(edits, analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.TextEditscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#{
458 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#Pos.: lhsIdent.Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#End().(),
459 Endscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#End.: lhsIdent.Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#End().(),
460 NewTextscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#NewText.: []byte(", _, _"),
461 })
462
463 // Function name: Split/SplitN → Cut
464 edits = append(edits, analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.TextEditscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#{
465 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#Pos.: callFunIdent.Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#Pos().(),
466 Endscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#End.: callFunIdent.Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#End().(),
467 NewTextscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#NewText.: []byte("Cut"),
468 })
469
470 // For SplitN: remove the ", 2" third argument.
471 if obj.Namescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#Name().() == "SplitN" {
472 edits = append(edits, analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.TextEditscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#{
473 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#Pos.: callExpr.Argsscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Args.[1].Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#End().(), // after sep
474 Endscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#End.: callExpr.Rparenscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Rparen., // before )
475 })
476 }
477
478 // Remove the "[0]" index expression.
479 edits = append(edits, analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.TextEditscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#{
480 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#Pos.: indexExpr.Lbrackscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/IndexExpr#Lbrack.,
481 Endscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/TextEdit#End.: indexExpr.Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/IndexExpr#End().(),
482 })
483
484 pass.Reportscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Pass#Report.(analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.Diagnosticscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Diagnostic#{
485 Posscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Diagnostic#Pos.: callExpr.Funscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Fun..Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#Pos().(),
486 Endscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Diagnostic#End.: callExpr.Funscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Fun..Endscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#End().(),
487 Messagescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Diagnostic#Message.: fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Sprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Sprintf().("strings.%s call can be simplified using strings.Cut", obj.Namescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#Name().()),
488 Categoryscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Diagnostic#Category.: "stringscut",
489 SuggestedFixesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/Diagnostic#SuggestedFixes.: []analysisscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/.SuggestedFixscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/SuggestedFix#{{
490 Messagescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/SuggestedFix#Message.: fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Sprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Sprintf().("Simplify strings.%s call using strings.Cut", obj.Namescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#Name().()),
491 TextEditsscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis`/SuggestedFix#TextEdits.: edits,
492 }},
493 })
494 }
495 }
496 }
497
498 // indexArgValid reports whether expr is a valid strings.Index(_, _) arg
499 // for the transformation. An arg is valid iff it is:
500 // - constant;
501 // - a local variable with no modifying uses after the Index() call; or
502 // - []byte(x) where x is also valid by this definition.
503 // All other expressions are assumed not referentially transparent,
504 // so we cannot be sure that all uses are safe to replace.
505 func indexArgValidscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/indexArgValid().(info *typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Infoscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#, index *typeindexscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/.Indexscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/Index#, expr astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Exprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Expr#, afterPos tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.Posscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/Pos#) bool {
506 tv := info.Typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#Types.[expr]
507 if tv.Valuescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/TypeAndValue#Value. != nil {
508 return true // constant
509 }
510 switch expr := expr.(type) {
511 case *astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.CallExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#:
512 return typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Identicalscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Identical().(tv.Typescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/TypeAndValue#Type., byteSliceTypescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/byteSliceType.) &&
513 info.Typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#Types.[expr.Funscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Fun.].IsTypescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/TypeAndValue#IsType().() && // make sure this isn't a function that returns a byte slice
514 indexArgValidscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/indexArgValid().(info, index, expr.Argsscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Args.[0], afterPos) // check s in []byte(s)
515 case *astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Identscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#:
516 sObj := info.Usesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#Uses.[expr]
517 sUses := index.Usesscip-go gomod golang.org/x/tools . `golang.org/x/tools/internal/typesinternal/typeindex`/Index#Uses().(sObj)
518 return !hasModifyingUsesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/hasModifyingUses().(sUses, afterPos)
519 default:
520 // For now, skip instances where s or substr are not
521 // identifiers, basic lits, or call expressions of the form
522 // []byte(s).
523 // TODO(mkalil): Handle s and substr being expressions like ptr.field[i].
524 // From adonovan: We'd need to analyze s and substr to see
525 // whether they are referentially transparent, and if not,
526 // analyze all code between declaration and use and see if
527 // there are statements or expressions with potential side
528 // effects.
529 return false
530 }
531 }
532
533 // checkIdxUses inspects the uses of i to make sure they match certain criteria that
534 // allows us to suggest a modernization. If all uses of i, s and substr match
535 // one of the following four valid formats, it returns a list of occurrences for
536 // each format. If any of the uses do not match one of the formats, return nil
537 // for all values, since we should not offer a replacement.
538 // 1. negative - a condition equivalent to i < 0
539 // 2. nonnegative - a condition equivalent to i >= 0
540 // 3. beforeSlice - a slice of `s` that matches either s[:i], s[0:i]
541 // 4. afterSlice - a slice of `s` that matches one of: s[i+len(substr):], s[len(substr) + i:], s[i + const], s[k + i] (where k = len(substr))
542 //
543 // Additionally, all beforeSlice and afterSlice uses must be dominated by a
544 // nonnegative guard on i (i.e., inside the body of an if whose condition
545 // checks i >= 0, or in the else of a negative check, or after an
546 // early-return negative check). This ensures that the rewrite from
547 // s[i+len(sep):] to "after" preserves semantics, since when i == -1,
548 // s[i+len(sep):] may yield a valid substring (e.g. s[0:] for single-byte
549 // separators), but "after" would be "".
550 //
551 // When len(substr)==1, it's safe to use s[i+1:] even when i < 0.
552 // Otherwise, each replacement of s[i+1:] must be guarded by a check
553 // that i is nonnegative.
554 func checkIdxUsesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/checkIdxUses().(info *typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Infoscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#, uses iterscip-go gomod github.com/golang/go/src go1.25.0 iter/.Seqscip-go gomod github.com/golang/go/src go1.25.0 iter/Seq#[inspectorscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/.Cursorscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#], s, substr astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Exprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Expr#, iObj typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Objectscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#) (negative, nonnegative, beforeSlice, afterSlice []astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Exprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Expr#) {
555 requireGuard := true
556 if l := constSubstrLenscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/constSubstrLen().(info, substr); l != -1 && l != 1 {
557 requireGuard = false
558 }
559
560 use := func(cur inspectorscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/.Cursorscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#) bool {
561 ek := cur.ParentEdgeKindscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#ParentEdgeKind().()
562 n := cur.Parentscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Parent().().Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().()
563 switch ek {
564 case edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.BinaryExpr_Xscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/BinaryExpr_X., edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.BinaryExpr_Yscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/BinaryExpr_Y.:
565 check := n.(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.BinaryExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#)
566 switch checkIdxComparisonscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/checkIdxComparison().(info, check, iObj) {
567 case -1:
568 negative = append(negative, check)
569 return true
570 case 1:
571 nonnegative = append(nonnegative, check)
572 return true
573 }
574 // Check is not equivalent to that i < 0 or i >= 0.
575 // Might be part of an outer slice expression like s[i + k]
576 // which requires a different check.
577 // Check that the thing being sliced is s and that the slice
578 // doesn't have a max index.
579 if slice, ok := cur.Parentscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Parent().().Parentscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Parent().().Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().().(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.SliceExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/SliceExpr#); ok &&
580 sameObjectscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/sameObject().(info, s, slice.Xscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/SliceExpr#X.) &&
581 slice.Maxscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/SliceExpr#Max. == nil {
582 if isBeforeSlicescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isBeforeSlice().(info, ek, slice) && (!requireGuard || isSliceIndexGuardedscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isSliceIndexGuarded().(info, cur, iObj)) {
583 beforeSlice = append(beforeSlice, slice)
584 return true
585 } else if isAfterSlicescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isAfterSlice().(info, ek, slice, substr) && (!requireGuard || isSliceIndexGuardedscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isSliceIndexGuarded().(info, cur, iObj)) {
586 afterSlice = append(afterSlice, slice)
587 return true
588 }
589 }
590 case edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.SliceExpr_Lowscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/SliceExpr_Low., edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.SliceExpr_Highscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/SliceExpr_High.:
591 slice := n.(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.SliceExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/SliceExpr#)
592 // Check that the thing being sliced is s and that the slice doesn't
593 // have a max index.
594 if sameObjectscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/sameObject().(info, s, slice.Xscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/SliceExpr#X.) && slice.Maxscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/SliceExpr#Max. == nil {
595 if isBeforeSlicescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isBeforeSlice().(info, ek, slice) && (!requireGuard || isSliceIndexGuardedscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isSliceIndexGuarded().(info, cur, iObj)) {
596 beforeSlice = append(beforeSlice, slice)
597 return true
598 } else if isAfterSlicescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isAfterSlice().(info, ek, slice, substr) && (!requireGuard || isSliceIndexGuardedscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isSliceIndexGuarded().(info, cur, iObj)) {
599 afterSlice = append(afterSlice, slice)
600 return true
601 }
602 }
603 }
604 return false
605 }
606
607 for curIdent := range uses {
608 if !use(curIdent) {
609 return nil, nil, nil, nil
610 }
611 }
612 return negative, nonnegative, beforeSlice, afterSlice
613 }
614
615 // hasModifyingUses reports whether any of the uses involve potential
616 // modifications. Uses involving assignments before the "afterPos" won't be
617 // considered.
618 func hasModifyingUsesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/hasModifyingUses().(uses iterscip-go gomod github.com/golang/go/src go1.25.0 iter/.Seqscip-go gomod github.com/golang/go/src go1.25.0 iter/Seq#[inspectorscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/.Cursorscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#], afterPos tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.Posscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/Pos#) bool {
619 for curUse := range uses {
620 ek := curUse.ParentEdgeKindscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#ParentEdgeKind().()
621 if ek == edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.AssignStmt_Lhsscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/AssignStmt_Lhs. {
622 if curUse.Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().().Posscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#Pos().() <= afterPos {
623 continue
624 }
625 // Any use on the LHS is a modifying use.
626 return true
627 } else if ek == edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.UnaryExpr_Xscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/UnaryExpr_X. &&
628 curUse.Parentscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Parent().().Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().().(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.UnaryExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/UnaryExpr#).Opscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/UnaryExpr#Op. == tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.ANDscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/AND. {
629 // Modifying use because we might be passing the object by reference (an explicit &).
630 // We can ignore the case where we have a method call on the expression (which
631 // has an implicit &) because we know the type of s and substr are strings
632 // which cannot have methods on them.
633 return true
634 }
635 }
636 return false
637 }
638
639 // checkIdxComparison reports whether the check is equivalent to i < 0 or its negation, or neither.
640 // For equivalent to i >= 0, we only accept this exact BinaryExpr since
641 // expressions like i > 0 or i >= 1 make a stronger statement about the value of i.
642 // We avoid suggesting a fix in this case since it may result in an invalid
643 // transformation (See golang/go#76687).
644 // Since strings.Index returns exactly -1 if the substring is not found, we
645 // don't need to handle expressions like i <= -3.
646 // We return 0 if the expression does not match any of these options.
647 func checkIdxComparisonscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/checkIdxComparison().(info *typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Infoscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#, check *astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.BinaryExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#, iObj typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Objectscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#) int {
648 isI := func(e astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Exprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Expr#) bool {
649 id, ok := e.(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Identscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#)
650 return ok && info.Usesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#Uses.[id] == iObj
651 }
652 if !isI(check.Xscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#X.) && !isI(check.Yscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#Y.) {
653 return 0
654 }
655
656 // Ensure that the constant (if any) is on the right.
657 x, op, y := check.Xscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#X., check.Opscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#Op., check.Yscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#Y.
658 if info.Typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#Types.[x].Valuescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/TypeAndValue#Value. != nil {
659 x, op, y = y, flipscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/flip().(op), x
660 }
661
662 yIsInt := func(k int64) bool {
663 return isIntLiteralscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isIntLiteral().(info, y, k)
664 }
665
666 if op == tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.LSSscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/LSS. && yIsInt(0) || // i < 0
667 op == tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.EQLscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/EQL. && yIsInt(-1) || // i == -1
668 op == tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.LEQscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/LEQ. && yIsInt(-1) { // i <= -1
669 return -1 // check <=> i is negative
670 }
671
672 if op == tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.GEQscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/GEQ. && yIsInt(0) || // i >= 0
673 op == tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.NEQscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/NEQ. && yIsInt(-1) || // i != -1
674 op == tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.GTRscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/GTR. && yIsInt(-1) { // i > -1
675 return +1 // check <=> i is non-negative
676 }
677
678 return 0 // unknown
679 }
680
681 // flip changes the comparison token as if the operands were flipped.
682 // It is defined only for == and the four inequalities.
683 func flipscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/flip().(op tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.Tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/Token#) tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.Tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/Token# {
684 switch op {
685 case tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.EQLscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/EQL.:
686 return tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.EQLscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/EQL. // (same)
687 case tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.GEQscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/GEQ.:
688 return tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.LEQscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/LEQ.
689 case tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.GTRscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/GTR.:
690 return tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.LSSscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/LSS.
691 case tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.LEQscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/LEQ.:
692 return tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.GEQscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/GEQ.
693 case tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.LSSscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/LSS.:
694 return tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.GTRscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/GTR.
695 }
696 return op
697 }
698
699 // isBeforeSlice reports whether the SliceExpr is of the form s[:i] or s[0:i].
700 func isBeforeSlicescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isBeforeSlice().(info *typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Infoscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#, ek edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.Kindscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/Kind#, slice *astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.SliceExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/SliceExpr#) bool {
701 return ek == edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.SliceExpr_Highscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/SliceExpr_High. && (slice.Lowscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/SliceExpr#Low. == nil || isZeroIntConstscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isZeroIntConst().(info, slice.Lowscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/SliceExpr#Low.))
702 }
703
704 // constSubstrLen returns the constant length of substr, or -1 if unknown.
705 func constSubstrLenscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/constSubstrLen().(info *typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Infoscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#, substr astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Exprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Expr#) int {
706 // Handle len([]byte(substr))
707 if call, ok := substr.(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.CallExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#); ok {
708 tv := info.Typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#Types.[call.Funscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Fun.]
709 if tv.IsTypescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/TypeAndValue#IsType().() && typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Identicalscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Identical().(tv.Typescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/TypeAndValue#Type., byteSliceTypescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/byteSliceType.) {
710 // Only one arg in []byte conversion.
711 substr = call.Argsscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Args.[0]
712 }
713 }
714 substrVal := info.Typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#Types.[substr].Valuescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/TypeAndValue#Value.
715 if substrVal != nil {
716 switch substrVal.Kindscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/Value#Kind().() {
717 case constantscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/.Stringscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/String.:
718 return len(constantscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/.StringValscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/StringVal().(substrVal))
719 case constantscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/.Intscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/Int.:
720 // constant.Value is a byte literal, e.g. bytes.IndexByte(_, 'a')
721 // or a numeric byte literal, e.g. bytes.IndexByte(_, 65)
722 // ([]byte(rune) is not legal.)
723 return 1
724 }
725 }
726 return -1
727 }
728
729 // isAfterSlice reports whether the SliceExpr is of the form s[i+len(substr):],
730 // or s[i + k:] where k is a const is equal to len(substr).
731 func isAfterSlicescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isAfterSlice().(info *typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Infoscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#, ek edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.Kindscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/Kind#, slice *astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.SliceExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/SliceExpr#, substr astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Exprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Expr#) bool {
732 lowExpr, ok := slice.Lowscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/SliceExpr#Low..(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.BinaryExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#)
733 if !ok || slice.Highscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/SliceExpr#High. != nil {
734 return false
735 }
736 // Returns true if the expression is a call to len(substr).
737 isLenCall := func(expr astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Exprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Expr#) bool {
738 call, ok := expr.(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.CallExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#)
739 if !ok || len(call.Argsscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Args.) != 1 {
740 return false
741 }
742 return sameObjectscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/sameObject().(info, substr, call.Argsscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Args.[0]) && typeutilscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/types/typeutil`/.Calleescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/types/typeutil`/Callee().(info, call) == builtinLenscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/builtinLen.
743 }
744
745 substrLen := constSubstrLenscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/constSubstrLen().(info, substr)
746
747 switch ek {
748 case edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.BinaryExpr_Xscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/BinaryExpr_X.:
749 kVal := info.Typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#Types.[lowExpr.Yscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#Y.].Valuescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/TypeAndValue#Value.
750 if kVal == nil {
751 // i + len(substr)
752 return lowExpr.Opscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#Op. == tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.ADDscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/ADD. && isLenCall(lowExpr.Yscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#Y.)
753 } else {
754 // i + k
755 kInt, ok := constantscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/.Int64Valscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/Int64Val().(kVal)
756 return ok && substrLen == int(kInt)
757 }
758 case edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.BinaryExpr_Yscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/BinaryExpr_Y.:
759 kVal := info.Typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#Types.[lowExpr.Xscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#X.].Valuescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/TypeAndValue#Value.
760 if kVal == nil {
761 // len(substr) + i
762 return lowExpr.Opscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#Op. == tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.ADDscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/ADD. && isLenCall(lowExpr.Xscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#X.)
763 } else {
764 // k + i
765 kInt, ok := constantscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/.Int64Valscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/Int64Val().(kVal)
766 return ok && substrLen == int(kInt)
767 }
768 }
769 return false
770 }
771
772 // isSliceIndexGuarded reports whether a use of the index variable i (at the given cursor)
773 // inside a slice expression is dominated by a nonnegative guard.
774 // A use is considered guarded if any of the following are true:
775 // - It is inside the Body of an IfStmt whose condition is a nonnegative check on i.
776 // - It is inside the Else of an IfStmt whose condition is a negative check on i.
777 // - It is preceded (in the same block) by an IfStmt whose condition is a
778 // negative check on i with a terminating body (e.g., early return).
779 //
780 // Conversely, a use is immediately rejected if:
781 // - It is inside the Body of an IfStmt whose condition is a negative check on i.
782 // - It is inside the Else of an IfStmt whose condition is a nonnegative check on i.
783 //
784 // We have already checked (see [hasModifyingUses]) that there are no
785 // intervening uses (incl. via aliases) of i that might alter its value.
786 func isSliceIndexGuardedscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/isSliceIndexGuarded().(info *typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Infoscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#, cur inspectorscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/.Cursorscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#, iObj typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Objectscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#) bool {
787 for anc := range cur.Enclosingscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Enclosing().() {
788 switch anc.ParentEdgeKindscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#ParentEdgeKind().() {
789 case edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.IfStmt_Bodyscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/IfStmt_Body., edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.IfStmt_Elsescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/IfStmt_Else.:
790 ifStmt := anc.Parentscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Parent().().Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().().(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.IfStmtscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/IfStmt#)
791 check := condChecksIdxscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/condChecksIdx().(info, ifStmt.Condscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/IfStmt#Cond., iObj)
792 if anc.ParentEdgeKindscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#ParentEdgeKind().() == edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.IfStmt_Elsescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/IfStmt_Else. {
793 check = -check
794 }
795 if check > 0 {
796 return true // inside nonnegative-guarded block (i >= 0 here)
797 }
798 if check < 0 {
799 return false // inside negative-guarded block (i < 0 here)
800 }
801 case edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.BlockStmt_Listscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/BlockStmt_List.:
802 // Check preceding siblings for early-return negative checks.
803 for sib, ok := anc.PrevSiblingscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#PrevSibling().(); ok; sib, ok = sib.PrevSiblingscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#PrevSibling().() {
804 ifStmt, ok := sib.Nodescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/inspector`/Cursor#Node().().(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.IfStmtscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/IfStmt#)
805 if ok && condChecksIdxscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/condChecksIdx().(info, ifStmt.Condscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/IfStmt#Cond., iObj) < 0 && bodyTerminatesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/bodyTerminates().(ifStmt.Bodyscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/IfStmt#Body.) {
806 return true // preceded by early-return negative check
807 }
808 }
809 case edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.FuncDecl_Bodyscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/FuncDecl_Body., edgescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/.FuncLit_Bodyscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/ast/edge`/FuncLit_Body.:
810 return false // stop at function boundary
811 }
812 }
813 return false
814 }
815
816 // condChecksIdx reports whether cond is a BinaryExpr that checks
817 // the index variable iObj for negativity or non-negativity.
818 // Returns -1 for negative (e.g. i < 0), +1 for nonnegative (e.g. i >= 0), 0 otherwise.
819 func condChecksIdxscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/condChecksIdx().(info *typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Infoscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#, cond astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Exprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Expr#, iObj typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Objectscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#) int {
820 binExpr, ok := cond.(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.BinaryExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BinaryExpr#)
821 if !ok {
822 return 0
823 }
824 return checkIdxComparisonscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/checkIdxComparison().(info, binExpr, iObj)
825 }
826
827 // bodyTerminates reports whether the given block statement unconditionally
828 // terminates execution (via return, break, continue, or goto).
829 func bodyTerminatesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/bodyTerminates().(block *astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.BlockStmtscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BlockStmt#) bool {
830 if len(block.Listscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BlockStmt#List.) == 0 {
831 return false
832 }
833 last := block.Listscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BlockStmt#List.[len(block.Listscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BlockStmt#List.)-1]
834 switch last.(type) {
835 case *astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.ReturnStmtscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/ReturnStmt#, *astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.BranchStmtscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/BranchStmt#:
836 return true // return, break, continue, goto
837 }
838 return false
839 }
840
841 // sameObject reports whether we know that the expressions resolve to the same object.
842 func sameObjectscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/analysis/passes/modernize`/sameObject().(info *typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Infoscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#, expr1, expr2 astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Exprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Expr#) bool {
843 if ident1, ok := expr1.(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Identscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#); ok {
844 if ident2, ok := expr2.(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Identscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#); ok {
845 uses1, ok1 := info.Usesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#Uses.[ident1]
846 uses2, ok2 := info.Usesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#Uses.[ident2]
847 return ok1 && ok2 && uses1 == uses2
848 }
849 }
850 return false
851 }