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