]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/to_proto.rs
Merge #4711
[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, Runnable,
7     RunnableKind, Severity, SourceChange, SourceFileEdit, TextEdit,
8 };
9 use ra_syntax::{SyntaxKind, TextRange, TextSize};
10 use ra_vfs::LineEndings;
11 use rustc_hash::FxHashMap;
12
13 use crate::{
14     cargo_target_spec::CargoTargetSpec, lsp_ext, semantic_tokens, world::WorldSnapshot, 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(world: &WorldSnapshot, file_id: FileId) -> Result<lsp_types::Url> {
389     world.file_id_to_uri(file_id)
390 }
391
392 pub(crate) fn versioned_text_document_identifier(
393     world: &WorldSnapshot,
394     file_id: FileId,
395     version: Option<i64>,
396 ) -> Result<lsp_types::VersionedTextDocumentIdentifier> {
397     let res = lsp_types::VersionedTextDocumentIdentifier { uri: url(world, file_id)?, version };
398     Ok(res)
399 }
400
401 pub(crate) fn location(world: &WorldSnapshot, frange: FileRange) -> Result<lsp_types::Location> {
402     let url = url(world, frange.file_id)?;
403     let line_index = world.analysis().file_line_index(frange.file_id)?;
404     let range = range(&line_index, frange.range);
405     let loc = lsp_types::Location::new(url, range);
406     Ok(loc)
407 }
408
409 pub(crate) fn location_link(
410     world: &WorldSnapshot,
411     src: Option<FileRange>,
412     target: NavigationTarget,
413 ) -> Result<lsp_types::LocationLink> {
414     let origin_selection_range = match src {
415         Some(src) => {
416             let line_index = world.analysis().file_line_index(src.file_id)?;
417             let range = range(&line_index, src.range);
418             Some(range)
419         }
420         None => None,
421     };
422     let (target_uri, target_range, target_selection_range) = location_info(world, target)?;
423     let res = lsp_types::LocationLink {
424         origin_selection_range,
425         target_uri,
426         target_range,
427         target_selection_range,
428     };
429     Ok(res)
430 }
431
432 fn location_info(
433     world: &WorldSnapshot,
434     target: NavigationTarget,
435 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
436     let line_index = world.analysis().file_line_index(target.file_id())?;
437
438     let target_uri = url(world, target.file_id())?;
439     let target_range = range(&line_index, target.full_range());
440     let target_selection_range =
441         target.focus_range().map(|it| range(&line_index, it)).unwrap_or(target_range);
442     Ok((target_uri, target_range, target_selection_range))
443 }
444
445 pub(crate) fn goto_definition_response(
446     world: &WorldSnapshot,
447     src: Option<FileRange>,
448     targets: Vec<NavigationTarget>,
449 ) -> Result<lsp_types::GotoDefinitionResponse> {
450     if world.config.client_caps.location_link {
451         let links = targets
452             .into_iter()
453             .map(|nav| location_link(world, src, nav))
454             .collect::<Result<Vec<_>>>()?;
455         Ok(links.into())
456     } else {
457         let locations = targets
458             .into_iter()
459             .map(|nav| {
460                 location(
461                     world,
462                     FileRange {
463                         file_id: nav.file_id(),
464                         range: nav.focus_range().unwrap_or(nav.range()),
465                     },
466                 )
467             })
468             .collect::<Result<Vec<_>>>()?;
469         Ok(locations.into())
470     }
471 }
472
473 pub(crate) fn snippet_text_document_edit(
474     world: &WorldSnapshot,
475     is_snippet: bool,
476     source_file_edit: SourceFileEdit,
477 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
478     let text_document = versioned_text_document_identifier(world, source_file_edit.file_id, None)?;
479     let line_index = world.analysis().file_line_index(source_file_edit.file_id)?;
480     let line_endings = world.file_line_endings(source_file_edit.file_id);
481     let edits = source_file_edit
482         .edit
483         .into_iter()
484         .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
485         .collect();
486     Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
487 }
488
489 pub(crate) fn resource_op(
490     world: &WorldSnapshot,
491     file_system_edit: FileSystemEdit,
492 ) -> Result<lsp_types::ResourceOp> {
493     let res = match file_system_edit {
494         FileSystemEdit::CreateFile { source_root, path } => {
495             let uri = world.path_to_uri(source_root, &path)?;
496             lsp_types::ResourceOp::Create(lsp_types::CreateFile { uri, options: None })
497         }
498         FileSystemEdit::MoveFile { src, dst_source_root, dst_path } => {
499             let old_uri = world.file_id_to_uri(src)?;
500             let new_uri = world.path_to_uri(dst_source_root, &dst_path)?;
501             lsp_types::ResourceOp::Rename(lsp_types::RenameFile { old_uri, new_uri, options: None })
502         }
503     };
504     Ok(res)
505 }
506
507 pub(crate) fn snippet_workspace_edit(
508     world: &WorldSnapshot,
509     source_change: SourceChange,
510 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
511     let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
512     for op in source_change.file_system_edits {
513         let op = resource_op(&world, op)?;
514         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Op(op));
515     }
516     for edit in source_change.source_file_edits {
517         let edit = snippet_text_document_edit(&world, source_change.is_snippet, edit)?;
518         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
519     }
520     let workspace_edit =
521         lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
522     Ok(workspace_edit)
523 }
524
525 pub(crate) fn workspace_edit(
526     world: &WorldSnapshot,
527     source_change: SourceChange,
528 ) -> Result<lsp_types::WorkspaceEdit> {
529     assert!(!source_change.is_snippet);
530     snippet_workspace_edit(world, source_change).map(|it| it.into())
531 }
532
533 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
534     fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
535         lsp_types::WorkspaceEdit {
536             changes: None,
537             document_changes: snippet_workspace_edit.document_changes.map(|changes| {
538                 lsp_types::DocumentChanges::Operations(
539                     changes
540                         .into_iter()
541                         .map(|change| match change {
542                             lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
543                                 lsp_types::DocumentChangeOperation::Op(op)
544                             }
545                             lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
546                                 lsp_types::DocumentChangeOperation::Edit(
547                                     lsp_types::TextDocumentEdit {
548                                         text_document: edit.text_document,
549                                         edits: edit
550                                             .edits
551                                             .into_iter()
552                                             .map(|edit| lsp_types::TextEdit {
553                                                 range: edit.range,
554                                                 new_text: edit.new_text,
555                                             })
556                                             .collect(),
557                                     },
558                                 )
559                             }
560                         })
561                         .collect(),
562                 )
563             }),
564         }
565     }
566 }
567
568 pub fn call_hierarchy_item(
569     world: &WorldSnapshot,
570     target: NavigationTarget,
571 ) -> Result<lsp_types::CallHierarchyItem> {
572     let name = target.name().to_string();
573     let detail = target.description().map(|it| it.to_string());
574     let kind = symbol_kind(target.kind());
575     let (uri, range, selection_range) = location_info(world, target)?;
576     Ok(lsp_types::CallHierarchyItem { name, kind, tags: None, detail, uri, range, selection_range })
577 }
578
579 #[cfg(test)]
580 mod tests {
581     use test_utils::extract_ranges;
582
583     use super::*;
584
585     #[test]
586     fn conv_fold_line_folding_only_fixup() {
587         let text = r#"<fold>mod a;
588 mod b;
589 mod c;</fold>
590
591 fn main() <fold>{
592     if cond <fold>{
593         a::do_a();
594     }</fold> else <fold>{
595         b::do_b();
596     }</fold>
597 }</fold>"#;
598
599         let (ranges, text) = extract_ranges(text, "fold");
600         assert_eq!(ranges.len(), 4);
601         let folds = vec![
602             Fold { range: ranges[0], kind: FoldKind::Mods },
603             Fold { range: ranges[1], kind: FoldKind::Block },
604             Fold { range: ranges[2], kind: FoldKind::Block },
605             Fold { range: ranges[3], kind: FoldKind::Block },
606         ];
607
608         let line_index = LineIndex::new(&text);
609         let converted: Vec<lsp_types::FoldingRange> =
610             folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
611
612         let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
613         assert_eq!(converted.len(), expected_lines.len());
614         for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
615             assert_eq!(folding_range.start_line, *start_line);
616             assert_eq!(folding_range.start_character, None);
617             assert_eq!(folding_range.end_line, *end_line);
618             assert_eq!(folding_range.end_character, None);
619         }
620     }
621 }
622
623 pub(crate) fn code_action(world: &WorldSnapshot, assist: Assist) -> Result<lsp_ext::CodeAction> {
624     let res = lsp_ext::CodeAction {
625         title: assist.label,
626         group: if world.config.client_caps.code_action_group { assist.group_label } else { None },
627         kind: Some(String::new()),
628         edit: Some(snippet_workspace_edit(world, assist.source_change)?),
629         command: None,
630     };
631     Ok(res)
632 }
633
634 pub(crate) fn runnable(
635     world: &WorldSnapshot,
636     file_id: FileId,
637     runnable: Runnable,
638 ) -> Result<lsp_ext::Runnable> {
639     let spec = CargoTargetSpec::for_file(world, file_id)?;
640     let target = spec.as_ref().map(|s| s.target.clone());
641     let (args, extra_args) =
642         CargoTargetSpec::runnable_args(spec, &runnable.kind, &runnable.cfg_exprs)?;
643     let line_index = world.analysis().file_line_index(file_id)?;
644     let label = match &runnable.kind {
645         RunnableKind::Test { test_id, .. } => format!("test {}", test_id),
646         RunnableKind::TestMod { path } => format!("test-mod {}", path),
647         RunnableKind::Bench { test_id } => format!("bench {}", test_id),
648         RunnableKind::DocTest { test_id, .. } => format!("doctest {}", test_id),
649         RunnableKind::Bin => {
650             target.map_or_else(|| "run binary".to_string(), |t| format!("run {}", t))
651         }
652     };
653
654     Ok(lsp_ext::Runnable {
655         range: range(&line_index, runnable.range),
656         label,
657         kind: lsp_ext::RunnableKind::Cargo,
658         args,
659         extra_args,
660         env: {
661             let mut m = FxHashMap::default();
662             m.insert("RUST_BACKTRACE".to_string(), "short".to_string());
663             m
664         },
665         cwd: world.workspace_root_for(file_id).map(|root| root.to_owned()),
666     })
667 }