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