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::{
13 self, EarlyBinder, FloatTy, Instance, IntTy, Ty, TyCtxt, TypeFoldable, UintTy,
15 use rustc_span::symbol::kw;
16 use rustc_target::abi::call::FnAbi;
17 use rustc_target::abi::Integer;
18 use rustc_target::spec::abi::Abi;
24 pub(super) fn mangle<'tcx>(
26 instance: Instance<'tcx>,
27 instantiating_crate: Option<CrateNum>,
29 let def_id = instance.def_id();
30 // FIXME(eddyb) this should ideally not be needed.
31 let substs = tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), instance.substs);
34 let mut cx = &mut SymbolMangler {
36 start_offset: prefix.len(),
37 paths: FxHashMap::default(),
38 types: FxHashMap::default(),
39 consts: FxHashMap::default(),
41 out: String::from(prefix),
44 // Append `::{shim:...#0}` to shims that can coexist with a non-shim instance.
45 let shim_kind = match instance.def {
46 ty::InstanceDef::VtableShim(_) => Some("vtable"),
47 ty::InstanceDef::ReifyShim(_) => Some("reify"),
52 cx = if let Some(shim_kind) = shim_kind {
53 cx.path_append_ns(|cx| cx.print_def_path(def_id, substs), 'S', 0, shim_kind).unwrap()
55 cx.print_def_path(def_id, substs).unwrap()
57 if let Some(instantiating_crate) = instantiating_crate {
58 cx = cx.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap();
60 std::mem::take(&mut cx.out)
63 pub(super) fn mangle_typeid_for_fnabi<'tcx>(
65 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
67 // LLVM uses type metadata to allow IR modules to aggregate pointers by their types.[1] This
68 // type metadata is used by LLVM Control Flow Integrity to test whether a given pointer is
69 // associated with a type identifier (i.e., test type membership).
71 // Clang uses the Itanium C++ ABI's[2] virtual tables and RTTI typeinfo structure name[3] as
72 // type metadata identifiers for function pointers. The typeinfo name encoding is a
73 // two-character code (i.e., “TS”) prefixed to the type encoding for the function.
75 // For cross-language LLVM CFI support, a compatible encoding must be used by either
77 // a. Using a superset of types that encompasses types used by Clang (i.e., Itanium C++ ABI's
78 // type encodings[4]), or at least types used at the FFI boundary.
79 // b. Reducing the types to the least common denominator between types used by Clang (or at
80 // least types used at the FFI boundary) and Rust compilers (if even possible).
81 // c. Creating a new ABI for cross-language CFI and using it for Clang and Rust compilers (and
82 // possibly other compilers).
84 // Option (b) may weaken the protection for Rust-compiled only code, so it should be provided
85 // as an alternative to a Rust-specific encoding for when mixing Rust and C and C++ -compiled
86 // code. Option (c) would require changes to Clang to use the new ABI.
88 // [1] https://llvm.org/docs/TypeMetadata.html
89 // [2] https://itanium-cxx-abi.github.io/cxx-abi/abi.html
90 // [3] https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-special-vtables
91 // [4] https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-type
93 // FIXME(rcvalle): See comment above.
94 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
95 format!("typeid{}", arg_count)
99 /// The range of distances from the root of what's
100 /// being printed, to the lifetimes in a binder.
101 /// Specifically, a `BrAnon(i)` lifetime has depth
102 /// `lifetime_depths.start + i`, going away from the
103 /// the root and towards its use site, as `i` increases.
104 /// This is used to flatten rustc's pairing of `BrAnon`
105 /// (intra-binder disambiguation) with a `DebruijnIndex`
106 /// (binder addressing), to "true" de Bruijn indices,
107 /// by subtracting the depth of a certain lifetime, from
108 /// the innermost depth at its use site.
109 lifetime_depths: Range<u32>,
112 struct SymbolMangler<'tcx> {
114 binders: Vec<BinderLevel>,
117 /// The length of the prefix in `out` (e.g. 2 for `_R`).
119 /// The values are start positions in `out`, in bytes.
120 paths: FxHashMap<(DefId, &'tcx [GenericArg<'tcx>]), usize>,
121 types: FxHashMap<Ty<'tcx>, usize>,
122 consts: FxHashMap<ty::Const<'tcx>, usize>,
125 impl<'tcx> SymbolMangler<'tcx> {
126 fn push(&mut self, s: &str) {
127 self.out.push_str(s);
130 /// Push a `_`-terminated base 62 integer, using the format
131 /// specified in the RFC as `<base-62-number>`, that is:
132 /// * `x = 0` is encoded as just the `"_"` terminator
133 /// * `x > 0` is encoded as `x - 1` in base 62, followed by `"_"`,
134 /// e.g. `1` becomes `"0_"`, `62` becomes `"Z_"`, etc.
135 fn push_integer_62(&mut self, x: u64) {
136 if let Some(x) = x.checked_sub(1) {
137 base_n::push_str(x as u128, 62, &mut self.out);
142 /// Push a `tag`-prefixed base 62 integer, when larger than `0`, that is:
143 /// * `x = 0` is encoded as `""` (nothing)
144 /// * `x > 0` is encoded as the `tag` followed by `push_integer_62(x - 1)`
145 /// e.g. `1` becomes `tag + "_"`, `2` becomes `tag + "0_"`, etc.
146 fn push_opt_integer_62(&mut self, tag: &str, x: u64) {
147 if let Some(x) = x.checked_sub(1) {
149 self.push_integer_62(x);
153 fn push_disambiguator(&mut self, dis: u64) {
154 self.push_opt_integer_62("s", dis);
157 fn push_ident(&mut self, ident: &str) {
158 let mut use_punycode = false;
159 for b in ident.bytes() {
161 b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
162 0x80..=0xff => use_punycode = true,
163 _ => bug!("symbol_names: bad byte {} in ident {:?}", b, ident),
168 let ident = if use_punycode {
171 // FIXME(eddyb) we should probably roll our own punycode implementation.
172 let mut punycode_bytes = match punycode::encode(ident) {
173 Ok(s) => s.into_bytes(),
174 Err(()) => bug!("symbol_names: punycode encoding failed for ident {:?}", ident),
177 // Replace `-` with `_`.
178 if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
182 // FIXME(eddyb) avoid rechecking UTF-8 validity.
183 punycode_string = String::from_utf8(punycode_bytes).unwrap();
189 let _ = write!(self.out, "{}", ident.len());
191 // Write a separating `_` if necessary (leading digit or `_`).
192 if let Some('_' | '0'..='9') = ident.chars().next() {
199 fn path_append_ns<'a>(
200 mut self: &'a mut Self,
201 print_prefix: impl FnOnce(&'a mut Self) -> Result<&'a mut Self, !>,
205 ) -> Result<&'a mut Self, !> {
208 self = print_prefix(self)?;
209 self.push_disambiguator(disambiguator as u64);
210 self.push_ident(name);
214 fn print_backref(&mut self, i: usize) -> Result<&mut Self, !> {
216 self.push_integer_62((i - self.start_offset) as u64);
221 mut self: &'a mut Self,
222 value: &ty::Binder<'tcx, T>,
223 print_value: impl FnOnce(&'a mut Self, &T) -> Result<&'a mut Self, !>,
224 ) -> Result<&'a mut Self, !>
226 T: TypeFoldable<'tcx>,
228 let regions = if value.has_late_bound_regions() {
229 self.tcx.collect_referenced_late_bound_regions(value)
234 let mut lifetime_depths =
235 self.binders.last().map(|b| b.lifetime_depths.end).map_or(0..0, |i| i..i);
237 let lifetimes = regions
241 _ => bug!("symbol_names: non-anonymized region `{:?}` in `{:?}`", br, value),
244 .map_or(0, |max| max + 1);
246 self.push_opt_integer_62("G", lifetimes as u64);
247 lifetime_depths.end += lifetimes;
249 self.binders.push(BinderLevel { lifetime_depths });
250 self = print_value(self, value.as_ref().skip_binder())?;
257 impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> {
263 type DynExistential = Self;
266 fn tcx(&self) -> TyCtxt<'tcx> {
273 substs: &'tcx [GenericArg<'tcx>],
274 ) -> Result<Self::Path, Self::Error> {
275 if let Some(&i) = self.paths.get(&(def_id, substs)) {
276 return self.print_backref(i);
278 let start = self.out.len();
280 self = self.default_print_def_path(def_id, substs)?;
282 // Only cache paths that do not refer to an enclosing
283 // binder (which would change depending on context).
284 if !substs.iter().any(|k| k.has_escaping_bound_vars()) {
285 self.paths.insert((def_id, substs), start);
293 substs: &'tcx [GenericArg<'tcx>],
294 mut self_ty: Ty<'tcx>,
295 mut impl_trait_ref: Option<ty::TraitRef<'tcx>>,
296 ) -> Result<Self::Path, Self::Error> {
297 let key = self.tcx.def_key(impl_def_id);
298 let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
300 let mut param_env = self.tcx.param_env_reveal_all_normalized(impl_def_id);
301 if !substs.is_empty() {
302 param_env = EarlyBinder(param_env).subst(self.tcx, substs);
305 match &mut impl_trait_ref {
306 Some(impl_trait_ref) => {
307 assert_eq!(impl_trait_ref.self_ty(), self_ty);
308 *impl_trait_ref = self.tcx.normalize_erasing_regions(param_env, *impl_trait_ref);
309 self_ty = impl_trait_ref.self_ty();
312 self_ty = self.tcx.normalize_erasing_regions(param_env, self_ty);
316 self.push(match impl_trait_ref {
321 // Encode impl generic params if the substitutions contain parameters (implying
322 // polymorphization is enabled) and this isn't an inherent impl.
323 if impl_trait_ref.is_some() && substs.iter().any(|a| a.has_param_types_or_consts()) {
324 self = self.path_generic_args(
327 |cx| cx.print_def_path(parent_def_id, &[]),
329 key.disambiguated_data.disambiguator as u64,
336 self.push_disambiguator(key.disambiguated_data.disambiguator as u64);
337 self = self.print_def_path(parent_def_id, &[])?;
340 self = self_ty.print(self)?;
342 if let Some(trait_ref) = impl_trait_ref {
343 self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?;
349 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
350 let i = match *region {
351 // Erased lifetimes use the index 0, for a
352 // shorter mangling of `L_`.
355 // Late-bound lifetimes use indices starting at 1,
356 // see `BinderLevel` for more details.
357 ty::ReLateBound(debruijn, ty::BoundRegion { kind: ty::BrAnon(i), .. }) => {
358 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
359 let depth = binder.lifetime_depths.start + i;
361 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
364 _ => bug!("symbol_names: non-erased region `{:?}`", region),
367 self.push_integer_62(i as u64);
371 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
372 // Basic types, never cached (single-character).
373 let basic_type = match ty.kind() {
377 ty::Tuple(_) if ty.is_unit() => "u",
378 ty::Int(IntTy::I8) => "a",
379 ty::Int(IntTy::I16) => "s",
380 ty::Int(IntTy::I32) => "l",
381 ty::Int(IntTy::I64) => "x",
382 ty::Int(IntTy::I128) => "n",
383 ty::Int(IntTy::Isize) => "i",
384 ty::Uint(UintTy::U8) => "h",
385 ty::Uint(UintTy::U16) => "t",
386 ty::Uint(UintTy::U32) => "m",
387 ty::Uint(UintTy::U64) => "y",
388 ty::Uint(UintTy::U128) => "o",
389 ty::Uint(UintTy::Usize) => "j",
390 ty::Float(FloatTy::F32) => "f",
391 ty::Float(FloatTy::F64) => "d",
394 // Placeholders (should be demangled as `_`).
395 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => "p",
399 if !basic_type.is_empty() {
400 self.push(basic_type);
404 if let Some(&i) = self.types.get(&ty) {
405 return self.print_backref(i);
407 let start = self.out.len();
410 // Basic types, handled above.
411 ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
414 ty::Tuple(_) if ty.is_unit() => unreachable!(),
416 // Placeholders, also handled as part of basic types.
417 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => {
421 ty::Ref(r, ty, mutbl) => {
422 self.push(match mutbl {
423 hir::Mutability::Not => "R",
424 hir::Mutability::Mut => "Q",
427 self = r.print(self)?;
429 self = ty.print(self)?;
433 self.push(match mt.mutbl {
434 hir::Mutability::Not => "P",
435 hir::Mutability::Mut => "O",
437 self = mt.ty.print(self)?;
440 ty::Array(ty, len) => {
442 self = ty.print(self)?;
443 self = self.print_const(len)?;
447 self = ty.print(self)?;
452 for ty in tys.iter() {
453 self = ty.print(self)?;
458 // Mangle all nominal types as paths.
459 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), substs)
460 | ty::FnDef(def_id, substs)
461 | ty::Opaque(def_id, substs)
462 | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
463 | ty::Closure(def_id, substs)
464 | ty::Generator(def_id, substs, _) => {
465 self = self.print_def_path(def_id, substs)?;
467 ty::Foreign(def_id) => {
468 self = self.print_def_path(def_id, &[])?;
473 self = self.in_binder(&sig, |mut cx, sig| {
474 if sig.unsafety == hir::Unsafety::Unsafe {
479 Abi::C { unwind: false } => cx.push("KC"),
482 let name = abi.name();
483 if name.contains('-') {
484 cx.push_ident(&name.replace('-', "_"));
490 for &ty in sig.inputs() {
497 sig.output().print(cx)
501 ty::Dynamic(predicates, r) => {
503 self = self.print_dyn_existential(predicates)?;
504 self = r.print(self)?;
507 ty::GeneratorWitness(_) => bug!("symbol_names: unexpected `GeneratorWitness`"),
510 // Only cache types that do not refer to an enclosing
511 // binder (which would change depending on context).
512 if !ty.has_escaping_bound_vars() {
513 self.types.insert(ty, start);
518 fn print_dyn_existential(
520 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
521 ) -> Result<Self::DynExistential, Self::Error> {
522 // Okay, so this is a bit tricky. Imagine we have a trait object like
523 // `dyn for<'a> Foo<'a, Bar = &'a ()>`. When we mangle this, the
524 // output looks really close to the syntax, where the `Bar = &'a ()` bit
525 // is under the same binders (`['a]`) as the `Foo<'a>` bit. However, we
526 // actually desugar these into two separate `ExistentialPredicate`s. We
527 // can't enter/exit the "binder scope" twice though, because then we
528 // would mangle the binders twice. (Also, side note, we merging these
529 // two is kind of difficult, because of potential HRTBs in the Projection
532 // Also worth mentioning: imagine that we instead had
533 // `dyn for<'a> Foo<'a, Bar = &'a ()> + Send`. In this case, `Send` is
534 // under the same binders as `Foo`. Currently, this doesn't matter,
535 // because only *auto traits* are allowed other than the principal trait
536 // and all auto traits don't have any generics. Two things could
537 // make this not an "okay" mangling:
538 // 1) Instead of mangling only *used*
539 // bound vars, we want to mangle *all* bound vars (`for<'b> Send` is a
540 // valid trait predicate);
541 // 2) We allow multiple "principal" traits in the future, or at least
542 // allow in any form another trait predicate that can take generics.
544 // Here we assume that predicates have the following structure:
545 // [<Trait> [{<Projection>}]] [{<Auto>}]
546 // Since any predicates after the first one shouldn't change the binders,
547 // just put them all in the binders of the first.
548 self = self.in_binder(&predicates[0], |mut cx, _| {
549 for predicate in predicates.iter() {
550 // It would be nice to be able to validate bound vars here, but
551 // projections can actually include bound vars from super traits
552 // because of HRTBs (only in the `Self` type). Also, auto traits
553 // could have different bound vars *anyways*.
554 match predicate.as_ref().skip_binder() {
555 ty::ExistentialPredicate::Trait(trait_ref) => {
556 // Use a type that can't appear in defaults of type parameters.
557 let dummy_self = cx.tcx.mk_ty_infer(ty::FreshTy(0));
558 let trait_ref = trait_ref.with_self_ty(cx.tcx, dummy_self);
559 cx = cx.print_def_path(trait_ref.def_id, trait_ref.substs)?;
561 ty::ExistentialPredicate::Projection(projection) => {
562 let name = cx.tcx.associated_item(projection.item_def_id).name;
564 cx.push_ident(name.as_str());
565 cx = match projection.term {
566 ty::Term::Ty(ty) => ty.print(cx),
567 ty::Term::Const(c) => c.print(cx),
570 ty::ExistentialPredicate::AutoTrait(def_id) => {
571 cx = cx.print_def_path(*def_id, &[])?;
582 fn print_const(mut self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
583 // We only mangle a typed value if the const can be evaluated.
584 let ct = ct.eval(self.tcx, ty::ParamEnv::reveal_all());
586 ty::ConstKind::Value(_) => {}
588 // Placeholders (should be demangled as `_`).
589 // NOTE(eddyb) despite `Unevaluated` having a `DefId` (and therefore
590 // a path), even for it we still need to encode a placeholder, as
591 // the path could refer back to e.g. an `impl` using the constant.
592 ty::ConstKind::Unevaluated(_)
593 | ty::ConstKind::Param(_)
594 | ty::ConstKind::Infer(_)
595 | ty::ConstKind::Bound(..)
596 | ty::ConstKind::Placeholder(_)
597 | ty::ConstKind::Error(_) => {
598 // Never cached (single-character).
604 if let Some(&i) = self.consts.get(&ct) {
605 return self.print_backref(i);
607 let start = self.out.len();
609 match ct.ty().kind() {
610 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Char => {
611 self = ct.ty().print(self)?;
613 let mut bits = ct.eval_bits(self.tcx, ty::ParamEnv::reveal_all(), ct.ty());
615 // Negative integer values are mangled using `n` as a "sign prefix".
616 if let ty::Int(ity) = ct.ty().kind() {
618 Integer::from_int_ty(&self.tcx, *ity).size().sign_extend(bits) as i128;
622 bits = val.unsigned_abs();
625 let _ = write!(self.out, "{:x}_", bits);
628 // HACK(eddyb) because `ty::Const` only supports sized values (for now),
629 // we can't use `deref_const` + supporting `str`, we have to specially
630 // handle `&str` and include both `&` ("R") and `str` ("e") prefixes.
631 ty::Ref(_, ty, hir::Mutability::Not) if *ty == self.tcx.types.str_ => {
634 ty::ConstKind::Value(ConstValue::Slice { data, start, end }) => {
635 // NOTE(eddyb) the following comment was kept from `ty::print::pretty`:
636 // The `inspect` here is okay since we checked the bounds, and there are no
637 // relocations (we have an active `str` reference here). We don't use this
638 // result to affect interpreter execution.
641 .inspect_with_uninit_and_ptr_outside_interpreter(start..end);
642 let s = std::str::from_utf8(slice).expect("non utf8 str from miri");
645 // FIXME(eddyb) use a specialized hex-encoding loop.
646 for byte in s.bytes() {
647 let _ = write!(self.out, "{:02x}", byte);
653 bug!("symbol_names: unsupported `&str` constant: {:?}", ct);
658 ty::Ref(_, _, mutbl) => {
659 self.push(match mutbl {
660 hir::Mutability::Not => "R",
661 hir::Mutability::Mut => "Q",
663 self = self.tcx.deref_const(ty::ParamEnv::reveal_all().and(ct)).print(self)?;
666 ty::Array(..) | ty::Tuple(..) | ty::Adt(..) => {
667 let contents = self.tcx.destructure_const(ty::ParamEnv::reveal_all().and(ct));
668 let fields = contents.fields.iter().copied();
670 let print_field_list = |mut this: Self| {
671 for field in fields.clone() {
672 this = field.print(this)?;
678 match *ct.ty().kind() {
681 self = print_field_list(self)?;
685 self = print_field_list(self)?;
687 ty::Adt(def, substs) => {
689 contents.variant.expect("destructed const of adt without variant idx");
690 let variant_def = &def.variant(variant_idx);
693 self = self.print_def_path(variant_def.def_id, substs)?;
695 match variant_def.ctor_kind {
701 self = print_field_list(self)?;
703 CtorKind::Fictive => {
705 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
706 // HACK(eddyb) this mimics `path_append`,
707 // instead of simply using `field_def.ident`,
708 // just to be able to handle disambiguators.
709 let disambiguated_field =
710 self.tcx.def_key(field_def.did).disambiguated_data;
711 let field_name = disambiguated_field.data.get_opt_name();
712 self.push_disambiguator(
713 disambiguated_field.disambiguator as u64,
715 self.push_ident(field_name.unwrap_or(kw::Empty).as_str());
717 self = field.print(self)?;
728 bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct.ty(), ct);
732 // Only cache consts that do not refer to an enclosing
733 // binder (which would change depending on context).
734 if !ct.has_escaping_bound_vars() {
735 self.consts.insert(ct, start);
740 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
742 let stable_crate_id = self.tcx.def_path_hash(cnum.as_def_id()).stable_crate_id();
743 self.push_disambiguator(stable_crate_id.to_u64());
744 let name = self.tcx.crate_name(cnum);
745 self.push_ident(name.as_str());
752 trait_ref: Option<ty::TraitRef<'tcx>>,
753 ) -> Result<Self::Path, Self::Error> {
754 assert!(trait_ref.is_some());
755 let trait_ref = trait_ref.unwrap();
758 self = self_ty.print(self)?;
759 self.print_def_path(trait_ref.def_id, trait_ref.substs)
764 _: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
765 _: &DisambiguatedDefPathData,
767 _: Option<ty::TraitRef<'tcx>>,
768 ) -> Result<Self::Path, Self::Error> {
769 // Inlined into `print_impl_path`
775 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
776 disambiguated_data: &DisambiguatedDefPathData,
777 ) -> Result<Self::Path, Self::Error> {
778 let ns = match disambiguated_data.data {
779 // Extern block segments can be skipped, names from extern blocks
780 // are effectively living in their parent modules.
781 DefPathData::ForeignMod => return print_prefix(self),
783 // Uppercase categories are more stable than lowercase ones.
784 DefPathData::TypeNs(_) => 't',
785 DefPathData::ValueNs(_) => 'v',
786 DefPathData::ClosureExpr => 'C',
787 DefPathData::Ctor => 'c',
788 DefPathData::AnonConst => 'k',
789 DefPathData::ImplTrait => 'i',
791 // These should never show up as `path_append` arguments.
792 DefPathData::CrateRoot
794 | DefPathData::GlobalAsm
796 | DefPathData::MacroNs(_)
797 | DefPathData::LifetimeNs(_) => {
798 bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
802 let name = disambiguated_data.data.get_opt_name();
807 disambiguated_data.disambiguator as u64,
808 name.unwrap_or(kw::Empty).as_str(),
812 fn path_generic_args(
814 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
815 args: &[GenericArg<'tcx>],
816 ) -> Result<Self::Path, Self::Error> {
817 // Don't print any regions if they're all erased.
818 let print_regions = args.iter().any(|arg| match arg.unpack() {
819 GenericArgKind::Lifetime(r) => !r.is_erased(),
822 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
823 GenericArgKind::Lifetime(_) => print_regions,
827 if args.clone().next().is_none() {
828 return print_prefix(self);
832 self = print_prefix(self)?;
835 GenericArgKind::Lifetime(lt) => {
836 self = lt.print(self)?;
838 GenericArgKind::Type(ty) => {
839 self = ty.print(self)?;
841 GenericArgKind::Const(c) => {
843 self = c.print(self)?;