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