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, CompletionItem, CompletionItemKind, Documentation, FileSystemEdit, Fold,
8 FoldKind, FunctionSignature, 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_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,
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_information(
223 signature: FunctionSignature,
225 ) -> lsp_types::SignatureInformation {
226 let (label, documentation, params) = if concise {
227 let mut params = signature.parameters;
228 if signature.has_self_param {
231 (params.join(", "), None, params)
233 (signature.to_string(), signature.doc.map(documentation), signature.parameters)
236 let parameters: Vec<lsp_types::ParameterInformation> = params
238 .map(|param| lsp_types::ParameterInformation {
239 label: lsp_types::ParameterLabel::Simple(param),
244 lsp_types::SignatureInformation { label, documentation, parameters: Some(parameters) }
247 pub(crate) fn inlay_int(line_index: &LineIndex, inlay_hint: InlayHint) -> 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,
259 pub(crate) fn semantic_tokens(
261 line_index: &LineIndex,
262 highlights: Vec<HighlightedRange>,
263 ) -> lsp_types::SemanticTokens {
264 let mut builder = semantic_tokens::SemanticTokensBuilder::default();
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;
271 for mut text_range in line_index.lines(highlight_range.range) {
272 if text[text_range].ends_with('\n') {
274 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
276 let range = range(&line_index, text_range);
277 builder.push(range, token_index, modifier_bitset);
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::Generic => semantic_tokens::GENERIC,
300 HighlightTag::Module => lsp_types::SemanticTokenType::NAMESPACE,
301 HighlightTag::Constant => {
302 mods |= semantic_tokens::CONSTANT;
303 mods |= lsp_types::SemanticTokenModifier::STATIC;
304 lsp_types::SemanticTokenType::VARIABLE
306 HighlightTag::Static => {
307 mods |= lsp_types::SemanticTokenModifier::STATIC;
308 lsp_types::SemanticTokenType::VARIABLE
310 HighlightTag::EnumVariant => semantic_tokens::ENUM_MEMBER,
311 HighlightTag::Macro => lsp_types::SemanticTokenType::MACRO,
312 HighlightTag::ValueParam => lsp_types::SemanticTokenType::PARAMETER,
313 HighlightTag::Local => lsp_types::SemanticTokenType::VARIABLE,
314 HighlightTag::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
315 HighlightTag::Lifetime => semantic_tokens::LIFETIME,
316 HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => {
317 lsp_types::SemanticTokenType::NUMBER
319 HighlightTag::BoolLiteral => semantic_tokens::BOOLEAN,
320 HighlightTag::CharLiteral | HighlightTag::StringLiteral => {
321 lsp_types::SemanticTokenType::STRING
323 HighlightTag::Comment => lsp_types::SemanticTokenType::COMMENT,
324 HighlightTag::Attribute => semantic_tokens::ATTRIBUTE,
325 HighlightTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
326 HighlightTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
327 HighlightTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
328 HighlightTag::Operator => lsp_types::SemanticTokenType::OPERATOR,
329 HighlightTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
332 for modifier in highlight.modifiers.iter() {
333 let modifier = match modifier {
334 HighlightModifier::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
335 HighlightModifier::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
336 HighlightModifier::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
337 HighlightModifier::Injected => semantic_tokens::INJECTED,
338 HighlightModifier::ControlFlow => semantic_tokens::CONTROL_FLOW,
339 HighlightModifier::Mutable => semantic_tokens::MUTABLE,
340 HighlightModifier::Unsafe => semantic_tokens::UNSAFE,
348 pub(crate) fn folding_range(
350 line_index: &LineIndex,
351 line_folding_only: bool,
353 ) -> lsp_types::FoldingRange {
354 let kind = match fold.kind {
355 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
356 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
357 FoldKind::Mods | FoldKind::Block | FoldKind::ArgList => None,
360 let range = range(line_index, fold.range);
362 if line_folding_only {
363 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
364 // even if it contains text not in the folding range. To prevent that we exclude
365 // range.end.line from the folding region if there is more text after range.end
367 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
369 .take_while(|it| *it != '\n')
370 .any(|it| !it.is_whitespace());
372 let end_line = if has_more_text_on_end_line {
373 range.end.line.saturating_sub(1)
378 lsp_types::FoldingRange {
379 start_line: range.start.line,
380 start_character: None,
386 lsp_types::FoldingRange {
387 start_line: range.start.line,
388 start_character: Some(range.start.character),
389 end_line: range.end.line,
390 end_character: Some(range.end.character),
396 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
397 snap.file_id_to_url(file_id)
400 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
401 /// This will only happen when processing windows paths.
403 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
404 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
405 assert!(path.is_absolute());
406 let url = lsp_types::Url::from_file_path(path).unwrap();
407 match path.components().next() {
408 Some(path::Component::Prefix(prefix)) if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
410 // Need to lowercase driver letter
415 let driver_letter_range = {
416 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
420 let start = scheme.len() + ':'.len_utf8();
421 start..(start + drive_letter.len())
424 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
425 // machinery *also* canonicalizes the drive letter. So, just massage the
427 let mut url = url.into_string();
428 url[driver_letter_range].make_ascii_lowercase();
429 lsp_types::Url::parse(&url).unwrap()
432 pub(crate) fn versioned_text_document_identifier(
433 snap: &GlobalStateSnapshot,
435 version: Option<i64>,
436 ) -> lsp_types::VersionedTextDocumentIdentifier {
437 lsp_types::VersionedTextDocumentIdentifier { uri: url(snap, file_id), version }
440 pub(crate) fn location(
441 snap: &GlobalStateSnapshot,
443 ) -> Result<lsp_types::Location> {
444 let url = url(snap, frange.file_id);
445 let line_index = snap.analysis.file_line_index(frange.file_id)?;
446 let range = range(&line_index, frange.range);
447 let loc = lsp_types::Location::new(url, range);
451 /// Perefer using `location_link`, if the client has the cap.
452 pub(crate) fn location_from_nav(
453 snap: &GlobalStateSnapshot,
454 nav: NavigationTarget,
455 ) -> Result<lsp_types::Location> {
456 let url = url(snap, nav.file_id());
457 let line_index = snap.analysis.file_line_index(nav.file_id())?;
458 let range = range(&line_index, nav.full_range());
459 let loc = lsp_types::Location::new(url, range);
463 pub(crate) fn location_link(
464 snap: &GlobalStateSnapshot,
465 src: Option<FileRange>,
466 target: NavigationTarget,
467 ) -> Result<lsp_types::LocationLink> {
468 let origin_selection_range = match src {
470 let line_index = snap.analysis.file_line_index(src.file_id)?;
471 let range = range(&line_index, src.range);
476 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
477 let res = lsp_types::LocationLink {
478 origin_selection_range,
481 target_selection_range,
487 snap: &GlobalStateSnapshot,
488 target: NavigationTarget,
489 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
490 let line_index = snap.analysis.file_line_index(target.file_id())?;
492 let target_uri = url(snap, target.file_id());
493 let target_range = range(&line_index, target.full_range());
494 let target_selection_range =
495 target.focus_range().map(|it| range(&line_index, it)).unwrap_or(target_range);
496 Ok((target_uri, target_range, target_selection_range))
499 pub(crate) fn goto_definition_response(
500 snap: &GlobalStateSnapshot,
501 src: Option<FileRange>,
502 targets: Vec<NavigationTarget>,
503 ) -> Result<lsp_types::GotoDefinitionResponse> {
504 if snap.config.client_caps.location_link {
507 .map(|nav| location_link(snap, src, nav))
508 .collect::<Result<Vec<_>>>()?;
511 let locations = targets
517 file_id: nav.file_id(),
518 range: nav.focus_range().unwrap_or(nav.range()),
522 .collect::<Result<Vec<_>>>()?;
527 pub(crate) fn snippet_text_document_edit(
528 snap: &GlobalStateSnapshot,
530 source_file_edit: SourceFileEdit,
531 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
532 let text_document = versioned_text_document_identifier(snap, source_file_edit.file_id, None);
533 let line_index = snap.analysis.file_line_index(source_file_edit.file_id)?;
534 let line_endings = snap.file_line_endings(source_file_edit.file_id);
535 let edits = source_file_edit
538 .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
540 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
543 pub(crate) fn resource_op(
544 snap: &GlobalStateSnapshot,
545 file_system_edit: FileSystemEdit,
546 ) -> lsp_types::ResourceOp {
547 match file_system_edit {
548 FileSystemEdit::CreateFile { anchor, dst } => {
549 let uri = snap.anchored_path(anchor, &dst);
550 lsp_types::ResourceOp::Create(lsp_types::CreateFile { uri, options: None })
552 FileSystemEdit::MoveFile { src, anchor, dst } => {
553 let old_uri = snap.file_id_to_url(src);
554 let new_uri = snap.anchored_path(anchor, &dst);
555 lsp_types::ResourceOp::Rename(lsp_types::RenameFile { old_uri, new_uri, options: None })
560 pub(crate) fn snippet_workspace_edit(
561 snap: &GlobalStateSnapshot,
562 source_change: SourceChange,
563 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
564 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
565 for op in source_change.file_system_edits {
566 let op = resource_op(&snap, op);
567 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Op(op));
569 for edit in source_change.source_file_edits {
570 let edit = snippet_text_document_edit(&snap, source_change.is_snippet, edit)?;
571 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
574 lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
578 pub(crate) fn workspace_edit(
579 snap: &GlobalStateSnapshot,
580 source_change: SourceChange,
581 ) -> Result<lsp_types::WorkspaceEdit> {
582 assert!(!source_change.is_snippet);
583 snippet_workspace_edit(snap, source_change).map(|it| it.into())
586 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
587 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
588 lsp_types::WorkspaceEdit {
590 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
591 lsp_types::DocumentChanges::Operations(
594 .map(|change| match change {
595 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
596 lsp_types::DocumentChangeOperation::Op(op)
598 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
599 lsp_types::DocumentChangeOperation::Edit(
600 lsp_types::TextDocumentEdit {
601 text_document: edit.text_document,
605 .map(|edit| lsp_types::TextEdit {
607 new_text: edit.new_text,
621 pub(crate) fn call_hierarchy_item(
622 snap: &GlobalStateSnapshot,
623 target: NavigationTarget,
624 ) -> Result<lsp_types::CallHierarchyItem> {
625 let name = target.name().to_string();
626 let detail = target.description().map(|it| it.to_string());
627 let kind = symbol_kind(target.kind());
628 let (uri, range, selection_range) = location_info(snap, target)?;
629 Ok(lsp_types::CallHierarchyItem { name, kind, tags: None, detail, uri, range, selection_range })
632 pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
634 AssistKind::None | AssistKind::Generate => lsp_types::CodeActionKind::EMPTY,
635 AssistKind::QuickFix => lsp_types::CodeActionKind::QUICKFIX,
636 AssistKind::Refactor => lsp_types::CodeActionKind::REFACTOR,
637 AssistKind::RefactorExtract => lsp_types::CodeActionKind::REFACTOR_EXTRACT,
638 AssistKind::RefactorInline => lsp_types::CodeActionKind::REFACTOR_INLINE,
639 AssistKind::RefactorRewrite => lsp_types::CodeActionKind::REFACTOR_REWRITE,
643 pub(crate) fn unresolved_code_action(
644 snap: &GlobalStateSnapshot,
647 ) -> Result<lsp_ext::CodeAction> {
648 let res = lsp_ext::CodeAction {
650 id: Some(format!("{}:{}", assist.id.0.to_owned(), index.to_string())),
651 group: assist.group.filter(|_| snap.config.client_caps.code_action_group).map(|gr| gr.0),
652 kind: Some(code_action_kind(assist.id.1)),
658 pub(crate) fn resolved_code_action(
659 snap: &GlobalStateSnapshot,
660 assist: ResolvedAssist,
661 ) -> Result<lsp_ext::CodeAction> {
662 let change = assist.source_change;
663 unresolved_code_action(snap, assist.assist, 0).and_then(|it| {
664 Ok(lsp_ext::CodeAction {
666 edit: Some(snippet_workspace_edit(snap, change)?),
672 pub(crate) fn runnable(
673 snap: &GlobalStateSnapshot,
676 ) -> Result<lsp_ext::Runnable> {
677 let spec = CargoTargetSpec::for_file(snap, file_id)?;
678 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
679 let target = spec.as_ref().map(|s| s.target.clone());
680 let (cargo_args, executable_args) =
681 CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg_exprs)?;
682 let label = runnable.label(target);
683 let location = location_link(snap, None, runnable.nav)?;
685 Ok(lsp_ext::Runnable {
687 location: Some(location),
688 kind: lsp_ext::RunnableKind::Cargo,
689 args: lsp_ext::CargoRunnable {
690 workspace_root: workspace_root.map(|it| it.into()),
698 pub(crate) fn markup_content(markup: Markup) -> lsp_types::MarkupContent {
699 lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value: markup.into() }
704 use ra_ide::Analysis;
709 fn conv_fold_line_folding_only_fixup() {
722 let (analysis, file_id) = Analysis::from_single_file(text.to_string());
723 let folds = analysis.folding_ranges(file_id).unwrap();
724 assert_eq!(folds.len(), 4);
726 let line_index = LineIndex::new(&text);
727 let converted: Vec<lsp_types::FoldingRange> =
728 folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
730 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
731 assert_eq!(converted.len(), expected_lines.len());
732 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
733 assert_eq!(folding_range.start_line, *start_line);
734 assert_eq!(folding_range.start_character, None);
735 assert_eq!(folding_range.end_line, *end_line);
736 assert_eq!(folding_range.end_character, None);
740 // `Url` is not able to parse windows paths on unix machines.
742 #[cfg(target_os = "windows")]
743 fn test_lowercase_drive_letter_with_drive() {
744 let url = url_from_abs_path(Path::new("C:\\Test"));
745 assert_eq!(url.to_string(), "file:///c:/Test");
749 #[cfg(target_os = "windows")]
750 fn test_drive_without_colon_passthrough() {
751 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
752 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");