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