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