MCPcopy Create free account
hub / github.com/bytebase/bytebase / convertPositionToUTF16Position

Function convertPositionToUTF16Position

backend/plugin/parser/base/diagnose.go:23–67  ·  view source on GitHub ↗

convertPositionToUTF16Position converts a Position to a UTF16Position in a given text. Position uses 1-based line and 1-based character column. LSP Position uses 0-based line and 0-based UTF-16 code unit offset. If the Position is nil, it returns a UTF16Position with line and character set to 0. If

(p *storepb.Position, text string)

Source from the content-addressed store, hash-verified

21// If the line in Position is out of the end of text, replace it with the last line.
22// If the column in Position is out of the end of line, replace it with the last column.
23func convertPositionToUTF16Position(p *storepb.Position, text string) *lsp.Position {
24 if p == nil {
25 return &lsp.Position{
26 Line: 0,
27 Character: 0,
28 }
29 }
30 lines := strings.Split(text, "\n")
31 // Convert from 1-based to 0-based line
32 lineNumber := p.Line - 1
33 if lineNumber < 0 {
34 lineNumber = 0
35 }
36 if lineNumber >= int32(len(lines)) {
37 lineNumber = int32(len(lines)) - 1
38 }
39
40 // Convert from 1-based character column to 0-based UTF-16 code units
41 line := lines[lineNumber]
42 runes := []rune(line)
43
44 // p.Column is 1-based, convert to 0-based character offset
45 charOffset := int(p.Column) - 1
46 if charOffset < 0 {
47 charOffset = 0
48 }
49 if charOffset > len(runes) {
50 charOffset = len(runes)
51 }
52
53 // Count UTF-16 code units up to the character offset
54 u16CodeUnits := 0
55 for i := 0; i < charOffset && i < len(runes); i++ {
56 u16CodeUnits++
57 if runes[i] > 0xFFFF {
58 // Characters outside BMP need surrogate pairs in UTF-16
59 u16CodeUnits++
60 }
61 }
62
63 return &lsp.Position{
64 Line: uint32(lineNumber),
65 Character: uint32(u16CodeUnits),
66 }
67}
68
69func ConvertSyntaxErrorToDiagnostic(err *SyntaxError, statement string) Diagnostic {
70 start := *convertPositionToUTF16Position(err.Position, statement)

Calls

no outgoing calls

Tested by 1