1use std::fmt::{self, Write};
2use std::mem::{self, discriminant};
3
4use rustc_data_structures::stable_hash::{StableHash, StableHasher};
5use rustc_hashes::Hash64;
6use rustc_hir::def_id::{CrateNum, DefId};
7use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
8use rustc_middle::ty::consts::ConstExt;
9use rustc_middle::ty::print::{PrettyPrinter, Print, PrintError, Printer};
10use rustc_middle::ty::{
11 self, GenericArg, GenericArgKind, Instance, ReifyReason, Ty, TyCtxt, TypeVisitableExt,
12 Unnormalized,
13};
14use rustc_span::bug;
15use tracing::debug;
16
17pub(super) fn mangle<'tcx>(
18 tcx: TyCtxt<'tcx>,
19 instance: Instance<'tcx>,
20 instantiating_crate: Option<CrateNum>,
21) -> String {
22 let def_id = instance.def_id();
23
24 let mut ty_def_id = def_id;
29 let instance_ty;
30 loop {
31 let key = tcx.def_key(ty_def_id);
32 match key.disambiguated_data.data {
33 DefPathData::TypeNs(_)
34 | DefPathData::ValueNs(_)
35 | DefPathData::Closure
36 | DefPathData::SyntheticCoroutineBody => {
37 instance_ty = tcx.type_of(ty_def_id).instantiate_identity().skip_norm_wip();
38 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_symbol_mangling/src/legacy.rs:38",
"rustc_symbol_mangling::legacy", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_symbol_mangling/src/legacy.rs"),
::tracing_core::__macro_support::Option::Some(38u32),
::tracing_core::__macro_support::Option::Some("rustc_symbol_mangling::legacy"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("instance_ty")
}> =
::tracing::__macro_support::FieldName::new("instance_ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance_ty)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?instance_ty);
39 break;
40 }
41 DefPathData::GlobalAsm => {
42 instance_ty = tcx.types.unit;
44 break;
45 }
46 _ => {
47 ty_def_id.index = key.parent.unwrap_or_else(|| {
51 ::rustc_span::macros::bug_impl(None,
format_args!("finding type for {0:?}, encountered def-id {1:?} with no parent",
def_id, ty_def_id), Location::caller());bug!(
52 "finding type for {:?}, encountered def-id {:?} with no \
53 parent",
54 def_id,
55 ty_def_id
56 );
57 });
58 }
59 }
60 }
61
62 let instance_ty = tcx.erase_and_anonymize_regions(instance_ty);
65
66 let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate);
67
68 let mut p = LegacySymbolMangler { tcx, path: SymbolPath::new(), keep_within_component: false };
69 p.print_def_path(
70 def_id,
71 if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, _))
72 | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(_, _))
73 | ty::InstanceKind::Shim(ty::ShimKind::FutureDropPoll(_, _, _)) = instance.def
74 {
75 &*instance.args
77 } else if let ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlue(_, ty)) = instance.def {
78 let ty::Coroutine(_, cor_args) = ty.kind() else {
79 ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller());bug!();
80 };
81 let drop_ty = cor_args.first().unwrap().expect_ty();
82 tcx.mk_args(&[GenericArg::from(drop_ty)])
83 } else {
84 &[]
85 },
86 )
87 .unwrap();
88
89 match instance.def {
90 ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(..)) => {
91 p.write_str("{{tls-shim}}").unwrap();
92 }
93 ty::InstanceKind::Shim(ty::ShimKind::VTable(..)) => {
94 p.write_str("{{vtable-shim}}").unwrap();
95 }
96 ty::InstanceKind::Shim(ty::ShimKind::Reify(_, reason)) => {
97 p.write_str("{{reify-shim").unwrap();
98 match reason {
99 Some(ReifyReason::FnPtr) => p.write_str("-fnptr").unwrap(),
100 Some(ReifyReason::Vtable) => p.write_str("-vtable").unwrap(),
101 None => (),
102 }
103 p.write_str("}}").unwrap();
104 }
105 ty::InstanceKind::Shim(ty::ShimKind::ConstructCoroutineInClosure {
108 receiver_by_ref,
109 ..
110 }) => {
111 p.write_str(if receiver_by_ref { "{{by-move-shim}}" } else { "{{by-ref-shim}}" })
112 .unwrap();
113 }
114 _ => {}
115 }
116
117 if let ty::InstanceKind::Shim(ty::ShimKind::FutureDropPoll(..)) = instance.def {
118 let _ = p.write_str("{{drop-shim}}");
119 }
120
121 p.path.finish(hash)
122}
123
124fn get_symbol_hash<'tcx>(
125 tcx: TyCtxt<'tcx>,
126
127 instance: Instance<'tcx>,
129
130 item_type: Ty<'tcx>,
135
136 instantiating_crate: Option<CrateNum>,
137) -> Hash64 {
138 let def_id = instance.def_id();
139 let args = instance.args;
140 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_symbol_mangling/src/legacy.rs:140",
"rustc_symbol_mangling::legacy", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/e9bbadf6824e65b3583c2dda3a0926ec76df9143/compiler/rustc_symbol_mangling/src/legacy.rs"),
::tracing_core::__macro_support::Option::Some(140u32),
::tracing_core::__macro_support::Option::Some("rustc_symbol_mangling::legacy"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("get_symbol_hash(def_id={0:?}, parameters={1:?})",
def_id, args) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, args);
141
142 tcx.with_stable_hashing_context(|mut hcx| {
143 let mut hasher = StableHasher::new();
144
145 tcx.def_path_hash(def_id).stable_hash(&mut hcx, &mut hasher);
149
150 if !!item_type.has_erasable_regions() {
::core::panicking::panic("assertion failed: !item_type.has_erasable_regions()")
};assert!(!item_type.has_erasable_regions());
154 hcx.while_hashing_spans(false, |hcx| {
155 item_type.stable_hash(hcx, &mut hasher);
156
157 if let ty::FnDef(..) = item_type.kind() {
161 item_type.fn_sig(tcx).stable_hash(hcx, &mut hasher);
162 }
163
164 args.stable_hash(hcx, &mut hasher);
166
167 if let Some(instantiating_crate) = instantiating_crate {
168 tcx.stable_crate_id(instantiating_crate).stable_hash(hcx, &mut hasher);
169 }
170
171 discriminant(&instance.def).stable_hash(hcx, &mut hasher);
175 });
176
177 hasher.finish::<Hash64>()
179 })
180}
181
182#[derive(#[automatically_derived]
impl ::core::fmt::Debug for SymbolPath {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "SymbolPath",
"result", &self.result, "temp_buf", &&self.temp_buf)
}
}Debug)]
196struct SymbolPath {
197 result: String,
198 temp_buf: String,
199}
200
201impl SymbolPath {
202 fn new() -> Self {
203 let mut result =
204 SymbolPath { result: String::with_capacity(64), temp_buf: String::with_capacity(16) };
205 result.result.push_str("_ZN"); result
207 }
208
209 fn finalize_pending_component(&mut self) {
210 if !self.temp_buf.is_empty() {
211 let _ = self.result.write_fmt(format_args!("{0}{1}", self.temp_buf.len(),
self.temp_buf))write!(self.result, "{}{}", self.temp_buf.len(), self.temp_buf);
212 self.temp_buf.clear();
213 }
214 }
215
216 fn finish(mut self, hash: Hash64) -> String {
217 self.finalize_pending_component();
218 let _ = self.result.write_fmt(format_args!("17h{0:016x}E", hash))write!(self.result, "17h{hash:016x}E");
220 self.result
221 }
222}
223
224struct LegacySymbolMangler<'tcx> {
225 tcx: TyCtxt<'tcx>,
226 path: SymbolPath,
227
228 keep_within_component: bool,
233}
234
235impl<'tcx> Printer<'tcx> for LegacySymbolMangler<'tcx> {
240 fn tcx(&self) -> TyCtxt<'tcx> {
241 self.tcx
242 }
243
244 fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> {
245 Ok(())
249 }
250
251 fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
252 match *ty.kind() {
253 ty::Alias(
255 _,
256 ty::AliasTy {
257 kind: ty::Projection { def_id } | ty::Opaque { def_id }, args, ..
258 },
259 )
260 | ty::Closure(def_id, args)
261 | ty::CoroutineClosure(def_id, args)
262 | ty::Coroutine(def_id, args) => self.print_def_path(def_id, args),
263
264 ty::FnDef(def_id, args) => self.print_def_path(def_id, args.no_bound_vars().unwrap()),
265
266 ty::Array(ty, size) => {
269 self.write_str("[")?;
270 self.print_type(ty)?;
271 self.write_str("; ")?;
272 if let Some(size) = size.try_to_target_usize(self.tcx()) {
273 self.write_fmt(format_args!("{0}", size))write!(self, "{size}")?
274 } else if let ty::ConstKind::Param(param) = size.kind() {
275 param.print(self)?
276 } else {
277 self.write_str("_")?
278 }
279 self.write_str("]")?;
280 Ok(())
281 }
282
283 ty::Alias(_, ty::AliasTy { kind: ty::Inherent { .. }, .. }) => {
284 {
::core::panicking::panic_fmt(format_args!("unexpected inherent projection"));
}panic!("unexpected inherent projection")
285 }
286
287 _ => self.pretty_print_type(ty),
288 }
289 }
290
291 fn print_dyn_existential(
292 &mut self,
293 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
294 ) -> Result<(), PrintError> {
295 let mut first = true;
296 for p in predicates {
297 if !first {
298 self.write_fmt(format_args!("+"))write!(self, "+")?;
299 }
300 first = false;
301 p.print(self)?;
302 }
303 Ok(())
304 }
305
306 fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
307 match ct.kind() {
309 ty::ConstKind::Value(cv) if cv.ty.is_integral() => {
310 let scalar = cv.to_leaf();
313 let signed = #[allow(non_exhaustive_omitted_patterns)] match cv.ty.kind() {
ty::Int(_) => true,
_ => false,
}matches!(cv.ty.kind(), ty::Int(_));
314 self.write_fmt(format_args!("{0:#?}",
ty::ConstInt::new(scalar, signed, cv.ty.is_ptr_sized_integral())))write!(
315 self,
316 "{:#?}",
317 ty::ConstInt::new(scalar, signed, cv.ty.is_ptr_sized_integral())
318 )?;
319 }
320 _ => self.write_str("_")?,
321 }
322 Ok(())
323 }
324
325 fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
326 self.write_str(self.tcx.crate_name(cnum).as_str())?;
327 Ok(())
328 }
329
330 fn print_path_with_qualified(
331 &mut self,
332 self_ty: Ty<'tcx>,
333 trait_ref: Option<ty::TraitRef<'tcx>>,
334 ) -> Result<(), PrintError> {
335 match self_ty.kind() {
338 ty::FnDef(..)
339 | ty::Alias(..)
340 | ty::Closure(..)
341 | ty::CoroutineClosure(..)
342 | ty::Coroutine(..)
343 if trait_ref.is_none() =>
344 {
345 self.print_type(self_ty)
346 }
347
348 _ => self.pretty_print_path_with_qualified(self_ty, trait_ref),
349 }
350 }
351
352 fn print_path_with_impl(
353 &mut self,
354 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
355 self_ty: Ty<'tcx>,
356 trait_ref: Option<ty::TraitRef<'tcx>>,
357 ) -> Result<(), PrintError> {
358 self.pretty_print_path_with_impl(
359 |cx| {
360 print_prefix(cx)?;
361
362 if cx.keep_within_component {
363 cx.write_str("::")?;
365 } else {
366 cx.path.finalize_pending_component();
367 }
368
369 Ok(())
370 },
371 self_ty,
372 trait_ref,
373 )
374 }
375
376 fn print_path_with_simple(
377 &mut self,
378 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
379 disambiguated_data: &DisambiguatedDefPathData,
380 ) -> Result<(), PrintError> {
381 print_prefix(self)?;
382
383 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
385 return Ok(());
386 }
387
388 if self.keep_within_component {
389 self.write_str("::")?;
391 } else {
392 self.path.finalize_pending_component();
393 }
394
395 self.write_fmt(format_args!("{0}", disambiguated_data.data))write!(self, "{}", disambiguated_data.data)?;
396
397 Ok(())
398 }
399
400 fn print_path_with_generic_args(
401 &mut self,
402 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
403 args: &[GenericArg<'tcx>],
404 ) -> Result<(), PrintError> {
405 print_prefix(self)?;
406
407 let args =
408 args.iter().cloned().filter(|arg| !#[allow(non_exhaustive_omitted_patterns)] match arg.kind() {
GenericArgKind::Lifetime(_) => true,
_ => false,
}matches!(arg.kind(), GenericArgKind::Lifetime(_)));
409 if args.clone().next().is_some() {
410 self.generic_delimiters(|cx| cx.comma_sep(args))
411 } else {
412 Ok(())
413 }
414 }
415
416 fn print_impl_path(
417 &mut self,
418 impl_def_id: DefId,
419 args: &'tcx [GenericArg<'tcx>],
420 ) -> Result<(), PrintError> {
421 let self_ty = self.tcx.type_of(impl_def_id);
422 let impl_trait_ref = self.tcx.impl_opt_trait_ref(impl_def_id);
423 let generics = self.tcx.generics_of(impl_def_id);
424 let (typing_env, mut self_ty, mut impl_trait_ref) = if generics.count() > args.len()
438 || &args[..generics.count()]
439 == self
440 .tcx
441 .erase_and_anonymize_regions(ty::GenericArgs::identity_for_item(
442 self.tcx,
443 impl_def_id,
444 ))
445 .as_slice()
446 {
447 (
448 ty::TypingEnv::post_analysis(self.tcx, impl_def_id),
449 self_ty.instantiate_identity().skip_norm_wip(),
450 impl_trait_ref
451 .map(|impl_trait_ref| impl_trait_ref.instantiate_identity().skip_norm_wip()),
452 )
453 } else {
454 if !!args.has_non_region_param() {
{
::core::panicking::panic_fmt(format_args!("should not be mangling partially substituted polymorphic instance: {0:?} {1:?}",
impl_def_id, args));
}
};assert!(
455 !args.has_non_region_param(),
456 "should not be mangling partially substituted \
457 polymorphic instance: {impl_def_id:?} {args:?}"
458 );
459 (
460 ty::TypingEnv::fully_monomorphized(),
461 self_ty.instantiate(self.tcx, args).skip_norm_wip(),
462 impl_trait_ref.map(|impl_trait_ref| {
463 impl_trait_ref.instantiate(self.tcx, args).skip_norm_wip()
464 }),
465 )
466 };
467
468 match &mut impl_trait_ref {
469 Some(impl_trait_ref) => {
470 {
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);
471 *impl_trait_ref = self
472 .tcx
473 .normalize_erasing_regions(typing_env, Unnormalized::new_wip(*impl_trait_ref));
474 self_ty = impl_trait_ref.self_ty();
475 }
476 None => {
477 self_ty =
478 self.tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(self_ty));
479 }
480 }
481
482 self.default_print_impl_path(impl_def_id, self_ty, impl_trait_ref)
483 }
484}
485
486impl<'tcx> PrettyPrinter<'tcx> for LegacySymbolMangler<'tcx> {
487 fn should_print_optional_region(&self, _region: ty::Region<'_>) -> bool {
488 false
489 }
490
491 fn comma_sep<T>(&mut self, mut elems: impl Iterator<Item = T>) -> Result<(), PrintError>
493 where
494 T: Print<Self>,
495 {
496 if let Some(first) = elems.next() {
497 first.print(self)?;
498 for elem in elems {
499 self.write_str(",")?;
500 elem.print(self)?;
501 }
502 }
503 Ok(())
504 }
505
506 fn generic_delimiters(
507 &mut self,
508 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
509 ) -> Result<(), PrintError> {
510 self.write_fmt(format_args!("<"))write!(self, "<")?;
511
512 let kept_within_component = mem::replace(&mut self.keep_within_component, true);
513 f(self)?;
514 self.keep_within_component = kept_within_component;
515
516 self.write_fmt(format_args!(">"))write!(self, ">")?;
517
518 Ok(())
519 }
520}
521
522impl fmt::Write for LegacySymbolMangler<'_> {
523 fn write_str(&mut self, s: &str) -> fmt::Result {
524 for c in s.chars() {
531 if self.path.temp_buf.is_empty() {
532 match c {
533 'a'..='z' | 'A'..='Z' | '_' => {}
534 _ => {
535 self.path.temp_buf.push('_');
537 }
538 }
539 }
540 match c {
541 '@' => self.path.temp_buf.push_str("$SP$"),
543 '*' => self.path.temp_buf.push_str("$BP$"),
544 '&' => self.path.temp_buf.push_str("$RF$"),
545 '<' => self.path.temp_buf.push_str("$LT$"),
546 '>' => self.path.temp_buf.push_str("$GT$"),
547 '(' => self.path.temp_buf.push_str("$LP$"),
548 ')' => self.path.temp_buf.push_str("$RP$"),
549 ',' => self.path.temp_buf.push_str("$C$"),
550
551 '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => {
552 self.path.temp_buf.push('$')
554 }
555
556 '-' | ':' => self.path.temp_buf.push('.'),
559
560 'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"),
562
563 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),
565
566 _ => {
567 self.path.temp_buf.push('$');
568 for c in c.escape_unicode().skip(1) {
569 match c {
570 '{' => {}
571 '}' => self.path.temp_buf.push('$'),
572 c => self.path.temp_buf.push(c),
573 }
574 }
575 }
576 }
577 }
578
579 Ok(())
580 }
581}