| 1 | // Copyright 2020 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 stringintconv |
| 6 | |
| 7 | import ( |
| 8 | _ "embed" |
| 9 | "fmt" |
| 10 | "go/ast" |
| 11 | "go/types" |
| 12 | "strings" |
| 13 | |
| 14 | "golang.org/x/tools/go/analysis" |
| 15 | "golang.org/x/tools/go/analysis/passes/inspect" |
| 16 | "golang.org/x/tools/go/ast/inspector" |
| 17 | "golang.org/x/tools/internal/analysis/analyzerutil" |
| 18 | "golang.org/x/tools/internal/refactor" |
| 19 | "golang.org/x/tools/internal/typeparams" |
| 20 | "golang.org/x/tools/internal/typesinternal" |
| 21 | ) |
| 22 | |
| 23 | //go:embed doc.go |
| 24 | var doc string |
| 25 | |
| 26 | var Analyzer = &analysis.Analyzer{ |
| 27 | Name: "stringintconv", |
| 28 | Doc: analyzerutil.MustExtractDoc(doc, "stringintconv"), |
| 29 | URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/stringintconv", |
| 30 | Requires: []*analysis.Analyzer{inspect.Analyzer}, |
| 31 | Run: run, |
| 32 | } |
| 33 | |
| 34 | // describe returns a string describing the type typ contained within the type |
| 35 | // set of inType. If non-empty, inName is used as the name of inType (this is |
| 36 | // necessary so that we can use alias type names that may not be reachable from |
| 37 | // inType itself). |
| 38 | func describe(typ, inType types.Type, inName string) string { |
| 39 | name := inName |
| 40 | if typ != inType { |
| 41 | name = typeName(typ) |
| 42 | } |
| 43 | if name == "" { |
| 44 | return "" |
| 45 | } |
| 46 | |
| 47 | var parentheticals []string |
| 48 | if underName := typeName(typ.Underlying()); underName != "" && underName != name { |
| 49 | parentheticals = append(parentheticals, underName) |
| 50 | } |
| 51 | |
| 52 | if typ != inType && inName != "" && inName != name { |
| 53 | parentheticals = append(parentheticals, "in "+inName) |
| 54 | } |
| 55 | |
| 56 | if len(parentheticals) > 0 { |
| 57 | name += " (" + strings.Join(parentheticals, ", ") + ")" |
| 58 | } |
| 59 | |
| 60 | return name |
| 61 | } |
| 62 | |
| 63 | func typeName(t types.Type) string { |
| 64 | if basic, ok := t.(*types.Basic); ok { |
| 65 | return basic.Name() // may be (e.g.) "untyped int", which has no TypeName |
| 66 | } |
| 67 | if tname := typesinternal.TypeNameFor(t); tname != nil { |
| 68 | return tname.Name() |
| 69 | } |
| 70 | return "" |
| 71 | } |
| 72 | |
| 73 | func run(pass *analysis.Pass) (any, error) { |
| 74 | inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 75 | nodeFilter := []ast.Node{ |
| 76 | (*ast.File)(nil), |
| 77 | (*ast.CallExpr)(nil), |
| 78 | } |
| 79 | var file *ast.File |
| 80 | inspect.Preorder(nodeFilter, func(n ast.Node) { |
| 81 | if n, ok := n.(*ast.File); ok { |
| 82 | file = n |
| 83 | return |
| 84 | } |
| 85 | call := n.(*ast.CallExpr) |
| 86 | |
| 87 | if len(call.Args) != 1 { |
| 88 | return |
| 89 | } |
| 90 | arg := call.Args[0] |
| 91 | |
| 92 | // Retrieve target type name. |
| 93 | var tname *types.TypeName |
| 94 | switch fun := call.Fun.(type) { |
| 95 | case *ast.Ident: |
| 96 | tname, _ = pass.TypesInfo.Uses[fun].(*types.TypeName) |
| 97 | case *ast.SelectorExpr: |
| 98 | tname, _ = pass.TypesInfo.Uses[fun.Sel].(*types.TypeName) |
| 99 | } |
| 100 | if tname == nil { |
| 101 | return |
| 102 | } |
| 103 | |
| 104 | // In the conversion T(v) of a value v of type V to a target type T, we |
| 105 | // look for types T0 in the type set of T and V0 in the type set of V, such |
| 106 | // that V0->T0 is a problematic conversion. If T and V are not type |
| 107 | // parameters, this amounts to just checking if V->T is a problematic |
| 108 | // conversion. |
| 109 | |
| 110 | // First, find a type T0 in T that has an underlying type of string. |
| 111 | T := tname.Type() |
| 112 | ttypes, err := structuralTypes(T) |
| 113 | if err != nil { |
| 114 | return // invalid type |
| 115 | } |
| 116 | |
| 117 | var T0 types.Type // string type in the type set of T |
| 118 | |
| 119 | for _, tt := range ttypes { |
| 120 | u, _ := tt.Underlying().(*types.Basic) |
| 121 | if u != nil && u.Kind() == types.String { |
| 122 | T0 = tt |
| 123 | break |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | if T0 == nil { |
| 128 | // No target types have an underlying type of string. |
| 129 | return |
| 130 | } |
| 131 | |
| 132 | // Next, find a type V0 in V that has an underlying integral type that is |
| 133 | // not byte or rune. |
| 134 | V := pass.TypesInfo.TypeOf(arg) |
| 135 | vtypes, err := structuralTypes(V) |
| 136 | if err != nil { |
| 137 | return // invalid type |
| 138 | } |
| 139 | |
| 140 | var V0 types.Type // integral type in the type set of V |
| 141 | |
| 142 | for _, vt := range vtypes { |
| 143 | u, _ := vt.Underlying().(*types.Basic) |
| 144 | if u != nil && u.Info()&types.IsInteger != 0 { |
| 145 | switch u.Kind() { |
| 146 | case types.Byte, types.Rune, types.UntypedRune: |
| 147 | continue |
| 148 | } |
| 149 | V0 = vt |
| 150 | break |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | if V0 == nil { |
| 155 | // No source types are non-byte or rune integer types. |
| 156 | return |
| 157 | } |
| 158 | |
| 159 | convertibleToRune := true // if true, we can suggest a fix |
| 160 | for _, t := range vtypes { |
| 161 | if !types.ConvertibleTo(t, types.Typ[types.Rune]) { |
| 162 | convertibleToRune = false |
| 163 | break |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | target := describe(T0, T, tname.Name()) |
| 168 | source := describe(V0, V, typeName(V)) |
| 169 | |
| 170 | if target == "" || source == "" { |
| 171 | return // something went wrong |
| 172 | } |
| 173 | |
| 174 | diag := analysis.Diagnostic{ |
| 175 | Pos: n.Pos(), |
| 176 | Message: fmt.Sprintf("conversion from %s to %s yields a string of one rune, not a string of digits", source, target), |
| 177 | } |
| 178 | addFix := func(message string, edits []analysis.TextEdit) { |
| 179 | diag.SuggestedFixes = append(diag.SuggestedFixes, analysis.SuggestedFix{ |
| 180 | Message: message, |
| 181 | TextEdits: edits, |
| 182 | }) |
| 183 | } |
| 184 | |
| 185 | // Fix 1: use fmt.Sprint(x) |
| 186 | // |
| 187 | // Prefer fmt.Sprint over strconv.Itoa, FormatInt, |
| 188 | // or FormatUint, as it works for any type. |
| 189 | // Add an import of "fmt" as needed. |
| 190 | // |
| 191 | // Unless the type is exactly string, we must retain the conversion. |
| 192 | // |
| 193 | // Do not offer this fix if type parameters are involved, |
| 194 | // as there are too many combinations and subtleties. |
| 195 | // Consider x = rune | int16 | []byte: in all cases, |
| 196 | // string(x) is legal, but the appropriate diagnostic |
| 197 | // and fix differs. Similarly, don't offer the fix if |
| 198 | // the type has methods, as some {String,GoString,Format} |
| 199 | // may change the behavior of fmt.Sprint. |
| 200 | if len(ttypes) == 1 && len(vtypes) == 1 && types.NewMethodSet(V0).Len() == 0 { |
| 201 | prefix, importEdits := refactor.AddImport(pass.TypesInfo, file, "fmt", "fmt", "Sprint", arg.Pos()) |
| 202 | if types.Identical(T0, types.Typ[types.String]) { |
| 203 | // string(x) -> fmt.Sprint(x) |
| 204 | addFix("Format the number as a decimal", append(importEdits, |
| 205 | analysis.TextEdit{ |
| 206 | Pos: call.Fun.Pos(), |
| 207 | End: call.Fun.End(), |
| 208 | NewText: []byte(prefix + "Sprint"), |
| 209 | }), |
| 210 | ) |
| 211 | } else { |
| 212 | // mystring(x) -> mystring(fmt.Sprint(x)) |
| 213 | addFix("Format the number as a decimal", append(importEdits, |
| 214 | analysis.TextEdit{ |
| 215 | Pos: call.Lparen + 1, |
| 216 | End: call.Lparen + 1, |
| 217 | NewText: []byte(prefix + "Sprint("), |
| 218 | }, |
| 219 | analysis.TextEdit{ |
| 220 | Pos: call.Rparen, |
| 221 | End: call.Rparen, |
| 222 | NewText: []byte(")"), |
| 223 | }), |
| 224 | ) |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | // Fix 2: use string(rune(x)) |
| 229 | if convertibleToRune { |
| 230 | addFix("Convert a single rune to a string", []analysis.TextEdit{ |
| 231 | { |
| 232 | Pos: arg.Pos(), |
| 233 | End: arg.Pos(), |
| 234 | NewText: []byte("rune("), |
| 235 | }, |
| 236 | { |
| 237 | Pos: arg.End(), |
| 238 | End: arg.End(), |
| 239 | NewText: []byte(")"), |
| 240 | }, |
| 241 | }) |
| 242 | } |
| 243 | pass.Report(diag) |
| 244 | }) |
| 245 | return nil, nil |
| 246 | } |
| 247 | |
| 248 | func structuralTypes(t types.Type) ([]types.Type, error) { |
| 249 | var structuralTypes []types.Type |
| 250 | if tp, ok := types.Unalias(t).(*types.TypeParam); ok { |
| 251 | terms, err := typeparams.StructuralTerms(tp) |
| 252 | if err != nil { |
| 253 | return nil, err |
| 254 | } |
| 255 | for _, term := range terms { |
| 256 | structuralTypes = append(structuralTypes, term.Type()) |
| 257 | } |
| 258 | } else { |
| 259 | structuralTypes = append(structuralTypes, t) |
| 260 | } |
| 261 | return structuralTypes, nil |
| 262 | } |