]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/to_proto.rs
204cae2654f34bc22daa00a3cb67e67ff748d4dd
[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         if highlight_range.highlight.is_empty() {
347             continue;
348         }
349         let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
350         let token_index = semantic_tokens::type_index(type_);
351         let modifier_bitset = mods.0;
352
353         for mut text_range in line_index.lines(highlight_range.range) {
354             if text[text_range].ends_with('\n') {
355                 text_range =
356                     TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
357             }
358             let range = range(&line_index, text_range);
359             builder.push(range, token_index, modifier_bitset);
360         }
361     }
362
363     builder.build()
364 }
365
366 pub(crate) fn semantic_token_delta(
367     previous: &lsp_types::SemanticTokens,
368     current: &lsp_types::SemanticTokens,
369 ) -> lsp_types::SemanticTokensDelta {
370     let result_id = current.result_id.clone();
371     let edits = semantic_tokens::diff_tokens(&previous.data, &current.data);
372     lsp_types::SemanticTokensDelta { result_id, edits }
373 }
374
375 fn semantic_token_type_and_modifiers(
376     highlight: Highlight,
377 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
378     let mut mods = semantic_tokens::ModifierSet::default();
379     let type_ = match highlight.tag {
380         HighlightTag::Symbol(symbol) => match symbol {
381             SymbolKind::Module => lsp_types::SemanticTokenType::NAMESPACE,
382             SymbolKind::Impl => lsp_types::SemanticTokenType::TYPE,
383             SymbolKind::Field => lsp_types::SemanticTokenType::PROPERTY,
384             SymbolKind::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
385             SymbolKind::ConstParam => semantic_tokens::CONST_PARAMETER,
386             SymbolKind::LifetimeParam => semantic_tokens::LIFETIME,
387             SymbolKind::Label => semantic_tokens::LABEL,
388             SymbolKind::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
389             SymbolKind::SelfParam => semantic_tokens::SELF_KEYWORD,
390             SymbolKind::Local => lsp_types::SemanticTokenType::VARIABLE,
391             SymbolKind::Function => {
392                 if highlight.modifiers.contains(HighlightModifier::Associated) {
393                     lsp_types::SemanticTokenType::METHOD
394                 } else {
395                     lsp_types::SemanticTokenType::FUNCTION
396                 }
397             }
398             SymbolKind::Const => {
399                 mods |= semantic_tokens::CONSTANT;
400                 mods |= lsp_types::SemanticTokenModifier::STATIC;
401                 lsp_types::SemanticTokenType::VARIABLE
402             }
403             SymbolKind::Static => {
404                 mods |= lsp_types::SemanticTokenModifier::STATIC;
405                 lsp_types::SemanticTokenType::VARIABLE
406             }
407             SymbolKind::Struct => lsp_types::SemanticTokenType::STRUCT,
408             SymbolKind::Enum => lsp_types::SemanticTokenType::ENUM,
409             SymbolKind::Variant => lsp_types::SemanticTokenType::ENUM_MEMBER,
410             SymbolKind::Union => semantic_tokens::UNION,
411             SymbolKind::TypeAlias => semantic_tokens::TYPE_ALIAS,
412             SymbolKind::Trait => lsp_types::SemanticTokenType::INTERFACE,
413             SymbolKind::Macro => lsp_types::SemanticTokenType::MACRO,
414         },
415         HighlightTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
416         HighlightTag::Dummy => semantic_tokens::GENERIC,
417         HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => {
418             lsp_types::SemanticTokenType::NUMBER
419         }
420         HighlightTag::BoolLiteral => semantic_tokens::BOOLEAN,
421         HighlightTag::CharLiteral | HighlightTag::StringLiteral => {
422             lsp_types::SemanticTokenType::STRING
423         }
424         HighlightTag::Comment => lsp_types::SemanticTokenType::COMMENT,
425         HighlightTag::Attribute => semantic_tokens::ATTRIBUTE,
426         HighlightTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
427         HighlightTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
428         HighlightTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
429         HighlightTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
430         HighlightTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
431         HighlightTag::Punctuation => semantic_tokens::PUNCTUATION,
432     };
433
434     for modifier in highlight.modifiers.iter() {
435         let modifier = match modifier {
436             HighlightModifier::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
437             HighlightModifier::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
438             HighlightModifier::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
439             HighlightModifier::Injected => semantic_tokens::INJECTED,
440             HighlightModifier::ControlFlow => semantic_tokens::CONTROL_FLOW,
441             HighlightModifier::Mutable => semantic_tokens::MUTABLE,
442             HighlightModifier::Consuming => semantic_tokens::CONSUMING,
443             HighlightModifier::Unsafe => semantic_tokens::UNSAFE,
444             HighlightModifier::Callable => semantic_tokens::CALLABLE,
445             HighlightModifier::Static => lsp_types::SemanticTokenModifier::STATIC,
446             HighlightModifier::Associated => continue,
447         };
448         mods |= modifier;
449     }
450
451     (type_, mods)
452 }
453
454 pub(crate) fn folding_range(
455     text: &str,
456     line_index: &LineIndex,
457     line_folding_only: bool,
458     fold: Fold,
459 ) -> lsp_types::FoldingRange {
460     let kind = match fold.kind {
461         FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
462         FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
463         FoldKind::Mods | FoldKind::Block | FoldKind::ArgList => None,
464     };
465
466     let range = range(line_index, fold.range);
467
468     if line_folding_only {
469         // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
470         // even if it contains text not in the folding range. To prevent that we exclude
471         // range.end.line from the folding region if there is more text after range.end
472         // on the same line.
473         let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
474             .chars()
475             .take_while(|it| *it != '\n')
476             .any(|it| !it.is_whitespace());
477
478         let end_line = if has_more_text_on_end_line {
479             range.end.line.saturating_sub(1)
480         } else {
481             range.end.line
482         };
483
484         lsp_types::FoldingRange {
485             start_line: range.start.line,
486             start_character: None,
487             end_line,
488             end_character: None,
489             kind,
490         }
491     } else {
492         lsp_types::FoldingRange {
493             start_line: range.start.line,
494             start_character: Some(range.start.character),
495             end_line: range.end.line,
496             end_character: Some(range.end.character),
497             kind,
498         }
499     }
500 }
501
502 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
503     snap.file_id_to_url(file_id)
504 }
505
506 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
507 /// This will only happen when processing windows paths.
508 ///
509 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
510 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
511     assert!(path.is_absolute());
512     let url = lsp_types::Url::from_file_path(path).unwrap();
513     match path.components().next() {
514         Some(path::Component::Prefix(prefix)) if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
515         {
516             // Need to lowercase driver letter
517         }
518         _ => return url,
519     }
520
521     let driver_letter_range = {
522         let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
523             Some(it) => it,
524             None => return url,
525         };
526         let start = scheme.len() + ':'.len_utf8();
527         start..(start + drive_letter.len())
528     };
529
530     // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
531     // machinery *also* canonicalizes the drive letter. So, just massage the
532     // string in place.
533     let mut url = url.into_string();
534     url[driver_letter_range].make_ascii_lowercase();
535     lsp_types::Url::parse(&url).unwrap()
536 }
537
538 pub(crate) fn optional_versioned_text_document_identifier(
539     snap: &GlobalStateSnapshot,
540     file_id: FileId,
541 ) -> lsp_types::OptionalVersionedTextDocumentIdentifier {
542     let url = url(snap, file_id);
543     let version = snap.url_file_version(&url);
544     lsp_types::OptionalVersionedTextDocumentIdentifier { uri: url, version }
545 }
546
547 pub(crate) fn location(
548     snap: &GlobalStateSnapshot,
549     frange: FileRange,
550 ) -> Result<lsp_types::Location> {
551     let url = url(snap, frange.file_id);
552     let line_index = snap.analysis.file_line_index(frange.file_id)?;
553     let range = range(&line_index, frange.range);
554     let loc = lsp_types::Location::new(url, range);
555     Ok(loc)
556 }
557
558 /// Perefer using `location_link`, if the client has the cap.
559 pub(crate) fn location_from_nav(
560     snap: &GlobalStateSnapshot,
561     nav: NavigationTarget,
562 ) -> Result<lsp_types::Location> {
563     let url = url(snap, nav.file_id);
564     let line_index = snap.analysis.file_line_index(nav.file_id)?;
565     let range = range(&line_index, nav.full_range);
566     let loc = lsp_types::Location::new(url, range);
567     Ok(loc)
568 }
569
570 pub(crate) fn location_link(
571     snap: &GlobalStateSnapshot,
572     src: Option<FileRange>,
573     target: NavigationTarget,
574 ) -> Result<lsp_types::LocationLink> {
575     let origin_selection_range = match src {
576         Some(src) => {
577             let line_index = snap.analysis.file_line_index(src.file_id)?;
578             let range = range(&line_index, src.range);
579             Some(range)
580         }
581         None => None,
582     };
583     let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
584     let res = lsp_types::LocationLink {
585         origin_selection_range,
586         target_uri,
587         target_range,
588         target_selection_range,
589     };
590     Ok(res)
591 }
592
593 fn location_info(
594     snap: &GlobalStateSnapshot,
595     target: NavigationTarget,
596 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
597     let line_index = snap.analysis.file_line_index(target.file_id)?;
598
599     let target_uri = url(snap, target.file_id);
600     let target_range = range(&line_index, target.full_range);
601     let target_selection_range =
602         target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
603     Ok((target_uri, target_range, target_selection_range))
604 }
605
606 pub(crate) fn goto_definition_response(
607     snap: &GlobalStateSnapshot,
608     src: Option<FileRange>,
609     targets: Vec<NavigationTarget>,
610 ) -> Result<lsp_types::GotoDefinitionResponse> {
611     if snap.config.location_link() {
612         let links = targets
613             .into_iter()
614             .map(|nav| location_link(snap, src, nav))
615             .collect::<Result<Vec<_>>>()?;
616         Ok(links.into())
617     } else {
618         let locations = targets
619             .into_iter()
620             .map(|nav| {
621                 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
622             })
623             .collect::<Result<Vec<_>>>()?;
624         Ok(locations.into())
625     }
626 }
627
628 pub(crate) fn snippet_text_document_edit(
629     snap: &GlobalStateSnapshot,
630     is_snippet: bool,
631     source_file_edit: SourceFileEdit,
632 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
633     let text_document = optional_versioned_text_document_identifier(snap, source_file_edit.file_id);
634     let line_index = snap.analysis.file_line_index(source_file_edit.file_id)?;
635     let line_endings = snap.file_line_endings(source_file_edit.file_id);
636     let edits = source_file_edit
637         .edit
638         .into_iter()
639         .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
640         .collect();
641     Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
642 }
643
644 pub(crate) fn snippet_text_document_ops(
645     snap: &GlobalStateSnapshot,
646     file_system_edit: FileSystemEdit,
647 ) -> Vec<lsp_ext::SnippetDocumentChangeOperation> {
648     let mut ops = Vec::new();
649     match file_system_edit {
650         FileSystemEdit::CreateFile { dst, initial_contents } => {
651             let uri = snap.anchored_path(&dst);
652             let create_file = lsp_types::ResourceOp::Create(lsp_types::CreateFile {
653                 uri: uri.clone(),
654                 options: None,
655                 annotation_id: None,
656             });
657             ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(create_file));
658             if !initial_contents.is_empty() {
659                 let text_document =
660                     lsp_types::OptionalVersionedTextDocumentIdentifier { uri, version: None };
661                 let range = range(&LineIndex::new(""), TextRange::empty(TextSize::from(0)));
662                 let text_edit = lsp_ext::SnippetTextEdit {
663                     range,
664                     new_text: initial_contents,
665                     insert_text_format: Some(lsp_types::InsertTextFormat::PlainText),
666                 };
667                 let edit_file =
668                     lsp_ext::SnippetTextDocumentEdit { text_document, edits: vec![text_edit] };
669                 ops.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit_file));
670             }
671         }
672         FileSystemEdit::MoveFile { src, dst } => {
673             let old_uri = snap.file_id_to_url(src);
674             let new_uri = snap.anchored_path(&dst);
675             let rename_file = lsp_types::ResourceOp::Rename(lsp_types::RenameFile {
676                 old_uri,
677                 new_uri,
678                 options: None,
679                 annotation_id: None,
680             });
681             ops.push(lsp_ext::SnippetDocumentChangeOperation::Op(rename_file))
682         }
683     }
684     ops
685 }
686
687 pub(crate) fn snippet_workspace_edit(
688     snap: &GlobalStateSnapshot,
689     source_change: SourceChange,
690 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
691     let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
692     for op in source_change.file_system_edits {
693         let ops = snippet_text_document_ops(snap, op);
694         document_changes.extend_from_slice(&ops);
695     }
696     for edit in source_change.source_file_edits {
697         let edit = snippet_text_document_edit(&snap, source_change.is_snippet, edit)?;
698         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
699     }
700     let workspace_edit =
701         lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
702     Ok(workspace_edit)
703 }
704
705 pub(crate) fn workspace_edit(
706     snap: &GlobalStateSnapshot,
707     source_change: SourceChange,
708 ) -> Result<lsp_types::WorkspaceEdit> {
709     assert!(!source_change.is_snippet);
710     snippet_workspace_edit(snap, source_change).map(|it| it.into())
711 }
712
713 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
714     fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
715         lsp_types::WorkspaceEdit {
716             changes: None,
717             document_changes: snippet_workspace_edit.document_changes.map(|changes| {
718                 lsp_types::DocumentChanges::Operations(
719                     changes
720                         .into_iter()
721                         .map(|change| match change {
722                             lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
723                                 lsp_types::DocumentChangeOperation::Op(op)
724                             }
725                             lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
726                                 lsp_types::DocumentChangeOperation::Edit(
727                                     lsp_types::TextDocumentEdit {
728                                         text_document: edit.text_document,
729                                         edits: edit
730                                             .edits
731                                             .into_iter()
732                                             .map(|edit| {
733                                                 lsp_types::OneOf::Left(lsp_types::TextEdit {
734                                                     range: edit.range,
735                                                     new_text: edit.new_text,
736                                                 })
737                                             })
738                                             .collect(),
739                                     },
740                                 )
741                             }
742                         })
743                         .collect(),
744                 )
745             }),
746             change_annotations: None,
747         }
748     }
749 }
750
751 pub(crate) fn call_hierarchy_item(
752     snap: &GlobalStateSnapshot,
753     target: NavigationTarget,
754 ) -> Result<lsp_types::CallHierarchyItem> {
755     let name = target.name.to_string();
756     let detail = target.description.clone();
757     let kind = target.kind.map(symbol_kind).unwrap_or(lsp_types::SymbolKind::Function);
758     let (uri, range, selection_range) = location_info(snap, target)?;
759     Ok(lsp_types::CallHierarchyItem {
760         name,
761         kind,
762         tags: None,
763         detail,
764         uri,
765         range,
766         selection_range,
767         data: None,
768     })
769 }
770
771 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
772     match kind {
773         AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
774         AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
775         AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
776         AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
777         AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
778         AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
779     }
780 }
781
782 pub(crate) fn unresolved_code_action(
783     snap: &GlobalStateSnapshot,
784     code_action_params: lsp_types::CodeActionParams,
785     assist: Assist,
786     index: usize,
787 ) -> Result<lsp_ext::CodeAction> {
788     assert!(assist.source_change.is_none());
789     let res = lsp_ext::CodeAction {
790         title: assist.label.to_string(),
791         group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
792         kind: Some(code_action_kind(assist.id.1)),
793         edit: None,
794         is_preferred: None,
795         data: Some(lsp_ext::CodeActionData {
796             id: format!("{}:{}", assist.id.0, index.to_string()),
797             code_action_params,
798         }),
799     };
800     Ok(res)
801 }
802
803 pub(crate) fn resolved_code_action(
804     snap: &GlobalStateSnapshot,
805     assist: Assist,
806 ) -> Result<lsp_ext::CodeAction> {
807     let change = assist.source_change.unwrap();
808     let res = lsp_ext::CodeAction {
809         edit: Some(snippet_workspace_edit(snap, change)?),
810         title: assist.label.to_string(),
811         group: assist.group.filter(|_| snap.config.code_action_group()).map(|gr| gr.0),
812         kind: Some(code_action_kind(assist.id.1)),
813         is_preferred: None,
814         data: None,
815     };
816     Ok(res)
817 }
818
819 pub(crate) fn runnable(
820     snap: &GlobalStateSnapshot,
821     file_id: FileId,
822     runnable: Runnable,
823 ) -> Result<lsp_ext::Runnable> {
824     let config = snap.config.runnables();
825     let spec = CargoTargetSpec::for_file(snap, file_id)?;
826     let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
827     let target = spec.as_ref().map(|s| s.target.clone());
828     let (cargo_args, executable_args) =
829         CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?;
830     let label = runnable.label(target);
831     let location = location_link(snap, None, runnable.nav)?;
832
833     Ok(lsp_ext::Runnable {
834         label,
835         location: Some(location),
836         kind: lsp_ext::RunnableKind::Cargo,
837         args: lsp_ext::CargoRunnable {
838             workspace_root: workspace_root.map(|it| it.into()),
839             override_cargo: config.override_cargo,
840             cargo_args,
841             cargo_extra_args: config.cargo_extra_args,
842             executable_args,
843             expect_test: None,
844         },
845     })
846 }
847
848 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
849     let value = crate::markdown::format_docs(markup.as_str());
850     lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
851 }
852
853 #[cfg(test)]
854 mod tests {
855     use ide::Analysis;
856     use ide_db::helpers::SnippetCap;
857
858     use super::*;
859
860     #[test]
861     fn test_completion_with_ref() {
862         let fixture = r#"
863         struct Foo;
864         fn foo(arg: &Foo) {}
865         fn main() {
866             let arg = Foo;
867             foo($0)
868         }"#;
869
870         let (offset, text) = test_utils::extract_offset(fixture);
871         let line_index = LineIndex::new(&text);
872         let (analysis, file_id) = Analysis::from_single_file(text);
873         let completions: Vec<(String, Option<String>)> = analysis
874             .completions(
875                 &ide::CompletionConfig {
876                     enable_postfix_completions: true,
877                     enable_autoimport_completions: true,
878                     add_call_parenthesis: true,
879                     add_call_argument_snippets: true,
880                     snippet_cap: SnippetCap::new(true),
881                     merge: None,
882                 },
883                 ide_db::base_db::FilePosition { file_id, offset },
884             )
885             .unwrap()
886             .unwrap()
887             .into_iter()
888             .filter(|c| c.label().ends_with("arg"))
889             .map(|c| completion_item(&line_index, LineEndings::Unix, c))
890             .flat_map(|comps| comps.into_iter().map(|c| (c.label, c.sort_text)))
891             .collect();
892         expect_test::expect![[r#"
893             [
894                 (
895                     "arg",
896                     None,
897                 ),
898                 (
899                     "&arg",
900                     Some(
901                         " &arg",
902                     ),
903                 ),
904             ]
905         "#]]
906         .assert_debug_eq(&completions);
907     }
908
909     #[test]
910     fn conv_fold_line_folding_only_fixup() {
911         let text = r#"mod a;
912 mod b;
913 mod c;
914
915 fn main() {
916     if cond {
917         a::do_a();
918     } else {
919         b::do_b();
920     }
921 }"#;
922
923         let (analysis, file_id) = Analysis::from_single_file(text.to_string());
924         let folds = analysis.folding_ranges(file_id).unwrap();
925         assert_eq!(folds.len(), 4);
926
927         let line_index = LineIndex::new(&text);
928         let converted: Vec<lsp_types::FoldingRange> =
929             folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
930
931         let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
932         assert_eq!(converted.len(), expected_lines.len());
933         for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
934             assert_eq!(folding_range.start_line, *start_line);
935             assert_eq!(folding_range.start_character, None);
936             assert_eq!(folding_range.end_line, *end_line);
937             assert_eq!(folding_range.end_character, None);
938         }
939     }
940
941     // `Url` is not able to parse windows paths on unix machines.
942     #[test]
943     #[cfg(target_os = "windows")]
944     fn test_lowercase_drive_letter_with_drive() {
945         let url = url_from_abs_path(Path::new("C:\\Test"));
946         assert_eq!(url.to_string(), "file:///c:/Test");
947     }
948
949     #[test]
950     #[cfg(target_os = "windows")]
951     fn test_drive_without_colon_passthrough() {
952         let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
953         assert_eq!(url.to_string(), "file://localhost/C$/my_dir");
954     }
955 }