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