ink_lsp_server/translator/
from_lsp.rs1use line_index::{LineCol, WideEncoding, WideLineCol};
4
5use super::PositionTranslationContext;
6
7pub fn offset(
9 position: lsp_types::Position,
10 context: &PositionTranslationContext,
11) -> Option<ink_analyzer::TextSize> {
12 let line_col = if context.encoding == lsp_types::PositionEncodingKind::UTF16
13 || context.encoding == lsp_types::PositionEncodingKind::UTF32
14 {
15 let wide_line_col = WideLineCol {
17 line: position.line,
18 col: position.character,
19 };
20 let wide_encoding = if context.encoding == lsp_types::PositionEncodingKind::UTF32 {
21 WideEncoding::Utf32
22 } else {
23 WideEncoding::Utf16
24 };
25 context.line_index.to_utf8(wide_encoding, wide_line_col)?
26 } else {
27 LineCol {
29 line: position.line,
30 col: position.character,
31 }
32 };
33
34 context.line_index.offset(line_col)
35}
36
37pub fn text_range(
39 range: lsp_types::Range,
40 context: &PositionTranslationContext,
41) -> Option<ink_analyzer::TextRange> {
42 let start = offset(range.start, context)?;
43 let end = offset(range.end, context)?;
44 (start <= end).then(|| ink_analyzer::TextRange::new(start, end))
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50 use crate::test_utils::offset_position_encoding_fixture;
51 use line_index::LineIndex;
52
53 #[test]
54 fn offset_works() {
55 let (text, offset_position_groups) = offset_position_encoding_fixture();
57
58 for offset_and_positions in offset_position_groups {
60 for (encoding, position, expected_offset) in [
62 (
63 lsp_types::PositionEncodingKind::UTF8,
64 offset_and_positions.position_utf8,
65 Some(offset_and_positions.offset_utf8),
66 ),
67 (
68 lsp_types::PositionEncodingKind::UTF16,
69 offset_and_positions.position_utf16,
70 Some(offset_and_positions.offset_utf8),
71 ),
72 (
73 lsp_types::PositionEncodingKind::UTF32,
74 offset_and_positions.position_utf32,
75 Some(offset_and_positions.offset_utf8),
76 ),
77 ] {
78 let context = PositionTranslationContext {
79 encoding,
80 line_index: LineIndex::new(text),
81 };
82
83 assert_eq!(offset(position, &context), expected_offset);
85 }
86 }
87 }
88}