]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/conv.rs
Don't set sortText
[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::{
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)> for CompletionItem {
118     type Output = ::lsp_types::CompletionItem;
119
120     fn conv_with(self, ctx: (&LineIndex, LineEndings)) -> ::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 self.score().is_some() {
169             res.preselect = Some(true)
170         }
171
172         if self.deprecated() {
173             res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
174         }
175
176         res.insert_text_format = Some(match self.insert_text_format() {
177             InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
178             InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
179         });
180
181         res
182     }
183 }
184
185 impl ConvWith<&LineIndex> for Position {
186     type Output = TextUnit;
187
188     fn conv_with(self, line_index: &LineIndex) -> TextUnit {
189         let line_col = LineCol { line: self.line as u32, col_utf16: self.character as u32 };
190         line_index.offset(line_col)
191     }
192 }
193
194 impl ConvWith<&LineIndex> for TextUnit {
195     type Output = Position;
196
197     fn conv_with(self, line_index: &LineIndex) -> Position {
198         let line_col = line_index.line_col(self);
199         Position::new(u64::from(line_col.line), u64::from(line_col.col_utf16))
200     }
201 }
202
203 impl ConvWith<&LineIndex> for TextRange {
204     type Output = Range;
205
206     fn conv_with(self, line_index: &LineIndex) -> Range {
207         Range::new(self.start().conv_with(line_index), self.end().conv_with(line_index))
208     }
209 }
210
211 impl ConvWith<&LineIndex> for Range {
212     type Output = TextRange;
213
214     fn conv_with(self, line_index: &LineIndex) -> TextRange {
215         TextRange::from_to(self.start.conv_with(line_index), self.end.conv_with(line_index))
216     }
217 }
218
219 impl Conv for ra_ide::Documentation {
220     type Output = lsp_types::Documentation;
221     fn conv(self) -> Documentation {
222         Documentation::MarkupContent(MarkupContent {
223             kind: MarkupKind::Markdown,
224             value: crate::markdown::format_docs(self.as_str()),
225         })
226     }
227 }
228
229 impl ConvWith<bool> for ra_ide::FunctionSignature {
230     type Output = lsp_types::SignatureInformation;
231     fn conv_with(self, concise: bool) -> Self::Output {
232         let (label, documentation, params) = if concise {
233             let mut params = self.parameters;
234             if self.has_self_param {
235                 params.remove(0);
236             }
237             (params.join(", "), None, params)
238         } else {
239             (self.to_string(), self.doc.map(|it| it.conv()), self.parameters)
240         };
241
242         let parameters: Vec<ParameterInformation> = params
243             .into_iter()
244             .map(|param| ParameterInformation {
245                 label: ParameterLabel::Simple(param),
246                 documentation: None,
247             })
248             .collect();
249
250         SignatureInformation { label, documentation, parameters: Some(parameters) }
251     }
252 }
253
254 impl ConvWith<(&LineIndex, LineEndings)> for TextEdit {
255     type Output = Vec<lsp_types::TextEdit>;
256
257     fn conv_with(self, ctx: (&LineIndex, LineEndings)) -> Vec<lsp_types::TextEdit> {
258         self.as_atoms().iter().map_conv_with(ctx).collect()
259     }
260 }
261
262 impl ConvWith<(&LineIndex, LineEndings)> for &AtomTextEdit {
263     type Output = lsp_types::TextEdit;
264
265     fn conv_with(
266         self,
267         (line_index, line_endings): (&LineIndex, LineEndings),
268     ) -> lsp_types::TextEdit {
269         let mut new_text = self.insert.clone();
270         if line_endings == LineEndings::Dos {
271             new_text = new_text.replace('\n', "\r\n");
272         }
273         lsp_types::TextEdit { range: self.delete.conv_with(line_index), new_text }
274     }
275 }
276
277 pub(crate) struct FoldConvCtx<'a> {
278     pub(crate) text: &'a str,
279     pub(crate) line_index: &'a LineIndex,
280     pub(crate) line_folding_only: bool,
281 }
282
283 impl ConvWith<&FoldConvCtx<'_>> for Fold {
284     type Output = lsp_types::FoldingRange;
285
286     fn conv_with(self, ctx: &FoldConvCtx) -> lsp_types::FoldingRange {
287         let kind = match self.kind {
288             FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
289             FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
290             FoldKind::Mods => None,
291             FoldKind::Block => None,
292         };
293
294         let range = self.range.conv_with(&ctx.line_index);
295
296         if ctx.line_folding_only {
297             // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
298             // even if it contains text not in the folding range. To prevent that we exclude
299             // range.end.line from the folding region if there is more text after range.end
300             // on the same line.
301             let has_more_text_on_end_line = ctx.text
302                 [TextRange::from_to(self.range.end(), TextUnit::of_str(ctx.text))]
303             .chars()
304             .take_while(|it| *it != '\n')
305             .any(|it| !it.is_whitespace());
306
307             let end_line = if has_more_text_on_end_line {
308                 range.end.line.saturating_sub(1)
309             } else {
310                 range.end.line
311             };
312
313             lsp_types::FoldingRange {
314                 start_line: range.start.line,
315                 start_character: None,
316                 end_line,
317                 end_character: None,
318                 kind,
319             }
320         } else {
321             lsp_types::FoldingRange {
322                 start_line: range.start.line,
323                 start_character: Some(range.start.character),
324                 end_line: range.end.line,
325                 end_character: Some(range.end.character),
326                 kind,
327             }
328         }
329     }
330 }
331
332 impl ConvWith<&LineIndex> for InlayHint {
333     type Output = req::InlayHint;
334     fn conv_with(self, line_index: &LineIndex) -> Self::Output {
335         req::InlayHint {
336             label: self.label.to_string(),
337             range: self.range.conv_with(line_index),
338             kind: match self.kind {
339                 InlayKind::ParameterHint => req::InlayKind::ParameterHint,
340                 InlayKind::TypeHint => req::InlayKind::TypeHint,
341                 InlayKind::ChainingHint => req::InlayKind::ChainingHint,
342             },
343         }
344     }
345 }
346
347 impl Conv for Highlight {
348     type Output = (u32, u32);
349
350     fn conv(self) -> Self::Output {
351         let mut mods = ModifierSet::default();
352         let type_ = match self.tag {
353             HighlightTag::Struct => SemanticTokenType::STRUCT,
354             HighlightTag::Enum => SemanticTokenType::ENUM,
355             HighlightTag::Union => UNION,
356             HighlightTag::TypeAlias => TYPE_ALIAS,
357             HighlightTag::Trait => SemanticTokenType::INTERFACE,
358             HighlightTag::BuiltinType => BUILTIN_TYPE,
359             HighlightTag::SelfType => SemanticTokenType::TYPE,
360             HighlightTag::Field => SemanticTokenType::MEMBER,
361             HighlightTag::Function => SemanticTokenType::FUNCTION,
362             HighlightTag::Module => SemanticTokenType::NAMESPACE,
363             HighlightTag::Constant => {
364                 mods |= CONSTANT;
365                 mods |= SemanticTokenModifier::STATIC;
366                 SemanticTokenType::VARIABLE
367             }
368             HighlightTag::Static => {
369                 mods |= SemanticTokenModifier::STATIC;
370                 SemanticTokenType::VARIABLE
371             }
372             HighlightTag::EnumVariant => ENUM_MEMBER,
373             HighlightTag::Macro => SemanticTokenType::MACRO,
374             HighlightTag::Local => SemanticTokenType::VARIABLE,
375             HighlightTag::TypeParam => SemanticTokenType::TYPE_PARAMETER,
376             HighlightTag::Lifetime => LIFETIME,
377             HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => SemanticTokenType::NUMBER,
378             HighlightTag::CharLiteral | HighlightTag::StringLiteral => SemanticTokenType::STRING,
379             HighlightTag::Comment => SemanticTokenType::COMMENT,
380             HighlightTag::Attribute => ATTRIBUTE,
381             HighlightTag::Keyword => SemanticTokenType::KEYWORD,
382             HighlightTag::UnresolvedReference => UNRESOLVED_REFERENCE,
383         };
384
385         for modifier in self.modifiers.iter() {
386             let modifier = match modifier {
387                 HighlightModifier::Definition => SemanticTokenModifier::DECLARATION,
388                 HighlightModifier::ControlFlow => CONTROL_FLOW,
389                 HighlightModifier::Mutable => MUTABLE,
390                 HighlightModifier::Unsafe => UNSAFE,
391             };
392             mods |= modifier;
393         }
394
395         (semantic_tokens::type_index(type_), mods.0)
396     }
397 }
398
399 impl<T: ConvWith<CTX>, CTX> ConvWith<CTX> for Option<T> {
400     type Output = Option<T::Output>;
401
402     fn conv_with(self, ctx: CTX) -> Self::Output {
403         self.map(|x| ConvWith::conv_with(x, ctx))
404     }
405 }
406
407 impl TryConvWith<&WorldSnapshot> for &Url {
408     type Output = FileId;
409     fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
410         world.uri_to_file_id(self)
411     }
412 }
413
414 impl TryConvWith<&WorldSnapshot> for FileId {
415     type Output = Url;
416     fn try_conv_with(self, world: &WorldSnapshot) -> Result<Url> {
417         world.file_id_to_uri(self)
418     }
419 }
420
421 impl TryConvWith<&WorldSnapshot> for &TextDocumentItem {
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 &VersionedTextDocumentIdentifier {
429     type Output = FileId;
430     fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
431         self.uri.try_conv_with(world)
432     }
433 }
434
435 impl TryConvWith<&WorldSnapshot> for &TextDocumentIdentifier {
436     type Output = FileId;
437     fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
438         world.uri_to_file_id(&self.uri)
439     }
440 }
441
442 impl TryConvWith<&WorldSnapshot> for &TextDocumentPositionParams {
443     type Output = FilePosition;
444     fn try_conv_with(self, world: &WorldSnapshot) -> Result<FilePosition> {
445         let file_id = self.text_document.try_conv_with(world)?;
446         let line_index = world.analysis().file_line_index(file_id)?;
447         let offset = self.position.conv_with(&line_index);
448         Ok(FilePosition { file_id, offset })
449     }
450 }
451
452 impl TryConvWith<&WorldSnapshot> for (&TextDocumentIdentifier, Range) {
453     type Output = FileRange;
454     fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileRange> {
455         let file_id = self.0.try_conv_with(world)?;
456         let line_index = world.analysis().file_line_index(file_id)?;
457         let range = self.1.conv_with(&line_index);
458         Ok(FileRange { file_id, range })
459     }
460 }
461
462 impl<T: TryConvWith<CTX>, CTX: Copy> TryConvWith<CTX> for Vec<T> {
463     type Output = Vec<<T as TryConvWith<CTX>>::Output>;
464     fn try_conv_with(self, ctx: CTX) -> Result<Self::Output> {
465         let mut res = Vec::with_capacity(self.len());
466         for item in self {
467             res.push(item.try_conv_with(ctx)?);
468         }
469         Ok(res)
470     }
471 }
472
473 impl TryConvWith<&WorldSnapshot> for SourceChange {
474     type Output = req::SourceChange;
475     fn try_conv_with(self, world: &WorldSnapshot) -> Result<req::SourceChange> {
476         let cursor_position = match self.cursor_position {
477             None => None,
478             Some(pos) => {
479                 let line_index = world.analysis().file_line_index(pos.file_id)?;
480                 let edit = self
481                     .source_file_edits
482                     .iter()
483                     .find(|it| it.file_id == pos.file_id)
484                     .map(|it| &it.edit);
485                 let line_col = match edit {
486                     Some(edit) => translate_offset_with_edit(&*line_index, pos.offset, edit),
487                     None => line_index.line_col(pos.offset),
488                 };
489                 let position =
490                     Position::new(u64::from(line_col.line), u64::from(line_col.col_utf16));
491                 Some(TextDocumentPositionParams {
492                     text_document: TextDocumentIdentifier::new(pos.file_id.try_conv_with(world)?),
493                     position,
494                 })
495             }
496         };
497         let mut document_changes: Vec<DocumentChangeOperation> = Vec::new();
498         for resource_op in self.file_system_edits.try_conv_with(world)? {
499             document_changes.push(DocumentChangeOperation::Op(resource_op));
500         }
501         for text_document_edit in self.source_file_edits.try_conv_with(world)? {
502             document_changes.push(DocumentChangeOperation::Edit(text_document_edit));
503         }
504         let workspace_edit = WorkspaceEdit {
505             changes: None,
506             document_changes: Some(DocumentChanges::Operations(document_changes)),
507         };
508         Ok(req::SourceChange { label: self.label, workspace_edit, cursor_position })
509     }
510 }
511
512 impl TryConvWith<&WorldSnapshot> for SourceFileEdit {
513     type Output = TextDocumentEdit;
514     fn try_conv_with(self, world: &WorldSnapshot) -> Result<TextDocumentEdit> {
515         let text_document = VersionedTextDocumentIdentifier {
516             uri: self.file_id.try_conv_with(world)?,
517             version: None,
518         };
519         let line_index = world.analysis().file_line_index(self.file_id)?;
520         let line_endings = world.file_line_endings(self.file_id);
521         let edits =
522             self.edit.as_atoms().iter().map_conv_with((&line_index, line_endings)).collect();
523         Ok(TextDocumentEdit { text_document, edits })
524     }
525 }
526
527 impl TryConvWith<&WorldSnapshot> for FileSystemEdit {
528     type Output = ResourceOp;
529     fn try_conv_with(self, world: &WorldSnapshot) -> Result<ResourceOp> {
530         let res = match self {
531             FileSystemEdit::CreateFile { source_root, path } => {
532                 let uri = world.path_to_uri(source_root, &path)?;
533                 ResourceOp::Create(CreateFile { uri, options: None })
534             }
535             FileSystemEdit::MoveFile { src, dst_source_root, dst_path } => {
536                 let old_uri = world.file_id_to_uri(src)?;
537                 let new_uri = world.path_to_uri(dst_source_root, &dst_path)?;
538                 ResourceOp::Rename(RenameFile { old_uri, new_uri, options: None })
539             }
540         };
541         Ok(res)
542     }
543 }
544
545 impl TryConvWith<&WorldSnapshot> for &NavigationTarget {
546     type Output = Location;
547     fn try_conv_with(self, world: &WorldSnapshot) -> Result<Location> {
548         let line_index = world.analysis().file_line_index(self.file_id())?;
549         let range = self.range();
550         to_location(self.file_id(), range, &world, &line_index)
551     }
552 }
553
554 impl TryConvWith<&WorldSnapshot> for (FileId, RangeInfo<NavigationTarget>) {
555     type Output = LocationLink;
556     fn try_conv_with(self, world: &WorldSnapshot) -> Result<LocationLink> {
557         let (src_file_id, target) = self;
558
559         let target_uri = target.info.file_id().try_conv_with(world)?;
560         let src_line_index = world.analysis().file_line_index(src_file_id)?;
561         let tgt_line_index = world.analysis().file_line_index(target.info.file_id())?;
562
563         let target_range = target.info.full_range().conv_with(&tgt_line_index);
564
565         let target_selection_range = target
566             .info
567             .focus_range()
568             .map(|it| it.conv_with(&tgt_line_index))
569             .unwrap_or(target_range);
570
571         let res = LocationLink {
572             origin_selection_range: Some(target.range.conv_with(&src_line_index)),
573             target_uri,
574             target_range,
575             target_selection_range,
576         };
577         Ok(res)
578     }
579 }
580
581 impl TryConvWith<&WorldSnapshot> for (FileId, RangeInfo<Vec<NavigationTarget>>) {
582     type Output = req::GotoDefinitionResponse;
583     fn try_conv_with(self, world: &WorldSnapshot) -> Result<req::GotoTypeDefinitionResponse> {
584         let (file_id, RangeInfo { range, info: navs }) = self;
585         let links = navs
586             .into_iter()
587             .map(|nav| (file_id, RangeInfo::new(range, nav)))
588             .try_conv_with_to_vec(world)?;
589         if world.config.client_caps.location_link {
590             Ok(links.into())
591         } else {
592             let locations: Vec<Location> = links
593                 .into_iter()
594                 .map(|link| Location { uri: link.target_uri, range: link.target_selection_range })
595                 .collect();
596             Ok(locations.into())
597         }
598     }
599 }
600
601 pub fn to_call_hierarchy_item(
602     file_id: FileId,
603     range: TextRange,
604     world: &WorldSnapshot,
605     line_index: &LineIndex,
606     nav: NavigationTarget,
607 ) -> Result<lsp_types::CallHierarchyItem> {
608     Ok(lsp_types::CallHierarchyItem {
609         name: nav.name().to_string(),
610         kind: nav.kind().conv(),
611         tags: None,
612         detail: nav.description().map(|it| it.to_string()),
613         uri: file_id.try_conv_with(&world)?,
614         range: nav.range().conv_with(&line_index),
615         selection_range: range.conv_with(&line_index),
616     })
617 }
618
619 pub fn to_location(
620     file_id: FileId,
621     range: TextRange,
622     world: &WorldSnapshot,
623     line_index: &LineIndex,
624 ) -> Result<Location> {
625     let url = file_id.try_conv_with(world)?;
626     let loc = Location::new(url, range.conv_with(line_index));
627     Ok(loc)
628 }
629
630 pub trait MapConvWith<CTX>: Sized {
631     type Output;
632
633     fn map_conv_with(self, ctx: CTX) -> ConvWithIter<Self, CTX> {
634         ConvWithIter { iter: self, ctx }
635     }
636 }
637
638 impl<CTX, I> MapConvWith<CTX> for I
639 where
640     I: Iterator,
641     I::Item: ConvWith<CTX>,
642 {
643     type Output = <I::Item as ConvWith<CTX>>::Output;
644 }
645
646 pub struct ConvWithIter<I, CTX> {
647     iter: I,
648     ctx: CTX,
649 }
650
651 impl<I, CTX> Iterator for ConvWithIter<I, CTX>
652 where
653     I: Iterator,
654     I::Item: ConvWith<CTX>,
655     CTX: Copy,
656 {
657     type Item = <I::Item as ConvWith<CTX>>::Output;
658
659     fn next(&mut self) -> Option<Self::Item> {
660         self.iter.next().map(|item| item.conv_with(self.ctx))
661     }
662 }
663
664 pub trait TryConvWithToVec<CTX>: Sized {
665     type Output;
666
667     fn try_conv_with_to_vec(self, ctx: CTX) -> Result<Vec<Self::Output>>;
668 }
669
670 impl<I, CTX> TryConvWithToVec<CTX> for I
671 where
672     I: Iterator,
673     I::Item: TryConvWith<CTX>,
674     CTX: Copy,
675 {
676     type Output = <I::Item as TryConvWith<CTX>>::Output;
677
678     fn try_conv_with_to_vec(self, ctx: CTX) -> Result<Vec<Self::Output>> {
679         self.map(|it| it.try_conv_with(ctx)).collect()
680     }
681 }
682
683 #[cfg(test)]
684 mod tests {
685     use super::*;
686     use test_utils::extract_ranges;
687
688     #[test]
689     fn conv_fold_line_folding_only_fixup() {
690         let text = r#"<fold>mod a;
691 mod b;
692 mod c;</fold>
693
694 fn main() <fold>{
695     if cond <fold>{
696         a::do_a();
697     }</fold> else <fold>{
698         b::do_b();
699     }</fold>
700 }</fold>"#;
701
702         let (ranges, text) = extract_ranges(text, "fold");
703         assert_eq!(ranges.len(), 4);
704         let folds = vec![
705             Fold { range: ranges[0], kind: FoldKind::Mods },
706             Fold { range: ranges[1], kind: FoldKind::Block },
707             Fold { range: ranges[2], kind: FoldKind::Block },
708             Fold { range: ranges[3], kind: FoldKind::Block },
709         ];
710
711         let line_index = LineIndex::new(&text);
712         let ctx = FoldConvCtx { text: &text, line_index: &line_index, line_folding_only: true };
713         let converted: Vec<_> = folds.into_iter().map_conv_with(&ctx).collect();
714
715         let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
716         assert_eq!(converted.len(), expected_lines.len());
717         for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
718             assert_eq!(folding_range.start_line, *start_line);
719             assert_eq!(folding_range.start_character, None);
720             assert_eq!(folding_range.end_line, *end_line);
721             assert_eq!(folding_range.end_character, None);
722         }
723     }
724 }