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