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