Debian Codegraph @

gopls/internal/protocol/mapper.go

raw symbols SCIP
1 // Copyright 2023 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 protocol
6
7 // This file defines Mapper, which wraps a file content buffer
8 // ([]byte) and provides efficient conversion between every kind of
9 // position representation.
10 //
11 // gopls uses four main representations of position:
12 //
13 // 1. byte offsets, e.g. (start, end int), starting from zero.
14 //
15 // 2. go/token notation. Use these types when interacting directly
16 // with the go/* syntax packages:
17 //
18 // token.Pos
19 // token.FileSet
20 // token.File
21 //
22 // Because File.Offset and File.Pos panic on invalid inputs,
23 // we do not call them directly and instead use the safetoken package
24 // for these conversions. This is enforced by a static check.
25 //
26 // Beware also that the methods of token.File have two bugs for which
27 // safetoken contains workarounds:
28 // - #57490, whereby the parser may create ast.Nodes during error
29 // recovery whose computed positions are out of bounds (EOF+1).
30 // - #41029, whereby the wrong line number is returned for the EOF position.
31 //
32 // 3. the cmd package.
33 //
34 // cmd.point = (line, col8, offset).
35 // cmd.Span = (uri URI, start, end cmd.point)
36 //
37 // Line and column are 1-based.
38 // Columns are measured in bytes (UTF-8 codes).
39 // All fields are optional.
40 //
41 // These types are useful as intermediate conversions of validated
42 // ranges. Since their fields are optional they are also useful for
43 // parsing user-provided positions (e.g. in the CLI) before we have
44 // access to file contents.
45 //
46 // 4. protocol, the LSP RPC message format.
47 //
48 // protocol.Position = (Line, Character uint32)
49 // protocol.Range = (start, end Position)
50 // protocol.Location = (URI, protocol.Range)
51 //
52 // Line and Character are 0-based.
53 // Characters (columns) are measured in UTF-16 codes.
54 //
55 // protocol.Mapper holds the (URI, Content) of a file, enabling
56 // efficient mapping between byte offsets, cmd ranges, and
57 // protocol ranges.
58
59 import (
60 "bytes"
61 "fmt"
62 "go/ast"
63 "go/token"
64 "sort"
65 "sync"
66 "unicode/utf8"
67
68 "golang.org/x/tools/gopls/internal/util/bug"
69 "golang.org/x/tools/gopls/internal/util/safetoken"
70 )
71
72 // A Mapper wraps the content of a file and provides mapping
73 // between byte offsets and notations of position such as:
74 //
75 // - (line, col8) pairs, where col8 is a 1-based UTF-8 column number
76 // (bytes), as used by the go/token and cmd packages.
77 //
78 // - (line, col16) pairs, where col16 is a 1-based UTF-16 column
79 // number, as used by the LSP protocol.
80 //
81 // All conversion methods are named "FromTo", where From and To are the two types.
82 // For example, the PointPosition method converts from a Point to a Position.
83 //
84 // Mapper does not intrinsically depend on go/token-based
85 // representations. Use safetoken to map between token.Pos <=> byte
86 // offsets, or the convenience methods such as PosPosition,
87 // NodePosition, or NodeRange.
88 //
89 // See overview comments at top of this file.
90 type Mapper struct {
91 URI DocumentURI
92 Content []byte
93
94 // Line-number information is requested only for a tiny
95 // fraction of Mappers, so we compute it lazily.
96 // Call initLines() before accessing fields below.
97 linesOnce sync.Once
98 lineStart []int // byte offset of start of ith line (0-based); last=EOF iff \n-terminated
99 nonASCII bool
100
101 // TODO(adonovan): adding an extra lineStart entry for EOF
102 // might simplify every method that accesses it. Try it out.
103 }
104
105 // NewMapper creates a new mapper for the given URI and content.
106 func NewMapper(uri DocumentURI, content []byte) *Mapper {
107 return &Mapper{URI: uri, Content: content}
108 }
109
110 // initLines populates the lineStart table.
111 func (m *Mapper) initLines() {
112 m.linesOnce.Do(func() {
113 nlines := bytes.Count(m.Content, []byte("\n"))
114 m.lineStart = make([]int, 1, nlines+1) // initially []int{0}
115 for offset, b := range m.Content {
116 if b == '\n' {
117 m.lineStart = append(m.lineStart, offset+1)
118 }
119 if b >= utf8.RuneSelf {
120 m.nonASCII = true
121 }
122 }
123 })
124 }
125
126 // LineCol8Position converts a valid line and UTF-8 column number,
127 // both 1-based, to a protocol (UTF-16) position.
128 func (m *Mapper) LineCol8Position(line, col8 int) (Position, error) {
129 // Report a bug for inputs that are invalid for any file content.
130 if line < 1 {
131 return Position{}, bug.Errorf("invalid 1-based line number: %d", line)
132 }
133 if col8 < 1 {
134 return Position{}, bug.Errorf("invalid 1-based column number: %d", col8)
135 }
136
137 m.initLines()
138 line0 := line - 1 // 0-based
139 if !(0 <= line0 && line0 < len(m.lineStart)) {
140 return Position{}, fmt.Errorf("line number %d out of range (max %d)", line, len(m.lineStart))
141 }
142
143 // content[start:end] is the preceding partial line.
144 start := m.lineStart[line0]
145 end := start + col8 - 1
146
147 // Validate column.
148 if end > len(m.Content) {
149 return Position{}, fmt.Errorf("column is beyond end of file")
150 } else if line0+1 < len(m.lineStart) && end >= m.lineStart[line0+1] {
151 return Position{}, fmt.Errorf("column is beyond end of line")
152 }
153
154 char := UTF16Len(m.Content[start:end])
155 return Position{Line: uint32(line0), Character: uint32(char)}, nil
156 }
157
158 // -- conversions from byte offsets --
159
160 // OffsetLocation converts a byte-offset interval to a protocol (UTF-16) location.
161 func (m *Mapper) OffsetLocation(start, end int) (Location, error) {
162 rng, err := m.OffsetRange(start, end)
163 if err != nil {
164 return Location{}, err
165 }
166 return m.URI.Location(rng), nil
167 }
168
169 // OffsetRange converts a byte-offset interval to a protocol (UTF-16) range.
170 func (m *Mapper) OffsetRange(start, end int) (Range, error) {
171 if start > end {
172 return Range{}, fmt.Errorf("start offset (%d) > end (%d)", start, end)
173 }
174 startPosition, err := m.OffsetPosition(start)
175 if err != nil {
176 return Range{}, fmt.Errorf("start: %v", err)
177 }
178 endPosition, err := m.OffsetPosition(end)
179 if err != nil {
180 return Range{}, fmt.Errorf("end: %v", err)
181 }
182 return Range{Start: startPosition, End: endPosition}, nil
183 }
184
185 // OffsetPosition converts a byte offset to a protocol (UTF-16) position.
186 func (m *Mapper) OffsetPosition(offset int) (Position, error) {
187 if !(0 <= offset && offset <= len(m.Content)) {
188 return Position{}, fmt.Errorf("invalid offset %d (want 0-%d)", offset, len(m.Content))
189 }
190 // No error may be returned after this point,
191 // even if the offset does not fall at a rune boundary.
192
193 line, col16 := m.lineCol16(offset)
194 return Position{Line: uint32(line), Character: uint32(col16)}, nil
195 }
196
197 // lineCol16 converts a valid byte offset to line and UTF-16 column numbers, both 0-based.
198 func (m *Mapper) lineCol16(offset int) (int, int) {
199 line, start, cr := m.line(offset)
200 var col16 int
201 if m.nonASCII {
202 col16 = UTF16Len(m.Content[start:offset])
203 } else {
204 col16 = offset - start
205 }
206 if cr {
207 col16-- // retreat from \r at line end
208 }
209 return line, col16
210 }
211
212 // OffsetLineCol8 converts a valid byte offset to line and UTF-8 column numbers, both 1-based.
213 func (m *Mapper) OffsetLineCol8(offset int) (int, int) {
214 line, start, cr := m.line(offset)
215 col8 := offset - start
216 if cr {
217 col8-- // retreat from \r at line end
218 }
219 return line + 1, col8 + 1
220 }
221
222 // line returns:
223 // - the 0-based index of the line that encloses the (valid) byte offset;
224 // - the start offset of that line; and
225 // - whether the offset denotes a carriage return (\r) at line end.
226 func (m *Mapper) line(offset int) (int, int, bool) {
227 m.initLines()
228 // In effect, binary search returns a 1-based result.
229 line := sort.Search(len(m.lineStart), func(i int) bool {
230 return offset < m.lineStart[i]
231 })
232
233 // Adjustment for line-endings: \r|\n is the same as |\r\n.
234 var eol int
235 if line == len(m.lineStart) {
236 eol = len(m.Content) // EOF
237 } else {
238 eol = m.lineStart[line] - 1
239 }
240 cr := offset == eol && offset > 0 && m.Content[offset-1] == '\r'
241
242 line-- // 0-based
243
244 return line, m.lineStart[line], cr
245 }
246
247 // -- conversions from protocol (UTF-16) domain --
248
249 // RangeOffsets converts a protocol (UTF-16) range to start/end byte offsets.
250 func (m *Mapper) RangeOffsets(r Range) (int, int, error) {
251 start, err := m.PositionOffset(r.Start)
252 if err != nil {
253 return 0, 0, err
254 }
255 end, err := m.PositionOffset(r.End)
256 if err != nil {
257 return 0, 0, err
258 }
259 if start > end {
260 return 0, 0, fmt.Errorf("start (offset %d) > end (offset %d)", start, end)
261 }
262 return start, end, nil
263 }
264
265 // PositionOffset converts a protocol (UTF-16) position to a byte offset.
266 func (m *Mapper) PositionOffset(p Position) (int, error) {
267 m.initLines()
268
269 // Validate line number.
270 if p.Line > uint32(len(m.lineStart)) {
271 return 0, fmt.Errorf("line number %d out of range 0-%d", p.Line, len(m.lineStart))
272 } else if p.Line == uint32(len(m.lineStart)) {
273 if p.Character == 0 {
274 return len(m.Content), nil // EOF
275 }
276 return 0, fmt.Errorf("column is beyond end of file")
277 }
278
279 offset := m.lineStart[p.Line]
280 content := m.Content[offset:] // rest of file from start of enclosing line
281
282 // Advance bytes up to the required number of UTF-16 codes.
283 col8 := 0
284 for col16 := 0; col16 < int(p.Character); col16++ {
285 r, sz := utf8.DecodeRune(content)
286 if sz == 0 {
287 return 0, fmt.Errorf("column is beyond end of file")
288 }
289 if r == '\n' {
290 return 0, fmt.Errorf("column is beyond end of line")
291 }
292 if sz == 1 && r == utf8.RuneError {
293 return 0, fmt.Errorf("buffer contains invalid UTF-8 text")
294 }
295 content = content[sz:]
296
297 if r >= 0x10000 {
298 col16++ // rune was encoded by a pair of surrogate UTF-16 codes
299
300 if col16 == int(p.Character) {
301 break // requested position is in the middle of a rune
302 }
303 }
304 col8 += sz
305 }
306 return offset + col8, nil
307 }
308
309 // -- go/token domain convenience methods --
310
311 // PosPosition converts a token pos to a protocol (UTF-16) position.
312 func (m *Mapper) PosPosition(tf *token.File, pos token.Pos) (Position, error) {
313 offset, err := safetoken.Offset(tf, pos)
314 if err != nil {
315 return Position{}, err
316 }
317 return m.OffsetPosition(offset)
318 }
319
320 // PosLocation converts a token range to a protocol (UTF-16) location.
321 func (m *Mapper) PosLocation(tf *token.File, start, end token.Pos) (Location, error) {
322 startOffset, endOffset, err := safetoken.Offsets(tf, start, end)
323 if err != nil {
324 return Location{}, err
325 }
326 rng, err := m.OffsetRange(startOffset, endOffset)
327 if err != nil {
328 return Location{}, err
329 }
330 return m.URI.Location(rng), nil
331 }
332
333 // PosRange converts a token range to a protocol (UTF-16) range.
334 func (m *Mapper) PosRange(tf *token.File, start, end token.Pos) (Range, error) {
335 startOffset, endOffset, err := safetoken.Offsets(tf, start, end)
336 if err != nil {
337 return Range{}, err
338 }
339 return m.OffsetRange(startOffset, endOffset)
340 }
341
342 // PosText returns the source text for the token range.
343 func (m *Mapper) PosText(tf *token.File, start, end token.Pos) ([]byte, error) {
344 startOffset, endOffset, err := safetoken.Offsets(tf, start, end)
345 if err != nil {
346 return nil, err
347 }
348 return m.Content[startOffset:endOffset], nil
349 }
350
351 // NodeRange converts a syntax node range to a protocol (UTF-16) range.
352 func (m *Mapper) NodeRange(tf *token.File, node ast.Node) (Range, error) {
353 return m.PosRange(tf, node.Pos(), node.End())
354 }
355
356 // NodeText returns the source text for syntax node range.
357 func (m *Mapper) NodeText(tf *token.File, node ast.Node) ([]byte, error) {
358 return m.PosText(tf, node.Pos(), node.End())
359 }
360
361 // LocationTextDocumentPositionParams converts its argument to its result.
362 func LocationTextDocumentPositionParams(loc Location) TextDocumentPositionParams {
363 return TextDocumentPositionParams{
364 TextDocument: TextDocumentIdentifier{URI: loc.URI},
365 Range: loc.Range,
366 Position: loc.Range.Start, // not used
367 }
368 }