Debian Codegraph @

staticcheck/sa6005/sa6005.go

raw
1 package sa6005
2
3 import (
4 "go/ast"
5 "go/token"
6
7 "honnef.co/go/tools/analysis/code"
8 "honnef.co/go/tools/analysis/edit"
9 "honnef.co/go/tools/analysis/lint"
10 "honnef.co/go/tools/analysis/report"
11 "honnef.co/go/tools/pattern"
12
13 "golang.org/x/tools/go/analysis"
14 )
15
16 var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
17 Analyzer: &analysis.Analyzer{
18 Name: "SA6005",
19 Run: run,
20 Requires: code.RequiredAnalyzers,
21 },
22 Doc: &lint.RawDocumentation{
23 Title: `Inefficient string comparison with \'strings.ToLower\' or \'strings.ToUpper\'`,
24 Text: `Converting two strings to the same case and comparing them like so
25
26 if strings.ToLower(s1) == strings.ToLower(s2) {
27 ...
28 }
29
30 is significantly more expensive than comparing them with
31 \'strings.EqualFold(s1, s2)\'. This is due to memory usage as well as
32 computational complexity.
33
34 \'strings.ToLower\' will have to allocate memory for the new strings, as
35 well as convert both strings fully, even if they differ on the very
36 first byte. strings.EqualFold, on the other hand, compares the strings
37 one character at a time. It doesn't need to create two intermediate
38 strings and can return as soon as the first non-matching character has
39 been found.
40
41 For a more in-depth explanation of this issue, see
42 https://blog.digitalocean.com/how-to-efficiently-compare-strings-in-go/`,
43 Since: "2019.2",
44 Severity: lint.SeverityWarning,
45 MergeIf: lint.MergeIfAny,
46 },
47 })
48
49 var Analyzer = SCAnalyzer.Analyzer
50
51 var (
52 checkToLowerToUpperComparisonQ = pattern.MustParse(`
53 (BinaryExpr
54 (CallExpr fun@(Symbol (Or "strings.ToLower" "strings.ToUpper")) [a])
55 tok@(Or "==" "!=")
56 (CallExpr fun [b]))`)
57 checkToLowerToUpperComparisonR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "strings") (Ident "EqualFold")) [a b])`)
58 )
59
60 func run(pass *analysis.Pass) (any, error) {
61 for node, m := range code.Matches(pass, checkToLowerToUpperComparisonQ) {
62 rn := pattern.NodeToAST(checkToLowerToUpperComparisonR.Root, m.State).(ast.Expr)
63 if m.State["tok"].(token.Token) == token.NEQ {
64 rn = &ast.UnaryExpr{
65 Op: token.NOT,
66 X: rn,
67 }
68 }
69
70 report.Report(pass, node,
71 "should use strings.EqualFold instead",
72 report.Fixes(edit.Fix("Replace with strings.EqualFold", edit.ReplaceWithNode(pass.Fset, node, rn))))
73 }
74 return nil, nil
75 }