]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/to_proto.rs
Merge #4928
[rust.git] / crates / rust-analyzer / src / to_proto.rs
1 //! Conversion of rust-analyzer specific types to lsp_types equivalents.
2 use std::path::{self, Path};
3
4 use itertools::Itertools;
5 use ra_db::{FileId, FileRange};
6 use ra_ide::{
7     Assist, CompletionItem, CompletionItemKind, Documentation, FileSystemEdit, Fold, FoldKind,
8     FunctionSignature, Highlight, HighlightModifier, HighlightTag, HighlightedRange, Indel,
9     InlayHint, InlayKind, InsertTextFormat, LineIndex, NavigationTarget, ReferenceAccess,
10     ResolvedAssist, Runnable, Severity, SourceChange, SourceFileEdit, TextEdit,
11 };
12 use ra_syntax::{SyntaxKind, TextRange, TextSize};
13 use ra_vfs::LineEndings;
14
15 use crate::{
16     cargo_target_spec::CargoTargetSpec, global_state::GlobalStateSnapshot, lsp_ext,
17     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     let line = u64::from(line_col.line);
23     let character = u64::from(line_col.col_utf16);
24     lsp_types::Position::new(line, character)
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_DEF => lsp_types::SymbolKind::Function,
36         SyntaxKind::STRUCT_DEF => lsp_types::SymbolKind::Struct,
37         SyntaxKind::ENUM_DEF => lsp_types::SymbolKind::Enum,
38         SyntaxKind::ENUM_VARIANT => lsp_types::SymbolKind::EnumMember,
39         SyntaxKind::TRAIT_DEF => lsp_types::SymbolKind::Interface,
40         SyntaxKind::MACRO_CALL => lsp_types::SymbolKind::Function,
41         SyntaxKind::MODULE => lsp_types::SymbolKind::Module,
42         SyntaxKind::TYPE_ALIAS_DEF => lsp_types::SymbolKind::TypeParameter,
43         SyntaxKind::RECORD_FIELD_DEF => lsp_types::SymbolKind::Field,
44         SyntaxKind::STATIC_DEF => lsp_types::SymbolKind::Constant,
45         SyntaxKind::CONST_DEF => lsp_types::SymbolKind::Constant,
46         SyntaxKind::IMPL_DEF => 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     }
105 }
106
107 pub(crate) fn text_edit(
108     line_index: &LineIndex,
109     line_endings: LineEndings,
110     indel: Indel,
111 ) -> lsp_types::TextEdit {
112     let range = range(line_index, indel.delete);
113     let new_text = match line_endings {
114         LineEndings::Unix => indel.insert,
115         LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
116     };
117     lsp_types::TextEdit { range, new_text }
118 }
119
120 pub(crate) fn snippet_text_edit(
121     line_index: &LineIndex,
122     line_endings: LineEndings,
123     is_snippet: bool,
124     indel: Indel,
125 ) -> lsp_ext::SnippetTextEdit {
126     let text_edit = text_edit(line_index, line_endings, indel);
127     let insert_text_format =
128         if is_snippet { Some(lsp_types::InsertTextFormat::Snippet) } else { None };
129     lsp_ext::SnippetTextEdit {
130         range: text_edit.range,
131         new_text: text_edit.new_text,
132         insert_text_format,
133     }
134 }
135
136 pub(crate) fn text_edit_vec(
137     line_index: &LineIndex,
138     line_endings: LineEndings,
139     text_edit: TextEdit,
140 ) -> Vec<lsp_types::TextEdit> {
141     text_edit.into_iter().map(|indel| self::text_edit(line_index, line_endings, indel)).collect()
142 }
143
144 pub(crate) fn snippet_text_edit_vec(
145     line_index: &LineIndex,
146     line_endings: LineEndings,
147     is_snippet: bool,
148     text_edit: TextEdit,
149 ) -> Vec<lsp_ext::SnippetTextEdit> {
150     text_edit
151         .into_iter()
152         .map(|indel| self::snippet_text_edit(line_index, line_endings, is_snippet, indel))
153         .collect()
154 }
155
156 pub(crate) fn completion_item(
157     line_index: &LineIndex,
158     line_endings: LineEndings,
159     completion_item: CompletionItem,
160 ) -> lsp_types::CompletionItem {
161     let mut additional_text_edits = Vec::new();
162     let mut text_edit = None;
163     // LSP does not allow arbitrary edits in completion, so we have to do a
164     // non-trivial mapping here.
165     let source_range = completion_item.source_range();
166     for indel in completion_item.text_edit().iter() {
167         if indel.delete.contains_range(source_range) {
168             text_edit = Some(if indel.delete == source_range {
169                 self::text_edit(line_index, line_endings, indel.clone())
170             } else {
171                 assert!(source_range.end() == indel.delete.end());
172                 let range1 = TextRange::new(indel.delete.start(), source_range.start());
173                 let range2 = source_range;
174                 let indel1 = Indel::replace(range1, String::new());
175                 let indel2 = Indel::replace(range2, indel.insert.clone());
176                 additional_text_edits.push(self::text_edit(line_index, line_endings, indel1));
177                 self::text_edit(line_index, line_endings, indel2)
178             })
179         } else {
180             assert!(source_range.intersect(indel.delete).is_none());
181             let text_edit = self::text_edit(line_index, line_endings, indel.clone());
182             additional_text_edits.push(text_edit);
183         }
184     }
185     let text_edit = text_edit.unwrap();
186
187     let mut res = lsp_types::CompletionItem {
188         label: completion_item.label().to_string(),
189         detail: completion_item.detail().map(|it| it.to_string()),
190         filter_text: Some(completion_item.lookup().to_string()),
191         kind: completion_item.kind().map(completion_item_kind),
192         text_edit: Some(text_edit.into()),
193         additional_text_edits: Some(additional_text_edits),
194         documentation: completion_item.documentation().map(documentation),
195         deprecated: Some(completion_item.deprecated()),
196         ..Default::default()
197     };
198
199     if completion_item.score().is_some() {
200         res.preselect = Some(true);
201         // HACK: sort preselect items first
202         res.sort_text = Some(format!(" {}", completion_item.label()));
203     }
204
205     if completion_item.deprecated() {
206         res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
207     }
208
209     if completion_item.trigger_call_info() {
210         res.command = Some(lsp_types::Command {
211             title: "triggerParameterHints".into(),
212             command: "editor.action.triggerParameterHints".into(),
213             arguments: None,
214         });
215     }
216
217     res.insert_text_format = Some(insert_text_format(completion_item.insert_text_format()));
218
219     res
220 }
221
222 pub(crate) fn signature_information(
223     signature: FunctionSignature,
224     concise: bool,
225 ) -> lsp_types::SignatureInformation {
226     let (label, documentation, params) = if concise {
227         let mut params = signature.parameters;
228         if signature.has_self_param {
229             params.remove(0);
230         }
231         (params.join(", "), None, params)
232     } else {
233         (signature.to_string(), signature.doc.map(documentation), signature.parameters)
234     };
235
236     let parameters: Vec<lsp_types::ParameterInformation> = params
237         .into_iter()
238         .map(|param| lsp_types::ParameterInformation {
239             label: lsp_types::ParameterLabel::Simple(param),
240             documentation: None,
241         })
242         .collect();
243
244     lsp_types::SignatureInformation { label, documentation, parameters: Some(parameters) }
245 }
246
247 pub(crate) fn inlay_int(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
248     lsp_ext::InlayHint {
249         label: inlay_hint.label.to_string(),
250         range: range(line_index, inlay_hint.range),
251         kind: match inlay_hint.kind {
252             InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
253             InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
254             InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
255         },
256     }
257 }
258
259 pub(crate) fn semantic_tokens(
260     text: &str,
261     line_index: &LineIndex,
262     highlights: Vec<HighlightedRange>,
263 ) -> lsp_types::SemanticTokens {
264     let mut builder = semantic_tokens::SemanticTokensBuilder::default();
265
266     for highlight_range in highlights {
267         let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
268         let token_index = semantic_tokens::type_index(type_);
269         let modifier_bitset = mods.0;
270
271         for mut text_range in line_index.lines(highlight_range.range) {
272             if text[text_range].ends_with('\n') {
273                 text_range =
274                     TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
275             }
276             let range = range(&line_index, text_range);
277             builder.push(range, token_index, modifier_bitset);
278         }
279     }
280
281     builder.build()
282 }
283
284 fn semantic_token_type_and_modifiers(
285     highlight: Highlight,
286 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
287     let mut mods = semantic_tokens::ModifierSet::default();
288     let type_ = match highlight.tag {
289         HighlightTag::Struct => lsp_types::SemanticTokenType::STRUCT,
290         HighlightTag::Enum => lsp_types::SemanticTokenType::ENUM,
291         HighlightTag::Union => semantic_tokens::UNION,
292         HighlightTag::TypeAlias => semantic_tokens::TYPE_ALIAS,
293         HighlightTag::Trait => lsp_types::SemanticTokenType::INTERFACE,
294         HighlightTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
295         HighlightTag::SelfKeyword => semantic_tokens::SELF_KEYWORD,
296         HighlightTag::SelfType => lsp_types::SemanticTokenType::TYPE,
297         HighlightTag::Field => lsp_types::SemanticTokenType::PROPERTY,
298         HighlightTag::Function => lsp_types::SemanticTokenType::FUNCTION,
299         HighlightTag::Module => lsp_types::SemanticTokenType::NAMESPACE,
300         HighlightTag::Constant => {
301             mods |= semantic_tokens::CONSTANT;
302             mods |= lsp_types::SemanticTokenModifier::STATIC;
303             lsp_types::SemanticTokenType::VARIABLE
304         }
305         HighlightTag::Static => {
306             mods |= lsp_types::SemanticTokenModifier::STATIC;
307             lsp_types::SemanticTokenType::VARIABLE
308         }
309         HighlightTag::EnumVariant => semantic_tokens::ENUM_MEMBER,
310         HighlightTag::Macro => lsp_types::SemanticTokenType::MACRO,
311         HighlightTag::Local => lsp_types::SemanticTokenType::VARIABLE,
312         HighlightTag::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
313         HighlightTag::Lifetime => semantic_tokens::LIFETIME,
314         HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => {
315             lsp_types::SemanticTokenType::NUMBER
316         }
317         HighlightTag::BoolLiteral => semantic_tokens::BOOLEAN,
318         HighlightTag::CharLiteral | HighlightTag::StringLiteral => {
319             lsp_types::SemanticTokenType::STRING
320         }
321         HighlightTag::Comment => lsp_types::SemanticTokenType::COMMENT,
322         HighlightTag::Attribute => semantic_tokens::ATTRIBUTE,
323         HighlightTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
324         HighlightTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
325         HighlightTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
326         HighlightTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
327         HighlightTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
328     };
329
330     for modifier in highlight.modifiers.iter() {
331         let modifier = match modifier {
332             HighlightModifier::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
333             HighlightModifier::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
334             HighlightModifier::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
335             HighlightModifier::ControlFlow => semantic_tokens::CONTROL_FLOW,
336             HighlightModifier::Mutable => semantic_tokens::MUTABLE,
337             HighlightModifier::Unsafe => semantic_tokens::UNSAFE,
338         };
339         mods |= modifier;
340     }
341
342     (type_, mods)
343 }
344
345 pub(crate) fn folding_range(
346     text: &str,
347     line_index: &LineIndex,
348     line_folding_only: bool,
349     fold: Fold,
350 ) -> lsp_types::FoldingRange {
351     let kind = match fold.kind {
352         FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
353         FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
354         FoldKind::Mods | FoldKind::Block => None,
355     };
356
357     let range = range(line_index, fold.range);
358
359     if line_folding_only {
360         // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
361         // even if it contains text not in the folding range. To prevent that we exclude
362         // range.end.line from the folding region if there is more text after range.end
363         // on the same line.
364         let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
365             .chars()
366             .take_while(|it| *it != '\n')
367             .any(|it| !it.is_whitespace());
368
369         let end_line = if has_more_text_on_end_line {
370             range.end.line.saturating_sub(1)
371         } else {
372             range.end.line
373         };
374
375         lsp_types::FoldingRange {
376             start_line: range.start.line,
377             start_character: None,
378             end_line,
379             end_character: None,
380             kind,
381         }
382     } else {
383         lsp_types::FoldingRange {
384             start_line: range.start.line,
385             start_character: Some(range.start.character),
386             end_line: range.end.line,
387             end_character: Some(range.end.character),
388             kind,
389         }
390     }
391 }
392
393 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
394     snap.file_id_to_url(file_id)
395 }
396
397 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
398 /// This will only happen when processing windows paths.
399 ///
400 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
401 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
402     assert!(path.is_absolute());
403     let url = lsp_types::Url::from_file_path(path).unwrap();
404     match path.components().next() {
405         Some(path::Component::Prefix(prefix)) if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
406         {
407             // Need to lowercase driver letter
408         }
409         _ => return url,
410     }
411
412     let driver_letter_range = {
413         let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
414             Some(it) => it,
415             None => return url,
416         };
417         let start = scheme.len() + ':'.len_utf8();
418         start..(start + drive_letter.len())
419     };
420
421     // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
422     // machinery *also* canonicalizes the drive letter. So, just massage the
423     // string in place.
424     let mut url = url.into_string();
425     url[driver_letter_range].make_ascii_lowercase();
426     lsp_types::Url::parse(&url).unwrap()
427 }
428
429 pub(crate) fn versioned_text_document_identifier(
430     snap: &GlobalStateSnapshot,
431     file_id: FileId,
432     version: Option<i64>,
433 ) -> lsp_types::VersionedTextDocumentIdentifier {
434     lsp_types::VersionedTextDocumentIdentifier { uri: url(snap, file_id), version }
435 }
436
437 pub(crate) fn location(
438     snap: &GlobalStateSnapshot,
439     frange: FileRange,
440 ) -> Result<lsp_types::Location> {
441     let url = url(snap, frange.file_id);
442     let line_index = snap.analysis().file_line_index(frange.file_id)?;
443     let range = range(&line_index, frange.range);
444     let loc = lsp_types::Location::new(url, range);
445     Ok(loc)
446 }
447
448 pub(crate) fn location_link(
449     snap: &GlobalStateSnapshot,
450     src: Option<FileRange>,
451     target: NavigationTarget,
452 ) -> Result<lsp_types::LocationLink> {
453     let origin_selection_range = match src {
454         Some(src) => {
455             let line_index = snap.analysis().file_line_index(src.file_id)?;
456             let range = range(&line_index, src.range);
457             Some(range)
458         }
459         None => None,
460     };
461     let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
462     let res = lsp_types::LocationLink {
463         origin_selection_range,
464         target_uri,
465         target_range,
466         target_selection_range,
467     };
468     Ok(res)
469 }
470
471 fn location_info(
472     snap: &GlobalStateSnapshot,
473     target: NavigationTarget,
474 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
475     let line_index = snap.analysis().file_line_index(target.file_id())?;
476
477     let target_uri = url(snap, target.file_id());
478     let target_range = range(&line_index, target.full_range());
479     let target_selection_range =
480         target.focus_range().map(|it| range(&line_index, it)).unwrap_or(target_range);
481     Ok((target_uri, target_range, target_selection_range))
482 }
483
484 pub(crate) fn goto_definition_response(
485     snap: &GlobalStateSnapshot,
486     src: Option<FileRange>,
487     targets: Vec<NavigationTarget>,
488 ) -> Result<lsp_types::GotoDefinitionResponse> {
489     if snap.config.client_caps.location_link {
490         let links = targets
491             .into_iter()
492             .map(|nav| location_link(snap, src, nav))
493             .collect::<Result<Vec<_>>>()?;
494         Ok(links.into())
495     } else {
496         let locations = targets
497             .into_iter()
498             .map(|nav| {
499                 location(
500                     snap,
501                     FileRange {
502                         file_id: nav.file_id(),
503                         range: nav.focus_range().unwrap_or(nav.range()),
504                     },
505                 )
506             })
507             .collect::<Result<Vec<_>>>()?;
508         Ok(locations.into())
509     }
510 }
511
512 pub(crate) fn snippet_text_document_edit(
513     snap: &GlobalStateSnapshot,
514     is_snippet: bool,
515     source_file_edit: SourceFileEdit,
516 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
517     let text_document = versioned_text_document_identifier(snap, source_file_edit.file_id, None);
518     let line_index = snap.analysis().file_line_index(source_file_edit.file_id)?;
519     let line_endings = snap.file_line_endings(source_file_edit.file_id);
520     let edits = source_file_edit
521         .edit
522         .into_iter()
523         .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
524         .collect();
525     Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
526 }
527
528 pub(crate) fn resource_op(
529     snap: &GlobalStateSnapshot,
530     file_system_edit: FileSystemEdit,
531 ) -> lsp_types::ResourceOp {
532     match file_system_edit {
533         FileSystemEdit::CreateFile { anchor, dst } => {
534             let uri = snap.anchored_path(anchor, &dst);
535             lsp_types::ResourceOp::Create(lsp_types::CreateFile { uri, options: None })
536         }
537         FileSystemEdit::MoveFile { src, anchor, dst } => {
538             let old_uri = snap.file_id_to_url(src);
539             let new_uri = snap.anchored_path(anchor, &dst);
540             lsp_types::ResourceOp::Rename(lsp_types::RenameFile { old_uri, new_uri, options: None })
541         }
542     }
543 }
544
545 pub(crate) fn snippet_workspace_edit(
546     snap: &GlobalStateSnapshot,
547     source_change: SourceChange,
548 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
549     let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
550     for op in source_change.file_system_edits {
551         let op = resource_op(&snap, op);
552         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Op(op));
553     }
554     for edit in source_change.source_file_edits {
555         let edit = snippet_text_document_edit(&snap, source_change.is_snippet, edit)?;
556         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
557     }
558     let workspace_edit =
559         lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
560     Ok(workspace_edit)
561 }
562
563 pub(crate) fn workspace_edit(
564     snap: &GlobalStateSnapshot,
565     source_change: SourceChange,
566 ) -> Result<lsp_types::WorkspaceEdit> {
567     assert!(!source_change.is_snippet);
568     snippet_workspace_edit(snap, source_change).map(|it| it.into())
569 }
570
571 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
572     fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
573         lsp_types::WorkspaceEdit {
574             changes: None,
575             document_changes: snippet_workspace_edit.document_changes.map(|changes| {
576                 lsp_types::DocumentChanges::Operations(
577                     changes
578                         .into_iter()
579                         .map(|change| match change {
580                             lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
581                                 lsp_types::DocumentChangeOperation::Op(op)
582                             }
583                             lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
584                                 lsp_types::DocumentChangeOperation::Edit(
585                                     lsp_types::TextDocumentEdit {
586                                         text_document: edit.text_document,
587                                         edits: edit
588                                             .edits
589                                             .into_iter()
590                                             .map(|edit| lsp_types::TextEdit {
591                                                 range: edit.range,
592                                                 new_text: edit.new_text,
593                                             })
594                                             .collect(),
595                                     },
596                                 )
597                             }
598                         })
599                         .collect(),
600                 )
601             }),
602         }
603     }
604 }
605
606 pub(crate) fn call_hierarchy_item(
607     snap: &GlobalStateSnapshot,
608     target: NavigationTarget,
609 ) -> Result<lsp_types::CallHierarchyItem> {
610     let name = target.name().to_string();
611     let detail = target.description().map(|it| it.to_string());
612     let kind = symbol_kind(target.kind());
613     let (uri, range, selection_range) = location_info(snap, target)?;
614     Ok(lsp_types::CallHierarchyItem { name, kind, tags: None, detail, uri, range, selection_range })
615 }
616
617 pub(crate) fn unresolved_code_action(
618     snap: &GlobalStateSnapshot,
619     assist: Assist,
620     index: usize,
621 ) -> Result<lsp_ext::CodeAction> {
622     let res = lsp_ext::CodeAction {
623         title: assist.label,
624         id: Some(format!("{}:{}", assist.id.0.to_owned(), index.to_string())),
625         group: assist.group.filter(|_| snap.config.client_caps.code_action_group).map(|gr| gr.0),
626         kind: Some(String::new()),
627         edit: None,
628         command: None,
629     };
630     Ok(res)
631 }
632
633 pub(crate) fn resolved_code_action(
634     snap: &GlobalStateSnapshot,
635     assist: ResolvedAssist,
636 ) -> Result<lsp_ext::CodeAction> {
637     let change = assist.source_change;
638     unresolved_code_action(snap, assist.assist, 0).and_then(|it| {
639         Ok(lsp_ext::CodeAction {
640             id: None,
641             edit: Some(snippet_workspace_edit(snap, change)?),
642             ..it
643         })
644     })
645 }
646
647 pub(crate) fn runnable(
648     snap: &GlobalStateSnapshot,
649     file_id: FileId,
650     runnable: Runnable,
651 ) -> Result<lsp_ext::Runnable> {
652     let spec = CargoTargetSpec::for_file(snap, file_id)?;
653     let target = spec.as_ref().map(|s| s.target.clone());
654     let (cargo_args, executable_args) =
655         CargoTargetSpec::runnable_args(spec, &runnable.kind, &runnable.cfg_exprs)?;
656     let label = runnable.label(target);
657     let location = location_link(snap, None, runnable.nav)?;
658
659     Ok(lsp_ext::Runnable {
660         label,
661         location: Some(location),
662         kind: lsp_ext::RunnableKind::Cargo,
663         args: lsp_ext::CargoRunnable {
664             workspace_root: snap.workspace_root_for(file_id).map(|root| root.to_owned()),
665             cargo_args,
666             executable_args,
667         },
668     })
669 }
670
671 #[cfg(test)]
672 mod tests {
673     use test_utils::extract_ranges;
674
675     use super::*;
676
677     #[test]
678     fn conv_fold_line_folding_only_fixup() {
679         let text = r#"<fold>mod a;
680 mod b;
681 mod c;</fold>
682
683 fn main() <fold>{
684     if cond <fold>{
685         a::do_a();
686     }</fold> else <fold>{
687         b::do_b();
688     }</fold>
689 }</fold>"#;
690
691         let (ranges, text) = extract_ranges(text, "fold");
692         assert_eq!(ranges.len(), 4);
693         let folds = vec![
694             Fold { range: ranges[0], kind: FoldKind::Mods },
695             Fold { range: ranges[1], kind: FoldKind::Block },
696             Fold { range: ranges[2], kind: FoldKind::Block },
697             Fold { range: ranges[3], kind: FoldKind::Block },
698         ];
699
700         let line_index = LineIndex::new(&text);
701         let converted: Vec<lsp_types::FoldingRange> =
702             folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
703
704         let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
705         assert_eq!(converted.len(), expected_lines.len());
706         for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
707             assert_eq!(folding_range.start_line, *start_line);
708             assert_eq!(folding_range.start_character, None);
709             assert_eq!(folding_range.end_line, *end_line);
710             assert_eq!(folding_range.end_character, None);
711         }
712     }
713
714     // `Url` is not able to parse windows paths on unix machines.
715     #[test]
716     #[cfg(target_os = "windows")]
717     fn test_lowercase_drive_letter_with_drive() {
718         let url = url_from_abs_path(Path::new("C:\\Test"));
719         assert_eq!(url.to_string(), "file:///c:/Test");
720     }
721
722     #[test]
723     #[cfg(target_os = "windows")]
724     fn test_drive_without_colon_passthrough() {
725         let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
726         assert_eq!(url.to_string(), "file://localhost/C$/my_dir");
727     }
728 }