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_hasher::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,
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(ty::TypingEnv::fully_monomorphized(), instance.args);
34
35 let prefix = "_R";
36 let mut p: V0SymbolMangler<'_> = V0SymbolMangler {
37 tcx,
38 start_offset: prefix.len(),
39 is_exportable,
40 paths: FxHashMap::default(),
41 types: FxHashMap::default(),
42 consts: FxHashMap::default(),
43 binders: vec![],
44 out: String::from(prefix),
45 };
46
47 let shim_kind = match instance.def {
49 ty::InstanceKind::ThreadLocalShim(_) => Some("tls"),
50 ty::InstanceKind::VTableShim(_) => Some("vtable"),
51 ty::InstanceKind::ReifyShim(_, None) => Some("reify"),
52 ty::InstanceKind::ReifyShim(_, Some(ReifyReason::FnPtr)) => Some("reify_fnptr"),
53 ty::InstanceKind::ReifyShim(_, Some(ReifyReason::Vtable)) => Some("reify_vtable"),
54
55 ty::InstanceKind::ConstructCoroutineInClosureShim { receiver_by_ref: true, .. } => {
58 Some("by_move")
59 }
60 ty::InstanceKind::ConstructCoroutineInClosureShim { receiver_by_ref: false, .. } => {
61 Some("by_ref")
62 }
63 ty::InstanceKind::FutureDropPollShim(_, _, _) => Some("drop"),
64 _ => None,
65 };
66
67 if let ty::InstanceKind::AsyncDropGlue(_, ty) = instance.def {
68 let ty::Coroutine(_, cor_args) = ty.kind() else {
69 bug!();
70 };
71 let drop_ty = cor_args.first().unwrap().expect_ty();
72 p.print_def_path(def_id, tcx.mk_args(&[GenericArg::from(drop_ty)])).unwrap()
73 } else if let Some(shim_kind) = shim_kind {
74 p.path_append_ns(|p| p.print_def_path(def_id, args), 'S', 0, shim_kind).unwrap()
75 } else {
76 p.print_def_path(def_id, args).unwrap()
77 };
78 if let Some(instantiating_crate) = instantiating_crate {
79 p.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap();
80 }
81 std::mem::take(&mut p.out)
82}
83
84pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> String {
85 match item_name {
86 "rust_eh_personality" => return item_name.to_owned(),
88 "__isPlatformVersionAtLeast" | "__isOSVersionAtLeast" => return item_name.to_owned(),
91 _ => {}
92 }
93
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: vec![],
103 out: String::from(prefix),
104 };
105
106 p.path_append_ns(
107 |p| {
108 p.push("C");
109 p.push_disambiguator({
110 let mut hasher = StableHasher::new();
111 hasher.write(tcx.sess.cfg_version.as_bytes());
117
118 let hash: Hash64 = hasher.finish();
119 hash.as_u64()
120 });
121 p.push_ident("__rustc");
122 Ok(())
123 },
124 'v',
125 0,
126 item_name,
127 )
128 .unwrap();
129
130 std::mem::take(&mut p.out)
131}
132
133pub(super) fn mangle_typeid_for_trait_ref<'tcx>(
134 tcx: TyCtxt<'tcx>,
135 trait_ref: ty::ExistentialTraitRef<'tcx>,
136) -> String {
137 let mut p = V0SymbolMangler {
139 tcx,
140 start_offset: 0,
141 is_exportable: false,
142 paths: FxHashMap::default(),
143 types: FxHashMap::default(),
144 consts: FxHashMap::default(),
145 binders: vec![],
146 out: String::new(),
147 };
148 p.print_def_path(trait_ref.def_id, &[]).unwrap();
149 std::mem::take(&mut p.out)
150}
151
152struct BinderLevel {
153 lifetime_depths: Range<u32>,
164}
165
166struct V0SymbolMangler<'tcx> {
167 tcx: TyCtxt<'tcx>,
168 binders: Vec<BinderLevel>,
169 out: String,
170 is_exportable: bool,
171
172 start_offset: usize,
174 paths: FxHashMap<(DefId, &'tcx [GenericArg<'tcx>]), usize>,
176 types: FxHashMap<Ty<'tcx>, usize>,
177 consts: FxHashMap<ty::Const<'tcx>, usize>,
178}
179
180impl<'tcx> V0SymbolMangler<'tcx> {
181 fn push(&mut self, s: &str) {
182 self.out.push_str(s);
183 }
184
185 fn push_integer_62(&mut self, x: u64) {
191 push_integer_62(x, &mut self.out)
192 }
193
194 fn push_opt_integer_62(&mut self, tag: &str, x: u64) {
199 if let Some(x) = x.checked_sub(1) {
200 self.push(tag);
201 self.push_integer_62(x);
202 }
203 }
204
205 fn push_disambiguator(&mut self, dis: u64) {
206 self.push_opt_integer_62("s", dis);
207 }
208
209 fn push_ident(&mut self, ident: &str) {
210 push_ident(ident, &mut self.out)
211 }
212
213 fn path_append_ns(
214 &mut self,
215 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
216 ns: char,
217 disambiguator: u64,
218 name: &str,
219 ) -> Result<(), PrintError> {
220 self.push("N");
221 self.out.push(ns);
222 print_prefix(self)?;
223 self.push_disambiguator(disambiguator);
224 self.push_ident(name);
225 Ok(())
226 }
227
228 fn print_backref(&mut self, i: usize) -> Result<(), PrintError> {
229 self.push("B");
230 self.push_integer_62((i - self.start_offset) as u64);
231 Ok(())
232 }
233
234 fn wrap_binder<T>(
235 &mut self,
236 value: &ty::Binder<'tcx, T>,
237 print_value: impl FnOnce(&mut Self, &T) -> Result<(), PrintError>,
238 ) -> Result<(), PrintError>
239 where
240 T: TypeVisitable<TyCtxt<'tcx>>,
241 {
242 let mut lifetime_depths =
243 self.binders.last().map(|b| b.lifetime_depths.end).map_or(0..0, |i| i..i);
244
245 let lifetimes = value
247 .bound_vars()
248 .iter()
249 .filter(|var| matches!(var, ty::BoundVariableKind::Region(..)))
250 .count() as u32;
251
252 self.push_opt_integer_62("G", lifetimes as u64);
253 lifetime_depths.end += lifetimes;
254
255 self.binders.push(BinderLevel { lifetime_depths });
256 print_value(self, value.as_ref().skip_binder())?;
257 self.binders.pop();
258
259 Ok(())
260 }
261
262 fn print_pat(&mut self, pat: ty::Pattern<'tcx>) -> Result<(), std::fmt::Error> {
263 Ok(match *pat {
264 ty::PatternKind::Range { start, end } => {
265 self.push("R");
266 self.print_const(start)?;
267 self.print_const(end)?;
268 }
269 ty::PatternKind::Or(patterns) => {
270 self.push("O");
271 for pat in patterns {
272 self.print_pat(pat)?;
273 }
274 self.push("E");
275 }
276 })
277 }
278}
279
280impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> {
281 fn tcx(&self) -> TyCtxt<'tcx> {
282 self.tcx
283 }
284
285 fn print_def_path(
286 &mut self,
287 def_id: DefId,
288 args: &'tcx [GenericArg<'tcx>],
289 ) -> Result<(), PrintError> {
290 if let Some(&i) = self.paths.get(&(def_id, args)) {
291 return self.print_backref(i);
292 }
293 let start = self.out.len();
294
295 self.default_print_def_path(def_id, args)?;
296
297 if !args.iter().any(|k| k.has_escaping_bound_vars()) {
300 self.paths.insert((def_id, args), start);
301 }
302 Ok(())
303 }
304
305 fn print_impl_path(
306 &mut self,
307 impl_def_id: DefId,
308 args: &'tcx [GenericArg<'tcx>],
309 ) -> Result<(), PrintError> {
310 let key = self.tcx.def_key(impl_def_id);
311 let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
312
313 let self_ty = self.tcx.type_of(impl_def_id);
314 let impl_trait_ref = self.tcx.impl_trait_ref(impl_def_id);
315 let generics = self.tcx.generics_of(impl_def_id);
316 let (typing_env, mut self_ty, mut impl_trait_ref) = if generics.count() > args.len()
330 || &args[..generics.count()]
331 == self
332 .tcx
333 .erase_and_anonymize_regions(ty::GenericArgs::identity_for_item(
334 self.tcx,
335 impl_def_id,
336 ))
337 .as_slice()
338 {
339 (
340 ty::TypingEnv::post_analysis(self.tcx, impl_def_id),
341 self_ty.instantiate_identity(),
342 impl_trait_ref.map(|impl_trait_ref| impl_trait_ref.instantiate_identity()),
343 )
344 } else {
345 assert!(
346 !args.has_non_region_param() && !args.has_free_regions(),
347 "should not be mangling partially substituted \
348 polymorphic instance: {impl_def_id:?} {args:?}"
349 );
350 (
351 ty::TypingEnv::fully_monomorphized(),
352 self_ty.instantiate(self.tcx, args),
353 impl_trait_ref.map(|impl_trait_ref| impl_trait_ref.instantiate(self.tcx, args)),
354 )
355 };
356
357 match &mut impl_trait_ref {
358 Some(impl_trait_ref) => {
359 assert_eq!(impl_trait_ref.self_ty(), self_ty);
360 *impl_trait_ref = self.tcx.normalize_erasing_regions(typing_env, *impl_trait_ref);
361 self_ty = impl_trait_ref.self_ty();
362 }
363 None => {
364 self_ty = self.tcx.normalize_erasing_regions(typing_env, self_ty);
365 }
366 }
367
368 self.push(match impl_trait_ref {
369 Some(_) => "X",
370 None => "M",
371 });
372
373 if impl_trait_ref.is_some() && args.iter().any(|a| a.has_non_region_param()) {
376 self.print_path_with_generic_args(
377 |this| {
378 this.path_append_ns(
379 |p| p.print_def_path(parent_def_id, &[]),
380 'I',
381 key.disambiguated_data.disambiguator as u64,
382 "",
383 )
384 },
385 args,
386 )?;
387 } else {
388 let exported_impl_order = self.tcx.stable_order_of_exportable_impls(impl_def_id.krate);
389 let disambiguator = match self.is_exportable {
390 true => exported_impl_order[&impl_def_id] as u64,
391 false => {
392 exported_impl_order.len() as u64 + key.disambiguated_data.disambiguator as u64
393 }
394 };
395 self.push_disambiguator(disambiguator);
396 self.print_def_path(parent_def_id, &[])?;
397 }
398
399 self_ty.print(self)?;
400
401 if let Some(trait_ref) = impl_trait_ref {
402 self.print_def_path(trait_ref.def_id, trait_ref.args)?;
403 }
404
405 Ok(())
406 }
407
408 fn print_region(&mut self, region: ty::Region<'_>) -> Result<(), PrintError> {
409 let i = match region.kind() {
410 ty::ReErased => 0,
413
414 ty::ReBound(debruijn, ty::BoundRegion { var, kind: ty::BoundRegionKind::Anon }) => {
417 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
418 let depth = binder.lifetime_depths.start + var.as_u32();
419
420 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
421 }
422
423 _ => bug!("symbol_names: non-erased region `{:?}`", region),
424 };
425 self.push("L");
426 self.push_integer_62(i as u64);
427 Ok(())
428 }
429
430 fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
431 let basic_type = match ty.kind() {
433 ty::Bool => "b",
434 ty::Char => "c",
435 ty::Str => "e",
436 ty::Int(IntTy::I8) => "a",
437 ty::Int(IntTy::I16) => "s",
438 ty::Int(IntTy::I32) => "l",
439 ty::Int(IntTy::I64) => "x",
440 ty::Int(IntTy::I128) => "n",
441 ty::Int(IntTy::Isize) => "i",
442 ty::Uint(UintTy::U8) => "h",
443 ty::Uint(UintTy::U16) => "t",
444 ty::Uint(UintTy::U32) => "m",
445 ty::Uint(UintTy::U64) => "y",
446 ty::Uint(UintTy::U128) => "o",
447 ty::Uint(UintTy::Usize) => "j",
448 ty::Float(FloatTy::F16) => "C3f16",
449 ty::Float(FloatTy::F32) => "f",
450 ty::Float(FloatTy::F64) => "d",
451 ty::Float(FloatTy::F128) => "C4f128",
452 ty::Never => "z",
453
454 ty::Tuple(_) if ty.is_unit() => "u",
455
456 ty::Param(_) => "p",
459
460 _ => "",
461 };
462 if !basic_type.is_empty() {
463 self.push(basic_type);
464 return Ok(());
465 }
466
467 if let Some(&i) = self.types.get(&ty) {
468 return self.print_backref(i);
469 }
470 let start = self.out.len();
471
472 match *ty.kind() {
473 ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
475 unreachable!()
476 }
477 ty::Tuple(_) if ty.is_unit() => unreachable!(),
478 ty::Param(_) => unreachable!(),
479
480 ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => bug!(),
481
482 ty::Ref(r, ty, mutbl) => {
483 self.push(match mutbl {
484 hir::Mutability::Not => "R",
485 hir::Mutability::Mut => "Q",
486 });
487 if !r.is_erased() {
488 r.print(self)?;
489 }
490 ty.print(self)?;
491 }
492
493 ty::RawPtr(ty, mutbl) => {
494 self.push(match mutbl {
495 hir::Mutability::Not => "P",
496 hir::Mutability::Mut => "O",
497 });
498 ty.print(self)?;
499 }
500
501 ty::Pat(ty, pat) => {
502 self.push("W");
503 ty.print(self)?;
504 self.print_pat(pat)?;
505 }
506
507 ty::Array(ty, len) => {
508 self.push("A");
509 ty.print(self)?;
510 self.print_const(len)?;
511 }
512 ty::Slice(ty) => {
513 self.push("S");
514 ty.print(self)?;
515 }
516
517 ty::Tuple(tys) => {
518 self.push("T");
519 for ty in tys.iter() {
520 ty.print(self)?;
521 }
522 self.push("E");
523 }
524
525 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), args)
527 | ty::FnDef(def_id, args)
528 | ty::Closure(def_id, args)
529 | ty::CoroutineClosure(def_id, args)
530 | ty::Coroutine(def_id, args) => {
531 self.print_def_path(def_id, args)?;
532 }
533
534 ty::Alias(ty::Projection, ty::AliasTy { def_id, args, .. }) => {
537 self.print_def_path(def_id, args)?;
538 }
539
540 ty::Foreign(def_id) => {
541 self.print_def_path(def_id, &[])?;
542 }
543
544 ty::FnPtr(sig_tys, hdr) => {
545 let sig = sig_tys.with(hdr);
546 self.push("F");
547 self.wrap_binder(&sig, |p, sig| {
548 if sig.safety.is_unsafe() {
549 p.push("U");
550 }
551 match sig.abi {
552 ExternAbi::Rust => {}
553 ExternAbi::C { unwind: false } => p.push("KC"),
554 abi => {
555 p.push("K");
556 let name = abi.as_str();
557 if name.contains('-') {
558 p.push_ident(&name.replace('-', "_"));
559 } else {
560 p.push_ident(name);
561 }
562 }
563 }
564 for &ty in sig.inputs() {
565 ty.print(p)?;
566 }
567 if sig.c_variadic {
568 p.push("v");
569 }
570 p.push("E");
571 sig.output().print(p)
572 })?;
573 }
574
575 ty::UnsafeBinder(..) => todo!(),
577
578 ty::Dynamic(predicates, r) => {
579 self.push("D");
580 self.print_dyn_existential(predicates)?;
581 r.print(self)?;
582 }
583
584 ty::Alias(..) => bug!("symbol_names: unexpected alias"),
585 ty::CoroutineWitness(..) => bug!("symbol_names: unexpected `CoroutineWitness`"),
586 }
587
588 if !ty.has_escaping_bound_vars() {
591 self.types.insert(ty, start);
592 }
593 Ok(())
594 }
595
596 fn print_dyn_existential(
597 &mut self,
598 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
599 ) -> Result<(), PrintError> {
600 self.wrap_binder(&predicates[0], |p, _| {
627 for predicate in predicates.iter() {
628 match predicate.as_ref().skip_binder() {
633 ty::ExistentialPredicate::Trait(trait_ref) => {
634 let dummy_self = Ty::new_fresh(p.tcx, 0);
636 let trait_ref = trait_ref.with_self_ty(p.tcx, dummy_self);
637 p.print_def_path(trait_ref.def_id, trait_ref.args)?;
638 }
639 ty::ExistentialPredicate::Projection(projection) => {
640 let name = p.tcx.associated_item(projection.def_id).name();
641 p.push("p");
642 p.push_ident(name.as_str());
643 match projection.term.kind() {
644 ty::TermKind::Ty(ty) => ty.print(p),
645 ty::TermKind::Const(c) => c.print(p),
646 }?;
647 }
648 ty::ExistentialPredicate::AutoTrait(def_id) => {
649 p.print_def_path(*def_id, &[])?;
650 }
651 }
652 }
653 Ok(())
654 })?;
655
656 self.push("E");
657 Ok(())
658 }
659
660 fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
661 let cv = match ct.kind() {
663 ty::ConstKind::Value(cv) => cv,
664
665 ty::ConstKind::Param(_) => {
668 self.push("p");
670 return Ok(());
671 }
672
673 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args, .. }) => {
676 return self.print_def_path(def, args);
677 }
678
679 ty::ConstKind::Expr(_)
680 | ty::ConstKind::Infer(_)
681 | ty::ConstKind::Bound(..)
682 | ty::ConstKind::Placeholder(_)
683 | ty::ConstKind::Error(_) => bug!(),
684 };
685
686 if let Some(&i) = self.consts.get(&ct) {
687 self.print_backref(i)?;
688 return Ok(());
689 }
690
691 let ty::Value { ty: ct_ty, valtree } = cv;
692 let start = self.out.len();
693
694 match ct_ty.kind() {
695 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Char => {
696 ct_ty.print(self)?;
697
698 let mut bits = cv
699 .try_to_bits(self.tcx, ty::TypingEnv::fully_monomorphized())
700 .expect("expected const to be monomorphic");
701
702 if let ty::Int(ity) = ct_ty.kind() {
704 let val =
705 Integer::from_int_ty(&self.tcx, *ity).size().sign_extend(bits) as i128;
706 if val < 0 {
707 self.push("n");
708 }
709 bits = val.unsigned_abs();
710 }
711
712 let _ = write!(self.out, "{bits:x}_");
713 }
714
715 ty::Str => {
717 let tcx = self.tcx();
718 let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, ct_ty);
721 let cv = ty::Value { ty: ref_ty, valtree };
722 let slice = cv.try_to_raw_bytes(tcx).unwrap_or_else(|| {
723 bug!("expected to get raw bytes from valtree {:?} for type {:}", valtree, ct_ty)
724 });
725 let s = std::str::from_utf8(slice).expect("non utf8 str from MIR interpreter");
726
727 self.push("e");
729
730 for byte in s.bytes() {
732 let _ = write!(self.out, "{byte:02x}");
733 }
734
735 self.push("_");
736 }
737
738 ty::Ref(_, _, mutbl) => {
741 self.push(match mutbl {
742 hir::Mutability::Not => "R",
743 hir::Mutability::Mut => "Q",
744 });
745
746 let pointee_ty =
747 ct_ty.builtin_deref(true).expect("tried to dereference on non-ptr type");
748 let dereferenced_const = ty::Const::new_value(self.tcx, valtree, pointee_ty);
749 dereferenced_const.print(self)?;
750 }
751
752 ty::Array(..) | ty::Tuple(..) | ty::Adt(..) | ty::Slice(_) => {
753 let contents = self.tcx.destructure_const(ct);
754 let fields = contents.fields.iter().copied();
755
756 let print_field_list = |this: &mut Self| {
757 for field in fields.clone() {
758 field.print(this)?;
759 }
760 this.push("E");
761 Ok(())
762 };
763
764 match *ct_ty.kind() {
765 ty::Array(..) | ty::Slice(_) => {
766 self.push("A");
767 print_field_list(self)?;
768 }
769 ty::Tuple(..) => {
770 self.push("T");
771 print_field_list(self)?;
772 }
773 ty::Adt(def, args) => {
774 let variant_idx =
775 contents.variant.expect("destructed const of adt without variant idx");
776 let variant_def = &def.variant(variant_idx);
777
778 self.push("V");
779 self.print_def_path(variant_def.def_id, args)?;
780
781 match variant_def.ctor_kind() {
782 Some(CtorKind::Const) => {
783 self.push("U");
784 }
785 Some(CtorKind::Fn) => {
786 self.push("T");
787 print_field_list(self)?;
788 }
789 None => {
790 self.push("S");
791 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
792 let disambiguated_field =
796 self.tcx.def_key(field_def.did).disambiguated_data;
797 let field_name = disambiguated_field.data.get_opt_name();
798 self.push_disambiguator(
799 disambiguated_field.disambiguator as u64,
800 );
801 self.push_ident(field_name.unwrap().as_str());
802
803 field.print(self)?;
804 }
805 self.push("E");
806 }
807 }
808 }
809 _ => unreachable!(),
810 }
811 }
812 _ => {
813 bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct_ty, ct);
814 }
815 }
816
817 if !ct.has_escaping_bound_vars() {
820 self.consts.insert(ct, start);
821 }
822 Ok(())
823 }
824
825 fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
826 self.push("C");
827 if !self.is_exportable {
828 let stable_crate_id = self.tcx.def_path_hash(cnum.as_def_id()).stable_crate_id();
829 self.push_disambiguator(stable_crate_id.as_u64());
830 }
831 let name = self.tcx.crate_name(cnum);
832 self.push_ident(name.as_str());
833 Ok(())
834 }
835
836 fn print_path_with_qualified(
837 &mut self,
838 self_ty: Ty<'tcx>,
839 trait_ref: Option<ty::TraitRef<'tcx>>,
840 ) -> Result<(), PrintError> {
841 assert!(trait_ref.is_some());
842 let trait_ref = trait_ref.unwrap();
843
844 self.push("Y");
845 self_ty.print(self)?;
846 self.print_def_path(trait_ref.def_id, trait_ref.args)
847 }
848
849 fn print_path_with_impl(
850 &mut self,
851 _: impl FnOnce(&mut Self) -> Result<(), PrintError>,
852 _: Ty<'tcx>,
853 _: Option<ty::TraitRef<'tcx>>,
854 ) -> Result<(), PrintError> {
855 unreachable!()
857 }
858
859 fn print_path_with_simple(
860 &mut self,
861 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
862 disambiguated_data: &DisambiguatedDefPathData,
863 ) -> Result<(), PrintError> {
864 let ns = match disambiguated_data.data {
865 DefPathData::ForeignMod => return print_prefix(self),
868
869 DefPathData::TypeNs(_) => 't',
871 DefPathData::ValueNs(_) => 'v',
872 DefPathData::Closure => 'C',
873 DefPathData::Ctor => 'c',
874 DefPathData::AnonConst => 'k',
875 DefPathData::OpaqueTy => 'i',
876 DefPathData::SyntheticCoroutineBody => 's',
877 DefPathData::NestedStatic => 'n',
878
879 DefPathData::CrateRoot
881 | DefPathData::Use
882 | DefPathData::GlobalAsm
883 | DefPathData::Impl
884 | DefPathData::MacroNs(_)
885 | DefPathData::LifetimeNs(_)
886 | DefPathData::OpaqueLifetime(_)
887 | DefPathData::AnonAssocTy(..) => {
888 bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
889 }
890 };
891
892 let name = disambiguated_data.data.get_opt_name();
893
894 self.path_append_ns(
895 print_prefix,
896 ns,
897 disambiguated_data.disambiguator as u64,
898 name.unwrap_or(sym::empty).as_str(),
899 )
900 }
901
902 fn print_path_with_generic_args(
903 &mut self,
904 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
905 args: &[GenericArg<'tcx>],
906 ) -> Result<(), PrintError> {
907 let print_regions = args.iter().any(|arg| match arg.kind() {
909 GenericArgKind::Lifetime(r) => !r.is_erased(),
910 _ => false,
911 });
912 let args = args.iter().cloned().filter(|arg| match arg.kind() {
913 GenericArgKind::Lifetime(_) => print_regions,
914 _ => true,
915 });
916
917 if args.clone().next().is_none() {
918 return print_prefix(self);
919 }
920
921 self.push("I");
922 print_prefix(self)?;
923 for arg in args {
924 match arg.kind() {
925 GenericArgKind::Lifetime(lt) => {
926 lt.print(self)?;
927 }
928 GenericArgKind::Type(ty) => {
929 ty.print(self)?;
930 }
931 GenericArgKind::Const(c) => {
932 self.push("K");
933 c.print(self)?;
934 }
935 }
936 }
937 self.push("E");
938
939 Ok(())
940 }
941}
942pub(crate) fn push_integer_62(x: u64, output: &mut String) {
948 if let Some(x) = x.checked_sub(1) {
949 output.push_str(&x.to_base(62));
950 }
951 output.push('_');
952}
953
954pub(crate) fn encode_integer_62(x: u64) -> String {
955 let mut output = String::new();
956 push_integer_62(x, &mut output);
957 output
958}
959
960pub(crate) fn push_ident(ident: &str, output: &mut String) {
961 let mut use_punycode = false;
962 for b in ident.bytes() {
963 match b {
964 b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
965 0x80..=0xff => use_punycode = true,
966 _ => bug!("symbol_names: bad byte {} in ident {:?}", b, ident),
967 }
968 }
969
970 let punycode_string;
971 let ident = if use_punycode {
972 output.push('u');
973
974 let mut punycode_bytes = match punycode::encode(ident) {
976 Ok(s) => s.into_bytes(),
977 Err(()) => bug!("symbol_names: punycode encoding failed for ident {:?}", ident),
978 };
979
980 if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
982 *c = b'_';
983 }
984
985 punycode_string = String::from_utf8(punycode_bytes).unwrap();
987 &punycode_string
988 } else {
989 ident
990 };
991
992 let _ = write!(output, "{}", ident.len());
993
994 if let Some('_' | '0'..='9') = ident.chars().next() {
996 output.push('_');
997 }
998
999 output.push_str(ident);
1000}