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