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