]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/to_proto.rs
999b18351558d5c8884e4d3ca96d4ce13fb25c3d
[rust.git] / crates / rust-analyzer / src / to_proto.rs
1 //! Conversion of rust-analyzer specific types to lsp_types equivalents.
2 use std::{
3     path::{self, Path},
4     sync::atomic::{AtomicU32, Ordering},
5 };
6
7 use ide::{
8     Assist, AssistKind, CallInfo, CompletionItem, CompletionItemKind, Documentation, FileId,
9     FileRange, FileSystemEdit, Fold, FoldKind, Highlight, HighlightModifier, HighlightTag,
10     HighlightedRange, Indel, InlayHint, InlayKind, InsertTextFormat, LineIndex, Markup,
11     NavigationTarget, ReferenceAccess, Runnable, Severity, SourceChange, SourceFileEdit,
12     SymbolKind, TextEdit, TextRange, TextSize,
13 };
14 use itertools::Itertools;
15
16 use crate::{
17     cargo_target_spec::CargoTargetSpec, global_state::GlobalStateSnapshot,
18     line_endings::LineEndings, lsp_ext, semantic_tokens, Result,
19 };
20
21 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
22     let line_col = line_index.line_col(offset);
23     lsp_types::Position::new(line_col.line, line_col.col_utf16)
24 }
25
26 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
27     let start = position(line_index, range.start());
28     let end = position(line_index, range.end());
29     lsp_types::Range::new(start, end)
30 }
31
32 pub(crate) fn symbol_kind(symbol_kind: SymbolKind) -> lsp_types::SymbolKind {
33     match symbol_kind {
34         SymbolKind::Function => lsp_types::SymbolKind::Function,
35         SymbolKind::Struct => lsp_types::SymbolKind::Struct,
36         SymbolKind::Enum => lsp_types::SymbolKind::Enum,
37         SymbolKind::Variant => lsp_types::SymbolKind::EnumMember,
38         SymbolKind::Trait => lsp_types::SymbolKind::Interface,
39         SymbolKind::Macro => lsp_types::SymbolKind::Function,
40         SymbolKind::Module => lsp_types::SymbolKind::Module,
41         SymbolKind::TypeAlias | SymbolKind::TypeParam => lsp_types::SymbolKind::TypeParameter,
42         SymbolKind::Field => lsp_types::SymbolKind::Field,
43         SymbolKind::Static => lsp_types::SymbolKind::Constant,
44         SymbolKind::Const => lsp_types::SymbolKind::Constant,
45         SymbolKind::ConstParam => lsp_types::SymbolKind::Constant,
46         SymbolKind::Impl => lsp_types::SymbolKind::Object,
47         SymbolKind::Local
48         | SymbolKind::SelfParam
49         | SymbolKind::LifetimeParam
50         | SymbolKind::ValueParam
51         | SymbolKind::Label => lsp_types::SymbolKind::Variable,
52         SymbolKind::Union => lsp_types::SymbolKind::Struct,
53     }
54 }
55
56 pub(crate) fn document_highlight_kind(
57     reference_access: ReferenceAccess,
58 ) -> lsp_types::DocumentHighlightKind {
59     match reference_access {
60         ReferenceAccess::Read => lsp_types::DocumentHighlightKind::Read,
61         ReferenceAccess::Write => lsp_types::DocumentHighlightKind::Write,
62     }
63 }
64
65 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
66     match severity {
67         Severity::Error => lsp_types::DiagnosticSeverity::Error,
68         Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
69     }
70 }
71
72 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
73     let value = crate::markdown::format_docs(documentation.as_str());
74     let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
75     lsp_types::Documentation::MarkupContent(markup_content)
76 }
77
78 pub(crate) fn insert_text_format(
79     insert_text_format: InsertTextFormat,
80 ) -> lsp_types::InsertTextFormat {
81     match insert_text_format {
82         InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
83         InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
84     }
85 }
86
87 pub(crate) fn completion_item_kind(
88     completion_item_kind: CompletionItemKind,
89 ) -> lsp_types::CompletionItemKind {
90     match completion_item_kind {
91         CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
92         CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
93         CompletionItemKind::Module => lsp_types::CompletionItemKind::Module,
94         CompletionItemKind::Function => lsp_types::CompletionItemKind::Function,
95         CompletionItemKind::Struct => lsp_types::CompletionItemKind::Struct,
96         CompletionItemKind::Enum => lsp_types::CompletionItemKind::Enum,
97         CompletionItemKind::EnumVariant => lsp_types::CompletionItemKind::EnumMember,
98         CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
99         CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
100         CompletionItemKind::Field => lsp_types::CompletionItemKind::Field,
101         CompletionItemKind::Trait => lsp_types::CompletionItemKind::Interface,
102         CompletionItemKind::TypeAlias => lsp_types::CompletionItemKind::Struct,
103         CompletionItemKind::Const => lsp_types::CompletionItemKind::Constant,
104         CompletionItemKind::Static => lsp_types::CompletionItemKind::Value,
105         CompletionItemKind::Method => lsp_types::CompletionItemKind::Method,
106         CompletionItemKind::TypeParam => lsp_types::CompletionItemKind::TypeParameter,
107         CompletionItemKind::Macro => lsp_types::CompletionItemKind::Method,
108         CompletionItemKind::Attribute => lsp_types::CompletionItemKind::EnumMember,
109         CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::Reference,
110     }
111 }
112
113 pub(crate) fn text_edit(
114     line_index: &LineIndex,
115     line_endings: LineEndings,
116     indel: Indel,
117 ) -> lsp_types::TextEdit {
118     let range = range(line_index, indel.delete);
119     let new_text = match line_endings {
120         LineEndings::Unix => indel.insert,
121         LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
122     };
123     lsp_types::TextEdit { range, new_text }
124 }
125
126 pub(crate) fn snippet_text_edit(
127     line_index: &LineIndex,
128     line_endings: LineEndings,
129     is_snippet: bool,
130     indel: Indel,
131 ) -> lsp_ext::SnippetTextEdit {
132     let text_edit = text_edit(line_index, line_endings, indel);
133     let insert_text_format =
134         if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
135     lsp_ext::SnippetTextEdit {
136         range: text_edit.range,
137         new_text: text_edit.new_text,
138         insert_text_format,
139     }
140 }
141
142 pub(crate) fn text_edit_vec(
143     line_index: &LineIndex,
144     line_endings: LineEndings,
145     text_edit: TextEdit,
146 ) -> Vec<lsp_types::TextEdit> {
147     text_edit.into_iter().map(|indel| self::text_edit(line_index, line_endings, indel)).collect()
148 }
149
150 pub(crate) fn snippet_text_edit_vec(
151     line_index: &LineIndex,
152     line_endings: LineEndings,
153     is_snippet: bool,
154     text_edit: TextEdit,
155 ) -> Vec<lsp_ext::SnippetTextEdit> {
156     text_edit
157         .into_iter()
158         .map(|indel| self::snippet_text_edit(line_index, line_endings, is_snippet, indel))
159         .collect()
160 }
161
162 pub(crate) fn completion_item(
163     line_index: &LineIndex,
164     line_endings: LineEndings,
165     completion_item: CompletionItem,
166 ) -> Vec<lsp_types::CompletionItem> {
167     fn set_score(res: &mut lsp_types::CompletionItem, label: &str) {
168         res.preselect = Some(true);
169         // HACK: sort preselect items first
170         res.sort_text = Some(format!(" {}", label));
171     }
172
173     let mut additional_text_edits = Vec::new();
174     let mut text_edit = None;
175     // LSP does not allow arbitrary edits in completion, so we have to do a
176     // non-trivial mapping here.
177     let source_range = completion_item.source_range();
178     for indel in completion_item.text_edit().iter() {
179         if indel.delete.contains_range(source_range) {
180             text_edit = Some(if indel.delete == source_range {
181                 self::text_edit(line_index, line_endings, indel.clone())
182             } else {
183                 assert!(source_range.end() == indel.delete.end());
184                 let range1 = TextRange::new(indel.delete.start(), source_range.start());
185                 let range2 = source_range;
186                 let indel1 = Indel::replace(range1, String::new());
187                 let indel2 = Indel::replace(range2, indel.insert.clone());
188                 additional_text_edits.push(self::text_edit(line_index, line_endings, indel1));
189                 self::text_edit(line_index, line_endings, indel2)
190             })
191         } else {
192             assert!(source_range.intersect(indel.delete).is_none());
193             let text_edit = self::text_edit(line_index, line_endings, indel.clone());
194             additional_text_edits.push(text_edit);
195         }
196     }
197     let text_edit = text_edit.unwrap();
198
199     let mut res = lsp_types::CompletionItem {
200         label: completion_item.label().to_string(),
201         detail: completion_item.detail().map(|it| it.to_string()),
202         filter_text: Some(completion_item.lookup().to_string()),
203         kind: completion_item.kind().map(completion_item_kind),
204         text_edit: Some(text_edit.into()),
205         additional_text_edits: Some(additional_text_edits),
206         documentation: completion_item.documentation().map(documentation),
207         deprecated: Some(completion_item.deprecated()),
208         ..Default::default()
209     };
210
211     if completion_item.score().is_some() {
212         set_score(&mut res, completion_item.label());
213     }
214
215     if completion_item.deprecated() {
216         res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
217     }
218
219     if completion_item.trigger_call_info() {
220         res.command = Some(lsp_types::Command {
221             title: "triggerParameterHints".into(),
222             command: "editor.action.triggerParameterHints".into(),
223             arguments: None,
224         });
225     }
226
227     let mut all_results = match completion_item.ref_match() {
228         Some(ref_match) => {
229             let mut refed = res.clone();
230             let (mutability, _score) = ref_match;
231             let label = format!("&{}{}", mutability.as_keyword_for_ref(), refed.label);
232             set_score(&mut refed, &label);
233             refed.label = label;
234             vec![res, refed]
235         }
236         None => vec![res],
237     };
238
239     for mut r in all_results.iter_mut() {
240         r.insert_text_format = Some(insert_text_format(completion_item.insert_text_format()));
241     }
242     all_results
243 }
244
245 pub(crate) fn signature_help(
246     call_info: CallInfo,
247     concise: bool,
248     label_offsets: bool,
249 ) -> lsp_types::SignatureHelp {
250     let (label, parameters) = match (concise, label_offsets) {
251         (_, false) => {
252             let params = call_info
253                 .parameter_labels()
254                 .map(|label| lsp_types::ParameterInformation {
255                     label: lsp_types::ParameterLabel::Simple(label.to_string()),
256                     documentation: None,
257                 })
258                 .collect::<Vec<_>>();
259             let label =
260                 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
261             (label, params)
262         }
263         (false, true) => {
264             let params = call_info
265                 .parameter_ranges()
266                 .iter()
267                 .map(|it| [u32::from(it.start()).into(), u32::from(it.end()).into()])
268                 .map(|label_offsets| lsp_types::ParameterInformation {
269                     label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
270                     documentation: None,
271                 })
272                 .collect::<Vec<_>>();
273             (call_info.signature, params)
274         }
275         (true, true) => {
276             let mut params = Vec::new();
277             let mut label = String::new();
278             let mut first = true;
279             for param in call_info.parameter_labels() {
280                 if !first {
281                     label.push_str(", ");
282                 }
283                 first = false;
284                 let start = label.len() as u32;
285                 label.push_str(param);
286                 let end = label.len() as u32;
287                 params.push(lsp_types::ParameterInformation {
288                     label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
289                     documentation: None,
290                 });
291             }
292
293             (label, params)
294         }
295     };
296
297     let documentation = if concise {
298         None
299     } else {
300         call_info.doc.map(|doc| {
301             lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
302                 kind: lsp_types::MarkupKind::Markdown,
303                 value: doc,
304             })
305         })
306     };
307
308     let active_parameter = call_info.active_parameter.map(|it| it as u32);
309
310     let signature = lsp_types::SignatureInformation {
311         label,
312         documentation,
313         parameters: Some(parameters),
314         active_parameter,
315     };
316     lsp_types::SignatureHelp {
317         signatures: vec![signature],
318         active_signature: None,
319         active_parameter,
320     }
321 }
322
323 pub(crate) fn inlay_hint(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
324     lsp_ext::InlayHint {
325         label: inlay_hint.label.to_string(),
326         range: range(line_index, inlay_hint.range),
327         kind: match inlay_hint.kind {
328             InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
329             InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
330             InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
331         },
332     }
333 }
334
335 static TOKEN_RESULT_COUNTER: AtomicU32 = AtomicU32::new(1);
336
337 pub(crate) fn semantic_tokens(
338     text: &str,
339     line_index: &LineIndex,
340     highlights: Vec<HighlightedRange>,
341 ) -> lsp_types::SemanticTokens {
342     let id = TOKEN_RESULT_COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
343     let mut builder = semantic_tokens::SemanticTokensBuilder::new(id);
344
345     for highlight_range in highlights {
346         let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
347         let token_index = semantic_tokens::type_index(type_);
348         let modifier_bitset = mods.0;
349
350         for mut text_range in line_index.lines(highlight_range.range) {
351             if text[text_range].ends_with('\n') {
352                 text_range =
353                     TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
354             }
355             let range = range(&line_index, text_range);
356             builder.push(range, token_index, modifier_bitset);
357         }
358     }
359
360     builder.build()
361 }
362
363 pub(crate) fn semantic_token_delta(
364     previous: &lsp_types::SemanticTokens,
365     current: &lsp_types::SemanticTokens,
366 ) -> lsp_types::SemanticTokensDelta {
367     let result_id = current.result_id.clone();
368     let edits = semantic_tokens::diff_tokens(&previous.data, &current.data);
369     lsp_types::SemanticTokensDelta { result_id, edits }
370 }
371
372 fn semantic_token_type_and_modifiers(
373     highlight: Highlight,
374 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
375     let mut mods = semantic_tokens::ModifierSet::default();
376     let type_ = match highlight.tag {
377         HighlightTag::Symbol(symbol) => match symbol {
378             SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
379             SymbolKind::Impl => lsp_types::SemanticTokenType::TYPE,
380             SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
381             SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
382             SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
383             SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
384             SymbolKind::Label => semantic_tokens::LABEL,
385             SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
386             SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
387             SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
388             SymbolKind::Function => {
389                 if highlight.modifiers.contains(HighlightModifier::Associated) {
390                     lsp_types::SemanticTokenType::METHOD
391                 } else {
392                     lsp_types::SemanticTokenType::FUNCTION
393                 }
394             }
395             SymbolKind::Const => {
396                 mods |= semantic_tokens::CONSTANT;
397                 mods |= lsp_types::SemanticTokenModifier::STATIC;
398                 lsp_types::SemanticTokenType::VARIABLE
399             }
400             SymbolKind::Static => {
401                 mods |= lsp_types::SemanticTokenModifier::STATIC;
402                 lsp_types::SemanticTokenType::VARIABLE
403             }
404             SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
405             SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
406             SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
407             SymbolKind::Union => semantic_tokens::UNION,
408             SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
409             SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
410             SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
411         },
412         HighlightTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
413         HighlightTag::Dummy => semantic_tokens::GENERIC,
414         HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => {
415             lsp_types::SemanticTokenType::NUMBER
416         }
417         HighlightTag::BoolLiteral => semantic_tokens::BOOLEAN,
418         HighlightTag::CharLiteral | HighlightTag::StringLiteral => {
419             lsp_types::SemanticTokenType::STRING
420         }
421         HighlightTag::Comment => lsp_types::SemanticTokenType::COMMENT,
422         HighlightTag::Attribute => semantic_tokens::ATTRIBUTE,
423         HighlightTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
424         HighlightTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
425         HighlightTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
426         HighlightTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
427         HighlightTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
428         HighlightTag::Punctuation => semantic_tokens::PUNCTUATION,
429     };
430
431     for modifier in highlight.modifiers.iter() {
432         let modifier = match modifier {
433             HighlightModifier::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
434             HighlightModifier::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
435             HighlightModifier::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
436             HighlightModifier::Injected => semantic_tokens::INJECTED,
437             HighlightModifier::ControlFlow => semantic_tokens::CONTROL_FLOW,
438             HighlightModifier::Mutable => semantic_tokens::MUTABLE,
439             HighlightModifier::Consuming => semantic_tokens::CONSUMING,
440             HighlightModifier::Unsafe => semantic_tokens::UNSAFE,
441             HighlightModifier::Callable => semantic_tokens::CALLABLE,
442             HighlightModifier::Static => lsp_types::SemanticTokenModifier::STATIC,
443             HighlightModifier::Associated => continue,
444         };
445         mods |= modifier;
446     }
447
448     (type_, mods)
449 }
450
451 pub(crate) fn folding_range(
452     text: &str,
453     line_index: &LineIndex,
454     line_folding_only: bool,
455     fold: Fold,
456 ) -> lsp_types::FoldingRange {
457     let kind = match fold.kind {
458         FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
459         FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
460         FoldKind::Mods | FoldKind::Block | FoldKind::ArgList => None,
461     };
462
463     let range = range(line_index, fold.range);
464
465     if line_folding_only {
466         // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
467         // even if it contains text not in the folding range. To prevent that we exclude
468         // range.end.line from the folding region if there is more text after range.end
469         // on the same line.
470         let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
471             .chars()
472             .take_while(|it| *it != '\n')
473             .any(|it| !it.is_whitespace());
474
475         let end_line = if has_more_text_on_end_line {
476             range.end.line.saturating_sub(1)
477         } else {
478             range.end.line
479         };
480
481         lsp_types::FoldingRange {
482             start_line: range.start.line,
483             start_character: None,
484             end_line,
485             end_character: None,
486             kind,
487         }
488     } else {
489         lsp_types::FoldingRange {
490             start_line: range.start.line,
491             start_character: Some(range.start.character),
492             end_line: range.end.line,
493             end_character: Some(range.end.character),
494             kind,
495         }
496     }
497 }
498
499 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
500     snap.file_id_to_url(file_id)
501 }
502
503 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
504 /// This will only happen when processing windows paths.
505 ///
506 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
507 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
508     assert!(path.is_absolute());
509     let url = lsp_types::Url::from_file_path(path).unwrap();
510     match path.components().next() {
511         Some(path::Component::Prefix(prefix)) if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
512         {
513             // Need to lowercase driver letter
514         }
515         _ => return url,
516     }
517
518     let driver_letter_range = {
519         let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
520             Some(it) => it,
521             None => return url,
522         };
523         let start = scheme.len() + ':'.len_utf8();
524         start..(start + drive_letter.len())
525     };
526
527     // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
528     // machinery *also* canonicalizes the drive letter. So, just massage the
529     // string in place.
530     let mut url = url.into_string();
531     url[driver_letter_range].make_ascii_lowercase();
532     lsp_types::Url::parse(&url).unwrap()
533 }
534
535 pub(crate) fn optional_versioned_text_document_identifier(
536     snap: &GlobalStateSnapshot,
537     file_id: FileId,
538 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
539     let url = url(snap, file_id);
540     let version = snap.url_file_version(&url);
541     lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
542 }
543
544 pub(crate) fn location(
545     snap: &GlobalStateSnapshot,
546     frange: FileRange,
547 ) -> Result<lsp_types::Location> {
548     let url = url(snap, frange.file_id);
549     let line_index = snap.analysis.file_line_index(frange.file_id)?;
550     let range = range(&line_index, frange.range);
551     let loc = lsp_types::Location::new(url, range);
552     Ok(loc)
553 }
554
555 /// Perefer using `location_link`, if the client has the cap.
556 pub(crate) fn location_from_nav(
557     snap: &GlobalStateSnapshot,
558     nav: NavigationTarget,
559 ) -> Result<lsp_types::Location> {
560     let url = url(snap, nav.file_id);
561     let line_index = snap.analysis.file_line_index(nav.file_id)?;
562     let range = range(&line_index, nav.full_range);
563     let loc = lsp_types::Location::new(url, range);
564     Ok(loc)
565 }
566
567 pub(crate) fn location_link(
568     snap: &GlobalStateSnapshot,
569     src: Option<FileRange>,
570     target: NavigationTarget,
571 ) -> Result<lsp_types::LocationLink> {
572     let origin_selection_range = match src {
573         Some(src) => {
574             let line_index = snap.analysis.file_line_index(src.file_id)?;
575             let range = range(&line_index, src.range);
576             Some(range)
577         }
578         None => None,
579     };
580     let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
581     let res = lsp_types::LocationLink {
582         origin_selection_range,
583         target_uri,
584         target_range,
585         target_selection_range,
586     };
587     Ok(res)
588 }
589
590 fn location_info(
591     snap: &GlobalStateSnapshot,
592     target: NavigationTarget,
593 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
594     let line_index = snap.analysis.file_line_index(target.file_id)?;
595
596     let target_uri = url(snap, target.file_id);
597     let target_range = range(&line_index, target.full_range);
598     let target_selection_range =
599         target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
600     Ok((target_uri, target_range, target_selection_range))
601 }
602
603 pub(crate) fn goto_definition_response(
604     snap: &GlobalStateSnapshot,
605     src: Option<FileRange>,
606     targets: Vec<NavigationTarget>,
607 ) -> Result<lsp_types::GotoDefinitionResponse> {
608     if snap.config.client_caps.location_link {
609         let links = targets
610             .into_iter()
611             .map(|nav| location_link(snap, src, nav))
612             .collect::<Result<Vec<_>>>()?;
613         Ok(links.into())
614     } else {
615         let locations = targets
616             .into_iter()
617             .map(|nav| {
618                 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
619             })
620             .collect::<Result<Vec<_>>>()?;
621         Ok(locations.into())
622     }
623 }
624
625 pub(crate) fn snippet_text_document_edit(
626     snap: &GlobalStateSnapshot,
627     is_snippet: bool,
628     source_file_edit: SourceFileEdit,
629 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
630     let text_document = optional_versioned_text_document_identifier(snap, source_file_edit.file_id);
631     let line_index = snap.analysis.file_line_index(source_file_edit.file_id)?;
632     let line_endings = snap.file_line_endings(source_file_edit.file_id);
633     let edits = source_file_edit
634         .edit
635         .into_iter()
636         .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
637         .collect();
638     Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
639 }
640
641 pub(crate) fn snippet_text_document_ops(
642     snap: &GlobalStateSnapshot,
643     file_system_edit: FileSystemEdit,
644 ) -> Vec<lsp_ext::SnippetDocumentChangeOperation> {
645     let mut ops = Vec::new();
646     match file_system_edit {
647         FileSystemEdit::CreateFile { dst, initial_contents } => {
648             let uri = snap.anchored_path(&dst);
649             let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
650                 uri: uri.clone(),
651                 options: None,
652                 annotation_id: None,
653             });
654             ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
655             if !initial_contents.is_empty() {
656                 let text_document =
657                     lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
658                 let range = range(&LineIndex::new(""), TextRange::empty(TextSize::from(0)));
659                 let text_edit = lsp_ext::SnippetTextEdit {
660                     range,
661                     new_text: initial_contents,
662                     insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
663                 };
664                 let edit_file =
665                     lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
666                 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
667             }
668         }
669         FileSystemEdit::MoveFile { src, dst } => {
670             let old_uri = snap.file_id_to_url(src);
671             let new_uri = snap.anchored_path(&dst);
672             let rename_file = lsp_types::ResourceOp::Rename(lsp_types::RenameFile {
673                 old_uri,
674                 new_uri,
675                 options: None,
676                 annotation_id: None,
677             });
678             ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(rename_file))
679         }
680     }
681     ops
682 }
683
684 pub(crate) fn snippet_workspace_edit(
685     snap: &GlobalStateSnapshot,
686     source_change: SourceChange,
687 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
688     let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
689     for op in source_change.file_system_edits {
690         let ops = snippet_text_document_ops(snap, op);
691         document_changes.extend_from_slice(&ops);
692     }
693     for edit in source_change.source_file_edits {
694         let edit = snippet_text_document_edit(&snap, source_change.is_snippet, edit)?;
695         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
696     }
697     let workspace_edit =
698         lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
699     Ok(workspace_edit)
700 }
701
702 pub(crate) fn workspace_edit(
703     snap: &GlobalStateSnapshot,
704     source_change: SourceChange,
705 ) -> Result<lsp_types::WorkspaceEdit> {
706     assert!(!source_change.is_snippet);
707     snippet_workspace_edit(snap, source_change).map(|it| it.into())
708 }
709
710 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
711     fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
712         lsp_types::WorkspaceEdit {
713             changes: None,
714             document_changes: snippet_workspace_edit.document_changes.map(|changes| {
715                 lsp_types::DocumentChanges::Operations(
716                     changes
717                         .into_iter()
718                         .map(|change| match change {
719                             lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
720                                 lsp_types::DocumentChangeOperation::Op(op)
721                             }
722                             lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
723                                 lsp_types::DocumentChangeOperation::Edit(
724                                     lsp_types::TextDocumentEdit {
725                                         text_document: edit.text_document,
726                                         edits: edit
727                                             .edits
728                                             .into_iter()
729                                             .map(|edit| {
730                                                 lsp_types::OneOf::Left(lsp_types::TextEdit {
731                                                     range: edit.range,
732                                                     new_text: edit.new_text,
733                                                 })
734                                             })
735                                             .collect(),
736                                     },
737                                 )
738                             }
739                         })
740                         .collect(),
741                 )
742             }),
743             change_annotations: None,
744         }
745     }
746 }
747
748 pub(crate) fn call_hierarchy_item(
749     snap: &GlobalStateSnapshot,
750     target: NavigationTarget,
751 ) -> Result<lsp_types::CallHierarchyItem> {
752     let name = target.name.to_string();
753     let detail = target.description.clone();
754     let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
755     let (uri, range, selection_range) = location_info(snap, target)?;
756     Ok(lsp_types::CallHierarchyItem {
757         name,
758         kind,
759         tags: None,
760         detail,
761         uri,
762         range,
763         selection_range,
764         data: None,
765     })
766 }
767
768 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
769     match kind {
770         AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
771         AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
772         AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
773         AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
774         AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
775         AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
776     }
777 }
778
779 pub(crate) fn unresolved_code_action(
780     snap: &GlobalStateSnapshot,
781     code_action_params: lsp_types::CodeActionParams,
782     assist: Assist,
783     index: usize,
784 ) -> Result<lsp_ext::CodeAction> {
785     assert!(assist.source_change.is_none());
786     let res = lsp_ext::CodeAction {
787         title: assist.label.to_string(),
788         group: assist.group.filter(|_| snap.config.client_caps.code_action_group).map(|gr| gr.0),
789         kind: Some(code_action_kind(assist.id.1)),
790         edit: None,
791         is_preferred: None,
792         data: Some(lsp_ext::CodeActionData {
793             id: format!("{}:{}", assist.id.0, index.to_string()),
794             code_action_params,
795         }),
796     };
797     Ok(res)
798 }
799
800 pub(crate) fn resolved_code_action(
801     snap: &GlobalStateSnapshot,
802     assist: Assist,
803 ) -> Result<lsp_ext::CodeAction> {
804     let change = assist.source_change.unwrap();
805     let res = lsp_ext::CodeAction {
806         edit: Some(snippet_workspace_edit(snap, change)?),
807         title: assist.label.to_string(),
808         group: assist.group.filter(|_| snap.config.client_caps.code_action_group).map(|gr| gr.0),
809         kind: Some(code_action_kind(assist.id.1)),
810         is_preferred: None,
811         data: None,
812     };
813     Ok(res)
814 }
815
816 pub(crate) fn runnable(
817     snap: &GlobalStateSnapshot,
818     file_id: FileId,
819     runnable: Runnable,
820 ) -> Result<lsp_ext::Runnable> {
821     let config = &snap.config.runnables;
822     let spec = CargoTargetSpec::for_file(snap, file_id)?;
823     let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
824     let target = spec.as_ref().map(|s| s.target.clone());
825     let (cargo_args, executable_args) =
826         CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
827     let label = runnable.label(target);
828     let location = location_link(snap, None, runnable.nav)?;
829
830     Ok(lsp_ext::Runnable {
831         label,
832         location: Some(location),
833         kind: lsp_ext::RunnableKind::Cargo,
834         args: lsp_ext::CargoRunnable {
835             workspace_root: workspace_root.map(|it| it.into()),
836             override_cargo: config.override_cargo.clone(),
837             cargo_args,
838             cargo_extra_args: config.cargo_extra_args.clone(),
839             executable_args,
840             expect_test: None,
841         },
842     })
843 }
844
845 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
846     let value = crate::markdown::format_docs(markup.as_str());
847     lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
848 }
849
850 #[cfg(test)]
851 mod tests {
852     use ide::Analysis;
853
854     use super::*;
855
856     #[test]
857     fn test_completion_with_ref() {
858         let fixture = r#"
859         struct Foo;
860         fn foo(arg: &Foo) {}
861         fn main() {
862             let arg = Foo;
863             foo(<|>)
864         }"#;
865
866         let (offset, text) = test_utils::extract_offset(fixture);
867         let line_index = LineIndex::new(&text);
868         let (analysis, file_id) = Analysis::from_single_file(text);
869         let completions: Vec<(String, Option<String>)> = analysis
870             .completions(
871                 &ide::CompletionConfig::default(),
872                 ide_db::base_db::FilePosition { file_id, offset },
873             )
874             .unwrap()
875             .unwrap()
876             .into_iter()
877             .filter(|c| c.label().ends_with("arg"))
878             .map(|c| completion_item(&line_index, LineEndings::Unix, c))
879             .flat_map(|comps| comps.into_iter().map(|c| (c.label, c.sort_text)))
880             .collect();
881         expect_test::expect![[r#"
882             [
883                 (
884                     "arg",
885                     None,
886                 ),
887                 (
888                     "&arg",
889                     Some(
890                         " &arg",
891                     ),
892                 ),
893             ]
894         "#]]
895         .assert_debug_eq(&completions);
896     }
897
898     #[test]
899     fn conv_fold_line_folding_only_fixup() {
900         let text = r#"mod a;
901 mod b;
902 mod c;
903
904 fn main() {
905     if cond {
906         a::do_a();
907     } else {
908         b::do_b();
909     }
910 }"#;
911
912         let (analysis, file_id) = Analysis::from_single_file(text.to_string());
913         let folds = analysis.folding_ranges(file_id).unwrap();
914         assert_eq!(folds.len(), 4);
915
916         let line_index = LineIndex::new(&text);
917         let converted: Vec<lsp_types::FoldingRange> =
918             folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
919
920         let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
921         assert_eq!(converted.len(), expected_lines.len());
922         for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
923             assert_eq!(folding_range.start_line, *start_line);
924             assert_eq!(folding_range.start_character, None);
925             assert_eq!(folding_range.end_line, *end_line);
926             assert_eq!(folding_range.end_character, None);
927         }
928     }
929
930     // `Url` is not able to parse windows paths on unix machines.
931     #[test]
932     #[cfg(target_os = "windows")]
933     fn test_lowercase_drive_letter_with_drive() {
934         let url = url_from_abs_path(Path::new("C:\\Test"));
935         assert_eq!(url.to_string(), "file:///c:/Test");
936     }
937
938     #[test]
939     #[cfg(target_os = "windows")]
940     fn test_drive_without_colon_passthrough() {
941         let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
942         assert_eq!(url.to_string(), "file://localhost/C$/my_dir");
943     }
944 }