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