1use std::fmt::Write;
2use std::hash::Hasher;
3use std::iter;
4use std::ops::Range;
5
6use rustc_abi::{ExternAbi, Integer};
7use rustc_data_structures::base_n::ToBaseN;
8use rustc_data_structures::fx::FxHashMap;
9use rustc_data_structures::intern::Interned;
10use rustc_data_structures::stable_hash::StableHasher;
11use rustc_hashes::Hash64;
12use rustc_hir as hir;
13use rustc_hir::def::CtorKind;
14use rustc_hir::def_id::{CrateNum, DefId};
15use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
16use rustc_middle::bug;
17use rustc_middle::ty::layout::IntegerExt;
18use rustc_middle::ty::print::{Print, PrintError, Printer};
19use rustc_middle::ty::{
20 self, FloatTy, GenericArg, GenericArgKind, Instance, IntTy, ReifyReason, Ty, TyCtxt,
21 TypeVisitable, TypeVisitableExt, UintTy, Unnormalized,
22};
23use rustc_span::sym;
24
25pub(super) fn mangle<'tcx>(
26 tcx: TyCtxt<'tcx>,
27 instance: Instance<'tcx>,
28 instantiating_crate: Option<CrateNum>,
29 is_exportable: bool,
30) -> String {
31 let def_id = instance.def_id();
32 let args = tcx.normalize_erasing_regions(
34 ty::TypingEnv::fully_monomorphized(),
35 Unnormalized::new_wip(instance.args),
36 );
37
38 let prefix = "_R";
39 let mut p: V0SymbolMangler<'_> = V0SymbolMangler {
40 tcx,
41 start_offset: prefix.len(),
42 is_exportable,
43 paths: FxHashMap::default(),
44 types: FxHashMap::default(),
45 consts: FxHashMap::default(),
46 binders: ::alloc::vec::Vec::new()vec![],
47 out: String::from(prefix),
48 };
49
50 let shim_kind = match instance.def {
52 ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(_)) => Some("tls"),
53 ty::InstanceKind::Shim(ty::ShimKind::VTable(_)) => Some("vtable"),
54 ty::InstanceKind::Shim(ty::ShimKind::Reify(_, None)) => Some("reify"),
55 ty::InstanceKind::Shim(ty::ShimKind::Reify(_, Some(ReifyReason::FnPtr))) => {
56 Some("reify_fnptr")
57 }
58 ty::InstanceKind::Shim(ty::ShimKind::Reify(_, Some(ReifyReason::Vtable))) => {
59 Some("reify_vtable")
60 }
61
62 ty::InstanceKind::Shim(ty::ShimKind::ConstructCoroutineInClosure {
65 receiver_by_ref: true,
66 ..
67 }) => Some("by_move"),
68 ty::InstanceKind::Shim(ty::ShimKind::ConstructCoroutineInClosure {
69 receiver_by_ref: false,
70 ..
71 }) => Some("by_ref"),
72 ty::InstanceKind::Shim(ty::ShimKind::FutureDropPoll(_, _, _)) => Some("drop"),
73 _ => None,
74 };
75
76 if let ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlue(_, ty)) = instance.def {
77 let ty::Coroutine(_, cor_args) = ty.kind() else {
78 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
79 };
80 let drop_ty = cor_args.first().unwrap().expect_ty();
81 p.print_def_path(def_id, tcx.mk_args(&[GenericArg::from(drop_ty)])).unwrap()
82 } else if let Some(shim_kind) = shim_kind {
83 p.path_append_ns(|p| p.print_def_path(def_id, args), 'S', 0, shim_kind).unwrap()
84 } else {
85 p.print_def_path(def_id, args).unwrap()
86 };
87 if let Some(instantiating_crate) = instantiating_crate {
88 p.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap();
89 }
90 std::mem::take(&mut p.out)
91}
92
93pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> String {
94 match item_name {
95 "rust_eh_personality" => return item_name.to_owned(),
97 "__isPlatformVersionAtLeast" | "__isOSVersionAtLeast" => return item_name.to_owned(),
100 _ => {}
101 }
102
103 let prefix = "_R";
104 let mut p: V0SymbolMangler<'_> = V0SymbolMangler {
105 tcx,
106 start_offset: prefix.len(),
107 is_exportable: false,
108 paths: FxHashMap::default(),
109 types: FxHashMap::default(),
110 consts: FxHashMap::default(),
111 binders: ::alloc::vec::Vec::new()vec![],
112 out: String::from(prefix),
113 };
114
115 p.path_append_ns(
116 |p| {
117 p.push("C");
118 p.push_disambiguator({
119 let mut hasher = StableHasher::new();
120 hasher.write(tcx.sess.cfg_version.as_bytes());
126
127 let hash: Hash64 = hasher.finish();
128 hash.as_u64()
129 });
130 p.push_ident("__rustc");
131 Ok(())
132 },
133 'v',
134 0,
135 item_name,
136 )
137 .unwrap();
138
139 std::mem::take(&mut p.out)
140}
141
142pub(super) fn mangle_typeid_for_trait_ref<'tcx>(
143 tcx: TyCtxt<'tcx>,
144 trait_ref: ty::ExistentialTraitRef<'tcx>,
145) -> String {
146 let mut p = V0SymbolMangler {
148 tcx,
149 start_offset: 0,
150 is_exportable: false,
151 paths: FxHashMap::default(),
152 types: FxHashMap::default(),
153 consts: FxHashMap::default(),
154 binders: ::alloc::vec::Vec::new()vec![],
155 out: String::new(),
156 };
157 p.print_def_path(trait_ref.def_id, &[]).unwrap();
158 std::mem::take(&mut p.out)
159}
160
161struct BinderLevel {
162 lifetime_depths: Range<u32>,
173}
174
175struct V0SymbolMangler<'tcx> {
176 tcx: TyCtxt<'tcx>,
177 binders: Vec<BinderLevel>,
178 out: String,
179 is_exportable: bool,
180
181 start_offset: usize,
183 paths: FxHashMap<(DefId, &'tcx [GenericArg<'tcx>]), usize>,
185 types: FxHashMap<Ty<'tcx>, usize>,
186 consts: FxHashMap<ty::Const<'tcx>, usize>,
187}
188
189impl<'tcx> V0SymbolMangler<'tcx> {
190 fn push(&mut self, s: &str) {
191 self.out.push_str(s);
192 }
193
194 fn push_integer_62(&mut self, x: u64) {
200 push_integer_62(x, &mut self.out)
201 }
202
203 fn push_opt_integer_62(&mut self, tag: &str, x: u64) {
208 if let Some(x) = x.checked_sub(1) {
209 self.push(tag);
210 self.push_integer_62(x);
211 }
212 }
213
214 fn push_disambiguator(&mut self, dis: u64) {
215 self.push_opt_integer_62("s", dis);
216 }
217
218 fn push_ident(&mut self, ident: &str) {
219 push_ident(ident, &mut self.out)
220 }
221
222 fn path_append_ns(
223 &mut self,
224 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
225 ns: char,
226 disambiguator: u64,
227 name: &str,
228 ) -> Result<(), PrintError> {
229 self.push("N");
230 self.out.push(ns);
231 print_prefix(self)?;
232 self.push_disambiguator(disambiguator);
233 self.push_ident(name);
234 Ok(())
235 }
236
237 fn print_backref(&mut self, i: usize) -> Result<(), PrintError> {
238 self.push("B");
239 self.push_integer_62((i - self.start_offset) as u64);
240 Ok(())
241 }
242
243 fn wrap_binder<T>(
244 &mut self,
245 value: &ty::Binder<'tcx, T>,
246 print_value: impl FnOnce(&mut Self, &T) -> Result<(), PrintError>,
247 ) -> Result<(), PrintError>
248 where
249 T: TypeVisitable<TyCtxt<'tcx>>,
250 {
251 let mut lifetime_depths =
252 self.binders.last().map(|b| b.lifetime_depths.end).map_or(0..0, |i| i..i);
253
254 let lifetimes = value
256 .bound_vars()
257 .iter()
258 .filter(|var| #[allow(non_exhaustive_omitted_patterns)] match var {
ty::BoundVariableKind::Region(..) => true,
_ => false,
}matches!(var, ty::BoundVariableKind::Region(..)))
259 .count() as u32;
260
261 self.push_opt_integer_62("G", lifetimes as u64);
262 lifetime_depths.end += lifetimes;
263
264 self.binders.push(BinderLevel { lifetime_depths });
265 print_value(self, value.as_ref().skip_binder())?;
266 self.binders.pop();
267
268 Ok(())
269 }
270
271 fn print_pat(&mut self, pat: ty::Pattern<'tcx>) -> Result<(), std::fmt::Error> {
272 Ok(match *pat {
273 ty::PatternKind::Range { start, end } => {
274 self.push("R");
275 self.print_const(start)?;
276 self.print_const(end)?;
277 }
278 ty::PatternKind::NotNull => {
279 self.tcx.types.unit.print(self)?;
280 }
281 ty::PatternKind::Or(patterns) => {
282 self.push("O");
283 for pat in patterns {
284 self.print_pat(pat)?;
285 }
286 self.push("E");
287 }
288 })
289 }
290}
291
292impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> {
293 fn tcx(&self) -> TyCtxt<'tcx> {
294 self.tcx
295 }
296
297 fn print_def_path(
298 &mut self,
299 def_id: DefId,
300 args: &'tcx [GenericArg<'tcx>],
301 ) -> Result<(), PrintError> {
302 if let Some(&i) = self.paths.get(&(def_id, args)) {
303 return self.print_backref(i);
304 }
305 let start = self.out.len();
306
307 self.default_print_def_path(def_id, args)?;
308
309 if !args.iter().any(|k| k.has_escaping_bound_vars()) {
312 self.paths.insert((def_id, args), start);
313 }
314 Ok(())
315 }
316
317 fn print_impl_path(
318 &mut self,
319 impl_def_id: DefId,
320 args: &'tcx [GenericArg<'tcx>],
321 ) -> Result<(), PrintError> {
322 let key = self.tcx.def_key(impl_def_id);
323 let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
324
325 let self_ty = self.tcx.type_of(impl_def_id);
326 let impl_trait_ref = self.tcx.impl_opt_trait_ref(impl_def_id);
327 let generics = self.tcx.generics_of(impl_def_id);
328 let (typing_env, mut self_ty, mut impl_trait_ref) = if generics.count() > args.len()
342 || &args[..generics.count()]
343 == self
344 .tcx
345 .erase_and_anonymize_regions(ty::GenericArgs::identity_for_item(
346 self.tcx,
347 impl_def_id,
348 ))
349 .as_slice()
350 {
351 (
352 ty::TypingEnv::post_analysis(self.tcx, impl_def_id),
353 self_ty.instantiate_identity().skip_norm_wip(),
354 impl_trait_ref
355 .map(|impl_trait_ref| impl_trait_ref.instantiate_identity().skip_norm_wip()),
356 )
357 } else {
358 if !(!args.has_non_region_param() && !args.has_free_regions()) {
{
::core::panicking::panic_fmt(format_args!("should not be mangling partially substituted polymorphic instance: {0:?} {1:?}",
impl_def_id, args));
}
};assert!(
359 !args.has_non_region_param() && !args.has_free_regions(),
360 "should not be mangling partially substituted \
361 polymorphic instance: {impl_def_id:?} {args:?}"
362 );
363 (
364 ty::TypingEnv::fully_monomorphized(),
365 self_ty.instantiate(self.tcx, args).skip_norm_wip(),
366 impl_trait_ref.map(|impl_trait_ref| {
367 impl_trait_ref.instantiate(self.tcx, args).skip_norm_wip()
368 }),
369 )
370 };
371
372 match &mut impl_trait_ref {
373 Some(impl_trait_ref) => {
374 {
match (&impl_trait_ref.self_ty(), &self_ty) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(impl_trait_ref.self_ty(), self_ty);
375 *impl_trait_ref = self
376 .tcx
377 .normalize_erasing_regions(typing_env, Unnormalized::new_wip(*impl_trait_ref));
378 self_ty = impl_trait_ref.self_ty();
379 }
380 None => {
381 self_ty =
382 self.tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(self_ty));
383 }
384 }
385
386 self.push(match impl_trait_ref {
387 Some(_) => "X",
388 None => "M",
389 });
390
391 if impl_trait_ref.is_some() && args.iter().any(|a| a.has_non_region_param()) {
394 self.print_path_with_generic_args(
395 |this| {
396 this.path_append_ns(
397 |p| p.print_def_path(parent_def_id, &[]),
398 'I',
399 key.disambiguated_data.disambiguator as u64,
400 "",
401 )
402 },
403 args,
404 )?;
405 } else {
406 let exported_impl_order = self.tcx.stable_order_of_exportable_impls(impl_def_id.krate);
407 let disambiguator = match self.is_exportable {
408 true => exported_impl_order[&impl_def_id] as u64,
409 false => {
410 exported_impl_order.len() as u64 + key.disambiguated_data.disambiguator as u64
411 }
412 };
413 self.push_disambiguator(disambiguator);
414 self.print_def_path(parent_def_id, &[])?;
415 }
416
417 self_ty.print(self)?;
418
419 if let Some(trait_ref) = impl_trait_ref {
420 self.print_def_path(trait_ref.def_id, trait_ref.args)?;
421 }
422
423 Ok(())
424 }
425
426 fn print_region(&mut self, region: ty::Region<'_>) -> Result<(), PrintError> {
427 let i = match region.kind() {
428 ty::ReErased => 0,
431
432 ty::ReBound(
435 ty::BoundVarIndexKind::Bound(debruijn),
436 ty::BoundRegion { var, kind: ty::BoundRegionKind::Anon },
437 ) => {
438 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
439 let depth = binder.lifetime_depths.start + var.as_u32();
440
441 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
442 }
443
444 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("symbol_names: non-erased region `{0:?}`",
region))bug!("symbol_names: non-erased region `{:?}`", region),
445 };
446 self.push("L");
447 self.push_integer_62(i as u64);
448 Ok(())
449 }
450
451 fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
452 let basic_type = match ty.kind() {
454 ty::Bool => "b",
455 ty::Char => "c",
456 ty::Str => "e",
457 ty::Int(IntTy::I8) => "a",
458 ty::Int(IntTy::I16) => "s",
459 ty::Int(IntTy::I32) => "l",
460 ty::Int(IntTy::I64) => "x",
461 ty::Int(IntTy::I128) => "n",
462 ty::Int(IntTy::Isize) => "i",
463 ty::Uint(UintTy::U8) => "h",
464 ty::Uint(UintTy::U16) => "t",
465 ty::Uint(UintTy::U32) => "m",
466 ty::Uint(UintTy::U64) => "y",
467 ty::Uint(UintTy::U128) => "o",
468 ty::Uint(UintTy::Usize) => "j",
469 ty::Float(FloatTy::F16) => "C3f16",
470 ty::Float(FloatTy::F32) => "f",
471 ty::Float(FloatTy::F64) => "d",
472 ty::Float(FloatTy::F128) => "C4f128",
473 ty::Never => "z",
474
475 ty::Tuple(_) if ty.is_unit() => "u",
476
477 ty::Param(_) => "p",
480
481 _ => "",
482 };
483 if !basic_type.is_empty() {
484 self.push(basic_type);
485 return Ok(());
486 }
487
488 if let Some(&i) = self.types.get(&ty) {
489 return self.print_backref(i);
490 }
491 let start = self.out.len();
492
493 match *ty.kind() {
494 ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
496 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
497 }
498 ty::Tuple(_) if ty.is_unit() => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
499 ty::Param(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
500
501 ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
502
503 ty::Ref(r, ty, mutbl) => {
504 self.push(match mutbl {
505 hir::Mutability::Not => "R",
506 hir::Mutability::Mut => "Q",
507 });
508 if !r.is_erased() {
509 r.print(self)?;
510 }
511 ty.print(self)?;
512 }
513
514 ty::RawPtr(ty, mutbl) => {
515 self.push(match mutbl {
516 hir::Mutability::Not => "P",
517 hir::Mutability::Mut => "O",
518 });
519 ty.print(self)?;
520 }
521
522 ty::Pat(ty, pat) => {
523 self.push("W");
524 ty.print(self)?;
525 self.print_pat(pat)?;
526 }
527
528 ty::Array(ty, len) => {
529 self.push("A");
530 ty.print(self)?;
531 self.print_const(len)?;
532 }
533 ty::Slice(ty) => {
534 self.push("S");
535 ty.print(self)?;
536 }
537
538 ty::Tuple(tys) => {
539 self.push("T");
540 for ty in tys.iter() {
541 ty.print(self)?;
542 }
543 self.push("E");
544 }
545
546 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), args)
548 | ty::Closure(def_id, args)
549 | ty::CoroutineClosure(def_id, args)
550 | ty::Coroutine(def_id, args) => {
551 self.print_def_path(def_id, args)?;
552 }
553
554 ty::FnDef(def_id, args) => {
555 self.print_def_path(def_id, args.no_bound_vars().unwrap())?
556 }
557
558 ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. }) => {
561 self.print_def_path(def_id, args)?;
562 }
563
564 ty::Foreign(def_id) => {
565 self.print_def_path(def_id, &[])?;
566 }
567
568 ty::FnPtr(sig_tys, hdr) => {
569 let sig = sig_tys.with(hdr);
570 self.push("F");
571 self.wrap_binder(&sig, |p, sig| {
572 if sig.safety().is_unsafe() {
573 p.push("U");
574 }
575 match sig.abi() {
576 ExternAbi::Rust => {}
577 ExternAbi::C { unwind: false } => p.push("KC"),
578 abi => {
579 p.push("K");
580 let name = abi.as_str();
581 if name.contains('-') {
582 p.push_ident(&name.replace('-', "_"));
583 } else {
584 p.push_ident(name);
585 }
586 }
587 }
588 for &ty in sig.inputs() {
589 ty.print(p)?;
590 }
591 if sig.c_variadic() {
592 p.push("v");
593 }
594 p.push("E");
595 sig.output().print(p)
596 })?;
597 }
598
599 ty::UnsafeBinder(..) => ::core::panicking::panic("not implemented")unimplemented!(),
601
602 ty::Dynamic(predicates, r) => {
603 self.push("D");
604 self.print_dyn_existential(predicates)?;
605 r.print(self)?;
606 }
607
608 ty::Alias(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("symbol_names: unexpected alias"))bug!("symbol_names: unexpected alias"),
609 ty::CoroutineWitness(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("symbol_names: unexpected `CoroutineWitness`"))bug!("symbol_names: unexpected `CoroutineWitness`"),
610 }
611
612 if !ty.has_escaping_bound_vars() {
615 self.types.insert(ty, start);
616 }
617 Ok(())
618 }
619
620 fn print_dyn_existential(
621 &mut self,
622 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
623 ) -> Result<(), PrintError> {
624 self.wrap_binder(&predicates[0], |p, _| {
651 for predicate in predicates.iter() {
652 match predicate.as_ref().skip_binder() {
657 ty::ExistentialPredicate::Trait(trait_ref) => {
658 let trait_ref =
662 trait_ref.with_self_ty(p.tcx, p.tcx.types.trait_object_dummy_self);
663 p.print_def_path(trait_ref.def_id, trait_ref.args)?;
664 }
665 ty::ExistentialPredicate::Projection(projection) => {
666 let name = p.tcx.associated_item(projection.def_id).name();
667 p.push("p");
668 p.push_ident(name.as_str());
669 match projection.term.kind() {
670 ty::TermKind::Ty(ty) => ty.print(p),
671 ty::TermKind::Const(c) => {
672 p.push("K");
673 c.print(p)
674 }
675 }?;
676 }
677 ty::ExistentialPredicate::AutoTrait(def_id) => {
678 p.print_def_path(*def_id, &[])?;
679 }
680 }
681 }
682 Ok(())
683 })?;
684
685 self.push("E");
686 Ok(())
687 }
688
689 fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
690 let cv = match ct.kind() {
692 ty::ConstKind::Value(cv) => cv,
693
694 ty::ConstKind::Param(_) => {
697 self.push("p");
699 return Ok(());
700 }
701
702 ty::ConstKind::Alias(_, ty::AliasConst { kind, args, .. }) => match kind {
705 ty::AliasConstKind::Projection { def_id }
706 | ty::AliasConstKind::Inherent { def_id }
707 | ty::AliasConstKind::Free { def_id }
708 | ty::AliasConstKind::Anon { def_id } => {
709 return self.print_def_path(def_id, args);
710 }
711 },
712
713 ty::ConstKind::Expr(_)
714 | ty::ConstKind::Infer(_)
715 | ty::ConstKind::Bound(..)
716 | ty::ConstKind::Placeholder(_)
717 | ty::ConstKind::Error(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
718 };
719
720 if let Some(&i) = self.consts.get(&ct) {
721 self.print_backref(i)?;
722 return Ok(());
723 }
724
725 let ty::Value { ty: ct_ty, valtree } = cv;
726 let start = self.out.len();
727
728 match ct_ty.kind() {
729 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Char => {
730 ct_ty.print(self)?;
731
732 let mut bits = cv
733 .try_to_bits(self.tcx, ty::TypingEnv::fully_monomorphized())
734 .expect("expected const to be monomorphic");
735
736 if let ty::Int(ity) = ct_ty.kind() {
738 let val =
739 Integer::from_int_ty(&self.tcx, *ity).size().sign_extend(bits) as i128;
740 if val < 0 {
741 self.push("n");
742 }
743 bits = val.unsigned_abs();
744 }
745
746 let _ = self.out.write_fmt(format_args!("{0:x}_", bits))write!(self.out, "{bits:x}_");
747 }
748
749 ty::Str => {
751 let tcx = self.tcx();
752 let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, ct_ty);
755 let cv = ty::Value { ty: ref_ty, valtree };
756 let slice = cv.try_to_raw_bytes(tcx).unwrap_or_else(|| {
757 ::rustc_middle::util::bug::bug_fmt(format_args!("expected to get raw bytes from valtree {0:?} for type {1}",
valtree, ct_ty))bug!("expected to get raw bytes from valtree {:?} for type {:}", valtree, ct_ty)
758 });
759 let s = std::str::from_utf8(slice).expect("non utf8 str from MIR interpreter");
760
761 self.push("e");
763
764 for byte in s.bytes() {
766 let _ = self.out.write_fmt(format_args!("{0:02x}", byte))write!(self.out, "{byte:02x}");
767 }
768
769 self.push("_");
770 }
771
772 ty::Ref(_, _, mutbl) => {
775 self.push(match mutbl {
776 hir::Mutability::Not => "R",
777 hir::Mutability::Mut => "Q",
778 });
779
780 let pointee_ty =
781 ct_ty.builtin_deref(true).expect("tried to dereference on non-ptr type");
782 let dereferenced_const = ty::Const::new_value(self.tcx, valtree, pointee_ty);
783 dereferenced_const.print(self)?;
784 }
785
786 ty::Array(..) | ty::Tuple(..) | ty::Slice(_) => {
787 let fields = cv.to_branch().iter().copied();
788
789 let print_field_list = |this: &mut Self| {
790 for field in fields.clone() {
791 field.print(this)?;
792 }
793 this.push("E");
794 Ok(())
795 };
796
797 match *ct_ty.kind() {
798 ty::Array(..) | ty::Slice(_) => {
799 self.push("A");
800 print_field_list(self)?;
801 }
802 ty::Tuple(..) => {
803 self.push("T");
804 print_field_list(self)?;
805 }
806 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
807 }
808 }
809 ty::Adt(def, args) => {
810 let contents = cv.destructure_adt_const();
811 let fields = contents.fields.iter().copied();
812
813 let print_field_list = |this: &mut Self| {
814 for field in fields.clone() {
815 field.print(this)?;
816 }
817 this.push("E");
818 Ok(())
819 };
820
821 let variant_idx = contents.variant;
822 let variant_def = &def.variant(variant_idx);
823
824 self.push("V");
825 self.print_def_path(variant_def.def_id, args)?;
826
827 match variant_def.ctor_kind() {
828 Some(CtorKind::Const) => {
829 self.push("U");
830 }
831 Some(CtorKind::Fn) => {
832 self.push("T");
833 print_field_list(self)?;
834 }
835 None => {
836 self.push("S");
837 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
838 let disambiguated_field =
842 self.tcx.def_key(field_def.did).disambiguated_data;
843 let field_name = disambiguated_field.data.get_opt_name();
844 self.push_disambiguator(disambiguated_field.disambiguator as u64);
845 self.push_ident(field_name.unwrap().as_str());
846
847 field.print(self)?;
848 }
849 self.push("E");
850 }
851 }
852 }
853 _ => {
854 ::rustc_middle::util::bug::bug_fmt(format_args!("symbol_names: unsupported constant of type `{0}` ({1:?})",
ct_ty, ct));bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct_ty, ct);
855 }
856 }
857
858 if !ct.has_escaping_bound_vars() {
861 self.consts.insert(ct, start);
862 }
863 Ok(())
864 }
865
866 fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
867 self.push("C");
868 if !self.is_exportable {
869 let stable_crate_id = self.tcx.stable_crate_id(cnum);
870 self.push_disambiguator(stable_crate_id.as_u64());
871 }
872 let name = self.tcx.crate_name(cnum);
873 self.push_ident(name.as_str());
874 Ok(())
875 }
876
877 fn print_path_with_qualified(
878 &mut self,
879 self_ty: Ty<'tcx>,
880 trait_ref: Option<ty::TraitRef<'tcx>>,
881 ) -> Result<(), PrintError> {
882 if !trait_ref.is_some() {
::core::panicking::panic("assertion failed: trait_ref.is_some()")
};assert!(trait_ref.is_some());
883 let trait_ref = trait_ref.unwrap();
884
885 self.push("Y");
886 self_ty.print(self)?;
887 self.print_def_path(trait_ref.def_id, trait_ref.args)
888 }
889
890 fn print_path_with_impl(
891 &mut self,
892 _: impl FnOnce(&mut Self) -> Result<(), PrintError>,
893 _: Ty<'tcx>,
894 _: Option<ty::TraitRef<'tcx>>,
895 ) -> Result<(), PrintError> {
896 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
898 }
899
900 fn print_path_with_simple(
901 &mut self,
902 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
903 disambiguated_data: &DisambiguatedDefPathData,
904 ) -> Result<(), PrintError> {
905 let ns = match disambiguated_data.data {
906 DefPathData::ForeignMod => return print_prefix(self),
909
910 DefPathData::TypeNs(_) => 't',
912 DefPathData::ValueNs(_) => 'v',
913 DefPathData::Closure => 'C',
914 DefPathData::Ctor => 'c',
915 DefPathData::AnonConst => 'K',
916 DefPathData::OpaqueTy => 'i',
917 DefPathData::SyntheticCoroutineBody => 's',
918 DefPathData::NestedStatic => 'n',
919 DefPathData::GlobalAsm => 'a',
920
921 DefPathData::CrateRoot
923 | DefPathData::Use
924 | DefPathData::Impl
925 | DefPathData::MacroNs(_)
926 | DefPathData::LifetimeNs(_)
927 | DefPathData::OpaqueLifetime(_)
928 | DefPathData::AnonAssocTy(..) => {
929 ::rustc_middle::util::bug::bug_fmt(format_args!("symbol_names: unexpected DefPathData: {0:?}",
disambiguated_data.data))bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
930 }
931 };
932
933 let name = disambiguated_data.data.get_opt_name();
934
935 self.path_append_ns(
936 print_prefix,
937 ns,
938 disambiguated_data.disambiguator as u64,
939 name.unwrap_or(sym::empty).as_str(),
940 )
941 }
942
943 fn print_path_with_generic_args(
944 &mut self,
945 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
946 args: &[GenericArg<'tcx>],
947 ) -> Result<(), PrintError> {
948 let print_regions = args.iter().any(|arg| match arg.kind() {
950 GenericArgKind::Lifetime(r) => !r.is_erased(),
951 _ => false,
952 });
953 let args = args.iter().cloned().filter(|arg| match arg.kind() {
954 GenericArgKind::Lifetime(_) => print_regions,
955 _ => true,
956 });
957
958 if args.clone().next().is_none() {
959 return print_prefix(self);
960 }
961
962 self.push("I");
963 print_prefix(self)?;
964 for arg in args {
965 match arg.kind() {
966 GenericArgKind::Lifetime(lt) => {
967 lt.print(self)?;
968 }
969 GenericArgKind::Type(ty) => {
970 ty.print(self)?;
971 }
972 GenericArgKind::Const(c) => {
973 self.push("K");
974 c.print(self)?;
975 }
976 }
977 }
978 self.push("E");
979
980 Ok(())
981 }
982}
983pub(crate) fn push_integer_62(x: u64, output: &mut String) {
989 if let Some(x) = x.checked_sub(1) {
990 output.push_str(&x.to_base(62));
991 }
992 output.push('_');
993}
994
995pub(crate) fn encode_integer_62(x: u64) -> String {
996 let mut output = String::new();
997 push_integer_62(x, &mut output);
998 output
999}
1000
1001pub(crate) fn push_ident(ident: &str, output: &mut String) {
1002 let mut use_punycode = false;
1003 for b in ident.bytes() {
1004 match b {
1005 b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
1006 0x80..=0xff => use_punycode = true,
1007 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("symbol_names: bad byte {0} in ident {1:?}",
b, ident))bug!("symbol_names: bad byte {} in ident {:?}", b, ident),
1008 }
1009 }
1010
1011 let punycode_string;
1012 let ident = if use_punycode {
1013 output.push('u');
1014
1015 let mut punycode_bytes = match punycode::encode(ident) {
1017 Ok(s) => s.into_bytes(),
1018 Err(()) => ::rustc_middle::util::bug::bug_fmt(format_args!("symbol_names: punycode encoding failed for ident {0:?}",
ident))bug!("symbol_names: punycode encoding failed for ident {:?}", ident),
1019 };
1020
1021 if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
1023 *c = b'_';
1024 }
1025
1026 punycode_string = String::from_utf8(punycode_bytes).unwrap();
1028 &punycode_string
1029 } else {
1030 ident
1031 };
1032
1033 let _ = output.write_fmt(format_args!("{0}", ident.len()))write!(output, "{}", ident.len());
1034
1035 if let Some('_' | '0'..='9') = ident.chars().next() {
1037 output.push('_');
1038 }
1039
1040 output.push_str(ident);
1041}