]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/to_proto.rs
Preliminary implementation of lazy CodeAssits
[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,
7     ResolvedAssist, Severity, 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 snippet_text_edit_vec(
139     line_index: &LineIndex,
140     line_endings: LineEndings,
141     is_snippet: bool,
142     text_edit: TextEdit,
143 ) -> Vec<lsp_ext::SnippetTextEdit> {
144     text_edit
145         .into_iter()
146         .map(|indel| self::snippet_text_edit(line_index, line_endings, is_snippet, indel))
147         .collect()
148 }
149
150 pub(crate) fn completion_item(
151     line_index: &LineIndex,
152     line_endings: LineEndings,
153     completion_item: CompletionItem,
154 ) -> lsp_types::CompletionItem {
155     let mut additional_text_edits = Vec::new();
156     let mut text_edit = None;
157     // LSP does not allow arbitrary edits in completion, so we have to do a
158     // non-trivial mapping here.
159     let source_range = completion_item.source_range();
160     for indel in completion_item.text_edit().iter() {
161         if indel.delete.contains_range(source_range) {
162             text_edit = Some(if indel.delete == source_range {
163                 self::text_edit(line_index, line_endings, indel.clone())
164             } else {
165                 assert!(source_range.end() == indel.delete.end());
166                 let range1 = TextRange::new(indel.delete.start(), source_range.start());
167                 let range2 = source_range;
168                 let indel1 = Indel::replace(range1, String::new());
169                 let indel2 = Indel::replace(range2, indel.insert.clone());
170                 additional_text_edits.push(self::text_edit(line_index, line_endings, indel1));
171                 self::text_edit(line_index, line_endings, indel2)
172             })
173         } else {
174             assert!(source_range.intersect(indel.delete).is_none());
175             let text_edit = self::text_edit(line_index, line_endings, indel.clone());
176             additional_text_edits.push(text_edit);
177         }
178     }
179     let text_edit = text_edit.unwrap();
180
181     let mut res = lsp_types::CompletionItem {
182         label: completion_item.label().to_string(),
183         detail: completion_item.detail().map(|it| it.to_string()),
184         filter_text: Some(completion_item.lookup().to_string()),
185         kind: completion_item.kind().map(completion_item_kind),
186         text_edit: Some(text_edit.into()),
187         additional_text_edits: Some(additional_text_edits),
188         documentation: completion_item.documentation().map(documentation),
189         deprecated: Some(completion_item.deprecated()),
190         ..Default::default()
191     };
192
193     if completion_item.score().is_some() {
194         res.preselect = Some(true);
195         // HACK: sort preselect items first
196         res.sort_text = Some(format!(" {}", completion_item.label()));
197     }
198
199     if completion_item.deprecated() {
200         res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
201     }
202
203     if completion_item.trigger_call_info() {
204         res.command = Some(lsp_types::Command {
205             title: "triggerParameterHints".into(),
206             command: "editor.action.triggerParameterHints".into(),
207             arguments: None,
208         });
209     }
210
211     res.insert_text_format = Some(insert_text_format(completion_item.insert_text_format()));
212
213     res
214 }
215
216 pub(crate) fn signature_information(
217     signature: FunctionSignature,
218     concise: bool,
219 ) -> lsp_types::SignatureInformation {
220     let (label, documentation, params) = if concise {
221         let mut params = signature.parameters;
222         if signature.has_self_param {
223             params.remove(0);
224         }
225         (params.join(", "), None, params)
226     } else {
227         (signature.to_string(), signature.doc.map(documentation), signature.parameters)
228     };
229
230     let parameters: Vec<lsp_types::ParameterInformation> = params
231         .into_iter()
232         .map(|param| lsp_types::ParameterInformation {
233             label: lsp_types::ParameterLabel::Simple(param),
234             documentation: None,
235         })
236         .collect();
237
238     lsp_types::SignatureInformation { label, documentation, parameters: Some(parameters) }
239 }
240
241 pub(crate) fn inlay_int(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
242     lsp_ext::InlayHint {
243         label: inlay_hint.label.to_string(),
244         range: range(line_index, inlay_hint.range),
245         kind: match inlay_hint.kind {
246             InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
247             InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
248             InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
249         },
250     }
251 }
252
253 pub(crate) fn semantic_tokens(
254     text: &str,
255     line_index: &LineIndex,
256     highlights: Vec<HighlightedRange>,
257 ) -> lsp_types::SemanticTokens {
258     let mut builder = semantic_tokens::SemanticTokensBuilder::default();
259
260     for highlight_range in highlights {
261         let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
262         let token_index = semantic_tokens::type_index(type_);
263         let modifier_bitset = mods.0;
264
265         for mut text_range in line_index.lines(highlight_range.range) {
266             if text[text_range].ends_with('\n') {
267                 text_range =
268                     TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
269             }
270             let range = range(&line_index, text_range);
271             builder.push(range, token_index, modifier_bitset);
272         }
273     }
274
275     builder.build()
276 }
277
278 fn semantic_token_type_and_modifiers(
279     highlight: Highlight,
280 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
281     let mut mods = semantic_tokens::ModifierSet::default();
282     let type_ = match highlight.tag {
283         HighlightTag::Struct => lsp_types::SemanticTokenType::STRUCT,
284         HighlightTag::Enum => lsp_types::SemanticTokenType::ENUM,
285         HighlightTag::Union => semantic_tokens::UNION,
286         HighlightTag::TypeAlias => semantic_tokens::TYPE_ALIAS,
287         HighlightTag::Trait => lsp_types::SemanticTokenType::INTERFACE,
288         HighlightTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
289         HighlightTag::SelfKeyword => semantic_tokens::SELF_KEYWORD,
290         HighlightTag::SelfType => lsp_types::SemanticTokenType::TYPE,
291         HighlightTag::Field => lsp_types::SemanticTokenType::PROPERTY,
292         HighlightTag::Function => lsp_types::SemanticTokenType::FUNCTION,
293         HighlightTag::Module => lsp_types::SemanticTokenType::NAMESPACE,
294         HighlightTag::Constant => {
295             mods |= semantic_tokens::CONSTANT;
296             mods |= lsp_types::SemanticTokenModifier::STATIC;
297             lsp_types::SemanticTokenType::VARIABLE
298         }
299         HighlightTag::Static => {
300             mods |= lsp_types::SemanticTokenModifier::STATIC;
301             lsp_types::SemanticTokenType::VARIABLE
302         }
303         HighlightTag::EnumVariant => semantic_tokens::ENUM_MEMBER,
304         HighlightTag::Macro => lsp_types::SemanticTokenType::MACRO,
305         HighlightTag::Local => lsp_types::SemanticTokenType::VARIABLE,
306         HighlightTag::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
307         HighlightTag::Lifetime => semantic_tokens::LIFETIME,
308         HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => {
309             lsp_types::SemanticTokenType::NUMBER
310         }
311         HighlightTag::BoolLiteral => semantic_tokens::BOOLEAN,
312         HighlightTag::CharLiteral | HighlightTag::StringLiteral => {
313             lsp_types::SemanticTokenType::STRING
314         }
315         HighlightTag::Comment => lsp_types::SemanticTokenType::COMMENT,
316         HighlightTag::Attribute => semantic_tokens::ATTRIBUTE,
317         HighlightTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
318         HighlightTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
319         HighlightTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
320         HighlightTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
321     };
322
323     for modifier in highlight.modifiers.iter() {
324         let modifier = match modifier {
325             HighlightModifier::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
326             HighlightModifier::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
327             HighlightModifier::ControlFlow => semantic_tokens::CONTROL_FLOW,
328             HighlightModifier::Mutable => semantic_tokens::MUTABLE,
329             HighlightModifier::Unsafe => semantic_tokens::UNSAFE,
330         };
331         mods |= modifier;
332     }
333
334     (type_, mods)
335 }
336
337 pub(crate) fn folding_range(
338     text: &str,
339     line_index: &LineIndex,
340     line_folding_only: bool,
341     fold: Fold,
342 ) -> lsp_types::FoldingRange {
343     let kind = match fold.kind {
344         FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
345         FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
346         FoldKind::Mods | FoldKind::Block => None,
347     };
348
349     let range = range(line_index, fold.range);
350
351     if line_folding_only {
352         // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
353         // even if it contains text not in the folding range. To prevent that we exclude
354         // range.end.line from the folding region if there is more text after range.end
355         // on the same line.
356         let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
357             .chars()
358             .take_while(|it| *it != '\n')
359             .any(|it| !it.is_whitespace());
360
361         let end_line = if has_more_text_on_end_line {
362             range.end.line.saturating_sub(1)
363         } else {
364             range.end.line
365         };
366
367         lsp_types::FoldingRange {
368             start_line: range.start.line,
369             start_character: None,
370             end_line,
371             end_character: None,
372             kind,
373         }
374     } else {
375         lsp_types::FoldingRange {
376             start_line: range.start.line,
377             start_character: Some(range.start.character),
378             end_line: range.end.line,
379             end_character: Some(range.end.character),
380             kind,
381         }
382     }
383 }
384
385 pub(crate) fn url(world: &WorldSnapshot, file_id: FileId) -> Result<lsp_types::Url> {
386     world.file_id_to_uri(file_id)
387 }
388
389 pub(crate) fn versioned_text_document_identifier(
390     world: &WorldSnapshot,
391     file_id: FileId,
392     version: Option<i64>,
393 ) -> Result<lsp_types::VersionedTextDocumentIdentifier> {
394     let res = lsp_types::VersionedTextDocumentIdentifier { uri: url(world, file_id)?, version };
395     Ok(res)
396 }
397
398 pub(crate) fn location(world: &WorldSnapshot, frange: FileRange) -> Result<lsp_types::Location> {
399     let url = url(world, frange.file_id)?;
400     let line_index = world.analysis().file_line_index(frange.file_id)?;
401     let range = range(&line_index, frange.range);
402     let loc = lsp_types::Location::new(url, range);
403     Ok(loc)
404 }
405
406 pub(crate) fn location_link(
407     world: &WorldSnapshot,
408     src: Option<FileRange>,
409     target: NavigationTarget,
410 ) -> Result<lsp_types::LocationLink> {
411     let origin_selection_range = match src {
412         Some(src) => {
413             let line_index = world.analysis().file_line_index(src.file_id)?;
414             let range = range(&line_index, src.range);
415             Some(range)
416         }
417         None => None,
418     };
419     let (target_uri, target_range, target_selection_range) = location_info(world, target)?;
420     let res = lsp_types::LocationLink {
421         origin_selection_range,
422         target_uri,
423         target_range,
424         target_selection_range,
425     };
426     Ok(res)
427 }
428
429 fn location_info(
430     world: &WorldSnapshot,
431     target: NavigationTarget,
432 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
433     let line_index = world.analysis().file_line_index(target.file_id())?;
434
435     let target_uri = url(world, target.file_id())?;
436     let target_range = range(&line_index, target.full_range());
437     let target_selection_range =
438         target.focus_range().map(|it| range(&line_index, it)).unwrap_or(target_range);
439     Ok((target_uri, target_range, target_selection_range))
440 }
441
442 pub(crate) fn goto_definition_response(
443     world: &WorldSnapshot,
444     src: Option<FileRange>,
445     targets: Vec<NavigationTarget>,
446 ) -> Result<lsp_types::GotoDefinitionResponse> {
447     if world.config.client_caps.location_link {
448         let links = targets
449             .into_iter()
450             .map(|nav| location_link(world, src, nav))
451             .collect::<Result<Vec<_>>>()?;
452         Ok(links.into())
453     } else {
454         let locations = targets
455             .into_iter()
456             .map(|nav| {
457                 location(
458                     world,
459                     FileRange {
460                         file_id: nav.file_id(),
461                         range: nav.focus_range().unwrap_or(nav.range()),
462                     },
463                 )
464             })
465             .collect::<Result<Vec<_>>>()?;
466         Ok(locations.into())
467     }
468 }
469
470 pub(crate) fn snippet_text_document_edit(
471     world: &WorldSnapshot,
472     is_snippet: bool,
473     source_file_edit: SourceFileEdit,
474 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
475     let text_document = versioned_text_document_identifier(world, source_file_edit.file_id, None)?;
476     let line_index = world.analysis().file_line_index(source_file_edit.file_id)?;
477     let line_endings = world.file_line_endings(source_file_edit.file_id);
478     let edits = source_file_edit
479         .edit
480         .into_iter()
481         .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
482         .collect();
483     Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
484 }
485
486 pub(crate) fn resource_op(
487     world: &WorldSnapshot,
488     file_system_edit: FileSystemEdit,
489 ) -> Result<lsp_types::ResourceOp> {
490     let res = match file_system_edit {
491         FileSystemEdit::CreateFile { source_root, path } => {
492             let uri = world.path_to_uri(source_root, &path)?;
493             lsp_types::ResourceOp::Create(lsp_types::CreateFile { uri, options: None })
494         }
495         FileSystemEdit::MoveFile { src, dst_source_root, dst_path } => {
496             let old_uri = world.file_id_to_uri(src)?;
497             let new_uri = world.path_to_uri(dst_source_root, &dst_path)?;
498             lsp_types::ResourceOp::Rename(lsp_types::RenameFile { old_uri, new_uri, options: None })
499         }
500     };
501     Ok(res)
502 }
503
504 pub(crate) fn snippet_workspace_edit(
505     world: &WorldSnapshot,
506     source_change: SourceChange,
507 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
508     let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
509     for op in source_change.file_system_edits {
510         let op = resource_op(&world, op)?;
511         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Op(op));
512     }
513     for edit in source_change.source_file_edits {
514         let edit = snippet_text_document_edit(&world, source_change.is_snippet, edit)?;
515         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
516     }
517     let workspace_edit =
518         lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
519     Ok(workspace_edit)
520 }
521
522 pub(crate) fn workspace_edit(
523     world: &WorldSnapshot,
524     source_change: SourceChange,
525 ) -> Result<lsp_types::WorkspaceEdit> {
526     assert!(!source_change.is_snippet);
527     snippet_workspace_edit(world, source_change).map(|it| it.into())
528 }
529
530 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
531     fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
532         lsp_types::WorkspaceEdit {
533             changes: None,
534             document_changes: snippet_workspace_edit.document_changes.map(|changes| {
535                 lsp_types::DocumentChanges::Operations(
536                     changes
537                         .into_iter()
538                         .map(|change| match change {
539                             lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
540                                 lsp_types::DocumentChangeOperation::Op(op)
541                             }
542                             lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
543                                 lsp_types::DocumentChangeOperation::Edit(
544                                     lsp_types::TextDocumentEdit {
545                                         text_document: edit.text_document,
546                                         edits: edit
547                                             .edits
548                                             .into_iter()
549                                             .map(|edit| lsp_types::TextEdit {
550                                                 range: edit.range,
551                                                 new_text: edit.new_text,
552                                             })
553                                             .collect(),
554                                     },
555                                 )
556                             }
557                         })
558                         .collect(),
559                 )
560             }),
561         }
562     }
563 }
564
565 pub fn call_hierarchy_item(
566     world: &WorldSnapshot,
567     target: NavigationTarget,
568 ) -> Result<lsp_types::CallHierarchyItem> {
569     let name = target.name().to_string();
570     let detail = target.description().map(|it| it.to_string());
571     let kind = symbol_kind(target.kind());
572     let (uri, range, selection_range) = location_info(world, target)?;
573     Ok(lsp_types::CallHierarchyItem { name, kind, tags: None, detail, uri, range, selection_range })
574 }
575
576 #[cfg(test)]
577 mod tests {
578     use test_utils::extract_ranges;
579
580     use super::*;
581
582     #[test]
583     fn conv_fold_line_folding_only_fixup() {
584         let text = r#"<fold>mod a;
585 mod b;
586 mod c;</fold>
587
588 fn main() <fold>{
589     if cond <fold>{
590         a::do_a();
591     }</fold> else <fold>{
592         b::do_b();
593     }</fold>
594 }</fold>"#;
595
596         let (ranges, text) = extract_ranges(text, "fold");
597         assert_eq!(ranges.len(), 4);
598         let folds = vec![
599             Fold { range: ranges[0], kind: FoldKind::Mods },
600             Fold { range: ranges[1], kind: FoldKind::Block },
601             Fold { range: ranges[2], kind: FoldKind::Block },
602             Fold { range: ranges[3], kind: FoldKind::Block },
603         ];
604
605         let line_index = LineIndex::new(&text);
606         let converted: Vec<lsp_types::FoldingRange> =
607             folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
608
609         let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
610         assert_eq!(converted.len(), expected_lines.len());
611         for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
612             assert_eq!(folding_range.start_line, *start_line);
613             assert_eq!(folding_range.start_character, None);
614             assert_eq!(folding_range.end_line, *end_line);
615             assert_eq!(folding_range.end_character, None);
616         }
617     }
618 }
619
620 pub(crate) fn unresolved_code_action(
621     world: &WorldSnapshot,
622     assist: Assist,
623 ) -> Result<lsp_ext::CodeAction> {
624     let res = lsp_ext::CodeAction {
625         title: assist.label,
626         id: Some(assist.id.0.to_owned()),
627         group: assist.group.and_then(|it| {
628             if world.config.client_caps.code_action_group {
629                 None
630             } else {
631                 Some(it.0)
632             }
633         }),
634         kind: Some(String::new()),
635         edit: None,
636         command: None,
637     };
638     Ok(res)
639 }
640
641 pub(crate) fn resolved_code_action(
642     world: &WorldSnapshot,
643     assist: ResolvedAssist,
644 ) -> Result<lsp_ext::CodeAction> {
645     let res = lsp_ext::CodeAction {
646         title: assist.assist.label,
647         id: Some(assist.assist.id.0.to_owned()),
648         group: assist.assist.group.and_then(|it| {
649             if world.config.client_caps.code_action_group {
650                 None
651             } else {
652                 Some(it.0)
653             }
654         }),
655         kind: Some(String::new()),
656         edit: Some(snippet_workspace_edit(world, assist.source_change)?),
657         command: None,
658     };
659     Ok(res)
660 }