1 use rustc_data_structures::base_n;
2 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_hir::def_id::{CrateNum, DefId};
5 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
6 use rustc_middle::ty::layout::IntegerExt;
7 use rustc_middle::ty::print::{Print, Printer};
8 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst};
9 use rustc_middle::ty::{self, FloatTy, Instance, IntTy, Ty, TyCtxt, TypeFoldable, UintTy};
10 use rustc_target::abi::Integer;
11 use rustc_target::spec::abi::Abi;
18 instance: Instance<'tcx>,
19 instantiating_crate: Option<CrateNum>,
21 let def_id = instance.def_id();
22 // FIXME(eddyb) this should ideally not be needed.
23 let substs = tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), instance.substs);
26 let mut cx = &mut SymbolMangler {
28 start_offset: prefix.len(),
29 paths: FxHashMap::default(),
30 types: FxHashMap::default(),
31 consts: FxHashMap::default(),
33 out: String::from(prefix),
36 // Append `::{shim:...#0}` to shims that can coexist with a non-shim instance.
37 let shim_kind = match instance.def {
38 ty::InstanceDef::VtableShim(_) => Some("vtable"),
39 ty::InstanceDef::ReifyShim(_) => Some("reify"),
44 cx = if let Some(shim_kind) = shim_kind {
45 cx.path_append_ns(|cx| cx.print_def_path(def_id, substs), 'S', 0, shim_kind).unwrap()
47 cx.print_def_path(def_id, substs).unwrap()
49 if let Some(instantiating_crate) = instantiating_crate {
50 cx = cx.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap();
52 std::mem::take(&mut cx.out)
56 /// The range of distances from the root of what's
57 /// being printed, to the lifetimes in a binder.
58 /// Specifically, a `BrAnon(i)` lifetime has depth
59 /// `lifetime_depths.start + i`, going away from the
60 /// the root and towards its use site, as `i` increases.
61 /// This is used to flatten rustc's pairing of `BrAnon`
62 /// (intra-binder disambiguation) with a `DebruijnIndex`
63 /// (binder addressing), to "true" de Bruijn indices,
64 /// by subtracting the depth of a certain lifetime, from
65 /// the innermost depth at its use site.
66 lifetime_depths: Range<u32>,
69 struct SymbolMangler<'tcx> {
71 binders: Vec<BinderLevel>,
74 /// The length of the prefix in `out` (e.g. 2 for `_R`).
76 /// The values are start positions in `out`, in bytes.
77 paths: FxHashMap<(DefId, &'tcx [GenericArg<'tcx>]), usize>,
78 types: FxHashMap<Ty<'tcx>, usize>,
79 consts: FxHashMap<&'tcx ty::Const<'tcx>, usize>,
82 impl SymbolMangler<'tcx> {
83 fn push(&mut self, s: &str) {
87 /// Push a `_`-terminated base 62 integer, using the format
88 /// specified in the RFC as `<base-62-number>`, that is:
89 /// * `x = 0` is encoded as just the `"_"` terminator
90 /// * `x > 0` is encoded as `x - 1` in base 62, followed by `"_"`,
91 /// e.g. `1` becomes `"0_"`, `62` becomes `"Z_"`, etc.
92 fn push_integer_62(&mut self, x: u64) {
93 if let Some(x) = x.checked_sub(1) {
94 base_n::push_str(x as u128, 62, &mut self.out);
99 /// Push a `tag`-prefixed base 62 integer, when larger than `0`, that is:
100 /// * `x = 0` is encoded as `""` (nothing)
101 /// * `x > 0` is encoded as the `tag` followed by `push_integer_62(x - 1)`
102 /// e.g. `1` becomes `tag + "_"`, `2` becomes `tag + "0_"`, etc.
103 fn push_opt_integer_62(&mut self, tag: &str, x: u64) {
104 if let Some(x) = x.checked_sub(1) {
106 self.push_integer_62(x);
110 fn push_disambiguator(&mut self, dis: u64) {
111 self.push_opt_integer_62("s", dis);
114 fn push_ident(&mut self, ident: &str) {
115 let mut use_punycode = false;
116 for b in ident.bytes() {
118 b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
119 0x80..=0xff => use_punycode = true,
120 _ => bug!("symbol_names: bad byte {} in ident {:?}", b, ident),
125 let ident = if use_punycode {
128 // FIXME(eddyb) we should probably roll our own punycode implementation.
129 let mut punycode_bytes = match punycode::encode(ident) {
130 Ok(s) => s.into_bytes(),
131 Err(()) => bug!("symbol_names: punycode encoding failed for ident {:?}", ident),
134 // Replace `-` with `_`.
135 if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
139 // FIXME(eddyb) avoid rechecking UTF-8 validity.
140 punycode_string = String::from_utf8(punycode_bytes).unwrap();
146 let _ = write!(self.out, "{}", ident.len());
148 // Write a separating `_` if necessary (leading digit or `_`).
149 if let Some('_' | '0'..='9') = ident.chars().next() {
156 fn path_append_ns<'a>(
157 mut self: &'a mut Self,
158 print_prefix: impl FnOnce(&'a mut Self) -> Result<&'a mut Self, !>,
162 ) -> Result<&'a mut 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<&mut Self, !> {
173 self.push_integer_62((i - self.start_offset) as u64);
178 mut self: &'a mut Self,
179 value: &ty::Binder<'tcx, T>,
180 print_value: impl FnOnce(&'a mut Self, &T) -> Result<&'a mut Self, !>,
181 ) -> Result<&'a mut 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
198 _ => bug!("symbol_names: non-anonymized region `{:?}` in `{:?}`", br, value),
201 .map_or(0, |max| max + 1);
203 self.push_opt_integer_62("G", lifetimes as u64);
204 lifetime_depths.end += lifetimes;
206 self.binders.push(BinderLevel { lifetime_depths });
207 self = print_value(self, value.as_ref().skip_binder())?;
214 impl Printer<'tcx> for &mut SymbolMangler<'tcx> {
220 type DynExistential = Self;
223 fn tcx(&self) -> TyCtxt<'tcx> {
230 substs: &'tcx [GenericArg<'tcx>],
231 ) -> Result<Self::Path, Self::Error> {
232 if let Some(&i) = self.paths.get(&(def_id, substs)) {
233 return self.print_backref(i);
235 let start = self.out.len();
237 self = self.default_print_def_path(def_id, substs)?;
239 // Only cache paths that do not refer to an enclosing
240 // binder (which would change depending on context).
241 if !substs.iter().any(|k| k.has_escaping_bound_vars()) {
242 self.paths.insert((def_id, substs), start);
250 substs: &'tcx [GenericArg<'tcx>],
251 mut self_ty: Ty<'tcx>,
252 mut impl_trait_ref: Option<ty::TraitRef<'tcx>>,
253 ) -> Result<Self::Path, Self::Error> {
254 let key = self.tcx.def_key(impl_def_id);
255 let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
257 let mut param_env = self.tcx.param_env_reveal_all_normalized(impl_def_id);
258 if !substs.is_empty() {
259 param_env = param_env.subst(self.tcx, substs);
262 match &mut impl_trait_ref {
263 Some(impl_trait_ref) => {
264 assert_eq!(impl_trait_ref.self_ty(), self_ty);
265 *impl_trait_ref = self.tcx.normalize_erasing_regions(param_env, *impl_trait_ref);
266 self_ty = impl_trait_ref.self_ty();
269 self_ty = self.tcx.normalize_erasing_regions(param_env, self_ty);
273 self.push(match impl_trait_ref {
278 // Encode impl generic params if the substitutions contain parameters (implying
279 // polymorphization is enabled) and this isn't an inherent impl.
280 if impl_trait_ref.is_some() && substs.iter().any(|a| a.has_param_types_or_consts()) {
281 self = self.path_generic_args(
284 |cx| cx.print_def_path(parent_def_id, &[]),
286 key.disambiguated_data.disambiguator as u64,
293 self.push_disambiguator(key.disambiguated_data.disambiguator as u64);
294 self = self.print_def_path(parent_def_id, &[])?;
297 self = self_ty.print(self)?;
299 if let Some(trait_ref) = impl_trait_ref {
300 self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?;
306 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
307 let i = match *region {
308 // Erased lifetimes use the index 0, for a
309 // shorter mangling of `L_`.
312 // Late-bound lifetimes use indices starting at 1,
313 // see `BinderLevel` for more details.
314 ty::ReLateBound(debruijn, ty::BoundRegion { kind: ty::BrAnon(i), .. }) => {
315 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
316 let depth = binder.lifetime_depths.start + i;
318 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
321 _ => bug!("symbol_names: non-erased region `{:?}`", region),
324 self.push_integer_62(i as u64);
328 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
329 // Basic types, never cached (single-character).
330 let basic_type = match ty.kind() {
334 ty::Tuple(_) if ty.is_unit() => "u",
335 ty::Int(IntTy::I8) => "a",
336 ty::Int(IntTy::I16) => "s",
337 ty::Int(IntTy::I32) => "l",
338 ty::Int(IntTy::I64) => "x",
339 ty::Int(IntTy::I128) => "n",
340 ty::Int(IntTy::Isize) => "i",
341 ty::Uint(UintTy::U8) => "h",
342 ty::Uint(UintTy::U16) => "t",
343 ty::Uint(UintTy::U32) => "m",
344 ty::Uint(UintTy::U64) => "y",
345 ty::Uint(UintTy::U128) => "o",
346 ty::Uint(UintTy::Usize) => "j",
347 ty::Float(FloatTy::F32) => "f",
348 ty::Float(FloatTy::F64) => "d",
351 // Placeholders (should be demangled as `_`).
352 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => "p",
356 if !basic_type.is_empty() {
357 self.push(basic_type);
361 if let Some(&i) = self.types.get(&ty) {
362 return self.print_backref(i);
364 let start = self.out.len();
367 // Basic types, handled above.
368 ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
371 ty::Tuple(_) if ty.is_unit() => unreachable!(),
373 // Placeholders, also handled as part of basic types.
374 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => {
378 ty::Ref(r, ty, mutbl) => {
379 self.push(match mutbl {
380 hir::Mutability::Not => "R",
381 hir::Mutability::Mut => "Q",
383 if *r != ty::ReErased {
384 self = r.print(self)?;
386 self = ty.print(self)?;
390 self.push(match mt.mutbl {
391 hir::Mutability::Not => "P",
392 hir::Mutability::Mut => "O",
394 self = mt.ty.print(self)?;
397 ty::Array(ty, len) => {
399 self = ty.print(self)?;
400 self = self.print_const(len)?;
404 self = ty.print(self)?;
409 for ty in tys.iter().map(|k| k.expect_ty()) {
410 self = ty.print(self)?;
415 // Mangle all nominal types as paths.
416 ty::Adt(&ty::AdtDef { did: def_id, .. }, substs)
417 | ty::FnDef(def_id, substs)
418 | ty::Opaque(def_id, substs)
419 | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
420 | ty::Closure(def_id, substs)
421 | ty::Generator(def_id, substs, _) => {
422 self = self.print_def_path(def_id, substs)?;
424 ty::Foreign(def_id) => {
425 self = self.print_def_path(def_id, &[])?;
430 self = self.in_binder(&sig, |mut cx, sig| {
431 if sig.unsafety == hir::Unsafety::Unsafe {
436 Abi::C { unwind: false } => cx.push("KC"),
439 let name = abi.name();
440 if name.contains('-') {
441 cx.push_ident(&name.replace('-', "_"));
447 for &ty in sig.inputs() {
454 sig.output().print(cx)
458 ty::Dynamic(predicates, r) => {
460 self = self.print_dyn_existential(predicates)?;
461 self = r.print(self)?;
464 ty::GeneratorWitness(_) => bug!("symbol_names: unexpected `GeneratorWitness`"),
467 // Only cache types that do not refer to an enclosing
468 // binder (which would change depending on context).
469 if !ty.has_escaping_bound_vars() {
470 self.types.insert(ty, start);
475 fn print_dyn_existential(
477 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
478 ) -> Result<Self::DynExistential, Self::Error> {
479 // Okay, so this is a bit tricky. Imagine we have a trait object like
480 // `dyn for<'a> Foo<'a, Bar = &'a ()>`. When we mangle this, the
481 // output looks really close to the syntax, where the `Bar = &'a ()` bit
482 // is under the same binders (`['a]`) as the `Foo<'a>` bit. However, we
483 // actually desugar these into two separate `ExistentialPredicate`s. We
484 // can't enter/exit the "binder scope" twice though, because then we
485 // would mangle the binders twice. (Also, side note, we merging these
486 // two is kind of difficult, because of potential HRTBs in the Projection
489 // Also worth mentioning: imagine that we instead had
490 // `dyn for<'a> Foo<'a, Bar = &'a ()> + Send`. In this case, `Send` is
491 // under the same binders as `Foo`. Currently, this doesn't matter,
492 // because only *auto traits* are allowed other than the principal trait
493 // and all auto traits don't have any generics. Two things could
494 // make this not an "okay" mangling:
495 // 1) Instead of mangling only *used*
496 // bound vars, we want to mangle *all* bound vars (`for<'b> Send` is a
497 // valid trait predicate);
498 // 2) We allow multiple "principal" traits in the future, or at least
499 // allow in any form another trait predicate that can take generics.
501 // Here we assume that predicates have the following structure:
502 // [<Trait> [{<Projection>}]] [{<Auto>}]
503 // Since any predicates after the first one shouldn't change the binders,
504 // just put them all in the binders of the first.
505 self = self.in_binder(&predicates[0], |mut cx, _| {
506 for predicate in predicates.iter() {
507 // It would be nice to be able to validate bound vars here, but
508 // projections can actually include bound vars from super traits
509 // because of HRTBs (only in the `Self` type). Also, auto traits
510 // could have different bound vars *anyways*.
511 match predicate.as_ref().skip_binder() {
512 ty::ExistentialPredicate::Trait(trait_ref) => {
513 // Use a type that can't appear in defaults of type parameters.
514 let dummy_self = cx.tcx.mk_ty_infer(ty::FreshTy(0));
515 let trait_ref = trait_ref.with_self_ty(cx.tcx, dummy_self);
516 cx = cx.print_def_path(trait_ref.def_id, trait_ref.substs)?;
518 ty::ExistentialPredicate::Projection(projection) => {
519 let name = cx.tcx.associated_item(projection.item_def_id).ident;
521 cx.push_ident(&name.as_str());
522 cx = projection.ty.print(cx)?;
524 ty::ExistentialPredicate::AutoTrait(def_id) => {
525 cx = cx.print_def_path(*def_id, &[])?;
536 fn print_const(mut self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
537 if let Some(&i) = self.consts.get(&ct) {
538 return self.print_backref(i);
540 let start = self.out.len();
543 let val = match ct.ty.kind() {
544 ty::Uint(_) | ty::Bool | ty::Char => {
545 ct.try_eval_bits(self.tcx, ty::ParamEnv::reveal_all(), ct.ty)
548 ct.try_eval_bits(self.tcx, ty::ParamEnv::reveal_all(), ct.ty).and_then(|b| {
549 let val = Integer::from_int_ty(&self.tcx, *ity).size().sign_extend(b) as i128;
553 Some(val.unsigned_abs())
557 bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct.ty, ct);
561 if let Some(bits) = val {
562 // We only print the type if the const can be evaluated.
563 self = ct.ty.print(self)?;
564 let _ = write!(self.out, "{}{:x}_", if neg { "n" } else { "" }, bits);
566 // NOTE(eddyb) despite having the path, we need to
567 // encode a placeholder, as the path could refer
568 // back to e.g. an `impl` using the constant.
572 // Only cache consts that do not refer to an enclosing
573 // binder (which would change depending on context).
574 if !ct.has_escaping_bound_vars() {
575 self.consts.insert(ct, start);
580 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
582 let stable_crate_id = self.tcx.def_path_hash(cnum.as_def_id()).stable_crate_id();
583 self.push_disambiguator(stable_crate_id.to_u64());
584 let name = self.tcx.crate_name(cnum).as_str();
585 self.push_ident(&name);
592 trait_ref: Option<ty::TraitRef<'tcx>>,
593 ) -> Result<Self::Path, Self::Error> {
594 assert!(trait_ref.is_some());
595 let trait_ref = trait_ref.unwrap();
598 self = self_ty.print(self)?;
599 self.print_def_path(trait_ref.def_id, trait_ref.substs)
604 _: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
605 _: &DisambiguatedDefPathData,
607 _: Option<ty::TraitRef<'tcx>>,
608 ) -> Result<Self::Path, Self::Error> {
609 // Inlined into `print_impl_path`
615 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
616 disambiguated_data: &DisambiguatedDefPathData,
617 ) -> Result<Self::Path, Self::Error> {
618 let ns = match disambiguated_data.data {
619 // Uppercase categories are more stable than lowercase ones.
620 DefPathData::TypeNs(_) => 't',
621 DefPathData::ValueNs(_) => 'v',
622 DefPathData::ClosureExpr => 'C',
623 DefPathData::Ctor => 'c',
624 DefPathData::AnonConst => 'k',
625 DefPathData::ImplTrait => 'i',
627 // These should never show up as `path_append` arguments.
628 DefPathData::CrateRoot
631 | DefPathData::MacroNs(_)
632 | DefPathData::LifetimeNs(_) => {
633 bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
637 let name = disambiguated_data.data.get_opt_name().map(|s| s.as_str());
642 disambiguated_data.disambiguator as u64,
643 name.as_ref().map_or("", |s| &s[..]),
647 fn path_generic_args(
649 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
650 args: &[GenericArg<'tcx>],
651 ) -> Result<Self::Path, Self::Error> {
652 // Don't print any regions if they're all erased.
653 let print_regions = args.iter().any(|arg| match arg.unpack() {
654 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
657 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
658 GenericArgKind::Lifetime(_) => print_regions,
662 if args.clone().next().is_none() {
663 return print_prefix(self);
667 self = print_prefix(self)?;
670 GenericArgKind::Lifetime(lt) => {
671 self = lt.print(self)?;
673 GenericArgKind::Type(ty) => {
674 self = ty.print(self)?;
676 GenericArgKind::Const(c) => {
678 self = c.print(self)?;