]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/to_proto.rs
Merge #4909
[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     };
328
329     for modifier in highlight.modifiers.iter() {
330         let modifier = match modifier {
331             HighlightModifier::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
332             HighlightModifier::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
333             HighlightModifier::ControlFlow => semantic_tokens::CONTROL_FLOW,
334             HighlightModifier::Mutable => semantic_tokens::MUTABLE,
335             HighlightModifier::Unsafe => semantic_tokens::UNSAFE,
336         };
337         mods |= modifier;
338     }
339
340     (type_, mods)
341 }
342
343 pub(crate) fn folding_range(
344     text: &str,
345     line_index: &LineIndex,
346     line_folding_only: bool,
347     fold: Fold,
348 ) -> lsp_types::FoldingRange {
349     let kind = match fold.kind {
350         FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
351         FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
352         FoldKind::Mods | FoldKind::Block => None,
353     };
354
355     let range = range(line_index, fold.range);
356
357     if line_folding_only {
358         // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
359         // even if it contains text not in the folding range. To prevent that we exclude
360         // range.end.line from the folding region if there is more text after range.end
361         // on the same line.
362         let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
363             .chars()
364             .take_while(|it| *it != '\n')
365             .any(|it| !it.is_whitespace());
366
367         let end_line = if has_more_text_on_end_line {
368             range.end.line.saturating_sub(1)
369         } else {
370             range.end.line
371         };
372
373         lsp_types::FoldingRange {
374             start_line: range.start.line,
375             start_character: None,
376             end_line,
377             end_character: None,
378             kind,
379         }
380     } else {
381         lsp_types::FoldingRange {
382             start_line: range.start.line,
383             start_character: Some(range.start.character),
384             end_line: range.end.line,
385             end_character: Some(range.end.character),
386             kind,
387         }
388     }
389 }
390
391 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
392     snap.file_id_to_url(file_id)
393 }
394
395 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
396 /// This will only happen when processing windows paths.
397 ///
398 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
399 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
400     assert!(path.is_absolute());
401     let url = lsp_types::Url::from_file_path(path).unwrap();
402     match path.components().next() {
403         Some(path::Component::Prefix(prefix)) if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
404         {
405             // Need to lowercase driver letter
406         }
407         _ => return url,
408     }
409
410     let driver_letter_range = {
411         let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
412             Some(it) => it,
413             None => return url,
414         };
415         let start = scheme.len() + ':'.len_utf8();
416         start..(start + drive_letter.len())
417     };
418
419     // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
420     // machinery *also* canonicalizes the drive letter. So, just massage the
421     // string in place.
422     let mut url = url.into_string();
423     url[driver_letter_range].make_ascii_lowercase();
424     lsp_types::Url::parse(&url).unwrap()
425 }
426
427 pub(crate) fn versioned_text_document_identifier(
428     snap: &GlobalStateSnapshot,
429     file_id: FileId,
430     version: Option<i64>,
431 ) -> lsp_types::VersionedTextDocumentIdentifier {
432     lsp_types::VersionedTextDocumentIdentifier { uri: url(snap, file_id), version }
433 }
434
435 pub(crate) fn location(
436     snap: &GlobalStateSnapshot,
437     frange: FileRange,
438 ) -> Result<lsp_types::Location> {
439     let url = url(snap, frange.file_id);
440     let line_index = snap.analysis().file_line_index(frange.file_id)?;
441     let range = range(&line_index, frange.range);
442     let loc = lsp_types::Location::new(url, range);
443     Ok(loc)
444 }
445
446 pub(crate) fn location_link(
447     snap: &GlobalStateSnapshot,
448     src: Option<FileRange>,
449     target: NavigationTarget,
450 ) -> Result<lsp_types::LocationLink> {
451     let origin_selection_range = match src {
452         Some(src) => {
453             let line_index = snap.analysis().file_line_index(src.file_id)?;
454             let range = range(&line_index, src.range);
455             Some(range)
456         }
457         None => None,
458     };
459     let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
460     let res = lsp_types::LocationLink {
461         origin_selection_range,
462         target_uri,
463         target_range,
464         target_selection_range,
465     };
466     Ok(res)
467 }
468
469 fn location_info(
470     snap: &GlobalStateSnapshot,
471     target: NavigationTarget,
472 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
473     let line_index = snap.analysis().file_line_index(target.file_id())?;
474
475     let target_uri = url(snap, target.file_id());
476     let target_range = range(&line_index, target.full_range());
477     let target_selection_range =
478         target.focus_range().map(|it| range(&line_index, it)).unwrap_or(target_range);
479     Ok((target_uri, target_range, target_selection_range))
480 }
481
482 pub(crate) fn goto_definition_response(
483     snap: &GlobalStateSnapshot,
484     src: Option<FileRange>,
485     targets: Vec<NavigationTarget>,
486 ) -> Result<lsp_types::GotoDefinitionResponse> {
487     if snap.config.client_caps.location_link {
488         let links = targets
489             .into_iter()
490             .map(|nav| location_link(snap, src, nav))
491             .collect::<Result<Vec<_>>>()?;
492         Ok(links.into())
493     } else {
494         let locations = targets
495             .into_iter()
496             .map(|nav| {
497                 location(
498                     snap,
499                     FileRange {
500                         file_id: nav.file_id(),
501                         range: nav.focus_range().unwrap_or(nav.range()),
502                     },
503                 )
504             })
505             .collect::<Result<Vec<_>>>()?;
506         Ok(locations.into())
507     }
508 }
509
510 pub(crate) fn snippet_text_document_edit(
511     snap: &GlobalStateSnapshot,
512     is_snippet: bool,
513     source_file_edit: SourceFileEdit,
514 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
515     let text_document = versioned_text_document_identifier(snap, source_file_edit.file_id, None);
516     let line_index = snap.analysis().file_line_index(source_file_edit.file_id)?;
517     let line_endings = snap.file_line_endings(source_file_edit.file_id);
518     let edits = source_file_edit
519         .edit
520         .into_iter()
521         .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
522         .collect();
523     Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
524 }
525
526 pub(crate) fn resource_op(
527     snap: &GlobalStateSnapshot,
528     file_system_edit: FileSystemEdit,
529 ) -> lsp_types::ResourceOp {
530     match file_system_edit {
531         FileSystemEdit::CreateFile { anchor, dst } => {
532             let uri = snap.anchored_path(anchor, &dst);
533             lsp_types::ResourceOp::Create(lsp_types::CreateFile { uri, options: None })
534         }
535         FileSystemEdit::MoveFile { src, anchor, dst } => {
536             let old_uri = snap.file_id_to_url(src);
537             let new_uri = snap.anchored_path(anchor, &dst);
538             lsp_types::ResourceOp::Rename(lsp_types::RenameFile { old_uri, new_uri, options: None })
539         }
540     }
541 }
542
543 pub(crate) fn snippet_workspace_edit(
544     snap: &GlobalStateSnapshot,
545     source_change: SourceChange,
546 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
547     let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
548     for op in source_change.file_system_edits {
549         let op = resource_op(&snap, op);
550         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Op(op));
551     }
552     for edit in source_change.source_file_edits {
553         let edit = snippet_text_document_edit(&snap, source_change.is_snippet, edit)?;
554         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
555     }
556     let workspace_edit =
557         lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
558     Ok(workspace_edit)
559 }
560
561 pub(crate) fn workspace_edit(
562     snap: &GlobalStateSnapshot,
563     source_change: SourceChange,
564 ) -> Result<lsp_types::WorkspaceEdit> {
565     assert!(!source_change.is_snippet);
566     snippet_workspace_edit(snap, source_change).map(|it| it.into())
567 }
568
569 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
570     fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
571         lsp_types::WorkspaceEdit {
572             changes: None,
573             document_changes: snippet_workspace_edit.document_changes.map(|changes| {
574                 lsp_types::DocumentChanges::Operations(
575                     changes
576                         .into_iter()
577                         .map(|change| match change {
578                             lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
579                                 lsp_types::DocumentChangeOperation::Op(op)
580                             }
581                             lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
582                                 lsp_types::DocumentChangeOperation::Edit(
583                                     lsp_types::TextDocumentEdit {
584                                         text_document: edit.text_document,
585                                         edits: edit
586                                             .edits
587                                             .into_iter()
588                                             .map(|edit| lsp_types::TextEdit {
589                                                 range: edit.range,
590                                                 new_text: edit.new_text,
591                                             })
592                                             .collect(),
593                                     },
594                                 )
595                             }
596                         })
597                         .collect(),
598                 )
599             }),
600         }
601     }
602 }
603
604 pub(crate) fn call_hierarchy_item(
605     snap: &GlobalStateSnapshot,
606     target: NavigationTarget,
607 ) -> Result<lsp_types::CallHierarchyItem> {
608     let name = target.name().to_string();
609     let detail = target.description().map(|it| it.to_string());
610     let kind = symbol_kind(target.kind());
611     let (uri, range, selection_range) = location_info(snap, target)?;
612     Ok(lsp_types::CallHierarchyItem { name, kind, tags: None, detail, uri, range, selection_range })
613 }
614
615 pub(crate) fn unresolved_code_action(
616     snap: &GlobalStateSnapshot,
617     assist: Assist,
618     index: usize,
619 ) -> Result<lsp_ext::CodeAction> {
620     let res = lsp_ext::CodeAction {
621         title: assist.label,
622         id: Some(format!("{}:{}", assist.id.0.to_owned(), index.to_string())),
623         group: assist.group.filter(|_| snap.config.client_caps.code_action_group).map(|gr| gr.0),
624         kind: Some(String::new()),
625         edit: None,
626         command: None,
627     };
628     Ok(res)
629 }
630
631 pub(crate) fn resolved_code_action(
632     snap: &GlobalStateSnapshot,
633     assist: ResolvedAssist,
634 ) -> Result<lsp_ext::CodeAction> {
635     let change = assist.source_change;
636     unresolved_code_action(snap, assist.assist, 0).and_then(|it| {
637         Ok(lsp_ext::CodeAction {
638             id: None,
639             edit: Some(snippet_workspace_edit(snap, change)?),
640             ..it
641         })
642     })
643 }
644
645 pub(crate) fn runnable(
646     snap: &GlobalStateSnapshot,
647     file_id: FileId,
648     runnable: Runnable,
649 ) -> Result<lsp_ext::Runnable> {
650     let spec = CargoTargetSpec::for_file(snap, file_id)?;
651     let target = spec.as_ref().map(|s| s.target.clone());
652     let (cargo_args, executable_args) =
653         CargoTargetSpec::runnable_args(spec, &runnable.kind, &runnable.cfg_exprs)?;
654     let label = runnable.label(target);
655     let location = location_link(snap, None, runnable.nav)?;
656
657     Ok(lsp_ext::Runnable {
658         label,
659         location: Some(location),
660         kind: lsp_ext::RunnableKind::Cargo,
661         args: lsp_ext::CargoRunnable {
662             workspace_root: snap.workspace_root_for(file_id).map(|root| root.to_owned()),
663             cargo_args,
664             executable_args,
665         },
666     })
667 }
668
669 #[cfg(test)]
670 mod tests {
671     use test_utils::extract_ranges;
672
673     use super::*;
674
675     #[test]
676     fn conv_fold_line_folding_only_fixup() {
677         let text = r#"<fold>mod a;
678 mod b;
679 mod c;</fold>
680
681 fn main() <fold>{
682     if cond <fold>{
683         a::do_a();
684     }</fold> else <fold>{
685         b::do_b();
686     }</fold>
687 }</fold>"#;
688
689         let (ranges, text) = extract_ranges(text, "fold");
690         assert_eq!(ranges.len(), 4);
691         let folds = vec![
692             Fold { range: ranges[0], kind: FoldKind::Mods },
693             Fold { range: ranges[1], kind: FoldKind::Block },
694             Fold { range: ranges[2], kind: FoldKind::Block },
695             Fold { range: ranges[3], kind: FoldKind::Block },
696         ];
697
698         let line_index = LineIndex::new(&text);
699         let converted: Vec<lsp_types::FoldingRange> =
700             folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
701
702         let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
703         assert_eq!(converted.len(), expected_lines.len());
704         for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
705             assert_eq!(folding_range.start_line, *start_line);
706             assert_eq!(folding_range.start_character, None);
707             assert_eq!(folding_range.end_line, *end_line);
708             assert_eq!(folding_range.end_character, None);
709         }
710     }
711
712     // `Url` is not able to parse windows paths on unix machines.
713     #[test]
714     #[cfg(target_os = "windows")]
715     fn test_lowercase_drive_letter_with_drive() {
716         let url = url_from_abs_path(Path::new("C:\\Test"));
717         assert_eq!(url.to_string(), "file:///c:/Test");
718     }
719
720     #[test]
721     #[cfg(target_os = "windows")]
722     fn test_drive_without_colon_passthrough() {
723         let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
724         assert_eq!(url.to_string(), "file://localhost/C$/my_dir");
725     }
726 }