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