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