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