]> git.lizzy.rs Git - rust.git/blob - crates/ra_lsp_server/src/conv.rs
clippy: cast_lossless
[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, SourceFileEdit};
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<T: TryConvWith> TryConvWith for Vec<T> {
169     type Ctx = <T as TryConvWith>::Ctx;
170     type Output = Vec<<T as TryConvWith>::Output>;
171     fn try_conv_with(self, ctx: &Self::Ctx) -> Result<Self::Output> {
172         let mut res = Vec::with_capacity(self.len());
173         for item in self {
174             res.push(item.try_conv_with(ctx)?);
175         }
176         Ok(res)
177     }
178 }
179
180 impl TryConvWith for SourceChange {
181     type Ctx = ServerWorld;
182     type Output = req::SourceChange;
183     fn try_conv_with(self, world: &ServerWorld) -> Result<req::SourceChange> {
184         let cursor_position = match self.cursor_position {
185             None => None,
186             Some(pos) => {
187                 let line_index = world.analysis().file_line_index(pos.file_id);
188                 let edits = self
189                     .source_file_edits
190                     .iter()
191                     .find(|it| it.file_id == pos.file_id)
192                     .map(|it| it.edits.as_slice())
193                     .unwrap_or(&[]);
194                 let line_col = translate_offset_with_edit(&*line_index, pos.offset, edits);
195                 let position = Position::new(u64::from(line_col.line), u64::from(u32::from(line_col.col)));
196                 Some(TextDocumentPositionParams {
197                     text_document: TextDocumentIdentifier::new(pos.file_id.try_conv_with(world)?),
198                     position,
199                 })
200             }
201         };
202         let source_file_edits = self.source_file_edits.try_conv_with(world)?;
203         let file_system_edits = self.file_system_edits.try_conv_with(world)?;
204         Ok(req::SourceChange {
205             label: self.label,
206             source_file_edits,
207             file_system_edits,
208             cursor_position,
209         })
210     }
211 }
212
213 // HACK: we should translate offset to line/column using linde_index *with edits applied*.
214 // A naive version of this function would be to apply `edits` to the original text,
215 // construct a new line index and use that, but it would be slow.
216 //
217 // Writing fast & correct version is issue #105, let's use a quick hack in the meantime
218 fn translate_offset_with_edit(
219     pre_edit_index: &LineIndex,
220     offset: TextUnit,
221     edits: &[AtomEdit],
222 ) -> LineCol {
223     let fallback = pre_edit_index.line_col(offset);
224     let edit = match edits.first() {
225         None => return fallback,
226         Some(edit) => edit,
227     };
228     let end_offset = edit.delete.start() + TextUnit::of_str(&edit.insert);
229     if !(edit.delete.start() <= offset && offset <= end_offset) {
230         return fallback;
231     }
232     let rel_offset = offset - edit.delete.start();
233     let in_edit_line_col = LineIndex::new(&edit.insert).line_col(rel_offset);
234     let edit_line_col = pre_edit_index.line_col(edit.delete.start());
235     if in_edit_line_col.line == 0 {
236         LineCol {
237             line: edit_line_col.line,
238             col: edit_line_col.col + in_edit_line_col.col,
239         }
240     } else {
241         LineCol {
242             line: edit_line_col.line + in_edit_line_col.line,
243             col: in_edit_line_col.col,
244         }
245     }
246 }
247
248 impl TryConvWith for SourceFileEdit {
249     type Ctx = ServerWorld;
250     type Output = TextDocumentEdit;
251     fn try_conv_with(self, world: &ServerWorld) -> Result<TextDocumentEdit> {
252         let text_document = VersionedTextDocumentIdentifier {
253             uri: self.file_id.try_conv_with(world)?,
254             version: None,
255         };
256         let line_index = world.analysis().file_line_index(self.file_id);
257         let edits = self.edits.into_iter().map_conv_with(&line_index).collect();
258         Ok(TextDocumentEdit {
259             text_document,
260             edits,
261         })
262     }
263 }
264
265 impl TryConvWith for FileSystemEdit {
266     type Ctx = ServerWorld;
267     type Output = req::FileSystemEdit;
268     fn try_conv_with(self, world: &ServerWorld) -> Result<req::FileSystemEdit> {
269         let res = match self {
270             FileSystemEdit::CreateFile { anchor, path } => {
271                 let uri = world.file_id_to_uri(anchor)?;
272                 let path = &path.as_str()[3..]; // strip `../` b/c url is weird
273                 let uri = uri.join(path)?;
274                 req::FileSystemEdit::CreateFile { uri }
275             }
276             FileSystemEdit::MoveFile { file, path } => {
277                 let src = world.file_id_to_uri(file)?;
278                 let path = &path.as_str()[3..]; // strip `../` b/c url is weird
279                 let dst = src.join(path)?;
280                 req::FileSystemEdit::MoveFile { src, dst }
281             }
282         };
283         Ok(res)
284     }
285 }
286
287 pub fn to_location(
288     file_id: FileId,
289     range: TextRange,
290     world: &ServerWorld,
291     line_index: &LineIndex,
292 ) -> Result<Location> {
293     let url = file_id.try_conv_with(world)?;
294     let loc = Location::new(url, range.conv_with(line_index));
295     Ok(loc)
296 }
297
298 pub trait MapConvWith<'a>: Sized + 'a {
299     type Ctx;
300     type Output;
301
302     fn map_conv_with(self, ctx: &'a Self::Ctx) -> ConvWithIter<'a, Self, Self::Ctx> {
303         ConvWithIter { iter: self, ctx }
304     }
305 }
306
307 impl<'a, I> MapConvWith<'a> for I
308 where
309     I: Iterator + 'a,
310     I::Item: ConvWith,
311 {
312     type Ctx = <I::Item as ConvWith>::Ctx;
313     type Output = <I::Item as ConvWith>::Output;
314 }
315
316 pub struct ConvWithIter<'a, I, Ctx: 'a> {
317     iter: I,
318     ctx: &'a Ctx,
319 }
320
321 impl<'a, I, Ctx> Iterator for ConvWithIter<'a, I, Ctx>
322 where
323     I: Iterator,
324     I::Item: ConvWith<Ctx = Ctx>,
325 {
326     type Item = <I::Item as ConvWith>::Output;
327
328     fn next(&mut self) -> Option<Self::Item> {
329         self.iter.next().map(|item| item.conv_with(self.ctx))
330     }
331 }