Debian Codegraph @

gopls/internal/golang/lines.go

raw symbols SCIP
1 // Copyright 2024 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 golang
6
7 // This file defines refactorings for splitting lists of elements
8 // (arguments, literals, etc) across multiple lines, and joining
9 // them into a single line.
10
11 import (
12 "bytes"
13 "go/ast"
14 "go/token"
15 "slices"
16 "sort"
17 "strings"
18
19 "golang.org/x/tools/go/analysis"
20 "golang.org/x/tools/go/ast/edge"
21 "golang.org/x/tools/go/ast/inspector"
22 "golang.org/x/tools/gopls/internal/cache"
23 "golang.org/x/tools/gopls/internal/cache/parsego"
24 "golang.org/x/tools/gopls/internal/util/safetoken"
25 )
26
27 // canSplitLines checks whether we can split lists of elements inside
28 // an enclosing curly bracket/parens into separate lines.
29 func canSplitLines(curFile inspector.Cursor, fset *token.FileSet, start, end token.Pos) (string, bool, error) {
30 itemType, items, comments, _, _, _ := findSplitJoinTarget(fset, curFile, nil, start, end)
31 if itemType == "" {
32 return "", false, nil
33 }
34
35 if !canSplitJoinLines(items, comments) {
36 return "", false, nil
37 }
38
39 for i := 1; i < len(items); i++ {
40 prevLine := safetoken.EndPosition(fset, items[i-1].End()).Line
41 curLine := safetoken.StartPosition(fset, items[i].Pos()).Line
42 if prevLine == curLine {
43 return "Split " + itemType + " into separate lines", true, nil
44 }
45 }
46
47 return "", false, nil
48 }
49
50 // canJoinLines checks whether we can join lists of elements inside an
51 // enclosing curly bracket/parens into a single line.
52 func canJoinLines(curFile inspector.Cursor, fset *token.FileSet, start, end token.Pos) (string, bool, error) {
53 itemType, items, comments, _, _, _ := findSplitJoinTarget(fset, curFile, nil, start, end)
54 if itemType == "" {
55 return "", false, nil
56 }
57
58 if !canSplitJoinLines(items, comments) {
59 return "", false, nil
60 }
61
62 for i := 1; i < len(items); i++ {
63 prevLine := safetoken.EndPosition(fset, items[i-1].End()).Line
64 curLine := safetoken.StartPosition(fset, items[i].Pos()).Line
65 if prevLine != curLine {
66 return "Join " + itemType + " into one line", true, nil
67 }
68 }
69
70 return "", false, nil
71 }
72
73 // canSplitJoinLines determines whether we should split/join the lines or not.
74 func canSplitJoinLines(items []ast.Node, comments []*ast.CommentGroup) bool {
75 if len(items) <= 1 {
76 return false
77 }
78
79 for _, cg := range comments {
80 if !strings.HasPrefix(cg.List[0].Text, "/*") {
81 return false // can't split/join lists containing "//" comments
82 }
83 }
84
85 return true
86 }
87
88 // splitLines is a singleFile fixer.
89 func splitLines(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) {
90 fset := pkg.FileSet()
91 itemType, items, comments, indent, braceOpen, braceClose := findSplitJoinTarget(fset, pgf.Cursor(), pgf.Src, start, end)
92 if itemType == "" {
93 return nil, nil, nil // no fix available
94 }
95
96 return fset, processLines(fset, items, comments, pgf.Src, braceOpen, braceClose, ",\n", "\n", ",\n"+indent, indent+"\t"), nil
97 }
98
99 // joinLines is a singleFile fixer.
100 func joinLines(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) {
101 fset := pkg.FileSet()
102 itemType, items, comments, _, braceOpen, braceClose := findSplitJoinTarget(fset, pgf.Cursor(), pgf.Src, start, end)
103 if itemType == "" {
104 return nil, nil, nil // no fix available
105 }
106
107 return fset, processLines(fset, items, comments, pgf.Src, braceOpen, braceClose, ", ", "", "", ""), nil
108 }
109
110 // processLines is the common operation for both split and join lines because this split/join operation is
111 // essentially a transformation of the separating whitespace.
112 func processLines(fset *token.FileSet, items []ast.Node, comments []*ast.CommentGroup, src []byte, braceOpen, braceClose token.Pos, sep, prefix, suffix, indent string) *analysis.SuggestedFix {
113 nodes := slices.Clone(items)
114
115 // box *ast.CommentGroup to ast.Node for easier processing later.
116 for _, cg := range comments {
117 nodes = append(nodes, cg)
118 }
119
120 // Sort to interleave comments and nodes.
121 sort.Slice(nodes, func(i, j int) bool {
122 return nodes[i].Pos() < nodes[j].Pos()
123 })
124
125 edits := []analysis.TextEdit{
126 {
127 Pos: token.Pos(int(braceOpen) + len("{")),
128 End: nodes[0].Pos(),
129 NewText: []byte(prefix + indent),
130 },
131 {
132 Pos: nodes[len(nodes)-1].End(),
133 End: braceClose,
134 NewText: []byte(suffix),
135 },
136 }
137
138 for i := 1; i < len(nodes); i++ {
139 pos, end := nodes[i-1].End(), nodes[i].Pos()
140 if pos > end {
141 // this will happen if we have a /*-style comment inside of a Field
142 // e.g. `a /*comment here */ int`
143 //
144 // we will ignore as we only care about finding the field delimiter.
145 continue
146 }
147
148 // at this point, the `,` token in between 2 nodes here must be the field delimiter.
149 posOffset := safetoken.EndPosition(fset, pos).Offset
150 endOffset := safetoken.StartPosition(fset, end).Offset
151 if bytes.IndexByte(src[posOffset:endOffset], ',') == -1 {
152 // nodes[i] or nodes[i-1] is a comment hence no delimiter in between
153 // in such case, do nothing.
154 continue
155 }
156
157 edits = append(edits, analysis.TextEdit{Pos: pos, End: end, NewText: []byte(sep + indent)})
158
159 // Print the Ellipsis if we synthesized one earlier.
160 if is[*ast.Ellipsis](nodes[i]) {
161 edits = append(edits, analysis.TextEdit{
162 Pos: nodes[i].End(),
163 End: nodes[i].End(),
164 NewText: []byte("..."),
165 })
166 }
167 }
168
169 return &analysis.SuggestedFix{TextEdits: edits}
170 }
171
172 // findSplitJoinTarget returns the first curly bracket/parens that encloses the current cursor.
173 func findSplitJoinTarget(fset *token.FileSet, curFile inspector.Cursor, src []byte, start, end token.Pos) (itemType string, items []ast.Node, comments []*ast.CommentGroup, indent string, open, close token.Pos) {
174
175 findTarget := func() (targetType string, target ast.Node, open, close token.Pos) {
176 cur, _ := curFile.FindByPos(start, end)
177 for cur := range cur.Enclosing() {
178 // TODO: do cur = enclosingUnparen(cur) first, once CL 701035 lands.
179 switch cur.ParentEdgeKind() {
180 // params or results of func signature
181 // Note:
182 // - each ast.Field (e.g. "x, y, z int") is considered a single item.
183 // - splitting Params and Results lists is not usually good style.
184 case edge.FuncType_Params:
185 p := cur.Node().(*ast.FieldList)
186 return "parameters", p, p.Opening, p.Closing
187 case edge.FuncType_Results:
188 r := cur.Node().(*ast.FieldList)
189 if !r.Opening.IsValid() {
190 continue
191 }
192 return "results", r, r.Opening, r.Closing
193 case edge.CallExpr_Args: // f(a, b, c)
194 node := cur.Parent().Node().(*ast.CallExpr)
195 return "arguments", node, node.Lparen, node.Rparen
196 case edge.CompositeLit_Elts: // T{a, b, c}
197 node := cur.Parent().Node().(*ast.CompositeLit)
198 return "elements", node, node.Lbrace, node.Rbrace
199 }
200 }
201 return "", nil, 0, 0
202 }
203
204 targetType, targetNode, open, close := findTarget()
205 if targetType == "" {
206 return "", nil, nil, "", 0, 0
207 }
208
209 switch node := targetNode.(type) {
210 case *ast.FieldList:
211 for _, field := range node.List {
212 items = append(items, field)
213 }
214 case *ast.CallExpr:
215 for _, arg := range node.Args {
216 items = append(items, arg)
217 }
218
219 // Preserve "..." by wrapping the last
220 // argument in an Ellipsis node
221 // with the same Pos/End as the argument.
222 // See corresponding logic in processLines.
223 if node.Ellipsis.IsValid() {
224 last := &items[len(items)-1]
225 *last = &ast.Ellipsis{
226 Ellipsis: (*last).Pos(), // determines Ellipsis.Pos()
227 Elt: (*last).(ast.Expr), // determines Ellipsis.End()
228 }
229 }
230 case *ast.CompositeLit:
231 for _, arg := range node.Elts {
232 items = append(items, arg)
233 }
234 }
235
236 // preserve comments separately as it's not part of the targetNode AST.
237 file := curFile.Node().(*ast.File)
238 for _, cg := range file.Comments {
239 if open <= cg.Pos() && cg.Pos() < close {
240 comments = append(comments, cg)
241 }
242 }
243
244 // indent is the leading whitespace before the opening curly bracket/paren.
245 //
246 // in case where we don't have access to src yet i.e. src == nil
247 // it's fine to return incorrect indent because we don't need it yet.
248 indent = ""
249 if len(src) > 0 {
250 var pos token.Pos
251 switch node := targetNode.(type) {
252 case *ast.FieldList:
253 pos = node.Opening
254 case *ast.CallExpr:
255 pos = node.Lparen
256 case *ast.CompositeLit:
257 pos = node.Lbrace
258 }
259
260 split := bytes.Split(src, []byte("\n"))
261 targetLineNumber := safetoken.StartPosition(fset, pos).Line
262 firstLine := string(split[targetLineNumber-1])
263 trimmed := strings.TrimSpace(string(firstLine))
264 indent = firstLine[:strings.Index(firstLine, trimmed)]
265 }
266
267 return targetType, items, comments, indent, open, close
268 }