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