2 use rustc::hir::def_id::{CrateNum, DefId};
3 use rustc::hir::map::{DefPathData, DisambiguatedDefPathData};
4 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable, Instance};
5 use rustc::ty::print::{Printer, Print};
6 use rustc::ty::subst::{Kind, Subst, UnpackedKind};
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::{IntTy, UintTy, FloatTy};
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.
23 tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), instance.substs);
26 let mut cx = SymbolMangler {
28 compress: Some(Box::new(CompressionCaches {
29 start_offset: prefix.len(),
31 paths: FxHashMap::default(),
32 types: FxHashMap::default(),
33 consts: FxHashMap::default(),
36 out: String::from(prefix),
38 cx = if instance.is_vtable_shim() {
40 |cx| cx.print_def_path(def_id, substs),
46 cx.print_def_path(def_id, substs).unwrap()
48 if let Some(instantiating_crate) = instantiating_crate {
49 cx = cx.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap();
54 struct CompressionCaches<'tcx> {
55 // The length of the prefix in `out` (e.g. 2 for `_R`).
58 // The values are start positions in `out`, in bytes.
59 paths: FxHashMap<(DefId, &'tcx [Kind<'tcx>]), usize>,
60 types: FxHashMap<Ty<'tcx>, usize>,
61 consts: FxHashMap<&'tcx ty::Const<'tcx>, usize>,
65 /// The range of distances from the root of what's
66 /// being printed, to the lifetimes in a binder.
67 /// Specifically, a `BrAnon(i)` lifetime has depth
68 /// `lifetime_depths.start + i`, going away from the
69 /// the root and towards its use site, as `i` increases.
70 /// This is used to flatten rustc's pairing of `BrAnon`
71 /// (intra-binder disambiguation) with a `DebruijnIndex`
72 /// (binder addressing), to "true" de Bruijn indices,
73 /// by subtracting the depth of a certain lifetime, from
74 /// the innermost depth at its use site.
75 lifetime_depths: Range<u32>,
78 struct SymbolMangler<'tcx> {
80 compress: Option<Box<CompressionCaches<'tcx>>>,
81 binders: Vec<BinderLevel>,
85 impl SymbolMangler<'tcx> {
86 fn push(&mut self, s: &str) {
90 /// Push a `_`-terminated base 62 integer, using the format
91 /// specified in the RFC as `<base-62-number>`, that is:
92 /// * `x = 0` is encoded as just the `"_"` terminator
93 /// * `x > 0` is encoded as `x - 1` in base 62, followed by `"_"`,
94 /// e.g. `1` becomes `"0_"`, `62` becomes `"Z_"`, etc.
95 fn push_integer_62(&mut self, x: u64) {
96 if let Some(x) = x.checked_sub(1) {
97 base_n::push_str(x as u128, 62, &mut self.out);
102 /// Push a `tag`-prefixed base 62 integer, when larger than `0`, that is:
103 /// * `x = 0` is encoded as `""` (nothing)
104 /// * `x > 0` is encoded as the `tag` followed by `push_integer_62(x - 1)`
105 /// e.g. `1` becomes `tag + "_"`, `2` becomes `tag + "0_"`, etc.
106 fn push_opt_integer_62(&mut self, tag: &str, x: u64) {
107 if let Some(x) = x.checked_sub(1) {
109 self.push_integer_62(x);
113 fn push_disambiguator(&mut self, dis: u64) {
114 self.push_opt_integer_62("s", dis);
117 fn push_ident(&mut self, ident: &str) {
118 let mut use_punycode = false;
119 for b in ident.bytes() {
121 b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
122 0x80..=0xff => use_punycode = true,
123 _ => bug!("symbol_names: bad byte {} in ident {:?}", b, ident),
128 let ident = if use_punycode {
131 // FIXME(eddyb) we should probably roll our own punycode implementation.
132 let mut punycode_bytes = match ::punycode::encode(ident) {
133 Ok(s) => s.into_bytes(),
134 Err(()) => bug!("symbol_names: punycode encoding failed for ident {:?}", ident),
137 // Replace `-` with `_`.
138 if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
142 // FIXME(eddyb) avoid rechecking UTF-8 validity.
143 punycode_string = String::from_utf8(punycode_bytes).unwrap();
149 let _ = write!(self.out, "{}", ident.len());
151 // Write a separating `_` if necessary (leading digit or `_`).
152 match ident.chars().next() {
153 Some('_') | Some('0'..='9') => {
164 print_prefix: impl FnOnce(Self) -> Result<Self, !>,
168 ) -> Result<Self, !> {
171 self = print_prefix(self)?;
172 self.push_disambiguator(disambiguator as u64);
173 self.push_ident(name);
177 fn print_backref(mut self, i: usize) -> Result<Self, !> {
179 self.push_integer_62((i - self.compress.as_ref().unwrap().start_offset) as u64);
185 value: &ty::Binder<T>,
186 print_value: impl FnOnce(Self, &T) -> Result<Self, !>
188 where T: TypeFoldable<'tcx>
190 let regions = if value.has_late_bound_regions() {
191 self.tcx.collect_referenced_late_bound_regions(value)
196 let mut lifetime_depths =
197 self.binders.last().map(|b| b.lifetime_depths.end).map_or(0..0, |i| i..i);
199 let lifetimes = regions.into_iter().map(|br| {
201 ty::BrAnon(i) => i + 1,
202 _ => bug!("symbol_names: non-anonymized region `{:?}` in `{:?}`", br, value),
204 }).max().unwrap_or(0);
206 self.push_opt_integer_62("G", lifetimes as u64);
207 lifetime_depths.end += lifetimes;
209 self.binders.push(BinderLevel { lifetime_depths });
210 self = print_value(self, value.skip_binder())?;
217 impl Printer<'tcx> for SymbolMangler<'tcx> {
223 type DynExistential = Self;
226 fn tcx(&self) -> TyCtxt<'tcx> {
233 substs: &'tcx [Kind<'tcx>],
234 ) -> Result<Self::Path, Self::Error> {
235 if let Some(&i) = self.compress.as_ref().and_then(|c| c.paths.get(&(def_id, substs))) {
236 return self.print_backref(i);
238 let start = self.out.len();
240 self = self.default_print_def_path(def_id, substs)?;
242 // Only cache paths that do not refer to an enclosing
243 // binder (which would change depending on context).
244 if !substs.iter().any(|k| k.has_escaping_bound_vars()) {
245 if let Some(c) = &mut self.compress {
246 c.paths.insert((def_id, substs), start);
255 substs: &'tcx [Kind<'tcx>],
256 mut self_ty: Ty<'tcx>,
257 mut impl_trait_ref: Option<ty::TraitRef<'tcx>>,
258 ) -> Result<Self::Path, Self::Error> {
259 let key = self.tcx.def_key(impl_def_id);
260 let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
262 let mut param_env = self.tcx.param_env(impl_def_id)
264 if !substs.is_empty() {
265 param_env = param_env.subst(self.tcx, substs);
268 match &mut impl_trait_ref {
269 Some(impl_trait_ref) => {
270 assert_eq!(impl_trait_ref.self_ty(), self_ty);
272 self.tcx.normalize_erasing_regions(param_env, *impl_trait_ref);
273 self_ty = impl_trait_ref.self_ty();
276 self_ty = self.tcx.normalize_erasing_regions(param_env, self_ty);
280 self.path_append_impl(
281 |cx| cx.print_def_path(parent_def_id, &[]),
282 &key.disambiguated_data,
290 region: ty::Region<'_>,
291 ) -> Result<Self::Region, Self::Error> {
292 let i = match *region {
293 // Erased lifetimes use the index 0, for a
294 // shorter mangling of `L_`.
297 // Late-bound lifetimes use indices starting at 1,
298 // see `BinderLevel` for more details.
299 ty::ReLateBound(debruijn, ty::BrAnon(i)) => {
300 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
301 let depth = binder.lifetime_depths.start + i;
303 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
306 _ => bug!("symbol_names: non-erased region `{:?}`", region),
309 self.push_integer_62(i as u64);
316 ) -> Result<Self::Type, Self::Error> {
317 // Basic types, never cached (single-character).
318 let basic_type = match ty.sty {
322 ty::Tuple(_) if ty.is_unit() => "u",
323 ty::Int(IntTy::I8) => "a",
324 ty::Int(IntTy::I16) => "s",
325 ty::Int(IntTy::I32) => "l",
326 ty::Int(IntTy::I64) => "x",
327 ty::Int(IntTy::I128) => "n",
328 ty::Int(IntTy::Isize) => "i",
329 ty::Uint(UintTy::U8) => "h",
330 ty::Uint(UintTy::U16) => "t",
331 ty::Uint(UintTy::U32) => "m",
332 ty::Uint(UintTy::U64) => "y",
333 ty::Uint(UintTy::U128) => "o",
334 ty::Uint(UintTy::Usize) => "j",
335 ty::Float(FloatTy::F32) => "f",
336 ty::Float(FloatTy::F64) => "d",
339 // Placeholders (should be demangled as `_`).
340 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) |
341 ty::Infer(_) | ty::Error => "p",
345 if !basic_type.is_empty() {
346 self.push(basic_type);
350 if let Some(&i) = self.compress.as_ref().and_then(|c| c.types.get(&ty)) {
351 return self.print_backref(i);
353 let start = self.out.len();
356 // Basic types, handled above.
357 ty::Bool | ty::Char | ty::Str |
358 ty::Int(_) | ty::Uint(_) | ty::Float(_) |
359 ty::Never => unreachable!(),
360 ty::Tuple(_) if ty.is_unit() => unreachable!(),
362 // Placeholders, also handled as part of basic types.
363 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) |
364 ty::Infer(_) | ty::Error => unreachable!(),
366 ty::Ref(r, ty, mutbl) => {
367 self.push(match mutbl {
368 hir::MutImmutable => "R",
369 hir::MutMutable => "Q",
371 if *r != ty::ReErased {
372 self = r.print(self)?;
374 self = ty.print(self)?;
378 self.push(match mt.mutbl {
379 hir::MutImmutable => "P",
380 hir::MutMutable => "O",
382 self = mt.ty.print(self)?;
385 ty::Array(ty, len) => {
387 self = ty.print(self)?;
388 self = self.print_const(len)?;
392 self = ty.print(self)?;
397 for ty in tys.iter().map(|k| k.expect_ty()) {
398 self = ty.print(self)?;
403 // Mangle all nominal types as paths.
404 ty::Adt(&ty::AdtDef { did: def_id, .. }, substs) |
405 ty::FnDef(def_id, substs) |
406 ty::Opaque(def_id, substs) |
407 ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs }) |
408 ty::UnnormalizedProjection(ty::ProjectionTy { item_def_id: def_id, substs }) |
409 ty::Closure(def_id, ty::ClosureSubsts { substs }) |
410 ty::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
411 self = self.print_def_path(def_id, substs)?;
413 ty::Foreign(def_id) => {
414 self = self.print_def_path(def_id, &[])?;
419 self = self.in_binder(&sig, |mut cx, sig| {
420 if sig.unsafety == hir::Unsafety::Unsafe {
425 Abi::C => cx.push("KC"),
428 let name = abi.name();
429 if name.contains('-') {
430 cx.push_ident(&name.replace('-', "_"));
436 for &ty in sig.inputs() {
443 sig.output().print(cx)
447 ty::Dynamic(predicates, r) => {
449 self = self.in_binder(&predicates, |cx, predicates| {
450 cx.print_dyn_existential(predicates)
452 self = r.print(self)?;
455 ty::GeneratorWitness(_) => {
456 bug!("symbol_names: unexpected `GeneratorWitness`")
460 // Only cache types that do not refer to an enclosing
461 // binder (which would change depending on context).
462 if !ty.has_escaping_bound_vars() {
463 if let Some(c) = &mut self.compress {
464 c.types.insert(ty, start);
470 fn print_dyn_existential(
472 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
473 ) -> Result<Self::DynExistential, Self::Error> {
474 for predicate in predicates {
476 ty::ExistentialPredicate::Trait(trait_ref) => {
477 // Use a type that can't appear in defaults of type parameters.
478 let dummy_self = self.tcx.mk_ty_infer(ty::FreshTy(0));
479 let trait_ref = trait_ref.with_self_ty(self.tcx, dummy_self);
480 self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?;
482 ty::ExistentialPredicate::Projection(projection) => {
483 let name = self.tcx.associated_item(projection.item_def_id).ident;
485 self.push_ident(&name.as_str());
486 self = projection.ty.print(self)?;
488 ty::ExistentialPredicate::AutoTrait(def_id) => {
489 self = self.print_def_path(def_id, &[])?;
499 ct: &'tcx ty::Const<'tcx>,
500 ) -> Result<Self::Const, Self::Error> {
501 if let Some(&i) = self.compress.as_ref().and_then(|c| c.consts.get(&ct)) {
502 return self.print_backref(i);
504 let start = self.out.len();
509 bug!("symbol_names: unsupported constant of type `{}` ({:?})",
513 self = ct.ty.print(self)?;
515 if let Some(bits) = ct.assert_bits(self.tcx, ty::ParamEnv::empty().and(ct.ty)) {
516 let _ = write!(self.out, "{:x}_", bits);
518 // NOTE(eddyb) despite having the path, we need to
519 // encode a placeholder, as the path could refer
520 // back to e.g. an `impl` using the constant.
524 // Only cache consts that do not refer to an enclosing
525 // binder (which would change depending on context).
526 if !ct.has_escaping_bound_vars() {
527 if let Some(c) = &mut self.compress {
528 c.consts.insert(ct, start);
537 ) -> Result<Self::Path, Self::Error> {
539 let fingerprint = self.tcx.crate_disambiguator(cnum).to_fingerprint();
540 self.push_disambiguator(fingerprint.to_smaller_hash());
541 let name = self.tcx.original_crate_name(cnum).as_str();
542 self.push_ident(&name);
548 trait_ref: Option<ty::TraitRef<'tcx>>,
549 ) -> Result<Self::Path, Self::Error> {
550 assert!(trait_ref.is_some());
551 let trait_ref = trait_ref.unwrap();
554 self = self_ty.print(self)?;
555 self.print_def_path(trait_ref.def_id, trait_ref.substs)
560 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
561 disambiguated_data: &DisambiguatedDefPathData,
563 trait_ref: Option<ty::TraitRef<'tcx>>,
564 ) -> Result<Self::Path, Self::Error> {
565 self.push(match trait_ref {
569 self.push_disambiguator(disambiguated_data.disambiguator as u64);
570 self = print_prefix(self)?;
571 self = self_ty.print(self)?;
572 if let Some(trait_ref) = trait_ref {
573 self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?;
579 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
580 disambiguated_data: &DisambiguatedDefPathData,
581 ) -> Result<Self::Path, Self::Error> {
582 let ns = match disambiguated_data.data {
583 // Uppercase categories are more stable than lowercase ones.
584 DefPathData::TypeNs(_) => 't',
585 DefPathData::ValueNs(_) => 'v',
586 DefPathData::ClosureExpr => 'C',
587 DefPathData::Ctor => 'c',
588 DefPathData::AnonConst => 'k',
589 DefPathData::ImplTrait => 'i',
591 // These should never show up as `path_append` arguments.
592 DefPathData::CrateRoot
595 | DefPathData::MacroNs(_)
596 | DefPathData::LifetimeNs(_)
597 | DefPathData::GlobalMetaData(_) => {
598 bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
602 let name = disambiguated_data.data.get_opt_name().map(|s| s.as_str());
607 disambiguated_data.disambiguator as u64,
608 name.as_ref().map_or("", |s| &s[..])
611 fn path_generic_args(
613 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
615 ) -> Result<Self::Path, Self::Error> {
616 // Don't print any regions if they're all erased.
617 let print_regions = args.iter().any(|arg| {
619 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
623 let args = args.iter().cloned().filter(|arg| {
625 UnpackedKind::Lifetime(_) => print_regions,
630 if args.clone().next().is_none() {
631 return print_prefix(self);
635 self = print_prefix(self)?;
638 UnpackedKind::Lifetime(lt) => {
639 self = lt.print(self)?;
641 UnpackedKind::Type(ty) => {
642 self = ty.print(self)?;
644 UnpackedKind::Const(c) => {
646 // FIXME(const_generics) implement `ty::print::Print` on `ty::Const`.
647 // self = c.print(self)?;
648 self = self.print_const(c)?;