1 use rustc_data_structures::base_n;
2 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_hir::def::CtorKind;
5 use rustc_hir::def_id::{CrateNum, DefId};
6 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
7 use rustc_middle::mir::interpret::ConstValue;
8 use rustc_middle::ty::layout::IntegerExt;
9 use rustc_middle::ty::print::{Print, Printer};
10 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst};
11 use rustc_middle::ty::{self, FloatTy, Instance, IntTy, Ty, TyCtxt, TypeFoldable, UintTy};
12 use rustc_span::symbol::kw;
13 use rustc_target::abi::call::FnAbi;
14 use rustc_target::abi::Integer;
15 use rustc_target::spec::abi::Abi;
21 pub(super) fn mangle<'tcx>(
23 instance: Instance<'tcx>,
24 instantiating_crate: Option<CrateNum>,
26 let def_id = instance.def_id();
27 // FIXME(eddyb) this should ideally not be needed.
28 let substs = tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), instance.substs);
31 let mut cx = &mut SymbolMangler {
33 start_offset: prefix.len(),
34 paths: FxHashMap::default(),
35 types: FxHashMap::default(),
36 consts: FxHashMap::default(),
38 out: String::from(prefix),
41 // Append `::{shim:...#0}` to shims that can coexist with a non-shim instance.
42 let shim_kind = match instance.def {
43 ty::InstanceDef::VtableShim(_) => Some("vtable"),
44 ty::InstanceDef::ReifyShim(_) => Some("reify"),
49 cx = if let Some(shim_kind) = shim_kind {
50 cx.path_append_ns(|cx| cx.print_def_path(def_id, substs), 'S', 0, shim_kind).unwrap()
52 cx.print_def_path(def_id, substs).unwrap()
54 if let Some(instantiating_crate) = instantiating_crate {
55 cx = cx.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap();
57 std::mem::take(&mut cx.out)
60 pub(super) fn mangle_typeid_for_fnabi<'tcx>(
62 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
64 // LLVM uses type metadata to allow IR modules to aggregate pointers by their types.[1] This
65 // type metadata is used by LLVM Control Flow Integrity to test whether a given pointer is
66 // associated with a type identifier (i.e., test type membership).
68 // Clang uses the Itanium C++ ABI's[2] virtual tables and RTTI typeinfo structure name[3] as
69 // type metadata identifiers for function pointers. The typeinfo name encoding is a
70 // two-character code (i.e., “TS”) prefixed to the type encoding for the function.
72 // For cross-language LLVM CFI support, a compatible encoding must be used by either
74 // a. Using a superset of types that encompasses types used by Clang (i.e., Itanium C++ ABI's
75 // type encodings[4]), or at least types used at the FFI boundary.
76 // b. Reducing the types to the least common denominator between types used by Clang (or at
77 // least types used at the FFI boundary) and Rust compilers (if even possible).
78 // c. Creating a new ABI for cross-language CFI and using it for Clang and Rust compilers (and
79 // possibly other compilers).
81 // Option (b) may weaken the protection for Rust-compiled only code, so it should be provided
82 // as an alternative to a Rust-specific encoding for when mixing Rust and C and C++ -compiled
83 // code. Option (c) would require changes to Clang to use the new ABI.
85 // [1] https://llvm.org/docs/TypeMetadata.html
86 // [2] https://itanium-cxx-abi.github.io/cxx-abi/abi.html
87 // [3] https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-special-vtables
88 // [4] https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-type
90 // FIXME(rcvalle): See comment above.
91 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
92 format!("typeid{}", arg_count)
96 /// The range of distances from the root of what's
97 /// being printed, to the lifetimes in a binder.
98 /// Specifically, a `BrAnon(i)` lifetime has depth
99 /// `lifetime_depths.start + i`, going away from the
100 /// the root and towards its use site, as `i` increases.
101 /// This is used to flatten rustc's pairing of `BrAnon`
102 /// (intra-binder disambiguation) with a `DebruijnIndex`
103 /// (binder addressing), to "true" de Bruijn indices,
104 /// by subtracting the depth of a certain lifetime, from
105 /// the innermost depth at its use site.
106 lifetime_depths: Range<u32>,
109 struct SymbolMangler<'tcx> {
111 binders: Vec<BinderLevel>,
114 /// The length of the prefix in `out` (e.g. 2 for `_R`).
116 /// The values are start positions in `out`, in bytes.
117 paths: FxHashMap<(DefId, &'tcx [GenericArg<'tcx>]), usize>,
118 types: FxHashMap<Ty<'tcx>, usize>,
119 consts: FxHashMap<ty::Const<'tcx>, usize>,
122 impl<'tcx> SymbolMangler<'tcx> {
123 fn push(&mut self, s: &str) {
124 self.out.push_str(s);
127 /// Push a `_`-terminated base 62 integer, using the format
128 /// specified in the RFC as `<base-62-number>`, that is:
129 /// * `x = 0` is encoded as just the `"_"` terminator
130 /// * `x > 0` is encoded as `x - 1` in base 62, followed by `"_"`,
131 /// e.g. `1` becomes `"0_"`, `62` becomes `"Z_"`, etc.
132 fn push_integer_62(&mut self, x: u64) {
133 if let Some(x) = x.checked_sub(1) {
134 base_n::push_str(x as u128, 62, &mut self.out);
139 /// Push a `tag`-prefixed base 62 integer, when larger than `0`, that is:
140 /// * `x = 0` is encoded as `""` (nothing)
141 /// * `x > 0` is encoded as the `tag` followed by `push_integer_62(x - 1)`
142 /// e.g. `1` becomes `tag + "_"`, `2` becomes `tag + "0_"`, etc.
143 fn push_opt_integer_62(&mut self, tag: &str, x: u64) {
144 if let Some(x) = x.checked_sub(1) {
146 self.push_integer_62(x);
150 fn push_disambiguator(&mut self, dis: u64) {
151 self.push_opt_integer_62("s", dis);
154 fn push_ident(&mut self, ident: &str) {
155 let mut use_punycode = false;
156 for b in ident.bytes() {
158 b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
159 0x80..=0xff => use_punycode = true,
160 _ => bug!("symbol_names: bad byte {} in ident {:?}", b, ident),
165 let ident = if use_punycode {
168 // FIXME(eddyb) we should probably roll our own punycode implementation.
169 let mut punycode_bytes = match punycode::encode(ident) {
170 Ok(s) => s.into_bytes(),
171 Err(()) => bug!("symbol_names: punycode encoding failed for ident {:?}", ident),
174 // Replace `-` with `_`.
175 if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
179 // FIXME(eddyb) avoid rechecking UTF-8 validity.
180 punycode_string = String::from_utf8(punycode_bytes).unwrap();
186 let _ = write!(self.out, "{}", ident.len());
188 // Write a separating `_` if necessary (leading digit or `_`).
189 if let Some('_' | '0'..='9') = ident.chars().next() {
196 fn path_append_ns<'a>(
197 mut self: &'a mut Self,
198 print_prefix: impl FnOnce(&'a mut Self) -> Result<&'a mut Self, !>,
202 ) -> Result<&'a mut Self, !> {
205 self = print_prefix(self)?;
206 self.push_disambiguator(disambiguator as u64);
207 self.push_ident(name);
211 fn print_backref(&mut self, i: usize) -> Result<&mut Self, !> {
213 self.push_integer_62((i - self.start_offset) as u64);
218 mut self: &'a mut Self,
219 value: &ty::Binder<'tcx, T>,
220 print_value: impl FnOnce(&'a mut Self, &T) -> Result<&'a mut Self, !>,
221 ) -> Result<&'a mut Self, !>
223 T: TypeFoldable<'tcx>,
225 let regions = if value.has_late_bound_regions() {
226 self.tcx.collect_referenced_late_bound_regions(value)
231 let mut lifetime_depths =
232 self.binders.last().map(|b| b.lifetime_depths.end).map_or(0..0, |i| i..i);
234 let lifetimes = regions
238 _ => bug!("symbol_names: non-anonymized region `{:?}` in `{:?}`", br, value),
241 .map_or(0, |max| max + 1);
243 self.push_opt_integer_62("G", lifetimes as u64);
244 lifetime_depths.end += lifetimes;
246 self.binders.push(BinderLevel { lifetime_depths });
247 self = print_value(self, value.as_ref().skip_binder())?;
254 impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> {
260 type DynExistential = Self;
263 fn tcx(&self) -> TyCtxt<'tcx> {
270 substs: &'tcx [GenericArg<'tcx>],
271 ) -> Result<Self::Path, Self::Error> {
272 if let Some(&i) = self.paths.get(&(def_id, substs)) {
273 return self.print_backref(i);
275 let start = self.out.len();
277 self = self.default_print_def_path(def_id, substs)?;
279 // Only cache paths that do not refer to an enclosing
280 // binder (which would change depending on context).
281 if !substs.iter().any(|k| k.has_escaping_bound_vars()) {
282 self.paths.insert((def_id, substs), start);
290 substs: &'tcx [GenericArg<'tcx>],
291 mut self_ty: Ty<'tcx>,
292 mut impl_trait_ref: Option<ty::TraitRef<'tcx>>,
293 ) -> Result<Self::Path, Self::Error> {
294 let key = self.tcx.def_key(impl_def_id);
295 let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
297 let mut param_env = self.tcx.param_env_reveal_all_normalized(impl_def_id);
298 if !substs.is_empty() {
299 param_env = param_env.subst(self.tcx, substs);
302 match &mut impl_trait_ref {
303 Some(impl_trait_ref) => {
304 assert_eq!(impl_trait_ref.self_ty(), self_ty);
305 *impl_trait_ref = self.tcx.normalize_erasing_regions(param_env, *impl_trait_ref);
306 self_ty = impl_trait_ref.self_ty();
309 self_ty = self.tcx.normalize_erasing_regions(param_env, self_ty);
313 self.push(match impl_trait_ref {
318 // Encode impl generic params if the substitutions contain parameters (implying
319 // polymorphization is enabled) and this isn't an inherent impl.
320 if impl_trait_ref.is_some() && substs.iter().any(|a| a.has_param_types_or_consts()) {
321 self = self.path_generic_args(
324 |cx| cx.print_def_path(parent_def_id, &[]),
326 key.disambiguated_data.disambiguator as u64,
333 self.push_disambiguator(key.disambiguated_data.disambiguator as u64);
334 self = self.print_def_path(parent_def_id, &[])?;
337 self = self_ty.print(self)?;
339 if let Some(trait_ref) = impl_trait_ref {
340 self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?;
346 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
347 let i = match *region {
348 // Erased lifetimes use the index 0, for a
349 // shorter mangling of `L_`.
352 // Late-bound lifetimes use indices starting at 1,
353 // see `BinderLevel` for more details.
354 ty::ReLateBound(debruijn, ty::BoundRegion { kind: ty::BrAnon(i), .. }) => {
355 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
356 let depth = binder.lifetime_depths.start + i;
358 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
361 _ => bug!("symbol_names: non-erased region `{:?}`", region),
364 self.push_integer_62(i as u64);
368 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
369 // Basic types, never cached (single-character).
370 let basic_type = match ty.kind() {
374 ty::Tuple(_) if ty.is_unit() => "u",
375 ty::Int(IntTy::I8) => "a",
376 ty::Int(IntTy::I16) => "s",
377 ty::Int(IntTy::I32) => "l",
378 ty::Int(IntTy::I64) => "x",
379 ty::Int(IntTy::I128) => "n",
380 ty::Int(IntTy::Isize) => "i",
381 ty::Uint(UintTy::U8) => "h",
382 ty::Uint(UintTy::U16) => "t",
383 ty::Uint(UintTy::U32) => "m",
384 ty::Uint(UintTy::U64) => "y",
385 ty::Uint(UintTy::U128) => "o",
386 ty::Uint(UintTy::Usize) => "j",
387 ty::Float(FloatTy::F32) => "f",
388 ty::Float(FloatTy::F64) => "d",
391 // Placeholders (should be demangled as `_`).
392 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => "p",
396 if !basic_type.is_empty() {
397 self.push(basic_type);
401 if let Some(&i) = self.types.get(&ty) {
402 return self.print_backref(i);
404 let start = self.out.len();
407 // Basic types, handled above.
408 ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
411 ty::Tuple(_) if ty.is_unit() => unreachable!(),
413 // Placeholders, also handled as part of basic types.
414 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => {
418 ty::Ref(r, ty, mutbl) => {
419 self.push(match mutbl {
420 hir::Mutability::Not => "R",
421 hir::Mutability::Mut => "Q",
424 self = r.print(self)?;
426 self = ty.print(self)?;
430 self.push(match mt.mutbl {
431 hir::Mutability::Not => "P",
432 hir::Mutability::Mut => "O",
434 self = mt.ty.print(self)?;
437 ty::Array(ty, len) => {
439 self = ty.print(self)?;
440 self = self.print_const(len)?;
444 self = ty.print(self)?;
449 for ty in tys.iter() {
450 self = ty.print(self)?;
455 // Mangle all nominal types as paths.
456 ty::Adt(&ty::AdtDef { did: def_id, .. }, substs)
457 | ty::FnDef(def_id, substs)
458 | ty::Opaque(def_id, substs)
459 | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
460 | ty::Closure(def_id, substs)
461 | ty::Generator(def_id, substs, _) => {
462 self = self.print_def_path(def_id, substs)?;
464 ty::Foreign(def_id) => {
465 self = self.print_def_path(def_id, &[])?;
470 self = self.in_binder(&sig, |mut cx, sig| {
471 if sig.unsafety == hir::Unsafety::Unsafe {
476 Abi::C { unwind: false } => cx.push("KC"),
479 let name = abi.name();
480 if name.contains('-') {
481 cx.push_ident(&name.replace('-', "_"));
487 for &ty in sig.inputs() {
494 sig.output().print(cx)
498 ty::Dynamic(predicates, r) => {
500 self = self.print_dyn_existential(predicates)?;
501 self = r.print(self)?;
504 ty::GeneratorWitness(_) => bug!("symbol_names: unexpected `GeneratorWitness`"),
507 // Only cache types that do not refer to an enclosing
508 // binder (which would change depending on context).
509 if !ty.has_escaping_bound_vars() {
510 self.types.insert(ty, start);
515 fn print_dyn_existential(
517 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
518 ) -> Result<Self::DynExistential, Self::Error> {
519 // Okay, so this is a bit tricky. Imagine we have a trait object like
520 // `dyn for<'a> Foo<'a, Bar = &'a ()>`. When we mangle this, the
521 // output looks really close to the syntax, where the `Bar = &'a ()` bit
522 // is under the same binders (`['a]`) as the `Foo<'a>` bit. However, we
523 // actually desugar these into two separate `ExistentialPredicate`s. We
524 // can't enter/exit the "binder scope" twice though, because then we
525 // would mangle the binders twice. (Also, side note, we merging these
526 // two is kind of difficult, because of potential HRTBs in the Projection
529 // Also worth mentioning: imagine that we instead had
530 // `dyn for<'a> Foo<'a, Bar = &'a ()> + Send`. In this case, `Send` is
531 // under the same binders as `Foo`. Currently, this doesn't matter,
532 // because only *auto traits* are allowed other than the principal trait
533 // and all auto traits don't have any generics. Two things could
534 // make this not an "okay" mangling:
535 // 1) Instead of mangling only *used*
536 // bound vars, we want to mangle *all* bound vars (`for<'b> Send` is a
537 // valid trait predicate);
538 // 2) We allow multiple "principal" traits in the future, or at least
539 // allow in any form another trait predicate that can take generics.
541 // Here we assume that predicates have the following structure:
542 // [<Trait> [{<Projection>}]] [{<Auto>}]
543 // Since any predicates after the first one shouldn't change the binders,
544 // just put them all in the binders of the first.
545 self = self.in_binder(&predicates[0], |mut cx, _| {
546 for predicate in predicates.iter() {
547 // It would be nice to be able to validate bound vars here, but
548 // projections can actually include bound vars from super traits
549 // because of HRTBs (only in the `Self` type). Also, auto traits
550 // could have different bound vars *anyways*.
551 match predicate.as_ref().skip_binder() {
552 ty::ExistentialPredicate::Trait(trait_ref) => {
553 // Use a type that can't appear in defaults of type parameters.
554 let dummy_self = cx.tcx.mk_ty_infer(ty::FreshTy(0));
555 let trait_ref = trait_ref.with_self_ty(cx.tcx, dummy_self);
556 cx = cx.print_def_path(trait_ref.def_id, trait_ref.substs)?;
558 ty::ExistentialPredicate::Projection(projection) => {
559 let name = cx.tcx.associated_item(projection.item_def_id).name;
561 cx.push_ident(name.as_str());
562 cx = match projection.term {
563 ty::Term::Ty(ty) => ty.print(cx),
564 ty::Term::Const(c) => c.print(cx),
567 ty::ExistentialPredicate::AutoTrait(def_id) => {
568 cx = cx.print_def_path(*def_id, &[])?;
579 fn print_const(mut self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
580 // We only mangle a typed value if the const can be evaluated.
581 let ct = ct.eval(self.tcx, ty::ParamEnv::reveal_all());
583 ty::ConstKind::Value(_) => {}
585 // Placeholders (should be demangled as `_`).
586 // NOTE(eddyb) despite `Unevaluated` having a `DefId` (and therefore
587 // a path), even for it we still need to encode a placeholder, as
588 // the path could refer back to e.g. an `impl` using the constant.
589 ty::ConstKind::Unevaluated(_)
590 | ty::ConstKind::Param(_)
591 | ty::ConstKind::Infer(_)
592 | ty::ConstKind::Bound(..)
593 | ty::ConstKind::Placeholder(_)
594 | ty::ConstKind::Error(_) => {
595 // Never cached (single-character).
601 if let Some(&i) = self.consts.get(&ct) {
602 return self.print_backref(i);
604 let start = self.out.len();
606 match ct.ty().kind() {
607 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Char => {
608 self = ct.ty().print(self)?;
610 let mut bits = ct.eval_bits(self.tcx, ty::ParamEnv::reveal_all(), ct.ty());
612 // Negative integer values are mangled using `n` as a "sign prefix".
613 if let ty::Int(ity) = ct.ty().kind() {
615 Integer::from_int_ty(&self.tcx, *ity).size().sign_extend(bits) as i128;
619 bits = val.unsigned_abs();
622 let _ = write!(self.out, "{:x}_", bits);
625 // HACK(eddyb) because `ty::Const` only supports sized values (for now),
626 // we can't use `deref_const` + supporting `str`, we have to specially
627 // handle `&str` and include both `&` ("R") and `str` ("e") prefixes.
628 ty::Ref(_, ty, hir::Mutability::Not) if *ty == self.tcx.types.str_ => {
631 ty::ConstKind::Value(ConstValue::Slice { data, start, end }) => {
632 // NOTE(eddyb) the following comment was kept from `ty::print::pretty`:
633 // The `inspect` here is okay since we checked the bounds, and there are no
634 // relocations (we have an active `str` reference here). We don't use this
635 // result to affect interpreter execution.
638 .inspect_with_uninit_and_ptr_outside_interpreter(start..end);
639 let s = std::str::from_utf8(slice).expect("non utf8 str from miri");
642 // FIXME(eddyb) use a specialized hex-encoding loop.
643 for byte in s.bytes() {
644 let _ = write!(self.out, "{:02x}", byte);
650 bug!("symbol_names: unsupported `&str` constant: {:?}", ct);
655 ty::Ref(_, _, mutbl) => {
656 self.push(match mutbl {
657 hir::Mutability::Not => "R",
658 hir::Mutability::Mut => "Q",
660 self = self.tcx.deref_const(ty::ParamEnv::reveal_all().and(ct)).print(self)?;
663 ty::Array(..) | ty::Tuple(..) | ty::Adt(..) => {
664 let contents = self.tcx.destructure_const(ty::ParamEnv::reveal_all().and(ct));
665 let fields = contents.fields.iter().copied();
667 let print_field_list = |mut this: Self| {
668 for field in fields.clone() {
669 this = field.print(this)?;
675 match *ct.ty().kind() {
678 self = print_field_list(self)?;
682 self = print_field_list(self)?;
684 ty::Adt(def, substs) => {
686 contents.variant.expect("destructed const of adt without variant idx");
687 let variant_def = &def.variants[variant_idx];
690 self = self.print_def_path(variant_def.def_id, substs)?;
692 match variant_def.ctor_kind {
698 self = print_field_list(self)?;
700 CtorKind::Fictive => {
702 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
703 // HACK(eddyb) this mimics `path_append`,
704 // instead of simply using `field_def.ident`,
705 // just to be able to handle disambiguators.
706 let disambiguated_field =
707 self.tcx.def_key(field_def.did).disambiguated_data;
708 let field_name = disambiguated_field.data.get_opt_name();
709 self.push_disambiguator(
710 disambiguated_field.disambiguator as u64,
712 self.push_ident(field_name.unwrap_or(kw::Empty).as_str());
714 self = field.print(self)?;
725 bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct.ty(), ct);
729 // Only cache consts that do not refer to an enclosing
730 // binder (which would change depending on context).
731 if !ct.has_escaping_bound_vars() {
732 self.consts.insert(ct, start);
737 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
739 let stable_crate_id = self.tcx.def_path_hash(cnum.as_def_id()).stable_crate_id();
740 self.push_disambiguator(stable_crate_id.to_u64());
741 let name = self.tcx.crate_name(cnum);
742 self.push_ident(name.as_str());
749 trait_ref: Option<ty::TraitRef<'tcx>>,
750 ) -> Result<Self::Path, Self::Error> {
751 assert!(trait_ref.is_some());
752 let trait_ref = trait_ref.unwrap();
755 self = self_ty.print(self)?;
756 self.print_def_path(trait_ref.def_id, trait_ref.substs)
761 _: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
762 _: &DisambiguatedDefPathData,
764 _: Option<ty::TraitRef<'tcx>>,
765 ) -> Result<Self::Path, Self::Error> {
766 // Inlined into `print_impl_path`
772 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
773 disambiguated_data: &DisambiguatedDefPathData,
774 ) -> Result<Self::Path, Self::Error> {
775 let ns = match disambiguated_data.data {
776 // Extern block segments can be skipped, names from extern blocks
777 // are effectively living in their parent modules.
778 DefPathData::ForeignMod => return print_prefix(self),
780 // Uppercase categories are more stable than lowercase ones.
781 DefPathData::TypeNs(_) => 't',
782 DefPathData::ValueNs(_) => 'v',
783 DefPathData::ClosureExpr => 'C',
784 DefPathData::Ctor => 'c',
785 DefPathData::AnonConst => 'k',
786 DefPathData::ImplTrait => 'i',
788 // These should never show up as `path_append` arguments.
789 DefPathData::CrateRoot
792 | DefPathData::MacroNs(_)
793 | DefPathData::LifetimeNs(_) => {
794 bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
798 let name = disambiguated_data.data.get_opt_name();
803 disambiguated_data.disambiguator as u64,
804 name.unwrap_or(kw::Empty).as_str(),
808 fn path_generic_args(
810 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
811 args: &[GenericArg<'tcx>],
812 ) -> Result<Self::Path, Self::Error> {
813 // Don't print any regions if they're all erased.
814 let print_regions = args.iter().any(|arg| match arg.unpack() {
815 GenericArgKind::Lifetime(r) => !r.is_erased(),
818 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
819 GenericArgKind::Lifetime(_) => print_regions,
823 if args.clone().next().is_none() {
824 return print_prefix(self);
828 self = print_prefix(self)?;
831 GenericArgKind::Lifetime(lt) => {
832 self = lt.print(self)?;
834 GenericArgKind::Type(ty) => {
835 self = ty.print(self)?;
837 GenericArgKind::Const(c) => {
839 self = c.print(self)?;