]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/to_proto.rs
Add punctuation highlighting for highlighting punctuation in doctests, fix highlighti...
[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::Module => lsp_types::SemanticTokenType::NAMESPACE,
299         HighlightTag::Constant => {
300             mods |= semantic_tokens::CONSTANT;
301             mods |= lsp_types::SemanticTokenModifier::STATIC;
302             lsp_types::SemanticTokenType::VARIABLE
303         }
304         HighlightTag::Static => {
305             mods |= lsp_types::SemanticTokenModifier::STATIC;
306             lsp_types::SemanticTokenType::VARIABLE
307         }
308         HighlightTag::EnumVariant => semantic_tokens::ENUM_MEMBER,
309         HighlightTag::Macro => lsp_types::SemanticTokenType::MACRO,
310         HighlightTag::Local => lsp_types::SemanticTokenType::VARIABLE,
311         HighlightTag::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
312         HighlightTag::Lifetime => semantic_tokens::LIFETIME,
313         HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => {
314             lsp_types::SemanticTokenType::NUMBER
315         }
316         HighlightTag::BoolLiteral => semantic_tokens::BOOLEAN,
317         HighlightTag::CharLiteral | HighlightTag::StringLiteral => {
318             lsp_types::SemanticTokenType::STRING
319         }
320         HighlightTag::Comment => lsp_types::SemanticTokenType::COMMENT,
321         HighlightTag::Attribute => semantic_tokens::ATTRIBUTE,
322         HighlightTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
323         HighlightTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
324         HighlightTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
325         HighlightTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
326         HighlightTag::Punctuation => semantic_tokens::PUNCTUATION,
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 => 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 pub(crate) fn location_link(
450     snap: &GlobalStateSnapshot,
451     src: Option<FileRange>,
452     target: NavigationTarget,
453 ) -> Result<lsp_types::LocationLink> {
454     let origin_selection_range = match src {
455         Some(src) => {
456             let line_index = snap.analysis().file_line_index(src.file_id)?;
457             let range = range(&line_index, src.range);
458             Some(range)
459         }
460         None => None,
461     };
462     let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
463     let res = lsp_types::LocationLink {
464         origin_selection_range,
465         target_uri,
466         target_range,
467         target_selection_range,
468     };
469     Ok(res)
470 }
471
472 fn location_info(
473     snap: &GlobalStateSnapshot,
474     target: NavigationTarget,
475 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
476     let line_index = snap.analysis().file_line_index(target.file_id())?;
477
478     let target_uri = url(snap, target.file_id());
479     let target_range = range(&line_index, target.full_range());
480     let target_selection_range =
481         target.focus_range().map(|it| range(&line_index, it)).unwrap_or(target_range);
482     Ok((target_uri, target_range, target_selection_range))
483 }
484
485 pub(crate) fn goto_definition_response(
486     snap: &GlobalStateSnapshot,
487     src: Option<FileRange>,
488     targets: Vec<NavigationTarget>,
489 ) -> Result<lsp_types::GotoDefinitionResponse> {
490     if snap.config.client_caps.location_link {
491         let links = targets
492             .into_iter()
493             .map(|nav| location_link(snap, src, nav))
494             .collect::<Result<Vec<_>>>()?;
495         Ok(links.into())
496     } else {
497         let locations = targets
498             .into_iter()
499             .map(|nav| {
500                 location(
501                     snap,
502                     FileRange {
503                         file_id: nav.file_id(),
504                         range: nav.focus_range().unwrap_or(nav.range()),
505                     },
506                 )
507             })
508             .collect::<Result<Vec<_>>>()?;
509         Ok(locations.into())
510     }
511 }
512
513 pub(crate) fn snippet_text_document_edit(
514     snap: &GlobalStateSnapshot,
515     is_snippet: bool,
516     source_file_edit: SourceFileEdit,
517 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
518     let text_document = versioned_text_document_identifier(snap, source_file_edit.file_id, None);
519     let line_index = snap.analysis().file_line_index(source_file_edit.file_id)?;
520     let line_endings = snap.file_line_endings(source_file_edit.file_id);
521     let edits = source_file_edit
522         .edit
523         .into_iter()
524         .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
525         .collect();
526     Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
527 }
528
529 pub(crate) fn resource_op(
530     snap: &GlobalStateSnapshot,
531     file_system_edit: FileSystemEdit,
532 ) -> lsp_types::ResourceOp {
533     match file_system_edit {
534         FileSystemEdit::CreateFile { anchor, dst } => {
535             let uri = snap.anchored_path(anchor, &dst);
536             lsp_types::ResourceOp::Create(lsp_types::CreateFile { uri, options: None })
537         }
538         FileSystemEdit::MoveFile { src, anchor, dst } => {
539             let old_uri = snap.file_id_to_url(src);
540             let new_uri = snap.anchored_path(anchor, &dst);
541             lsp_types::ResourceOp::Rename(lsp_types::RenameFile { old_uri, new_uri, options: None })
542         }
543     }
544 }
545
546 pub(crate) fn snippet_workspace_edit(
547     snap: &GlobalStateSnapshot,
548     source_change: SourceChange,
549 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
550     let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
551     for op in source_change.file_system_edits {
552         let op = resource_op(&snap, op);
553         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Op(op));
554     }
555     for edit in source_change.source_file_edits {
556         let edit = snippet_text_document_edit(&snap, source_change.is_snippet, edit)?;
557         document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
558     }
559     let workspace_edit =
560         lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
561     Ok(workspace_edit)
562 }
563
564 pub(crate) fn workspace_edit(
565     snap: &GlobalStateSnapshot,
566     source_change: SourceChange,
567 ) -> Result<lsp_types::WorkspaceEdit> {
568     assert!(!source_change.is_snippet);
569     snippet_workspace_edit(snap, source_change).map(|it| it.into())
570 }
571
572 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
573     fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
574         lsp_types::WorkspaceEdit {
575             changes: None,
576             document_changes: snippet_workspace_edit.document_changes.map(|changes| {
577                 lsp_types::DocumentChanges::Operations(
578                     changes
579                         .into_iter()
580                         .map(|change| match change {
581                             lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
582                                 lsp_types::DocumentChangeOperation::Op(op)
583                             }
584                             lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
585                                 lsp_types::DocumentChangeOperation::Edit(
586                                     lsp_types::TextDocumentEdit {
587                                         text_document: edit.text_document,
588                                         edits: edit
589                                             .edits
590                                             .into_iter()
591                                             .map(|edit| lsp_types::TextEdit {
592                                                 range: edit.range,
593                                                 new_text: edit.new_text,
594                                             })
595                                             .collect(),
596                                     },
597                                 )
598                             }
599                         })
600                         .collect(),
601                 )
602             }),
603         }
604     }
605 }
606
607 pub(crate) fn call_hierarchy_item(
608     snap: &GlobalStateSnapshot,
609     target: NavigationTarget,
610 ) -> Result<lsp_types::CallHierarchyItem> {
611     let name = target.name().to_string();
612     let detail = target.description().map(|it| it.to_string());
613     let kind = symbol_kind(target.kind());
614     let (uri, range, selection_range) = location_info(snap, target)?;
615     Ok(lsp_types::CallHierarchyItem { name, kind, tags: None, detail, uri, range, selection_range })
616 }
617
618 pub(crate) fn unresolved_code_action(
619     snap: &GlobalStateSnapshot,
620     assist: Assist,
621     index: usize,
622 ) -> Result<lsp_ext::CodeAction> {
623     let res = lsp_ext::CodeAction {
624         title: assist.label,
625         id: Some(format!("{}:{}", assist.id.0.to_owned(), index.to_string())),
626         group: assist.group.filter(|_| snap.config.client_caps.code_action_group).map(|gr| gr.0),
627         kind: Some(String::new()),
628         edit: None,
629         command: None,
630     };
631     Ok(res)
632 }
633
634 pub(crate) fn resolved_code_action(
635     snap: &GlobalStateSnapshot,
636     assist: ResolvedAssist,
637 ) -> Result<lsp_ext::CodeAction> {
638     let change = assist.source_change;
639     unresolved_code_action(snap, assist.assist, 0).and_then(|it| {
640         Ok(lsp_ext::CodeAction {
641             id: None,
642             edit: Some(snippet_workspace_edit(snap, change)?),
643             ..it
644         })
645     })
646 }
647
648 pub(crate) fn runnable(
649     snap: &GlobalStateSnapshot,
650     file_id: FileId,
651     runnable: Runnable,
652 ) -> Result<lsp_ext::Runnable> {
653     let spec = CargoTargetSpec::for_file(snap, file_id)?;
654     let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
655     let target = spec.as_ref().map(|s| s.target.clone());
656     let (cargo_args, executable_args) =
657         CargoTargetSpec::runnable_args(spec, &runnable.kind, &runnable.cfg_exprs)?;
658     let label = runnable.label(target);
659     let location = location_link(snap, None, runnable.nav)?;
660
661     Ok(lsp_ext::Runnable {
662         label,
663         location: Some(location),
664         kind: lsp_ext::RunnableKind::Cargo,
665         args: lsp_ext::CargoRunnable {
666             workspace_root: workspace_root,
667             cargo_args,
668             executable_args,
669         },
670     })
671 }
672
673 #[cfg(test)]
674 mod tests {
675     use test_utils::extract_ranges;
676
677     use super::*;
678
679     #[test]
680     fn conv_fold_line_folding_only_fixup() {
681         let text = r#"<fold>mod a;
682 mod b;
683 mod c;</fold>
684
685 fn main() <fold>{
686     if cond <fold>{
687         a::do_a();
688     }</fold> else <fold>{
689         b::do_b();
690     }</fold>
691 }</fold>"#;
692
693         let (ranges, text) = extract_ranges(text, "fold");
694         assert_eq!(ranges.len(), 4);
695         let folds = vec![
696             Fold { range: ranges[0], kind: FoldKind::Mods },
697             Fold { range: ranges[1], kind: FoldKind::Block },
698             Fold { range: ranges[2], kind: FoldKind::Block },
699             Fold { range: ranges[3], kind: FoldKind::Block },
700         ];
701
702         let line_index = LineIndex::new(&text);
703         let converted: Vec<lsp_types::FoldingRange> =
704             folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
705
706         let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
707         assert_eq!(converted.len(), expected_lines.len());
708         for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
709             assert_eq!(folding_range.start_line, *start_line);
710             assert_eq!(folding_range.start_character, None);
711             assert_eq!(folding_range.end_line, *end_line);
712             assert_eq!(folding_range.end_character, None);
713         }
714     }
715
716     // `Url` is not able to parse windows paths on unix machines.
717     #[test]
718     #[cfg(target_os = "windows")]
719     fn test_lowercase_drive_letter_with_drive() {
720         let url = url_from_abs_path(Path::new("C:\\Test"));
721         assert_eq!(url.to_string(), "file:///c:/Test");
722     }
723
724     #[test]
725     #[cfg(target_os = "windows")]
726     fn test_drive_without_colon_passthrough() {
727         let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
728         assert_eq!(url.to_string(), "file://localhost/C$/my_dir");
729     }
730 }