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