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