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