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, 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,
12 use ra_syntax::{SyntaxKind, TextRange, TextSize};
13 use ra_vfs::LineEndings;
16 cargo_target_spec::CargoTargetSpec, global_state::GlobalStateSnapshot, lsp_ext,
17 semantic_tokens, Result,
20 pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
21 let line_col = line_index.line_col(offset);
22 let line = u64::from(line_col.line);
23 let character = u64::from(line_col.col_utf16);
24 lsp_types::Position::new(line, character)
27 pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
28 let start = position(line_index, range.start());
29 let end = position(line_index, range.end());
30 lsp_types::Range::new(start, end)
33 pub(crate) fn symbol_kind(syntax_kind: SyntaxKind) -> lsp_types::SymbolKind {
35 SyntaxKind::FN_DEF => lsp_types::SymbolKind::Function,
36 SyntaxKind::STRUCT_DEF => lsp_types::SymbolKind::Struct,
37 SyntaxKind::ENUM_DEF => lsp_types::SymbolKind::Enum,
38 SyntaxKind::ENUM_VARIANT => lsp_types::SymbolKind::EnumMember,
39 SyntaxKind::TRAIT_DEF => lsp_types::SymbolKind::Interface,
40 SyntaxKind::MACRO_CALL => lsp_types::SymbolKind::Function,
41 SyntaxKind::MODULE => lsp_types::SymbolKind::Module,
42 SyntaxKind::TYPE_ALIAS_DEF => lsp_types::SymbolKind::TypeParameter,
43 SyntaxKind::RECORD_FIELD_DEF => lsp_types::SymbolKind::Field,
44 SyntaxKind::STATIC_DEF => lsp_types::SymbolKind::Constant,
45 SyntaxKind::CONST_DEF => lsp_types::SymbolKind::Constant,
46 SyntaxKind::IMPL_DEF => lsp_types::SymbolKind::Object,
47 _ => lsp_types::SymbolKind::Variable,
51 pub(crate) fn document_highlight_kind(
52 reference_access: ReferenceAccess,
53 ) -> lsp_types::DocumentHighlightKind {
54 match reference_access {
55 ReferenceAccess::Read => lsp_types::DocumentHighlightKind::Read,
56 ReferenceAccess::Write => lsp_types::DocumentHighlightKind::Write,
60 pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
62 Severity::Error => lsp_types::DiagnosticSeverity::Error,
63 Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
67 pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
68 let value = crate::markdown::format_docs(documentation.as_str());
69 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
70 lsp_types::Documentation::MarkupContent(markup_content)
73 pub(crate) fn insert_text_format(
74 insert_text_format: InsertTextFormat,
75 ) -> lsp_types::InsertTextFormat {
76 match insert_text_format {
77 InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
78 InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
82 pub(crate) fn completion_item_kind(
83 completion_item_kind: CompletionItemKind,
84 ) -> lsp_types::CompletionItemKind {
85 match completion_item_kind {
86 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
87 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
88 CompletionItemKind::Module => lsp_types::CompletionItemKind::Module,
89 CompletionItemKind::Function => lsp_types::CompletionItemKind::Function,
90 CompletionItemKind::Struct => lsp_types::CompletionItemKind::Struct,
91 CompletionItemKind::Enum => lsp_types::CompletionItemKind::Enum,
92 CompletionItemKind::EnumVariant => lsp_types::CompletionItemKind::EnumMember,
93 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
94 CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
95 CompletionItemKind::Field => lsp_types::CompletionItemKind::Field,
96 CompletionItemKind::Trait => lsp_types::CompletionItemKind::Interface,
97 CompletionItemKind::TypeAlias => lsp_types::CompletionItemKind::Struct,
98 CompletionItemKind::Const => lsp_types::CompletionItemKind::Constant,
99 CompletionItemKind::Static => lsp_types::CompletionItemKind::Value,
100 CompletionItemKind::Method => lsp_types::CompletionItemKind::Method,
101 CompletionItemKind::TypeParam => lsp_types::CompletionItemKind::TypeParameter,
102 CompletionItemKind::Macro => lsp_types::CompletionItemKind::Method,
103 CompletionItemKind::Attribute => lsp_types::CompletionItemKind::EnumMember,
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::Module => lsp_types::SemanticTokenType::NAMESPACE,
300 HighlightTag::Constant => {
301 mods |= semantic_tokens::CONSTANT;
302 mods |= lsp_types::SemanticTokenModifier::STATIC;
303 lsp_types::SemanticTokenType::VARIABLE
305 HighlightTag::Static => {
306 mods |= lsp_types::SemanticTokenModifier::STATIC;
307 lsp_types::SemanticTokenType::VARIABLE
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
317 HighlightTag::BoolLiteral => semantic_tokens::BOOLEAN,
318 HighlightTag::CharLiteral | HighlightTag::StringLiteral => {
319 lsp_types::SemanticTokenType::STRING
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,
329 for modifier in highlight.modifiers.iter() {
330 let modifier = match modifier {
331 HighlightModifier::Attribute => semantic_tokens::ATTRIBUTE_MODIFIER,
332 HighlightModifier::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
333 HighlightModifier::Documentation => lsp_types::SemanticTokenModifier::DOCUMENTATION,
334 HighlightModifier::ControlFlow => semantic_tokens::CONTROL_FLOW,
335 HighlightModifier::Mutable => semantic_tokens::MUTABLE,
336 HighlightModifier::Unsafe => semantic_tokens::UNSAFE,
344 pub(crate) fn folding_range(
346 line_index: &LineIndex,
347 line_folding_only: bool,
349 ) -> lsp_types::FoldingRange {
350 let kind = match fold.kind {
351 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
352 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
353 FoldKind::Mods | FoldKind::Block => None,
356 let range = range(line_index, fold.range);
358 if line_folding_only {
359 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
360 // even if it contains text not in the folding range. To prevent that we exclude
361 // range.end.line from the folding region if there is more text after range.end
363 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
365 .take_while(|it| *it != '\n')
366 .any(|it| !it.is_whitespace());
368 let end_line = if has_more_text_on_end_line {
369 range.end.line.saturating_sub(1)
374 lsp_types::FoldingRange {
375 start_line: range.start.line,
376 start_character: None,
382 lsp_types::FoldingRange {
383 start_line: range.start.line,
384 start_character: Some(range.start.character),
385 end_line: range.end.line,
386 end_character: Some(range.end.character),
392 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
393 snap.file_id_to_url(file_id)
396 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
397 /// This will only happen when processing windows paths.
399 /// When processing non-windows path, this is essentially the same as `Url::from_file_path`.
400 pub(crate) fn url_from_abs_path(path: &Path) -> lsp_types::Url {
401 assert!(path.is_absolute());
402 let url = lsp_types::Url::from_file_path(path).unwrap();
403 match path.components().next() {
404 Some(path::Component::Prefix(prefix)) if matches!(prefix.kind(), path::Prefix::Disk(_) | path::Prefix::VerbatimDisk(_)) =>
406 // Need to lowercase driver letter
411 let driver_letter_range = {
412 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
416 let start = scheme.len() + ':'.len_utf8();
417 start..(start + drive_letter.len())
420 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
421 // machinery *also* canonicalizes the drive letter. So, just massage the
423 let mut url = url.into_string();
424 url[driver_letter_range].make_ascii_lowercase();
425 lsp_types::Url::parse(&url).unwrap()
428 pub(crate) fn versioned_text_document_identifier(
429 snap: &GlobalStateSnapshot,
431 version: Option<i64>,
432 ) -> lsp_types::VersionedTextDocumentIdentifier {
433 lsp_types::VersionedTextDocumentIdentifier { uri: url(snap, file_id), version }
436 pub(crate) fn location(
437 snap: &GlobalStateSnapshot,
439 ) -> Result<lsp_types::Location> {
440 let url = url(snap, frange.file_id);
441 let line_index = snap.analysis().file_line_index(frange.file_id)?;
442 let range = range(&line_index, frange.range);
443 let loc = lsp_types::Location::new(url, range);
447 pub(crate) fn location_link(
448 snap: &GlobalStateSnapshot,
449 src: Option<FileRange>,
450 target: NavigationTarget,
451 ) -> Result<lsp_types::LocationLink> {
452 let origin_selection_range = match src {
454 let line_index = snap.analysis().file_line_index(src.file_id)?;
455 let range = range(&line_index, src.range);
460 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
461 let res = lsp_types::LocationLink {
462 origin_selection_range,
465 target_selection_range,
471 snap: &GlobalStateSnapshot,
472 target: NavigationTarget,
473 ) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
474 let line_index = snap.analysis().file_line_index(target.file_id())?;
476 let target_uri = url(snap, target.file_id());
477 let target_range = range(&line_index, target.full_range());
478 let target_selection_range =
479 target.focus_range().map(|it| range(&line_index, it)).unwrap_or(target_range);
480 Ok((target_uri, target_range, target_selection_range))
483 pub(crate) fn goto_definition_response(
484 snap: &GlobalStateSnapshot,
485 src: Option<FileRange>,
486 targets: Vec<NavigationTarget>,
487 ) -> Result<lsp_types::GotoDefinitionResponse> {
488 if snap.config.client_caps.location_link {
491 .map(|nav| location_link(snap, src, nav))
492 .collect::<Result<Vec<_>>>()?;
495 let locations = targets
501 file_id: nav.file_id(),
502 range: nav.focus_range().unwrap_or(nav.range()),
506 .collect::<Result<Vec<_>>>()?;
511 pub(crate) fn snippet_text_document_edit(
512 snap: &GlobalStateSnapshot,
514 source_file_edit: SourceFileEdit,
515 ) -> Result<lsp_ext::SnippetTextDocumentEdit> {
516 let text_document = versioned_text_document_identifier(snap, source_file_edit.file_id, None);
517 let line_index = snap.analysis().file_line_index(source_file_edit.file_id)?;
518 let line_endings = snap.file_line_endings(source_file_edit.file_id);
519 let edits = source_file_edit
522 .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
524 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
527 pub(crate) fn resource_op(
528 snap: &GlobalStateSnapshot,
529 file_system_edit: FileSystemEdit,
530 ) -> lsp_types::ResourceOp {
531 match file_system_edit {
532 FileSystemEdit::CreateFile { anchor, dst } => {
533 let uri = snap.anchored_path(anchor, &dst);
534 lsp_types::ResourceOp::Create(lsp_types::CreateFile { uri, options: None })
536 FileSystemEdit::MoveFile { src, anchor, dst } => {
537 let old_uri = snap.file_id_to_url(src);
538 let new_uri = snap.anchored_path(anchor, &dst);
539 lsp_types::ResourceOp::Rename(lsp_types::RenameFile { old_uri, new_uri, options: None })
544 pub(crate) fn snippet_workspace_edit(
545 snap: &GlobalStateSnapshot,
546 source_change: SourceChange,
547 ) -> Result<lsp_ext::SnippetWorkspaceEdit> {
548 let mut document_changes: Vec<lsp_ext::SnippetDocumentChangeOperation> = Vec::new();
549 for op in source_change.file_system_edits {
550 let op = resource_op(&snap, op);
551 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Op(op));
553 for edit in source_change.source_file_edits {
554 let edit = snippet_text_document_edit(&snap, source_change.is_snippet, edit)?;
555 document_changes.push(lsp_ext::SnippetDocumentChangeOperation::Edit(edit));
558 lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
562 pub(crate) fn workspace_edit(
563 snap: &GlobalStateSnapshot,
564 source_change: SourceChange,
565 ) -> Result<lsp_types::WorkspaceEdit> {
566 assert!(!source_change.is_snippet);
567 snippet_workspace_edit(snap, source_change).map(|it| it.into())
570 impl From<lsp_ext::SnippetWorkspaceEdit> for lsp_types::WorkspaceEdit {
571 fn from(snippet_workspace_edit: lsp_ext::SnippetWorkspaceEdit) -> lsp_types::WorkspaceEdit {
572 lsp_types::WorkspaceEdit {
574 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
575 lsp_types::DocumentChanges::Operations(
578 .map(|change| match change {
579 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
580 lsp_types::DocumentChangeOperation::Op(op)
582 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
583 lsp_types::DocumentChangeOperation::Edit(
584 lsp_types::TextDocumentEdit {
585 text_document: edit.text_document,
589 .map(|edit| lsp_types::TextEdit {
591 new_text: edit.new_text,
605 pub(crate) fn call_hierarchy_item(
606 snap: &GlobalStateSnapshot,
607 target: NavigationTarget,
608 ) -> Result<lsp_types::CallHierarchyItem> {
609 let name = target.name().to_string();
610 let detail = target.description().map(|it| it.to_string());
611 let kind = symbol_kind(target.kind());
612 let (uri, range, selection_range) = location_info(snap, target)?;
613 Ok(lsp_types::CallHierarchyItem { name, kind, tags: None, detail, uri, range, selection_range })
616 pub(crate) fn unresolved_code_action(
617 snap: &GlobalStateSnapshot,
620 ) -> Result<lsp_ext::CodeAction> {
621 let res = lsp_ext::CodeAction {
623 id: Some(format!("{}:{}", assist.id.0.to_owned(), index.to_string())),
624 group: assist.group.filter(|_| snap.config.client_caps.code_action_group).map(|gr| gr.0),
625 kind: Some(String::new()),
632 pub(crate) fn resolved_code_action(
633 snap: &GlobalStateSnapshot,
634 assist: ResolvedAssist,
635 ) -> Result<lsp_ext::CodeAction> {
636 let change = assist.source_change;
637 unresolved_code_action(snap, assist.assist, 0).and_then(|it| {
638 Ok(lsp_ext::CodeAction {
640 edit: Some(snippet_workspace_edit(snap, change)?),
646 pub(crate) fn runnable(
647 snap: &GlobalStateSnapshot,
650 ) -> Result<lsp_ext::Runnable> {
651 let spec = CargoTargetSpec::for_file(snap, file_id)?;
652 let target = spec.as_ref().map(|s| s.target.clone());
653 let (cargo_args, executable_args) =
654 CargoTargetSpec::runnable_args(spec, &runnable.kind, &runnable.cfg_exprs)?;
655 let label = runnable.label(target);
656 let location = location_link(snap, None, runnable.nav)?;
658 Ok(lsp_ext::Runnable {
660 location: Some(location),
661 kind: lsp_ext::RunnableKind::Cargo,
662 args: lsp_ext::CargoRunnable {
663 workspace_root: snap.workspace_root_for(file_id).map(|root| root.to_owned()),
672 use test_utils::extract_ranges;
677 fn conv_fold_line_folding_only_fixup() {
678 let text = r#"<fold>mod a;
685 }</fold> else <fold>{
690 let (ranges, text) = extract_ranges(text, "fold");
691 assert_eq!(ranges.len(), 4);
693 Fold { range: ranges[0], kind: FoldKind::Mods },
694 Fold { range: ranges[1], kind: FoldKind::Block },
695 Fold { range: ranges[2], kind: FoldKind::Block },
696 Fold { range: ranges[3], kind: FoldKind::Block },
699 let line_index = LineIndex::new(&text);
700 let converted: Vec<lsp_types::FoldingRange> =
701 folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
703 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
704 assert_eq!(converted.len(), expected_lines.len());
705 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
706 assert_eq!(folding_range.start_line, *start_line);
707 assert_eq!(folding_range.start_character, None);
708 assert_eq!(folding_range.end_line, *end_line);
709 assert_eq!(folding_range.end_character, None);
713 // `Url` is not able to parse windows paths on unix machines.
715 #[cfg(target_os = "windows")]
716 fn test_lowercase_drive_letter_with_drive() {
717 let url = url_from_abs_path(Path::new("C:\\Test"));
718 assert_eq!(url.to_string(), "file:///c:/Test");
722 #[cfg(target_os = "windows")]
723 fn test_drive_without_colon_passthrough() {
724 let url = url_from_abs_path(Path::new(r#"\\localhost\C$\my_dir"#));
725 assert_eq!(url.to_string(), "file://localhost/C$/my_dir");