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