2 use rustc::hir::def_id::{CrateNum, DefId};
3 use rustc::hir::map::{DefPathData, DisambiguatedDefPathData};
4 use rustc::ty::print::{Print, Printer};
5 use rustc::ty::subst::{GenericArg, GenericArgKind, Subst};
6 use rustc::ty::{self, Instance, Ty, TyCtxt, TypeFoldable};
7 use rustc_data_structures::base_n;
8 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9 use rustc_target::spec::abi::Abi;
10 use syntax::ast::{FloatTy, IntTy, UintTy};
17 instance: Instance<'tcx>,
18 instantiating_crate: Option<CrateNum>,
20 let def_id = instance.def_id();
21 // FIXME(eddyb) this should ideally not be needed.
22 let substs = tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), instance.substs);
25 let mut cx = SymbolMangler {
27 compress: Some(Box::new(CompressionCaches {
28 start_offset: prefix.len(),
30 paths: FxHashMap::default(),
31 types: FxHashMap::default(),
32 consts: FxHashMap::default(),
35 out: String::from(prefix),
37 cx = if instance.is_vtable_shim() {
38 cx.path_append_ns(|cx| cx.print_def_path(def_id, substs), 'S', 0, "").unwrap()
40 cx.print_def_path(def_id, substs).unwrap()
42 if let Some(instantiating_crate) = instantiating_crate {
43 cx = cx.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap();
48 struct CompressionCaches<'tcx> {
49 // The length of the prefix in `out` (e.g. 2 for `_R`).
52 // The values are start positions in `out`, in bytes.
53 paths: FxHashMap<(DefId, &'tcx [GenericArg<'tcx>]), usize>,
54 types: FxHashMap<Ty<'tcx>, usize>,
55 consts: FxHashMap<&'tcx ty::Const<'tcx>, usize>,
59 /// The range of distances from the root of what's
60 /// being printed, to the lifetimes in a binder.
61 /// Specifically, a `BrAnon(i)` lifetime has depth
62 /// `lifetime_depths.start + i`, going away from the
63 /// the root and towards its use site, as `i` increases.
64 /// This is used to flatten rustc's pairing of `BrAnon`
65 /// (intra-binder disambiguation) with a `DebruijnIndex`
66 /// (binder addressing), to "true" de Bruijn indices,
67 /// by subtracting the depth of a certain lifetime, from
68 /// the innermost depth at its use site.
69 lifetime_depths: Range<u32>,
72 struct SymbolMangler<'tcx> {
74 compress: Option<Box<CompressionCaches<'tcx>>>,
75 binders: Vec<BinderLevel>,
79 impl SymbolMangler<'tcx> {
80 fn push(&mut self, s: &str) {
84 /// Push a `_`-terminated base 62 integer, using the format
85 /// specified in the RFC as `<base-62-number>`, that is:
86 /// * `x = 0` is encoded as just the `"_"` terminator
87 /// * `x > 0` is encoded as `x - 1` in base 62, followed by `"_"`,
88 /// e.g. `1` becomes `"0_"`, `62` becomes `"Z_"`, etc.
89 fn push_integer_62(&mut self, x: u64) {
90 if let Some(x) = x.checked_sub(1) {
91 base_n::push_str(x as u128, 62, &mut self.out);
96 /// Push a `tag`-prefixed base 62 integer, when larger than `0`, that is:
97 /// * `x = 0` is encoded as `""` (nothing)
98 /// * `x > 0` is encoded as the `tag` followed by `push_integer_62(x - 1)`
99 /// e.g. `1` becomes `tag + "_"`, `2` becomes `tag + "0_"`, etc.
100 fn push_opt_integer_62(&mut self, tag: &str, x: u64) {
101 if let Some(x) = x.checked_sub(1) {
103 self.push_integer_62(x);
107 fn push_disambiguator(&mut self, dis: u64) {
108 self.push_opt_integer_62("s", dis);
111 fn push_ident(&mut self, ident: &str) {
112 let mut use_punycode = false;
113 for b in ident.bytes() {
115 b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
116 0x80..=0xff => use_punycode = true,
117 _ => bug!("symbol_names: bad byte {} in ident {:?}", b, ident),
122 let ident = if use_punycode {
125 // FIXME(eddyb) we should probably roll our own punycode implementation.
126 let mut punycode_bytes = match ::punycode::encode(ident) {
127 Ok(s) => s.into_bytes(),
128 Err(()) => bug!("symbol_names: punycode encoding failed for ident {:?}", ident),
131 // Replace `-` with `_`.
132 if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
136 // FIXME(eddyb) avoid rechecking UTF-8 validity.
137 punycode_string = String::from_utf8(punycode_bytes).unwrap();
143 let _ = write!(self.out, "{}", ident.len());
145 // Write a separating `_` if necessary (leading digit or `_`).
146 match ident.chars().next() {
147 Some('_') | Some('0'..='9') => {
158 print_prefix: impl FnOnce(Self) -> Result<Self, !>,
162 ) -> Result<Self, !> {
165 self = print_prefix(self)?;
166 self.push_disambiguator(disambiguator as u64);
167 self.push_ident(name);
171 fn print_backref(mut self, i: usize) -> Result<Self, !> {
173 self.push_integer_62((i - self.compress.as_ref().unwrap().start_offset) as u64);
179 value: &ty::Binder<T>,
180 print_value: impl FnOnce(Self, &T) -> Result<Self, !>,
183 T: TypeFoldable<'tcx>,
185 let regions = if value.has_late_bound_regions() {
186 self.tcx.collect_referenced_late_bound_regions(value)
191 let mut lifetime_depths =
192 self.binders.last().map(|b| b.lifetime_depths.end).map_or(0..0, |i| i..i);
194 let lifetimes = regions
199 // FIXME(eddyb) for some reason, `anonymize_late_bound_regions` starts at `1`.
203 _ => bug!("symbol_names: non-anonymized region `{:?}` in `{:?}`", br, value),
207 .map_or(0, |max| max + 1);
209 self.push_opt_integer_62("G", lifetimes as u64);
210 lifetime_depths.end += lifetimes;
212 self.binders.push(BinderLevel { lifetime_depths });
213 self = print_value(self, value.skip_binder())?;
220 impl Printer<'tcx> for SymbolMangler<'tcx> {
226 type DynExistential = Self;
229 fn tcx(&self) -> TyCtxt<'tcx> {
236 substs: &'tcx [GenericArg<'tcx>],
237 ) -> Result<Self::Path, Self::Error> {
238 if let Some(&i) = self.compress.as_ref().and_then(|c| c.paths.get(&(def_id, substs))) {
239 return self.print_backref(i);
241 let start = self.out.len();
243 self = self.default_print_def_path(def_id, substs)?;
245 // Only cache paths that do not refer to an enclosing
246 // binder (which would change depending on context).
247 if !substs.iter().any(|k| k.has_escaping_bound_vars()) {
248 if let Some(c) = &mut self.compress {
249 c.paths.insert((def_id, substs), start);
258 substs: &'tcx [GenericArg<'tcx>],
259 mut self_ty: Ty<'tcx>,
260 mut impl_trait_ref: Option<ty::TraitRef<'tcx>>,
261 ) -> Result<Self::Path, Self::Error> {
262 let key = self.tcx.def_key(impl_def_id);
263 let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
265 let mut param_env = self.tcx.param_env(impl_def_id).with_reveal_all();
266 if !substs.is_empty() {
267 param_env = param_env.subst(self.tcx, substs);
270 match &mut impl_trait_ref {
271 Some(impl_trait_ref) => {
272 assert_eq!(impl_trait_ref.self_ty(), self_ty);
273 *impl_trait_ref = self.tcx.normalize_erasing_regions(param_env, *impl_trait_ref);
274 self_ty = impl_trait_ref.self_ty();
277 self_ty = self.tcx.normalize_erasing_regions(param_env, self_ty);
281 self.path_append_impl(
282 |cx| cx.print_def_path(parent_def_id, &[]),
283 &key.disambiguated_data,
289 fn print_region(mut self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
290 let i = match *region {
291 // Erased lifetimes use the index 0, for a
292 // shorter mangling of `L_`.
295 // Late-bound lifetimes use indices starting at 1,
296 // see `BinderLevel` for more details.
297 ty::ReLateBound(debruijn, ty::BrAnon(i)) => {
298 // FIXME(eddyb) for some reason, `anonymize_late_bound_regions` starts at `1`.
302 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
303 let depth = binder.lifetime_depths.start + i;
305 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
308 _ => bug!("symbol_names: non-erased region `{:?}`", region),
311 self.push_integer_62(i as u64);
315 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
316 // Basic types, never cached (single-character).
317 let basic_type = match ty.kind {
321 ty::Tuple(_) if ty.is_unit() => "u",
322 ty::Int(IntTy::I8) => "a",
323 ty::Int(IntTy::I16) => "s",
324 ty::Int(IntTy::I32) => "l",
325 ty::Int(IntTy::I64) => "x",
326 ty::Int(IntTy::I128) => "n",
327 ty::Int(IntTy::Isize) => "i",
328 ty::Uint(UintTy::U8) => "h",
329 ty::Uint(UintTy::U16) => "t",
330 ty::Uint(UintTy::U32) => "m",
331 ty::Uint(UintTy::U64) => "y",
332 ty::Uint(UintTy::U128) => "o",
333 ty::Uint(UintTy::Usize) => "j",
334 ty::Float(FloatTy::F32) => "f",
335 ty::Float(FloatTy::F64) => "d",
338 // Placeholders (should be demangled as `_`).
339 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error => "p",
343 if !basic_type.is_empty() {
344 self.push(basic_type);
348 if let Some(&i) = self.compress.as_ref().and_then(|c| c.types.get(&ty)) {
349 return self.print_backref(i);
351 let start = self.out.len();
354 // Basic types, handled above.
355 ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
358 ty::Tuple(_) if ty.is_unit() => unreachable!(),
360 // Placeholders, also handled as part of basic types.
361 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error => {
365 ty::Ref(r, ty, mutbl) => {
366 self.push(match mutbl {
367 hir::Mutability::Not => "R",
368 hir::Mutability::Mut => "Q",
370 if *r != ty::ReErased {
371 self = r.print(self)?;
373 self = ty.print(self)?;
377 self.push(match mt.mutbl {
378 hir::Mutability::Not => "P",
379 hir::Mutability::Mut => "O",
381 self = mt.ty.print(self)?;
384 ty::Array(ty, len) => {
386 self = ty.print(self)?;
387 self = self.print_const(len)?;
391 self = ty.print(self)?;
396 for ty in tys.iter().map(|k| k.expect_ty()) {
397 self = ty.print(self)?;
402 // Mangle all nominal types as paths.
403 ty::Adt(&ty::AdtDef { did: def_id, .. }, substs)
404 | ty::FnDef(def_id, substs)
405 | ty::Opaque(def_id, substs)
406 | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
407 | ty::UnnormalizedProjection(ty::ProjectionTy { item_def_id: def_id, substs })
408 | ty::Closure(def_id, substs)
409 | ty::Generator(def_id, substs, _) => {
410 self = self.print_def_path(def_id, substs)?;
412 ty::Foreign(def_id) => {
413 self = self.print_def_path(def_id, &[])?;
418 self = self.in_binder(&sig, |mut cx, sig| {
419 if sig.unsafety == hir::Unsafety::Unsafe {
424 Abi::C => cx.push("KC"),
427 let name = abi.name();
428 if name.contains('-') {
429 cx.push_ident(&name.replace('-', "_"));
435 for &ty in sig.inputs() {
442 sig.output().print(cx)
446 ty::Dynamic(predicates, r) => {
448 self = self.in_binder(&predicates, |cx, predicates| {
449 cx.print_dyn_existential(predicates)
451 self = r.print(self)?;
454 ty::GeneratorWitness(_) => bug!("symbol_names: unexpected `GeneratorWitness`"),
457 // Only cache types that do not refer to an enclosing
458 // binder (which would change depending on context).
459 if !ty.has_escaping_bound_vars() {
460 if let Some(c) = &mut self.compress {
461 c.types.insert(ty, start);
467 fn print_dyn_existential(
469 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
470 ) -> Result<Self::DynExistential, Self::Error> {
471 for predicate in predicates {
473 ty::ExistentialPredicate::Trait(trait_ref) => {
474 // Use a type that can't appear in defaults of type parameters.
475 let dummy_self = self.tcx.mk_ty_infer(ty::FreshTy(0));
476 let trait_ref = trait_ref.with_self_ty(self.tcx, dummy_self);
477 self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?;
479 ty::ExistentialPredicate::Projection(projection) => {
480 let name = self.tcx.associated_item(projection.item_def_id).ident;
482 self.push_ident(&name.as_str());
483 self = projection.ty.print(self)?;
485 ty::ExistentialPredicate::AutoTrait(def_id) => {
486 self = self.print_def_path(def_id, &[])?;
494 fn print_const(mut self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
495 if let Some(&i) = self.compress.as_ref().and_then(|c| c.consts.get(&ct)) {
496 return self.print_backref(i);
498 let start = self.out.len();
503 bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct.ty, ct);
506 self = ct.ty.print(self)?;
508 if let Some(bits) = ct.try_eval_bits(self.tcx, ty::ParamEnv::reveal_all(), ct.ty) {
509 let _ = write!(self.out, "{:x}_", bits);
511 // NOTE(eddyb) despite having the path, we need to
512 // encode a placeholder, as the path could refer
513 // back to e.g. an `impl` using the constant.
517 // Only cache consts that do not refer to an enclosing
518 // binder (which would change depending on context).
519 if !ct.has_escaping_bound_vars() {
520 if let Some(c) = &mut self.compress {
521 c.consts.insert(ct, start);
527 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
529 let fingerprint = self.tcx.crate_disambiguator(cnum).to_fingerprint();
530 self.push_disambiguator(fingerprint.to_smaller_hash());
531 let name = self.tcx.original_crate_name(cnum).as_str();
532 self.push_ident(&name);
538 trait_ref: Option<ty::TraitRef<'tcx>>,
539 ) -> Result<Self::Path, Self::Error> {
540 assert!(trait_ref.is_some());
541 let trait_ref = trait_ref.unwrap();
544 self = self_ty.print(self)?;
545 self.print_def_path(trait_ref.def_id, trait_ref.substs)
550 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
551 disambiguated_data: &DisambiguatedDefPathData,
553 trait_ref: Option<ty::TraitRef<'tcx>>,
554 ) -> Result<Self::Path, Self::Error> {
555 self.push(match trait_ref {
559 self.push_disambiguator(disambiguated_data.disambiguator as u64);
560 self = print_prefix(self)?;
561 self = self_ty.print(self)?;
562 if let Some(trait_ref) = trait_ref {
563 self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?;
569 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
570 disambiguated_data: &DisambiguatedDefPathData,
571 ) -> Result<Self::Path, Self::Error> {
572 let ns = match disambiguated_data.data {
573 // Uppercase categories are more stable than lowercase ones.
574 DefPathData::TypeNs(_) => 't',
575 DefPathData::ValueNs(_) => 'v',
576 DefPathData::ClosureExpr => 'C',
577 DefPathData::Ctor => 'c',
578 DefPathData::AnonConst => 'k',
579 DefPathData::ImplTrait => 'i',
581 // These should never show up as `path_append` arguments.
582 DefPathData::CrateRoot
585 | DefPathData::MacroNs(_)
586 | DefPathData::LifetimeNs(_) => {
587 bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
591 let name = disambiguated_data.data.get_opt_name().map(|s| s.as_str());
596 disambiguated_data.disambiguator as u64,
597 name.as_ref().map_or("", |s| &s[..]),
600 fn path_generic_args(
602 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
603 args: &[GenericArg<'tcx>],
604 ) -> Result<Self::Path, Self::Error> {
605 // Don't print any regions if they're all erased.
606 let print_regions = args.iter().any(|arg| match arg.unpack() {
607 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
610 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
611 GenericArgKind::Lifetime(_) => print_regions,
615 if args.clone().next().is_none() {
616 return print_prefix(self);
620 self = print_prefix(self)?;
623 GenericArgKind::Lifetime(lt) => {
624 self = lt.print(self)?;
626 GenericArgKind::Type(ty) => {
627 self = ty.print(self)?;
629 GenericArgKind::Const(c) => {
631 // FIXME(const_generics) implement `ty::print::Print` on `ty::Const`.
632 // self = c.print(self)?;
633 self = self.print_const(c)?;