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