Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix: lsp handle textDocument/didChange Range in UTF-16 (#13636)

h3n4lc2a3d390d63a
diff --git a/backend/api/lsp/completion.go b/backend/api/lsp/completion.go
index 6a3d97fad0..b72853f376 100644
--- a/backend/api/lsp/completion.go
+++ b/backend/api/lsp/completion.go
@@ -42,9 +42,9 @@ func (h *Handler) handleTextDocumentCompletion(ctx context.Context, _ *jsonrpc2.
// We don't want to parse a huge file.
return newEmptyCompletionList(), nil
}
- _, valid, why := offsetForPosition(content, params.Position)
- if !valid {
- return nil, errors.Errorf("invalid position %d:%d (%s)", params.Position.Line, params.Position.Character, why)
+ _, err = offsetForPosition(content, params.Position)
+ if err != nil {
+ return nil, errors.Wrapf(err, "invalid position %d:%d", params.Position.Line, params.Position.Character)
}
defaultDatabase := h.getDefaultDatabase()
diff --git a/backend/api/lsp/fs.go b/backend/api/lsp/fs.go
index 5e1a932c51..68f0e3c199 100644
--- a/backend/api/lsp/fs.go
+++ b/backend/api/lsp/fs.go
@@ -49,23 +49,19 @@ func applyContentChanges(uri lsp.DocumentURI, content []byte, changes []lsp.Text
content = []byte(change.Text) // new full content
continue
}
- start, ok, why := offsetForPosition(content, change.Range.Start)
- if !ok {
- return nil, errors.Errorf("received textDocument/didChange for invalid position %q on %q: %s", change.Range.Start, uri, why)
+ start, err := offsetForPosition(content, change.Range.Start)
+ if err != nil {
+ return nil, errors.Wrapf(err, "received textDocument/didChange for invalid position %q on %q", change.Range.Start, uri)
}
- var end int
- if change.RangeLength != 0 {
- end = start + int(change.RangeLength)
- } else {
- // RangeLength not specified, work it out from Range.End
- end, ok, why = offsetForPosition(content, change.Range.End)
- if !ok {
- return nil, errors.Errorf("received textDocument/didChange for invalid position %q on %q: %s", change.Range.End, uri, why)
- }
+
+ end, err := offsetForPosition(content, change.Range.End)
+ if err != nil {
+ return nil, errors.Wrapf(err, "received textDocument/didChange for invalid position %q on %q", change.Range.End, uri)
}
if start < 0 || end > len(content) || start > end {
return nil, errors.Errorf("received textDocument/didChange for out of range position %q on %q", change.Range, uri)
}
+
// Try avoid doing too many allocations, so use bytes.Buffer
b := &bytes.Buffer{}
b.Grow(start + len(change.Text) + len(content) - end)
diff --git a/backend/api/lsp/utils.go b/backend/api/lsp/utils.go
new file mode 100644
index 0000000000..0e3f1f84dc
--- /dev/null
+++ b/backend/api/lsp/utils.go
@@ -0,0 +1,81 @@
+package lsp
+
+import (
+ "bytes"
+ "net/url"
+ "strings"
+ "unicode/utf8"
+
+ "github.com/pkg/errors"
+ "github.com/sourcegraph/go-lsp"
+)
+
+func trimFilePrefix(s string) string {
+ return strings.TrimPrefix(s, "file://")
+}
+
+// IsURI returns true if the given URI is a file:// URI.
+func IsURI(uri lsp.DocumentURI) bool {
+ return strings.HasPrefix(string(uri), "file://")
+}
+
+// URIToPath converts a URI to a file path.
+func URIToPath(uri lsp.DocumentURI) string {
+ u, err := url.Parse(string(uri))
+ if err != nil {
+ return trimFilePrefix(string(uri))
+ }
+ return u.Path
+}
+
+// offsetForPosition converts a protocol (UTF-16) position to a byte offset. content is utf8 encoded sequence.
+func offsetForPosition(content []byte, p lsp.Position) (byteOffset int, whyInvalid error) {
+ newLineCount := bytes.Count(content, []byte("\n"))
+ lineNumber := newLineCount + 1
+ // lineStartOffsets records the byte offset of each line start.
+ lineStartOffsets := make([]int, 1, lineNumber) // Init as {0}
+ for offset, b := range content {
+ if b == '\n' {
+ nextLineBeginOffset := offset + 1
+ lineStartOffsets = append(lineStartOffsets, nextLineBeginOffset)
+ }
+ }
+
+ // Validate line number, notes that the Posititon in LSP is 0-based.
+ if p.Line >= lineNumber {
+ return 0, errors.Errorf("line number %d out of range [0, %d)", p.Line, lineNumber)
+ }
+
+ offset := lineStartOffsets[p.Line]
+ trimmedContent := content[offset:]
+
+ col8 := 0
+ for col16 := 0; col16 < p.Character; col16++ {
+ // Unpack the first rune.
+ r, sz := utf8.DecodeRune(trimmedContent)
+ if sz == 0 {
+ return 0, errors.Errorf("column is beyond end of file")
+ }
+ if r == '\n' {
+ return 0, errors.Errorf("column is beyond end of line")
+ }
+ if sz == 1 && r == utf8.RuneError {
+ return 0, errors.Errorf("mem buffer contains invalid UTF-8 text")
+ }
+
+ // Step to the first code unit of next rune.
+ trimmedContent = trimmedContent[sz:]
+
+ if r > 0xFFFF {
+ // Rune was encoded by a pair of surrogate UTF-16 codes.
+ col16++
+
+ // Requested position is in the middle of a rune? Valid?
+ if col16 == int(p.Character) {
+ break
+ }
+ }
+ col8 += sz
+ }
+ return offset + col8, nil
+}
diff --git a/backend/api/lsp/utils_test.go b/backend/api/lsp/utils_test.go
new file mode 100644
index 0000000000..23394aeb42
--- /dev/null
+++ b/backend/api/lsp/utils_test.go
@@ -0,0 +1,87 @@
+package lsp
+
+import (
+ "testing"
+
+ "github.com/sourcegraph/go-lsp"
+ "github.com/stretchr/testify/require"
+)
+
+func TestOffsetForPosition(t *testing.T) {
+ testCases := []struct {
+ content []byte
+ position lsp.Position
+ expected int
+ valid bool
+ }{
+ {
+ content: []byte("Hello, World!"),
+ position: lsp.Position{Line: 0, Character: 0},
+ expected: 0,
+ valid: true,
+ },
+ {
+ content: []byte("Hello, World!"),
+ position: lsp.Position{Line: 0, Character: 7},
+ expected: 7,
+ valid: true,
+ },
+ {
+ content: []byte("Hello, 世界!"),
+ position: lsp.Position{Line: 0, Character: 7}, // Before '世'
+ expected: 7,
+ valid: true,
+ },
+ {
+ content: []byte("Hello, 世界!"),
+ position: lsp.Position{Line: 0, Character: 8}, // After '世'
+ expected: 10,
+ valid: true,
+ },
+ {
+ content: []byte("Hello,\nWorld!"),
+ position: lsp.Position{Line: 1, Character: 0}, // Start of line 2
+ expected: 7,
+ valid: true,
+ },
+ {
+ content: []byte("Hello,\nWorld!"),
+ position: lsp.Position{Line: 1, Character: 5}, // 'World'
+ expected: 12,
+ valid: true,
+ },
+ {
+ content: []byte("Hello,\nWorld!"),
+ position: lsp.Position{Line: 1, Character: 10}, // Beyond line boundary
+ valid: false,
+ },
+ {
+ content: []byte("Hello, 𐍈!"), // '𐍈' is a Unicode character requiring surrogate pairs in UTF-16
+ position: lsp.Position{Line: 0, Character: 7},
+ expected: 7,
+ valid: true,
+ },
+ {
+ content: []byte("Hello, 𐍈!"),
+ position: lsp.Position{Line: 0, Character: 9}, // After surrogate pairs in UTF-16
+ expected: 11,
+ valid: true,
+ },
+ {
+ content: []byte("Hello,\nWorld!"),
+ position: lsp.Position{Line: 2, Character: 0}, // Beyond last line
+ valid: false,
+ },
+ }
+
+ for idx, tc := range testCases {
+ offset, err := offsetForPosition(tc.content, tc.position)
+ if !tc.valid {
+ require.NotNil(t, err)
+ continue
+ }
+
+ require.Nil(t, err)
+ require.Equal(t, tc.expected, offset, "test cases %d", idx)
+ }
+}
diff --git a/backend/api/lsp/utls.go b/backend/api/lsp/utls.go
deleted file mode 100644
index 7aa72c5fca..0000000000
--- a/backend/api/lsp/utls.go
+++ /dev/null
@@ -1,54 +0,0 @@
-package lsp
-
-import (
- "fmt"
- "net/url"
- "strings"
-
- "github.com/sourcegraph/go-lsp"
-)
-
-func trimFilePrefix(s string) string {
- return strings.TrimPrefix(s, "file://")
-}
-
-// IsURI returns true if the given URI is a file:// URI.
-func IsURI(uri lsp.DocumentURI) bool {
- return strings.HasPrefix(string(uri), "file://")
-}
-
-// URIToPath converts a URI to a file path.
-func URIToPath(uri lsp.DocumentURI) string {
- u, err := url.Parse(string(uri))
- if err != nil {
- return trimFilePrefix(string(uri))
- }
- return u.Path
-}
-
-func offsetForPosition(content []byte, p lsp.Position) (offset int, valid bool, whyInvalid string) {
- line := 0
- col := 0
- for _, b := range content {
- if line == p.Line && col == p.Character {
- return offset, true, ""
- }
- if (line == p.Line && col > p.Character) || line > p.Line {
- return 0, false, fmt.Sprintf("character %d (zero-based) is beyond line %d boundary (zero-based)", p.Character, p.Line)
- }
- offset++
- if b == '\n' {
- line++
- col = 0
- } else {
- col++
- }
- }
- if line == p.Line && col == p.Character {
- return offset, true, ""
- }
- if line == 0 {
- return 0, false, fmt.Sprintf("character %d (zero-based) is beyond first line boundary", p.Character)
- }
- return 0, false, fmt.Sprintf("file only has %d lines", line+1)
-}