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