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