]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/to_proto.rs
Add self keyword semantic token type
[rust.git] / crates / rust-analyzer / src / to_proto.rs
1 //! Conversion of rust-analyzer specific types to lsp_types equivalents.
2 use ra_db::{FileId, FileRange};
3 use ra_ide::{
4     Assist, CompletionItem, CompletionItemKind, Documentation, FileSystemEdit, Fold, FoldKind,
5     FunctionSignature, Highlight, HighlightModifier, HighlightTag, HighlightedRange, Indel,
6     InlayHint, InlayKind, InsertTextFormat, LineIndex, NavigationTarget, ReferenceAccess, Severity,
7     SourceChange, SourceFileEdit, TextEdit,
8 };
9 use ra_syntax::{SyntaxKind, TextRange, TextSize};
10 use ra_vfs::LineEndings;
11
12 use crate::{lsp_ext, semantic_tokens, world::WorldSnapshot, Result};
13
14 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
15     let line_col = line_index.line_col(offset);
16     let line = u64::from(line_col.line);
17     let character = u64::from(line_col.col_utf16);
18     lsp_types::Position::new(line, character)
19 }
20
21 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
22     let start = position(line_index, range.start());
23     let end = position(line_index, range.end());
24     lsp_types::Range::new(start, end)
25 }
26
27 pub(crate) fn symbol_kind(syntax_kind: SyntaxKind) -> lsp_types::SymbolKind {
28     match syntax_kind {
29         SyntaxKind::FN_DEF => lsp_types::SymbolKind::Function,
30         SyntaxKind::STRUCT_DEF => lsp_types::SymbolKind::Struct,
31         SyntaxKind::ENUM_DEF => lsp_types::SymbolKind::Enum,
32         SyntaxKind::ENUM_VARIANT => lsp_types::SymbolKind::EnumMember,
33         SyntaxKind::TRAIT_DEF => lsp_types::SymbolKind::Interface,
34         SyntaxKind::MACRO_CALL => lsp_types::SymbolKind::Function,
35         SyntaxKind::MODULE => lsp_types::SymbolKind::Module,
36         SyntaxKind::TYPE_ALIAS_DEF => lsp_types::SymbolKind::TypeParameter,
37         SyntaxKind::RECORD_FIELD_DEF => lsp_types::SymbolKind::Field,
38         SyntaxKind::STATIC_DEF => lsp_types::SymbolKind::Constant,
39         SyntaxKind::CONST_DEF => lsp_types::SymbolKind::Constant,
40         SyntaxKind::IMPL_DEF => lsp_types::SymbolKind::Object,
41         _ => lsp_types::SymbolKind::Variable,
42     }
43 }
44
45 pub(crate) fn document_highlight_kind(
46     reference_access: ReferenceAccess,
47 ) -> lsp_types::DocumentHighlightKind {
48     match reference_access {
49         ReferenceAccess::Read => lsp_types::DocumentHighlightKind::Read,
50         ReferenceAccess::Write => lsp_types::DocumentHighlightKind::Write,
51     }
52 }
53
54 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
55     match severity {
56         Severity::Error => lsp_types::DiagnosticSeverity::Error,
57         Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
58     }
59 }
60
61 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
62     let value = crate::markdown::format_docs(documentation.as_str());
63     let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
64     lsp_types::Documentation::MarkupContent(markup_content)
65 }
66
67 pub(crate) fn insert_text_format(
68     insert_text_format: InsertTextFormat,
69 ) -> lsp_types::InsertTextFormat {
70     match insert_text_format {
71         InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
72         InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
73     }
74 }
75
76 pub(crate) fn completion_item_kind(
77     completion_item_kind: CompletionItemKind,
78 ) -> lsp_types::CompletionItemKind {
79     match completion_item_kind {
80         CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
81         CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
82         CompletionItemKind::Module => lsp_types::CompletionItemKind::Module,
83         CompletionItemKind::Function => lsp_types::CompletionItemKind::Function,
84         CompletionItemKind::Struct => lsp_types::CompletionItemKind::Struct,
85         CompletionItemKind::Enum => lsp_types::CompletionItemKind::Enum,
86         CompletionItemKind::EnumVariant => lsp_types::CompletionItemKind::EnumMember,
87         CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
88         CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
89         CompletionItemKind::Field => lsp_types::CompletionItemKind::Field,
90         CompletionItemKind::Trait => lsp_types::CompletionItemKind::Interface,
91         CompletionItemKind::TypeAlias => lsp_types::CompletionItemKind::Struct,
92         CompletionItemKind::Const => lsp_types::CompletionItemKind::Constant,
93         CompletionItemKind::Static => lsp_types::CompletionItemKind::Value,
94         CompletionItemKind::Method => lsp_types::CompletionItemKind::Method,
95         CompletionItemKind::TypeParam => lsp_types::CompletionItemKind::TypeParameter,
96         CompletionItemKind::Macro => lsp_types::CompletionItemKind::Method,
97         CompletionItemKind::Attribute => lsp_types::CompletionItemKind::EnumMember,
98     }
99 }
100
101 pub(crate) fn text_edit(
102     line_index: &LineIndex,
103     line_endings: LineEndings,
104     indel: Indel,
105 ) -> lsp_types::TextEdit {
106     let range = range(line_index, indel.delete);
107     let new_text = match line_endings {
108         LineEndings::Unix => indel.insert,
109         LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
110     };
111     lsp_types::TextEdit { range, new_text }
112 }
113
114 pub(crate) fn snippet_text_edit(
115     line_index: &LineIndex,
116     line_endings: LineEndings,
117     is_snippet: bool,
118     indel: Indel,
119 ) -> lsp_ext::SnippetTextEdit {
120     let text_edit = text_edit(line_index, line_endings, indel);
121     let insert_text_format =
122         if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
123     lsp_ext::SnippetTextEdit {
124         range: text_edit.range,
125         new_text: text_edit.new_text,
126         insert_text_format,
127     }
128 }
129
130 pub(crate) fn text_edit_vec(
131     line_index: &LineIndex,
132     line_endings: LineEndings,
133     text_edit: TextEdit,
134 ) -> Vec<lsp_types::TextEdit> {
135     text_edit.into_iter().map(|indel| self::text_edit(line_index, line_endings, indel)).collect()
136 }
137
138 pub(crate) fn completion_item(
139     line_index: &LineIndex,
140     line_endings: LineEndings,
141     completion_item: CompletionItem,
142 ) -> lsp_types::CompletionItem {
143     let mut additional_text_edits = Vec::new();
144     let mut text_edit = None;
145     // LSP does not allow arbitrary edits in completion, so we have to do a
146     // non-trivial mapping here.
147     let source_range = completion_item.source_range();
148     for indel in completion_item.text_edit().iter() {
149         if indel.delete.contains_range(source_range) {
150             text_edit = Some(if indel.delete == source_range {
151                 self::text_edit(line_index, line_endings, indel.clone())
152             } else {
153                 assert!(source_range.end() == indel.delete.end());
154                 let range1 = TextRange::new(indel.delete.start(), source_range.start());
155                 let range2 = source_range;
156                 let indel1 = Indel::replace(range1, String::new());
157                 let indel2 = Indel::replace(range2, indel.insert.clone());
158                 additional_text_edits.push(self::text_edit(line_index, line_endings, indel1));
159                 self::text_edit(line_index, line_endings, indel2)
160             })
161         } else {
162             assert!(source_range.intersect(indel.delete).is_none());
163             let text_edit = self::text_edit(line_index, line_endings, indel.clone());
164             additional_text_edits.push(text_edit);
165         }
166     }
167     let text_edit = text_edit.unwrap();
168
169     let mut res = lsp_types::CompletionItem {
170         label: completion_item.label().to_string(),
171         detail: completion_item.detail().map(|it| it.to_string()),
172         filter_text: Some(completion_item.lookup().to_string()),
173         kind: completion_item.kind().map(completion_item_kind),
174         text_edit: Some(text_edit.into()),
175         additional_text_edits: Some(additional_text_edits),
176         documentation: completion_item.documentation().map(documentation),
177         deprecated: Some(completion_item.deprecated()),
178         ..Default::default()
179     };
180
181     if completion_item.score().is_some() {
182         res.preselect = Some(true);
183         // HACK: sort preselect items first
184         res.sort_text = Some(format!(" {}", completion_item.label()));
185     }
186
187     if completion_item.deprecated() {
188         res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
189     }
190
191     if completion_item.trigger_call_info() {
192         res.command = Some(lsp_types::Command {
193             title: "triggerParameterHints".into(),
194             command: "editor.action.triggerParameterHints".into(),
195             arguments: None,
196         });
197     }
198
199     res.insert_text_format = Some(insert_text_format(completion_item.insert_text_format()));
200
201     res
202 }
203
204 pub(crate) fn signature_information(
205     signature: FunctionSignature,
206     concise: bool,
207 ) -> lsp_types::SignatureInformation {
208     let (label, documentation, params) = if concise {
209         let mut params = signature.parameters;
210         if signature.has_self_param {
211             params.remove(0);
212         }
213         (params.join(", "), None, params)
214     } else {
215         (signature.to_string(), signature.doc.map(documentation), signature.parameters)
216     };
217
218     let parameters: Vec<lsp_types::ParameterInformation> = params
219         .into_iter()
220         .map(|param| lsp_types::ParameterInformation {
221             label: lsp_types::ParameterLabel::Simple(param),
222             documentation: None,
223         })
224         .collect();
225
226     lsp_types::SignatureInformation { label, documentation, parameters: Some(parameters) }
227 }
228
229 pub(crate) fn inlay_int(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
230     lsp_ext::InlayHint {
231         label: inlay_hint.label.to_string(),
232         range: range(line_index, inlay_hint.range),
233         kind: match inlay_hint.kind {
234             InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
235             InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
236             InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
237         },
238     }
239 }
240
241 pub(crate) fn semantic_tokens(
242     text: &str,
243     line_index: &LineIndex,
244     highlights: Vec<HighlightedRange>,
245 ) -> lsp_types::SemanticTokens {
246     let mut builder = semantic_tokens::SemanticTokensBuilder::default();
247
248     for highlight_range in highlights {
249         let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
250         let token_index = semantic_tokens::type_index(type_);
251         let modifier_bitset = mods.0;
252
253         for mut text_range in line_index.lines(highlight_range.range) {
254             if text[text_range].ends_with('\n') {
255                 text_range =
256                     TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
257             }
258             let range = range(&line_index, text_range);
259             builder.push(range, token_index, modifier_bitset);
260         }
261     }
262
263     builder.build()
264 }
265
266 fn semantic_token_type_and_modifiers(
267     highlight: Highlight,
268 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
269     let mut mods = semantic_tokens::ModifierSet::default();
270     let type_ = match highlight.tag {
271         HighlightTag::Struct => lsp_types::SemanticTokenType::STRUCT,
272         HighlightTag::Enum => lsp_types::SemanticTokenType::ENUM,
273         HighlightTag::Union => semantic_tokens::UNION,
274         HighlightTag::TypeAlias => semantic_tokens::TYPE_ALIAS,
275         HighlightTag::Trait => lsp_types::SemanticTokenType::INTERFACE,
276         HighlightTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
277         HighlightTag::SelfKeyword => semantic_tokens::SELF_KEYWORD,
278         HighlightTag::SelfType => lsp_types::SemanticTokenType::TYPE,
279         HighlightTag::Field => lsp_types::SemanticTokenType::PROPERTY,
280         HighlightTag::Function => lsp_types::SemanticTokenType::FUNCTION,
281         HighlightTag::Module => lsp_types::SemanticTokenType::NAMESPACE,
282         HighlightTag::Constant => {
283             mods |= semantic_tokens::CONSTANT;
284             mods |= lsp_types::SemanticTokenModifier::STATIC;
285             lsp_types::SemanticTokenType::VARIABLE
286         }
287         HighlightTag::Static => {
288             mods |= lsp_types::SemanticTokenModifier::STATIC;
289             lsp_types::SemanticTokenType::VARIABLE
290         }
291         HighlightTag::EnumVariant => semantic_tokens::ENUM_MEMBER,
292         HighlightTag::Macro => lsp_types::SemanticTokenType::MACRO,
293         HighlightTag::Local => lsp_types::SemanticTokenType::VARIABLE,
294         HighlightTag::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
295         HighlightTag::Lifetime => semantic_tokens::LIFETIME,
296         HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => {
297             lsp_types::SemanticTokenType::NUMBER
298         }
299         HighlightTag::BoolLiteral => semantic_tokens::BOOLEAN,
300         HighlightTag::CharLiteral | HighlightTag::StringLiteral => {
301             lsp_types::SemanticTokenType::STRING
302         }
303         HighlightTag::Comment => lsp_types::SemanticTokenType::COMMENT,
304         HighlightTag::Attribute => semantic_tokens::ATTRIBUTE,
305         HighlightTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
306         HighlightTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
307         HighlightTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
308     };
309
310     for modifier in highlight.modifiers.iter() {
311         let modifier = match modifier {
312             HighlightModifier::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
313             HighlightModifier::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
314             HighlightModifier::ControlFlow => semantic_tokens::CONTROL_FLOW,
315             HighlightModifier::Mutable => semantic_tokens::MUTABLE,
316             HighlightModifier::Unsafe => semantic_tokens::UNSAFE,
317         };
318         mods |= modifier;
319     }
320
321     (type_, mods)
322 }
323
324 pub(crate) fn folding_range(
325     text: &str,
326     line_index: &LineIndex,
327     line_folding_only: bool,
328     fold: Fold,
329 ) -> lsp_types::FoldingRange {
330     let kind = match fold.kind {
331         FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
332         FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
333         FoldKind::Mods | FoldKind::Block => None,
334     };
335
336     let range = range(line_index, fold.range);
337
338     if line_folding_only {
339         // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
340         // even if it contains text not in the folding range. To prevent that we exclude
341         // range.end.line from the folding region if there is more text after range.end
342         // on the same line.
343         let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
344             .chars()
345             .take_while(|it| *it != '\n')
346             .any(|it| !it.is_whitespace());
347
348         let end_line = if has_more_text_on_end_line {
349             range.end.line.saturating_sub(1)
350         } else {
351             range.end.line
352         };
353
354         lsp_types::FoldingRange {
355             start_line: range.start.line,
356             start_character: None,
357             end_line,
358             end_character: None,
359             kind,
360         }
361     } else {
362         lsp_types::FoldingRange {
363             start_line: range.start.line,
364             start_character: Some(range.start.character),
365             end_line: range.end.line,
366             end_character: Some(range.end.character),
367             kind,
368         }
369     }
370 }
371
372 pub(crate) fn url(world: &WorldSnapshot, file_id: FileId) -> Result<lsp_types::Url> {
373     world.file_id_to_uri(file_id)
374 }
375
376 pub(crate) fn versioned_text_document_identifier(
377     world: &WorldSnapshot,
378     file_id: FileId,
379     version: Option<i64>,
380 ) -> Result<lsp_types::VersionedTextDocumentIdentifier> {
381     let res = lsp_types::VersionedTextDocumentIdentifier { uri: url(world, file_id)?, version };
382     Ok(res)
383 }
384
385 pub(crate) fn location(world: &WorldSnapshot, frange: FileRange) -> Result<lsp_types::Location> {
386     let url = url(world, frange.file_id)?;
387     let line_index = world.analysis().file_line_index(frange.file_id)?;
388     let range = range(&line_index, frange.range);
389     let loc = lsp_types::Location::new(url, range);
390     Ok(loc)
391 }
392
393 pub(crate) fn location_link(
394     world: &WorldSnapshot,
395     src: FileRange,
396     target: NavigationTarget,
397 ) -> Result<lsp_types::LocationLink> {
398     let src_location = location(world, src)?;
399     let (target_uri, target_range, target_selection_range) = location_info(world, target)?;
400     let res = lsp_types::LocationLink {
401         origin_selection_range: Some(src_location.range),
402         target_uri,
403         target_range,
404         target_selection_range,
405     };
406     Ok(res)
407 }
408
409 fn location_info(
410     world: &WorldSnapshot,
411     target: NavigationTarget,
412 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
413     let line_index = world.analysis().file_line_index(target.file_id())?;
414
415     let target_uri = url(world, target.file_id())?;
416     let target_range = range(&line_index, target.full_range());
417     let target_selection_range =
418         target.focus_range().map(|it| range(&line_index, it)).unwrap_or(target_range);
419     Ok((target_uri, target_range, target_selection_range))
420 }
421
422 pub(crate) fn goto_definition_response(
423     world: &WorldSnapshot,
424     src: FileRange,
425     targets: Vec<NavigationTarget>,
426 ) -> Result<lsp_types::GotoDefinitionResponse> {
427     if world.config.client_caps.location_link {
428         let links = targets
429             .into_iter()
430             .map(|nav| location_link(world, src, nav))
431             .collect::<Result<Vec<_>>>()?;
432         Ok(links.into())
433     } else {
434         let locations = targets
435             .into_iter()
436             .map(|nav| {
437                 location(
438                     world,
439                     FileRange {
440                         file_id: nav.file_id(),
441                         range: nav.focus_range().unwrap_or(nav.range()),
442                     },
443                 )
444             })
445             .collect::<Result<Vec<_>>>()?;
446         Ok(locations.into())
447     }
448 }
449
450 pub(crate) fn snippet_text_document_edit(
451     world: &WorldSnapshot,
452     is_snippet: bool,
453     source_file_edit: SourceFileEdit,
454 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
455     let text_document = versioned_text_document_identifier(world, source_file_edit.file_id, None)?;
456     let line_index = world.analysis().file_line_index(source_file_edit.file_id)?;
457     let line_endings = world.file_line_endings(source_file_edit.file_id);
458     let edits = source_file_edit
459         .edit
460         .into_iter()
461         .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
462         .collect();
463     Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
464 }
465
466 pub(crate) fn resource_op(
467     world: &WorldSnapshot,
468     file_system_edit: FileSystemEdit,
469 ) -> Result<lsp_types::ResourceOp> {
470     let res = match file_system_edit {
471         FileSystemEdit::CreateFile { source_root, path } => {
472             let uri = world.path_to_uri(source_root, &path)?;
473             lsp_types::ResourceOp::Create(lsp_types::CreateFile { uri, options: None })
474         }
475         FileSystemEdit::MoveFile { src, dst_source_root, dst_path } => {
476             let old_uri = world.file_id_to_uri(src)?;
477             let new_uri = world.path_to_uri(dst_source_root, &dst_path)?;
478             lsp_types::ResourceOp::Rename(lsp_types::RenameFile { old_uri, new_uri, options: None })
479         }
480     };
481     Ok(res)
482 }
483
484 pub(crate) fn snippet_workspace_edit(
485     world: &WorldSnapshot,
486     source_change: SourceChange,
487 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
488     let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
489     for op in source_change.file_system_edits {
490         let op = resource_op(&world, op)?;
491         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Op(op));
492     }
493     for edit in source_change.source_file_edits {
494         let edit = snippet_text_document_edit(&world, source_change.is_snippet, edit)?;
495         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
496     }
497     let workspace_edit =
498         lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
499     Ok(workspace_edit)
500 }
501
502 pub(crate) fn workspace_edit(
503     world: &WorldSnapshot,
504     source_change: SourceChange,
505 ) -> Result<lsp_types::WorkspaceEdit> {
506     assert!(!source_change.is_snippet);
507     snippet_workspace_edit(world, source_change).map(|it| it.into())
508 }
509
510 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
511     fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
512         lsp_types::WorkspaceEdit {
513             changes: None,
514             document_changes: snippet_workspace_edit.document_changes.map(|changes| {
515                 lsp_types::DocumentChanges::Operations(
516                     changes
517                         .into_iter()
518                         .map(|change| match change {
519                             lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
520                                 lsp_types::DocumentChangeOperation::Op(op)
521                             }
522                             lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
523                                 lsp_types::DocumentChangeOperation::Edit(
524                                     lsp_types::TextDocumentEdit {
525                                         text_document: edit.text_document,
526                                         edits: edit
527                                             .edits
528                                             .into_iter()
529                                             .map(|edit| lsp_types::TextEdit {
530                                                 range: edit.range,
531                                                 new_text: edit.new_text,
532                                             })
533                                             .collect(),
534                                     },
535                                 )
536                             }
537                         })
538                         .collect(),
539                 )
540             }),
541         }
542     }
543 }
544
545 pub fn call_hierarchy_item(
546     world: &WorldSnapshot,
547     target: NavigationTarget,
548 ) -> Result<lsp_types::CallHierarchyItem> {
549     let name = target.name().to_string();
550     let detail = target.description().map(|it| it.to_string());
551     let kind = symbol_kind(target.kind());
552     let (uri, range, selection_range) = location_info(world, target)?;
553     Ok(lsp_types::CallHierarchyItem { name, kind, tags: None, detail, uri, range, selection_range })
554 }
555
556 #[cfg(test)]
557 mod tests {
558     use test_utils::extract_ranges;
559
560     use super::*;
561
562     #[test]
563     fn conv_fold_line_folding_only_fixup() {
564         let text = r#"<fold>mod a;
565 mod b;
566 mod c;</fold>
567
568 fn main() <fold>{
569     if cond <fold>{
570         a::do_a();
571     }</fold> else <fold>{
572         b::do_b();
573     }</fold>
574 }</fold>"#;
575
576         let (ranges, text) = extract_ranges(text, "fold");
577         assert_eq!(ranges.len(), 4);
578         let folds = vec![
579             Fold { range: ranges[0], kind: FoldKind::Mods },
580             Fold { range: ranges[1], kind: FoldKind::Block },
581             Fold { range: ranges[2], kind: FoldKind::Block },
582             Fold { range: ranges[3], kind: FoldKind::Block },
583         ];
584
585         let line_index = LineIndex::new(&text);
586         let converted: Vec<lsp_types::FoldingRange> =
587             folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
588
589         let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
590         assert_eq!(converted.len(), expected_lines.len());
591         for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
592             assert_eq!(folding_range.start_line, *start_line);
593             assert_eq!(folding_range.start_character, None);
594             assert_eq!(folding_range.end_line, *end_line);
595             assert_eq!(folding_range.end_character, None);
596         }
597     }
598 }
599
600 pub(crate) fn code_action(world: &WorldSnapshot, assist: Assist) -> Result<lsp_ext::CodeAction> {
601     let res = lsp_ext::CodeAction {
602         title: assist.label,
603         group: if world.config.client_caps.code_action_group { assist.group_label } else { None },
604         kind: Some(String::new()),
605         edit: Some(snippet_workspace_edit(world, assist.source_change)?),
606         command: None,
607     };
608     Ok(res)
609 }