Debian Codegraph @

staticcheck/sa6006/sa6006.go

raw
1 package sa6006
2
3 import (
4 "go/ast"
5
6 "honnef.co/go/tools/analysis/code"
7 "honnef.co/go/tools/analysis/lint"
8 "honnef.co/go/tools/analysis/report"
9 "honnef.co/go/tools/pattern"
10
11 "golang.org/x/tools/go/analysis"
12 )
13
14 var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
15 Analyzer: &analysis.Analyzer{
16 Name: "SA6006",
17 Run: run,
18 Requires: code.RequiredAnalyzers,
19 },
20 Doc: &lint.RawDocumentation{
21 Title: `Using io.WriteString to write \'[]byte\'`,
22 Text: `Using io.WriteString to write a slice of bytes, as in
23
24 io.WriteString(w, string(b))
25
26 is both unnecessary and inefficient. Converting from \'[]byte\' to \'string\'
27 has to allocate and copy the data, and we could simply use \'w.Write(b)\'
28 instead.`,
29
30 Since: "2024.1",
31 },
32 })
33
34 var Analyzer = SCAnalyzer.Analyzer
35
36 var ioWriteStringConversion = pattern.MustParse(`(CallExpr (Symbol "io.WriteString") [_ (CallExpr (Builtin "string") [arg])])`)
37
38 func run(pass *analysis.Pass) (any, error) {
39 for node, m := range code.Matches(pass, ioWriteStringConversion) {
40 if !code.IsOfStringConvertibleByteSlice(pass, m.State["arg"].(ast.Expr)) {
41 continue
42 }
43 report.Report(pass, node, "use io.Writer.Write instead of converting from []byte to string to use io.WriteString")
44 }
45 return nil, nil
46 }