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