]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/rust-analyzer/src/to_proto.rs
Rollup merge of #98441 - calebzulawski:simd_as, r=oli-obk
[rust.git] / src / tools / rust-analyzer / crates / rust-analyzer / src / to_proto.rs
1 //! Conversion of rust-analyzer specific types to lsp_types equivalents.
2 use std::{
3     iter::once,
4     path,
5     sync::atomic::{AtomicU32, Ordering},
6 };
7
8 use ide::{
9     Annotation, AnnotationKind, Assist, AssistKind, Cancellable, CompletionItem,
10     CompletionItemKind, CompletionRelevance, Documentation, FileId, FileRange, FileSystemEdit,
11     Fold, FoldKind, Highlight, HlMod, HlOperator, HlPunct, HlRange, HlTag, Indel, InlayHint,
12     InlayHintLabel, InlayKind, Markup, NavigationTarget, ReferenceCategory, RenameError, Runnable,
13     Severity, SignatureHelp, SourceChange, StructureNodeKind, SymbolKind, TextEdit, TextRange,
14     TextSize,
15 };
16 use itertools::Itertools;
17 use serde_json::to_value;
18 use vfs::AbsPath;
19
20 use crate::{
21     cargo_target_spec::CargoTargetSpec,
22     config::{CallInfoConfig, Config},
23     global_state::GlobalStateSnapshot,
24     line_index::{LineEndings, LineIndex, OffsetEncoding},
25     lsp_ext,
26     lsp_utils::invalid_params_error,
27     semantic_tokens, Result,
28 };
29
30 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
31     let line_col = line_index.index.line_col(offset);
32     match line_index.encoding {
33         OffsetEncoding::Utf8 => lsp_types::Position::new(line_col.line, line_col.col),
34         OffsetEncoding::Utf16 => {
35             let line_col = line_index.index.to_utf16(line_col);
36             lsp_types::Position::new(line_col.line, line_col.col)
37         }
38     }
39 }
40
41 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
42     let start = position(line_index, range.start());
43     let end = position(line_index, range.end());
44     lsp_types::Range::new(start, end)
45 }
46
47 pub(crate) fn symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind {
48     match symbol_kind {
49         SymbolKind::Function => lsp_types::SymbolKind::FUNCTION,
50         SymbolKind::Struct => lsp_types::SymbolKind::STRUCT,
51         SymbolKind::Enum => lsp_types::SymbolKind::ENUM,
52         SymbolKind::Variant => lsp_types::SymbolKind::ENUM_MEMBER,
53         SymbolKind::Trait => lsp_types::SymbolKind::INTERFACE,
54         SymbolKind::Macro
55         | SymbolKind::BuiltinAttr
56         | SymbolKind::Attribute
57         | SymbolKind::Derive
58         | SymbolKind::DeriveHelper => lsp_types::SymbolKind::FUNCTION,
59         SymbolKind::Module | SymbolKind::ToolModule => lsp_types::SymbolKind::MODULE,
60         SymbolKind::TypeAlias | SymbolKind::TypeParam | SymbolKind::SelfType => {
61             lsp_types::SymbolKind::TYPE_PARAMETER
62         }
63         SymbolKind::Field => lsp_types::SymbolKind::FIELD,
64         SymbolKind::Static => lsp_types::SymbolKind::CONSTANT,
65         SymbolKind::Const => lsp_types::SymbolKind::CONSTANT,
66         SymbolKind::ConstParam => lsp_types::SymbolKind::CONSTANT,
67         SymbolKind::Impl => lsp_types::SymbolKind::OBJECT,
68         SymbolKind::Local
69         | SymbolKind::SelfParam
70         | SymbolKind::LifetimeParam
71         | SymbolKind::ValueParam
72         | SymbolKind::Label => lsp_types::SymbolKind::VARIABLE,
73         SymbolKind::Union => lsp_types::SymbolKind::STRUCT,
74     }
75 }
76
77 pub(crate) fn structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolKind {
78     match kind {
79         StructureNodeKind::SymbolKind(symbol) => symbol_kind(symbol),
80         StructureNodeKind::Region => lsp_types::SymbolKind::NAMESPACE,
81     }
82 }
83
84 pub(crate) fn document_highlight_kind(
85     category: ReferenceCategory,
86 ) -> lsp_types::DocumentHighlightKind {
87     match category {
88         ReferenceCategory::Read => lsp_types::DocumentHighlightKind::READ,
89         ReferenceCategory::Write => lsp_types::DocumentHighlightKind::WRITE,
90     }
91 }
92
93 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
94     match severity {
95         Severity::Error => lsp_types::DiagnosticSeverity::ERROR,
96         Severity::WeakWarning => lsp_types::DiagnosticSeverity::HINT,
97     }
98 }
99
100 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
101     let value = crate::markdown::format_docs(documentation.as_str());
102     let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
103     lsp_types::Documentation::MarkupContent(markup_content)
104 }
105
106 pub(crate) fn completion_item_kind(
107     completion_item_kind: CompletionItemKind,
108 ) -> lsp_types::CompletionItemKind {
109     match completion_item_kind {
110         CompletionItemKind::Binding => lsp_types::CompletionItemKind::VARIABLE,
111         CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::STRUCT,
112         CompletionItemKind::InferredType => lsp_types::CompletionItemKind::SNIPPET,
113         CompletionItemKind::Keyword => lsp_types::CompletionItemKind::KEYWORD,
114         CompletionItemKind::Method => lsp_types::CompletionItemKind::METHOD,
115         CompletionItemKind::Snippet => lsp_types::CompletionItemKind::SNIPPET,
116         CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::REFERENCE,
117         CompletionItemKind::SymbolKind(symbol) => match symbol {
118             SymbolKind::Attribute => lsp_types::CompletionItemKind::FUNCTION,
119             SymbolKind::Const => lsp_types::CompletionItemKind::CONSTANT,
120             SymbolKind::ConstParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
121             SymbolKind::Derive => lsp_types::CompletionItemKind::FUNCTION,
122             SymbolKind::DeriveHelper => lsp_types::CompletionItemKind::FUNCTION,
123             SymbolKind::Enum => lsp_types::CompletionItemKind::ENUM,
124             SymbolKind::Field => lsp_types::CompletionItemKind::FIELD,
125             SymbolKind::Function => lsp_types::CompletionItemKind::FUNCTION,
126             SymbolKind::Impl => lsp_types::CompletionItemKind::TEXT,
127             SymbolKind::Label => lsp_types::CompletionItemKind::VARIABLE,
128             SymbolKind::LifetimeParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
129             SymbolKind::Local => lsp_types::CompletionItemKind::VARIABLE,
130             SymbolKind::Macro => lsp_types::CompletionItemKind::FUNCTION,
131             SymbolKind::Module => lsp_types::CompletionItemKind::MODULE,
132             SymbolKind::SelfParam => lsp_types::CompletionItemKind::VALUE,
133             SymbolKind::SelfType => lsp_types::CompletionItemKind::TYPE_PARAMETER,
134             SymbolKind::Static => lsp_types::CompletionItemKind::VALUE,
135             SymbolKind::Struct => lsp_types::CompletionItemKind::STRUCT,
136             SymbolKind::Trait => lsp_types::CompletionItemKind::INTERFACE,
137             SymbolKind::TypeAlias => lsp_types::CompletionItemKind::STRUCT,
138             SymbolKind::TypeParam => lsp_types::CompletionItemKind::TYPE_PARAMETER,
139             SymbolKind::Union => lsp_types::CompletionItemKind::STRUCT,
140             SymbolKind::ValueParam => lsp_types::CompletionItemKind::VALUE,
141             SymbolKind::Variant => lsp_types::CompletionItemKind::ENUM_MEMBER,
142             SymbolKind::BuiltinAttr => lsp_types::CompletionItemKind::FUNCTION,
143             SymbolKind::ToolModule => lsp_types::CompletionItemKind::MODULE,
144         },
145     }
146 }
147
148 pub(crate) fn text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit {
149     let range = range(line_index, indel.delete);
150     let new_text = match line_index.endings {
151         LineEndings::Unix => indel.insert,
152         LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
153     };
154     lsp_types::TextEdit { range, new_text }
155 }
156
157 pub(crate) fn completion_text_edit(
158     line_index: &LineIndex,
159     insert_replace_support: Option<lsp_types::Position>,
160     indel: Indel,
161 ) -> lsp_types::CompletionTextEdit {
162     let text_edit = text_edit(line_index, indel);
163     match insert_replace_support {
164         Some(cursor_pos) => lsp_types::InsertReplaceEdit {
165             new_text: text_edit.new_text,
166             insert: lsp_types::Range { start: text_edit.range.start, end: cursor_pos },
167             replace: text_edit.range,
168         }
169         .into(),
170         None => text_edit.into(),
171     }
172 }
173
174 pub(crate) fn snippet_text_edit(
175     line_index: &LineIndex,
176     is_snippet: bool,
177     indel: Indel,
178 ) -> lsp_ext::SnippetTextEdit {
179     let text_edit = text_edit(line_index, indel);
180     let insert_text_format =
181         if is_snippet { Some(lsp_types::InsertTextFormat::SNIPPET) } else { None };
182     lsp_ext::SnippetTextEdit {
183         range: text_edit.range,
184         new_text: text_edit.new_text,
185         insert_text_format,
186         annotation_id: None,
187     }
188 }
189
190 pub(crate) fn text_edit_vec(
191     line_index: &LineIndex,
192     text_edit: TextEdit,
193 ) -> Vec<lsp_types::TextEdit> {
194     text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
195 }
196
197 pub(crate) fn snippet_text_edit_vec(
198     line_index: &LineIndex,
199     is_snippet: bool,
200     text_edit: TextEdit,
201 ) -> Vec<lsp_ext::SnippetTextEdit> {
202     text_edit
203         .into_iter()
204         .map(|indel| self::snippet_text_edit(line_index, is_snippet, indel))
205         .collect()
206 }
207
208 pub(crate) fn completion_items(
209     config: &Config,
210     line_index: &LineIndex,
211     tdpp: lsp_types::TextDocumentPositionParams,
212     items: Vec<CompletionItem>,
213 ) -> Vec<lsp_types::CompletionItem> {
214     let max_relevance = items.iter().map(|it| it.relevance().score()).max().unwrap_or_default();
215     let mut res = Vec::with_capacity(items.len());
216     for item in items {
217         completion_item(&mut res, config, line_index, &tdpp, max_relevance, item)
218     }
219     res
220 }
221
222 fn completion_item(
223     acc: &mut Vec<lsp_types::CompletionItem>,
224     config: &Config,
225     line_index: &LineIndex,
226     tdpp: &lsp_types::TextDocumentPositionParams,
227     max_relevance: u32,
228     item: CompletionItem,
229 ) {
230     let insert_replace_support = config.insert_replace_support().then(|| tdpp.position);
231     let mut additional_text_edits = Vec::new();
232
233     // LSP does not allow arbitrary edits in completion, so we have to do a
234     // non-trivial mapping here.
235     let text_edit = {
236         let mut text_edit = None;
237         let source_range = item.source_range();
238         for indel in item.text_edit().iter() {
239             if indel.delete.contains_range(source_range) {
240                 text_edit = Some(if indel.delete == source_range {
241                     self::completion_text_edit(line_index, insert_replace_support, indel.clone())
242                 } else {
243                     assert!(source_range.end() == indel.delete.end());
244                     let range1 = TextRange::new(indel.delete.start(), source_range.start());
245                     let range2 = source_range;
246                     let indel1 = Indel::replace(range1, String::new());
247                     let indel2 = Indel::replace(range2, indel.insert.clone());
248                     additional_text_edits.push(self::text_edit(line_index, indel1));
249                     self::completion_text_edit(line_index, insert_replace_support, indel2)
250                 })
251             } else {
252                 assert!(source_range.intersect(indel.delete).is_none());
253                 let text_edit = self::text_edit(line_index, indel.clone());
254                 additional_text_edits.push(text_edit);
255             }
256         }
257         text_edit.unwrap()
258     };
259
260     let insert_text_format = item.is_snippet().then(|| lsp_types::InsertTextFormat::SNIPPET);
261     let tags = item.deprecated().then(|| vec![lsp_types::CompletionItemTag::DEPRECATED]);
262     let command = if item.trigger_call_info() && config.client_commands().trigger_parameter_hints {
263         Some(command::trigger_parameter_hints())
264     } else {
265         None
266     };
267
268     let mut lsp_item = lsp_types::CompletionItem {
269         label: item.label().to_string(),
270         detail: item.detail().map(|it| it.to_string()),
271         filter_text: Some(item.lookup().to_string()),
272         kind: Some(completion_item_kind(item.kind())),
273         text_edit: Some(text_edit),
274         additional_text_edits: Some(additional_text_edits),
275         documentation: item.documentation().map(documentation),
276         deprecated: Some(item.deprecated()),
277         tags,
278         command,
279         insert_text_format,
280         ..Default::default()
281     };
282
283     if config.completion_label_details_support() {
284         lsp_item.label_details = Some(lsp_types::CompletionItemLabelDetails {
285             detail: None,
286             description: lsp_item.detail.clone(),
287         });
288     }
289
290     set_score(&mut lsp_item, max_relevance, item.relevance());
291
292     if config.completion().enable_imports_on_the_fly {
293         if let imports @ [_, ..] = item.imports_to_add() {
294             let imports: Vec<_> = imports
295                 .iter()
296                 .filter_map(|import_edit| {
297                     let import_path = &import_edit.import_path;
298                     let import_name = import_path.segments().last()?;
299                     Some(lsp_ext::CompletionImport {
300                         full_import_path: import_path.to_string(),
301                         imported_name: import_name.to_string(),
302                     })
303                 })
304                 .collect();
305             if !imports.is_empty() {
306                 let data = lsp_ext::CompletionResolveData { position: tdpp.clone(), imports };
307                 lsp_item.data = Some(to_value(data).unwrap());
308             }
309         }
310     }
311
312     if let Some((mutability, offset, relevance)) = item.ref_match() {
313         let mut lsp_item_with_ref = lsp_item.clone();
314         set_score(&mut lsp_item_with_ref, max_relevance, relevance);
315         lsp_item_with_ref.label =
316             format!("&{}{}", mutability.as_keyword_for_ref(), lsp_item_with_ref.label);
317         lsp_item_with_ref.additional_text_edits.get_or_insert_with(Default::default).push(
318             self::text_edit(
319                 line_index,
320                 Indel::insert(offset, format!("&{}", mutability.as_keyword_for_ref())),
321             ),
322         );
323
324         acc.push(lsp_item_with_ref);
325     };
326
327     acc.push(lsp_item);
328
329     fn set_score(
330         res: &mut lsp_types::CompletionItem,
331         max_relevance: u32,
332         relevance: CompletionRelevance,
333     ) {
334         if relevance.is_relevant() && relevance.score() == max_relevance {
335             res.preselect = Some(true);
336         }
337         // The relevance needs to be inverted to come up with a sort score
338         // because the client will sort ascending.
339         let sort_score = relevance.score() ^ 0xFF_FF_FF_FF;
340         // Zero pad the string to ensure values can be properly sorted
341         // by the client. Hex format is used because it is easier to
342         // visually compare very large values, which the sort text
343         // tends to be since it is the opposite of the score.
344         res.sort_text = Some(format!("{:08x}", sort_score));
345     }
346 }
347
348 pub(crate) fn signature_help(
349     call_info: SignatureHelp,
350     config: CallInfoConfig,
351     label_offsets: bool,
352 ) -> lsp_types::SignatureHelp {
353     let (label, parameters) = match (config.params_only, label_offsets) {
354         (concise, false) => {
355             let params = call_info
356                 .parameter_labels()
357                 .map(|label| lsp_types::ParameterInformation {
358                     label: lsp_types::ParameterLabel::Simple(label.to_string()),
359                     documentation: None,
360                 })
361                 .collect::<Vec<_>>();
362             let label =
363                 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
364             (label, params)
365         }
366         (false, true) => {
367             let params = call_info
368                 .parameter_ranges()
369                 .iter()
370                 .map(|it| {
371                     let start = call_info.signature[..it.start().into()].chars().count() as u32;
372                     let end = call_info.signature[..it.end().into()].chars().count() as u32;
373                     [start, end]
374                 })
375                 .map(|label_offsets| lsp_types::ParameterInformation {
376                     label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
377                     documentation: None,
378                 })
379                 .collect::<Vec<_>>();
380             (call_info.signature, params)
381         }
382         (true, true) => {
383             let mut params = Vec::new();
384             let mut label = String::new();
385             let mut first = true;
386             for param in call_info.parameter_labels() {
387                 if !first {
388                     label.push_str(", ");
389                 }
390                 first = false;
391                 let start = label.chars().count() as u32;
392                 label.push_str(param);
393                 let end = label.chars().count() as u32;
394                 params.push(lsp_types::ParameterInformation {
395                     label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
396                     documentation: None,
397                 });
398             }
399
400             (label, params)
401         }
402     };
403
404     let documentation = call_info.doc.filter(|_| config.docs).map(|doc| {
405         lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
406             kind: lsp_types::MarkupKind::Markdown,
407             value: doc,
408         })
409     });
410
411     let active_parameter = call_info.active_parameter.map(|it| it as u32);
412
413     let signature = lsp_types::SignatureInformation {
414         label,
415         documentation,
416         parameters: Some(parameters),
417         active_parameter,
418     };
419     lsp_types::SignatureHelp {
420         signatures: vec![signature],
421         active_signature: Some(0),
422         active_parameter,
423     }
424 }
425
426 pub(crate) fn inlay_hint(
427     snap: &GlobalStateSnapshot,
428     line_index: &LineIndex,
429     render_colons: bool,
430     mut inlay_hint: InlayHint,
431 ) -> Result<lsp_types::InlayHint> {
432     match inlay_hint.kind {
433         InlayKind::ParameterHint if render_colons => inlay_hint.label.append_str(":"),
434         InlayKind::TypeHint if render_colons => inlay_hint.label.prepend_str(": "),
435         InlayKind::ClosureReturnTypeHint => inlay_hint.label.prepend_str(" -> "),
436         _ => {}
437     }
438
439     Ok(lsp_types::InlayHint {
440         position: match inlay_hint.kind {
441             // before annotated thing
442             InlayKind::ParameterHint
443             | InlayKind::ImplicitReborrowHint
444             | InlayKind::BindingModeHint => position(line_index, inlay_hint.range.start()),
445             // after annotated thing
446             InlayKind::ClosureReturnTypeHint
447             | InlayKind::TypeHint
448             | InlayKind::ChainingHint
449             | InlayKind::GenericParamListHint
450             | InlayKind::LifetimeHint
451             | InlayKind::ClosingBraceHint => position(line_index, inlay_hint.range.end()),
452         },
453         padding_left: Some(match inlay_hint.kind {
454             InlayKind::TypeHint => !render_colons,
455             InlayKind::ChainingHint | InlayKind::ClosingBraceHint => true,
456             InlayKind::BindingModeHint
457             | InlayKind::ClosureReturnTypeHint
458             | InlayKind::GenericParamListHint
459             | InlayKind::ImplicitReborrowHint
460             | InlayKind::LifetimeHint
461             | InlayKind::ParameterHint => false,
462         }),
463         padding_right: Some(match inlay_hint.kind {
464             InlayKind::ChainingHint
465             | InlayKind::ClosureReturnTypeHint
466             | InlayKind::GenericParamListHint
467             | InlayKind::ImplicitReborrowHint
468             | InlayKind::TypeHint
469             | InlayKind::ClosingBraceHint => false,
470             InlayKind::BindingModeHint => inlay_hint.label.as_simple_str() != Some("&"),
471             InlayKind::ParameterHint | InlayKind::LifetimeHint => true,
472         }),
473         kind: match inlay_hint.kind {
474             InlayKind::ParameterHint => Some(lsp_types::InlayHintKind::PARAMETER),
475             InlayKind::ClosureReturnTypeHint | InlayKind::TypeHint | InlayKind::ChainingHint => {
476                 Some(lsp_types::InlayHintKind::TYPE)
477             }
478             InlayKind::BindingModeHint
479             | InlayKind::GenericParamListHint
480             | InlayKind::LifetimeHint
481             | InlayKind::ImplicitReborrowHint
482             | InlayKind::ClosingBraceHint => None,
483         },
484         text_edits: None,
485         data: (|| match inlay_hint.tooltip {
486             Some(ide::InlayTooltip::HoverOffset(file_id, offset)) => {
487                 let uri = url(snap, file_id);
488                 let line_index = snap.file_line_index(file_id).ok()?;
489
490                 let text_document = lsp_types::TextDocumentIdentifier { uri };
491                 to_value(lsp_ext::InlayHintResolveData {
492                     text_document,
493                     position: lsp_ext::PositionOrRange::Position(position(&line_index, offset)),
494                 })
495                 .ok()
496             }
497             Some(ide::InlayTooltip::HoverRanged(file_id, text_range)) => {
498                 let uri = url(snap, file_id);
499                 let text_document = lsp_types::TextDocumentIdentifier { uri };
500                 let line_index = snap.file_line_index(file_id).ok()?;
501                 to_value(lsp_ext::InlayHintResolveData {
502                     text_document,
503                     position: lsp_ext::PositionOrRange::Range(range(&line_index, text_range)),
504                 })
505                 .ok()
506             }
507             _ => None,
508         })(),
509         tooltip: Some(match inlay_hint.tooltip {
510             Some(ide::InlayTooltip::String(s)) => lsp_types::InlayHintTooltip::String(s),
511             _ => lsp_types::InlayHintTooltip::String(inlay_hint.label.to_string()),
512         }),
513         label: inlay_hint_label(snap, inlay_hint.label)?,
514     })
515 }
516
517 fn inlay_hint_label(
518     snap: &GlobalStateSnapshot,
519     label: InlayHintLabel,
520 ) -> Result<lsp_types::InlayHintLabel> {
521     Ok(match label.as_simple_str() {
522         Some(s) => lsp_types::InlayHintLabel::String(s.into()),
523         None => lsp_types::InlayHintLabel::LabelParts(
524             label
525                 .parts
526                 .into_iter()
527                 .map(|part| {
528                     Ok(lsp_types::InlayHintLabelPart {
529                         value: part.text,
530                         tooltip: None,
531                         location: part
532                             .linked_location
533                             .map(|range| location(snap, range))
534                             .transpose()?,
535                         command: None,
536                     })
537                 })
538                 .collect::<Result<Vec<_>>>()?,
539         ),
540     })
541 }
542
543 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
544
545 pub(crate) fn semantic_tokens(
546     text: &str,
547     line_index: &LineIndex,
548     highlights: Vec<HlRange>,
549 ) -> lsp_types::SemanticTokens {
550     let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
551     let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
552
553     for highlight_range in highlights {
554         if highlight_range.highlight.is_empty() {
555             continue;
556         }
557
558         let (ty, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
559         let token_index = semantic_tokens::type_index(ty);
560         let modifier_bitset = mods.0;
561
562         for mut text_range in line_index.index.lines(highlight_range.range) {
563             if text[text_range].ends_with('\n') {
564                 text_range =
565                     TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
566             }
567             let range = range(line_index, text_range);
568             builder.push(range, token_index, modifier_bitset);
569         }
570     }
571
572     builder.build()
573 }
574
575 pub(crate) fn semantic_token_delta(
576     previous: &lsp_types::SemanticTokens,
577     current: &lsp_types::SemanticTokens,
578 ) -> lsp_types::SemanticTokensDelta {
579     let result_id = current.result_id.clone();
580     let edits = semantic_tokens::diff_tokens(&previous.data, &current.data);
581     lsp_types::SemanticTokensDelta { result_id, edits }
582 }
583
584 fn semantic_token_type_and_modifiers(
585     highlight: Highlight,
586 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
587     let mut mods = semantic_tokens::ModifierSet::default();
588     let type_ = match highlight.tag {
589         HlTag::Symbol(symbol) => match symbol {
590             SymbolKind::Attribute => semantic_tokens::DECORATOR,
591             SymbolKind::Derive => semantic_tokens::DERIVE,
592             SymbolKind::DeriveHelper => semantic_tokens::DERIVE_HELPER,
593             SymbolKind::Module => semantic_tokens::NAMESPACE,
594             SymbolKind::Impl => semantic_tokens::TYPE_ALIAS,
595             SymbolKind::Field => semantic_tokens::PROPERTY,
596             SymbolKind::TypeParam => semantic_tokens::TYPE_PARAMETER,
597             SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
598             SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
599             SymbolKind::Label => semantic_tokens::LABEL,
600             SymbolKind::ValueParam => semantic_tokens::PARAMETER,
601             SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
602             SymbolKind::SelfType => semantic_tokens::SELF_TYPE_KEYWORD,
603             SymbolKind::Local => semantic_tokens::VARIABLE,
604             SymbolKind::Function => {
605                 if highlight.mods.contains(HlMod::Associated) {
606                     semantic_tokens::METHOD
607                 } else {
608                     semantic_tokens::FUNCTION
609                 }
610             }
611             SymbolKind::Const => {
612                 mods |= semantic_tokens::CONSTANT;
613                 mods |= semantic_tokens::STATIC;
614                 semantic_tokens::VARIABLE
615             }
616             SymbolKind::Static => {
617                 mods |= semantic_tokens::STATIC;
618                 semantic_tokens::VARIABLE
619             }
620             SymbolKind::Struct => semantic_tokens::STRUCT,
621             SymbolKind::Enum => semantic_tokens::ENUM,
622             SymbolKind::Variant => semantic_tokens::ENUM_MEMBER,
623             SymbolKind::Union => semantic_tokens::UNION,
624             SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
625             SymbolKind::Trait => semantic_tokens::INTERFACE,
626             SymbolKind::Macro => semantic_tokens::MACRO,
627             SymbolKind::BuiltinAttr => semantic_tokens::BUILTIN_ATTRIBUTE,
628             SymbolKind::ToolModule => semantic_tokens::TOOL_MODULE,
629         },
630         HlTag::AttributeBracket => semantic_tokens::ATTRIBUTE_BRACKET,
631         HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
632         HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
633         HlTag::ByteLiteral | HlTag::NumericLiteral => semantic_tokens::NUMBER,
634         HlTag::CharLiteral => semantic_tokens::CHAR,
635         HlTag::Comment => semantic_tokens::COMMENT,
636         HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
637         HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
638         HlTag::Keyword => semantic_tokens::KEYWORD,
639         HlTag::None => semantic_tokens::GENERIC,
640         HlTag::Operator(op) => match op {
641             HlOperator::Bitwise => semantic_tokens::BITWISE,
642             HlOperator::Arithmetic => semantic_tokens::ARITHMETIC,
643             HlOperator::Logical => semantic_tokens::LOGICAL,
644             HlOperator::Comparison => semantic_tokens::COMPARISON,
645             HlOperator::Other => semantic_tokens::OPERATOR,
646         },
647         HlTag::StringLiteral => semantic_tokens::STRING,
648         HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
649         HlTag::Punctuation(punct) => match punct {
650             HlPunct::Bracket => semantic_tokens::BRACKET,
651             HlPunct::Brace => semantic_tokens::BRACE,
652             HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
653             HlPunct::Angle => semantic_tokens::ANGLE,
654             HlPunct::Comma => semantic_tokens::COMMA,
655             HlPunct::Dot => semantic_tokens::DOT,
656             HlPunct::Colon => semantic_tokens::COLON,
657             HlPunct::Semi => semantic_tokens::SEMICOLON,
658             HlPunct::Other => semantic_tokens::PUNCTUATION,
659             HlPunct::MacroBang => semantic_tokens::MACRO_BANG,
660         },
661     };
662
663     for modifier in highlight.mods.iter() {
664         let modifier = match modifier {
665             HlMod::Associated => continue,
666             HlMod::Async => semantic_tokens::ASYNC,
667             HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
668             HlMod::Callable => semantic_tokens::CALLABLE,
669             HlMod::Consuming => semantic_tokens::CONSUMING,
670             HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
671             HlMod::CrateRoot => semantic_tokens::CRATE_ROOT,
672             HlMod::DefaultLibrary => semantic_tokens::DEFAULT_LIBRARY,
673             HlMod::Definition => semantic_tokens::DECLARATION,
674             HlMod::Documentation => semantic_tokens::DOCUMENTATION,
675             HlMod::Injected => semantic_tokens::INJECTED,
676             HlMod::IntraDocLink => semantic_tokens::INTRA_DOC_LINK,
677             HlMod::Library => semantic_tokens::LIBRARY,
678             HlMod::Mutable => semantic_tokens::MUTABLE,
679             HlMod::Public => semantic_tokens::PUBLIC,
680             HlMod::Reference => semantic_tokens::REFERENCE,
681             HlMod::Static => semantic_tokens::STATIC,
682             HlMod::Trait => semantic_tokens::TRAIT_MODIFIER,
683             HlMod::Unsafe => semantic_tokens::UNSAFE,
684         };
685         mods |= modifier;
686     }
687
688     (type_, mods)
689 }
690
691 pub(crate) fn folding_range(
692     text: &str,
693     line_index: &LineIndex,
694     line_folding_only: bool,
695     fold: Fold,
696 ) -> lsp_types::FoldingRange {
697     let kind = match fold.kind {
698         FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
699         FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
700         FoldKind::Region => Some(lsp_types::FoldingRangeKind::Region),
701         FoldKind::Mods
702         | FoldKind::Block
703         | FoldKind::ArgList
704         | FoldKind::Consts
705         | FoldKind::Statics
706         | FoldKind::WhereClause
707         | FoldKind::ReturnType
708         | FoldKind::Array
709         | FoldKind::MatchArm => None,
710     };
711
712     let range = range(line_index, fold.range);
713
714     if line_folding_only {
715         // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
716         // even if it contains text not in the folding range. To prevent that we exclude
717         // range.end.line from the folding region if there is more text after range.end
718         // on the same line.
719         let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
720             .chars()
721             .take_while(|it| *it != '\n')
722             .any(|it| !it.is_whitespace());
723
724         let end_line = if has_more_text_on_end_line {
725             range.end.line.saturating_sub(1)
726         } else {
727             range.end.line
728         };
729
730         lsp_types::FoldingRange {
731             start_line: range.start.line,
732             start_character: None,
733             end_line,
734             end_character: None,
735             kind,
736         }
737     } else {
738         lsp_types::FoldingRange {
739             start_line: range.start.line,
740             start_character: Some(range.start.character),
741             end_line: range.end.line,
742             end_character: Some(range.end.character),
743             kind,
744         }
745     }
746 }
747
748 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
749     snap.file_id_to_url(file_id)
750 }
751
752 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
753 /// This will only happen when processing windows paths.
754 ///
755 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
756 pub(crate) fn url_from_abs_path(path: &AbsPath) -> lsp_types::Url {
757     let url = lsp_types::Url::from_file_path(path).unwrap();
758     match path.as_ref().components().next() {
759         Some(path::Component::Prefix(prefix))
760             if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
761         {
762             // Need to lowercase driver letter
763         }
764         _ => return url,
765     }
766
767     let driver_letter_range = {
768         let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
769             Some(it) => it,
770             None => return url,
771         };
772         let start = scheme.len() + ':'.len_utf8();
773         start..(start + drive_letter.len())
774     };
775
776     // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
777     // machinery *also* canonicalizes the drive letter. So, just massage the
778     // string in place.
779     let mut url: String = url.into();
780     url[driver_letter_range].make_ascii_lowercase();
781     lsp_types::Url::parse(&url).unwrap()
782 }
783
784 pub(crate) fn optional_versioned_text_document_identifier(
785     snap: &GlobalStateSnapshot,
786     file_id: FileId,
787 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
788     let url = url(snap, file_id);
789     let version = snap.url_file_version(&url);
790     lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
791 }
792
793 pub(crate) fn location(
794     snap: &GlobalStateSnapshot,
795     frange: FileRange,
796 ) -> Result<lsp_types::Location> {
797     let url = url(snap, frange.file_id);
798     let line_index = snap.file_line_index(frange.file_id)?;
799     let range = range(&line_index, frange.range);
800     let loc = lsp_types::Location::new(url, range);
801     Ok(loc)
802 }
803
804 /// Prefer using `location_link`, if the client has the cap.
805 pub(crate) fn location_from_nav(
806     snap: &GlobalStateSnapshot,
807     nav: NavigationTarget,
808 ) -> Result<lsp_types::Location> {
809     let url = url(snap, nav.file_id);
810     let line_index = snap.file_line_index(nav.file_id)?;
811     let range = range(&line_index, nav.full_range);
812     let loc = lsp_types::Location::new(url, range);
813     Ok(loc)
814 }
815
816 pub(crate) fn location_link(
817     snap: &GlobalStateSnapshot,
818     src: Option<FileRange>,
819     target: NavigationTarget,
820 ) -> Result<lsp_types::LocationLink> {
821     let origin_selection_range = match src {
822         Some(src) => {
823             let line_index = snap.file_line_index(src.file_id)?;
824             let range = range(&line_index, src.range);
825             Some(range)
826         }
827         None => None,
828     };
829     let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
830     let res = lsp_types::LocationLink {
831         origin_selection_range,
832         target_uri,
833         target_range,
834         target_selection_range,
835     };
836     Ok(res)
837 }
838
839 fn location_info(
840     snap: &GlobalStateSnapshot,
841     target: NavigationTarget,
842 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
843     let line_index = snap.file_line_index(target.file_id)?;
844
845     let target_uri = url(snap, target.file_id);
846     let target_range = range(&line_index, target.full_range);
847     let target_selection_range =
848         target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
849     Ok((target_uri, target_range, target_selection_range))
850 }
851
852 pub(crate) fn goto_definition_response(
853     snap: &GlobalStateSnapshot,
854     src: Option<FileRange>,
855     targets: Vec<NavigationTarget>,
856 ) -> Result<lsp_types::GotoDefinitionResponse> {
857     if snap.config.location_link() {
858         let links = targets
859             .into_iter()
860             .map(|nav| location_link(snap, src, nav))
861             .collect::<Result<Vec<_>>>()?;
862         Ok(links.into())
863     } else {
864         let locations = targets
865             .into_iter()
866             .map(|nav| {
867                 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
868             })
869             .collect::<Result<Vec<_>>>()?;
870         Ok(locations.into())
871     }
872 }
873
874 fn outside_workspace_annotation_id() -> String {
875     String::from("OutsideWorkspace")
876 }
877
878 pub(crate) fn snippet_text_document_edit(
879     snap: &GlobalStateSnapshot,
880     is_snippet: bool,
881     file_id: FileId,
882     edit: TextEdit,
883 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
884     let text_document = optional_versioned_text_document_identifier(snap, file_id);
885     let line_index = snap.file_line_index(file_id)?;
886     let mut edits: Vec<_> =
887         edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
888
889     if snap.analysis.is_library_file(file_id)? && snap.config.change_annotation_support() {
890         for edit in &mut edits {
891             edit.annotation_id = Some(outside_workspace_annotation_id())
892         }
893     }
894     Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
895 }
896
897 pub(crate) fn snippet_text_document_ops(
898     snap: &GlobalStateSnapshot,
899     file_system_edit: FileSystemEdit,
900 ) -> Cancellable<Vec<lsp_ext::SnippetDocumentChangeOperation>> {
901     let mut ops = Vec::new();
902     match file_system_edit {
903         FileSystemEdit::CreateFile { dst, initial_contents } => {
904             let uri = snap.anchored_path(&dst);
905             let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
906                 uri: uri.clone(),
907                 options: None,
908                 annotation_id: None,
909             });
910             ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
911             if !initial_contents.is_empty() {
912                 let text_document =
913                     lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
914                 let text_edit = lsp_ext::SnippetTextEdit {
915                     range: lsp_types::Range::default(),
916                     new_text: initial_contents,
917                     insert_text_format: Some(lsp_types::InsertTextFormat::PLAIN_TEXT),
918                     annotation_id: None,
919                 };
920                 let edit_file =
921                     lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
922                 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
923             }
924         }
925         FileSystemEdit::MoveFile { src, dst } => {
926             let old_uri = snap.file_id_to_url(src);
927             let new_uri = snap.anchored_path(&dst);
928             let mut rename_file =
929                 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
930             if snap.analysis.is_library_file(src).ok() == Some(true)
931                 && snap.config.change_annotation_support()
932             {
933                 rename_file.annotation_id = Some(outside_workspace_annotation_id())
934             }
935             ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(lsp_types::ResourceOp::Rename(
936                 rename_file,
937             )))
938         }
939         FileSystemEdit::MoveDir { src, src_id, dst } => {
940             let old_uri = snap.anchored_path(&src);
941             let new_uri = snap.anchored_path(&dst);
942             let mut rename_file =
943                 lsp_types::RenameFile { old_uri, new_uri, options: None, annotation_id: None };
944             if snap.analysis.is_library_file(src_id).ok() == Some(true)
945                 && snap.config.change_annotation_support()
946             {
947                 rename_file.annotation_id = Some(outside_workspace_annotation_id())
948             }
949             ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(lsp_types::ResourceOp::Rename(
950                 rename_file,
951             )))
952         }
953     }
954     Ok(ops)
955 }
956
957 pub(crate) fn snippet_workspace_edit(
958     snap: &GlobalStateSnapshot,
959     source_change: SourceChange,
960 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
961     let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
962
963     for op in source_change.file_system_edits {
964         let ops = snippet_text_document_ops(snap, op)?;
965         document_changes.extend_from_slice(&ops);
966     }
967     for (file_id, edit) in source_change.source_file_edits {
968         let edit = snippet_text_document_edit(snap, source_change.is_snippet, file_id, edit)?;
969         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
970     }
971     let mut workspace_edit = lsp_ext::SnippetWorkspaceEdit {
972         changes: None,
973         document_changes: Some(document_changes),
974         change_annotations: None,
975     };
976     if snap.config.change_annotation_support() {
977         workspace_edit.change_annotations = Some(
978             once((
979                 outside_workspace_annotation_id(),
980                 lsp_types::ChangeAnnotation {
981                     label: String::from("Edit outside of the workspace"),
982                     needs_confirmation: Some(true),
983                     description: Some(String::from(
984                         "This edit lies outside of the workspace and may affect dependencies",
985                     )),
986                 },
987             ))
988             .collect(),
989         )
990     }
991     Ok(workspace_edit)
992 }
993
994 pub(crate) fn workspace_edit(
995     snap: &GlobalStateSnapshot,
996     source_change: SourceChange,
997 ) -> Result<lsp_types::WorkspaceEdit> {
998     assert!(!source_change.is_snippet);
999     snippet_workspace_edit(snap, source_change).map(|it| it.into())
1000 }
1001
1002 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
1003     fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
1004         lsp_types::WorkspaceEdit {
1005             changes: None,
1006             document_changes: snippet_workspace_edit.document_changes.map(|changes| {
1007                 lsp_types::DocumentChanges::Operations(
1008                     changes
1009                         .into_iter()
1010                         .map(|change| match change {
1011                             lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
1012                                 lsp_types::DocumentChangeOperation::Op(op)
1013                             }
1014                             lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
1015                                 lsp_types::DocumentChangeOperation::Edit(
1016                                     lsp_types::TextDocumentEdit {
1017                                         text_document: edit.text_document,
1018                                         edits: edit.edits.into_iter().map(From::from).collect(),
1019                                     },
1020                                 )
1021                             }
1022                         })
1023                         .collect(),
1024                 )
1025             }),
1026             change_annotations: snippet_workspace_edit.change_annotations,
1027         }
1028     }
1029 }
1030
1031 impl From<lsp_ext::SnippetTextEdit>
1032     for lsp_types::OneOf<lsp_types::TextEdit, lsp_types::AnnotatedTextEdit>
1033 {
1034     fn from(
1035         lsp_ext::SnippetTextEdit { annotation_id, insert_text_format:_, new_text, range }: lsp_ext::SnippetTextEdit,
1036     ) -> Self {
1037         match annotation_id {
1038             Some(annotation_id) => lsp_types::OneOf::Right(lsp_types::AnnotatedTextEdit {
1039                 text_edit: lsp_types::TextEdit { range, new_text },
1040                 annotation_id,
1041             }),
1042             None => lsp_types::OneOf::Left(lsp_types::TextEdit { range, new_text }),
1043         }
1044     }
1045 }
1046
1047 pub(crate) fn call_hierarchy_item(
1048     snap: &GlobalStateSnapshot,
1049     target: NavigationTarget,
1050 ) -> Result<lsp_types::CallHierarchyItem> {
1051     let name = target.name.to_string();
1052     let detail = target.description.clone();
1053     let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::FUNCTION);
1054     let (uri, range, selection_range) = location_info(snap, target)?;
1055     Ok(lsp_types::CallHierarchyItem {
1056         name,
1057         kind,
1058         tags: None,
1059         detail,
1060         uri,
1061         range,
1062         selection_range,
1063         data: None,
1064     })
1065 }
1066
1067 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
1068     match kind {
1069         AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
1070         AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
1071         AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
1072         AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
1073         AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
1074         AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
1075     }
1076 }
1077
1078 pub(crate) fn code_action(
1079     snap: &GlobalStateSnapshot,
1080     assist: Assist,
1081     resolve_data: Option<(usize, lsp_types::CodeActionParams)>,
1082 ) -> Result<lsp_ext::CodeAction> {
1083     let mut res = lsp_ext::CodeAction {
1084         title: assist.label.to_string(),
1085         group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
1086         kind: Some(code_action_kind(assist.id.1)),
1087         edit: None,
1088         is_preferred: None,
1089         data: None,
1090         command: None,
1091     };
1092
1093     if assist.trigger_signature_help && snap.config.client_commands().trigger_parameter_hints {
1094         res.command = Some(command::trigger_parameter_hints());
1095     }
1096
1097     match (assist.source_change, resolve_data) {
1098         (Some(it), _) => res.edit = Some(snippet_workspace_edit(snap, it)?),
1099         (None, Some((index, code_action_params))) => {
1100             res.data = Some(lsp_ext::CodeActionData {
1101                 id: format!("{}:{}:{}", assist.id.0, assist.id.1.name(), index),
1102                 code_action_params,
1103             });
1104         }
1105         (None, None) => {
1106             stdx::never!("assist should always be resolved if client can't do lazy resolving")
1107         }
1108     };
1109     Ok(res)
1110 }
1111
1112 pub(crate) fn runnable(
1113     snap: &GlobalStateSnapshot,
1114     runnable: Runnable,
1115 ) -> Result<lsp_ext::Runnable> {
1116     let config = snap.config.runnables();
1117     let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?;
1118     let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
1119     let target = spec.as_ref().map(|s| s.target.clone());
1120     let (cargo_args, executable_args) =
1121         CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
1122     let label = runnable.label(target);
1123     let location = location_link(snap, None, runnable.nav)?;
1124
1125     Ok(lsp_ext::Runnable {
1126         label,
1127         location: Some(location),
1128         kind: lsp_ext::RunnableKind::Cargo,
1129         args: lsp_ext::CargoRunnable {
1130             workspace_root: workspace_root.map(|it| it.into()),
1131             override_cargo: config.override_cargo,
1132             cargo_args,
1133             cargo_extra_args: config.cargo_extra_args,
1134             executable_args,
1135             expect_test: None,
1136         },
1137     })
1138 }
1139
1140 pub(crate) fn code_lens(
1141     acc: &mut Vec<lsp_types::CodeLens>,
1142     snap: &GlobalStateSnapshot,
1143     annotation: Annotation,
1144 ) -> Result<()> {
1145     let client_commands_config = snap.config.client_commands();
1146     match annotation.kind {
1147         AnnotationKind::Runnable(run) => {
1148             let line_index = snap.file_line_index(run.nav.file_id)?;
1149             let annotation_range = range(&line_index, annotation.range);
1150
1151             let title = run.title();
1152             let can_debug = match run.kind {
1153                 ide::RunnableKind::DocTest { .. } => false,
1154                 ide::RunnableKind::TestMod { .. }
1155                 | ide::RunnableKind::Test { .. }
1156                 | ide::RunnableKind::Bench { .. }
1157                 | ide::RunnableKind::Bin => true,
1158             };
1159             let r = runnable(snap, run)?;
1160
1161             let lens_config = snap.config.lens();
1162             if lens_config.run && client_commands_config.run_single {
1163                 let command = command::run_single(&r, &title);
1164                 acc.push(lsp_types::CodeLens {
1165                     range: annotation_range,
1166                     command: Some(command),
1167                     data: None,
1168                 })
1169             }
1170             if lens_config.debug && can_debug && client_commands_config.debug_single {
1171                 let command = command::debug_single(&r);
1172                 acc.push(lsp_types::CodeLens {
1173                     range: annotation_range,
1174                     command: Some(command),
1175                     data: None,
1176                 })
1177             }
1178         }
1179         AnnotationKind::HasImpls { file_id, data } => {
1180             if !client_commands_config.show_reference {
1181                 return Ok(());
1182             }
1183             let line_index = snap.file_line_index(file_id)?;
1184             let annotation_range = range(&line_index, annotation.range);
1185             let url = url(snap, file_id);
1186
1187             let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1188
1189             let doc_pos = lsp_types::TextDocumentPositionParams::new(id, annotation_range.start);
1190
1191             let goto_params = lsp_types::request::GotoImplementationParams {
1192                 text_document_position_params: doc_pos,
1193                 work_done_progress_params: Default::default(),
1194                 partial_result_params: Default::default(),
1195             };
1196
1197             let command = data.map(|ranges| {
1198                 let locations: Vec<lsp_types::Location> = ranges
1199                     .into_iter()
1200                     .filter_map(|target| {
1201                         location(
1202                             snap,
1203                             FileRange { file_id: target.file_id, range: target.full_range },
1204                         )
1205                         .ok()
1206                     })
1207                     .collect();
1208
1209                 command::show_references(
1210                     implementation_title(locations.len()),
1211                     &url,
1212                     annotation_range.start,
1213                     locations,
1214                 )
1215             });
1216
1217             acc.push(lsp_types::CodeLens {
1218                 range: annotation_range,
1219                 command,
1220                 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
1221             })
1222         }
1223         AnnotationKind::HasReferences { file_id, data } => {
1224             if !client_commands_config.show_reference {
1225                 return Ok(());
1226             }
1227             let line_index = snap.file_line_index(file_id)?;
1228             let annotation_range = range(&line_index, annotation.range);
1229             let url = url(snap, file_id);
1230
1231             let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
1232
1233             let doc_pos = lsp_types::TextDocumentPositionParams::new(id, annotation_range.start);
1234
1235             let command = data.map(|ranges| {
1236                 let locations: Vec<lsp_types::Location> =
1237                     ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
1238
1239                 command::show_references(
1240                     reference_title(locations.len()),
1241                     &url,
1242                     annotation_range.start,
1243                     locations,
1244                 )
1245             });
1246
1247             acc.push(lsp_types::CodeLens {
1248                 range: annotation_range,
1249                 command,
1250                 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
1251             })
1252         }
1253     }
1254     Ok(())
1255 }
1256
1257 pub(crate) mod command {
1258     use ide::{FileRange, NavigationTarget};
1259     use serde_json::to_value;
1260
1261     use crate::{
1262         global_state::GlobalStateSnapshot,
1263         lsp_ext,
1264         to_proto::{location, location_link},
1265     };
1266
1267     pub(crate) fn show_references(
1268         title: String,
1269         uri: &lsp_types::Url,
1270         position: lsp_types::Position,
1271         locations: Vec<lsp_types::Location>,
1272     ) -> lsp_types::Command {
1273         // We cannot use the 'editor.action.showReferences' command directly
1274         // because that command requires vscode types which we convert in the handler
1275         // on the client side.
1276
1277         lsp_types::Command {
1278             title,
1279             command: "rust-analyzer.showReferences".into(),
1280             arguments: Some(vec![
1281                 to_value(uri).unwrap(),
1282                 to_value(position).unwrap(),
1283                 to_value(locations).unwrap(),
1284             ]),
1285         }
1286     }
1287
1288     pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
1289         lsp_types::Command {
1290             title: title.to_string(),
1291             command: "rust-analyzer.runSingle".into(),
1292             arguments: Some(vec![to_value(runnable).unwrap()]),
1293         }
1294     }
1295
1296     pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1297         lsp_types::Command {
1298             title: "Debug".into(),
1299             command: "rust-analyzer.debugSingle".into(),
1300             arguments: Some(vec![to_value(runnable).unwrap()]),
1301         }
1302     }
1303
1304     pub(crate) fn goto_location(
1305         snap: &GlobalStateSnapshot,
1306         nav: &NavigationTarget,
1307     ) -> Option<lsp_types::Command> {
1308         let value = if snap.config.location_link() {
1309             let link = location_link(snap, None, nav.clone()).ok()?;
1310             to_value(link).ok()?
1311         } else {
1312             let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1313             let location = location(snap, range).ok()?;
1314             to_value(location).ok()?
1315         };
1316
1317         Some(lsp_types::Command {
1318             title: nav.name.to_string(),
1319             command: "rust-analyzer.gotoLocation".into(),
1320             arguments: Some(vec![value]),
1321         })
1322     }
1323
1324     pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1325         lsp_types::Command {
1326             title: "triggerParameterHints".into(),
1327             command: "editor.action.triggerParameterHints".into(),
1328             arguments: None,
1329         }
1330     }
1331 }
1332
1333 pub(crate) fn implementation_title(count: usize) -> String {
1334     if count == 1 {
1335         "1 implementation".into()
1336     } else {
1337         format!("{} implementations", count)
1338     }
1339 }
1340
1341 pub(crate) fn reference_title(count: usize) -> String {
1342     if count == 1 {
1343         "1 reference".into()
1344     } else {
1345         format!("{} references", count)
1346     }
1347 }
1348
1349 pub(crate) fn markup_content(
1350     markup: Markup,
1351     kind: ide::HoverDocFormat,
1352 ) -> lsp_types::MarkupContent {
1353     let kind = match kind {
1354         ide::HoverDocFormat::Markdown => lsp_types::MarkupKind::Markdown,
1355         ide::HoverDocFormat::PlainText => lsp_types::MarkupKind::PlainText,
1356     };
1357     let value = crate::markdown::format_docs(markup.as_str());
1358     lsp_types::MarkupContent { kind, value }
1359 }
1360
1361 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1362     // This is wrong, but we don't have a better alternative I suppose?
1363     // https://github.com/microsoft/language-server-protocol/issues/1341
1364     invalid_params_error(err.to_string())
1365 }
1366
1367 #[cfg(test)]
1368 mod tests {
1369     use std::sync::Arc;
1370
1371     use ide::Analysis;
1372
1373     use super::*;
1374
1375     #[test]
1376     fn conv_fold_line_folding_only_fixup() {
1377         let text = r#"mod a;
1378 mod b;
1379 mod c;
1380
1381 fn main() {
1382     if cond {
1383         a::do_a();
1384     } else {
1385         b::do_b();
1386     }
1387 }"#;
1388
1389         let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1390         let folds = analysis.folding_ranges(file_id).unwrap();
1391         assert_eq!(folds.len(), 4);
1392
1393         let line_index = LineIndex {
1394             index: Arc::new(ide::LineIndex::new(text)),
1395             endings: LineEndings::Unix,
1396             encoding: OffsetEncoding::Utf16,
1397         };
1398         let converted: Vec<lsp_types::FoldingRange> =
1399             folds.into_iter().map(|it| folding_range(text, &line_index, true, it)).collect();
1400
1401         let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1402         assert_eq!(converted.len(), expected_lines.len());
1403         for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1404             assert_eq!(folding_range.start_line, *start_line);
1405             assert_eq!(folding_range.start_character, None);
1406             assert_eq!(folding_range.end_line, *end_line);
1407             assert_eq!(folding_range.end_character, None);
1408         }
1409     }
1410
1411     // `Url` is not able to parse windows paths on unix machines.
1412     #[test]
1413     #[cfg(target_os = "windows")]
1414     fn test_lowercase_drive_letter() {
1415         use std::path::Path;
1416
1417         let url = url_from_abs_path(Path::new("C:\\Test").try_into().unwrap());
1418         assert_eq!(url.to_string(), "file:///c:/Test");
1419
1420         let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#).try_into().unwrap());
1421         assert_eq!(url.to_string(), "file://localhost/C$/my_dir");
1422     }
1423 }