Debian Codegraph @

third_party/rust/rustc-demangle/src/lib.rs

raw
1 //! Demangle Rust compiler symbol names.
2 //!
3 //! This crate provides a `demangle` function which will return a `Demangle`
4 //! sentinel value that can be used to learn about the demangled version of a
5 //! symbol name. The demangled representation will be the same as the original
6 //! if it doesn't look like a mangled symbol name.
7 //!
8 //! `Demangle` can be formatted with the `Display` trait. The alternate
9 //! modifier (`#`) can be used to format the symbol name without the
10 //! trailing hash value.
11 //!
12 //! # Examples
13 //!
14 //! ```
15 //! use rustc_demangle::demangle;
16 //!
17 //! assert_eq!(demangle("_ZN4testE").to_string(), "test");
18 //! assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar");
19 //! assert_eq!(demangle("foo").to_string(), "foo");
20 //! // With hash
21 //! assert_eq!(format!("{}", demangle("_ZN3foo17h05af221e174051e9E")), "foo::h05af221e174051e9");
22 //! // Without hash
23 //! assert_eq!(format!("{:#}", demangle("_ZN3foo17h05af221e174051e9E")), "foo");
24 //! ```
25
26 #![no_std]
27 #![deny(missing_docs)]
28
29 #[cfg(test)]
30 #[macro_use]
31 extern crate std;
32
33 // HACK(eddyb) helper macros for tests.
34 #[cfg(test)]
35 macro_rules! assert_contains {
36 ($s:expr, $needle:expr) => {{
37 let (s, needle) = ($s, $needle);
38 assert!(
39 s.contains(needle),
40 "{:?} should've contained {:?}",
41 s,
42 needle
43 );
44 }};
45 }
46 #[cfg(test)]
47 macro_rules! assert_ends_with {
48 ($s:expr, $suffix:expr) => {{
49 let (s, suffix) = ($s, $suffix);
50 assert!(
51 s.ends_with(suffix),
52 "{:?} should've ended in {:?}",
53 s,
54 suffix
55 );
56 }};
57 }
58
59 mod legacy;
60 mod v0;
61
62 use core::fmt::{self, Write as _};
63
64 /// Representation of a demangled symbol name.
65 pub struct Demangle<'a> {
66 style: Option<DemangleStyle<'a>>,
67 original: &'a str,
68 suffix: &'a str,
69 }
70
71 enum DemangleStyle<'a> {
72 Legacy(legacy::Demangle<'a>),
73 V0(v0::Demangle<'a>),
74 }
75
76 /// De-mangles a Rust symbol into a more readable version
77 ///
78 /// This function will take a **mangled** symbol and return a value. When printed,
79 /// the de-mangled version will be written. If the symbol does not look like
80 /// a mangled symbol, the original value will be written instead.
81 ///
82 /// # Examples
83 ///
84 /// ```
85 /// use rustc_demangle::demangle;
86 ///
87 /// assert_eq!(demangle("_ZN4testE").to_string(), "test");
88 /// assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar");
89 /// assert_eq!(demangle("foo").to_string(), "foo");
90 /// ```
91 pub fn demangle(mut s: &str) -> Demangle {
92 // During ThinLTO LLVM may import and rename internal symbols, so strip out
93 // those endings first as they're one of the last manglings applied to symbol
94 // names.
95 let llvm = ".llvm.";
96 if let Some(i) = s.find(llvm) {
97 let candidate = &s[i + llvm.len()..];
98 let all_hex = candidate.chars().all(|c| match c {
99 'A'..='F' | '0'..='9' | '@' => true,
100 _ => false,
101 });
102
103 if all_hex {
104 s = &s[..i];
105 }
106 }
107
108 let mut suffix = "";
109 let mut style = match legacy::demangle(s) {
110 Ok((d, s)) => {
111 suffix = s;
112 Some(DemangleStyle::Legacy(d))
113 }
114 Err(()) => match v0::demangle(s) {
115 Ok((d, s)) => {
116 suffix = s;
117 Some(DemangleStyle::V0(d))
118 }
119 // FIXME(eddyb) would it make sense to treat an unknown-validity
120 // symbol (e.g. one that errored with `RecursedTooDeep`) as
121 // v0-mangled, and have the error show up in the demangling?
122 // (that error already gets past this initial check, and therefore
123 // will show up in the demangling, if hidden behind a backref)
124 Err(v0::ParseError::Invalid) | Err(v0::ParseError::RecursedTooDeep) => None,
125 },
126 };
127
128 // Output like LLVM IR adds extra period-delimited words. See if
129 // we are in that case and save the trailing words if so.
130 if !suffix.is_empty() {
131 if suffix.starts_with('.') && is_symbol_like(suffix) {
132 // Keep the suffix.
133 } else {
134 // Reset the suffix and invalidate the demangling.
135 suffix = "";
136 style = None;
137 }
138 }
139
140 Demangle {
141 style,
142 original: s,
143 suffix,
144 }
145 }
146
147 /// Error returned from the `try_demangle` function below when demangling fails.
148 #[derive(Debug, Clone)]
149 pub struct TryDemangleError {
150 _priv: (),
151 }
152
153 /// The same as `demangle`, except return an `Err` if the string does not appear
154 /// to be a Rust symbol, rather than "demangling" the given string as a no-op.
155 ///
156 /// ```
157 /// extern crate rustc_demangle;
158 ///
159 /// let not_a_rust_symbol = "la la la";
160 ///
161 /// // The `try_demangle` function will reject strings which are not Rust symbols.
162 /// assert!(rustc_demangle::try_demangle(not_a_rust_symbol).is_err());
163 ///
164 /// // While `demangle` will just pass the non-symbol through as a no-op.
165 /// assert_eq!(rustc_demangle::demangle(not_a_rust_symbol).as_str(), not_a_rust_symbol);
166 /// ```
167 pub fn try_demangle(s: &str) -> Result<Demangle, TryDemangleError> {
168 let sym = demangle(s);
169 if sym.style.is_some() {
170 Ok(sym)
171 } else {
172 Err(TryDemangleError { _priv: () })
173 }
174 }
175
176 impl<'a> Demangle<'a> {
177 /// Returns the underlying string that's being demangled.
178 pub fn as_str(&self) -> &'a str {
179 self.original
180 }
181 }
182
183 fn is_symbol_like(s: &str) -> bool {
184 s.chars().all(|c| {
185 // Once `char::is_ascii_punctuation` and `char::is_ascii_alphanumeric`
186 // have been stable for long enough, use those instead for clarity
187 is_ascii_alphanumeric(c) || is_ascii_punctuation(c)
188 })
189 }
190
191 // Copied from the documentation of `char::is_ascii_alphanumeric`
192 fn is_ascii_alphanumeric(c: char) -> bool {
193 match c {
194 '\u{0041}'..='\u{005A}' | '\u{0061}'..='\u{007A}' | '\u{0030}'..='\u{0039}' => true,
195 _ => false,
196 }
197 }
198
199 // Copied from the documentation of `char::is_ascii_punctuation`
200 fn is_ascii_punctuation(c: char) -> bool {
201 match c {
202 '\u{0021}'..='\u{002F}'
203 | '\u{003A}'..='\u{0040}'
204 | '\u{005B}'..='\u{0060}'
205 | '\u{007B}'..='\u{007E}' => true,
206 _ => false,
207 }
208 }
209
210 impl<'a> fmt::Display for DemangleStyle<'a> {
211 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
212 match *self {
213 DemangleStyle::Legacy(ref d) => fmt::Display::fmt(d, f),
214 DemangleStyle::V0(ref d) => fmt::Display::fmt(d, f),
215 }
216 }
217 }
218
219 // Maximum size of the symbol that we'll print.
220 const MAX_SIZE: usize = 1_000_000;
221
222 #[derive(Copy, Clone, Debug)]
223 struct SizeLimitExhausted;
224
225 struct SizeLimitedFmtAdapter<F> {
226 remaining: Result<usize, SizeLimitExhausted>,
227 inner: F,
228 }
229
230 impl<F: fmt::Write> fmt::Write for SizeLimitedFmtAdapter<F> {
231 fn write_str(&mut self, s: &str) -> fmt::Result {
232 self.remaining = self
233 .remaining
234 .and_then(|r| r.checked_sub(s.len()).ok_or(SizeLimitExhausted));
235
236 match self.remaining {
237 Ok(_) => self.inner.write_str(s),
238 Err(SizeLimitExhausted) => Err(fmt::Error),
239 }
240 }
241 }
242
243 impl<'a> fmt::Display for Demangle<'a> {
244 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
245 match self.style {
246 None => f.write_str(self.original)?,
247 Some(ref d) => {
248 let alternate = f.alternate();
249 let mut size_limited_fmt = SizeLimitedFmtAdapter {
250 remaining: Ok(MAX_SIZE),
251 inner: &mut *f,
252 };
253 let fmt_result = if alternate {
254 write!(size_limited_fmt, "{:#}", d)
255 } else {
256 write!(size_limited_fmt, "{}", d)
257 };
258 let size_limit_result = size_limited_fmt.remaining.map(|_| ());
259
260 // Translate a `fmt::Error` generated by `SizeLimitedFmtAdapter`
261 // into an error message, instead of propagating it upwards
262 // (which could cause panicking from inside e.g. `std::io::print`).
263 match (fmt_result, size_limit_result) {
264 (Err(_), Err(SizeLimitExhausted)) => f.write_str("{size limit reached}")?,
265
266 _ => {
267 fmt_result?;
268 size_limit_result
269 .expect("`fmt::Error` from `SizeLimitedFmtAdapter` was discarded");
270 }
271 }
272 }
273 }
274 f.write_str(self.suffix)
275 }
276 }
277
278 impl<'a> fmt::Debug for Demangle<'a> {
279 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
280 fmt::Display::fmt(self, f)
281 }
282 }
283
284 #[cfg(test)]
285 mod tests {
286 use std::prelude::v1::*;
287
288 macro_rules! t {
289 ($a:expr, $b:expr) => {
290 assert!(ok($a, $b))
291 };
292 }
293
294 macro_rules! t_err {
295 ($a:expr) => {
296 assert!(ok_err($a))
297 };
298 }
299
300 macro_rules! t_nohash {
301 ($a:expr, $b:expr) => {{
302 assert_eq!(format!("{:#}", super::demangle($a)), $b);
303 }};
304 }
305
306 fn ok(sym: &str, expected: &str) -> bool {
307 match super::try_demangle(sym) {
308 Ok(s) => {
309 if s.to_string() == expected {
310 true
311 } else {
312 println!("\n{}\n!=\n{}\n", s, expected);
313 false
314 }
315 }
316 Err(_) => {
317 println!("error demangling");
318 false
319 }
320 }
321 }
322
323 fn ok_err(sym: &str) -> bool {
324 match super::try_demangle(sym) {
325 Ok(_) => {
326 println!("succeeded in demangling");
327 false
328 }
329 Err(_) => super::demangle(sym).to_string() == sym,
330 }
331 }
332
333 #[test]
334 fn demangle() {
335 t_err!("test");
336 t!("_ZN4testE", "test");
337 t_err!("_ZN4test");
338 t!("_ZN4test1a2bcE", "test::a::bc");
339 }
340
341 #[test]
342 fn demangle_dollars() {
343 t!("_ZN4$RP$E", ")");
344 t!("_ZN8$RF$testE", "&test");
345 t!("_ZN8$BP$test4foobE", "*test::foob");
346 t!("_ZN9$u20$test4foobE", " test::foob");
347 t!("_ZN35Bar$LT$$u5b$u32$u3b$$u20$4$u5d$$GT$E", "Bar<[u32; 4]>");
348 }
349
350 #[test]
351 fn demangle_many_dollars() {
352 t!("_ZN13test$u20$test4foobE", "test test::foob");
353 t!("_ZN12test$BP$test4foobE", "test*test::foob");
354 }
355
356 #[test]
357 fn demangle_osx() {
358 t!(
359 "__ZN5alloc9allocator6Layout9for_value17h02a996811f781011E",
360 "alloc::allocator::Layout::for_value::h02a996811f781011"
361 );
362 t!("__ZN38_$LT$core..option..Option$LT$T$GT$$GT$6unwrap18_MSG_FILE_LINE_COL17haf7cb8d5824ee659E", "<core::option::Option<T>>::unwrap::_MSG_FILE_LINE_COL::haf7cb8d5824ee659");
363 t!("__ZN4core5slice89_$LT$impl$u20$core..iter..traits..IntoIterator$u20$for$u20$$RF$$u27$a$u20$$u5b$T$u5d$$GT$9into_iter17h450e234d27262170E", "core::slice::<impl core::iter::traits::IntoIterator for &'a [T]>::into_iter::h450e234d27262170");
364 }
365
366 #[test]
367 fn demangle_windows() {
368 t!("ZN4testE", "test");
369 t!("ZN13test$u20$test4foobE", "test test::foob");
370 t!("ZN12test$RF$test4foobE", "test&test::foob");
371 }
372
373 #[test]
374 fn demangle_elements_beginning_with_underscore() {
375 t!("_ZN13_$LT$test$GT$E", "<test>");
376 t!("_ZN28_$u7b$$u7b$closure$u7d$$u7d$E", "{{closure}}");
377 t!("_ZN15__STATIC_FMTSTRE", "__STATIC_FMTSTR");
378 }
379
380 #[test]
381 fn demangle_trait_impls() {
382 t!(
383 "_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE",
384 "<Test + 'static as foo::Bar<Test>>::bar"
385 );
386 }
387
388 #[test]
389 fn demangle_without_hash() {
390 let s = "_ZN3foo17h05af221e174051e9E";
391 t!(s, "foo::h05af221e174051e9");
392 t_nohash!(s, "foo");
393 }
394
395 #[test]
396 fn demangle_without_hash_edgecases() {
397 // One element, no hash.
398 t_nohash!("_ZN3fooE", "foo");
399 // Two elements, no hash.
400 t_nohash!("_ZN3foo3barE", "foo::bar");
401 // Longer-than-normal hash.
402 t_nohash!("_ZN3foo20h05af221e174051e9abcE", "foo");
403 // Shorter-than-normal hash.
404 t_nohash!("_ZN3foo5h05afE", "foo");
405 // Valid hash, but not at the end.
406 t_nohash!("_ZN17h05af221e174051e93fooE", "h05af221e174051e9::foo");
407 // Not a valid hash, missing the 'h'.
408 t_nohash!("_ZN3foo16ffaf221e174051e9E", "foo::ffaf221e174051e9");
409 // Not a valid hash, has a non-hex-digit.
410 t_nohash!("_ZN3foo17hg5af221e174051e9E", "foo::hg5af221e174051e9");
411 }
412
413 #[test]
414 fn demangle_thinlto() {
415 // One element, no hash.
416 t!("_ZN3fooE.llvm.9D1C9369", "foo");
417 t!("_ZN3fooE.llvm.9D1C9369@@16", "foo");
418 t_nohash!(
419 "_ZN9backtrace3foo17hbb467fcdaea5d79bE.llvm.A5310EB9",
420 "backtrace::foo"
421 );
422 }
423
424 #[test]
425 fn demangle_llvm_ir_branch_labels() {
426 t!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice::<impl core::ops::index::IndexMut<I> for [T]>::index_mut::haf9727c2edfbc47b.exit.i.i");
427 t_nohash!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice::<impl core::ops::index::IndexMut<I> for [T]>::index_mut.exit.i.i");
428 }
429
430 #[test]
431 fn demangle_ignores_suffix_that_doesnt_look_like_a_symbol() {
432 t_err!("_ZN3fooE.llvm moocow");
433 }
434
435 #[test]
436 fn dont_panic() {
437 super::demangle("_ZN2222222222222222222222EE").to_string();
438 super::demangle("_ZN5*70527e27.ll34csaғE").to_string();
439 super::demangle("_ZN5*70527a54.ll34_$b.1E").to_string();
440 super::demangle(
441 "\
442 _ZN5~saäb4e\n\
443 2734cOsbE\n\
444 5usage20h)3\0\0\0\0\0\0\07e2734cOsbE\
445 ",
446 )
447 .to_string();
448 }
449
450 #[test]
451 fn invalid_no_chop() {
452 t_err!("_ZNfooE");
453 }
454
455 #[test]
456 fn handle_assoc_types() {
457 t!("_ZN151_$LT$alloc..boxed..Box$LT$alloc..boxed..FnBox$LT$A$C$$u20$Output$u3d$R$GT$$u20$$u2b$$u20$$u27$a$GT$$u20$as$u20$core..ops..function..FnOnce$LT$A$GT$$GT$9call_once17h69e8f44b3723e1caE", "<alloc::boxed::Box<alloc::boxed::FnBox<A, Output=R> + 'a> as core::ops::function::FnOnce<A>>::call_once::h69e8f44b3723e1ca");
458 }
459
460 #[test]
461 fn handle_bang() {
462 t!(
463 "_ZN88_$LT$core..result..Result$LT$$u21$$C$$u20$E$GT$$u20$as$u20$std..process..Termination$GT$6report17hfc41d0da4a40b3e8E",
464 "<core::result::Result<!, E> as std::process::Termination>::report::hfc41d0da4a40b3e8"
465 );
466 }
467
468 #[test]
469 fn limit_recursion() {
470 assert_contains!(
471 super::demangle("_RNvB_1a").to_string(),
472 "{recursion limit reached}"
473 );
474 assert_contains!(
475 super::demangle("_RMC0RB2_").to_string(),
476 "{recursion limit reached}"
477 );
478 }
479
480 #[test]
481 fn limit_output() {
482 assert_ends_with!(
483 super::demangle("RYFG_FGyyEvRYFF_EvRYFFEvERLB_B_B_ERLRjB_B_B_").to_string(),
484 "{size limit reached}"
485 );
486 // NOTE(eddyb) somewhat reduced version of the above, effectively
487 // `<for<...> fn()>` with a larger number of lifetimes in `...`.
488 assert_ends_with!(
489 super::demangle("_RMC0FGZZZ_Eu").to_string(),
490 "{size limit reached}"
491 );
492 }
493 }