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};
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,
106 pub(crate) fn text_edit(
107 line_index: &LineIndex,
108 line_endings: LineEndings,
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"),
116 lsp_types::TextEdit { range, new_text }
119 pub(crate) fn snippet_text_edit(
120 line_index: &LineIndex,
121 line_endings: LineEndings,
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,
135 pub(crate) fn text_edit_vec(
136 line_index: &LineIndex,
137 line_endings: LineEndings,
139 ) -> Vec<lsp_types::TextEdit> {
140 text_edit.into_iter().map(|indel| self::text_edit(line_index, line_endings, indel)).collect()
143 pub(crate) fn snippet_text_edit_vec(
144 line_index: &LineIndex,
145 line_endings: LineEndings,
148 ) -> Vec<lsp_ext::SnippetTextEdit> {
151 .map(|indel| self::snippet_text_edit(line_index, line_endings, is_snippet, indel))
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())
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)
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);
184 let text_edit = text_edit.unwrap();
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()),
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()));
204 if completion_item.deprecated() {
205 res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
208 if completion_item.trigger_call_info() {
209 res.command = Some(lsp_types::Command {
210 title: "triggerParameterHints".into(),
211 command: "editor.action.triggerParameterHints".into(),
216 res.insert_text_format = Some(insert_text_format(completion_item.insert_text_format()));
221 pub(crate) fn signature_information(
222 signature: FunctionSignature,
224 ) -> lsp_types::SignatureInformation {
225 let (label, documentation, params) = if concise {
226 let mut params = signature.parameters;
227 if signature.has_self_param {
230 (params.join(", "), None, params)
232 (signature.to_string(), signature.doc.map(documentation), signature.parameters)
235 let parameters: Vec<lsp_types::ParameterInformation> = params
237 .map(|param| lsp_types::ParameterInformation {
238 label: lsp_types::ParameterLabel::Simple(param),
243 lsp_types::SignatureInformation { label, documentation, parameters: Some(parameters) }
246 pub(crate) fn inlay_int(line_index: &LineIndex, inlay_hint: InlayHint) -> 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,
258 pub(crate) fn semantic_tokens(
260 line_index: &LineIndex,
261 highlights: Vec<HighlightedRange>,
262 ) -> lsp_types::SemanticTokens {
263 let mut builder = semantic_tokens::SemanticTokensBuilder::default();
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;
270 for mut text_range in line_index.lines(highlight_range.range) {
271 if text[text_range].ends_with('\n') {
273 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
275 let range = range(&line_index, text_range);
276 builder.push(range, token_index, modifier_bitset);
283 fn semantic_token_type_and_modifiers(
284 highlight: Highlight,
285 ) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
286 let mut mods = semantic_tokens::ModifierSet::default();
287 let type_ = match highlight.tag {
288 HighlightTag::Struct => lsp_types::SemanticTokenType::STRUCT,
289 HighlightTag::Enum => lsp_types::SemanticTokenType::ENUM,
290 HighlightTag::Union => semantic_tokens::UNION,
291 HighlightTag::TypeAlias => semantic_tokens::TYPE_ALIAS,
292 HighlightTag::Trait => lsp_types::SemanticTokenType::INTERFACE,
293 HighlightTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
294 HighlightTag::SelfKeyword => semantic_tokens::SELF_KEYWORD,
295 HighlightTag::SelfType => lsp_types::SemanticTokenType::TYPE,
296 HighlightTag::Field => lsp_types::SemanticTokenType::PROPERTY,
297 HighlightTag::Function => lsp_types::SemanticTokenType::FUNCTION,
298 HighlightTag::Generic => semantic_tokens::GENERIC,
299 HighlightTag::Module => lsp_types::SemanticTokenType::NAMESPACE,
300 HighlightTag::Constant => {
301 mods |= semantic_tokens::CONSTANT;
302 mods |= lsp_types::SemanticTokenModifier::STATIC;
303 lsp_types::SemanticTokenType::VARIABLE
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,
327 HighlightTag::EscapeSequence => semantic_tokens::ESCAPE_SEQUENCE,
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,
346 pub(crate) fn folding_range(
348 line_index: &LineIndex,
349 line_folding_only: bool,
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,
358 let range = range(line_index, fold.range);
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
365 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
367 .take_while(|it| *it != '\n')
368 .any(|it| !it.is_whitespace());
370 let end_line = if has_more_text_on_end_line {
371 range.end.line.saturating_sub(1)
376 lsp_types::FoldingRange {
377 start_line: range.start.line,
378 start_character: None,
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),
394 pub(crate) fn url(snap: &GlobalStateSnapshot, file_id: FileId) -> lsp_types::Url {
395 snap.file_id_to_url(file_id)
398 /// Returns a `Url` object from a given path, will lowercase drive letters if present.
399 /// This will only happen when processing windows paths.
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(_)) =>
408 // Need to lowercase driver letter
413 let driver_letter_range = {
414 let (scheme, drive_letter, _rest) = match url.as_str().splitn(3, ':').collect_tuple() {
418 let start = scheme.len() + ':'.len_utf8();
419 start..(start + drive_letter.len())
422 // Note: lowercasing the `path` itself doesn't help, the `Url::parse`
423 // machinery *also* canonicalizes the drive letter. So, just massage the
425 let mut url = url.into_string();
426 url[driver_letter_range].make_ascii_lowercase();
427 lsp_types::Url::parse(&url).unwrap()
430 pub(crate) fn versioned_text_document_identifier(
431 snap: &GlobalStateSnapshot,
433 version: Option<i64>,
434 ) -> lsp_types::VersionedTextDocumentIdentifier {
435 lsp_types::VersionedTextDocumentIdentifier { uri: url(snap, file_id), version }
438 pub(crate) fn location(
439 snap: &GlobalStateSnapshot,
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);
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 {
456 let line_index = snap.analysis().file_line_index(src.file_id)?;
457 let range = range(&line_index, src.range);
462 let (target_uri, target_range, target_selection_range) = location_info(snap, target)?;
463 let res = lsp_types::LocationLink {
464 origin_selection_range,
467 target_selection_range,
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())?;
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))
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 {
493 .map(|nav| location_link(snap, src, nav))
494 .collect::<Result<Vec<_>>>()?;
497 let locations = targets
503 file_id: nav.file_id(),
504 range: nav.focus_range().unwrap_or(nav.range()),
508 .collect::<Result<Vec<_>>>()?;
513 pub(crate) fn snippet_text_document_edit(
514 snap: &GlobalStateSnapshot,
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
524 .map(|it| snippet_text_edit(&line_index, line_endings, is_snippet, it))
526 Ok(lsp_ext::SnippetTextDocumentEdit { text_document, edits })
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 })
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 })
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));
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));
560 lsp_ext::SnippetWorkspaceEdit { changes: None, document_changes: Some(document_changes) };
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())
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 {
576 document_changes: snippet_workspace_edit.document_changes.map(|changes| {
577 lsp_types::DocumentChanges::Operations(
580 .map(|change| match change {
581 lsp_ext::SnippetDocumentChangeOperation::Op(op) => {
582 lsp_types::DocumentChangeOperation::Op(op)
584 lsp_ext::SnippetDocumentChangeOperation::Edit(edit) => {
585 lsp_types::DocumentChangeOperation::Edit(
586 lsp_types::TextDocumentEdit {
587 text_document: edit.text_document,
591 .map(|edit| lsp_types::TextEdit {
593 new_text: edit.new_text,
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 })
618 pub(crate) fn unresolved_code_action(
619 snap: &GlobalStateSnapshot,
622 ) -> Result<lsp_ext::CodeAction> {
623 let res = lsp_ext::CodeAction {
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()),
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 {
642 edit: Some(snippet_workspace_edit(snap, change)?),
648 pub(crate) fn runnable(
649 snap: &GlobalStateSnapshot,
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)?;
661 Ok(lsp_ext::Runnable {
663 location: Some(location),
664 kind: lsp_ext::RunnableKind::Cargo,
665 args: lsp_ext::CargoRunnable {
666 workspace_root: workspace_root.map(|it| it.into()),
675 use test_utils::extract_ranges;
680 fn conv_fold_line_folding_only_fixup() {
681 let text = r#"<fold>mod a;
688 }</fold> else <fold>{
693 let (ranges, text) = extract_ranges(text, "fold");
694 assert_eq!(ranges.len(), 4);
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 },
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();
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);
716 // `Url` is not able to parse windows paths on unix machines.
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");
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");