Skip to main content

rustc_symbol_mangling/
v0.rs

1use std::fmt::Write;
2use std::hash::Hasher;
3use std::iter;
4use std::ops::Range;
5
6use rustc_abi::{ExternAbi, Integer};
7use rustc_data_structures::base_n::ToBaseN;
8use rustc_data_structures::either::Either;
9use rustc_data_structures::fx::FxHashMap;
10use rustc_data_structures::intern::Interned;
11use rustc_data_structures::stable_hash::StableHasher;
12use rustc_hashes::Hash64;
13use rustc_hir as hir;
14use rustc_hir::def::CtorKind;
15use rustc_hir::def_id::{CrateNum, DefId};
16use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
17use rustc_middle::ty::layout::IntegerExt;
18use rustc_middle::ty::print::{Print, PrintError, Printer};
19use rustc_middle::ty::{
20    self, FloatTy, GenericArg, GenericArgKind, Instance, IntTy, ReifyReason, Ty, TyCtxt,
21    TypeVisitable, TypeVisitableExt, UintTy, Unnormalized,
22};
23use rustc_span::{bug, sym};
24
25pub(super) fn mangle<'tcx>(
26    tcx: TyCtxt<'tcx>,
27    instance: Instance<'tcx>,
28    instantiating_crate: Option<CrateNum>,
29    is_exportable: bool,
30) -> String {
31    let def_id = instance.def_id();
32    // FIXME(eddyb) this should ideally not be needed.
33    let args = tcx.normalize_erasing_regions(
34        ty::TypingEnv::fully_monomorphized(),
35        Unnormalized::new_wip(instance.args),
36    );
37
38    let prefix = "_R";
39    let mut p: V0SymbolMangler<'_> = V0SymbolMangler {
40        tcx,
41        start_offset: prefix.len(),
42        is_exportable,
43        paths: FxHashMap::default(),
44        types: FxHashMap::default(),
45        consts: FxHashMap::default(),
46        binders: ::alloc::vec::Vec::new()vec![],
47        out: String::from(prefix),
48    };
49
50    // Append `::{shim:...#0}` to shims that can coexist with a non-shim instance.
51    let shim_kind = match instance.def {
52        ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(_)) => Some("tls"),
53        ty::InstanceKind::Shim(ty::ShimKind::VTable(_)) => Some("vtable"),
54        ty::InstanceKind::Shim(ty::ShimKind::Reify(_, None)) => Some("reify"),
55        ty::InstanceKind::Shim(ty::ShimKind::Reify(_, Some(ReifyReason::FnPtr))) => {
56            Some("reify_fnptr")
57        }
58        ty::InstanceKind::Shim(ty::ShimKind::Reify(_, Some(ReifyReason::Vtable))) => {
59            Some("reify_vtable")
60        }
61
62        // FIXME(async_closures): This shouldn't be needed when we fix
63        // `Instance::ty`/`Instance::def_id`.
64        ty::InstanceKind::Shim(ty::ShimKind::ConstructCoroutineInClosure {
65            receiver_by_ref: true,
66            ..
67        }) => Some("by_move"),
68        ty::InstanceKind::Shim(ty::ShimKind::ConstructCoroutineInClosure {
69            receiver_by_ref: false,
70            ..
71        }) => Some("by_ref"),
72        ty::InstanceKind::Shim(ty::ShimKind::FutureDropPoll(_, _, _)) => Some("drop"),
73        _ => None,
74    };
75
76    if let ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlue(_, ty)) = instance.def {
77        let ty::Coroutine(_, cor_args) = ty.kind() else {
78            ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller());bug!();
79        };
80        let drop_ty = cor_args.first().unwrap().expect_ty();
81        p.print_def_path(def_id, tcx.mk_args(&[GenericArg::from(drop_ty)])).unwrap()
82    } else if let Some(shim_kind) = shim_kind {
83        p.path_append_ns(|p| p.print_def_path(def_id, args), 'S', 0, shim_kind).unwrap()
84    } else {
85        p.print_def_path(def_id, args).unwrap()
86    };
87    if let Some(instantiating_crate) = instantiating_crate {
88        p.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap();
89    }
90    std::mem::take(&mut p.out)
91}
92
93pub fn mangle_cgu<'tcx>(tcx: TyCtxt<'tcx>, krate: CrateNum, cgu_name: Either<u64, &str>) -> String {
94    let prefix = "_R";
95    let mut p: V0SymbolMangler<'_> = V0SymbolMangler {
96        tcx,
97        start_offset: prefix.len(),
98        is_exportable: false,
99        paths: FxHashMap::default(),
100        types: FxHashMap::default(),
101        consts: FxHashMap::default(),
102        binders: ::alloc::vec::Vec::new()vec![],
103        out: String::from(prefix),
104    };
105
106    match cgu_name {
107        Either::Left(cgu_index) => {
108            // If we have a CGU index, we can easily encode this with the shim mechanism.
109            p.path_append_ns(|p| p.print_def_path(krate.as_def_id(), &[]), 'S', cgu_index, "cgu")
110                .unwrap();
111        }
112        Either::Right(name) => {
113            // In incremental compilation we just have a name and no index. Encode this as a str-typed generic argument to cgu shim for now.
114            p.out.push('I');
115            p.path_append_ns(|p| p.print_def_path(krate.as_def_id(), &[]), 'S', 0, "cgu").unwrap();
116            p.push("KRe");
117
118            for byte in name.as_bytes() {
119                let _ = p.out.write_fmt(format_args!("{0:02x}", byte))write!(p.out, "{byte:02x}");
120            }
121
122            p.push("_E");
123        }
124    }
125
126    std::mem::take(&mut p.out)
127}
128
129pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> String {
130    match item_name {
131        // rust_eh_personality must not be renamed as LLVM hard-codes the name
132        "rust_eh_personality" => return item_name.to_owned(),
133        // Apple availability symbols need to not be mangled to be usable by
134        // C/Objective-C code.
135        "__isPlatformVersionAtLeast" | "__isOSVersionAtLeast" => return item_name.to_owned(),
136        _ => {}
137    }
138
139    let prefix = "_R";
140    let mut p: V0SymbolMangler<'_> = V0SymbolMangler {
141        tcx,
142        start_offset: prefix.len(),
143        is_exportable: false,
144        paths: FxHashMap::default(),
145        types: FxHashMap::default(),
146        consts: FxHashMap::default(),
147        binders: ::alloc::vec::Vec::new()vec![],
148        out: String::from(prefix),
149    };
150
151    p.path_append_ns(
152        |p| {
153            p.push("C");
154            p.push_disambiguator({
155                let mut hasher = StableHasher::new();
156                // Incorporate the rustc version to ensure #[rustc_std_internal_symbol] functions
157                // get a different symbol name depending on the rustc version.
158                //
159                // RUSTC_FORCE_RUSTC_VERSION is ignored here as otherwise different we would get an
160                // abi incompatibility with the standard library.
161                hasher.write(tcx.sess.cfg_version.as_bytes());
162
163                let hash: Hash64 = hasher.finish();
164                hash.as_u64()
165            });
166            p.push_ident("__rustc");
167            Ok(())
168        },
169        'v',
170        0,
171        item_name,
172    )
173    .unwrap();
174
175    std::mem::take(&mut p.out)
176}
177
178pub(super) fn mangle_typeid_for_trait_ref<'tcx>(
179    tcx: TyCtxt<'tcx>,
180    trait_ref: ty::ExistentialTraitRef<'tcx>,
181) -> String {
182    // FIXME(flip1995): See comment in `mangle_typeid_for_fnabi`.
183    let mut p = V0SymbolMangler {
184        tcx,
185        start_offset: 0,
186        is_exportable: false,
187        paths: FxHashMap::default(),
188        types: FxHashMap::default(),
189        consts: FxHashMap::default(),
190        binders: ::alloc::vec::Vec::new()vec![],
191        out: String::new(),
192    };
193    p.print_def_path(trait_ref.def_id, &[]).unwrap();
194    std::mem::take(&mut p.out)
195}
196
197struct BinderLevel {
198    /// The range of distances from the root of what's
199    /// being printed, to the lifetimes in a binder.
200    /// Specifically, a `BrAnon` lifetime has depth
201    /// `lifetime_depths.start + index`, going away from the
202    /// the root and towards its use site, as the var index increases.
203    /// This is used to flatten rustc's pairing of `BrAnon`
204    /// (intra-binder disambiguation) with a `DebruijnIndex`
205    /// (binder addressing), to "true" de Bruijn indices,
206    /// by subtracting the depth of a certain lifetime, from
207    /// the innermost depth at its use site.
208    lifetime_depths: Range<u32>,
209}
210
211struct V0SymbolMangler<'tcx> {
212    tcx: TyCtxt<'tcx>,
213    binders: Vec<BinderLevel>,
214    out: String,
215    is_exportable: bool,
216
217    /// The length of the prefix in `out` (e.g. 2 for `_R`).
218    start_offset: usize,
219    /// The values are start positions in `out`, in bytes.
220    paths: FxHashMap<(DefId, &'tcx [GenericArg<'tcx>]), usize>,
221    types: FxHashMap<Ty<'tcx>, usize>,
222    consts: FxHashMap<ty::Const<'tcx>, usize>,
223}
224
225impl<'tcx> V0SymbolMangler<'tcx> {
226    fn push(&mut self, s: &str) {
227        self.out.push_str(s);
228    }
229
230    /// Push a `_`-terminated base 62 integer, using the format
231    /// specified in the RFC as `<base-62-number>`, that is:
232    /// * `x = 0` is encoded as just the `"_"` terminator
233    /// * `x > 0` is encoded as `x - 1` in base 62, followed by `"_"`,
234    ///   e.g. `1` becomes `"0_"`, `62` becomes `"Z_"`, etc.
235    fn push_integer_62(&mut self, x: u64) {
236        push_integer_62(x, &mut self.out)
237    }
238
239    /// Push a `tag`-prefixed base 62 integer, when larger than `0`, that is:
240    /// * `x = 0` is encoded as `""` (nothing)
241    /// * `x > 0` is encoded as the `tag` followed by `push_integer_62(x - 1)`
242    ///   e.g. `1` becomes `tag + "_"`, `2` becomes `tag + "0_"`, etc.
243    fn push_opt_integer_62(&mut self, tag: &str, x: u64) {
244        if let Some(x) = x.checked_sub(1) {
245            self.push(tag);
246            self.push_integer_62(x);
247        }
248    }
249
250    fn push_disambiguator(&mut self, dis: u64) {
251        self.push_opt_integer_62("s", dis);
252    }
253
254    fn push_ident(&mut self, ident: &str) {
255        push_ident(ident, &mut self.out)
256    }
257
258    fn path_append_ns(
259        &mut self,
260        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
261        ns: char,
262        disambiguator: u64,
263        name: &str,
264    ) -> Result<(), PrintError> {
265        self.push("N");
266        self.out.push(ns);
267        print_prefix(self)?;
268        self.push_disambiguator(disambiguator);
269        self.push_ident(name);
270        Ok(())
271    }
272
273    fn print_backref(&mut self, i: usize) -> Result<(), PrintError> {
274        self.push("B");
275        self.push_integer_62((i - self.start_offset) as u64);
276        Ok(())
277    }
278
279    fn wrap_binder<T>(
280        &mut self,
281        value: &ty::Binder<'tcx, T>,
282        print_value: impl FnOnce(&mut Self, &T) -> Result<(), PrintError>,
283    ) -> Result<(), PrintError>
284    where
285        T: TypeVisitable<TyCtxt<'tcx>>,
286    {
287        let mut lifetime_depths =
288            self.binders.last().map(|b| b.lifetime_depths.end).map_or(0..0, |i| i..i);
289
290        // FIXME(non-lifetime-binders): What to do here?
291        let lifetimes = value
292            .bound_vars()
293            .iter()
294            .filter(|var| #[allow(non_exhaustive_omitted_patterns)] match var {
    ty::BoundVariableKind::Region(..) => true,
    _ => false,
}matches!(var, ty::BoundVariableKind::Region(..)))
295            .count() as u32;
296
297        self.push_opt_integer_62("G", lifetimes as u64);
298        lifetime_depths.end += lifetimes;
299
300        self.binders.push(BinderLevel { lifetime_depths });
301        print_value(self, value.as_ref().skip_binder())?;
302        self.binders.pop();
303
304        Ok(())
305    }
306
307    fn print_pat(&mut self, pat: ty::Pattern<'tcx>) -> Result<(), std::fmt::Error> {
308        Ok(match *pat {
309            ty::PatternKind::Range { start, end } => {
310                self.push("R");
311                self.print_const(start)?;
312                self.print_const(end)?;
313            }
314            ty::PatternKind::NotNull => {
315                self.tcx.types.unit.print(self)?;
316            }
317            ty::PatternKind::Or(patterns) => {
318                self.push("O");
319                for pat in patterns {
320                    self.print_pat(pat)?;
321                }
322                self.push("E");
323            }
324        })
325    }
326}
327
328impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> {
329    fn tcx(&self) -> TyCtxt<'tcx> {
330        self.tcx
331    }
332
333    fn print_def_path(
334        &mut self,
335        def_id: DefId,
336        args: &'tcx [GenericArg<'tcx>],
337    ) -> Result<(), PrintError> {
338        if let Some(&i) = self.paths.get(&(def_id, args)) {
339            return self.print_backref(i);
340        }
341        let start = self.out.len();
342
343        self.default_print_def_path(def_id, args)?;
344
345        // Only cache paths that do not refer to an enclosing
346        // binder (which would change depending on context).
347        if !args.iter().any(|k| k.has_escaping_bound_vars()) {
348            self.paths.insert((def_id, args), start);
349        }
350        Ok(())
351    }
352
353    fn print_impl_path(
354        &mut self,
355        impl_def_id: DefId,
356        args: &'tcx [GenericArg<'tcx>],
357    ) -> Result<(), PrintError> {
358        let key = self.tcx.def_key(impl_def_id);
359        let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
360
361        let self_ty = self.tcx.type_of(impl_def_id);
362        let impl_trait_ref = self.tcx.impl_opt_trait_ref(impl_def_id);
363        let generics = self.tcx.generics_of(impl_def_id);
364        // We have two cases to worry about here:
365        // 1. We're printing a nested item inside of an impl item, like an inner
366        // function inside of a method. Due to the way that def path printing works,
367        // we'll render this something like `<Ty as Trait>::method::inner_fn`
368        // but we have no substs for this impl since it's not really inheriting
369        // generics from the outer item. We need to use the identity substs, and
370        // to normalize we need to use the correct param-env too.
371        // 2. We're mangling an item with identity substs. This seems to only happen
372        // when generating coverage, since we try to generate coverage for unused
373        // items too, and if something isn't monomorphized then we necessarily don't
374        // have anything to substitute the instance with.
375        // NOTE: We don't support mangling partially substituted but still polymorphic
376        // instances, like `impl<A> Tr<A> for ()` where `A` is substituted w/ `(T,)`.
377        let (typing_env, mut self_ty, mut impl_trait_ref) = if generics.count() > args.len()
378            || &args[..generics.count()]
379                == self
380                    .tcx
381                    .erase_and_anonymize_regions(ty::GenericArgs::identity_for_item(
382                        self.tcx,
383                        impl_def_id,
384                    ))
385                    .as_slice()
386        {
387            (
388                ty::TypingEnv::post_analysis(self.tcx, impl_def_id),
389                self_ty.instantiate_identity().skip_norm_wip(),
390                impl_trait_ref
391                    .map(|impl_trait_ref| impl_trait_ref.instantiate_identity().skip_norm_wip()),
392            )
393        } else {
394            if !(!args.has_non_region_param() && !args.has_free_regions()) {
    {
        ::core::panicking::panic_fmt(format_args!("should not be mangling partially substituted polymorphic instance: {0:?} {1:?}",
                impl_def_id, args));
    }
};assert!(
395                !args.has_non_region_param() && !args.has_free_regions(),
396                "should not be mangling partially substituted \
397                polymorphic instance: {impl_def_id:?} {args:?}"
398            );
399            (
400                ty::TypingEnv::fully_monomorphized(),
401                self_ty.instantiate(self.tcx, args).skip_norm_wip(),
402                impl_trait_ref.map(|impl_trait_ref| {
403                    impl_trait_ref.instantiate(self.tcx, args).skip_norm_wip()
404                }),
405            )
406        };
407
408        match &mut impl_trait_ref {
409            Some(impl_trait_ref) => {
410                {
    match (&impl_trait_ref.self_ty(), &self_ty) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(impl_trait_ref.self_ty(), self_ty);
411                *impl_trait_ref = self
412                    .tcx
413                    .normalize_erasing_regions(typing_env, Unnormalized::new_wip(*impl_trait_ref));
414                self_ty = impl_trait_ref.self_ty();
415            }
416            None => {
417                self_ty =
418                    self.tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(self_ty));
419            }
420        }
421
422        self.push(match impl_trait_ref {
423            Some(_) => "X",
424            None => "M",
425        });
426
427        // Encode impl generic params if the generic parameters contain non-region parameters
428        // and this isn't an inherent impl.
429        if impl_trait_ref.is_some() && args.iter().any(|a| a.has_non_region_param()) {
430            self.print_path_with_generic_args(
431                |this| {
432                    this.path_append_ns(
433                        |p| p.print_def_path(parent_def_id, &[]),
434                        'I',
435                        key.disambiguated_data.disambiguator as u64,
436                        "",
437                    )
438                },
439                args,
440            )?;
441        } else {
442            let exported_impl_order = self.tcx.stable_order_of_exportable_impls(impl_def_id.krate);
443            let disambiguator = match self.is_exportable {
444                true => exported_impl_order[&impl_def_id] as u64,
445                false => {
446                    exported_impl_order.len() as u64 + key.disambiguated_data.disambiguator as u64
447                }
448            };
449            self.push_disambiguator(disambiguator);
450            self.print_def_path(parent_def_id, &[])?;
451        }
452
453        self_ty.print(self)?;
454
455        if let Some(trait_ref) = impl_trait_ref {
456            self.print_def_path(trait_ref.def_id, trait_ref.args)?;
457        }
458
459        Ok(())
460    }
461
462    fn print_region(&mut self, region: ty::Region<'_>) -> Result<(), PrintError> {
463        let i = match region.kind() {
464            // Erased lifetimes use the index 0, for a
465            // shorter mangling of `L_`.
466            ty::ReErased => 0,
467
468            // Bound lifetimes use indices starting at 1,
469            // see `BinderLevel` for more details.
470            ty::ReBound(
471                ty::BoundVarIndexKind::Bound(debruijn),
472                ty::BoundRegion { var, kind: ty::BoundRegionKind::Anon },
473            ) => {
474                let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
475                let depth = binder.lifetime_depths.start + var.as_u32();
476
477                1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
478            }
479
480            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("symbol_names: non-erased region `{0:?}`", region),
    Location::caller())bug!("symbol_names: non-erased region `{:?}`", region),
481        };
482        self.push("L");
483        self.push_integer_62(i as u64);
484        Ok(())
485    }
486
487    fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
488        // Basic types, never cached (single-character).
489        let basic_type = match ty.kind() {
490            ty::Bool => "b",
491            ty::Char => "c",
492            ty::Str => "e",
493            ty::Int(IntTy::I8) => "a",
494            ty::Int(IntTy::I16) => "s",
495            ty::Int(IntTy::I32) => "l",
496            ty::Int(IntTy::I64) => "x",
497            ty::Int(IntTy::I128) => "n",
498            ty::Int(IntTy::Isize) => "i",
499            ty::Uint(UintTy::U8) => "h",
500            ty::Uint(UintTy::U16) => "t",
501            ty::Uint(UintTy::U32) => "m",
502            ty::Uint(UintTy::U64) => "y",
503            ty::Uint(UintTy::U128) => "o",
504            ty::Uint(UintTy::Usize) => "j",
505            ty::Float(FloatTy::F16) => "C3f16",
506            ty::Float(FloatTy::F32) => "f",
507            ty::Float(FloatTy::F64) => "d",
508            ty::Float(FloatTy::F128) => "C4f128",
509            ty::Never => "z",
510
511            ty::Tuple(_) if ty.is_unit() => "u",
512
513            // Should only be encountered within the identity-substituted
514            // impl header of an item nested within an impl item.
515            ty::Param(_) => "p",
516
517            _ => "",
518        };
519        if !basic_type.is_empty() {
520            self.push(basic_type);
521            return Ok(());
522        }
523
524        if let Some(&i) = self.types.get(&ty) {
525            return self.print_backref(i);
526        }
527        let start = self.out.len();
528
529        match *ty.kind() {
530            // Basic types, handled above.
531            ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
532                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
533            }
534            ty::Tuple(_) if ty.is_unit() => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
535            ty::Param(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
536
537            ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
538
539            ty::Ref(r, ty, mutbl) => {
540                self.push(match mutbl {
541                    hir::Mutability::Not => "R",
542                    hir::Mutability::Mut => "Q",
543                });
544                if !r.is_erased() {
545                    r.print(self)?;
546                }
547                ty.print(self)?;
548            }
549
550            ty::RawPtr(ty, mutbl) => {
551                self.push(match mutbl {
552                    hir::Mutability::Not => "P",
553                    hir::Mutability::Mut => "O",
554                });
555                ty.print(self)?;
556            }
557
558            ty::Pat(ty, pat) => {
559                self.push("W");
560                ty.print(self)?;
561                self.print_pat(pat)?;
562            }
563
564            ty::Array(ty, len) => {
565                self.push("A");
566                ty.print(self)?;
567                self.print_const(len)?;
568            }
569            ty::Slice(ty) => {
570                self.push("S");
571                ty.print(self)?;
572            }
573
574            ty::Tuple(tys) => {
575                self.push("T");
576                for ty in tys.iter() {
577                    ty.print(self)?;
578                }
579                self.push("E");
580            }
581
582            // Mangle all nominal types as paths.
583            ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), args)
584            | ty::Closure(def_id, args)
585            | ty::CoroutineClosure(def_id, args)
586            | ty::Coroutine(def_id, args) => {
587                self.print_def_path(def_id, args)?;
588            }
589
590            ty::FnDef(def_id, args) => {
591                self.print_def_path(def_id, args.no_bound_vars().unwrap())?
592            }
593
594            // We may still encounter projections here due to the printing
595            // logic sometimes passing identity-substituted impl headers.
596            ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. }) => {
597                self.print_def_path(def_id, args)?;
598            }
599
600            ty::Foreign(def_id) => {
601                self.print_def_path(def_id, &[])?;
602            }
603
604            ty::FnPtr(sig_tys, hdr) => {
605                let splatted_arg_index = hdr.splatted().map(usize::from);
606                let sig = sig_tys.with(hdr);
607                self.push("F");
608                self.wrap_binder(&sig, |p, sig| {
609                    if sig.safety().is_unsafe() {
610                        p.push("U");
611                    }
612                    match sig.abi() {
613                        ExternAbi::Rust => {}
614                        ExternAbi::C { unwind: false } => p.push("KC"),
615                        abi => {
616                            p.push("K");
617                            let name = abi.as_str();
618                            if name.contains('-') {
619                                p.push_ident(&name.replace('-', "_"));
620                            } else {
621                                p.push_ident(name);
622                            }
623                        }
624                    }
625                    for (i, &ty) in sig.inputs().iter().enumerate() {
626                        if splatted_arg_index == Some(i) {
627                            // The splat feature is unstable and its mangling is subject to change
628                            // FIXME(splat):
629                            // - for efficiency we might want to use a letter that can't occur in any type, rather than
630                            //   taking an unused letter
631                            // - splat isn't implemented for legacy mangling
632                            p.push("w");
633                        }
634                        ty.print(p)?;
635                    }
636                    if sig.c_variadic() {
637                        p.push("v");
638                    }
639                    p.push("E");
640                    sig.output().print(p)
641                })?;
642            }
643
644            // FIXME(unsafe_binder):
645            ty::UnsafeBinder(..) => ::core::panicking::panic("not implemented")unimplemented!(),
646
647            ty::Dynamic(predicates, r) => {
648                self.push("D");
649                self.print_dyn_existential(predicates)?;
650                r.print(self)?;
651            }
652
653            ty::Alias(..) => ::rustc_span::macros::bug_impl(None,
    format_args!("symbol_names: unexpected alias"), Location::caller())bug!("symbol_names: unexpected alias"),
654            ty::CoroutineWitness(..) => ::rustc_span::macros::bug_impl(None,
    format_args!("symbol_names: unexpected `CoroutineWitness`"),
    Location::caller())bug!("symbol_names: unexpected `CoroutineWitness`"),
655        }
656
657        // Only cache types that do not refer to an enclosing
658        // binder (which would change depending on context).
659        if !ty.has_escaping_bound_vars() {
660            self.types.insert(ty, start);
661        }
662        Ok(())
663    }
664
665    fn print_dyn_existential(
666        &mut self,
667        predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
668    ) -> Result<(), PrintError> {
669        // Okay, so this is a bit tricky. Imagine we have a trait object like
670        // `dyn for<'a> Foo<'a, Bar = &'a ()>`. When we mangle this, the
671        // output looks really close to the syntax, where the `Bar = &'a ()` bit
672        // is under the same binders (`['a]`) as the `Foo<'a>` bit. However, we
673        // actually desugar these into two separate `ExistentialPredicate`s. We
674        // can't enter/exit the "binder scope" twice though, because then we
675        // would mangle the binders twice. (Also, side note, we merging these
676        // two is kind of difficult, because of potential HRTBs in the Projection
677        // predicate.)
678        //
679        // Also worth mentioning: imagine that we instead had
680        // `dyn for<'a> Foo<'a, Bar = &'a ()> + Send`. In this case, `Send` is
681        // under the same binders as `Foo`. Currently, this doesn't matter,
682        // because only *auto traits* are allowed other than the principal trait
683        // and all auto traits don't have any generics. Two things could
684        // make this not an "okay" mangling:
685        // 1) Instead of mangling only *used*
686        // bound vars, we want to mangle *all* bound vars (`for<'b> Send` is a
687        // valid trait predicate);
688        // 2) We allow multiple "principal" traits in the future, or at least
689        // allow in any form another trait predicate that can take generics.
690        //
691        // Here we assume that predicates have the following structure:
692        // [<Trait> [{<Projection>}]] [{<Auto>}]
693        // Since any predicates after the first one shouldn't change the binders,
694        // just put them all in the binders of the first.
695        self.wrap_binder(&predicates[0], |p, _| {
696            for predicate in predicates.iter() {
697                // It would be nice to be able to validate bound vars here, but
698                // projections can actually include bound vars from super traits
699                // because of HRTBs (only in the `Self` type). Also, auto traits
700                // could have different bound vars *anyways*.
701                match predicate.as_ref().skip_binder() {
702                    ty::ExistentialPredicate::Trait(trait_ref) => {
703                        // Dummy Self is safe to use as it can't appear in generic param defaults
704                        // which is important later on for correctly eliding generic args that
705                        // coincide with their default.
706                        let trait_ref =
707                            trait_ref.with_self_ty(p.tcx, p.tcx.types.trait_object_dummy_self);
708                        p.print_def_path(trait_ref.def_id, trait_ref.args)?;
709                    }
710                    ty::ExistentialPredicate::Projection(projection) => {
711                        let name = p.tcx.associated_item(projection.def_id).name();
712                        p.push("p");
713                        p.push_ident(name.as_str());
714                        match projection.term.kind() {
715                            ty::TermKind::Ty(ty) => ty.print(p),
716                            ty::TermKind::Const(c) => {
717                                p.push("K");
718                                c.print(p)
719                            }
720                        }?;
721                    }
722                    ty::ExistentialPredicate::AutoTrait(def_id) => {
723                        p.print_def_path(*def_id, &[])?;
724                    }
725                }
726            }
727            Ok(())
728        })?;
729
730        self.push("E");
731        Ok(())
732    }
733
734    fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
735        // We only mangle a typed value if the const can be evaluated.
736        let cv = match ct.kind() {
737            ty::ConstKind::Value(cv) => cv,
738
739            // Should only be encountered within the identity-substituted
740            // impl header of an item nested within an impl item.
741            ty::ConstKind::Param(_) => {
742                // Never cached (single-character).
743                self.push("p");
744                return Ok(());
745            }
746
747            // We may still encounter alias consts due to the printing
748            // logic sometimes passing identity-substituted impl headers.
749            ty::ConstKind::Alias(_, ty::AliasConst { kind, args, .. }) => match kind {
750                ty::AliasConstKind::Projection { def_id }
751                | ty::AliasConstKind::InherentSelf { def_id }
752                | ty::AliasConstKind::InherentImpl { def_id }
753                | ty::AliasConstKind::Free { def_id }
754                | ty::AliasConstKind::Anon { def_id } => {
755                    return self.print_def_path(def_id, args);
756                }
757            },
758
759            ty::ConstKind::Expr(_)
760            | ty::ConstKind::Infer(_)
761            | ty::ConstKind::Bound(..)
762            | ty::ConstKind::Placeholder(_)
763            | ty::ConstKind::Error(_) => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
764        };
765
766        if let Some(&i) = self.consts.get(&ct) {
767            self.print_backref(i)?;
768            return Ok(());
769        }
770
771        let ty::Value { ty: ct_ty, valtree } = cv;
772        let start = self.out.len();
773
774        match ct_ty.kind() {
775            ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Char => {
776                ct_ty.print(self)?;
777
778                let mut bits = cv
779                    .try_to_bits(self.tcx, ty::TypingEnv::fully_monomorphized())
780                    .expect("expected const to be monomorphic");
781
782                // Negative integer values are mangled using `n` as a "sign prefix".
783                if let ty::Int(ity) = ct_ty.kind() {
784                    let val =
785                        Integer::from_int_ty(&self.tcx, *ity).size().sign_extend(bits) as i128;
786                    if val < 0 {
787                        self.push("n");
788                    }
789                    bits = val.unsigned_abs();
790                }
791
792                let _ = self.out.write_fmt(format_args!("{0:x}_", bits))write!(self.out, "{bits:x}_");
793            }
794
795            // Handle `str` as partial support for unsized constants
796            ty::Str => {
797                let tcx = self.tcx();
798                // HACK(jaic1): hide the `str` type behind a reference
799                // for the following transformation from valtree to raw bytes
800                let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, ct_ty);
801                let cv = ty::Value { ty: ref_ty, valtree };
802                let slice = cv.try_to_raw_bytes(tcx).unwrap_or_else(|| {
803                    ::rustc_span::macros::bug_impl(None,
    format_args!("expected to get raw bytes from valtree {0:?} for type {1}",
        valtree, ct_ty), Location::caller())bug!("expected to get raw bytes from valtree {:?} for type {:}", valtree, ct_ty)
804                });
805                let s = std::str::from_utf8(slice).expect("non utf8 str from MIR interpreter");
806
807                // "e" for str as a basic type
808                self.push("e");
809
810                // FIXME(eddyb) use a specialized hex-encoding loop.
811                for byte in s.bytes() {
812                    let _ = self.out.write_fmt(format_args!("{0:02x}", byte))write!(self.out, "{byte:02x}");
813                }
814
815                self.push("_");
816            }
817
818            // FIXME(valtrees): Remove the special case for `str`
819            // here and fully support unsized constants.
820            ty::Ref(_, _, mutbl) => {
821                self.push(match mutbl {
822                    hir::Mutability::Not => "R",
823                    hir::Mutability::Mut => "Q",
824                });
825
826                let pointee_ty =
827                    ct_ty.builtin_deref(true).expect("tried to dereference on non-ptr type");
828                let dereferenced_const = ty::Const::new_value(self.tcx, valtree, pointee_ty);
829                dereferenced_const.print(self)?;
830            }
831
832            ty::Array(..) | ty::Tuple(..) | ty::Slice(_) => {
833                let fields = cv.to_branch().iter().copied();
834
835                let print_field_list = |this: &mut Self| {
836                    for field in fields.clone() {
837                        field.print(this)?;
838                    }
839                    this.push("E");
840                    Ok(())
841                };
842
843                match *ct_ty.kind() {
844                    ty::Array(..) | ty::Slice(_) => {
845                        self.push("A");
846                        print_field_list(self)?;
847                    }
848                    ty::Tuple(..) => {
849                        self.push("T");
850                        print_field_list(self)?;
851                    }
852                    _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
853                }
854            }
855            ty::Adt(def, args) => {
856                let contents = cv.destructure_adt_const();
857                let fields = contents.fields.iter().copied();
858
859                let print_field_list = |this: &mut Self| {
860                    for field in fields.clone() {
861                        field.print(this)?;
862                    }
863                    this.push("E");
864                    Ok(())
865                };
866
867                let variant_idx = contents.variant;
868                let variant_def = &def.variant(variant_idx);
869
870                self.push("V");
871                self.print_def_path(variant_def.def_id, args)?;
872
873                match variant_def.ctor_kind() {
874                    Some(CtorKind::Const) => {
875                        self.push("U");
876                    }
877                    Some(CtorKind::Fn) => {
878                        self.push("T");
879                        print_field_list(self)?;
880                    }
881                    None => {
882                        self.push("S");
883                        for (field_def, field) in iter::zip(&variant_def.fields, fields) {
884                            // HACK(eddyb) this mimics `print_path_with_simple`,
885                            // instead of simply using `field_def.ident`,
886                            // just to be able to handle disambiguators.
887                            let disambiguated_field =
888                                self.tcx.def_key(field_def.did).disambiguated_data;
889                            let field_name = disambiguated_field.data.get_opt_name();
890                            self.push_disambiguator(disambiguated_field.disambiguator as u64);
891                            self.push_ident(field_name.unwrap().as_str());
892
893                            field.print(self)?;
894                        }
895                        self.push("E");
896                    }
897                }
898            }
899            _ => {
900                ::rustc_span::macros::bug_impl(None,
    format_args!("symbol_names: unsupported constant of type `{0}` ({1:?})",
        ct_ty, ct), Location::caller());bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct_ty, ct);
901            }
902        }
903
904        // Only cache consts that do not refer to an enclosing
905        // binder (which would change depending on context).
906        if !ct.has_escaping_bound_vars() {
907            self.consts.insert(ct, start);
908        }
909        Ok(())
910    }
911
912    fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
913        self.push("C");
914        if !self.is_exportable {
915            let stable_crate_id = self.tcx.stable_crate_id(cnum);
916            self.push_disambiguator(stable_crate_id.as_u64());
917        }
918        let name = self.tcx.crate_name(cnum);
919        self.push_ident(name.as_str());
920        Ok(())
921    }
922
923    fn print_path_with_qualified(
924        &mut self,
925        self_ty: Ty<'tcx>,
926        trait_ref: Option<ty::TraitRef<'tcx>>,
927    ) -> Result<(), PrintError> {
928        if !trait_ref.is_some() {
    ::core::panicking::panic("assertion failed: trait_ref.is_some()")
};assert!(trait_ref.is_some());
929        let trait_ref = trait_ref.unwrap();
930
931        self.push("Y");
932        self_ty.print(self)?;
933        self.print_def_path(trait_ref.def_id, trait_ref.args)
934    }
935
936    fn print_path_with_impl(
937        &mut self,
938        _: impl FnOnce(&mut Self) -> Result<(), PrintError>,
939        _: Ty<'tcx>,
940        _: Option<ty::TraitRef<'tcx>>,
941    ) -> Result<(), PrintError> {
942        // Inlined into `print_impl_path`
943        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
944    }
945
946    fn print_path_with_simple(
947        &mut self,
948        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
949        disambiguated_data: &DisambiguatedDefPathData,
950    ) -> Result<(), PrintError> {
951        let ns = match disambiguated_data.data {
952            // Extern block segments can be skipped, names from extern blocks
953            // are effectively living in their parent modules.
954            DefPathData::ForeignMod => return print_prefix(self),
955
956            // Uppercase categories are more stable than lowercase ones.
957            DefPathData::TypeNs(_) => 't',
958            DefPathData::ValueNs(_) => 'v',
959            DefPathData::Closure => 'C',
960            DefPathData::Ctor => 'c',
961            DefPathData::AnonConst => 'K',
962            DefPathData::OpaqueTy => 'i',
963            DefPathData::SyntheticCoroutineBody => 's',
964            DefPathData::NestedStatic => 'n',
965            DefPathData::GlobalAsm => 'a',
966
967            // These should never show up as `print_path_with_simple` arguments.
968            DefPathData::CrateRoot
969            | DefPathData::Use
970            | DefPathData::Impl
971            | DefPathData::MacroNs(_)
972            | DefPathData::LifetimeNs(_)
973            | DefPathData::OpaqueLifetime(_)
974            | DefPathData::AnonAssocTy(..)
975            | DefPathData::TestBinderConstraints => {
976                ::rustc_span::macros::bug_impl(None,
    format_args!("symbol_names: unexpected DefPathData: {0:?}",
        disambiguated_data.data), Location::caller())bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
977            }
978        };
979
980        let name = disambiguated_data.data.get_opt_name();
981
982        self.path_append_ns(
983            print_prefix,
984            ns,
985            disambiguated_data.disambiguator as u64,
986            name.unwrap_or(sym::empty).as_str(),
987        )
988    }
989
990    fn print_path_with_generic_args(
991        &mut self,
992        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
993        args: &[GenericArg<'tcx>],
994    ) -> Result<(), PrintError> {
995        // Don't print any regions if they're all erased.
996        let print_regions = args.iter().any(|arg| match arg.kind() {
997            GenericArgKind::Lifetime(r) => !r.is_erased(),
998            _ => false,
999        });
1000        let args = args.iter().cloned().filter(|arg| match arg.kind() {
1001            GenericArgKind::Lifetime(_) => print_regions,
1002            _ => true,
1003        });
1004
1005        if args.clone().next().is_none() {
1006            return print_prefix(self);
1007        }
1008
1009        self.push("I");
1010        print_prefix(self)?;
1011        for arg in args {
1012            match arg.kind() {
1013                GenericArgKind::Lifetime(lt) => {
1014                    lt.print(self)?;
1015                }
1016                GenericArgKind::Type(ty) => {
1017                    ty.print(self)?;
1018                }
1019                GenericArgKind::Const(c) => {
1020                    self.push("K");
1021                    c.print(self)?;
1022                }
1023            }
1024        }
1025        self.push("E");
1026
1027        Ok(())
1028    }
1029}
1030/// Push a `_`-terminated base 62 integer, using the format
1031/// specified in the RFC as `<base-62-number>`, that is:
1032/// * `x = 0` is encoded as just the `"_"` terminator
1033/// * `x > 0` is encoded as `x - 1` in base 62, followed by `"_"`,
1034///   e.g. `1` becomes `"0_"`, `62` becomes `"Z_"`, etc.
1035pub(crate) fn push_integer_62(x: u64, output: &mut String) {
1036    if let Some(x) = x.checked_sub(1) {
1037        output.push_str(&x.to_base(62));
1038    }
1039    output.push('_');
1040}
1041
1042pub(crate) fn encode_integer_62(x: u64) -> String {
1043    let mut output = String::new();
1044    push_integer_62(x, &mut output);
1045    output
1046}
1047
1048pub(crate) fn push_ident(ident: &str, output: &mut String) {
1049    let mut use_punycode = false;
1050    for b in ident.bytes() {
1051        match b {
1052            b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
1053            0x80..=0xff => use_punycode = true,
1054            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("symbol_names: bad byte {0} in ident {1:?}", b, ident),
    Location::caller())bug!("symbol_names: bad byte {} in ident {:?}", b, ident),
1055        }
1056    }
1057
1058    let punycode_string;
1059    let ident = if use_punycode {
1060        output.push('u');
1061
1062        // FIXME(eddyb) we should probably roll our own punycode implementation.
1063        let mut punycode_bytes = match punycode::encode(ident) {
1064            Ok(s) => s.into_bytes(),
1065            Err(()) => ::rustc_span::macros::bug_impl(None,
    format_args!("symbol_names: punycode encoding failed for ident {0:?}",
        ident), Location::caller())bug!("symbol_names: punycode encoding failed for ident {:?}", ident),
1066        };
1067
1068        // Replace `-` with `_`.
1069        if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
1070            *c = b'_';
1071        }
1072
1073        // FIXME(eddyb) avoid rechecking UTF-8 validity.
1074        punycode_string = String::from_utf8(punycode_bytes).unwrap();
1075        &punycode_string
1076    } else {
1077        ident
1078    };
1079
1080    let _ = output.write_fmt(format_args!("{0}", ident.len()))write!(output, "{}", ident.len());
1081
1082    // Write a separating `_` if necessary (leading digit or `_`).
1083    if let Some('_' | '0'..='9') = ident.chars().next() {
1084        output.push('_');
1085    }
1086
1087    output.push_str(ident);
1088}