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, RegionUtilitiesExt, ReifyReason,
21    Ty, TyCtxt, 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::Closure(def_id, args)
549            | ty::CoroutineClosure(def_id, args)
550            | ty::Coroutine(def_id, args) => {
551                self.print_def_path(def_id, args)?;
552            }
553
554            ty::FnDef(def_id, args) => {
555                self.print_def_path(def_id, args.no_bound_vars().unwrap())?
556            }
557
558            // We may still encounter projections here due to the printing
559            // logic sometimes passing identity-substituted impl headers.
560            ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. }) => {
561                self.print_def_path(def_id, args)?;
562            }
563
564            ty::Foreign(def_id) => {
565                self.print_def_path(def_id, &[])?;
566            }
567
568            ty::FnPtr(sig_tys, hdr) => {
569                let splatted_arg_index = hdr.splatted().map(usize::from);
570                let sig = sig_tys.with(hdr);
571                self.push("F");
572                self.wrap_binder(&sig, |p, sig| {
573                    if sig.safety().is_unsafe() {
574                        p.push("U");
575                    }
576                    match sig.abi() {
577                        ExternAbi::Rust => {}
578                        ExternAbi::C { unwind: false } => p.push("KC"),
579                        abi => {
580                            p.push("K");
581                            let name = abi.as_str();
582                            if name.contains('-') {
583                                p.push_ident(&name.replace('-', "_"));
584                            } else {
585                                p.push_ident(name);
586                            }
587                        }
588                    }
589                    for (i, &ty) in sig.inputs().iter().enumerate() {
590                        if splatted_arg_index == Some(i) {
591                            // The splat feature is unstable and its mangling is subject to change
592                            // FIXME(splat):
593                            // - for efficiency we might want to use a letter that can't occur in any type, rather than
594                            //   taking an unused letter
595                            // - splat isn't implemented for legacy mangling
596                            p.push("w");
597                        }
598                        ty.print(p)?;
599                    }
600                    if sig.c_variadic() {
601                        p.push("v");
602                    }
603                    p.push("E");
604                    sig.output().print(p)
605                })?;
606            }
607
608            // FIXME(unsafe_binder):
609            ty::UnsafeBinder(..) => ::core::panicking::panic("not implemented")unimplemented!(),
610
611            ty::Dynamic(predicates, r) => {
612                self.push("D");
613                self.print_dyn_existential(predicates)?;
614                r.print(self)?;
615            }
616
617            ty::Alias(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("symbol_names: unexpected alias"))bug!("symbol_names: unexpected alias"),
618            ty::CoroutineWitness(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("symbol_names: unexpected `CoroutineWitness`"))bug!("symbol_names: unexpected `CoroutineWitness`"),
619        }
620
621        // Only cache types that do not refer to an enclosing
622        // binder (which would change depending on context).
623        if !ty.has_escaping_bound_vars() {
624            self.types.insert(ty, start);
625        }
626        Ok(())
627    }
628
629    fn print_dyn_existential(
630        &mut self,
631        predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
632    ) -> Result<(), PrintError> {
633        // Okay, so this is a bit tricky. Imagine we have a trait object like
634        // `dyn for<'a> Foo<'a, Bar = &'a ()>`. When we mangle this, the
635        // output looks really close to the syntax, where the `Bar = &'a ()` bit
636        // is under the same binders (`['a]`) as the `Foo<'a>` bit. However, we
637        // actually desugar these into two separate `ExistentialPredicate`s. We
638        // can't enter/exit the "binder scope" twice though, because then we
639        // would mangle the binders twice. (Also, side note, we merging these
640        // two is kind of difficult, because of potential HRTBs in the Projection
641        // predicate.)
642        //
643        // Also worth mentioning: imagine that we instead had
644        // `dyn for<'a> Foo<'a, Bar = &'a ()> + Send`. In this case, `Send` is
645        // under the same binders as `Foo`. Currently, this doesn't matter,
646        // because only *auto traits* are allowed other than the principal trait
647        // and all auto traits don't have any generics. Two things could
648        // make this not an "okay" mangling:
649        // 1) Instead of mangling only *used*
650        // bound vars, we want to mangle *all* bound vars (`for<'b> Send` is a
651        // valid trait predicate);
652        // 2) We allow multiple "principal" traits in the future, or at least
653        // allow in any form another trait predicate that can take generics.
654        //
655        // Here we assume that predicates have the following structure:
656        // [<Trait> [{<Projection>}]] [{<Auto>}]
657        // Since any predicates after the first one shouldn't change the binders,
658        // just put them all in the binders of the first.
659        self.wrap_binder(&predicates[0], |p, _| {
660            for predicate in predicates.iter() {
661                // It would be nice to be able to validate bound vars here, but
662                // projections can actually include bound vars from super traits
663                // because of HRTBs (only in the `Self` type). Also, auto traits
664                // could have different bound vars *anyways*.
665                match predicate.as_ref().skip_binder() {
666                    ty::ExistentialPredicate::Trait(trait_ref) => {
667                        // Dummy Self is safe to use as it can't appear in generic param defaults
668                        // which is important later on for correctly eliding generic args that
669                        // coincide with their default.
670                        let trait_ref =
671                            trait_ref.with_self_ty(p.tcx, p.tcx.types.trait_object_dummy_self);
672                        p.print_def_path(trait_ref.def_id, trait_ref.args)?;
673                    }
674                    ty::ExistentialPredicate::Projection(projection) => {
675                        let name = p.tcx.associated_item(projection.def_id).name();
676                        p.push("p");
677                        p.push_ident(name.as_str());
678                        match projection.term.kind() {
679                            ty::TermKind::Ty(ty) => ty.print(p),
680                            ty::TermKind::Const(c) => {
681                                p.push("K");
682                                c.print(p)
683                            }
684                        }?;
685                    }
686                    ty::ExistentialPredicate::AutoTrait(def_id) => {
687                        p.print_def_path(*def_id, &[])?;
688                    }
689                }
690            }
691            Ok(())
692        })?;
693
694        self.push("E");
695        Ok(())
696    }
697
698    fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
699        // We only mangle a typed value if the const can be evaluated.
700        let cv = match ct.kind() {
701            ty::ConstKind::Value(cv) => cv,
702
703            // Should only be encountered within the identity-substituted
704            // impl header of an item nested within an impl item.
705            ty::ConstKind::Param(_) => {
706                // Never cached (single-character).
707                self.push("p");
708                return Ok(());
709            }
710
711            // We may still encounter alias consts due to the printing
712            // logic sometimes passing identity-substituted impl headers.
713            ty::ConstKind::Alias(_, ty::AliasConst { kind, args, .. }) => match kind {
714                ty::AliasConstKind::Projection { def_id }
715                | ty::AliasConstKind::Inherent { def_id }
716                | ty::AliasConstKind::Free { def_id }
717                | ty::AliasConstKind::Anon { def_id } => {
718                    return self.print_def_path(def_id, args);
719                }
720            },
721
722            ty::ConstKind::Expr(_)
723            | ty::ConstKind::Infer(_)
724            | ty::ConstKind::Bound(..)
725            | ty::ConstKind::Placeholder(_)
726            | ty::ConstKind::Error(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
727        };
728
729        if let Some(&i) = self.consts.get(&ct) {
730            self.print_backref(i)?;
731            return Ok(());
732        }
733
734        let ty::Value { ty: ct_ty, valtree } = cv;
735        let start = self.out.len();
736
737        match ct_ty.kind() {
738            ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Char => {
739                ct_ty.print(self)?;
740
741                let mut bits = cv
742                    .try_to_bits(self.tcx, ty::TypingEnv::fully_monomorphized())
743                    .expect("expected const to be monomorphic");
744
745                // Negative integer values are mangled using `n` as a "sign prefix".
746                if let ty::Int(ity) = ct_ty.kind() {
747                    let val =
748                        Integer::from_int_ty(&self.tcx, *ity).size().sign_extend(bits) as i128;
749                    if val < 0 {
750                        self.push("n");
751                    }
752                    bits = val.unsigned_abs();
753                }
754
755                let _ = self.out.write_fmt(format_args!("{0:x}_", bits))write!(self.out, "{bits:x}_");
756            }
757
758            // Handle `str` as partial support for unsized constants
759            ty::Str => {
760                let tcx = self.tcx();
761                // HACK(jaic1): hide the `str` type behind a reference
762                // for the following transformation from valtree to raw bytes
763                let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, ct_ty);
764                let cv = ty::Value { ty: ref_ty, valtree };
765                let slice = cv.try_to_raw_bytes(tcx).unwrap_or_else(|| {
766                    ::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)
767                });
768                let s = std::str::from_utf8(slice).expect("non utf8 str from MIR interpreter");
769
770                // "e" for str as a basic type
771                self.push("e");
772
773                // FIXME(eddyb) use a specialized hex-encoding loop.
774                for byte in s.bytes() {
775                    let _ = self.out.write_fmt(format_args!("{0:02x}", byte))write!(self.out, "{byte:02x}");
776                }
777
778                self.push("_");
779            }
780
781            // FIXME(valtrees): Remove the special case for `str`
782            // here and fully support unsized constants.
783            ty::Ref(_, _, mutbl) => {
784                self.push(match mutbl {
785                    hir::Mutability::Not => "R",
786                    hir::Mutability::Mut => "Q",
787                });
788
789                let pointee_ty =
790                    ct_ty.builtin_deref(true).expect("tried to dereference on non-ptr type");
791                let dereferenced_const = ty::Const::new_value(self.tcx, valtree, pointee_ty);
792                dereferenced_const.print(self)?;
793            }
794
795            ty::Array(..) | ty::Tuple(..) | ty::Slice(_) => {
796                let fields = cv.to_branch().iter().copied();
797
798                let print_field_list = |this: &mut Self| {
799                    for field in fields.clone() {
800                        field.print(this)?;
801                    }
802                    this.push("E");
803                    Ok(())
804                };
805
806                match *ct_ty.kind() {
807                    ty::Array(..) | ty::Slice(_) => {
808                        self.push("A");
809                        print_field_list(self)?;
810                    }
811                    ty::Tuple(..) => {
812                        self.push("T");
813                        print_field_list(self)?;
814                    }
815                    _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
816                }
817            }
818            ty::Adt(def, args) => {
819                let contents = cv.destructure_adt_const();
820                let fields = contents.fields.iter().copied();
821
822                let print_field_list = |this: &mut Self| {
823                    for field in fields.clone() {
824                        field.print(this)?;
825                    }
826                    this.push("E");
827                    Ok(())
828                };
829
830                let variant_idx = contents.variant;
831                let variant_def = &def.variant(variant_idx);
832
833                self.push("V");
834                self.print_def_path(variant_def.def_id, args)?;
835
836                match variant_def.ctor_kind() {
837                    Some(CtorKind::Const) => {
838                        self.push("U");
839                    }
840                    Some(CtorKind::Fn) => {
841                        self.push("T");
842                        print_field_list(self)?;
843                    }
844                    None => {
845                        self.push("S");
846                        for (field_def, field) in iter::zip(&variant_def.fields, fields) {
847                            // HACK(eddyb) this mimics `print_path_with_simple`,
848                            // instead of simply using `field_def.ident`,
849                            // just to be able to handle disambiguators.
850                            let disambiguated_field =
851                                self.tcx.def_key(field_def.did).disambiguated_data;
852                            let field_name = disambiguated_field.data.get_opt_name();
853                            self.push_disambiguator(disambiguated_field.disambiguator as u64);
854                            self.push_ident(field_name.unwrap().as_str());
855
856                            field.print(self)?;
857                        }
858                        self.push("E");
859                    }
860                }
861            }
862            _ => {
863                ::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);
864            }
865        }
866
867        // Only cache consts that do not refer to an enclosing
868        // binder (which would change depending on context).
869        if !ct.has_escaping_bound_vars() {
870            self.consts.insert(ct, start);
871        }
872        Ok(())
873    }
874
875    fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
876        self.push("C");
877        if !self.is_exportable {
878            let stable_crate_id = self.tcx.stable_crate_id(cnum);
879            self.push_disambiguator(stable_crate_id.as_u64());
880        }
881        let name = self.tcx.crate_name(cnum);
882        self.push_ident(name.as_str());
883        Ok(())
884    }
885
886    fn print_path_with_qualified(
887        &mut self,
888        self_ty: Ty<'tcx>,
889        trait_ref: Option<ty::TraitRef<'tcx>>,
890    ) -> Result<(), PrintError> {
891        if !trait_ref.is_some() {
    ::core::panicking::panic("assertion failed: trait_ref.is_some()")
};assert!(trait_ref.is_some());
892        let trait_ref = trait_ref.unwrap();
893
894        self.push("Y");
895        self_ty.print(self)?;
896        self.print_def_path(trait_ref.def_id, trait_ref.args)
897    }
898
899    fn print_path_with_impl(
900        &mut self,
901        _: impl FnOnce(&mut Self) -> Result<(), PrintError>,
902        _: Ty<'tcx>,
903        _: Option<ty::TraitRef<'tcx>>,
904    ) -> Result<(), PrintError> {
905        // Inlined into `print_impl_path`
906        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
907    }
908
909    fn print_path_with_simple(
910        &mut self,
911        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
912        disambiguated_data: &DisambiguatedDefPathData,
913    ) -> Result<(), PrintError> {
914        let ns = match disambiguated_data.data {
915            // Extern block segments can be skipped, names from extern blocks
916            // are effectively living in their parent modules.
917            DefPathData::ForeignMod => return print_prefix(self),
918
919            // Uppercase categories are more stable than lowercase ones.
920            DefPathData::TypeNs(_) => 't',
921            DefPathData::ValueNs(_) => 'v',
922            DefPathData::Closure => 'C',
923            DefPathData::Ctor => 'c',
924            DefPathData::AnonConst => 'K',
925            DefPathData::OpaqueTy => 'i',
926            DefPathData::SyntheticCoroutineBody => 's',
927            DefPathData::NestedStatic => 'n',
928            DefPathData::GlobalAsm => 'a',
929
930            // These should never show up as `print_path_with_simple` arguments.
931            DefPathData::CrateRoot
932            | DefPathData::Use
933            | DefPathData::Impl
934            | DefPathData::MacroNs(_)
935            | DefPathData::LifetimeNs(_)
936            | DefPathData::OpaqueLifetime(_)
937            | DefPathData::AnonAssocTy(..) => {
938                ::rustc_middle::util::bug::bug_fmt(format_args!("symbol_names: unexpected DefPathData: {0:?}",
        disambiguated_data.data))bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
939            }
940        };
941
942        let name = disambiguated_data.data.get_opt_name();
943
944        self.path_append_ns(
945            print_prefix,
946            ns,
947            disambiguated_data.disambiguator as u64,
948            name.unwrap_or(sym::empty).as_str(),
949        )
950    }
951
952    fn print_path_with_generic_args(
953        &mut self,
954        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
955        args: &[GenericArg<'tcx>],
956    ) -> Result<(), PrintError> {
957        // Don't print any regions if they're all erased.
958        let print_regions = args.iter().any(|arg| match arg.kind() {
959            GenericArgKind::Lifetime(r) => !r.is_erased(),
960            _ => false,
961        });
962        let args = args.iter().cloned().filter(|arg| match arg.kind() {
963            GenericArgKind::Lifetime(_) => print_regions,
964            _ => true,
965        });
966
967        if args.clone().next().is_none() {
968            return print_prefix(self);
969        }
970
971        self.push("I");
972        print_prefix(self)?;
973        for arg in args {
974            match arg.kind() {
975                GenericArgKind::Lifetime(lt) => {
976                    lt.print(self)?;
977                }
978                GenericArgKind::Type(ty) => {
979                    ty.print(self)?;
980                }
981                GenericArgKind::Const(c) => {
982                    self.push("K");
983                    c.print(self)?;
984                }
985            }
986        }
987        self.push("E");
988
989        Ok(())
990    }
991}
992/// Push a `_`-terminated base 62 integer, using the format
993/// specified in the RFC as `<base-62-number>`, that is:
994/// * `x = 0` is encoded as just the `"_"` terminator
995/// * `x > 0` is encoded as `x - 1` in base 62, followed by `"_"`,
996///   e.g. `1` becomes `"0_"`, `62` becomes `"Z_"`, etc.
997pub(crate) fn push_integer_62(x: u64, output: &mut String) {
998    if let Some(x) = x.checked_sub(1) {
999        output.push_str(&x.to_base(62));
1000    }
1001    output.push('_');
1002}
1003
1004pub(crate) fn encode_integer_62(x: u64) -> String {
1005    let mut output = String::new();
1006    push_integer_62(x, &mut output);
1007    output
1008}
1009
1010pub(crate) fn push_ident(ident: &str, output: &mut String) {
1011    let mut use_punycode = false;
1012    for b in ident.bytes() {
1013        match b {
1014            b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
1015            0x80..=0xff => use_punycode = true,
1016            _ => ::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),
1017        }
1018    }
1019
1020    let punycode_string;
1021    let ident = if use_punycode {
1022        output.push('u');
1023
1024        // FIXME(eddyb) we should probably roll our own punycode implementation.
1025        let mut punycode_bytes = match punycode::encode(ident) {
1026            Ok(s) => s.into_bytes(),
1027            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),
1028        };
1029
1030        // Replace `-` with `_`.
1031        if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
1032            *c = b'_';
1033        }
1034
1035        // FIXME(eddyb) avoid rechecking UTF-8 validity.
1036        punycode_string = String::from_utf8(punycode_bytes).unwrap();
1037        &punycode_string
1038    } else {
1039        ident
1040    };
1041
1042    let _ = output.write_fmt(format_args!("{0}", ident.len()))write!(output, "{}", ident.len());
1043
1044    // Write a separating `_` if necessary (leading digit or `_`).
1045    if let Some('_' | '0'..='9') = ident.chars().next() {
1046        output.push('_');
1047    }
1048
1049    output.push_str(ident);
1050}