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