Debian Codegraph @

third-party/rust-demangle/test-harness/src/lib.rs

raw
1 use std::fmt;
2
3 // HACK(eddyb) helper macros for tests.
4 #[macro_export]
5 macro_rules! assert_contains {
6 ($s:expr, $needle:expr) => {{
7 let (s, needle) = ($s, $needle);
8 assert!(
9 s.contains(needle),
10 "{:?} should've contained {:?}",
11 s,
12 needle
13 );
14 }};
15 }
16 #[macro_export]
17 macro_rules! assert_ends_with {
18 ($s:expr, $suffix:expr) => {{
19 let (s, suffix) = ($s, $suffix);
20 assert!(
21 s.ends_with(suffix),
22 "{:?} should've ended in {:?}",
23 s,
24 suffix
25 );
26 }};
27 }
28
29 /// `rustc_demangle::Demangle` wrapper that will also attempt demanging with
30 /// `rust-demangle.c`'s `rust_demangle` when formatted, and assert equality.
31 ///
32 /// The reason this mimics `rustc_demangle`'s API is to allow its tests to be
33 /// reused without rewriting them (which could risk introducing bugs).
34 pub struct Demangle<'a> {
35 // NOTE(eddyb) we don't trust `rustc_demangle` to keep the original string
36 // unmodified, as if it e.g. strips suffixes early, it could hide the fact
37 // that the C port doesn't have that sort of thing supported yet.
38 original: &'a str,
39
40 rustc_demangle: rustc_demangle::Demangle<'a>,
41 }
42
43 pub fn demangle(s: &str) -> Demangle {
44 Demangle {
45 original: s,
46 rustc_demangle: rustc_demangle::demangle(s),
47 }
48 }
49
50 pub fn try_demangle(s: &str) -> Result<Demangle<'_>, rustc_demangle::TryDemangleError> {
51 match rustc_demangle::try_demangle(s) {
52 Ok(d) => Ok(Demangle {
53 original: s,
54 rustc_demangle: d,
55 }),
56 Err(e) => {
57 assert!(demangle_via_c(s, false).is_err());
58
59 Err(e)
60 }
61 }
62 }
63
64 impl fmt::Display for Demangle<'_> {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 f.write_str(&self.to_string_maybe_verbose(!f.alternate()))
67 }
68 }
69
70 // HACK(eddyb) the C port doesn't have the "is printable Unicode" heuristic,
71 // to avoid having to include the non-trivial amount of data that requires,
72 // so instead we allow mismatches when `b` has more `\u{...}` escapes than `a`.
73 fn equal_modulo_unicode_escapes(a: &str, b: &str) -> bool {
74 let mut a_chars = a.chars();
75 let mut a_active_escape: Option<std::char::EscapeUnicode> = None;
76 let mut b_chars = b.chars();
77 loop {
78 let a_ch = a_active_escape
79 .as_mut()
80 .and_then(|escape| escape.next())
81 .or_else(|| {
82 a_active_escape = None;
83 a_chars.next()
84 });
85 let b_ch = b_chars.next();
86 match (a_ch, b_ch) {
87 (Some(a_ch), Some(b_ch)) if a_ch == b_ch => {}
88 // Compare with the `\u{...}` escape instead, if possible.
89 (Some(a_ch), Some('\\')) if a_active_escape.is_none() => {
90 let mut escape = a_ch.escape_unicode();
91 assert_eq!(escape.next(), Some('\\'));
92 a_active_escape = Some(escape);
93 }
94 (None, None) => return true,
95 _ => return false,
96 }
97 }
98 }
99
100 impl Demangle<'_> {
101 pub fn to_string_maybe_verbose(&self, verbose: bool) -> String {
102 let rust = if verbose {
103 format!("{}", self.rustc_demangle)
104 } else {
105 format!("{:#}", self.rustc_demangle)
106 };
107 let c = demangle_via_c(self.original, verbose).unwrap_or_else(|_| self.original.to_owned());
108 if rust != c && !equal_modulo_unicode_escapes(&rust, &c) {
109 panic!(
110 "Rust vs C demangling difference:\
111 \n mangled: {mangled:?}\
112 \n rust: {rust:?}\
113 \n c: {c:?}\
114 \n",
115 mangled = self.original
116 );
117 }
118
119 rust
120 }
121 }
122
123 fn demangle_via_c(mangled: &str, verbose: bool) -> Result<String, ()> {
124 use std::ffi::{CStr, CString};
125 use std::os::raw::c_char;
126
127 extern "C" {
128 fn rust_demangle(mangled: *const c_char, flags: i32) -> *mut c_char;
129 fn free(ptr: *mut c_char);
130 }
131
132 let flags = if verbose { 1 } else { 0 };
133 let Ok(mangled) = CString::new(mangled) else {
134 // C can't handle strings containing nul bytes
135 return Err(());
136 };
137 let out = unsafe { rust_demangle(mangled.as_ptr(), flags) };
138 if out.is_null() {
139 Err(())
140 } else {
141 unsafe {
142 let s = CStr::from_ptr(out).to_string_lossy().into_owned();
143 free(out);
144 Ok(s)
145 }
146 }
147 }