Skip to main content

rustc_symbol_mangling/
legacy.rs

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    // We want to compute the "type" of this item. Unfortunately, some
25    // kinds of items (e.g., synthetic static allocations from const eval)
26    // don't have a proper implementation for the `type_of` query. So walk
27    // back up the find the closest parent that DOES have a type.
28    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                // `global_asm!` doesn't have a type.
43                instance_ty = tcx.types.unit;
44                break;
45            }
46            _ => {
47                // if we're making a symbol for something, there ought
48                // to be a value or type-def or something in there
49                // *somewhere*
50                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    // Erase regions because they may not be deterministic when hashed
63    // and should not matter anyhow.
64    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            // Add the name of the dropped type to the symbol name
76            &*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        // FIXME(async_closures): This shouldn't be needed when we fix
106        // `Instance::ty`/`Instance::def_id`.
107        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 this name will be for
128    instance: Instance<'tcx>,
129
130    // type of the item, without any generic
131    // parameters instantiated; this is
132    // included in the hash as a kind of
133    // safeguard.
134    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        // the main symbol name is not necessarily unique; hash in the
146        // compiler's internal def-path, guaranteeing each symbol has a
147        // truly unique path
148        tcx.def_path_hash(def_id).stable_hash(&mut hcx, &mut hasher);
149
150        // Include the main item-type. Note that, in this case, the
151        // assertions about `has_param` may not hold, but this item-type
152        // ought to be the same for every reference anyway.
153        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 this is a function, we hash the signature as well.
158            // This is not *strictly* needed, but it may help in some
159            // situations, see the `run-make/a-b-a-linker-guard` test.
160            if let ty::FnDef(..) = item_type.kind() {
161                item_type.fn_sig(tcx).stable_hash(hcx, &mut hasher);
162            }
163
164            // also include any type parameters (for generic items)
165            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            // We want to avoid accidental collision between different types of instances.
172            // Especially, `VTableShim`s and `ReifyShim`s may overlap with their original
173            // instances without this.
174            discriminant(&instance.def).stable_hash(hcx, &mut hasher);
175        });
176
177        // 64 bits should be enough to avoid collisions.
178        hasher.finish::<Hash64>()
179    })
180}
181
182// Follow C++ namespace-mangling style, see
183// https://en.wikipedia.org/wiki/Name_mangling for more info.
184//
185// It turns out that on macOS you can actually have arbitrary symbols in
186// function names (at least when given to LLVM), but this is not possible
187// when using unix's linker. Perhaps one day when we just use a linker from LLVM
188// we won't need to do this name mangling. The problem with name mangling is
189// that it seriously limits the available characters. For example we can't
190// have things like &T in symbol names when one would theoretically
191// want them for things like impls of traits on that type.
192//
193// To be able to work on all platforms and get *some* reasonable output, we
194// use C++ name-mangling.
195#[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"); // _Z == Begin name-sequence, N == nested
206        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        // E = end name-sequence
219        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    // When `true`, `finalize_pending_component` isn't used.
229    // This is needed when recursing into `print_path_with_qualified`,
230    // or `print_path_with_generic_args`, as any nested paths are
231    // logically within one component.
232    keep_within_component: bool,
233}
234
235// HACK(eddyb) this relies on using the `fmt` interface to get
236// `PrettyPrinter` aka pretty printing of e.g. types in paths,
237// symbol names should have their own printing machinery.
238
239impl<'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        // This might be reachable (via `pretty_print_dyn_existential`) even though
246        // `<Self As PrettyPrinter>::should_print_optional_region` returns false and
247        // `print_path_with_generic_args` filters out lifetimes. See #144994.
248        Ok(())
249    }
250
251    fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
252        match *ty.kind() {
253            // Print all nominal types as paths (unlike `pretty_print_type`).
254            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            // The `pretty_print_type` formatting of array size depends on
267            // -Zverbose-internals flag, so we cannot reuse it here.
268            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        // only print integers
308        match ct.kind() {
309            ty::ConstKind::Value(cv) if cv.ty.is_integral() => {
310                // The `pretty_print_const` formatting depends on -Zverbose-internals
311                // flag, so we cannot reuse it here.
312                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        // Similar to `pretty_print_path_with_qualified`, but for the other
336        // types that are printed as paths (see `print_type` above).
337        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                    // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
364                    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        // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
384        if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
385            return Ok(());
386        }
387
388        if self.keep_within_component {
389            // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
390            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        // We have two cases to worry about here:
425        // 1. We're printing a nested item inside of an impl item, like an inner
426        // function inside of a method. Due to the way that def path printing works,
427        // we'll render this something like `<Ty as Trait>::method::inner_fn`
428        // but we have no substs for this impl since it's not really inheriting
429        // generics from the outer item. We need to use the identity substs, and
430        // to normalize we need to use the correct param-env too.
431        // 2. We're mangling an item with identity substs. This seems to only happen
432        // when generating coverage, since we try to generate coverage for unused
433        // items too, and if something isn't monomorphized then we necessarily don't
434        // have anything to substitute the instance with.
435        // NOTE: We don't support mangling partially substituted but still polymorphic
436        // instances, like `impl<A> Tr<A> for ()` where `A` is substituted w/ `(T,)`.
437        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    // Identical to `PrettyPrinter::comma_sep` except there is no space after each comma.
492    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        // Name sanitation. LLVM will happily accept identifiers with weird names, but
525        // gas doesn't!
526        // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
527        // NVPTX assembly has more strict naming rules than gas, so additionally, dots
528        // are replaced with '$' there.
529
530        for c in s.chars() {
531            if self.path.temp_buf.is_empty() {
532                match c {
533                    'a'..='z' | 'A'..='Z' | '_' => {}
534                    _ => {
535                        // Underscore-qualify anything that didn't start as an ident.
536                        self.path.temp_buf.push('_');
537                    }
538                }
539            }
540            match c {
541                // Escape these with $ sequences
542                '@' => 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                    // NVPTX doesn't support these characters in symbol names.
553                    self.path.temp_buf.push('$')
554                }
555
556                // '.' doesn't occur in types and functions, so reuse it
557                // for ':' and '-'
558                '-' | ':' => self.path.temp_buf.push('.'),
559
560                // Avoid crashing LLVM in certain (LTO-related) situations, see #60925.
561                'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"),
562
563                // These are legal symbols
564                '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}