| 1 |
#![allow(unstable_name_collisions)] // Intentional! |
| 2 |
|
| 3 |
use proc_macro::Span; |
| 4 |
use std::path::{Path, PathBuf}; |
| 5 |
|
| 6 |
/// Trait providing a fallback method for `Span` methods. |
| 7 |
#[allow(unused)] |
| 8 |
pub(crate) trait FallbackSpan { |
| 9 |
fn line(&self) -> usize; |
| 10 |
fn column(&self) -> usize; |
| 11 |
fn file(&self) -> String; |
| 12 |
fn local_file(&self) -> Option<PathBuf>; |
| 13 |
fn source_text(&self) -> Option<String>; |
| 14 |
} |
| 15 |
|
| 16 |
/// Implement it for references of Span using autoref, giving it lower priority |
| 17 |
/// than inherent methods. |
| 18 |
impl FallbackSpan for &Span { |
| 19 |
#[inline(always)] |
| 20 |
fn line(&self) -> usize { |
| 21 |
0 |
| 22 |
} |
| 23 |
#[inline(always)] |
| 24 |
fn column(&self) -> usize { |
| 25 |
0 |
| 26 |
} |
| 27 |
#[inline(always)] |
| 28 |
fn file(&self) -> String { |
| 29 |
String::new() |
| 30 |
} |
| 31 |
#[inline(always)] |
| 32 |
fn local_file(&self) -> Option<PathBuf> { |
| 33 |
None |
| 34 |
} |
| 35 |
#[inline(always)] |
| 36 |
fn source_text(&self) -> Option<String> { |
| 37 |
None |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
#[allow(unused, clippy::needless_borrow)] |
| 42 |
pub(crate) fn has_1_88_span_methods(span: Span) -> bool { |
| 43 |
let line_val = (&span).line(); |
| 44 |
|
| 45 |
// If it returns 0, we are on an older compiler. |
| 46 |
line_val != 0 |
| 47 |
} |
| 48 |
|
| 49 |
#[inline(always)] |
| 50 |
pub(crate) fn file(span: &Span) -> String { |
| 51 |
let file = span.file(); |
| 52 |
let path = Path::new(&file); |
| 53 |
if path.is_absolute() { |
| 54 |
// Rust 1.88..1.94 reports dependency-crate spans as absolute paths when |
| 55 |
// inspected from a downstream crate, while the defining crate sees the |
| 56 |
// working-directory-relative form. Relativise against rustc's working |
| 57 |
// directory so both agree, fall back to the file name otherwise (e.g. |
| 58 |
// `cargo expand`, whose paths are not under the working directory). |
| 59 |
std::env::current_dir() |
| 60 |
.ok() |
| 61 |
.and_then(|cwd| path.strip_prefix(&cwd).ok().map(Path::to_path_buf)) |
| 62 |
.map(|rel| rel.to_string_lossy().into_owned()) |
| 63 |
.unwrap_or_else(|| { |
| 64 |
path.file_name() |
| 65 |
.unwrap_or_default() |
| 66 |
.to_string_lossy() |
| 67 |
.into_owned() |
| 68 |
}) |
| 69 |
} else { |
| 70 |
file |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
#[inline(always)] |
| 75 |
pub(crate) fn line(span: &Span) -> usize { |
| 76 |
span.line() |
| 77 |
} |
| 78 |
|
| 79 |
#[inline(always)] |
| 80 |
pub(crate) fn local_file(span: &Span) -> Option<PathBuf> { |
| 81 |
span.local_file() |
| 82 |
} |
| 83 |
|
| 84 |
#[inline(always)] |
| 85 |
pub(crate) fn column(span: &Span) -> usize { |
| 86 |
span.column() |
| 87 |
} |
| 88 |
|
| 89 |
#[inline(always)] |
| 90 |
pub(crate) fn source_text(span: &Span) -> Option<String> { |
| 91 |
span.source_text() |
| 92 |
} |