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