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<&'tcx 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()
321 && substs.iter().any(|a| a.definitely_has_param_types_or_consts(self.tcx))
323 self = self.path_generic_args(
326 |cx| cx.print_def_path(parent_def_id, &[]),
328 key.disambiguated_data.disambiguator as u64,
335 self.push_disambiguator(key.disambiguated_data.disambiguator as u64);
336 self = self.print_def_path(parent_def_id, &[])?;
339 self = self_ty.print(self)?;
341 if let Some(trait_ref) = impl_trait_ref {
342 self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?;
348 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
349 let i = match *region {
350 // Erased lifetimes use the index 0, for a
351 // shorter mangling of `L_`.
354 // Late-bound lifetimes use indices starting at 1,
355 // see `BinderLevel` for more details.
356 ty::ReLateBound(debruijn, ty::BoundRegion { kind: ty::BrAnon(i), .. }) => {
357 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
358 let depth = binder.lifetime_depths.start + i;
360 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
363 _ => bug!("symbol_names: non-erased region `{:?}`", region),
366 self.push_integer_62(i as u64);
370 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
371 // Basic types, never cached (single-character).
372 let basic_type = match ty.kind() {
376 ty::Tuple(_) if ty.is_unit() => "u",
377 ty::Int(IntTy::I8) => "a",
378 ty::Int(IntTy::I16) => "s",
379 ty::Int(IntTy::I32) => "l",
380 ty::Int(IntTy::I64) => "x",
381 ty::Int(IntTy::I128) => "n",
382 ty::Int(IntTy::Isize) => "i",
383 ty::Uint(UintTy::U8) => "h",
384 ty::Uint(UintTy::U16) => "t",
385 ty::Uint(UintTy::U32) => "m",
386 ty::Uint(UintTy::U64) => "y",
387 ty::Uint(UintTy::U128) => "o",
388 ty::Uint(UintTy::Usize) => "j",
389 ty::Float(FloatTy::F32) => "f",
390 ty::Float(FloatTy::F64) => "d",
393 // Placeholders (should be demangled as `_`).
394 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => "p",
398 if !basic_type.is_empty() {
399 self.push(basic_type);
403 if let Some(&i) = self.types.get(&ty) {
404 return self.print_backref(i);
406 let start = self.out.len();
409 // Basic types, handled above.
410 ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
413 ty::Tuple(_) if ty.is_unit() => unreachable!(),
415 // Placeholders, also handled as part of basic types.
416 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => {
420 ty::Ref(r, ty, mutbl) => {
421 self.push(match mutbl {
422 hir::Mutability::Not => "R",
423 hir::Mutability::Mut => "Q",
425 if *r != ty::ReErased {
426 self = r.print(self)?;
428 self = ty.print(self)?;
432 self.push(match mt.mutbl {
433 hir::Mutability::Not => "P",
434 hir::Mutability::Mut => "O",
436 self = mt.ty.print(self)?;
439 ty::Array(ty, len) => {
441 self = ty.print(self)?;
442 self = self.print_const(len)?;
446 self = ty.print(self)?;
451 for ty in tys.iter().map(|k| k.expect_ty()) {
452 self = ty.print(self)?;
457 // Mangle all nominal types as paths.
458 ty::Adt(&ty::AdtDef { did: def_id, .. }, substs)
459 | ty::FnDef(def_id, substs)
460 | ty::Opaque(def_id, substs)
461 | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
462 | ty::Closure(def_id, substs)
463 | ty::Generator(def_id, substs, _) => {
464 self = self.print_def_path(def_id, substs)?;
466 ty::Foreign(def_id) => {
467 self = self.print_def_path(def_id, &[])?;
472 self = self.in_binder(&sig, |mut cx, sig| {
473 if sig.unsafety == hir::Unsafety::Unsafe {
478 Abi::C { unwind: false } => cx.push("KC"),
481 let name = abi.name();
482 if name.contains('-') {
483 cx.push_ident(&name.replace('-', "_"));
489 for &ty in sig.inputs() {
496 sig.output().print(cx)
500 ty::Dynamic(predicates, r) => {
502 self = self.print_dyn_existential(predicates)?;
503 self = r.print(self)?;
506 ty::GeneratorWitness(_) => bug!("symbol_names: unexpected `GeneratorWitness`"),
509 // Only cache types that do not refer to an enclosing
510 // binder (which would change depending on context).
511 if !ty.has_escaping_bound_vars() {
512 self.types.insert(ty, start);
517 fn print_dyn_existential(
519 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
520 ) -> Result<Self::DynExistential, Self::Error> {
521 // Okay, so this is a bit tricky. Imagine we have a trait object like
522 // `dyn for<'a> Foo<'a, Bar = &'a ()>`. When we mangle this, the
523 // output looks really close to the syntax, where the `Bar = &'a ()` bit
524 // is under the same binders (`['a]`) as the `Foo<'a>` bit. However, we
525 // actually desugar these into two separate `ExistentialPredicate`s. We
526 // can't enter/exit the "binder scope" twice though, because then we
527 // would mangle the binders twice. (Also, side note, we merging these
528 // two is kind of difficult, because of potential HRTBs in the Projection
531 // Also worth mentioning: imagine that we instead had
532 // `dyn for<'a> Foo<'a, Bar = &'a ()> + Send`. In this case, `Send` is
533 // under the same binders as `Foo`. Currently, this doesn't matter,
534 // because only *auto traits* are allowed other than the principal trait
535 // and all auto traits don't have any generics. Two things could
536 // make this not an "okay" mangling:
537 // 1) Instead of mangling only *used*
538 // bound vars, we want to mangle *all* bound vars (`for<'b> Send` is a
539 // valid trait predicate);
540 // 2) We allow multiple "principal" traits in the future, or at least
541 // allow in any form another trait predicate that can take generics.
543 // Here we assume that predicates have the following structure:
544 // [<Trait> [{<Projection>}]] [{<Auto>}]
545 // Since any predicates after the first one shouldn't change the binders,
546 // just put them all in the binders of the first.
547 self = self.in_binder(&predicates[0], |mut cx, _| {
548 for predicate in predicates.iter() {
549 // It would be nice to be able to validate bound vars here, but
550 // projections can actually include bound vars from super traits
551 // because of HRTBs (only in the `Self` type). Also, auto traits
552 // could have different bound vars *anyways*.
553 match predicate.as_ref().skip_binder() {
554 ty::ExistentialPredicate::Trait(trait_ref) => {
555 // Use a type that can't appear in defaults of type parameters.
556 let dummy_self = cx.tcx.mk_ty_infer(ty::FreshTy(0));
557 let trait_ref = trait_ref.with_self_ty(cx.tcx, dummy_self);
558 cx = cx.print_def_path(trait_ref.def_id, trait_ref.substs)?;
560 ty::ExistentialPredicate::Projection(projection) => {
561 let name = cx.tcx.associated_item(projection.item_def_id).ident;
563 cx.push_ident(name.as_str());
564 cx = projection.ty.print(cx)?;
566 ty::ExistentialPredicate::AutoTrait(def_id) => {
567 cx = cx.print_def_path(*def_id, &[])?;
578 fn print_const(mut self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
579 // We only mangle a typed value if the const can be evaluated.
580 let ct = ct.eval(self.tcx, ty::ParamEnv::reveal_all());
582 ty::ConstKind::Value(_) => {}
584 // Placeholders (should be demangled as `_`).
585 // NOTE(eddyb) despite `Unevaluated` having a `DefId` (and therefore
586 // a path), even for it we still need to encode a placeholder, as
587 // the path could refer back to e.g. an `impl` using the constant.
588 ty::ConstKind::Unevaluated(_)
589 | ty::ConstKind::Param(_)
590 | ty::ConstKind::Infer(_)
591 | ty::ConstKind::Bound(..)
592 | ty::ConstKind::Placeholder(_)
593 | ty::ConstKind::Error(_) => {
594 // Never cached (single-character).
600 if let Some(&i) = self.consts.get(&ct) {
601 return self.print_backref(i);
603 let start = self.out.len();
606 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Char => {
607 self = ct.ty.print(self)?;
609 let mut bits = ct.eval_bits(self.tcx, ty::ParamEnv::reveal_all(), ct.ty);
611 // Negative integer values are mangled using `n` as a "sign prefix".
612 if let ty::Int(ity) = ct.ty.kind() {
614 Integer::from_int_ty(&self.tcx, *ity).size().sign_extend(bits) as i128;
618 bits = val.unsigned_abs();
621 let _ = write!(self.out, "{:x}_", bits);
624 // HACK(eddyb) because `ty::Const` only supports sized values (for now),
625 // we can't use `deref_const` + supporting `str`, we have to specially
626 // handle `&str` and include both `&` ("R") and `str` ("e") prefixes.
627 ty::Ref(_, ty, hir::Mutability::Not) if *ty == self.tcx.types.str_ => {
630 ty::ConstKind::Value(ConstValue::Slice { data, start, end }) => {
631 // NOTE(eddyb) the following comment was kept from `ty::print::pretty`:
632 // The `inspect` here is okay since we checked the bounds, and there are no
633 // relocations (we have an active `str` reference here). We don't use this
634 // result to affect interpreter execution.
636 data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
637 let s = std::str::from_utf8(slice).expect("non utf8 str from miri");
640 // FIXME(eddyb) use a specialized hex-encoding loop.
641 for byte in s.bytes() {
642 let _ = write!(self.out, "{:02x}", byte);
648 bug!("symbol_names: unsupported `&str` constant: {:?}", ct);
653 ty::Ref(_, _, mutbl) => {
654 self.push(match mutbl {
655 hir::Mutability::Not => "R",
656 hir::Mutability::Mut => "Q",
658 self = self.tcx.deref_const(ty::ParamEnv::reveal_all().and(ct)).print(self)?;
661 ty::Array(..) | ty::Tuple(..) | ty::Adt(..) => {
662 let contents = self.tcx.destructure_const(ty::ParamEnv::reveal_all().and(ct));
663 let fields = contents.fields.iter().copied();
665 let print_field_list = |mut this: Self| {
666 for field in fields.clone() {
667 this = field.print(this)?;
673 match *ct.ty.kind() {
676 self = print_field_list(self)?;
680 self = print_field_list(self)?;
682 ty::Adt(def, substs) => {
684 contents.variant.expect("destructed const of adt without variant idx");
685 let variant_def = &def.variants[variant_idx];
688 self = self.print_def_path(variant_def.def_id, substs)?;
690 match variant_def.ctor_kind {
696 self = print_field_list(self)?;
698 CtorKind::Fictive => {
700 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
701 // HACK(eddyb) this mimics `path_append`,
702 // instead of simply using `field_def.ident`,
703 // just to be able to handle disambiguators.
704 let disambiguated_field =
705 self.tcx.def_key(field_def.did).disambiguated_data;
706 let field_name = disambiguated_field.data.get_opt_name();
707 self.push_disambiguator(
708 disambiguated_field.disambiguator as u64,
710 self.push_ident(field_name.unwrap_or(kw::Empty).as_str());
712 self = field.print(self)?;
723 bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct.ty, ct);
727 // Only cache consts that do not refer to an enclosing
728 // binder (which would change depending on context).
729 if !ct.has_escaping_bound_vars() {
730 self.consts.insert(ct, start);
735 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
737 let stable_crate_id = self.tcx.def_path_hash(cnum.as_def_id()).stable_crate_id();
738 self.push_disambiguator(stable_crate_id.to_u64());
739 let name = self.tcx.crate_name(cnum);
740 self.push_ident(name.as_str());
747 trait_ref: Option<ty::TraitRef<'tcx>>,
748 ) -> Result<Self::Path, Self::Error> {
749 assert!(trait_ref.is_some());
750 let trait_ref = trait_ref.unwrap();
753 self = self_ty.print(self)?;
754 self.print_def_path(trait_ref.def_id, trait_ref.substs)
759 _: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
760 _: &DisambiguatedDefPathData,
762 _: Option<ty::TraitRef<'tcx>>,
763 ) -> Result<Self::Path, Self::Error> {
764 // Inlined into `print_impl_path`
770 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
771 disambiguated_data: &DisambiguatedDefPathData,
772 ) -> Result<Self::Path, Self::Error> {
773 let ns = match disambiguated_data.data {
774 // FIXME: It shouldn't be necessary to add anything for extern block segments,
775 // but we add 't' for backward compatibility.
776 DefPathData::ForeignMod => 't',
778 // Uppercase categories are more stable than lowercase ones.
779 DefPathData::TypeNs(_) => 't',
780 DefPathData::ValueNs(_) => 'v',
781 DefPathData::ClosureExpr => 'C',
782 DefPathData::Ctor => 'c',
783 DefPathData::AnonConst => 'k',
784 DefPathData::ImplTrait => 'i',
786 // These should never show up as `path_append` arguments.
787 DefPathData::CrateRoot
790 | DefPathData::MacroNs(_)
791 | DefPathData::LifetimeNs(_) => {
792 bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
796 let name = disambiguated_data.data.get_opt_name();
801 disambiguated_data.disambiguator as u64,
802 name.unwrap_or(kw::Empty).as_str(),
806 fn path_generic_args(
808 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
809 args: &[GenericArg<'tcx>],
810 ) -> Result<Self::Path, Self::Error> {
811 // Don't print any regions if they're all erased.
812 let print_regions = args.iter().any(|arg| match arg.unpack() {
813 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
816 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
817 GenericArgKind::Lifetime(_) => print_regions,
821 if args.clone().next().is_none() {
822 return print_prefix(self);
826 self = print_prefix(self)?;
829 GenericArgKind::Lifetime(lt) => {
830 self = lt.print(self)?;
832 GenericArgKind::Type(ty) => {
833 self = ty.print(self)?;
835 GenericArgKind::Const(c) => {
837 self = c.print(self)?;