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