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::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::{bug, 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_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller());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_cgu<'tcx>(tcx: TyCtxt<'tcx>, krate: CrateNum, cgu_name: Either<u64, &str>) -> String {
94 let prefix = "_R";
95 let mut p: V0SymbolMangler<'_> = V0SymbolMangler {
96 tcx,
97 start_offset: prefix.len(),
98 is_exportable: false,
99 paths: FxHashMap::default(),
100 types: FxHashMap::default(),
101 consts: FxHashMap::default(),
102 binders: ::alloc::vec::Vec::new()vec![],
103 out: String::from(prefix),
104 };
105
106 match cgu_name {
107 Either::Left(cgu_index) => {
108 p.path_append_ns(|p| p.print_def_path(krate.as_def_id(), &[]), 'S', cgu_index, "cgu")
110 .unwrap();
111 }
112 Either::Right(name) => {
113 p.out.push('I');
115 p.path_append_ns(|p| p.print_def_path(krate.as_def_id(), &[]), 'S', 0, "cgu").unwrap();
116 p.push("KRe");
117
118 for byte in name.as_bytes() {
119 let _ = p.out.write_fmt(format_args!("{0:02x}", byte))write!(p.out, "{byte:02x}");
120 }
121
122 p.push("_E");
123 }
124 }
125
126 std::mem::take(&mut p.out)
127}
128
129pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> String {
130 match item_name {
131 "rust_eh_personality" => return item_name.to_owned(),
133 "__isPlatformVersionAtLeast" | "__isOSVersionAtLeast" => return item_name.to_owned(),
136 _ => {}
137 }
138
139 let prefix = "_R";
140 let mut p: V0SymbolMangler<'_> = V0SymbolMangler {
141 tcx,
142 start_offset: prefix.len(),
143 is_exportable: false,
144 paths: FxHashMap::default(),
145 types: FxHashMap::default(),
146 consts: FxHashMap::default(),
147 binders: ::alloc::vec::Vec::new()vec![],
148 out: String::from(prefix),
149 };
150
151 p.path_append_ns(
152 |p| {
153 p.push("C");
154 p.push_disambiguator({
155 let mut hasher = StableHasher::new();
156 hasher.write(tcx.sess.cfg_version.as_bytes());
162
163 let hash: Hash64 = hasher.finish();
164 hash.as_u64()
165 });
166 p.push_ident("__rustc");
167 Ok(())
168 },
169 'v',
170 0,
171 item_name,
172 )
173 .unwrap();
174
175 std::mem::take(&mut p.out)
176}
177
178pub(super) fn mangle_typeid_for_trait_ref<'tcx>(
179 tcx: TyCtxt<'tcx>,
180 trait_ref: ty::ExistentialTraitRef<'tcx>,
181) -> String {
182 let mut p = V0SymbolMangler {
184 tcx,
185 start_offset: 0,
186 is_exportable: false,
187 paths: FxHashMap::default(),
188 types: FxHashMap::default(),
189 consts: FxHashMap::default(),
190 binders: ::alloc::vec::Vec::new()vec![],
191 out: String::new(),
192 };
193 p.print_def_path(trait_ref.def_id, &[]).unwrap();
194 std::mem::take(&mut p.out)
195}
196
197struct BinderLevel {
198 lifetime_depths: Range<u32>,
209}
210
211struct V0SymbolMangler<'tcx> {
212 tcx: TyCtxt<'tcx>,
213 binders: Vec<BinderLevel>,
214 out: String,
215 is_exportable: bool,
216
217 start_offset: usize,
219 paths: FxHashMap<(DefId, &'tcx [GenericArg<'tcx>]), usize>,
221 types: FxHashMap<Ty<'tcx>, usize>,
222 consts: FxHashMap<ty::Const<'tcx>, usize>,
223}
224
225impl<'tcx> V0SymbolMangler<'tcx> {
226 fn push(&mut self, s: &str) {
227 self.out.push_str(s);
228 }
229
230 fn push_integer_62(&mut self, x: u64) {
236 push_integer_62(x, &mut self.out)
237 }
238
239 fn push_opt_integer_62(&mut self, tag: &str, x: u64) {
244 if let Some(x) = x.checked_sub(1) {
245 self.push(tag);
246 self.push_integer_62(x);
247 }
248 }
249
250 fn push_disambiguator(&mut self, dis: u64) {
251 self.push_opt_integer_62("s", dis);
252 }
253
254 fn push_ident(&mut self, ident: &str) {
255 push_ident(ident, &mut self.out)
256 }
257
258 fn path_append_ns(
259 &mut self,
260 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
261 ns: char,
262 disambiguator: u64,
263 name: &str,
264 ) -> Result<(), PrintError> {
265 self.push("N");
266 self.out.push(ns);
267 print_prefix(self)?;
268 self.push_disambiguator(disambiguator);
269 self.push_ident(name);
270 Ok(())
271 }
272
273 fn print_backref(&mut self, i: usize) -> Result<(), PrintError> {
274 self.push("B");
275 self.push_integer_62((i - self.start_offset) as u64);
276 Ok(())
277 }
278
279 fn wrap_binder<T>(
280 &mut self,
281 value: &ty::Binder<'tcx, T>,
282 print_value: impl FnOnce(&mut Self, &T) -> Result<(), PrintError>,
283 ) -> Result<(), PrintError>
284 where
285 T: TypeVisitable<TyCtxt<'tcx>>,
286 {
287 let mut lifetime_depths =
288 self.binders.last().map(|b| b.lifetime_depths.end).map_or(0..0, |i| i..i);
289
290 let lifetimes = value
292 .bound_vars()
293 .iter()
294 .filter(|var| #[allow(non_exhaustive_omitted_patterns)] match var {
ty::BoundVariableKind::Region(..) => true,
_ => false,
}matches!(var, ty::BoundVariableKind::Region(..)))
295 .count() as u32;
296
297 self.push_opt_integer_62("G", lifetimes as u64);
298 lifetime_depths.end += lifetimes;
299
300 self.binders.push(BinderLevel { lifetime_depths });
301 print_value(self, value.as_ref().skip_binder())?;
302 self.binders.pop();
303
304 Ok(())
305 }
306
307 fn print_pat(&mut self, pat: ty::Pattern<'tcx>) -> Result<(), std::fmt::Error> {
308 Ok(match *pat {
309 ty::PatternKind::Range { start, end } => {
310 self.push("R");
311 self.print_const(start)?;
312 self.print_const(end)?;
313 }
314 ty::PatternKind::NotNull => {
315 self.tcx.types.unit.print(self)?;
316 }
317 ty::PatternKind::Or(patterns) => {
318 self.push("O");
319 for pat in patterns {
320 self.print_pat(pat)?;
321 }
322 self.push("E");
323 }
324 })
325 }
326}
327
328impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> {
329 fn tcx(&self) -> TyCtxt<'tcx> {
330 self.tcx
331 }
332
333 fn print_def_path(
334 &mut self,
335 def_id: DefId,
336 args: &'tcx [GenericArg<'tcx>],
337 ) -> Result<(), PrintError> {
338 if let Some(&i) = self.paths.get(&(def_id, args)) {
339 return self.print_backref(i);
340 }
341 let start = self.out.len();
342
343 self.default_print_def_path(def_id, args)?;
344
345 if !args.iter().any(|k| k.has_escaping_bound_vars()) {
348 self.paths.insert((def_id, args), start);
349 }
350 Ok(())
351 }
352
353 fn print_impl_path(
354 &mut self,
355 impl_def_id: DefId,
356 args: &'tcx [GenericArg<'tcx>],
357 ) -> Result<(), PrintError> {
358 let key = self.tcx.def_key(impl_def_id);
359 let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
360
361 let self_ty = self.tcx.type_of(impl_def_id);
362 let impl_trait_ref = self.tcx.impl_opt_trait_ref(impl_def_id);
363 let generics = self.tcx.generics_of(impl_def_id);
364 let (typing_env, mut self_ty, mut impl_trait_ref) = if generics.count() > args.len()
378 || &args[..generics.count()]
379 == self
380 .tcx
381 .erase_and_anonymize_regions(ty::GenericArgs::identity_for_item(
382 self.tcx,
383 impl_def_id,
384 ))
385 .as_slice()
386 {
387 (
388 ty::TypingEnv::post_analysis(self.tcx, impl_def_id),
389 self_ty.instantiate_identity().skip_norm_wip(),
390 impl_trait_ref
391 .map(|impl_trait_ref| impl_trait_ref.instantiate_identity().skip_norm_wip()),
392 )
393 } else {
394 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!(
395 !args.has_non_region_param() && !args.has_free_regions(),
396 "should not be mangling partially substituted \
397 polymorphic instance: {impl_def_id:?} {args:?}"
398 );
399 (
400 ty::TypingEnv::fully_monomorphized(),
401 self_ty.instantiate(self.tcx, args).skip_norm_wip(),
402 impl_trait_ref.map(|impl_trait_ref| {
403 impl_trait_ref.instantiate(self.tcx, args).skip_norm_wip()
404 }),
405 )
406 };
407
408 match &mut impl_trait_ref {
409 Some(impl_trait_ref) => {
410 {
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);
411 *impl_trait_ref = self
412 .tcx
413 .normalize_erasing_regions(typing_env, Unnormalized::new_wip(*impl_trait_ref));
414 self_ty = impl_trait_ref.self_ty();
415 }
416 None => {
417 self_ty =
418 self.tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(self_ty));
419 }
420 }
421
422 self.push(match impl_trait_ref {
423 Some(_) => "X",
424 None => "M",
425 });
426
427 if impl_trait_ref.is_some() && args.iter().any(|a| a.has_non_region_param()) {
430 self.print_path_with_generic_args(
431 |this| {
432 this.path_append_ns(
433 |p| p.print_def_path(parent_def_id, &[]),
434 'I',
435 key.disambiguated_data.disambiguator as u64,
436 "",
437 )
438 },
439 args,
440 )?;
441 } else {
442 let exported_impl_order = self.tcx.stable_order_of_exportable_impls(impl_def_id.krate);
443 let disambiguator = match self.is_exportable {
444 true => exported_impl_order[&impl_def_id] as u64,
445 false => {
446 exported_impl_order.len() as u64 + key.disambiguated_data.disambiguator as u64
447 }
448 };
449 self.push_disambiguator(disambiguator);
450 self.print_def_path(parent_def_id, &[])?;
451 }
452
453 self_ty.print(self)?;
454
455 if let Some(trait_ref) = impl_trait_ref {
456 self.print_def_path(trait_ref.def_id, trait_ref.args)?;
457 }
458
459 Ok(())
460 }
461
462 fn print_region(&mut self, region: ty::Region<'_>) -> Result<(), PrintError> {
463 let i = match region.kind() {
464 ty::ReErased => 0,
467
468 ty::ReBound(
471 ty::BoundVarIndexKind::Bound(debruijn),
472 ty::BoundRegion { var, kind: ty::BoundRegionKind::Anon },
473 ) => {
474 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
475 let depth = binder.lifetime_depths.start + var.as_u32();
476
477 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
478 }
479
480 _ => ::rustc_span::macros::bug_impl(None,
format_args!("symbol_names: non-erased region `{0:?}`", region),
Location::caller())bug!("symbol_names: non-erased region `{:?}`", region),
481 };
482 self.push("L");
483 self.push_integer_62(i as u64);
484 Ok(())
485 }
486
487 fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
488 let basic_type = match ty.kind() {
490 ty::Bool => "b",
491 ty::Char => "c",
492 ty::Str => "e",
493 ty::Int(IntTy::I8) => "a",
494 ty::Int(IntTy::I16) => "s",
495 ty::Int(IntTy::I32) => "l",
496 ty::Int(IntTy::I64) => "x",
497 ty::Int(IntTy::I128) => "n",
498 ty::Int(IntTy::Isize) => "i",
499 ty::Uint(UintTy::U8) => "h",
500 ty::Uint(UintTy::U16) => "t",
501 ty::Uint(UintTy::U32) => "m",
502 ty::Uint(UintTy::U64) => "y",
503 ty::Uint(UintTy::U128) => "o",
504 ty::Uint(UintTy::Usize) => "j",
505 ty::Float(FloatTy::F16) => "C3f16",
506 ty::Float(FloatTy::F32) => "f",
507 ty::Float(FloatTy::F64) => "d",
508 ty::Float(FloatTy::F128) => "C4f128",
509 ty::Never => "z",
510
511 ty::Tuple(_) if ty.is_unit() => "u",
512
513 ty::Param(_) => "p",
516
517 _ => "",
518 };
519 if !basic_type.is_empty() {
520 self.push(basic_type);
521 return Ok(());
522 }
523
524 if let Some(&i) = self.types.get(&ty) {
525 return self.print_backref(i);
526 }
527 let start = self.out.len();
528
529 match *ty.kind() {
530 ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
532 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
533 }
534 ty::Tuple(_) if ty.is_unit() => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
535 ty::Param(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
536
537 ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!(),
538
539 ty::Ref(r, ty, mutbl) => {
540 self.push(match mutbl {
541 hir::Mutability::Not => "R",
542 hir::Mutability::Mut => "Q",
543 });
544 if !r.is_erased() {
545 r.print(self)?;
546 }
547 ty.print(self)?;
548 }
549
550 ty::RawPtr(ty, mutbl) => {
551 self.push(match mutbl {
552 hir::Mutability::Not => "P",
553 hir::Mutability::Mut => "O",
554 });
555 ty.print(self)?;
556 }
557
558 ty::Pat(ty, pat) => {
559 self.push("W");
560 ty.print(self)?;
561 self.print_pat(pat)?;
562 }
563
564 ty::Array(ty, len) => {
565 self.push("A");
566 ty.print(self)?;
567 self.print_const(len)?;
568 }
569 ty::Slice(ty) => {
570 self.push("S");
571 ty.print(self)?;
572 }
573
574 ty::Tuple(tys) => {
575 self.push("T");
576 for ty in tys.iter() {
577 ty.print(self)?;
578 }
579 self.push("E");
580 }
581
582 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), args)
584 | ty::Closure(def_id, args)
585 | ty::CoroutineClosure(def_id, args)
586 | ty::Coroutine(def_id, args) => {
587 self.print_def_path(def_id, args)?;
588 }
589
590 ty::FnDef(def_id, args) => {
591 self.print_def_path(def_id, args.no_bound_vars().unwrap())?
592 }
593
594 ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. }) => {
597 self.print_def_path(def_id, args)?;
598 }
599
600 ty::Foreign(def_id) => {
601 self.print_def_path(def_id, &[])?;
602 }
603
604 ty::FnPtr(sig_tys, hdr) => {
605 let splatted_arg_index = hdr.splatted().map(usize::from);
606 let sig = sig_tys.with(hdr);
607 self.push("F");
608 self.wrap_binder(&sig, |p, sig| {
609 if sig.safety().is_unsafe() {
610 p.push("U");
611 }
612 match sig.abi() {
613 ExternAbi::Rust => {}
614 ExternAbi::C { unwind: false } => p.push("KC"),
615 abi => {
616 p.push("K");
617 let name = abi.as_str();
618 if name.contains('-') {
619 p.push_ident(&name.replace('-', "_"));
620 } else {
621 p.push_ident(name);
622 }
623 }
624 }
625 for (i, &ty) in sig.inputs().iter().enumerate() {
626 if splatted_arg_index == Some(i) {
627 p.push("w");
633 }
634 ty.print(p)?;
635 }
636 if sig.c_variadic() {
637 p.push("v");
638 }
639 p.push("E");
640 sig.output().print(p)
641 })?;
642 }
643
644 ty::UnsafeBinder(..) => ::core::panicking::panic("not implemented")unimplemented!(),
646
647 ty::Dynamic(predicates, r) => {
648 self.push("D");
649 self.print_dyn_existential(predicates)?;
650 r.print(self)?;
651 }
652
653 ty::Alias(..) => ::rustc_span::macros::bug_impl(None,
format_args!("symbol_names: unexpected alias"), Location::caller())bug!("symbol_names: unexpected alias"),
654 ty::CoroutineWitness(..) => ::rustc_span::macros::bug_impl(None,
format_args!("symbol_names: unexpected `CoroutineWitness`"),
Location::caller())bug!("symbol_names: unexpected `CoroutineWitness`"),
655 }
656
657 if !ty.has_escaping_bound_vars() {
660 self.types.insert(ty, start);
661 }
662 Ok(())
663 }
664
665 fn print_dyn_existential(
666 &mut self,
667 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
668 ) -> Result<(), PrintError> {
669 self.wrap_binder(&predicates[0], |p, _| {
696 for predicate in predicates.iter() {
697 match predicate.as_ref().skip_binder() {
702 ty::ExistentialPredicate::Trait(trait_ref) => {
703 let trait_ref =
707 trait_ref.with_self_ty(p.tcx, p.tcx.types.trait_object_dummy_self);
708 p.print_def_path(trait_ref.def_id, trait_ref.args)?;
709 }
710 ty::ExistentialPredicate::Projection(projection) => {
711 let name = p.tcx.associated_item(projection.def_id).name();
712 p.push("p");
713 p.push_ident(name.as_str());
714 match projection.term.kind() {
715 ty::TermKind::Ty(ty) => ty.print(p),
716 ty::TermKind::Const(c) => {
717 p.push("K");
718 c.print(p)
719 }
720 }?;
721 }
722 ty::ExistentialPredicate::AutoTrait(def_id) => {
723 p.print_def_path(*def_id, &[])?;
724 }
725 }
726 }
727 Ok(())
728 })?;
729
730 self.push("E");
731 Ok(())
732 }
733
734 fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
735 let cv = match ct.kind() {
737 ty::ConstKind::Value(cv) => cv,
738
739 ty::ConstKind::Param(_) => {
742 self.push("p");
744 return Ok(());
745 }
746
747 ty::ConstKind::Alias(_, ty::AliasConst { kind, args, .. }) => match kind {
750 ty::AliasConstKind::Projection { def_id }
751 | ty::AliasConstKind::InherentSelf { def_id }
752 | ty::AliasConstKind::InherentImpl { 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_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())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_span::macros::bug_impl(None,
format_args!("expected to get raw bytes from valtree {0:?} for type {1}",
valtree, ct_ty), Location::caller())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_span::macros::bug_impl(None,
format_args!("symbol_names: unsupported constant of type `{0}` ({1:?})",
ct_ty, ct), Location::caller());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 | DefPathData::TestBinderConstraints => {
976 ::rustc_span::macros::bug_impl(None,
format_args!("symbol_names: unexpected DefPathData: {0:?}",
disambiguated_data.data), Location::caller())bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
977 }
978 };
979
980 let name = disambiguated_data.data.get_opt_name();
981
982 self.path_append_ns(
983 print_prefix,
984 ns,
985 disambiguated_data.disambiguator as u64,
986 name.unwrap_or(sym::empty).as_str(),
987 )
988 }
989
990 fn print_path_with_generic_args(
991 &mut self,
992 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
993 args: &[GenericArg<'tcx>],
994 ) -> Result<(), PrintError> {
995 let print_regions = args.iter().any(|arg| match arg.kind() {
997 GenericArgKind::Lifetime(r) => !r.is_erased(),
998 _ => false,
999 });
1000 let args = args.iter().cloned().filter(|arg| match arg.kind() {
1001 GenericArgKind::Lifetime(_) => print_regions,
1002 _ => true,
1003 });
1004
1005 if args.clone().next().is_none() {
1006 return print_prefix(self);
1007 }
1008
1009 self.push("I");
1010 print_prefix(self)?;
1011 for arg in args {
1012 match arg.kind() {
1013 GenericArgKind::Lifetime(lt) => {
1014 lt.print(self)?;
1015 }
1016 GenericArgKind::Type(ty) => {
1017 ty.print(self)?;
1018 }
1019 GenericArgKind::Const(c) => {
1020 self.push("K");
1021 c.print(self)?;
1022 }
1023 }
1024 }
1025 self.push("E");
1026
1027 Ok(())
1028 }
1029}
1030pub(crate) fn push_integer_62(x: u64, output: &mut String) {
1036 if let Some(x) = x.checked_sub(1) {
1037 output.push_str(&x.to_base(62));
1038 }
1039 output.push('_');
1040}
1041
1042pub(crate) fn encode_integer_62(x: u64) -> String {
1043 let mut output = String::new();
1044 push_integer_62(x, &mut output);
1045 output
1046}
1047
1048pub(crate) fn push_ident(ident: &str, output: &mut String) {
1049 let mut use_punycode = false;
1050 for b in ident.bytes() {
1051 match b {
1052 b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
1053 0x80..=0xff => use_punycode = true,
1054 _ => ::rustc_span::macros::bug_impl(None,
format_args!("symbol_names: bad byte {0} in ident {1:?}", b, ident),
Location::caller())bug!("symbol_names: bad byte {} in ident {:?}", b, ident),
1055 }
1056 }
1057
1058 let punycode_string;
1059 let ident = if use_punycode {
1060 output.push('u');
1061
1062 let mut punycode_bytes = match punycode::encode(ident) {
1064 Ok(s) => s.into_bytes(),
1065 Err(()) => ::rustc_span::macros::bug_impl(None,
format_args!("symbol_names: punycode encoding failed for ident {0:?}",
ident), Location::caller())bug!("symbol_names: punycode encoding failed for ident {:?}", ident),
1066 };
1067
1068 if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
1070 *c = b'_';
1071 }
1072
1073 punycode_string = String::from_utf8(punycode_bytes).unwrap();
1075 &punycode_string
1076 } else {
1077 ident
1078 };
1079
1080 let _ = output.write_fmt(format_args!("{0}", ident.len()))write!(output, "{}", ident.len());
1081
1082 if let Some('_' | '0'..='9') = ident.chars().next() {
1084 output.push('_');
1085 }
1086
1087 output.push_str(ident);
1088}