Debian Codegraph @

gopls/internal/golang/folding_range.go

raw symbols SCIP
1 // Copyright 2019 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 import (
8 "cmp"
9 "context"
10 "go/ast"
11 "go/token"
12 "slices"
13 "strings"
14
15 "golang.org/x/tools/gopls/internal/cache"
16 "golang.org/x/tools/gopls/internal/cache/parsego"
17 "golang.org/x/tools/gopls/internal/file"
18 "golang.org/x/tools/gopls/internal/protocol"
19 "golang.org/x/tools/gopls/internal/util/bug"
20 "golang.org/x/tools/gopls/internal/util/safetoken"
21 )
22
23 // FoldingRange gets all of the folding range for f.
24 func FoldingRange(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, lineFoldingOnly bool) ([]protocol.FoldingRange, error) {
25 // TODO(suzmue): consider limiting the number of folding ranges returned, and
26 // implement a way to prioritize folding ranges in that case.
27 pgf, err := snapshot.ParseGo(ctx, fh, parsego.Full)
28 if err != nil {
29 return nil, err
30 }
31
32 // With parse errors, we wouldn't be able to produce accurate folding info.
33 // LSP protocol (3.16) currently does not have a way to handle this case
34 // (https://github.com/microsoft/language-server-protocol/issues/1200).
35 // We cannot return an error either because we are afraid some editors
36 // may not handle errors nicely. As a workaround, we now return an empty
37 // result and let the client handle this case by double check the file
38 // contents (i.e. if the file is not empty and the folding range result
39 // is empty, raise an internal error).
40 if pgf.ParseErr != nil {
41 return nil, nil
42 }
43
44 // Get folding ranges for comments separately as they are not walked by ast.Inspect.
45 ranges := commentsFoldingRange(pgf)
46
47 // Walk the ast and collect folding ranges.
48 filter := []ast.Node{
49 (*ast.BasicLit)(nil),
50 (*ast.BlockStmt)(nil),
51 (*ast.CallExpr)(nil),
52 (*ast.CaseClause)(nil),
53 (*ast.CommClause)(nil),
54 (*ast.CompositeLit)(nil),
55 (*ast.FieldList)(nil),
56 (*ast.GenDecl)(nil),
57 }
58 for cur := range pgf.Cursor().Preorder(filter...) {
59 var kind protocol.FoldingRangeKind
60 // start and end define the range of content to fold away.
61 var start, end token.Pos
62 switch n := cur.Node().(type) {
63 case *ast.BlockStmt:
64 // Fold between positions of or lines between "{" and "}".
65 start, end = bracketedFoldingRange(pgf, n.Lbrace, n.Rbrace, lineFoldingOnly)
66
67 case *ast.CaseClause:
68 // Fold from position of ":" to end.
69 start, end = n.Colon+1, n.End()
70
71 case *ast.CommClause:
72 // Fold from position of ":" to end.
73 start, end = n.Colon+1, n.End()
74
75 case *ast.CallExpr:
76 // Fold between positions of or lines between "(" and ")".
77 start, end = bracketedFoldingRange(pgf, n.Lparen, n.Rparen, lineFoldingOnly)
78
79 case *ast.FieldList:
80 // Fold between positions of or lines between opening parenthesis/brace and closing parenthesis/brace.
81 start, end = bracketedFoldingRange(pgf, n.Opening, n.Closing, lineFoldingOnly)
82
83 case *ast.GenDecl:
84 // If this is an import declaration, set the kind to be protocol.Imports.
85 if n.Tok == token.IMPORT {
86 kind = protocol.Imports
87 }
88 // Fold between positions of or lines between "(" and ")".
89 start, end = bracketedFoldingRange(pgf, n.Lparen, n.Rparen, lineFoldingOnly)
90
91 case *ast.BasicLit:
92 // Fold raw string literals from position of "`" to position of "`".
93 if n.Kind == token.STRING && len(n.Value) >= 2 && n.Value[0] == '`' && n.Value[len(n.Value)-1] == '`' {
94 start, end = n.Pos(), n.End()
95 }
96
97 case *ast.CompositeLit:
98 // Fold between positions of or lines between "{" and "}".
99 start, end = bracketedFoldingRange(pgf, n.Lbrace, n.Rbrace, lineFoldingOnly)
100
101 default:
102 panic(n)
103 }
104
105 // Check that folding positions are valid.
106 if !start.IsValid() || !end.IsValid() {
107 continue
108 }
109 if start == end {
110 // Nothing to fold.
111 continue
112 }
113 // in line folding mode, do not fold if the start and end lines are the same.
114 if lineFoldingOnly && safetoken.Line(pgf.Tok, start) == safetoken.Line(pgf.Tok, end) {
115 continue
116 }
117 rng, err := pgf.PosRange(start, end)
118 if err != nil {
119 bug.Reportf("failed to create range: %s", err) // can't happen
120 continue
121 }
122 ranges = append(ranges, foldingRange(kind, rng))
123 }
124
125 // Sort by start position.
126 slices.SortFunc(ranges, func(x, y protocol.FoldingRange) int {
127 if d := cmp.Compare(*x.StartLine, *y.StartLine); d != 0 {
128 return d
129 }
130 return cmp.Compare(*x.StartCharacter, *y.StartCharacter)
131 })
132
133 return ranges, nil
134 }
135
136 // bracketedFoldingRange returns the folding range for nodes with parentheses/braces/brackets
137 // that potentially can take up multiple lines.
138 func bracketedFoldingRange(pgf *parsego.File, open, close token.Pos, lineFoldingOnly bool) (token.Pos, token.Pos) {
139 if !open.IsValid() || !close.IsValid() {
140 return token.NoPos, token.NoPos
141 }
142 if open+1 == close {
143 // Nothing to fold: (), {} or [].
144 return token.NoPos, token.NoPos
145 }
146
147 if !lineFoldingOnly {
148 return open + 1, close
149 }
150
151 // Clients with "LineFoldingOnly" set to true can fold only full lines.
152 // This is also checked in the caller.
153 //
154 // Clients that support folding ranges can display them in various ways
155 // (e.g., how are folding ranges marked? is the final line displayed?).
156 // The most common client
157 // is vscode, which displays the first line followed by ..., and then does not
158 // display any other lines in the range, but other clients might also display
159 // final line of the range. For example, the following code
160 //
161 // var x = []string{"a",
162 // "b",
163 // "c" }
164 //
165 // can be folded (in vscode) to
166 //
167 // var x = []string{"a", ...
168 //
169 // or in some other client
170 //
171 // var x = []string{"a", ...
172 // "c" }
173 //
174 // This code displays the final line containing ),},], but not the closing quote
175 // of a multi-line string
176
177 prevLineEnd := pgf.Tok.LineStart(safetoken.Line(pgf.Tok, close)) - 1 // there was a previous line
178 if prevLineEnd <= open { // all the same line
179 return token.NoPos, token.NoPos
180 }
181 return open + 1, prevLineEnd
182 }
183
184 // commentsFoldingRange returns the folding ranges for all comment blocks in file.
185 // The folding range starts at the end of the first line of the comment block, and ends at the end of the
186 // comment block and has kind protocol.Comment.
187 func commentsFoldingRange(pgf *parsego.File) (comments []protocol.FoldingRange) {
188 tokFile := pgf.Tok
189 for _, commentGrp := range pgf.File.Comments {
190 startGrpLine, endGrpLine := safetoken.Line(tokFile, commentGrp.Pos()), safetoken.Line(tokFile, commentGrp.End())
191 if startGrpLine == endGrpLine {
192 // Don't fold single line comments.
193 continue
194 }
195
196 firstComment := commentGrp.List[0]
197 startPos, endLinePos := firstComment.Pos(), firstComment.End()
198 startCmmntLine, endCmmntLine := safetoken.Line(tokFile, startPos), safetoken.Line(tokFile, endLinePos)
199 if startCmmntLine != endCmmntLine {
200 // If the first comment spans multiple lines, then we want to have the
201 // folding range start at the end of the first line.
202 endLinePos = token.Pos(int(startPos) + len(strings.Split(firstComment.Text, "\n")[0]))
203 }
204 rng, err := pgf.PosRange(endLinePos, commentGrp.End())
205 if err != nil {
206 bug.Reportf("failed to create mapped range: %s", err) // can't happen
207 continue
208 }
209 // Fold from the end of the first line comment to the end of the comment block.
210 comments = append(comments, foldingRange(protocol.Comment, rng))
211 }
212 return comments
213 }
214
215 func foldingRange(kind protocol.FoldingRangeKind, rng protocol.Range) protocol.FoldingRange {
216 return protocol.FoldingRange{
217 // (I guess LSP doesn't use a protocol.Range here
218 // because missing means something different from zero.)
219 StartLine: varOf(rng.Start.Line),
220 StartCharacter: varOf(rng.Start.Character),
221 EndLine: varOf(rng.End.Line),
222 EndCharacter: varOf(rng.End.Character),
223 Kind: string(kind),
224 }
225 }
226
227 // varOf returns a new variable whose value is x.
228 func varOf[T any](x T) *T { return &x }