]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/conv.rs
Merge #3826
[rust.git] / crates / rust-analyzer / src / conv.rs
1 //! Convenience module responsible for translating between rust-analyzer's types
2 //! and LSP types.
3
4 use lsp_types::{
5     self, CreateFile, DiagnosticSeverity, DocumentChangeOperation, DocumentChanges, Documentation,
6     Location, LocationLink, MarkupContent, MarkupKind, ParameterInformation, ParameterLabel,
7     Position, Range, RenameFile, ResourceOp, SemanticTokenModifier, SemanticTokenType,
8     SignatureInformation, SymbolKind, TextDocumentEdit, TextDocumentIdentifier, TextDocumentItem,
9     TextDocumentPositionParams, Url, VersionedTextDocumentIdentifier, WorkspaceEdit,
10 };
11 use ra_ide::{
12     translate_offset_with_edit, CompletionItem, CompletionItemKind, FileId, FilePosition,
13     FileRange, FileSystemEdit, Fold, FoldKind, Highlight, HighlightModifier, HighlightTag,
14     InlayHint, InlayKind, InsertTextFormat, LineCol, LineIndex, NavigationTarget, RangeInfo,
15     ReferenceAccess, Severity, SourceChange, SourceFileEdit,
16 };
17 use ra_syntax::{SyntaxKind, TextRange, TextUnit};
18 use ra_text_edit::{AtomTextEdit, TextEdit};
19 use ra_vfs::LineEndings;
20
21 use crate::{
22     req,
23     semantic_tokens::{self, ModifierSet, CONSTANT, CONTROL_FLOW, MUTABLE, UNSAFE},
24     world::WorldSnapshot,
25     Result,
26 };
27 use semantic_tokens::{ATTRIBUTE, BUILTIN_TYPE, ENUM_MEMBER, LIFETIME, TYPE_ALIAS, UNION};
28
29 pub trait Conv {
30     type Output;
31     fn conv(self) -> Self::Output;
32 }
33
34 pub trait ConvWith<CTX> {
35     type Output;
36     fn conv_with(self, ctx: CTX) -> Self::Output;
37 }
38
39 pub trait TryConvWith<CTX> {
40     type Output;
41     fn try_conv_with(self, ctx: CTX) -> Result<Self::Output>;
42 }
43
44 impl Conv for SyntaxKind {
45     type Output = SymbolKind;
46
47     fn conv(self) -> <Self as Conv>::Output {
48         match self {
49             SyntaxKind::FN_DEF => SymbolKind::Function,
50             SyntaxKind::STRUCT_DEF => SymbolKind::Struct,
51             SyntaxKind::ENUM_DEF => SymbolKind::Enum,
52             SyntaxKind::ENUM_VARIANT => SymbolKind::EnumMember,
53             SyntaxKind::TRAIT_DEF => SymbolKind::Interface,
54             SyntaxKind::MACRO_CALL => SymbolKind::Function,
55             SyntaxKind::MODULE => SymbolKind::Module,
56             SyntaxKind::TYPE_ALIAS_DEF => SymbolKind::TypeParameter,
57             SyntaxKind::RECORD_FIELD_DEF => SymbolKind::Field,
58             SyntaxKind::STATIC_DEF => SymbolKind::Constant,
59             SyntaxKind::CONST_DEF => SymbolKind::Constant,
60             SyntaxKind::IMPL_DEF => SymbolKind::Object,
61             _ => SymbolKind::Variable,
62         }
63     }
64 }
65
66 impl Conv for ReferenceAccess {
67     type Output = ::lsp_types::DocumentHighlightKind;
68
69     fn conv(self) -> Self::Output {
70         use lsp_types::DocumentHighlightKind;
71         match self {
72             ReferenceAccess::Read => DocumentHighlightKind::Read,
73             ReferenceAccess::Write => DocumentHighlightKind::Write,
74         }
75     }
76 }
77
78 impl Conv for CompletionItemKind {
79     type Output = ::lsp_types::CompletionItemKind;
80
81     fn conv(self) -> <Self as Conv>::Output {
82         use lsp_types::CompletionItemKind::*;
83         match self {
84             CompletionItemKind::Keyword => Keyword,
85             CompletionItemKind::Snippet => Snippet,
86             CompletionItemKind::Module => Module,
87             CompletionItemKind::Function => Function,
88             CompletionItemKind::Struct => Struct,
89             CompletionItemKind::Enum => Enum,
90             CompletionItemKind::EnumVariant => EnumMember,
91             CompletionItemKind::BuiltinType => Struct,
92             CompletionItemKind::Binding => Variable,
93             CompletionItemKind::Field => Field,
94             CompletionItemKind::Trait => Interface,
95             CompletionItemKind::TypeAlias => Struct,
96             CompletionItemKind::Const => Constant,
97             CompletionItemKind::Static => Value,
98             CompletionItemKind::Method => Method,
99             CompletionItemKind::TypeParam => TypeParameter,
100             CompletionItemKind::Macro => Method,
101         }
102     }
103 }
104
105 impl Conv for Severity {
106     type Output = DiagnosticSeverity;
107     fn conv(self) -> DiagnosticSeverity {
108         match self {
109             Severity::Error => DiagnosticSeverity::Error,
110             Severity::WeakWarning => DiagnosticSeverity::Hint,
111         }
112     }
113 }
114
115 impl ConvWith<(&LineIndex, LineEndings)> for CompletionItem {
116     type Output = ::lsp_types::CompletionItem;
117
118     fn conv_with(self, ctx: (&LineIndex, LineEndings)) -> ::lsp_types::CompletionItem {
119         let mut additional_text_edits = Vec::new();
120         let mut text_edit = None;
121         // LSP does not allow arbitrary edits in completion, so we have to do a
122         // non-trivial mapping here.
123         for atom_edit in self.text_edit().as_atoms() {
124             if self.source_range().is_subrange(&atom_edit.delete) {
125                 text_edit = Some(if atom_edit.delete == self.source_range() {
126                     atom_edit.conv_with(ctx)
127                 } else {
128                     assert!(self.source_range().end() == atom_edit.delete.end());
129                     let range1 =
130                         TextRange::from_to(atom_edit.delete.start(), self.source_range().start());
131                     let range2 = self.source_range();
132                     let edit1 = AtomTextEdit::replace(range1, String::new());
133                     let edit2 = AtomTextEdit::replace(range2, atom_edit.insert.clone());
134                     additional_text_edits.push(edit1.conv_with(ctx));
135                     edit2.conv_with(ctx)
136                 })
137             } else {
138                 assert!(self.source_range().intersection(&atom_edit.delete).is_none());
139                 additional_text_edits.push(atom_edit.conv_with(ctx));
140             }
141         }
142         let text_edit = text_edit.unwrap();
143
144         let mut res = lsp_types::CompletionItem {
145             label: self.label().to_string(),
146             detail: self.detail().map(|it| it.to_string()),
147             filter_text: Some(self.lookup().to_string()),
148             kind: self.kind().map(|it| it.conv()),
149             text_edit: Some(text_edit),
150             additional_text_edits: Some(additional_text_edits),
151             documentation: self.documentation().map(|it| it.conv()),
152             deprecated: Some(self.deprecated()),
153             command: if self.trigger_call_info() {
154                 let cmd = lsp_types::Command {
155                     title: "triggerParameterHints".into(),
156                     command: "editor.action.triggerParameterHints".into(),
157                     arguments: None,
158                 };
159                 Some(cmd)
160             } else {
161                 None
162             },
163             ..Default::default()
164         };
165
166         if self.deprecated() {
167             res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
168         }
169
170         res.insert_text_format = Some(match self.insert_text_format() {
171             InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
172             InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
173         });
174
175         res
176     }
177 }
178
179 impl ConvWith<&LineIndex> for Position {
180     type Output = TextUnit;
181
182     fn conv_with(self, line_index: &LineIndex) -> TextUnit {
183         let line_col = LineCol { line: self.line as u32, col_utf16: self.character as u32 };
184         line_index.offset(line_col)
185     }
186 }
187
188 impl ConvWith<&LineIndex> for TextUnit {
189     type Output = Position;
190
191     fn conv_with(self, line_index: &LineIndex) -> Position {
192         let line_col = line_index.line_col(self);
193         Position::new(u64::from(line_col.line), u64::from(line_col.col_utf16))
194     }
195 }
196
197 impl ConvWith<&LineIndex> for TextRange {
198     type Output = Range;
199
200     fn conv_with(self, line_index: &LineIndex) -> Range {
201         Range::new(self.start().conv_with(line_index), self.end().conv_with(line_index))
202     }
203 }
204
205 impl ConvWith<&LineIndex> for Range {
206     type Output = TextRange;
207
208     fn conv_with(self, line_index: &LineIndex) -> TextRange {
209         TextRange::from_to(self.start.conv_with(line_index), self.end.conv_with(line_index))
210     }
211 }
212
213 impl Conv for ra_ide::Documentation {
214     type Output = lsp_types::Documentation;
215     fn conv(self) -> Documentation {
216         Documentation::MarkupContent(MarkupContent {
217             kind: MarkupKind::Markdown,
218             value: crate::markdown::format_docs(self.as_str()),
219         })
220     }
221 }
222
223 impl ConvWith<bool> for ra_ide::FunctionSignature {
224     type Output = lsp_types::SignatureInformation;
225     fn conv_with(self, concise: bool) -> Self::Output {
226         let (label, documentation, params) = if concise {
227             let mut params = self.parameters;
228             if self.has_self_param {
229                 params.remove(0);
230             }
231             (params.join(", "), None, params)
232         } else {
233             (self.to_string(), self.doc.map(|it| it.conv()), self.parameters)
234         };
235
236         let parameters: Vec<ParameterInformation> = params
237             .into_iter()
238             .map(|param| ParameterInformation {
239                 label: ParameterLabel::Simple(param),
240                 documentation: None,
241             })
242             .collect();
243
244         SignatureInformation { label, documentation, parameters: Some(parameters) }
245     }
246 }
247
248 impl ConvWith<(&LineIndex, LineEndings)> for TextEdit {
249     type Output = Vec<lsp_types::TextEdit>;
250
251     fn conv_with(self, ctx: (&LineIndex, LineEndings)) -> Vec<lsp_types::TextEdit> {
252         self.as_atoms().iter().map_conv_with(ctx).collect()
253     }
254 }
255
256 impl ConvWith<(&LineIndex, LineEndings)> for &AtomTextEdit {
257     type Output = lsp_types::TextEdit;
258
259     fn conv_with(
260         self,
261         (line_index, line_endings): (&LineIndex, LineEndings),
262     ) -> lsp_types::TextEdit {
263         let mut new_text = self.insert.clone();
264         if line_endings == LineEndings::Dos {
265             new_text = new_text.replace('\n', "\r\n");
266         }
267         lsp_types::TextEdit { range: self.delete.conv_with(line_index), new_text }
268     }
269 }
270
271 pub(crate) struct FoldConvCtx<'a> {
272     pub(crate) text: &'a str,
273     pub(crate) line_index: &'a LineIndex,
274     pub(crate) line_folding_only: bool,
275 }
276
277 impl ConvWith<&FoldConvCtx<'_>> for Fold {
278     type Output = lsp_types::FoldingRange;
279
280     fn conv_with(self, ctx: &FoldConvCtx) -> lsp_types::FoldingRange {
281         let kind = match self.kind {
282             FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
283             FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
284             FoldKind::Mods => None,
285             FoldKind::Block => None,
286         };
287
288         let range = self.range.conv_with(&ctx.line_index);
289
290         if ctx.line_folding_only {
291             // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
292             // even if it contains text not in the folding range. To prevent that we exclude
293             // range.end.line from the folding region if there is more text after range.end
294             // on the same line.
295             let has_more_text_on_end_line = ctx.text
296                 [TextRange::from_to(self.range.end(), TextUnit::of_str(ctx.text))]
297             .chars()
298             .take_while(|it| *it != '\n')
299             .any(|it| !it.is_whitespace());
300
301             let end_line = if has_more_text_on_end_line {
302                 range.end.line.saturating_sub(1)
303             } else {
304                 range.end.line
305             };
306
307             lsp_types::FoldingRange {
308                 start_line: range.start.line,
309                 start_character: None,
310                 end_line,
311                 end_character: None,
312                 kind,
313             }
314         } else {
315             lsp_types::FoldingRange {
316                 start_line: range.start.line,
317                 start_character: Some(range.start.character),
318                 end_line: range.end.line,
319                 end_character: Some(range.end.character),
320                 kind,
321             }
322         }
323     }
324 }
325
326 impl ConvWith<&LineIndex> for InlayHint {
327     type Output = req::InlayHint;
328     fn conv_with(self, line_index: &LineIndex) -> Self::Output {
329         req::InlayHint {
330             label: self.label.to_string(),
331             range: self.range.conv_with(line_index),
332             kind: match self.kind {
333                 InlayKind::ParameterHint => req::InlayKind::ParameterHint,
334                 InlayKind::TypeHint => req::InlayKind::TypeHint,
335                 InlayKind::ChainingHint => req::InlayKind::ChainingHint,
336             },
337         }
338     }
339 }
340
341 impl Conv for Highlight {
342     type Output = (u32, u32);
343
344     fn conv(self) -> Self::Output {
345         let mut mods = ModifierSet::default();
346         let type_ = match self.tag {
347             HighlightTag::Struct => SemanticTokenType::STRUCT,
348             HighlightTag::Enum => SemanticTokenType::ENUM,
349             HighlightTag::Union => UNION,
350             HighlightTag::TypeAlias => TYPE_ALIAS,
351             HighlightTag::Trait => SemanticTokenType::INTERFACE,
352             HighlightTag::BuiltinType => BUILTIN_TYPE,
353             HighlightTag::SelfType => SemanticTokenType::TYPE,
354             HighlightTag::Field => SemanticTokenType::MEMBER,
355             HighlightTag::Function => SemanticTokenType::FUNCTION,
356             HighlightTag::Module => SemanticTokenType::NAMESPACE,
357             HighlightTag::Constant => {
358                 mods |= CONSTANT;
359                 mods |= SemanticTokenModifier::STATIC;
360                 SemanticTokenType::VARIABLE
361             }
362             HighlightTag::Static => {
363                 mods |= SemanticTokenModifier::STATIC;
364                 SemanticTokenType::VARIABLE
365             }
366             HighlightTag::EnumVariant => ENUM_MEMBER,
367             HighlightTag::Macro => SemanticTokenType::MACRO,
368             HighlightTag::Local => SemanticTokenType::VARIABLE,
369             HighlightTag::TypeParam => SemanticTokenType::TYPE_PARAMETER,
370             HighlightTag::Lifetime => LIFETIME,
371             HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => SemanticTokenType::NUMBER,
372             HighlightTag::CharLiteral | HighlightTag::StringLiteral => SemanticTokenType::STRING,
373             HighlightTag::Comment => SemanticTokenType::COMMENT,
374             HighlightTag::Attribute => ATTRIBUTE,
375             HighlightTag::Keyword => SemanticTokenType::KEYWORD,
376         };
377
378         for modifier in self.modifiers.iter() {
379             let modifier = match modifier {
380                 HighlightModifier::Definition => SemanticTokenModifier::DECLARATION,
381                 HighlightModifier::ControlFlow => CONTROL_FLOW,
382                 HighlightModifier::Mutable => MUTABLE,
383                 HighlightModifier::Unsafe => UNSAFE,
384             };
385             mods |= modifier;
386         }
387
388         (semantic_tokens::type_index(type_), mods.0)
389     }
390 }
391
392 impl<T: ConvWith<CTX>, CTX> ConvWith<CTX> for Option<T> {
393     type Output = Option<T::Output>;
394
395     fn conv_with(self, ctx: CTX) -> Self::Output {
396         self.map(|x| ConvWith::conv_with(x, ctx))
397     }
398 }
399
400 impl TryConvWith<&WorldSnapshot> for &Url {
401     type Output = FileId;
402     fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
403         world.uri_to_file_id(self)
404     }
405 }
406
407 impl TryConvWith<&WorldSnapshot> for FileId {
408     type Output = Url;
409     fn try_conv_with(self, world: &WorldSnapshot) -> Result<Url> {
410         world.file_id_to_uri(self)
411     }
412 }
413
414 impl TryConvWith<&WorldSnapshot> for &TextDocumentItem {
415     type Output = FileId;
416     fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
417         self.uri.try_conv_with(world)
418     }
419 }
420
421 impl TryConvWith<&WorldSnapshot> for &VersionedTextDocumentIdentifier {
422     type Output = FileId;
423     fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
424         self.uri.try_conv_with(world)
425     }
426 }
427
428 impl TryConvWith<&WorldSnapshot> for &TextDocumentIdentifier {
429     type Output = FileId;
430     fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
431         world.uri_to_file_id(&self.uri)
432     }
433 }
434
435 impl TryConvWith<&WorldSnapshot> for &TextDocumentPositionParams {
436     type Output = FilePosition;
437     fn try_conv_with(self, world: &WorldSnapshot) -> Result<FilePosition> {
438         let file_id = self.text_document.try_conv_with(world)?;
439         let line_index = world.analysis().file_line_index(file_id)?;
440         let offset = self.position.conv_with(&line_index);
441         Ok(FilePosition { file_id, offset })
442     }
443 }
444
445 impl TryConvWith<&WorldSnapshot> for (&TextDocumentIdentifier, Range) {
446     type Output = FileRange;
447     fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileRange> {
448         let file_id = self.0.try_conv_with(world)?;
449         let line_index = world.analysis().file_line_index(file_id)?;
450         let range = self.1.conv_with(&line_index);
451         Ok(FileRange { file_id, range })
452     }
453 }
454
455 impl<T: TryConvWith<CTX>, CTX: Copy> TryConvWith<CTX> for Vec<T> {
456     type Output = Vec<<T as TryConvWith<CTX>>::Output>;
457     fn try_conv_with(self, ctx: CTX) -> Result<Self::Output> {
458         let mut res = Vec::with_capacity(self.len());
459         for item in self {
460             res.push(item.try_conv_with(ctx)?);
461         }
462         Ok(res)
463     }
464 }
465
466 impl TryConvWith<&WorldSnapshot> for SourceChange {
467     type Output = req::SourceChange;
468     fn try_conv_with(self, world: &WorldSnapshot) -> Result<req::SourceChange> {
469         let cursor_position = match self.cursor_position {
470             None => None,
471             Some(pos) => {
472                 let line_index = world.analysis().file_line_index(pos.file_id)?;
473                 let edit = self
474                     .source_file_edits
475                     .iter()
476                     .find(|it| it.file_id == pos.file_id)
477                     .map(|it| &it.edit);
478                 let line_col = match edit {
479                     Some(edit) => translate_offset_with_edit(&*line_index, pos.offset, edit),
480                     None => line_index.line_col(pos.offset),
481                 };
482                 let position =
483                     Position::new(u64::from(line_col.line), u64::from(line_col.col_utf16));
484                 Some(TextDocumentPositionParams {
485                     text_document: TextDocumentIdentifier::new(pos.file_id.try_conv_with(world)?),
486                     position,
487                 })
488             }
489         };
490         let mut document_changes: Vec<DocumentChangeOperation> = Vec::new();
491         for resource_op in self.file_system_edits.try_conv_with(world)? {
492             document_changes.push(DocumentChangeOperation::Op(resource_op));
493         }
494         for text_document_edit in self.source_file_edits.try_conv_with(world)? {
495             document_changes.push(DocumentChangeOperation::Edit(text_document_edit));
496         }
497         let workspace_edit = WorkspaceEdit {
498             changes: None,
499             document_changes: Some(DocumentChanges::Operations(document_changes)),
500         };
501         Ok(req::SourceChange { label: self.label, workspace_edit, cursor_position })
502     }
503 }
504
505 impl TryConvWith<&WorldSnapshot> for SourceFileEdit {
506     type Output = TextDocumentEdit;
507     fn try_conv_with(self, world: &WorldSnapshot) -> Result<TextDocumentEdit> {
508         let text_document = VersionedTextDocumentIdentifier {
509             uri: self.file_id.try_conv_with(world)?,
510             version: None,
511         };
512         let line_index = world.analysis().file_line_index(self.file_id)?;
513         let line_endings = world.file_line_endings(self.file_id);
514         let edits =
515             self.edit.as_atoms().iter().map_conv_with((&line_index, line_endings)).collect();
516         Ok(TextDocumentEdit { text_document, edits })
517     }
518 }
519
520 impl TryConvWith<&WorldSnapshot> for FileSystemEdit {
521     type Output = ResourceOp;
522     fn try_conv_with(self, world: &WorldSnapshot) -> Result<ResourceOp> {
523         let res = match self {
524             FileSystemEdit::CreateFile { source_root, path } => {
525                 let uri = world.path_to_uri(source_root, &path)?;
526                 ResourceOp::Create(CreateFile { uri, options: None })
527             }
528             FileSystemEdit::MoveFile { src, dst_source_root, dst_path } => {
529                 let old_uri = world.file_id_to_uri(src)?;
530                 let new_uri = world.path_to_uri(dst_source_root, &dst_path)?;
531                 ResourceOp::Rename(RenameFile { old_uri, new_uri, options: None })
532             }
533         };
534         Ok(res)
535     }
536 }
537
538 impl TryConvWith<&WorldSnapshot> for &NavigationTarget {
539     type Output = Location;
540     fn try_conv_with(self, world: &WorldSnapshot) -> Result<Location> {
541         let line_index = world.analysis().file_line_index(self.file_id())?;
542         let range = self.range();
543         to_location(self.file_id(), range, &world, &line_index)
544     }
545 }
546
547 impl TryConvWith<&WorldSnapshot> for (FileId, RangeInfo<NavigationTarget>) {
548     type Output = LocationLink;
549     fn try_conv_with(self, world: &WorldSnapshot) -> Result<LocationLink> {
550         let (src_file_id, target) = self;
551
552         let target_uri = target.info.file_id().try_conv_with(world)?;
553         let src_line_index = world.analysis().file_line_index(src_file_id)?;
554         let tgt_line_index = world.analysis().file_line_index(target.info.file_id())?;
555
556         let target_range = target.info.full_range().conv_with(&tgt_line_index);
557
558         let target_selection_range = target
559             .info
560             .focus_range()
561             .map(|it| it.conv_with(&tgt_line_index))
562             .unwrap_or(target_range);
563
564         let res = LocationLink {
565             origin_selection_range: Some(target.range.conv_with(&src_line_index)),
566             target_uri,
567             target_range,
568             target_selection_range,
569         };
570         Ok(res)
571     }
572 }
573
574 impl TryConvWith<&WorldSnapshot> for (FileId, RangeInfo<Vec<NavigationTarget>>) {
575     type Output = req::GotoDefinitionResponse;
576     fn try_conv_with(self, world: &WorldSnapshot) -> Result<req::GotoTypeDefinitionResponse> {
577         let (file_id, RangeInfo { range, info: navs }) = self;
578         let links = navs
579             .into_iter()
580             .map(|nav| (file_id, RangeInfo::new(range, nav)))
581             .try_conv_with_to_vec(world)?;
582         if world.config.client_caps.location_link {
583             Ok(links.into())
584         } else {
585             let locations: Vec<Location> = links
586                 .into_iter()
587                 .map(|link| Location { uri: link.target_uri, range: link.target_selection_range })
588                 .collect();
589             Ok(locations.into())
590         }
591     }
592 }
593
594 pub fn to_call_hierarchy_item(
595     file_id: FileId,
596     range: TextRange,
597     world: &WorldSnapshot,
598     line_index: &LineIndex,
599     nav: NavigationTarget,
600 ) -> Result<lsp_types::CallHierarchyItem> {
601     Ok(lsp_types::CallHierarchyItem {
602         name: nav.name().to_string(),
603         kind: nav.kind().conv(),
604         tags: None,
605         detail: nav.description().map(|it| it.to_string()),
606         uri: file_id.try_conv_with(&world)?,
607         range: nav.range().conv_with(&line_index),
608         selection_range: range.conv_with(&line_index),
609     })
610 }
611
612 pub fn to_location(
613     file_id: FileId,
614     range: TextRange,
615     world: &WorldSnapshot,
616     line_index: &LineIndex,
617 ) -> Result<Location> {
618     let url = file_id.try_conv_with(world)?;
619     let loc = Location::new(url, range.conv_with(line_index));
620     Ok(loc)
621 }
622
623 pub trait MapConvWith<CTX>: Sized {
624     type Output;
625
626     fn map_conv_with(self, ctx: CTX) -> ConvWithIter<Self, CTX> {
627         ConvWithIter { iter: self, ctx }
628     }
629 }
630
631 impl<CTX, I> MapConvWith<CTX> for I
632 where
633     I: Iterator,
634     I::Item: ConvWith<CTX>,
635 {
636     type Output = <I::Item as ConvWith<CTX>>::Output;
637 }
638
639 pub struct ConvWithIter<I, CTX> {
640     iter: I,
641     ctx: CTX,
642 }
643
644 impl<I, CTX> Iterator for ConvWithIter<I, CTX>
645 where
646     I: Iterator,
647     I::Item: ConvWith<CTX>,
648     CTX: Copy,
649 {
650     type Item = <I::Item as ConvWith<CTX>>::Output;
651
652     fn next(&mut self) -> Option<Self::Item> {
653         self.iter.next().map(|item| item.conv_with(self.ctx))
654     }
655 }
656
657 pub trait TryConvWithToVec<CTX>: Sized {
658     type Output;
659
660     fn try_conv_with_to_vec(self, ctx: CTX) -> Result<Vec<Self::Output>>;
661 }
662
663 impl<I, CTX> TryConvWithToVec<CTX> for I
664 where
665     I: Iterator,
666     I::Item: TryConvWith<CTX>,
667     CTX: Copy,
668 {
669     type Output = <I::Item as TryConvWith<CTX>>::Output;
670
671     fn try_conv_with_to_vec(self, ctx: CTX) -> Result<Vec<Self::Output>> {
672         self.map(|it| it.try_conv_with(ctx)).collect()
673     }
674 }
675
676 #[cfg(test)]
677 mod tests {
678     use super::*;
679     use test_utils::extract_ranges;
680
681     #[test]
682     fn conv_fold_line_folding_only_fixup() {
683         let text = r#"<fold>mod a;
684 mod b;
685 mod c;</fold>
686
687 fn main() <fold>{
688     if cond <fold>{
689         a::do_a();
690     }</fold> else <fold>{
691         b::do_b();
692     }</fold>
693 }</fold>"#;
694
695         let (ranges, text) = extract_ranges(text, "fold");
696         assert_eq!(ranges.len(), 4);
697         let folds = vec![
698             Fold { range: ranges[0], kind: FoldKind::Mods },
699             Fold { range: ranges[1], kind: FoldKind::Block },
700             Fold { range: ranges[2], kind: FoldKind::Block },
701             Fold { range: ranges[3], kind: FoldKind::Block },
702         ];
703
704         let line_index = LineIndex::new(&text);
705         let ctx = FoldConvCtx { text: &text, line_index: &line_index, line_folding_only: true };
706         let converted: Vec<_> = folds.into_iter().map_conv_with(&ctx).collect();
707
708         let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
709         assert_eq!(converted.len(), expected_lines.len());
710         for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
711             assert_eq!(folding_range.start_line, *start_line);
712             assert_eq!(folding_range.start_character, None);
713             assert_eq!(folding_range.end_line, *end_line);
714             assert_eq!(folding_range.end_character, None);
715         }
716     }
717 }