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 let consts = [start, end];
266 for ct in consts {
267 Ty::new_array_with_const_len(self.tcx, self.tcx.types.unit, ct).print(self)?;
268 }
269 }
270 ty::PatternKind::Or(patterns) => {
271 for pat in patterns {
272 self.print_pat(pat)?;
273 }
274 }
275 })
276 }
277}
278
279impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> {
280 fn tcx(&self) -> TyCtxt<'tcx> {
281 self.tcx
282 }
283
284 fn print_def_path(
285 &mut self,
286 def_id: DefId,
287 args: &'tcx [GenericArg<'tcx>],
288 ) -> Result<(), PrintError> {
289 if let Some(&i) = self.paths.get(&(def_id, args)) {
290 return self.print_backref(i);
291 }
292 let start = self.out.len();
293
294 self.default_print_def_path(def_id, args)?;
295
296 if !args.iter().any(|k| k.has_escaping_bound_vars()) {
299 self.paths.insert((def_id, args), start);
300 }
301 Ok(())
302 }
303
304 fn print_impl_path(
305 &mut self,
306 impl_def_id: DefId,
307 args: &'tcx [GenericArg<'tcx>],
308 ) -> Result<(), PrintError> {
309 let key = self.tcx.def_key(impl_def_id);
310 let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
311
312 let self_ty = self.tcx.type_of(impl_def_id);
313 let impl_trait_ref = self.tcx.impl_trait_ref(impl_def_id);
314 let generics = self.tcx.generics_of(impl_def_id);
315 let (typing_env, mut self_ty, mut impl_trait_ref) = if generics.count() > args.len()
329 || &args[..generics.count()]
330 == self
331 .tcx
332 .erase_and_anonymize_regions(ty::GenericArgs::identity_for_item(
333 self.tcx,
334 impl_def_id,
335 ))
336 .as_slice()
337 {
338 (
339 ty::TypingEnv::post_analysis(self.tcx, impl_def_id),
340 self_ty.instantiate_identity(),
341 impl_trait_ref.map(|impl_trait_ref| impl_trait_ref.instantiate_identity()),
342 )
343 } else {
344 assert!(
345 !args.has_non_region_param() && !args.has_free_regions(),
346 "should not be mangling partially substituted \
347 polymorphic instance: {impl_def_id:?} {args:?}"
348 );
349 (
350 ty::TypingEnv::fully_monomorphized(),
351 self_ty.instantiate(self.tcx, args),
352 impl_trait_ref.map(|impl_trait_ref| impl_trait_ref.instantiate(self.tcx, args)),
353 )
354 };
355
356 match &mut impl_trait_ref {
357 Some(impl_trait_ref) => {
358 assert_eq!(impl_trait_ref.self_ty(), self_ty);
359 *impl_trait_ref = self.tcx.normalize_erasing_regions(typing_env, *impl_trait_ref);
360 self_ty = impl_trait_ref.self_ty();
361 }
362 None => {
363 self_ty = self.tcx.normalize_erasing_regions(typing_env, self_ty);
364 }
365 }
366
367 self.push(match impl_trait_ref {
368 Some(_) => "X",
369 None => "M",
370 });
371
372 if impl_trait_ref.is_some() && args.iter().any(|a| a.has_non_region_param()) {
375 self.print_path_with_generic_args(
376 |this| {
377 this.path_append_ns(
378 |p| p.print_def_path(parent_def_id, &[]),
379 'I',
380 key.disambiguated_data.disambiguator as u64,
381 "",
382 )
383 },
384 args,
385 )?;
386 } else {
387 let exported_impl_order = self.tcx.stable_order_of_exportable_impls(impl_def_id.krate);
388 let disambiguator = match self.is_exportable {
389 true => exported_impl_order[&impl_def_id] as u64,
390 false => {
391 exported_impl_order.len() as u64 + key.disambiguated_data.disambiguator as u64
392 }
393 };
394 self.push_disambiguator(disambiguator);
395 self.print_def_path(parent_def_id, &[])?;
396 }
397
398 self_ty.print(self)?;
399
400 if let Some(trait_ref) = impl_trait_ref {
401 self.print_def_path(trait_ref.def_id, trait_ref.args)?;
402 }
403
404 Ok(())
405 }
406
407 fn print_region(&mut self, region: ty::Region<'_>) -> Result<(), PrintError> {
408 let i = match region.kind() {
409 ty::ReErased => 0,
412
413 ty::ReBound(debruijn, ty::BoundRegion { var, kind: ty::BoundRegionKind::Anon }) => {
416 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
417 let depth = binder.lifetime_depths.start + var.as_u32();
418
419 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
420 }
421
422 _ => bug!("symbol_names: non-erased region `{:?}`", region),
423 };
424 self.push("L");
425 self.push_integer_62(i as u64);
426 Ok(())
427 }
428
429 fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
430 let basic_type = match ty.kind() {
432 ty::Bool => "b",
433 ty::Char => "c",
434 ty::Str => "e",
435 ty::Int(IntTy::I8) => "a",
436 ty::Int(IntTy::I16) => "s",
437 ty::Int(IntTy::I32) => "l",
438 ty::Int(IntTy::I64) => "x",
439 ty::Int(IntTy::I128) => "n",
440 ty::Int(IntTy::Isize) => "i",
441 ty::Uint(UintTy::U8) => "h",
442 ty::Uint(UintTy::U16) => "t",
443 ty::Uint(UintTy::U32) => "m",
444 ty::Uint(UintTy::U64) => "y",
445 ty::Uint(UintTy::U128) => "o",
446 ty::Uint(UintTy::Usize) => "j",
447 ty::Float(FloatTy::F16) => "C3f16",
448 ty::Float(FloatTy::F32) => "f",
449 ty::Float(FloatTy::F64) => "d",
450 ty::Float(FloatTy::F128) => "C4f128",
451 ty::Never => "z",
452
453 ty::Tuple(_) if ty.is_unit() => "u",
454
455 ty::Param(_) => "p",
458
459 _ => "",
460 };
461 if !basic_type.is_empty() {
462 self.push(basic_type);
463 return Ok(());
464 }
465
466 if let Some(&i) = self.types.get(&ty) {
467 return self.print_backref(i);
468 }
469 let start = self.out.len();
470
471 match *ty.kind() {
472 ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
474 unreachable!()
475 }
476 ty::Tuple(_) if ty.is_unit() => unreachable!(),
477 ty::Param(_) => unreachable!(),
478
479 ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => bug!(),
480
481 ty::Ref(r, ty, mutbl) => {
482 self.push(match mutbl {
483 hir::Mutability::Not => "R",
484 hir::Mutability::Mut => "Q",
485 });
486 if !r.is_erased() {
487 r.print(self)?;
488 }
489 ty.print(self)?;
490 }
491
492 ty::RawPtr(ty, mutbl) => {
493 self.push(match mutbl {
494 hir::Mutability::Not => "P",
495 hir::Mutability::Mut => "O",
496 });
497 ty.print(self)?;
498 }
499
500 ty::Pat(ty, pat) => {
501 self.push("T");
504 ty.print(self)?;
505 self.print_pat(pat)?;
506 self.push("E");
507 }
508
509 ty::Array(ty, len) => {
510 self.push("A");
511 ty.print(self)?;
512 self.print_const(len)?;
513 }
514 ty::Slice(ty) => {
515 self.push("S");
516 ty.print(self)?;
517 }
518
519 ty::Tuple(tys) => {
520 self.push("T");
521 for ty in tys.iter() {
522 ty.print(self)?;
523 }
524 self.push("E");
525 }
526
527 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), args)
529 | ty::FnDef(def_id, args)
530 | ty::Closure(def_id, args)
531 | ty::CoroutineClosure(def_id, args)
532 | ty::Coroutine(def_id, args) => {
533 self.print_def_path(def_id, args)?;
534 }
535
536 ty::Alias(ty::Projection, ty::AliasTy { def_id, args, .. }) => {
539 self.print_def_path(def_id, args)?;
540 }
541
542 ty::Foreign(def_id) => {
543 self.print_def_path(def_id, &[])?;
544 }
545
546 ty::FnPtr(sig_tys, hdr) => {
547 let sig = sig_tys.with(hdr);
548 self.push("F");
549 self.wrap_binder(&sig, |p, sig| {
550 if sig.safety.is_unsafe() {
551 p.push("U");
552 }
553 match sig.abi {
554 ExternAbi::Rust => {}
555 ExternAbi::C { unwind: false } => p.push("KC"),
556 abi => {
557 p.push("K");
558 let name = abi.as_str();
559 if name.contains('-') {
560 p.push_ident(&name.replace('-', "_"));
561 } else {
562 p.push_ident(name);
563 }
564 }
565 }
566 for &ty in sig.inputs() {
567 ty.print(p)?;
568 }
569 if sig.c_variadic {
570 p.push("v");
571 }
572 p.push("E");
573 sig.output().print(p)
574 })?;
575 }
576
577 ty::UnsafeBinder(..) => todo!(),
579
580 ty::Dynamic(predicates, r, kind) => {
581 self.push(match kind {
582 ty::Dyn => "D",
583 });
584 self.print_dyn_existential(predicates)?;
585 r.print(self)?;
586 }
587
588 ty::Alias(..) => bug!("symbol_names: unexpected alias"),
589 ty::CoroutineWitness(..) => bug!("symbol_names: unexpected `CoroutineWitness`"),
590 }
591
592 if !ty.has_escaping_bound_vars() {
595 self.types.insert(ty, start);
596 }
597 Ok(())
598 }
599
600 fn print_dyn_existential(
601 &mut self,
602 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
603 ) -> Result<(), PrintError> {
604 self.wrap_binder(&predicates[0], |p, _| {
631 for predicate in predicates.iter() {
632 match predicate.as_ref().skip_binder() {
637 ty::ExistentialPredicate::Trait(trait_ref) => {
638 let dummy_self = Ty::new_fresh(p.tcx, 0);
640 let trait_ref = trait_ref.with_self_ty(p.tcx, dummy_self);
641 p.print_def_path(trait_ref.def_id, trait_ref.args)?;
642 }
643 ty::ExistentialPredicate::Projection(projection) => {
644 let name = p.tcx.associated_item(projection.def_id).name();
645 p.push("p");
646 p.push_ident(name.as_str());
647 match projection.term.kind() {
648 ty::TermKind::Ty(ty) => ty.print(p),
649 ty::TermKind::Const(c) => c.print(p),
650 }?;
651 }
652 ty::ExistentialPredicate::AutoTrait(def_id) => {
653 p.print_def_path(*def_id, &[])?;
654 }
655 }
656 }
657 Ok(())
658 })?;
659
660 self.push("E");
661 Ok(())
662 }
663
664 fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
665 let cv = match ct.kind() {
667 ty::ConstKind::Value(cv) => cv,
668
669 ty::ConstKind::Param(_) => {
672 self.push("p");
674 return Ok(());
675 }
676
677 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args, .. }) => {
680 return self.print_def_path(def, args);
681 }
682
683 ty::ConstKind::Expr(_)
684 | ty::ConstKind::Infer(_)
685 | ty::ConstKind::Bound(..)
686 | ty::ConstKind::Placeholder(_)
687 | ty::ConstKind::Error(_) => bug!(),
688 };
689
690 if let Some(&i) = self.consts.get(&ct) {
691 self.print_backref(i)?;
692 return Ok(());
693 }
694
695 let ty::Value { ty: ct_ty, valtree } = cv;
696 let start = self.out.len();
697
698 match ct_ty.kind() {
699 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Char => {
700 ct_ty.print(self)?;
701
702 let mut bits = cv
703 .try_to_bits(self.tcx, ty::TypingEnv::fully_monomorphized())
704 .expect("expected const to be monomorphic");
705
706 if let ty::Int(ity) = ct_ty.kind() {
708 let val =
709 Integer::from_int_ty(&self.tcx, *ity).size().sign_extend(bits) as i128;
710 if val < 0 {
711 self.push("n");
712 }
713 bits = val.unsigned_abs();
714 }
715
716 let _ = write!(self.out, "{bits:x}_");
717 }
718
719 ty::Str => {
721 let tcx = self.tcx();
722 let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, ct_ty);
725 let cv = ty::Value { ty: ref_ty, valtree };
726 let slice = cv.try_to_raw_bytes(tcx).unwrap_or_else(|| {
727 bug!("expected to get raw bytes from valtree {:?} for type {:}", valtree, ct_ty)
728 });
729 let s = std::str::from_utf8(slice).expect("non utf8 str from MIR interpreter");
730
731 self.push("e");
733
734 for byte in s.bytes() {
736 let _ = write!(self.out, "{byte:02x}");
737 }
738
739 self.push("_");
740 }
741
742 ty::Ref(_, _, mutbl) => {
745 self.push(match mutbl {
746 hir::Mutability::Not => "R",
747 hir::Mutability::Mut => "Q",
748 });
749
750 let pointee_ty =
751 ct_ty.builtin_deref(true).expect("tried to dereference on non-ptr type");
752 let dereferenced_const = ty::Const::new_value(self.tcx, valtree, pointee_ty);
753 dereferenced_const.print(self)?;
754 }
755
756 ty::Array(..) | ty::Tuple(..) | ty::Adt(..) | ty::Slice(_) => {
757 let contents = self.tcx.destructure_const(ct);
758 let fields = contents.fields.iter().copied();
759
760 let print_field_list = |this: &mut Self| {
761 for field in fields.clone() {
762 field.print(this)?;
763 }
764 this.push("E");
765 Ok(())
766 };
767
768 match *ct_ty.kind() {
769 ty::Array(..) | ty::Slice(_) => {
770 self.push("A");
771 print_field_list(self)?;
772 }
773 ty::Tuple(..) => {
774 self.push("T");
775 print_field_list(self)?;
776 }
777 ty::Adt(def, args) => {
778 let variant_idx =
779 contents.variant.expect("destructed const of adt without variant idx");
780 let variant_def = &def.variant(variant_idx);
781
782 self.push("V");
783 self.print_def_path(variant_def.def_id, args)?;
784
785 match variant_def.ctor_kind() {
786 Some(CtorKind::Const) => {
787 self.push("U");
788 }
789 Some(CtorKind::Fn) => {
790 self.push("T");
791 print_field_list(self)?;
792 }
793 None => {
794 self.push("S");
795 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
796 let disambiguated_field =
800 self.tcx.def_key(field_def.did).disambiguated_data;
801 let field_name = disambiguated_field.data.get_opt_name();
802 self.push_disambiguator(
803 disambiguated_field.disambiguator as u64,
804 );
805 self.push_ident(field_name.unwrap().as_str());
806
807 field.print(self)?;
808 }
809 self.push("E");
810 }
811 }
812 }
813 _ => unreachable!(),
814 }
815 }
816 _ => {
817 bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct_ty, ct);
818 }
819 }
820
821 if !ct.has_escaping_bound_vars() {
824 self.consts.insert(ct, start);
825 }
826 Ok(())
827 }
828
829 fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
830 self.push("C");
831 if !self.is_exportable {
832 let stable_crate_id = self.tcx.def_path_hash(cnum.as_def_id()).stable_crate_id();
833 self.push_disambiguator(stable_crate_id.as_u64());
834 }
835 let name = self.tcx.crate_name(cnum);
836 self.push_ident(name.as_str());
837 Ok(())
838 }
839
840 fn print_path_with_qualified(
841 &mut self,
842 self_ty: Ty<'tcx>,
843 trait_ref: Option<ty::TraitRef<'tcx>>,
844 ) -> Result<(), PrintError> {
845 assert!(trait_ref.is_some());
846 let trait_ref = trait_ref.unwrap();
847
848 self.push("Y");
849 self_ty.print(self)?;
850 self.print_def_path(trait_ref.def_id, trait_ref.args)
851 }
852
853 fn print_path_with_impl(
854 &mut self,
855 _: impl FnOnce(&mut Self) -> Result<(), PrintError>,
856 _: Ty<'tcx>,
857 _: Option<ty::TraitRef<'tcx>>,
858 ) -> Result<(), PrintError> {
859 unreachable!()
861 }
862
863 fn print_path_with_simple(
864 &mut self,
865 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
866 disambiguated_data: &DisambiguatedDefPathData,
867 ) -> Result<(), PrintError> {
868 let ns = match disambiguated_data.data {
869 DefPathData::ForeignMod => return print_prefix(self),
872
873 DefPathData::TypeNs(_) => 't',
875 DefPathData::ValueNs(_) => 'v',
876 DefPathData::Closure => 'C',
877 DefPathData::Ctor => 'c',
878 DefPathData::AnonConst => 'k',
879 DefPathData::OpaqueTy => 'i',
880 DefPathData::SyntheticCoroutineBody => 's',
881 DefPathData::NestedStatic => 'n',
882
883 DefPathData::CrateRoot
885 | DefPathData::Use
886 | DefPathData::GlobalAsm
887 | DefPathData::Impl
888 | DefPathData::MacroNs(_)
889 | DefPathData::LifetimeNs(_)
890 | DefPathData::OpaqueLifetime(_)
891 | DefPathData::AnonAssocTy(..) => {
892 bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
893 }
894 };
895
896 let name = disambiguated_data.data.get_opt_name();
897
898 self.path_append_ns(
899 print_prefix,
900 ns,
901 disambiguated_data.disambiguator as u64,
902 name.unwrap_or(sym::empty).as_str(),
903 )
904 }
905
906 fn print_path_with_generic_args(
907 &mut self,
908 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
909 args: &[GenericArg<'tcx>],
910 ) -> Result<(), PrintError> {
911 let print_regions = args.iter().any(|arg| match arg.kind() {
913 GenericArgKind::Lifetime(r) => !r.is_erased(),
914 _ => false,
915 });
916 let args = args.iter().cloned().filter(|arg| match arg.kind() {
917 GenericArgKind::Lifetime(_) => print_regions,
918 _ => true,
919 });
920
921 if args.clone().next().is_none() {
922 return print_prefix(self);
923 }
924
925 self.push("I");
926 print_prefix(self)?;
927 for arg in args {
928 match arg.kind() {
929 GenericArgKind::Lifetime(lt) => {
930 lt.print(self)?;
931 }
932 GenericArgKind::Type(ty) => {
933 ty.print(self)?;
934 }
935 GenericArgKind::Const(c) => {
936 self.push("K");
937 c.print(self)?;
938 }
939 }
940 }
941 self.push("E");
942
943 Ok(())
944 }
945}
946pub(crate) fn push_integer_62(x: u64, output: &mut String) {
952 if let Some(x) = x.checked_sub(1) {
953 output.push_str(&x.to_base(62));
954 }
955 output.push('_');
956}
957
958pub(crate) fn encode_integer_62(x: u64) -> String {
959 let mut output = String::new();
960 push_integer_62(x, &mut output);
961 output
962}
963
964pub(crate) fn push_ident(ident: &str, output: &mut String) {
965 let mut use_punycode = false;
966 for b in ident.bytes() {
967 match b {
968 b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
969 0x80..=0xff => use_punycode = true,
970 _ => bug!("symbol_names: bad byte {} in ident {:?}", b, ident),
971 }
972 }
973
974 let punycode_string;
975 let ident = if use_punycode {
976 output.push('u');
977
978 let mut punycode_bytes = match punycode::encode(ident) {
980 Ok(s) => s.into_bytes(),
981 Err(()) => bug!("symbol_names: punycode encoding failed for ident {:?}", ident),
982 };
983
984 if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
986 *c = b'_';
987 }
988
989 punycode_string = String::from_utf8(punycode_bytes).unwrap();
991 &punycode_string
992 } else {
993 ident
994 };
995
996 let _ = write!(output, "{}", ident.len());
997
998 if let Some('_' | '0'..='9') = ident.chars().next() {
1000 output.push('_');
1001 }
1002
1003 output.push_str(ident);
1004}