]> git.lizzy.rs Git - rust.git/blob - crates/ra_lsp_server/src/conv.rs
Rename col to col_utf16
[rust.git] / crates / ra_lsp_server / src / conv.rs
1 use languageserver_types::{
2     Location, Position, Range, SymbolKind, TextDocumentEdit, TextDocumentIdentifier,
3     TextDocumentItem, TextDocumentPositionParams, TextEdit, Url, VersionedTextDocumentIdentifier,
4 };
5 use ra_analysis::{FileId, FileSystemEdit, SourceChange, SourceFileNodeEdit, FilePosition};
6 use ra_editor::{AtomEdit, Edit, LineCol, LineIndex};
7 use ra_syntax::{SyntaxKind, TextRange, TextUnit};
8
9 use crate::{req, server_world::ServerWorld, Result};
10
11 pub trait Conv {
12     type Output;
13     fn conv(self) -> Self::Output;
14 }
15
16 pub trait ConvWith {
17     type Ctx;
18     type Output;
19     fn conv_with(self, ctx: &Self::Ctx) -> Self::Output;
20 }
21
22 pub trait TryConvWith {
23     type Ctx;
24     type Output;
25     fn try_conv_with(self, ctx: &Self::Ctx) -> Result<Self::Output>;
26 }
27
28 impl Conv for SyntaxKind {
29     type Output = SymbolKind;
30
31     fn conv(self) -> <Self as Conv>::Output {
32         match self {
33             SyntaxKind::FN_DEF => SymbolKind::Function,
34             SyntaxKind::STRUCT_DEF => SymbolKind::Struct,
35             SyntaxKind::ENUM_DEF => SymbolKind::Enum,
36             SyntaxKind::TRAIT_DEF => SymbolKind::Interface,
37             SyntaxKind::MODULE => SymbolKind::Module,
38             SyntaxKind::TYPE_DEF => SymbolKind::TypeParameter,
39             SyntaxKind::STATIC_DEF => SymbolKind::Constant,
40             SyntaxKind::CONST_DEF => SymbolKind::Constant,
41             SyntaxKind::IMPL_ITEM => SymbolKind::Object,
42             _ => SymbolKind::Variable,
43         }
44     }
45 }
46
47 impl ConvWith for Position {
48     type Ctx = LineIndex;
49     type Output = TextUnit;
50
51     fn conv_with(self, line_index: &LineIndex) -> TextUnit {
52         let line_col = LineCol {
53             line: self.line as u32,
54             col_utf16: self.character as u32,
55         };
56         line_index.offset(line_col)
57     }
58 }
59
60 impl ConvWith for TextUnit {
61     type Ctx = LineIndex;
62     type Output = Position;
63
64     fn conv_with(self, line_index: &LineIndex) -> Position {
65         let line_col = line_index.line_col(self);
66         Position::new(
67             u64::from(line_col.line),
68             u64::from(u32::from(line_col.col_utf16)),
69         )
70     }
71 }
72
73 impl ConvWith for TextRange {
74     type Ctx = LineIndex;
75     type Output = Range;
76
77     fn conv_with(self, line_index: &LineIndex) -> Range {
78         Range::new(
79             self.start().conv_with(line_index),
80             self.end().conv_with(line_index),
81         )
82     }
83 }
84
85 impl ConvWith for Range {
86     type Ctx = LineIndex;
87     type Output = TextRange;
88
89     fn conv_with(self, line_index: &LineIndex) -> TextRange {
90         TextRange::from_to(
91             self.start.conv_with(line_index),
92             self.end.conv_with(line_index),
93         )
94     }
95 }
96
97 impl ConvWith for Edit {
98     type Ctx = LineIndex;
99     type Output = Vec<TextEdit>;
100
101     fn conv_with(self, line_index: &LineIndex) -> Vec<TextEdit> {
102         self.into_atoms()
103             .into_iter()
104             .map_conv_with(line_index)
105             .collect()
106     }
107 }
108
109 impl ConvWith for AtomEdit {
110     type Ctx = LineIndex;
111     type Output = TextEdit;
112
113     fn conv_with(self, line_index: &LineIndex) -> TextEdit {
114         TextEdit {
115             range: self.delete.conv_with(line_index),
116             new_text: self.insert,
117         }
118     }
119 }
120
121 impl<T: ConvWith> ConvWith for Option<T> {
122     type Ctx = <T as ConvWith>::Ctx;
123     type Output = Option<<T as ConvWith>::Output>;
124     fn conv_with(self, ctx: &Self::Ctx) -> Self::Output {
125         self.map(|x| ConvWith::conv_with(x, ctx))
126     }
127 }
128
129 impl<'a> TryConvWith for &'a Url {
130     type Ctx = ServerWorld;
131     type Output = FileId;
132     fn try_conv_with(self, world: &ServerWorld) -> Result<FileId> {
133         world.uri_to_file_id(self)
134     }
135 }
136
137 impl TryConvWith for FileId {
138     type Ctx = ServerWorld;
139     type Output = Url;
140     fn try_conv_with(self, world: &ServerWorld) -> Result<Url> {
141         world.file_id_to_uri(self)
142     }
143 }
144
145 impl<'a> TryConvWith for &'a TextDocumentItem {
146     type Ctx = ServerWorld;
147     type Output = FileId;
148     fn try_conv_with(self, world: &ServerWorld) -> Result<FileId> {
149         self.uri.try_conv_with(world)
150     }
151 }
152
153 impl<'a> TryConvWith for &'a VersionedTextDocumentIdentifier {
154     type Ctx = ServerWorld;
155     type Output = FileId;
156     fn try_conv_with(self, world: &ServerWorld) -> Result<FileId> {
157         self.uri.try_conv_with(world)
158     }
159 }
160
161 impl<'a> TryConvWith for &'a TextDocumentIdentifier {
162     type Ctx = ServerWorld;
163     type Output = FileId;
164     fn try_conv_with(self, world: &ServerWorld) -> Result<FileId> {
165         world.uri_to_file_id(&self.uri)
166     }
167 }
168
169 impl<'a> TryConvWith for &'a TextDocumentPositionParams {
170     type Ctx = ServerWorld;
171     type Output = FilePosition;
172     fn try_conv_with(self, world: &ServerWorld) -> Result<FilePosition> {
173         let file_id = self.text_document.try_conv_with(world)?;
174         let line_index = world.analysis().file_line_index(file_id);
175         let offset = self.position.conv_with(&line_index);
176         Ok(FilePosition { file_id, offset })
177     }
178 }
179
180 impl<T: TryConvWith> TryConvWith for Vec<T> {
181     type Ctx = <T as TryConvWith>::Ctx;
182     type Output = Vec<<T as TryConvWith>::Output>;
183     fn try_conv_with(self, ctx: &Self::Ctx) -> Result<Self::Output> {
184         let mut res = Vec::with_capacity(self.len());
185         for item in self {
186             res.push(item.try_conv_with(ctx)?);
187         }
188         Ok(res)
189     }
190 }
191
192 impl TryConvWith for SourceChange {
193     type Ctx = ServerWorld;
194     type Output = req::SourceChange;
195     fn try_conv_with(self, world: &ServerWorld) -> Result<req::SourceChange> {
196         let cursor_position = match self.cursor_position {
197             None => None,
198             Some(pos) => {
199                 let line_index = world.analysis().file_line_index(pos.file_id);
200                 let edits = self
201                     .source_file_edits
202                     .iter()
203                     .find(|it| it.file_id == pos.file_id)
204                     .map(|it| it.edits.as_slice())
205                     .unwrap_or(&[]);
206                 let line_col = translate_offset_with_edit(&*line_index, pos.offset, edits);
207                 let position = Position::new(
208                     u64::from(line_col.line),
209                     u64::from(u32::from(line_col.col_utf16)),
210                 );
211                 Some(TextDocumentPositionParams {
212                     text_document: TextDocumentIdentifier::new(pos.file_id.try_conv_with(world)?),
213                     position,
214                 })
215             }
216         };
217         let source_file_edits = self.source_file_edits.try_conv_with(world)?;
218         let file_system_edits = self.file_system_edits.try_conv_with(world)?;
219         Ok(req::SourceChange {
220             label: self.label,
221             source_file_edits,
222             file_system_edits,
223             cursor_position,
224         })
225     }
226 }
227
228 // HACK: we should translate offset to line/column using linde_index *with edits applied*.
229 // A naive version of this function would be to apply `edits` to the original text,
230 // construct a new line index and use that, but it would be slow.
231 //
232 // Writing fast & correct version is issue #105, let's use a quick hack in the meantime
233 fn translate_offset_with_edit(
234     pre_edit_index: &LineIndex,
235     offset: TextUnit,
236     edits: &[AtomEdit],
237 ) -> LineCol {
238     let fallback = pre_edit_index.line_col(offset);
239     let edit = match edits.first() {
240         None => return fallback,
241         Some(edit) => edit,
242     };
243     let end_offset = edit.delete.start() + TextUnit::of_str(&edit.insert);
244     if !(edit.delete.start() <= offset && offset <= end_offset) {
245         return fallback;
246     }
247     let rel_offset = offset - edit.delete.start();
248     let in_edit_line_col = LineIndex::new(&edit.insert).line_col(rel_offset);
249     let edit_line_col = pre_edit_index.line_col(edit.delete.start());
250     if in_edit_line_col.line == 0 {
251         LineCol {
252             line: edit_line_col.line,
253             col_utf16: edit_line_col.col_utf16 + in_edit_line_col.col_utf16,
254         }
255     } else {
256         LineCol {
257             line: edit_line_col.line + in_edit_line_col.line,
258             col_utf16: in_edit_line_col.col_utf16,
259         }
260     }
261 }
262
263 impl TryConvWith for SourceFileNodeEdit {
264     type Ctx = ServerWorld;
265     type Output = TextDocumentEdit;
266     fn try_conv_with(self, world: &ServerWorld) -> Result<TextDocumentEdit> {
267         let text_document = VersionedTextDocumentIdentifier {
268             uri: self.file_id.try_conv_with(world)?,
269             version: None,
270         };
271         let line_index = world.analysis().file_line_index(self.file_id);
272         let edits = self.edits.into_iter().map_conv_with(&line_index).collect();
273         Ok(TextDocumentEdit {
274             text_document,
275             edits,
276         })
277     }
278 }
279
280 impl TryConvWith for FileSystemEdit {
281     type Ctx = ServerWorld;
282     type Output = req::FileSystemEdit;
283     fn try_conv_with(self, world: &ServerWorld) -> Result<req::FileSystemEdit> {
284         let res = match self {
285             FileSystemEdit::CreateFile { anchor, path } => {
286                 let uri = world.file_id_to_uri(anchor)?;
287                 let path = &path.as_str()[3..]; // strip `../` b/c url is weird
288                 let uri = uri.join(path)?;
289                 req::FileSystemEdit::CreateFile { uri }
290             }
291             FileSystemEdit::MoveFile { file, path } => {
292                 let src = world.file_id_to_uri(file)?;
293                 let path = &path.as_str()[3..]; // strip `../` b/c url is weird
294                 let dst = src.join(path)?;
295                 req::FileSystemEdit::MoveFile { src, dst }
296             }
297         };
298         Ok(res)
299     }
300 }
301
302 pub fn to_location(
303     file_id: FileId,
304     range: TextRange,
305     world: &ServerWorld,
306     line_index: &LineIndex,
307 ) -> Result<Location> {
308     let url = file_id.try_conv_with(world)?;
309     let loc = Location::new(url, range.conv_with(line_index));
310     Ok(loc)
311 }
312
313 pub trait MapConvWith<'a>: Sized + 'a {
314     type Ctx;
315     type Output;
316
317     fn map_conv_with(self, ctx: &'a Self::Ctx) -> ConvWithIter<'a, Self, Self::Ctx> {
318         ConvWithIter { iter: self, ctx }
319     }
320 }
321
322 impl<'a, I> MapConvWith<'a> for I
323 where
324     I: Iterator + 'a,
325     I::Item: ConvWith,
326 {
327     type Ctx = <I::Item as ConvWith>::Ctx;
328     type Output = <I::Item as ConvWith>::Output;
329 }
330
331 pub struct ConvWithIter<'a, I, Ctx: 'a> {
332     iter: I,
333     ctx: &'a Ctx,
334 }
335
336 impl<'a, I, Ctx> Iterator for ConvWithIter<'a, I, Ctx>
337 where
338     I: Iterator,
339     I::Item: ConvWith<Ctx = Ctx>,
340 {
341     type Item = <I::Item as ConvWith>::Output;
342
343     fn next(&mut self) -> Option<Self::Item> {
344         self.iter.next().map(|item| item.conv_with(self.ctx))
345     }
346 }