]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/to_proto.rs
update relevance score u8 -> u32
[rust.git] / crates / rust-analyzer / src / to_proto.rs
1 //! Conversion of rust-analyzer specific types to lsp_types equivalents.
2 use std::{
3     path::{self, Path},
4     sync::atomic::{AtomicU32, Ordering},
5 };
6
7 use ide::{
8     Annotation, AnnotationKind, Assist, AssistKind, CallInfo, CompletionItem, CompletionItemKind,
9     CompletionRelevance, Documentation, FileId, FileRange, FileSystemEdit, Fold, FoldKind,
10     Highlight, HlMod, HlPunct, HlRange, HlTag, Indel, InlayHint, InlayKind, InsertTextFormat,
11     Markup, NavigationTarget, ReferenceAccess, RenameError, Runnable, Severity, SourceChange,
12     TextEdit, TextRange, TextSize,
13 };
14 use ide_db::SymbolKind;
15 use itertools::Itertools;
16 use serde_json::to_value;
17
18 use crate::{
19     cargo_target_spec::CargoTargetSpec,
20     global_state::GlobalStateSnapshot,
21     line_index::{LineEndings, LineIndex, OffsetEncoding},
22     lsp_ext, semantic_tokens, Result,
23 };
24
25 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
26     let line_col = line_index.index.line_col(offset);
27     match line_index.encoding {
28         OffsetEncoding::Utf8 => lsp_types::Position::new(line_col.line, line_col.col),
29         OffsetEncoding::Utf16 => {
30             let line_col = line_index.index.to_utf16(line_col);
31             lsp_types::Position::new(line_col.line, line_col.col)
32         }
33     }
34 }
35
36 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
37     let start = position(line_index, range.start());
38     let end = position(line_index, range.end());
39     lsp_types::Range::new(start, end)
40 }
41
42 pub(crate) fn symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind {
43     match symbol_kind {
44         SymbolKind::Function => lsp_types::SymbolKind::Function,
45         SymbolKind::Struct => lsp_types::SymbolKind::Struct,
46         SymbolKind::Enum => lsp_types::SymbolKind::Enum,
47         SymbolKind::Variant => lsp_types::SymbolKind::EnumMember,
48         SymbolKind::Trait => lsp_types::SymbolKind::Interface,
49         SymbolKind::Macro => lsp_types::SymbolKind::Function,
50         SymbolKind::Module => lsp_types::SymbolKind::Module,
51         SymbolKind::TypeAlias | SymbolKind::TypeParam => lsp_types::SymbolKind::TypeParameter,
52         SymbolKind::Field => lsp_types::SymbolKind::Field,
53         SymbolKind::Static => lsp_types::SymbolKind::Constant,
54         SymbolKind::Const => lsp_types::SymbolKind::Constant,
55         SymbolKind::ConstParam => lsp_types::SymbolKind::Constant,
56         SymbolKind::Impl => lsp_types::SymbolKind::Object,
57         SymbolKind::Local
58         | SymbolKind::SelfParam
59         | SymbolKind::LifetimeParam
60         | SymbolKind::ValueParam
61         | SymbolKind::Label => lsp_types::SymbolKind::Variable,
62         SymbolKind::Union => lsp_types::SymbolKind::Struct,
63     }
64 }
65
66 pub(crate) fn document_highlight_kind(
67     reference_access: ReferenceAccess,
68 ) -> lsp_types::DocumentHighlightKind {
69     match reference_access {
70         ReferenceAccess::Read => lsp_types::DocumentHighlightKind::Read,
71         ReferenceAccess::Write => lsp_types::DocumentHighlightKind::Write,
72     }
73 }
74
75 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
76     match severity {
77         Severity::Error => lsp_types::DiagnosticSeverity::Error,
78         Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
79     }
80 }
81
82 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
83     let value = crate::markdown::format_docs(documentation.as_str());
84     let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
85     lsp_types::Documentation::MarkupContent(markup_content)
86 }
87
88 pub(crate) fn insert_text_format(
89     insert_text_format: InsertTextFormat,
90 ) -> lsp_types::InsertTextFormat {
91     match insert_text_format {
92         InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
93         InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
94     }
95 }
96
97 pub(crate) fn completion_item_kind(
98     completion_item_kind: CompletionItemKind,
99 ) -> lsp_types::CompletionItemKind {
100     match completion_item_kind {
101         CompletionItemKind::Attribute => lsp_types::CompletionItemKind::EnumMember,
102         CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
103         CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
104         CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
105         CompletionItemKind::Method => lsp_types::CompletionItemKind::Method,
106         CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
107         CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::Reference,
108         CompletionItemKind::SymbolKind(symbol) => match symbol {
109             SymbolKind::Const => lsp_types::CompletionItemKind::Constant,
110             SymbolKind::ConstParam => lsp_types::CompletionItemKind::TypeParameter,
111             SymbolKind::Enum => lsp_types::CompletionItemKind::Enum,
112             SymbolKind::Field => lsp_types::CompletionItemKind::Field,
113             SymbolKind::Function => lsp_types::CompletionItemKind::Function,
114             SymbolKind::Impl => lsp_types::CompletionItemKind::Text,
115             SymbolKind::Label => lsp_types::CompletionItemKind::Variable,
116             SymbolKind::LifetimeParam => lsp_types::CompletionItemKind::TypeParameter,
117             SymbolKind::Local => lsp_types::CompletionItemKind::Variable,
118             SymbolKind::Macro => lsp_types::CompletionItemKind::Method,
119             SymbolKind::Module => lsp_types::CompletionItemKind::Module,
120             SymbolKind::SelfParam => lsp_types::CompletionItemKind::Value,
121             SymbolKind::Static => lsp_types::CompletionItemKind::Value,
122             SymbolKind::Struct => lsp_types::CompletionItemKind::Struct,
123             SymbolKind::Trait => lsp_types::CompletionItemKind::Interface,
124             SymbolKind::TypeAlias => lsp_types::CompletionItemKind::Struct,
125             SymbolKind::TypeParam => lsp_types::CompletionItemKind::TypeParameter,
126             SymbolKind::Union => lsp_types::CompletionItemKind::Struct,
127             SymbolKind::ValueParam => lsp_types::CompletionItemKind::Value,
128             SymbolKind::Variant => lsp_types::CompletionItemKind::EnumMember,
129         },
130     }
131 }
132
133 pub(crate) fn text_edit(line_index: &LineIndex, indel: Indel) -> lsp_types::TextEdit {
134     let range = range(line_index, indel.delete);
135     let new_text = match line_index.endings {
136         LineEndings::Unix => indel.insert,
137         LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
138     };
139     lsp_types::TextEdit { range, new_text }
140 }
141
142 pub(crate) fn snippet_text_edit(
143     line_index: &LineIndex,
144     is_snippet: bool,
145     indel: Indel,
146 ) -> lsp_ext::SnippetTextEdit {
147     let text_edit = text_edit(line_index, indel);
148     let insert_text_format =
149         if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
150     lsp_ext::SnippetTextEdit {
151         range: text_edit.range,
152         new_text: text_edit.new_text,
153         insert_text_format,
154     }
155 }
156
157 pub(crate) fn text_edit_vec(
158     line_index: &LineIndex,
159     text_edit: TextEdit,
160 ) -> Vec<lsp_types::TextEdit> {
161     text_edit.into_iter().map(|indel| self::text_edit(line_index, indel)).collect()
162 }
163
164 pub(crate) fn snippet_text_edit_vec(
165     line_index: &LineIndex,
166     is_snippet: bool,
167     text_edit: TextEdit,
168 ) -> Vec<lsp_ext::SnippetTextEdit> {
169     text_edit
170         .into_iter()
171         .map(|indel| self::snippet_text_edit(line_index, is_snippet, indel))
172         .collect()
173 }
174
175 pub(crate) fn completion_item(
176     line_index: &LineIndex,
177     item: CompletionItem,
178 ) -> Vec<lsp_types::CompletionItem> {
179     let mut additional_text_edits = Vec::new();
180     let mut text_edit = None;
181     // LSP does not allow arbitrary edits in completion, so we have to do a
182     // non-trivial mapping here.
183     let source_range = item.source_range();
184     for indel in item.text_edit().iter() {
185         if indel.delete.contains_range(source_range) {
186             text_edit = Some(if indel.delete == source_range {
187                 self::text_edit(line_index, indel.clone())
188             } else {
189                 assert!(source_range.end() == indel.delete.end());
190                 let range1 = TextRange::new(indel.delete.start(), source_range.start());
191                 let range2 = source_range;
192                 let indel1 = Indel::replace(range1, String::new());
193                 let indel2 = Indel::replace(range2, indel.insert.clone());
194                 additional_text_edits.push(self::text_edit(line_index, indel1));
195                 self::text_edit(line_index, indel2)
196             })
197         } else {
198             assert!(source_range.intersect(indel.delete).is_none());
199             let text_edit = self::text_edit(line_index, indel.clone());
200             additional_text_edits.push(text_edit);
201         }
202     }
203     let text_edit = text_edit.unwrap();
204
205     let mut lsp_item = lsp_types::CompletionItem {
206         label: item.label().to_string(),
207         detail: item.detail().map(|it| it.to_string()),
208         filter_text: Some(item.lookup().to_string()),
209         kind: item.kind().map(completion_item_kind),
210         text_edit: Some(text_edit.into()),
211         additional_text_edits: Some(additional_text_edits),
212         documentation: item.documentation().map(documentation),
213         deprecated: Some(item.deprecated()),
214         ..Default::default()
215     };
216
217     fn set_score(res: &mut lsp_types::CompletionItem, relevance: CompletionRelevance) {
218         if relevance.is_relevant() {
219             res.preselect = Some(true);
220         }
221         // The relevance needs to be inverted to come up with a sort score
222         // because the client will sort ascending.
223         let sort_score = relevance.score() ^ 0xFF_FF_FF_FF;
224         // Zero pad the string to ensure values can be properly sorted
225         // by the client. Hex format is used because it is easier to
226         // visually compare very large values, which the sort text
227         // tends to be since it is the opposite of the score.
228         res.sort_text = Some(format!("{:08x}", sort_score));
229     }
230
231     set_score(&mut lsp_item, item.relevance());
232
233     if item.deprecated() {
234         lsp_item.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
235     }
236
237     if item.trigger_call_info() {
238         lsp_item.command = Some(command::trigger_parameter_hints());
239     }
240
241     let mut res = match item.ref_match() {
242         Some((mutability, relevance)) => {
243             let mut lsp_item_with_ref = lsp_item.clone();
244             set_score(&mut lsp_item_with_ref, relevance);
245             lsp_item_with_ref.label =
246                 format!("&{}{}", mutability.as_keyword_for_ref(), lsp_item_with_ref.label);
247             if let Some(lsp_types::CompletionTextEdit::Edit(it)) = &mut lsp_item_with_ref.text_edit
248             {
249                 it.new_text = format!("&{}{}", mutability.as_keyword_for_ref(), it.new_text);
250             }
251             vec![lsp_item_with_ref, lsp_item]
252         }
253         None => vec![lsp_item],
254     };
255
256     for lsp_item in res.iter_mut() {
257         lsp_item.insert_text_format = Some(insert_text_format(item.insert_text_format()));
258     }
259     res
260 }
261
262 pub(crate) fn signature_help(
263     call_info: CallInfo,
264     concise: bool,
265     label_offsets: bool,
266 ) -> lsp_types::SignatureHelp {
267     let (label, parameters) = match (concise, label_offsets) {
268         (_, false) => {
269             let params = call_info
270                 .parameter_labels()
271                 .map(|label| lsp_types::ParameterInformation {
272                     label: lsp_types::ParameterLabel::Simple(label.to_string()),
273                     documentation: None,
274                 })
275                 .collect::<Vec<_>>();
276             let label =
277                 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
278             (label, params)
279         }
280         (false, true) => {
281             let params = call_info
282                 .parameter_ranges()
283                 .iter()
284                 .map(|it| [u32::from(it.start()).into(), u32::from(it.end()).into()])
285                 .map(|label_offsets| lsp_types::ParameterInformation {
286                     label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
287                     documentation: None,
288                 })
289                 .collect::<Vec<_>>();
290             (call_info.signature, params)
291         }
292         (true, true) => {
293             let mut params = Vec::new();
294             let mut label = String::new();
295             let mut first = true;
296             for param in call_info.parameter_labels() {
297                 if !first {
298                     label.push_str(", ");
299                 }
300                 first = false;
301                 let start = label.len() as u32;
302                 label.push_str(param);
303                 let end = label.len() as u32;
304                 params.push(lsp_types::ParameterInformation {
305                     label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
306                     documentation: None,
307                 });
308             }
309
310             (label, params)
311         }
312     };
313
314     let documentation = if concise {
315         None
316     } else {
317         call_info.doc.map(|doc| {
318             lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
319                 kind: lsp_types::MarkupKind::Markdown,
320                 value: doc,
321             })
322         })
323     };
324
325     let active_parameter = call_info.active_parameter.map(|it| it as u32);
326
327     let signature = lsp_types::SignatureInformation {
328         label,
329         documentation,
330         parameters: Some(parameters),
331         active_parameter,
332     };
333     lsp_types::SignatureHelp {
334         signatures: vec![signature],
335         active_signature: None,
336         active_parameter,
337     }
338 }
339
340 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
341     lsp_ext::InlayHint {
342         label: inlay_hint.label.to_string(),
343         range: range(line_index, inlay_hint.range),
344         kind: match inlay_hint.kind {
345             InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
346             InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
347             InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
348         },
349     }
350 }
351
352 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
353
354 pub(crate) fn semantic_tokens(
355     text: &str,
356     line_index: &LineIndex,
357     highlights: Vec<HlRange>,
358 ) -> lsp_types::SemanticTokens {
359     let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
360     let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
361
362     for highlight_range in highlights {
363         if highlight_range.highlight.is_empty() {
364             continue;
365         }
366         let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
367         let token_index = semantic_tokens::type_index(type_);
368         let modifier_bitset = mods.0;
369
370         for mut text_range in line_index.index.lines(highlight_range.range) {
371             if text[text_range].ends_with('\n') {
372                 text_range =
373                     TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
374             }
375             let range = range(&line_index, text_range);
376             builder.push(range, token_index, modifier_bitset);
377         }
378     }
379
380     builder.build()
381 }
382
383 pub(crate) fn semantic_token_delta(
384     previous: &lsp_types::SemanticTokens,
385     current: &lsp_types::SemanticTokens,
386 ) -> lsp_types::SemanticTokensDelta {
387     let result_id = current.result_id.clone();
388     let edits = semantic_tokens::diff_tokens(&previous.data, &current.data);
389     lsp_types::SemanticTokensDelta { result_id, edits }
390 }
391
392 fn semantic_token_type_and_modifiers(
393     highlight: Highlight,
394 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
395     let mut mods = semantic_tokens::ModifierSet::default();
396     let type_ = match highlight.tag {
397         HlTag::Symbol(symbol) => match symbol {
398             SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
399             SymbolKind::Impl => lsp_types::SemanticTokenType::TYPE,
400             SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
401             SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
402             SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
403             SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
404             SymbolKind::Label => semantic_tokens::LABEL,
405             SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
406             SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
407             SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
408             SymbolKind::Function => {
409                 if highlight.mods.contains(HlMod::Associated) {
410                     lsp_types::SemanticTokenType::METHOD
411                 } else {
412                     lsp_types::SemanticTokenType::FUNCTION
413                 }
414             }
415             SymbolKind::Const => {
416                 mods |= semantic_tokens::CONSTANT;
417                 mods |= lsp_types::SemanticTokenModifier::STATIC;
418                 lsp_types::SemanticTokenType::VARIABLE
419             }
420             SymbolKind::Static => {
421                 mods |= lsp_types::SemanticTokenModifier::STATIC;
422                 lsp_types::SemanticTokenType::VARIABLE
423             }
424             SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
425             SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
426             SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
427             SymbolKind::Union => semantic_tokens::UNION,
428             SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
429             SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
430             SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
431         },
432         HlTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
433         HlTag::None => semantic_tokens::GENERIC,
434         HlTag::ByteLiteral | HlTag::NumericLiteral => lsp_types::SemanticTokenType::NUMBER,
435         HlTag::BoolLiteral => semantic_tokens::BOOLEAN,
436         HlTag::StringLiteral => lsp_types::SemanticTokenType::STRING,
437         HlTag::CharLiteral => semantic_tokens::CHAR_LITERAL,
438         HlTag::Comment => lsp_types::SemanticTokenType::COMMENT,
439         HlTag::Attribute => semantic_tokens::ATTRIBUTE,
440         HlTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
441         HlTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
442         HlTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
443         HlTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
444         HlTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
445         HlTag::Punctuation(punct) => match punct {
446             HlPunct::Bracket => semantic_tokens::BRACKET,
447             HlPunct::Brace => semantic_tokens::BRACE,
448             HlPunct::Parenthesis => semantic_tokens::PARENTHESIS,
449             HlPunct::Angle => semantic_tokens::ANGLE,
450             HlPunct::Comma => semantic_tokens::COMMA,
451             HlPunct::Dot => semantic_tokens::DOT,
452             HlPunct::Colon => semantic_tokens::COLON,
453             HlPunct::Semi => semantic_tokens::SEMICOLON,
454             HlPunct::Other => semantic_tokens::PUNCTUATION,
455         },
456     };
457
458     for modifier in highlight.mods.iter() {
459         let modifier = match modifier {
460             HlMod::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
461             HlMod::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
462             HlMod::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
463             HlMod::Injected => semantic_tokens::INJECTED,
464             HlMod::ControlFlow => semantic_tokens::CONTROL_FLOW,
465             HlMod::Mutable => semantic_tokens::MUTABLE,
466             HlMod::Consuming => semantic_tokens::CONSUMING,
467             HlMod::Unsafe => semantic_tokens::UNSAFE,
468             HlMod::Callable => semantic_tokens::CALLABLE,
469             HlMod::Static => lsp_types::SemanticTokenModifier::STATIC,
470             HlMod::Associated => continue,
471         };
472         mods |= modifier;
473     }
474
475     (type_, mods)
476 }
477
478 pub(crate) fn folding_range(
479     text: &str,
480     line_index: &LineIndex,
481     line_folding_only: bool,
482     fold: Fold,
483 ) -> lsp_types::FoldingRange {
484     let kind = match fold.kind {
485         FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
486         FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
487         FoldKind::Mods | FoldKind::Block | FoldKind::ArgList | FoldKind::Region => None,
488     };
489
490     let range = range(line_index, fold.range);
491
492     if line_folding_only {
493         // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
494         // even if it contains text not in the folding range. To prevent that we exclude
495         // range.end.line from the folding region if there is more text after range.end
496         // on the same line.
497         let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
498             .chars()
499             .take_while(|it| *it != '\n')
500             .any(|it| !it.is_whitespace());
501
502         let end_line = if has_more_text_on_end_line {
503             range.end.line.saturating_sub(1)
504         } else {
505             range.end.line
506         };
507
508         lsp_types::FoldingRange {
509             start_line: range.start.line,
510             start_character: None,
511             end_line,
512             end_character: None,
513             kind,
514         }
515     } else {
516         lsp_types::FoldingRange {
517             start_line: range.start.line,
518             start_character: Some(range.start.character),
519             end_line: range.end.line,
520             end_character: Some(range.end.character),
521             kind,
522         }
523     }
524 }
525
526 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
527     snap.file_id_to_url(file_id)
528 }
529
530 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
531 /// This will only happen when processing windows paths.
532 ///
533 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
534 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
535     assert!(path.is_absolute());
536     let url = lsp_types::Url::from_file_path(path).unwrap();
537     match path.components().next() {
538         Some(path::Component::Prefix(prefix))
539             if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
540         {
541             // Need to lowercase driver letter
542         }
543         _ => return url,
544     }
545
546     let driver_letter_range = {
547         let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
548             Some(it) => it,
549             None => return url,
550         };
551         let start = scheme.len() + ':'.len_utf8();
552         start..(start + drive_letter.len())
553     };
554
555     // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
556     // machinery *also* canonicalizes the drive letter. So, just massage the
557     // string in place.
558     let mut url = url.into_string();
559     url[driver_letter_range].make_ascii_lowercase();
560     lsp_types::Url::parse(&url).unwrap()
561 }
562
563 pub(crate) fn optional_versioned_text_document_identifier(
564     snap: &GlobalStateSnapshot,
565     file_id: FileId,
566 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
567     let url = url(snap, file_id);
568     let version = snap.url_file_version(&url);
569     lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
570 }
571
572 pub(crate) fn location(
573     snap: &GlobalStateSnapshot,
574     frange: FileRange,
575 ) -> Result<lsp_types::Location> {
576     let url = url(snap, frange.file_id);
577     let line_index = snap.file_line_index(frange.file_id)?;
578     let range = range(&line_index, frange.range);
579     let loc = lsp_types::Location::new(url, range);
580     Ok(loc)
581 }
582
583 /// Perefer using `location_link`, if the client has the cap.
584 pub(crate) fn location_from_nav(
585     snap: &GlobalStateSnapshot,
586     nav: NavigationTarget,
587 ) -> Result<lsp_types::Location> {
588     let url = url(snap, nav.file_id);
589     let line_index = snap.file_line_index(nav.file_id)?;
590     let range = range(&line_index, nav.full_range);
591     let loc = lsp_types::Location::new(url, range);
592     Ok(loc)
593 }
594
595 pub(crate) fn location_link(
596     snap: &GlobalStateSnapshot,
597     src: Option<FileRange>,
598     target: NavigationTarget,
599 ) -> Result<lsp_types::LocationLink> {
600     let origin_selection_range = match src {
601         Some(src) => {
602             let line_index = snap.file_line_index(src.file_id)?;
603             let range = range(&line_index, src.range);
604             Some(range)
605         }
606         None => None,
607     };
608     let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
609     let res = lsp_types::LocationLink {
610         origin_selection_range,
611         target_uri,
612         target_range,
613         target_selection_range,
614     };
615     Ok(res)
616 }
617
618 fn location_info(
619     snap: &GlobalStateSnapshot,
620     target: NavigationTarget,
621 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
622     let line_index = snap.file_line_index(target.file_id)?;
623
624     let target_uri = url(snap, target.file_id);
625     let target_range = range(&line_index, target.full_range);
626     let target_selection_range =
627         target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
628     Ok((target_uri, target_range, target_selection_range))
629 }
630
631 pub(crate) fn goto_definition_response(
632     snap: &GlobalStateSnapshot,
633     src: Option<FileRange>,
634     targets: Vec<NavigationTarget>,
635 ) -> Result<lsp_types::GotoDefinitionResponse> {
636     if snap.config.location_link() {
637         let links = targets
638             .into_iter()
639             .map(|nav| location_link(snap, src, nav))
640             .collect::<Result<Vec<_>>>()?;
641         Ok(links.into())
642     } else {
643         let locations = targets
644             .into_iter()
645             .map(|nav| {
646                 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
647             })
648             .collect::<Result<Vec<_>>>()?;
649         Ok(locations.into())
650     }
651 }
652
653 pub(crate) fn snippet_text_document_edit(
654     snap: &GlobalStateSnapshot,
655     is_snippet: bool,
656     file_id: FileId,
657     edit: TextEdit,
658 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
659     let text_document = optional_versioned_text_document_identifier(snap, file_id);
660     let line_index = snap.file_line_index(file_id)?;
661     let edits = edit.into_iter().map(|it| snippet_text_edit(&line_index, is_snippet, it)).collect();
662     Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
663 }
664
665 pub(crate) fn snippet_text_document_ops(
666     snap: &GlobalStateSnapshot,
667     file_system_edit: FileSystemEdit,
668 ) -> Vec<lsp_ext::SnippetDocumentChangeOperation> {
669     let mut ops = Vec::new();
670     match file_system_edit {
671         FileSystemEdit::CreateFile { dst, initial_contents } => {
672             let uri = snap.anchored_path(&dst);
673             let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
674                 uri: uri.clone(),
675                 options: None,
676                 annotation_id: None,
677             });
678             ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
679             if !initial_contents.is_empty() {
680                 let text_document =
681                     lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
682                 let text_edit = lsp_ext::SnippetTextEdit {
683                     range: lsp_types::Range::default(),
684                     new_text: initial_contents,
685                     insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
686                 };
687                 let edit_file =
688                     lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
689                 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
690             }
691         }
692         FileSystemEdit::MoveFile { src, dst } => {
693             let old_uri = snap.file_id_to_url(src);
694             let new_uri = snap.anchored_path(&dst);
695             let rename_file = lsp_types::ResourceOp::Rename(lsp_types::RenameFile {
696                 old_uri,
697                 new_uri,
698                 options: None,
699                 annotation_id: None,
700             });
701             ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(rename_file))
702         }
703     }
704     ops
705 }
706
707 pub(crate) fn snippet_workspace_edit(
708     snap: &GlobalStateSnapshot,
709     source_change: SourceChange,
710 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
711     let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
712     for op in source_change.file_system_edits {
713         let ops = snippet_text_document_ops(snap, op);
714         document_changes.extend_from_slice(&ops);
715     }
716     for (file_id, edit) in source_change.source_file_edits {
717         let edit = snippet_text_document_edit(&snap, source_change.is_snippet, file_id, edit)?;
718         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
719     }
720     let workspace_edit =
721         lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
722     Ok(workspace_edit)
723 }
724
725 pub(crate) fn workspace_edit(
726     snap: &GlobalStateSnapshot,
727     source_change: SourceChange,
728 ) -> Result<lsp_types::WorkspaceEdit> {
729     assert!(!source_change.is_snippet);
730     snippet_workspace_edit(snap, source_change).map(|it| it.into())
731 }
732
733 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
734     fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
735         lsp_types::WorkspaceEdit {
736             changes: None,
737             document_changes: snippet_workspace_edit.document_changes.map(|changes| {
738                 lsp_types::DocumentChanges::Operations(
739                     changes
740                         .into_iter()
741                         .map(|change| match change {
742                             lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
743                                 lsp_types::DocumentChangeOperation::Op(op)
744                             }
745                             lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
746                                 lsp_types::DocumentChangeOperation::Edit(
747                                     lsp_types::TextDocumentEdit {
748                                         text_document: edit.text_document,
749                                         edits: edit
750                                             .edits
751                                             .into_iter()
752                                             .map(|edit| {
753                                                 lsp_types::OneOf::Left(lsp_types::TextEdit {
754                                                     range: edit.range,
755                                                     new_text: edit.new_text,
756                                                 })
757                                             })
758                                             .collect(),
759                                     },
760                                 )
761                             }
762                         })
763                         .collect(),
764                 )
765             }),
766             change_annotations: None,
767         }
768     }
769 }
770
771 pub(crate) fn call_hierarchy_item(
772     snap: &GlobalStateSnapshot,
773     target: NavigationTarget,
774 ) -> Result<lsp_types::CallHierarchyItem> {
775     let name = target.name.to_string();
776     let detail = target.description.clone();
777     let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
778     let (uri, range, selection_range) = location_info(snap, target)?;
779     Ok(lsp_types::CallHierarchyItem {
780         name,
781         kind,
782         tags: None,
783         detail,
784         uri,
785         range,
786         selection_range,
787         data: None,
788     })
789 }
790
791 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
792     match kind {
793         AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
794         AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
795         AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
796         AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
797         AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
798         AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
799     }
800 }
801
802 pub(crate) fn unresolved_code_action(
803     snap: &GlobalStateSnapshot,
804     code_action_params: lsp_types::CodeActionParams,
805     assist: Assist,
806     index: usize,
807 ) -> Result<lsp_ext::CodeAction> {
808     assert!(assist.source_change.is_none());
809     let res = lsp_ext::CodeAction {
810         title: assist.label.to_string(),
811         group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
812         kind: Some(code_action_kind(assist.id.1)),
813         edit: None,
814         is_preferred: None,
815         data: Some(lsp_ext::CodeActionData {
816             id: format!("{}:{}", assist.id.0, index.to_string()),
817             code_action_params,
818         }),
819     };
820     Ok(res)
821 }
822
823 pub(crate) fn resolved_code_action(
824     snap: &GlobalStateSnapshot,
825     assist: Assist,
826 ) -> Result<lsp_ext::CodeAction> {
827     let change = assist.source_change.unwrap();
828     let res = lsp_ext::CodeAction {
829         edit: Some(snippet_workspace_edit(snap, change)?),
830         title: assist.label.to_string(),
831         group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
832         kind: Some(code_action_kind(assist.id.1)),
833         is_preferred: None,
834         data: None,
835     };
836     Ok(res)
837 }
838
839 pub(crate) fn runnable(
840     snap: &GlobalStateSnapshot,
841     file_id: FileId,
842     runnable: Runnable,
843 ) -> Result<lsp_ext::Runnable> {
844     let config = snap.config.runnables();
845     let spec = CargoTargetSpec::for_file(snap, file_id)?;
846     let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
847     let target = spec.as_ref().map(|s| s.target.clone());
848     let (cargo_args, executable_args) =
849         CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
850     let label = runnable.label(target);
851     let location = location_link(snap, None, runnable.nav)?;
852
853     Ok(lsp_ext::Runnable {
854         label,
855         location: Some(location),
856         kind: lsp_ext::RunnableKind::Cargo,
857         args: lsp_ext::CargoRunnable {
858             workspace_root: workspace_root.map(|it| it.into()),
859             override_cargo: config.override_cargo,
860             cargo_args,
861             cargo_extra_args: config.cargo_extra_args,
862             executable_args,
863             expect_test: None,
864         },
865     })
866 }
867
868 pub(crate) fn code_lens(
869     snap: &GlobalStateSnapshot,
870     annotation: Annotation,
871 ) -> Result<lsp_types::CodeLens> {
872     match annotation.kind {
873         AnnotationKind::Runnable { debug, runnable: run } => {
874             let line_index = snap.file_line_index(run.nav.file_id)?;
875             let annotation_range = range(&line_index, annotation.range);
876
877             let action = run.action();
878             let r = runnable(&snap, run.nav.file_id, run)?;
879
880             let command = if debug {
881                 command::debug_single(&r)
882             } else {
883                 let title = action.run_title.to_string();
884                 command::run_single(&r, &title)
885             };
886
887             Ok(lsp_types::CodeLens { range: annotation_range, command: Some(command), data: None })
888         }
889         AnnotationKind::HasImpls { position: file_position, data } => {
890             let line_index = snap.file_line_index(file_position.file_id)?;
891             let annotation_range = range(&line_index, annotation.range);
892             let url = url(snap, file_position.file_id);
893
894             let position = position(&line_index, file_position.offset);
895
896             let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
897
898             let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
899
900             let goto_params = lsp_types::request::GotoImplementationParams {
901                 text_document_position_params: doc_pos,
902                 work_done_progress_params: Default::default(),
903                 partial_result_params: Default::default(),
904             };
905
906             let command = data.map(|ranges| {
907                 let locations: Vec<lsp_types::Location> = ranges
908                     .into_iter()
909                     .filter_map(|target| {
910                         location(
911                             snap,
912                             FileRange { file_id: target.file_id, range: target.full_range },
913                         )
914                         .ok()
915                     })
916                     .collect();
917
918                 command::show_references(
919                     implementation_title(locations.len()),
920                     &url,
921                     position,
922                     locations,
923                 )
924             });
925
926             Ok(lsp_types::CodeLens {
927                 range: annotation_range,
928                 command,
929                 data: Some(to_value(lsp_ext::CodeLensResolveData::Impls(goto_params)).unwrap()),
930             })
931         }
932         AnnotationKind::HasReferences { position: file_position, data } => {
933             let line_index = snap.file_line_index(file_position.file_id)?;
934             let annotation_range = range(&line_index, annotation.range);
935             let url = url(snap, file_position.file_id);
936
937             let position = position(&line_index, file_position.offset);
938
939             let id = lsp_types::TextDocumentIdentifier { uri: url.clone() };
940
941             let doc_pos = lsp_types::TextDocumentPositionParams::new(id, position);
942
943             let command = data.map(|ranges| {
944                 let locations: Vec<lsp_types::Location> =
945                     ranges.into_iter().filter_map(|range| location(snap, range).ok()).collect();
946
947                 command::show_references(
948                     reference_title(locations.len()),
949                     &url,
950                     position,
951                     locations,
952                 )
953             });
954
955             Ok(lsp_types::CodeLens {
956                 range: annotation_range,
957                 command,
958                 data: Some(to_value(lsp_ext::CodeLensResolveData::References(doc_pos)).unwrap()),
959             })
960         }
961     }
962 }
963
964 pub(crate) mod command {
965     use ide::{FileRange, NavigationTarget};
966     use serde_json::to_value;
967
968     use crate::{
969         global_state::GlobalStateSnapshot,
970         lsp_ext,
971         to_proto::{location, location_link},
972     };
973
974     pub(crate) fn show_references(
975         title: String,
976         uri: &lsp_types::Url,
977         position: lsp_types::Position,
978         locations: Vec<lsp_types::Location>,
979     ) -> lsp_types::Command {
980         // We cannot use the 'editor.action.showReferences' command directly
981         // because that command requires vscode types which we convert in the handler
982         // on the client side.
983
984         lsp_types::Command {
985             title,
986             command: "rust-analyzer.showReferences".into(),
987             arguments: Some(vec![
988                 to_value(uri).unwrap(),
989                 to_value(position).unwrap(),
990                 to_value(locations).unwrap(),
991             ]),
992         }
993     }
994
995     pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command {
996         lsp_types::Command {
997             title: title.to_string(),
998             command: "rust-analyzer.runSingle".into(),
999             arguments: Some(vec![to_value(runnable).unwrap()]),
1000         }
1001     }
1002
1003     pub(crate) fn debug_single(runnable: &lsp_ext::Runnable) -> lsp_types::Command {
1004         lsp_types::Command {
1005             title: "Debug".into(),
1006             command: "rust-analyzer.debugSingle".into(),
1007             arguments: Some(vec![to_value(runnable).unwrap()]),
1008         }
1009     }
1010
1011     pub(crate) fn goto_location(
1012         snap: &GlobalStateSnapshot,
1013         nav: &NavigationTarget,
1014     ) -> Option<lsp_types::Command> {
1015         let value = if snap.config.location_link() {
1016             let link = location_link(snap, None, nav.clone()).ok()?;
1017             to_value(link).ok()?
1018         } else {
1019             let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1020             let location = location(snap, range).ok()?;
1021             to_value(location).ok()?
1022         };
1023
1024         Some(lsp_types::Command {
1025             title: nav.name.to_string(),
1026             command: "rust-analyzer.gotoLocation".into(),
1027             arguments: Some(vec![value]),
1028         })
1029     }
1030
1031     pub(crate) fn trigger_parameter_hints() -> lsp_types::Command {
1032         lsp_types::Command {
1033             title: "triggerParameterHints".into(),
1034             command: "editor.action.triggerParameterHints".into(),
1035             arguments: None,
1036         }
1037     }
1038 }
1039
1040 pub(crate) fn implementation_title(count: usize) -> String {
1041     if count == 1 {
1042         "1 implementation".into()
1043     } else {
1044         format!("{} implementations", count)
1045     }
1046 }
1047
1048 pub(crate) fn reference_title(count: usize) -> String {
1049     if count == 1 {
1050         "1 reference".into()
1051     } else {
1052         format!("{} references", count)
1053     }
1054 }
1055
1056 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
1057     let value = crate::markdown::format_docs(markup.as_str());
1058     lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
1059 }
1060
1061 pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
1062     crate::LspError { code: lsp_server::ErrorCode::InvalidParams as i32, message: err.to_string() }
1063 }
1064
1065 #[cfg(test)]
1066 mod tests {
1067     use std::sync::Arc;
1068
1069     use hir::PrefixKind;
1070     use ide::Analysis;
1071     use ide_db::helpers::{insert_use::InsertUseConfig, SnippetCap};
1072
1073     use super::*;
1074
1075     #[test]
1076     fn test_completion_with_ref() {
1077         let fixture = r#"
1078         struct Foo;
1079         fn foo(arg: &Foo) {}
1080         fn main() {
1081             let arg = Foo;
1082             foo($0)
1083         }"#;
1084
1085         let (offset, text) = test_utils::extract_offset(fixture);
1086         let line_index = LineIndex {
1087             index: Arc::new(ide::LineIndex::new(&text)),
1088             endings: LineEndings::Unix,
1089             encoding: OffsetEncoding::Utf16,
1090         };
1091         let (analysis, file_id) = Analysis::from_single_file(text);
1092         let completions: Vec<(String, Option<String>)> = analysis
1093             .completions(
1094                 &ide::CompletionConfig {
1095                     enable_postfix_completions: true,
1096                     enable_imports_on_the_fly: true,
1097                     add_call_parenthesis: true,
1098                     add_call_argument_snippets: true,
1099                     snippet_cap: SnippetCap::new(true),
1100                     insert_use: InsertUseConfig {
1101                         merge: None,
1102                         prefix_kind: PrefixKind::Plain,
1103                         group: true,
1104                     },
1105                 },
1106                 ide_db::base_db::FilePosition { file_id, offset },
1107             )
1108             .unwrap()
1109             .unwrap()
1110             .into_iter()
1111             .filter(|c| c.label().ends_with("arg"))
1112             .map(|c| completion_item(&line_index, c))
1113             .flat_map(|comps| comps.into_iter().map(|c| (c.label, c.sort_text)))
1114             .collect();
1115         expect_test::expect![[r#"
1116             [
1117                 (
1118                     "&arg",
1119                     Some(
1120                         "fffffffd",
1121                     ),
1122                 ),
1123                 (
1124                     "arg",
1125                     Some(
1126                         "fffffffe",
1127                     ),
1128                 ),
1129             ]
1130         "#]]
1131         .assert_debug_eq(&completions);
1132     }
1133
1134     #[test]
1135     fn conv_fold_line_folding_only_fixup() {
1136         let text = r#"mod a;
1137 mod b;
1138 mod c;
1139
1140 fn main() {
1141     if cond {
1142         a::do_a();
1143     } else {
1144         b::do_b();
1145     }
1146 }"#;
1147
1148         let (analysis, file_id) = Analysis::from_single_file(text.to_string());
1149         let folds = analysis.folding_ranges(file_id).unwrap();
1150         assert_eq!(folds.len(), 4);
1151
1152         let line_index = LineIndex {
1153             index: Arc::new(ide::LineIndex::new(&text)),
1154             endings: LineEndings::Unix,
1155             encoding: OffsetEncoding::Utf16,
1156         };
1157         let converted: Vec<lsp_types::FoldingRange> =
1158             folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
1159
1160         let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
1161         assert_eq!(converted.len(), expected_lines.len());
1162         for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
1163             assert_eq!(folding_range.start_line, *start_line);
1164             assert_eq!(folding_range.start_character, None);
1165             assert_eq!(folding_range.end_line, *end_line);
1166             assert_eq!(folding_range.end_character, None);
1167         }
1168     }
1169
1170     // `Url` is not able to parse windows paths on unix machines.
1171     #[test]
1172     #[cfg(target_os = "windows")]
1173     fn test_lowercase_drive_letter_with_drive() {
1174         let url = url_from_abs_path(Path::new("C:\\Test"));
1175         assert_eq!(url.to_string(), "file:///c:/Test");
1176     }
1177
1178     #[test]
1179     #[cfg(target_os = "windows")]
1180     fn test_drive_without_colon_passthrough() {
1181         let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
1182         assert_eq!(url.to_string(), "file://localhost/C$/my_dir");
1183     }
1184 }