1 use rustc_data_structures::base_n;
2 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
3 use rustc_data_structures::intern::Interned;
5 use rustc_hir::def::CtorKind;
6 use rustc_hir::def_id::{CrateNum, DefId};
7 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
8 use rustc_middle::mir::interpret::ConstValue;
9 use rustc_middle::ty::layout::IntegerExt;
10 use rustc_middle::ty::print::{Print, Printer};
11 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst};
12 use rustc_middle::ty::{self, FloatTy, Instance, IntTy, Ty, TyCtxt, TypeFoldable, UintTy};
13 use rustc_span::symbol::kw;
14 use rustc_target::abi::call::FnAbi;
15 use rustc_target::abi::Integer;
16 use rustc_target::spec::abi::Abi;
22 pub(super) fn mangle<'tcx>(
24 instance: Instance<'tcx>,
25 instantiating_crate: Option<CrateNum>,
27 let def_id = instance.def_id();
28 // FIXME(eddyb) this should ideally not be needed.
29 let substs = tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), instance.substs);
32 let mut cx = &mut SymbolMangler {
34 start_offset: prefix.len(),
35 paths: FxHashMap::default(),
36 types: FxHashMap::default(),
37 consts: FxHashMap::default(),
39 out: String::from(prefix),
42 // Append `::{shim:...#0}` to shims that can coexist with a non-shim instance.
43 let shim_kind = match instance.def {
44 ty::InstanceDef::VtableShim(_) => Some("vtable"),
45 ty::InstanceDef::ReifyShim(_) => Some("reify"),
50 cx = if let Some(shim_kind) = shim_kind {
51 cx.path_append_ns(|cx| cx.print_def_path(def_id, substs), 'S', 0, shim_kind).unwrap()
53 cx.print_def_path(def_id, substs).unwrap()
55 if let Some(instantiating_crate) = instantiating_crate {
56 cx = cx.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap();
58 std::mem::take(&mut cx.out)
61 pub(super) fn mangle_typeid_for_fnabi<'tcx>(
63 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
65 // LLVM uses type metadata to allow IR modules to aggregate pointers by their types.[1] This
66 // type metadata is used by LLVM Control Flow Integrity to test whether a given pointer is
67 // associated with a type identifier (i.e., test type membership).
69 // Clang uses the Itanium C++ ABI's[2] virtual tables and RTTI typeinfo structure name[3] as
70 // type metadata identifiers for function pointers. The typeinfo name encoding is a
71 // two-character code (i.e., “TS”) prefixed to the type encoding for the function.
73 // For cross-language LLVM CFI support, a compatible encoding must be used by either
75 // a. Using a superset of types that encompasses types used by Clang (i.e., Itanium C++ ABI's
76 // type encodings[4]), or at least types used at the FFI boundary.
77 // b. Reducing the types to the least common denominator between types used by Clang (or at
78 // least types used at the FFI boundary) and Rust compilers (if even possible).
79 // c. Creating a new ABI for cross-language CFI and using it for Clang and Rust compilers (and
80 // possibly other compilers).
82 // Option (b) may weaken the protection for Rust-compiled only code, so it should be provided
83 // as an alternative to a Rust-specific encoding for when mixing Rust and C and C++ -compiled
84 // code. Option (c) would require changes to Clang to use the new ABI.
86 // [1] https://llvm.org/docs/TypeMetadata.html
87 // [2] https://itanium-cxx-abi.github.io/cxx-abi/abi.html
88 // [3] https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-special-vtables
89 // [4] https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-type
91 // FIXME(rcvalle): See comment above.
92 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
93 format!("typeid{}", arg_count)
97 /// The range of distances from the root of what's
98 /// being printed, to the lifetimes in a binder.
99 /// Specifically, a `BrAnon(i)` lifetime has depth
100 /// `lifetime_depths.start + i`, going away from the
101 /// the root and towards its use site, as `i` increases.
102 /// This is used to flatten rustc's pairing of `BrAnon`
103 /// (intra-binder disambiguation) with a `DebruijnIndex`
104 /// (binder addressing), to "true" de Bruijn indices,
105 /// by subtracting the depth of a certain lifetime, from
106 /// the innermost depth at its use site.
107 lifetime_depths: Range<u32>,
110 struct SymbolMangler<'tcx> {
112 binders: Vec<BinderLevel>,
115 /// The length of the prefix in `out` (e.g. 2 for `_R`).
117 /// The values are start positions in `out`, in bytes.
118 paths: FxHashMap<(DefId, &'tcx [GenericArg<'tcx>]), usize>,
119 types: FxHashMap<Ty<'tcx>, usize>,
120 consts: FxHashMap<ty::Const<'tcx>, usize>,
123 impl<'tcx> SymbolMangler<'tcx> {
124 fn push(&mut self, s: &str) {
125 self.out.push_str(s);
128 /// Push a `_`-terminated base 62 integer, using the format
129 /// specified in the RFC as `<base-62-number>`, that is:
130 /// * `x = 0` is encoded as just the `"_"` terminator
131 /// * `x > 0` is encoded as `x - 1` in base 62, followed by `"_"`,
132 /// e.g. `1` becomes `"0_"`, `62` becomes `"Z_"`, etc.
133 fn push_integer_62(&mut self, x: u64) {
134 if let Some(x) = x.checked_sub(1) {
135 base_n::push_str(x as u128, 62, &mut self.out);
140 /// Push a `tag`-prefixed base 62 integer, when larger than `0`, that is:
141 /// * `x = 0` is encoded as `""` (nothing)
142 /// * `x > 0` is encoded as the `tag` followed by `push_integer_62(x - 1)`
143 /// e.g. `1` becomes `tag + "_"`, `2` becomes `tag + "0_"`, etc.
144 fn push_opt_integer_62(&mut self, tag: &str, x: u64) {
145 if let Some(x) = x.checked_sub(1) {
147 self.push_integer_62(x);
151 fn push_disambiguator(&mut self, dis: u64) {
152 self.push_opt_integer_62("s", dis);
155 fn push_ident(&mut self, ident: &str) {
156 let mut use_punycode = false;
157 for b in ident.bytes() {
159 b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
160 0x80..=0xff => use_punycode = true,
161 _ => bug!("symbol_names: bad byte {} in ident {:?}", b, ident),
166 let ident = if use_punycode {
169 // FIXME(eddyb) we should probably roll our own punycode implementation.
170 let mut punycode_bytes = match punycode::encode(ident) {
171 Ok(s) => s.into_bytes(),
172 Err(()) => bug!("symbol_names: punycode encoding failed for ident {:?}", ident),
175 // Replace `-` with `_`.
176 if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
180 // FIXME(eddyb) avoid rechecking UTF-8 validity.
181 punycode_string = String::from_utf8(punycode_bytes).unwrap();
187 let _ = write!(self.out, "{}", ident.len());
189 // Write a separating `_` if necessary (leading digit or `_`).
190 if let Some('_' | '0'..='9') = ident.chars().next() {
197 fn path_append_ns<'a>(
198 mut self: &'a mut Self,
199 print_prefix: impl FnOnce(&'a mut Self) -> Result<&'a mut Self, !>,
203 ) -> Result<&'a mut Self, !> {
206 self = print_prefix(self)?;
207 self.push_disambiguator(disambiguator as u64);
208 self.push_ident(name);
212 fn print_backref(&mut self, i: usize) -> Result<&mut Self, !> {
214 self.push_integer_62((i - self.start_offset) as u64);
219 mut self: &'a mut Self,
220 value: &ty::Binder<'tcx, T>,
221 print_value: impl FnOnce(&'a mut Self, &T) -> Result<&'a mut Self, !>,
222 ) -> Result<&'a mut Self, !>
224 T: TypeFoldable<'tcx>,
226 let regions = if value.has_late_bound_regions() {
227 self.tcx.collect_referenced_late_bound_regions(value)
232 let mut lifetime_depths =
233 self.binders.last().map(|b| b.lifetime_depths.end).map_or(0..0, |i| i..i);
235 let lifetimes = regions
239 _ => bug!("symbol_names: non-anonymized region `{:?}` in `{:?}`", br, value),
242 .map_or(0, |max| max + 1);
244 self.push_opt_integer_62("G", lifetimes as u64);
245 lifetime_depths.end += lifetimes;
247 self.binders.push(BinderLevel { lifetime_depths });
248 self = print_value(self, value.as_ref().skip_binder())?;
255 impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> {
261 type DynExistential = Self;
264 fn tcx(&self) -> TyCtxt<'tcx> {
271 substs: &'tcx [GenericArg<'tcx>],
272 ) -> Result<Self::Path, Self::Error> {
273 if let Some(&i) = self.paths.get(&(def_id, substs)) {
274 return self.print_backref(i);
276 let start = self.out.len();
278 self = self.default_print_def_path(def_id, substs)?;
280 // Only cache paths that do not refer to an enclosing
281 // binder (which would change depending on context).
282 if !substs.iter().any(|k| k.has_escaping_bound_vars()) {
283 self.paths.insert((def_id, substs), start);
291 substs: &'tcx [GenericArg<'tcx>],
292 mut self_ty: Ty<'tcx>,
293 mut impl_trait_ref: Option<ty::TraitRef<'tcx>>,
294 ) -> Result<Self::Path, Self::Error> {
295 let key = self.tcx.def_key(impl_def_id);
296 let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
298 let mut param_env = self.tcx.param_env_reveal_all_normalized(impl_def_id);
299 if !substs.is_empty() {
300 param_env = param_env.subst(self.tcx, substs);
303 match &mut impl_trait_ref {
304 Some(impl_trait_ref) => {
305 assert_eq!(impl_trait_ref.self_ty(), self_ty);
306 *impl_trait_ref = self.tcx.normalize_erasing_regions(param_env, *impl_trait_ref);
307 self_ty = impl_trait_ref.self_ty();
310 self_ty = self.tcx.normalize_erasing_regions(param_env, self_ty);
314 self.push(match impl_trait_ref {
319 // Encode impl generic params if the substitutions contain parameters (implying
320 // polymorphization is enabled) and this isn't an inherent impl.
321 if impl_trait_ref.is_some() && substs.iter().any(|a| a.has_param_types_or_consts()) {
322 self = self.path_generic_args(
325 |cx| cx.print_def_path(parent_def_id, &[]),
327 key.disambiguated_data.disambiguator as u64,
334 self.push_disambiguator(key.disambiguated_data.disambiguator as u64);
335 self = self.print_def_path(parent_def_id, &[])?;
338 self = self_ty.print(self)?;
340 if let Some(trait_ref) = impl_trait_ref {
341 self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?;
347 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
348 let i = match *region {
349 // Erased lifetimes use the index 0, for a
350 // shorter mangling of `L_`.
353 // Late-bound lifetimes use indices starting at 1,
354 // see `BinderLevel` for more details.
355 ty::ReLateBound(debruijn, ty::BoundRegion { kind: ty::BrAnon(i), .. }) => {
356 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
357 let depth = binder.lifetime_depths.start + i;
359 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
362 _ => bug!("symbol_names: non-erased region `{:?}`", region),
365 self.push_integer_62(i as u64);
369 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
370 // Basic types, never cached (single-character).
371 let basic_type = match ty.kind() {
375 ty::Tuple(_) if ty.is_unit() => "u",
376 ty::Int(IntTy::I8) => "a",
377 ty::Int(IntTy::I16) => "s",
378 ty::Int(IntTy::I32) => "l",
379 ty::Int(IntTy::I64) => "x",
380 ty::Int(IntTy::I128) => "n",
381 ty::Int(IntTy::Isize) => "i",
382 ty::Uint(UintTy::U8) => "h",
383 ty::Uint(UintTy::U16) => "t",
384 ty::Uint(UintTy::U32) => "m",
385 ty::Uint(UintTy::U64) => "y",
386 ty::Uint(UintTy::U128) => "o",
387 ty::Uint(UintTy::Usize) => "j",
388 ty::Float(FloatTy::F32) => "f",
389 ty::Float(FloatTy::F64) => "d",
392 // Placeholders (should be demangled as `_`).
393 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => "p",
397 if !basic_type.is_empty() {
398 self.push(basic_type);
402 if let Some(&i) = self.types.get(&ty) {
403 return self.print_backref(i);
405 let start = self.out.len();
408 // Basic types, handled above.
409 ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
412 ty::Tuple(_) if ty.is_unit() => unreachable!(),
414 // Placeholders, also handled as part of basic types.
415 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => {
419 ty::Ref(r, ty, mutbl) => {
420 self.push(match mutbl {
421 hir::Mutability::Not => "R",
422 hir::Mutability::Mut => "Q",
425 self = r.print(self)?;
427 self = ty.print(self)?;
431 self.push(match mt.mutbl {
432 hir::Mutability::Not => "P",
433 hir::Mutability::Mut => "O",
435 self = mt.ty.print(self)?;
438 ty::Array(ty, len) => {
440 self = ty.print(self)?;
441 self = self.print_const(len)?;
445 self = ty.print(self)?;
450 for ty in tys.iter() {
451 self = ty.print(self)?;
456 // Mangle all nominal types as paths.
457 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), substs)
458 | ty::FnDef(def_id, substs)
459 | ty::Opaque(def_id, substs)
460 | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
461 | ty::Closure(def_id, substs)
462 | ty::Generator(def_id, substs, _) => {
463 self = self.print_def_path(def_id, substs)?;
465 ty::Foreign(def_id) => {
466 self = self.print_def_path(def_id, &[])?;
471 self = self.in_binder(&sig, |mut cx, sig| {
472 if sig.unsafety == hir::Unsafety::Unsafe {
477 Abi::C { unwind: false } => cx.push("KC"),
480 let name = abi.name();
481 if name.contains('-') {
482 cx.push_ident(&name.replace('-', "_"));
488 for &ty in sig.inputs() {
495 sig.output().print(cx)
499 ty::Dynamic(predicates, r) => {
501 self = self.print_dyn_existential(predicates)?;
502 self = r.print(self)?;
505 ty::GeneratorWitness(_) => bug!("symbol_names: unexpected `GeneratorWitness`"),
508 // Only cache types that do not refer to an enclosing
509 // binder (which would change depending on context).
510 if !ty.has_escaping_bound_vars() {
511 self.types.insert(ty, start);
516 fn print_dyn_existential(
518 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
519 ) -> Result<Self::DynExistential, Self::Error> {
520 // Okay, so this is a bit tricky. Imagine we have a trait object like
521 // `dyn for<'a> Foo<'a, Bar = &'a ()>`. When we mangle this, the
522 // output looks really close to the syntax, where the `Bar = &'a ()` bit
523 // is under the same binders (`['a]`) as the `Foo<'a>` bit. However, we
524 // actually desugar these into two separate `ExistentialPredicate`s. We
525 // can't enter/exit the "binder scope" twice though, because then we
526 // would mangle the binders twice. (Also, side note, we merging these
527 // two is kind of difficult, because of potential HRTBs in the Projection
530 // Also worth mentioning: imagine that we instead had
531 // `dyn for<'a> Foo<'a, Bar = &'a ()> + Send`. In this case, `Send` is
532 // under the same binders as `Foo`. Currently, this doesn't matter,
533 // because only *auto traits* are allowed other than the principal trait
534 // and all auto traits don't have any generics. Two things could
535 // make this not an "okay" mangling:
536 // 1) Instead of mangling only *used*
537 // bound vars, we want to mangle *all* bound vars (`for<'b> Send` is a
538 // valid trait predicate);
539 // 2) We allow multiple "principal" traits in the future, or at least
540 // allow in any form another trait predicate that can take generics.
542 // Here we assume that predicates have the following structure:
543 // [<Trait> [{<Projection>}]] [{<Auto>}]
544 // Since any predicates after the first one shouldn't change the binders,
545 // just put them all in the binders of the first.
546 self = self.in_binder(&predicates[0], |mut cx, _| {
547 for predicate in predicates.iter() {
548 // It would be nice to be able to validate bound vars here, but
549 // projections can actually include bound vars from super traits
550 // because of HRTBs (only in the `Self` type). Also, auto traits
551 // could have different bound vars *anyways*.
552 match predicate.as_ref().skip_binder() {
553 ty::ExistentialPredicate::Trait(trait_ref) => {
554 // Use a type that can't appear in defaults of type parameters.
555 let dummy_self = cx.tcx.mk_ty_infer(ty::FreshTy(0));
556 let trait_ref = trait_ref.with_self_ty(cx.tcx, dummy_self);
557 cx = cx.print_def_path(trait_ref.def_id, trait_ref.substs)?;
559 ty::ExistentialPredicate::Projection(projection) => {
560 let name = cx.tcx.associated_item(projection.item_def_id).name;
562 cx.push_ident(name.as_str());
563 cx = match projection.term {
564 ty::Term::Ty(ty) => ty.print(cx),
565 ty::Term::Const(c) => c.print(cx),
568 ty::ExistentialPredicate::AutoTrait(def_id) => {
569 cx = cx.print_def_path(*def_id, &[])?;
580 fn print_const(mut self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
581 // We only mangle a typed value if the const can be evaluated.
582 let ct = ct.eval(self.tcx, ty::ParamEnv::reveal_all());
584 ty::ConstKind::Value(_) => {}
586 // Placeholders (should be demangled as `_`).
587 // NOTE(eddyb) despite `Unevaluated` having a `DefId` (and therefore
588 // a path), even for it we still need to encode a placeholder, as
589 // the path could refer back to e.g. an `impl` using the constant.
590 ty::ConstKind::Unevaluated(_)
591 | ty::ConstKind::Param(_)
592 | ty::ConstKind::Infer(_)
593 | ty::ConstKind::Bound(..)
594 | ty::ConstKind::Placeholder(_)
595 | ty::ConstKind::Error(_) => {
596 // Never cached (single-character).
602 if let Some(&i) = self.consts.get(&ct) {
603 return self.print_backref(i);
605 let start = self.out.len();
607 match ct.ty().kind() {
608 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Char => {
609 self = ct.ty().print(self)?;
611 let mut bits = ct.eval_bits(self.tcx, ty::ParamEnv::reveal_all(), ct.ty());
613 // Negative integer values are mangled using `n` as a "sign prefix".
614 if let ty::Int(ity) = ct.ty().kind() {
616 Integer::from_int_ty(&self.tcx, *ity).size().sign_extend(bits) as i128;
620 bits = val.unsigned_abs();
623 let _ = write!(self.out, "{:x}_", bits);
626 // HACK(eddyb) because `ty::Const` only supports sized values (for now),
627 // we can't use `deref_const` + supporting `str`, we have to specially
628 // handle `&str` and include both `&` ("R") and `str` ("e") prefixes.
629 ty::Ref(_, ty, hir::Mutability::Not) if *ty == self.tcx.types.str_ => {
632 ty::ConstKind::Value(ConstValue::Slice { data, start, end }) => {
633 // NOTE(eddyb) the following comment was kept from `ty::print::pretty`:
634 // The `inspect` here is okay since we checked the bounds, and there are no
635 // relocations (we have an active `str` reference here). We don't use this
636 // result to affect interpreter execution.
639 .inspect_with_uninit_and_ptr_outside_interpreter(start..end);
640 let s = std::str::from_utf8(slice).expect("non utf8 str from miri");
643 // FIXME(eddyb) use a specialized hex-encoding loop.
644 for byte in s.bytes() {
645 let _ = write!(self.out, "{:02x}", byte);
651 bug!("symbol_names: unsupported `&str` constant: {:?}", ct);
656 ty::Ref(_, _, mutbl) => {
657 self.push(match mutbl {
658 hir::Mutability::Not => "R",
659 hir::Mutability::Mut => "Q",
661 self = self.tcx.deref_const(ty::ParamEnv::reveal_all().and(ct)).print(self)?;
664 ty::Array(..) | ty::Tuple(..) | ty::Adt(..) => {
665 let contents = self.tcx.destructure_const(ty::ParamEnv::reveal_all().and(ct));
666 let fields = contents.fields.iter().copied();
668 let print_field_list = |mut this: Self| {
669 for field in fields.clone() {
670 this = field.print(this)?;
676 match *ct.ty().kind() {
679 self = print_field_list(self)?;
683 self = print_field_list(self)?;
685 ty::Adt(def, substs) => {
687 contents.variant.expect("destructed const of adt without variant idx");
688 let variant_def = &def.variant(variant_idx);
691 self = self.print_def_path(variant_def.def_id, substs)?;
693 match variant_def.ctor_kind {
699 self = print_field_list(self)?;
701 CtorKind::Fictive => {
703 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
704 // HACK(eddyb) this mimics `path_append`,
705 // instead of simply using `field_def.ident`,
706 // just to be able to handle disambiguators.
707 let disambiguated_field =
708 self.tcx.def_key(field_def.did).disambiguated_data;
709 let field_name = disambiguated_field.data.get_opt_name();
710 self.push_disambiguator(
711 disambiguated_field.disambiguator as u64,
713 self.push_ident(field_name.unwrap_or(kw::Empty).as_str());
715 self = field.print(self)?;
726 bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct.ty(), ct);
730 // Only cache consts that do not refer to an enclosing
731 // binder (which would change depending on context).
732 if !ct.has_escaping_bound_vars() {
733 self.consts.insert(ct, start);
738 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
740 let stable_crate_id = self.tcx.def_path_hash(cnum.as_def_id()).stable_crate_id();
741 self.push_disambiguator(stable_crate_id.to_u64());
742 let name = self.tcx.crate_name(cnum);
743 self.push_ident(name.as_str());
750 trait_ref: Option<ty::TraitRef<'tcx>>,
751 ) -> Result<Self::Path, Self::Error> {
752 assert!(trait_ref.is_some());
753 let trait_ref = trait_ref.unwrap();
756 self = self_ty.print(self)?;
757 self.print_def_path(trait_ref.def_id, trait_ref.substs)
762 _: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
763 _: &DisambiguatedDefPathData,
765 _: Option<ty::TraitRef<'tcx>>,
766 ) -> Result<Self::Path, Self::Error> {
767 // Inlined into `print_impl_path`
773 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
774 disambiguated_data: &DisambiguatedDefPathData,
775 ) -> Result<Self::Path, Self::Error> {
776 let ns = match disambiguated_data.data {
777 // Extern block segments can be skipped, names from extern blocks
778 // are effectively living in their parent modules.
779 DefPathData::ForeignMod => return print_prefix(self),
781 // Uppercase categories are more stable than lowercase ones.
782 DefPathData::TypeNs(_) => 't',
783 DefPathData::ValueNs(_) => 'v',
784 DefPathData::ClosureExpr => 'C',
785 DefPathData::Ctor => 'c',
786 DefPathData::AnonConst => 'k',
787 DefPathData::ImplTrait => 'i',
789 // These should never show up as `path_append` arguments.
790 DefPathData::CrateRoot
793 | DefPathData::MacroNs(_)
794 | DefPathData::LifetimeNs(_) => {
795 bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
799 let name = disambiguated_data.data.get_opt_name();
804 disambiguated_data.disambiguator as u64,
805 name.unwrap_or(kw::Empty).as_str(),
809 fn path_generic_args(
811 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
812 args: &[GenericArg<'tcx>],
813 ) -> Result<Self::Path, Self::Error> {
814 // Don't print any regions if they're all erased.
815 let print_regions = args.iter().any(|arg| match arg.unpack() {
816 GenericArgKind::Lifetime(r) => !r.is_erased(),
819 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
820 GenericArgKind::Lifetime(_) => print_regions,
824 if args.clone().next().is_none() {
825 return print_prefix(self);
829 self = print_prefix(self)?;
832 GenericArgKind::Lifetime(lt) => {
833 self = lt.print(self)?;
835 GenericArgKind::Type(ty) => {
836 self = ty.print(self)?;
838 GenericArgKind::Const(c) => {
840 self = c.print(self)?;