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