Debian Codegraph @

gopls/internal/analysis/writestring/writestring.go

raw symbols SCIP
1 // Copyright 2026 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 writestring defines an Analyzer that detects
6 // inefficient string concatenation in uses of WriteString.
7 package writestring
8
9 import (
10 _ "embed"
11 "fmt"
12 "go/ast"
13 "go/token"
14 "go/types"
15 "strings"
16
17 "golang.org/x/tools/go/analysis"
18 "golang.org/x/tools/go/analysis/passes/inspect"
19 "golang.org/x/tools/go/ast/edge"
20 "golang.org/x/tools/go/ast/inspector"
21 "golang.org/x/tools/go/types/typeutil"
22 "golang.org/x/tools/internal/analysis/analyzerutil"
23 "golang.org/x/tools/internal/astutil"
24 "golang.org/x/tools/internal/typesinternal"
25 )
26
27 //go:embed doc.go
28 var doc string
29
30 var Analyzer = &analysis.Analyzer{
31 Name: "writestring",
32 Doc: analyzerutil.MustExtractDoc(doc, "writestring"),
33 URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/writestring",
34 Requires: []*analysis.Analyzer{inspect.Analyzer},
35 Run: run,
36 }
37
38 func run(pass *analysis.Pass) (any, error) {
39 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
40
41 for curCall := range inspect.Root().Preorder((*ast.CallExpr)(nil)) {
42 call := curCall.Node().(*ast.CallExpr)
43 info := pass.TypesInfo
44 callee := typeutil.Callee(info, call)
45 if callee == nil || callee.Name() != "WriteString" {
46 continue
47 }
48
49 // We intervene only for io.Writer types where we know that WriteString
50 // is cheap and distributes over string concatenation.
51 // (This is not the case for, say, file descriptors, where each write
52 // is expensive, and splitting one UDP write into two is a behavior change.)
53 // TODO(mkalil): This doesn't detect calls to aliases of w.WriteString.
54 // I think it's okay to skip that case because it's uncommon and also
55 // would increase the complexity to determine the type of the writer.
56 if !(typesinternal.IsMethodNamed(callee, "strings", "Builder", "WriteString") ||
57 typesinternal.IsMethodNamed(callee, "bytes", "Buffer", "WriteString") ||
58 typesinternal.IsMethodNamed(callee, "bufio", "Writer", "WriteString") ||
59 typesinternal.IsMethodNamed(callee, "hash/maphash", "Hash", "WriteString")) {
60 continue
61 }
62
63 // curCall must be a standalone statement. We skip calls used in
64 // assignments, control flow expressions, or defer/go statements, since
65 // splitting them requires complex rewriting of the surrounding logic.
66 if curCall.ParentEdgeKind() != edge.ExprStmt_X {
67 continue
68 }
69
70 // Check that the receiver "w" in the call to w.WriteString has no side
71 // effects. For example, if the receiver involves some function call F,
72 // we cannot suggest a fix because duplicate calls to F may result in
73 // unintended behavior.
74 // returnsBuffer().WriteString(...) --> reject
75 // a.B.w.WriteString(...) --> ok
76 if !typesinternal.NoEffects(info, call.Fun) {
77 continue
78 }
79
80 if len(call.Args) != 1 {
81 continue // can't happen
82 }
83 arg := call.Args[0]
84 if _, ok := arg.(*ast.BinaryExpr); !ok {
85 continue
86 }
87
88 operands := stringConcatenands(info, arg)
89 if len(operands) < 2 {
90 continue
91 }
92
93 // Format the separate WriteString calls.
94 var newStmts []string
95 for _, operand := range operands {
96 stmt := fmt.Sprintf("%s(%s)",
97 astutil.Format(pass.Fset, call.Fun),
98 astutil.Format(pass.Fset, operand))
99 newStmts = append(newStmts, stmt)
100 }
101 replacement := strings.Join(newStmts, ";")
102
103 pass.Report(analysis.Diagnostic{
104 Pos: call.Pos(),
105 End: call.End(),
106 Message: "Inefficient string concatenation in call to WriteString",
107 SuggestedFixes: []analysis.SuggestedFix{{
108 Message: "Split into separate WriteString calls",
109 TextEdits: []analysis.TextEdit{{
110 Pos: call.Pos(),
111 End: call.End(),
112 NewText: []byte(replacement),
113 }},
114 }},
115 })
116 }
117 return nil, nil
118 }
119
120 // stringConcatenands flattens a string concatenation expression expr
121 // (e.g., "a" + "b" + c) into a sequence of individual operands. It combines
122 // adjacent constants or basic literals, whose combined value evaluates to a
123 // constant, into a single expression. For example, "a" + k + v would return
124 // [("a" + k), v]. Writing k and "a" separately would be a de-optimization, as
125 // we already evaluate the value of this expression at compile time. If the
126 // expression cannot be safely flattened, it returns nil.
127 func stringConcatenands(info *types.Info, expr ast.Expr) (operands []ast.Expr) {
128 if info.Types[expr].Value != nil {
129 return []ast.Expr{expr}
130 }
131 if bin, ok := ast.Unparen(expr).(*ast.BinaryExpr); ok {
132 if bin.Op != token.ADD {
133 // Valid Go code only allows string concatenation via the add
134 // operator.
135 panic("invalid concatenation operator")
136 }
137 opsX := stringConcatenands(info, bin.X)
138 if opsX == nil {
139 return nil
140 }
141 opsY := stringConcatenands(info, bin.Y)
142 if opsY == nil {
143 return nil
144 }
145 return append(opsX, opsY...)
146 }
147 return []ast.Expr{expr}
148 }