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