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