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