1 //! Conversion of rust-analyzer specific types to lsp_types equivalents.
2 use std::path::{self, Path};
4 use itertools::Itertools;
5 use ra_db::{FileId, FileRange};
7 Assist, AssistKind, CallInfo, CompletionItem, CompletionItemKind, Documentation,
8 FileSystemEdit, Fold, FoldKind, Highlight, HighlightModifier, HighlightTag, HighlightedRange,
9 Indel, InlayHint, InlayKind, InsertTextFormat, LineIndex, Markup, NavigationTarget,
10 ReferenceAccess, ResolvedAssist, Runnable, Severity, SourceChange, SourceFileEdit, TextEdit,
12 use ra_syntax::{SyntaxKind, TextRange, TextSize};
15 cargo_target_spec::CargoTargetSpec, global_state::GlobalStateSnapshot,
16 line_endings::LineEndings, lsp_ext, semantic_tokens, Result,
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)
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)
32 pub(crate) fn symbol_kind(syntax_kind: SyntaxKind) -> lsp_types::SymbolKind {
34 SyntaxKind::FN => lsp_types::SymbolKind::Function,
35 SyntaxKind::STRUCT => lsp_types::SymbolKind::Struct,
36 SyntaxKind::ENUM => lsp_types::SymbolKind::Enum,
37 SyntaxKind::VARIANT => lsp_types::SymbolKind::EnumMember,
38 SyntaxKind::TRAIT => lsp_types::SymbolKind::Interface,
39 SyntaxKind::MACRO_CALL => lsp_types::SymbolKind::Function,
40 SyntaxKind::MODULE => lsp_types::SymbolKind::Module,
41 SyntaxKind::TYPE_ALIAS => lsp_types::SymbolKind::TypeParameter,
42 SyntaxKind::RECORD_FIELD => lsp_types::SymbolKind::Field,
43 SyntaxKind::STATIC => lsp_types::SymbolKind::Constant,
44 SyntaxKind::CONST => lsp_types::SymbolKind::Constant,
45 SyntaxKind::IMPL => lsp_types::SymbolKind::Object,
46 _ => lsp_types::SymbolKind::Variable,
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,
59 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
61 Severity::Error => lsp_types::DiagnosticSeverity::Error,
62 Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
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)
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,
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 CompletionItemKind::UnresolvedReference => lsp_types::CompletionItemKind::Reference,
107 pub(crate) fn text_edit(
108 line_index: &LineIndex,
109 line_endings: LineEndings,
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"),
117 lsp_types::TextEdit { range, new_text }
120 pub(crate) fn snippet_text_edit(
121 line_index: &LineIndex,
122 line_endings: LineEndings,
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,
136 pub(crate) fn text_edit_vec(
137 line_index: &LineIndex,
138 line_endings: LineEndings,
140 ) -> Vec<lsp_types::TextEdit> {
141 text_edit.into_iter().map(|indel| self::text_edit(line_index, line_endings, indel)).collect()
144 pub(crate) fn snippet_text_edit_vec(
145 line_index: &LineIndex,
146 line_endings: LineEndings,
149 ) -> Vec<lsp_ext::SnippetTextEdit> {
152 .map(|indel| self::snippet_text_edit(line_index, line_endings, is_snippet, indel))
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())
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)
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);
185 let text_edit = text_edit.unwrap();
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()),
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()));
205 if completion_item.deprecated() {
206 res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
209 if completion_item.trigger_call_info() {
210 res.command = Some(lsp_types::Command {
211 title: "triggerParameterHints".into(),
212 command: "editor.action.triggerParameterHints".into(),
217 res.insert_text_format = Some(insert_text_format(completion_item.insert_text_format()));
222 pub(crate) fn signature_help(
226 ) -> lsp_types::SignatureHelp {
227 let (label, parameters) = match (concise, label_offsets) {
229 let params = call_info
231 .map(|label| lsp_types::ParameterInformation {
232 label: lsp_types::ParameterLabel::Simple(label.to_string()),
235 .collect::<Vec<_>>();
237 if concise { call_info.parameter_labels().join(", ") } else { call_info.signature };
241 let params = call_info
244 .map(|it| [u32::from(it.start()).into(), u32::from(it.end()).into()])
245 .map(|label_offsets| lsp_types::ParameterInformation {
246 label: lsp_types::ParameterLabel::LabelOffsets(label_offsets),
249 .collect::<Vec<_>>();
250 (call_info.signature, params)
253 let mut params = Vec::new();
254 let mut label = String::new();
255 let mut first = true;
256 for param in call_info.parameter_labels() {
258 label.push_str(", ");
261 let start = label.len() as u64;
262 label.push_str(param);
263 let end = label.len() as u64;
264 params.push(lsp_types::ParameterInformation {
265 label: lsp_types::ParameterLabel::LabelOffsets([start, end]),
274 let documentation = if concise {
277 call_info.doc.map(|doc| {
278 lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
279 kind: lsp_types::MarkupKind::Markdown,
286 lsp_types::SignatureInformation { label, documentation, parameters: Some(parameters) };
287 lsp_types::SignatureHelp {
288 signatures: vec![signature],
289 active_signature: None,
290 active_parameter: call_info.active_parameter.map(|it| it as i64),
294 pub(crate) fn inlay_int(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
296 label: inlay_hint.label.to_string(),
297 range: range(line_index, inlay_hint.range),
298 kind: match inlay_hint.kind {
299 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
300 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
301 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
306 pub(crate) fn semantic_tokens(
308 line_index: &LineIndex,
309 highlights: Vec<HighlightedRange>,
310 ) -> lsp_types::SemanticTokens {
311 let mut builder = semantic_tokens::SemanticTokensBuilder::default();
313 for highlight_range in highlights {
314 let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
315 let token_index = semantic_tokens::type_index(type_);
316 let modifier_bitset = mods.0;
318 for mut text_range in line_index.lines(highlight_range.range) {
319 if text[text_range].ends_with('\n') {
321 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
323 let range = range(&line_index, text_range);
324 builder.push(range, token_index, modifier_bitset);
331 fn semantic_token_type_and_modifiers(
332 highlight: Highlight,
333 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
334 let mut mods = semantic_tokens::ModifierSet::default();
335 let type_ = match highlight.tag {
336 HighlightTag::Struct => lsp_types::SemanticTokenType::STRUCT,
337 HighlightTag::Enum => lsp_types::SemanticTokenType::ENUM,
338 HighlightTag::Union => semantic_tokens::UNION,
339 HighlightTag::TypeAlias => semantic_tokens::TYPE_ALIAS,
340 HighlightTag::Trait => lsp_types::SemanticTokenType::INTERFACE,
341 HighlightTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
342 HighlightTag::SelfKeyword => semantic_tokens::SELF_KEYWORD,
343 HighlightTag::SelfType => lsp_types::SemanticTokenType::TYPE,
344 HighlightTag::Field => lsp_types::SemanticTokenType::PROPERTY,
345 HighlightTag::Function => lsp_types::SemanticTokenType::FUNCTION,
346 HighlightTag::Generic => semantic_tokens::GENERIC,
347 HighlightTag::Module => lsp_types::SemanticTokenType::NAMESPACE,
348 HighlightTag::Constant => {
349 mods |= semantic_tokens::CONSTANT;
350 mods |= lsp_types::SemanticTokenModifier::STATIC;
351 lsp_types::SemanticTokenType::VARIABLE
353 HighlightTag::Static => {
354 mods |= lsp_types::SemanticTokenModifier::STATIC;
355 lsp_types::SemanticTokenType::VARIABLE
357 HighlightTag::EnumVariant => semantic_tokens::ENUM_MEMBER,
358 HighlightTag::Macro => lsp_types::SemanticTokenType::MACRO,
359 HighlightTag::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
360 HighlightTag::Local => lsp_types::SemanticTokenType::VARIABLE,
361 HighlightTag::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
362 HighlightTag::Lifetime => semantic_tokens::LIFETIME,
363 HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => {
364 lsp_types::SemanticTokenType::NUMBER
366 HighlightTag::BoolLiteral => semantic_tokens::BOOLEAN,
367 HighlightTag::CharLiteral | HighlightTag::StringLiteral => {
368 lsp_types::SemanticTokenType::STRING
370 HighlightTag::Comment => lsp_types::SemanticTokenType::COMMENT,
371 HighlightTag::Attribute => semantic_tokens::ATTRIBUTE,
372 HighlightTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
373 HighlightTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
374 HighlightTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
375 HighlightTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
376 HighlightTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
377 HighlightTag::Punctuation => semantic_tokens::PUNCTUATION,
380 for modifier in highlight.modifiers.iter() {
381 let modifier = match modifier {
382 HighlightModifier::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
383 HighlightModifier::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
384 HighlightModifier::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
385 HighlightModifier::Injected => semantic_tokens::INJECTED,
386 HighlightModifier::ControlFlow => semantic_tokens::CONTROL_FLOW,
387 HighlightModifier::Mutable => semantic_tokens::MUTABLE,
388 HighlightModifier::Unsafe => semantic_tokens::UNSAFE,
396 pub(crate) fn folding_range(
398 line_index: &LineIndex,
399 line_folding_only: bool,
401 ) -> lsp_types::FoldingRange {
402 let kind = match fold.kind {
403 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
404 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
405 FoldKind::Mods | FoldKind::Block | FoldKind::ArgList => None,
408 let range = range(line_index, fold.range);
410 if line_folding_only {
411 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
412 // even if it contains text not in the folding range. To prevent that we exclude
413 // range.end.line from the folding region if there is more text after range.end
415 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
417 .take_while(|it| *it != '\n')
418 .any(|it| !it.is_whitespace());
420 let end_line = if has_more_text_on_end_line {
421 range.end.line.saturating_sub(1)
426 lsp_types::FoldingRange {
427 start_line: range.start.line,
428 start_character: None,
434 lsp_types::FoldingRange {
435 start_line: range.start.line,
436 start_character: Some(range.start.character),
437 end_line: range.end.line,
438 end_character: Some(range.end.character),
444 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
445 snap.file_id_to_url(file_id)
448 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
449 /// This will only happen when processing windows paths.
451 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
452 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
453 assert!(path.is_absolute());
454 let url = lsp_types::Url::from_file_path(path).unwrap();
455 match path.components().next() {
456 Some(path::Component::Prefix(prefix)) if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
458 // Need to lowercase driver letter
463 let driver_letter_range = {
464 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
468 let start = scheme.len() + ':'.len_utf8();
469 start..(start + drive_letter.len())
472 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
473 // machinery *also* canonicalizes the drive letter. So, just massage the
475 let mut url = url.into_string();
476 url[driver_letter_range].make_ascii_lowercase();
477 lsp_types::Url::parse(&url).unwrap()
480 pub(crate) fn versioned_text_document_identifier(
481 snap: &GlobalStateSnapshot,
483 ) -> lsp_types::VersionedTextDocumentIdentifier {
484 let url = url(snap, file_id);
485 let version = snap.url_file_version(&url);
486 lsp_types::VersionedTextDocumentIdentifier { uri: url, version }
489 pub(crate) fn location(
490 snap: &GlobalStateSnapshot,
492 ) -> Result<lsp_types::Location> {
493 let url = url(snap, frange.file_id);
494 let line_index = snap.analysis.file_line_index(frange.file_id)?;
495 let range = range(&line_index, frange.range);
496 let loc = lsp_types::Location::new(url, range);
500 /// Perefer using `location_link`, if the client has the cap.
501 pub(crate) fn location_from_nav(
502 snap: &GlobalStateSnapshot,
503 nav: NavigationTarget,
504 ) -> Result<lsp_types::Location> {
505 let url = url(snap, nav.file_id);
506 let line_index = snap.analysis.file_line_index(nav.file_id)?;
507 let range = range(&line_index, nav.full_range);
508 let loc = lsp_types::Location::new(url, range);
512 pub(crate) fn location_link(
513 snap: &GlobalStateSnapshot,
514 src: Option<FileRange>,
515 target: NavigationTarget,
516 ) -> Result<lsp_types::LocationLink> {
517 let origin_selection_range = match src {
519 let line_index = snap.analysis.file_line_index(src.file_id)?;
520 let range = range(&line_index, src.range);
525 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
526 let res = lsp_types::LocationLink {
527 origin_selection_range,
530 target_selection_range,
536 snap: &GlobalStateSnapshot,
537 target: NavigationTarget,
538 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
539 let line_index = snap.analysis.file_line_index(target.file_id)?;
541 let target_uri = url(snap, target.file_id);
542 let target_range = range(&line_index, target.full_range);
543 let target_selection_range =
544 target.focus_range.map(|it| range(&line_index, it)).unwrap_or(target_range);
545 Ok((target_uri, target_range, target_selection_range))
548 pub(crate) fn goto_definition_response(
549 snap: &GlobalStateSnapshot,
550 src: Option<FileRange>,
551 targets: Vec<NavigationTarget>,
552 ) -> Result<lsp_types::GotoDefinitionResponse> {
553 if snap.config.client_caps.location_link {
556 .map(|nav| location_link(snap, src, nav))
557 .collect::<Result<Vec<_>>>()?;
560 let locations = targets
563 location(snap, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() })
565 .collect::<Result<Vec<_>>>()?;
570 pub(crate) fn snippet_text_document_edit(
571 snap: &GlobalStateSnapshot,
573 source_file_edit: SourceFileEdit,
574 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
575 let text_document = versioned_text_document_identifier(snap, source_file_edit.file_id);
576 let line_index = snap.analysis.file_line_index(source_file_edit.file_id)?;
577 let line_endings = snap.file_line_endings(source_file_edit.file_id);
578 let edits = source_file_edit
581 .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
583 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
586 pub(crate) fn resource_op(
587 snap: &GlobalStateSnapshot,
588 file_system_edit: FileSystemEdit,
589 ) -> lsp_types::ResourceOp {
590 match file_system_edit {
591 FileSystemEdit::CreateFile { anchor, dst } => {
592 let uri = snap.anchored_path(anchor, &dst);
593 lsp_types::ResourceOp::Create(lsp_types::CreateFile { uri, options: None })
595 FileSystemEdit::MoveFile { src, anchor, dst } => {
596 let old_uri = snap.file_id_to_url(src);
597 let new_uri = snap.anchored_path(anchor, &dst);
598 lsp_types::ResourceOp::Rename(lsp_types::RenameFile { old_uri, new_uri, options: None })
603 pub(crate) fn snippet_workspace_edit(
604 snap: &GlobalStateSnapshot,
605 source_change: SourceChange,
606 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
607 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
608 for op in source_change.file_system_edits {
609 let op = resource_op(&snap, op);
610 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Op(op));
612 for edit in source_change.source_file_edits {
613 let edit = snippet_text_document_edit(&snap, source_change.is_snippet, edit)?;
614 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
617 lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
621 pub(crate) fn workspace_edit(
622 snap: &GlobalStateSnapshot,
623 source_change: SourceChange,
624 ) -> Result<lsp_types::WorkspaceEdit> {
625 assert!(!source_change.is_snippet);
626 snippet_workspace_edit(snap, source_change).map(|it| it.into())
629 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
630 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
631 lsp_types::WorkspaceEdit {
633 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
634 lsp_types::DocumentChanges::Operations(
637 .map(|change| match change {
638 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
639 lsp_types::DocumentChangeOperation::Op(op)
641 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
642 lsp_types::DocumentChangeOperation::Edit(
643 lsp_types::TextDocumentEdit {
644 text_document: edit.text_document,
648 .map(|edit| lsp_types::TextEdit {
650 new_text: edit.new_text,
664 pub(crate) fn call_hierarchy_item(
665 snap: &GlobalStateSnapshot,
666 target: NavigationTarget,
667 ) -> Result<lsp_types::CallHierarchyItem> {
668 let name = target.name.to_string();
669 let detail = target.description.clone();
670 let kind = symbol_kind(target.kind);
671 let (uri, range, selection_range) = location_info(snap, target)?;
672 Ok(lsp_types::CallHierarchyItem { name, kind, tags: None, detail, uri, range, selection_range })
675 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
677 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
678 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
679 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
680 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
681 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
682 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
686 pub(crate) fn unresolved_code_action(
687 snap: &GlobalStateSnapshot,
690 ) -> Result<lsp_ext::CodeAction> {
691 let res = lsp_ext::CodeAction {
693 id: Some(format!("{}:{}", assist.id.0.to_owned(), index.to_string())),
694 group: assist.group.filter(|_| snap.config.client_caps.code_action_group).map(|gr| gr.0),
695 kind: Some(code_action_kind(assist.id.1)),
702 pub(crate) fn resolved_code_action(
703 snap: &GlobalStateSnapshot,
704 assist: ResolvedAssist,
705 ) -> Result<lsp_ext::CodeAction> {
706 let change = assist.source_change;
707 unresolved_code_action(snap, assist.assist, 0).and_then(|it| {
708 Ok(lsp_ext::CodeAction {
710 edit: Some(snippet_workspace_edit(snap, change)?),
716 pub(crate) fn runnable(
717 snap: &GlobalStateSnapshot,
720 ) -> Result<lsp_ext::Runnable> {
721 let spec = CargoTargetSpec::for_file(snap, file_id)?;
722 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
723 let target = spec.as_ref().map(|s| s.target.clone());
724 let (cargo_args, executable_args) =
725 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg_exprs)?;
726 let label = runnable.label(target);
727 let location = location_link(snap, None, runnable.nav)?;
729 Ok(lsp_ext::Runnable {
731 location: Some(location),
732 kind: lsp_ext::RunnableKind::Cargo,
733 args: lsp_ext::CargoRunnable {
734 workspace_root: workspace_root.map(|it| it.into()),
742 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
743 lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value: markup.into() }
748 use ra_ide::Analysis;
753 fn conv_fold_line_folding_only_fixup() {
766 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
767 let folds = analysis.folding_ranges(file_id).unwrap();
768 assert_eq!(folds.len(), 4);
770 let line_index = LineIndex::new(&text);
771 let converted: Vec<lsp_types::FoldingRange> =
772 folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
774 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
775 assert_eq!(converted.len(), expected_lines.len());
776 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
777 assert_eq!(folding_range.start_line, *start_line);
778 assert_eq!(folding_range.start_character, None);
779 assert_eq!(folding_range.end_line, *end_line);
780 assert_eq!(folding_range.end_character, None);
784 // `Url` is not able to parse windows paths on unix machines.
786 #[cfg(target_os = "windows")]
787 fn test_lowercase_drive_letter_with_drive() {
788 let url = url_from_abs_path(Path::new("C:\\Test"));
789 assert_eq!(url.to_string(), "file:///c:/Test");
793 #[cfg(target_os = "windows")]
794 fn test_drive_without_colon_passthrough() {
795 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
796 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");