|
| 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 modernize |
| 6 | + |
| 7 | +import ( |
| 8 | + "fmt" |
| 9 | + "go/ast" |
| 10 | + "go/token" |
| 11 | + |
| 12 | + "golang.org/x/tools/go/analysis" |
| 13 | + "golang.org/x/tools/go/analysis/passes/inspect" |
| 14 | + "golang.org/x/tools/go/ast/inspector" |
| 15 | + "golang.org/x/tools/go/types/typeutil" |
| 16 | + "golang.org/x/tools/internal/analysisinternal" |
| 17 | +) |
| 18 | + |
| 19 | +// stringscutprefix offers a fix to replace an if statement which |
| 20 | +// calls to the 2 patterns below with strings.CutPrefix. |
| 21 | +// |
| 22 | +// Patterns: |
| 23 | +// |
| 24 | +// 1. if strings.HasPrefix(s, pre) { use(strings.TrimPrefix(s, pre) } |
| 25 | +// => |
| 26 | +// if after, ok := strings.CutPrefix(s, pre); ok { use(after) } |
| 27 | +// |
| 28 | +// 2. if after := strings.TrimPrefix(s, pre); after != s { use(after) } |
| 29 | +// => |
| 30 | +// if after, ok := strings.CutPrefix(s, pre); ok { use(after) } |
| 31 | +// |
| 32 | +// The use must occur within the first statement of the block, and the offered fix |
| 33 | +// only replaces the first occurrence of strings.TrimPrefix. |
| 34 | +// |
| 35 | +// Variants: |
| 36 | +// - bytes.HasPrefix usage as pattern 1. |
| 37 | +func stringscutprefix(pass *analysis.Pass) { |
| 38 | + if !analysisinternal.Imports(pass.Pkg, "strings") && |
| 39 | + !analysisinternal.Imports(pass.Pkg, "bytes") { |
| 40 | + return |
| 41 | + } |
| 42 | + |
| 43 | + const ( |
| 44 | + category = "stringscutprefix" |
| 45 | + fixedMessage = "Replace HasPrefix/TrimPrefix with CutPrefix" |
| 46 | + ) |
| 47 | + |
| 48 | + info := pass.TypesInfo |
| 49 | + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 50 | + for curFile := range filesUsing(inspect, pass.TypesInfo, "go1.20") { |
| 51 | + for curIfStmt := range curFile.Preorder((*ast.IfStmt)(nil)) { |
| 52 | + ifStmt := curIfStmt.Node().(*ast.IfStmt) |
| 53 | + |
| 54 | + // pattern1 |
| 55 | + if call, ok := ifStmt.Cond.(*ast.CallExpr); ok && len(ifStmt.Body.List) > 0 { |
| 56 | + obj := typeutil.Callee(info, call) |
| 57 | + if !analysisinternal.IsFunctionNamed(obj, "strings", "HasPrefix") && |
| 58 | + !analysisinternal.IsFunctionNamed(obj, "bytes", "HasPrefix") { |
| 59 | + continue |
| 60 | + } |
| 61 | + |
| 62 | + // Replace the first occurrence of strings.TrimPrefix(s, pre) in the first statement only, |
| 63 | + // but not later statements in case s or pre are modified by intervening logic. |
| 64 | + firstStmt := curIfStmt.Child(ifStmt.Body).Child(ifStmt.Body.List[0]) |
| 65 | + for curCall := range firstStmt.Preorder((*ast.CallExpr)(nil)) { |
| 66 | + call1 := curCall.Node().(*ast.CallExpr) |
| 67 | + obj1 := typeutil.Callee(info, call1) |
| 68 | + if !analysisinternal.IsFunctionNamed(obj1, "strings", "TrimPrefix") && |
| 69 | + !analysisinternal.IsFunctionNamed(obj1, "bytes", "TrimPrefix") { |
| 70 | + continue |
| 71 | + } |
| 72 | + |
| 73 | + // Have: if strings.HasPrefix(s0, pre0) { ...strings.TrimPrefix(s, pre)... } |
| 74 | + var ( |
| 75 | + s0 = call.Args[0] |
| 76 | + pre0 = call.Args[1] |
| 77 | + s = call1.Args[0] |
| 78 | + pre = call1.Args[1] |
| 79 | + ) |
| 80 | + |
| 81 | + // check whether the obj1 uses the exact the same argument with strings.HasPrefix |
| 82 | + // shadow variables won't be valid because we only access the first statement. |
| 83 | + if equalSyntax(s0, s) && equalSyntax(pre0, pre) { |
| 84 | + after := analysisinternal.FreshName(info.Scopes[ifStmt], ifStmt.Pos(), "after") |
| 85 | + _, prefix, importEdits := analysisinternal.AddImport( |
| 86 | + info, |
| 87 | + curFile.Node().(*ast.File), |
| 88 | + obj1.Pkg().Name(), |
| 89 | + obj1.Pkg().Path(), |
| 90 | + "CutPrefix", |
| 91 | + call.Pos(), |
| 92 | + ) |
| 93 | + okVarName := analysisinternal.FreshName(info.Scopes[ifStmt], ifStmt.Pos(), "ok") |
| 94 | + pass.Report(analysis.Diagnostic{ |
| 95 | + // highlight at HasPrefix call. |
| 96 | + Pos: call.Pos(), |
| 97 | + End: call.End(), |
| 98 | + Category: category, |
| 99 | + Message: "HasPrefix + TrimPrefix can be simplified to CutPrefix", |
| 100 | + SuggestedFixes: []analysis.SuggestedFix{{ |
| 101 | + Message: fixedMessage, |
| 102 | + // if strings.HasPrefix(s, pre) { use(strings.TrimPrefix(s, pre)) } |
| 103 | + // ------------ ----------------- ----- -------------------------- |
| 104 | + // if after, ok := strings.CutPrefix(s, pre); ok { use(after) } |
| 105 | + TextEdits: append(importEdits, []analysis.TextEdit{ |
| 106 | + { |
| 107 | + Pos: call.Fun.Pos(), |
| 108 | + End: call.Fun.Pos(), |
| 109 | + NewText: []byte(fmt.Sprintf("%s, %s :=", after, okVarName)), |
| 110 | + }, |
| 111 | + { |
| 112 | + Pos: call.Fun.Pos(), |
| 113 | + End: call.Fun.End(), |
| 114 | + NewText: fmt.Appendf(nil, "%sCutPrefix", prefix), |
| 115 | + }, |
| 116 | + { |
| 117 | + Pos: call.End(), |
| 118 | + End: call.End(), |
| 119 | + NewText: []byte(fmt.Sprintf("; %s ", okVarName)), |
| 120 | + }, |
| 121 | + { |
| 122 | + Pos: call1.Pos(), |
| 123 | + End: call1.End(), |
| 124 | + NewText: []byte(after), |
| 125 | + }, |
| 126 | + }...), |
| 127 | + }}}, |
| 128 | + ) |
| 129 | + break |
| 130 | + } |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + // pattern2 |
| 135 | + if bin, ok := ifStmt.Cond.(*ast.BinaryExpr); ok && |
| 136 | + bin.Op == token.NEQ && |
| 137 | + ifStmt.Init != nil && |
| 138 | + isSimpleAssign(ifStmt.Init) { |
| 139 | + assign := ifStmt.Init.(*ast.AssignStmt) |
| 140 | + if call, ok := assign.Rhs[0].(*ast.CallExpr); ok && assign.Tok == token.DEFINE { |
| 141 | + lhs := assign.Lhs[0] |
| 142 | + obj := typeutil.Callee(info, call) |
| 143 | + if analysisinternal.IsFunctionNamed(obj, "strings", "TrimPrefix") && |
| 144 | + (equalSyntax(lhs, bin.X) && equalSyntax(call.Args[0], bin.Y) || |
| 145 | + (equalSyntax(lhs, bin.Y) && equalSyntax(call.Args[0], bin.X))) { |
| 146 | + okVarName := analysisinternal.FreshName(info.Scopes[ifStmt], ifStmt.Pos(), "ok") |
| 147 | + // Have one of: |
| 148 | + // if rest := TrimPrefix(s, prefix); rest != s { |
| 149 | + // if rest := TrimPrefix(s, prefix); s != rest { |
| 150 | + |
| 151 | + // We use AddImport not to add an import (since it exists already) |
| 152 | + // but to compute the correct prefix in the dot-import case. |
| 153 | + _, prefix, importEdits := analysisinternal.AddImport( |
| 154 | + info, |
| 155 | + curFile.Node().(*ast.File), |
| 156 | + obj.Pkg().Name(), |
| 157 | + obj.Pkg().Path(), |
| 158 | + "CutPrefix", |
| 159 | + call.Pos(), |
| 160 | + ) |
| 161 | + |
| 162 | + pass.Report(analysis.Diagnostic{ |
| 163 | + // highlight from the init and the condition end. |
| 164 | + Pos: ifStmt.Init.Pos(), |
| 165 | + End: ifStmt.Cond.End(), |
| 166 | + Category: category, |
| 167 | + Message: "TrimPrefix can be simplified to CutPrefix", |
| 168 | + SuggestedFixes: []analysis.SuggestedFix{{ |
| 169 | + Message: fixedMessage, |
| 170 | + // if x := strings.TrimPrefix(s, pre); x != s ... |
| 171 | + // ---- ---------- ------ |
| 172 | + // if x, ok := strings.CutPrefix (s, pre); ok ... |
| 173 | + TextEdits: append(importEdits, []analysis.TextEdit{ |
| 174 | + { |
| 175 | + Pos: assign.Lhs[0].End(), |
| 176 | + End: assign.Lhs[0].End(), |
| 177 | + NewText: fmt.Appendf(nil, ", %s", okVarName), |
| 178 | + }, |
| 179 | + { |
| 180 | + Pos: call.Fun.Pos(), |
| 181 | + End: call.Fun.End(), |
| 182 | + NewText: fmt.Appendf(nil, "%sCutPrefix", prefix), |
| 183 | + }, |
| 184 | + { |
| 185 | + Pos: ifStmt.Cond.Pos(), |
| 186 | + End: ifStmt.Cond.End(), |
| 187 | + NewText: []byte(okVarName), |
| 188 | + }, |
| 189 | + }...), |
| 190 | + }}, |
| 191 | + }) |
| 192 | + } |
| 193 | + } |
| 194 | + } |
| 195 | + } |
| 196 | + } |
| 197 | +} |
0 commit comments