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