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