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