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