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