]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_symbol_mangling/src/v0.rs
Add type flags support for Ty and Const late-bound regions
[rust.git] / compiler / rustc_symbol_mangling / src / v0.rs
1 use rustc_data_structures::base_n;
2 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
3 use rustc_data_structures::intern::Interned;
4 use rustc_hir as hir;
5 use rustc_hir::def::CtorKind;
6 use rustc_hir::def_id::{CrateNum, DefId};
7 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
8 use rustc_middle::ty::layout::IntegerExt;
9 use rustc_middle::ty::print::{Print, Printer};
10 use rustc_middle::ty::{
11     self, EarlyBinder, FloatTy, Instance, IntTy, Ty, TyCtxt, TypeVisitable, UintTy,
12 };
13 use rustc_middle::ty::{GenericArg, GenericArgKind};
14 use rustc_span::symbol::kw;
15 use rustc_target::abi::Integer;
16 use rustc_target::spec::abi::Abi;
17
18 use std::fmt::Write;
19 use std::iter;
20 use std::ops::Range;
21
22 pub(super) fn mangle<'tcx>(
23     tcx: TyCtxt<'tcx>,
24     instance: Instance<'tcx>,
25     instantiating_crate: Option<CrateNum>,
26 ) -> String {
27     let def_id = instance.def_id();
28     // FIXME(eddyb) this should ideally not be needed.
29     let substs = tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), instance.substs);
30
31     let prefix = "_R";
32     let mut cx = &mut SymbolMangler {
33         tcx,
34         start_offset: prefix.len(),
35         paths: FxHashMap::default(),
36         types: FxHashMap::default(),
37         consts: FxHashMap::default(),
38         binders: vec![],
39         out: String::from(prefix),
40     };
41
42     // Append `::{shim:...#0}` to shims that can coexist with a non-shim instance.
43     let shim_kind = match instance.def {
44         ty::InstanceDef::VTableShim(_) => Some("vtable"),
45         ty::InstanceDef::ReifyShim(_) => Some("reify"),
46
47         _ => None,
48     };
49
50     cx = if let Some(shim_kind) = shim_kind {
51         cx.path_append_ns(|cx| cx.print_def_path(def_id, substs), 'S', 0, shim_kind).unwrap()
52     } else {
53         cx.print_def_path(def_id, substs).unwrap()
54     };
55     if let Some(instantiating_crate) = instantiating_crate {
56         cx = cx.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap();
57     }
58     std::mem::take(&mut cx.out)
59 }
60
61 pub(super) fn mangle_typeid_for_trait_ref<'tcx>(
62     tcx: TyCtxt<'tcx>,
63     trait_ref: ty::PolyExistentialTraitRef<'tcx>,
64 ) -> String {
65     // FIXME(flip1995): See comment in `mangle_typeid_for_fnabi`.
66     let mut cx = &mut SymbolMangler {
67         tcx,
68         start_offset: 0,
69         paths: FxHashMap::default(),
70         types: FxHashMap::default(),
71         consts: FxHashMap::default(),
72         binders: vec![],
73         out: String::new(),
74     };
75     cx = cx.print_def_path(trait_ref.def_id(), &[]).unwrap();
76     std::mem::take(&mut cx.out)
77 }
78
79 struct BinderLevel {
80     /// The range of distances from the root of what's
81     /// being printed, to the lifetimes in a binder.
82     /// Specifically, a `BrAnon(i)` lifetime has depth
83     /// `lifetime_depths.start + i`, going away from the
84     /// the root and towards its use site, as `i` increases.
85     /// This is used to flatten rustc's pairing of `BrAnon`
86     /// (intra-binder disambiguation) with a `DebruijnIndex`
87     /// (binder addressing), to "true" de Bruijn indices,
88     /// by subtracting the depth of a certain lifetime, from
89     /// the innermost depth at its use site.
90     lifetime_depths: Range<u32>,
91 }
92
93 struct SymbolMangler<'tcx> {
94     tcx: TyCtxt<'tcx>,
95     binders: Vec<BinderLevel>,
96     out: String,
97
98     /// The length of the prefix in `out` (e.g. 2 for `_R`).
99     start_offset: usize,
100     /// The values are start positions in `out`, in bytes.
101     paths: FxHashMap<(DefId, &'tcx [GenericArg<'tcx>]), usize>,
102     types: FxHashMap<Ty<'tcx>, usize>,
103     consts: FxHashMap<ty::Const<'tcx>, usize>,
104 }
105
106 impl<'tcx> SymbolMangler<'tcx> {
107     fn push(&mut self, s: &str) {
108         self.out.push_str(s);
109     }
110
111     /// Push a `_`-terminated base 62 integer, using the format
112     /// specified in the RFC as `<base-62-number>`, that is:
113     /// * `x = 0` is encoded as just the `"_"` terminator
114     /// * `x > 0` is encoded as `x - 1` in base 62, followed by `"_"`,
115     ///   e.g. `1` becomes `"0_"`, `62` becomes `"Z_"`, etc.
116     fn push_integer_62(&mut self, x: u64) {
117         if let Some(x) = x.checked_sub(1) {
118             base_n::push_str(x as u128, 62, &mut self.out);
119         }
120         self.push("_");
121     }
122
123     /// Push a `tag`-prefixed base 62 integer, when larger than `0`, that is:
124     /// * `x = 0` is encoded as `""` (nothing)
125     /// * `x > 0` is encoded as the `tag` followed by `push_integer_62(x - 1)`
126     ///   e.g. `1` becomes `tag + "_"`, `2` becomes `tag + "0_"`, etc.
127     fn push_opt_integer_62(&mut self, tag: &str, x: u64) {
128         if let Some(x) = x.checked_sub(1) {
129             self.push(tag);
130             self.push_integer_62(x);
131         }
132     }
133
134     fn push_disambiguator(&mut self, dis: u64) {
135         self.push_opt_integer_62("s", dis);
136     }
137
138     fn push_ident(&mut self, ident: &str) {
139         let mut use_punycode = false;
140         for b in ident.bytes() {
141             match b {
142                 b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
143                 0x80..=0xff => use_punycode = true,
144                 _ => bug!("symbol_names: bad byte {} in ident {:?}", b, ident),
145             }
146         }
147
148         let punycode_string;
149         let ident = if use_punycode {
150             self.push("u");
151
152             // FIXME(eddyb) we should probably roll our own punycode implementation.
153             let mut punycode_bytes = match punycode::encode(ident) {
154                 Ok(s) => s.into_bytes(),
155                 Err(()) => bug!("symbol_names: punycode encoding failed for ident {:?}", ident),
156             };
157
158             // Replace `-` with `_`.
159             if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
160                 *c = b'_';
161             }
162
163             // FIXME(eddyb) avoid rechecking UTF-8 validity.
164             punycode_string = String::from_utf8(punycode_bytes).unwrap();
165             &punycode_string
166         } else {
167             ident
168         };
169
170         let _ = write!(self.out, "{}", ident.len());
171
172         // Write a separating `_` if necessary (leading digit or `_`).
173         if let Some('_' | '0'..='9') = ident.chars().next() {
174             self.push("_");
175         }
176
177         self.push(ident);
178     }
179
180     fn path_append_ns<'a>(
181         mut self: &'a mut Self,
182         print_prefix: impl FnOnce(&'a mut Self) -> Result<&'a mut Self, !>,
183         ns: char,
184         disambiguator: u64,
185         name: &str,
186     ) -> Result<&'a mut Self, !> {
187         self.push("N");
188         self.out.push(ns);
189         self = print_prefix(self)?;
190         self.push_disambiguator(disambiguator as u64);
191         self.push_ident(name);
192         Ok(self)
193     }
194
195     fn print_backref(&mut self, i: usize) -> Result<&mut Self, !> {
196         self.push("B");
197         self.push_integer_62((i - self.start_offset) as u64);
198         Ok(self)
199     }
200
201     fn in_binder<'a, T>(
202         mut self: &'a mut Self,
203         value: &ty::Binder<'tcx, T>,
204         print_value: impl FnOnce(&'a mut Self, &T) -> Result<&'a mut Self, !>,
205     ) -> Result<&'a mut Self, !>
206     where
207         T: TypeVisitable<'tcx>,
208     {
209         // FIXME(non-lifetime-binders): What to do here?
210         let regions = if value.has_late_bound_regions() {
211             self.tcx.collect_referenced_late_bound_regions(value)
212         } else {
213             FxHashSet::default()
214         };
215
216         let mut lifetime_depths =
217             self.binders.last().map(|b| b.lifetime_depths.end).map_or(0..0, |i| i..i);
218
219         let lifetimes = regions
220             .into_iter()
221             .map(|br| match br {
222                 ty::BrAnon(i, _) => i,
223                 _ => bug!("symbol_names: non-anonymized region `{:?}` in `{:?}`", br, value),
224             })
225             .max()
226             .map_or(0, |max| max + 1);
227
228         self.push_opt_integer_62("G", lifetimes as u64);
229         lifetime_depths.end += lifetimes;
230
231         self.binders.push(BinderLevel { lifetime_depths });
232         self = print_value(self, value.as_ref().skip_binder())?;
233         self.binders.pop();
234
235         Ok(self)
236     }
237 }
238
239 impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> {
240     type Error = !;
241
242     type Path = Self;
243     type Region = Self;
244     type Type = Self;
245     type DynExistential = Self;
246     type Const = Self;
247
248     fn tcx(&self) -> TyCtxt<'tcx> {
249         self.tcx
250     }
251
252     fn print_def_path(
253         mut self,
254         def_id: DefId,
255         substs: &'tcx [GenericArg<'tcx>],
256     ) -> Result<Self::Path, Self::Error> {
257         if let Some(&i) = self.paths.get(&(def_id, substs)) {
258             return self.print_backref(i);
259         }
260         let start = self.out.len();
261
262         self = self.default_print_def_path(def_id, substs)?;
263
264         // Only cache paths that do not refer to an enclosing
265         // binder (which would change depending on context).
266         if !substs.iter().any(|k| k.has_escaping_bound_vars()) {
267             self.paths.insert((def_id, substs), start);
268         }
269         Ok(self)
270     }
271
272     fn print_impl_path(
273         mut self,
274         impl_def_id: DefId,
275         substs: &'tcx [GenericArg<'tcx>],
276         mut self_ty: Ty<'tcx>,
277         mut impl_trait_ref: Option<ty::TraitRef<'tcx>>,
278     ) -> Result<Self::Path, Self::Error> {
279         let key = self.tcx.def_key(impl_def_id);
280         let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
281
282         let mut param_env = self.tcx.param_env_reveal_all_normalized(impl_def_id);
283         if !substs.is_empty() {
284             param_env = EarlyBinder(param_env).subst(self.tcx, substs);
285         }
286
287         match &mut impl_trait_ref {
288             Some(impl_trait_ref) => {
289                 assert_eq!(impl_trait_ref.self_ty(), self_ty);
290                 *impl_trait_ref = self.tcx.normalize_erasing_regions(param_env, *impl_trait_ref);
291                 self_ty = impl_trait_ref.self_ty();
292             }
293             None => {
294                 self_ty = self.tcx.normalize_erasing_regions(param_env, self_ty);
295             }
296         }
297
298         self.push(match impl_trait_ref {
299             Some(_) => "X",
300             None => "M",
301         });
302
303         // Encode impl generic params if the substitutions contain parameters (implying
304         // polymorphization is enabled) and this isn't an inherent impl.
305         if impl_trait_ref.is_some() && substs.iter().any(|a| a.has_non_region_param()) {
306             self = self.path_generic_args(
307                 |this| {
308                     this.path_append_ns(
309                         |cx| cx.print_def_path(parent_def_id, &[]),
310                         'I',
311                         key.disambiguated_data.disambiguator as u64,
312                         "",
313                     )
314                 },
315                 substs,
316             )?;
317         } else {
318             self.push_disambiguator(key.disambiguated_data.disambiguator as u64);
319             self = self.print_def_path(parent_def_id, &[])?;
320         }
321
322         self = self_ty.print(self)?;
323
324         if let Some(trait_ref) = impl_trait_ref {
325             self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?;
326         }
327
328         Ok(self)
329     }
330
331     fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
332         let i = match *region {
333             // Erased lifetimes use the index 0, for a
334             // shorter mangling of `L_`.
335             ty::ReErased => 0,
336
337             // Late-bound lifetimes use indices starting at 1,
338             // see `BinderLevel` for more details.
339             ty::ReLateBound(debruijn, ty::BoundRegion { kind: ty::BrAnon(i, _), .. }) => {
340                 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
341                 let depth = binder.lifetime_depths.start + i;
342
343                 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
344             }
345
346             _ => bug!("symbol_names: non-erased region `{:?}`", region),
347         };
348         self.push("L");
349         self.push_integer_62(i as u64);
350         Ok(self)
351     }
352
353     fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
354         // Basic types, never cached (single-character).
355         let basic_type = match ty.kind() {
356             ty::Bool => "b",
357             ty::Char => "c",
358             ty::Str => "e",
359             ty::Tuple(_) if ty.is_unit() => "u",
360             ty::Int(IntTy::I8) => "a",
361             ty::Int(IntTy::I16) => "s",
362             ty::Int(IntTy::I32) => "l",
363             ty::Int(IntTy::I64) => "x",
364             ty::Int(IntTy::I128) => "n",
365             ty::Int(IntTy::Isize) => "i",
366             ty::Uint(UintTy::U8) => "h",
367             ty::Uint(UintTy::U16) => "t",
368             ty::Uint(UintTy::U32) => "m",
369             ty::Uint(UintTy::U64) => "y",
370             ty::Uint(UintTy::U128) => "o",
371             ty::Uint(UintTy::Usize) => "j",
372             ty::Float(FloatTy::F32) => "f",
373             ty::Float(FloatTy::F64) => "d",
374             ty::Never => "z",
375
376             // Placeholders (should be demangled as `_`).
377             ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => "p",
378
379             _ => "",
380         };
381         if !basic_type.is_empty() {
382             self.push(basic_type);
383             return Ok(self);
384         }
385
386         if let Some(&i) = self.types.get(&ty) {
387             return self.print_backref(i);
388         }
389         let start = self.out.len();
390
391         match *ty.kind() {
392             // Basic types, handled above.
393             ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
394                 unreachable!()
395             }
396             ty::Tuple(_) if ty.is_unit() => unreachable!(),
397
398             // Placeholders, also handled as part of basic types.
399             ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => {
400                 unreachable!()
401             }
402
403             ty::Ref(r, ty, mutbl) => {
404                 self.push(match mutbl {
405                     hir::Mutability::Not => "R",
406                     hir::Mutability::Mut => "Q",
407                 });
408                 if !r.is_erased() {
409                     self = r.print(self)?;
410                 }
411                 self = ty.print(self)?;
412             }
413
414             ty::RawPtr(mt) => {
415                 self.push(match mt.mutbl {
416                     hir::Mutability::Not => "P",
417                     hir::Mutability::Mut => "O",
418                 });
419                 self = mt.ty.print(self)?;
420             }
421
422             ty::Array(ty, len) => {
423                 self.push("A");
424                 self = ty.print(self)?;
425                 self = self.print_const(len)?;
426             }
427             ty::Slice(ty) => {
428                 self.push("S");
429                 self = ty.print(self)?;
430             }
431
432             ty::Tuple(tys) => {
433                 self.push("T");
434                 for ty in tys.iter() {
435                     self = ty.print(self)?;
436                 }
437                 self.push("E");
438             }
439
440             // Mangle all nominal types as paths.
441             ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), substs)
442             | ty::FnDef(def_id, substs)
443             | ty::Alias(_, ty::AliasTy { def_id, substs, .. })
444             | ty::Closure(def_id, substs)
445             | ty::Generator(def_id, substs, _) => {
446                 self = self.print_def_path(def_id, substs)?;
447             }
448             ty::Foreign(def_id) => {
449                 self = self.print_def_path(def_id, &[])?;
450             }
451
452             ty::FnPtr(sig) => {
453                 self.push("F");
454                 self = self.in_binder(&sig, |mut cx, sig| {
455                     if sig.unsafety == hir::Unsafety::Unsafe {
456                         cx.push("U");
457                     }
458                     match sig.abi {
459                         Abi::Rust => {}
460                         Abi::C { unwind: false } => cx.push("KC"),
461                         abi => {
462                             cx.push("K");
463                             let name = abi.name();
464                             if name.contains('-') {
465                                 cx.push_ident(&name.replace('-', "_"));
466                             } else {
467                                 cx.push_ident(name);
468                             }
469                         }
470                     }
471                     for &ty in sig.inputs() {
472                         cx = ty.print(cx)?;
473                     }
474                     if sig.c_variadic {
475                         cx.push("v");
476                     }
477                     cx.push("E");
478                     sig.output().print(cx)
479                 })?;
480             }
481
482             ty::Dynamic(predicates, r, kind) => {
483                 self.push(match kind {
484                     ty::Dyn => "D",
485                     // FIXME(dyn-star): need to update v0 mangling docs
486                     ty::DynStar => "D*",
487                 });
488                 self = self.print_dyn_existential(predicates)?;
489                 self = r.print(self)?;
490             }
491
492             ty::GeneratorWitness(_) => bug!("symbol_names: unexpected `GeneratorWitness`"),
493         }
494
495         // Only cache types that do not refer to an enclosing
496         // binder (which would change depending on context).
497         if !ty.has_escaping_bound_vars() {
498             self.types.insert(ty, start);
499         }
500         Ok(self)
501     }
502
503     fn print_dyn_existential(
504         mut self,
505         predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
506     ) -> Result<Self::DynExistential, Self::Error> {
507         // Okay, so this is a bit tricky. Imagine we have a trait object like
508         // `dyn for<'a> Foo<'a, Bar = &'a ()>`. When we mangle this, the
509         // output looks really close to the syntax, where the `Bar = &'a ()` bit
510         // is under the same binders (`['a]`) as the `Foo<'a>` bit. However, we
511         // actually desugar these into two separate `ExistentialPredicate`s. We
512         // can't enter/exit the "binder scope" twice though, because then we
513         // would mangle the binders twice. (Also, side note, we merging these
514         // two is kind of difficult, because of potential HRTBs in the Projection
515         // predicate.)
516         //
517         // Also worth mentioning: imagine that we instead had
518         // `dyn for<'a> Foo<'a, Bar = &'a ()> + Send`. In this case, `Send` is
519         // under the same binders as `Foo`. Currently, this doesn't matter,
520         // because only *auto traits* are allowed other than the principal trait
521         // and all auto traits don't have any generics. Two things could
522         // make this not an "okay" mangling:
523         // 1) Instead of mangling only *used*
524         // bound vars, we want to mangle *all* bound vars (`for<'b> Send` is a
525         // valid trait predicate);
526         // 2) We allow multiple "principal" traits in the future, or at least
527         // allow in any form another trait predicate that can take generics.
528         //
529         // Here we assume that predicates have the following structure:
530         // [<Trait> [{<Projection>}]] [{<Auto>}]
531         // Since any predicates after the first one shouldn't change the binders,
532         // just put them all in the binders of the first.
533         self = self.in_binder(&predicates[0], |mut cx, _| {
534             for predicate in predicates.iter() {
535                 // It would be nice to be able to validate bound vars here, but
536                 // projections can actually include bound vars from super traits
537                 // because of HRTBs (only in the `Self` type). Also, auto traits
538                 // could have different bound vars *anyways*.
539                 match predicate.as_ref().skip_binder() {
540                     ty::ExistentialPredicate::Trait(trait_ref) => {
541                         // Use a type that can't appear in defaults of type parameters.
542                         let dummy_self = cx.tcx.mk_ty_infer(ty::FreshTy(0));
543                         let trait_ref = trait_ref.with_self_ty(cx.tcx, dummy_self);
544                         cx = cx.print_def_path(trait_ref.def_id, trait_ref.substs)?;
545                     }
546                     ty::ExistentialPredicate::Projection(projection) => {
547                         let name = cx.tcx.associated_item(projection.def_id).name;
548                         cx.push("p");
549                         cx.push_ident(name.as_str());
550                         cx = match projection.term.unpack() {
551                             ty::TermKind::Ty(ty) => ty.print(cx),
552                             ty::TermKind::Const(c) => c.print(cx),
553                         }?;
554                     }
555                     ty::ExistentialPredicate::AutoTrait(def_id) => {
556                         cx = cx.print_def_path(*def_id, &[])?;
557                     }
558                 }
559             }
560             Ok(cx)
561         })?;
562
563         self.push("E");
564         Ok(self)
565     }
566
567     fn print_const(mut self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
568         // We only mangle a typed value if the const can be evaluated.
569         let ct = ct.eval(self.tcx, ty::ParamEnv::reveal_all());
570         match ct.kind() {
571             ty::ConstKind::Value(_) => {}
572
573             // Placeholders (should be demangled as `_`).
574             // NOTE(eddyb) despite `Unevaluated` having a `DefId` (and therefore
575             // a path), even for it we still need to encode a placeholder, as
576             // the path could refer back to e.g. an `impl` using the constant.
577             ty::ConstKind::Unevaluated(_)
578             | ty::ConstKind::Expr(_)
579             | ty::ConstKind::Param(_)
580             | ty::ConstKind::Infer(_)
581             | ty::ConstKind::Bound(..)
582             | ty::ConstKind::Placeholder(_)
583             | ty::ConstKind::Error(_) => {
584                 // Never cached (single-character).
585                 self.push("p");
586                 return Ok(self);
587             }
588         }
589
590         if let Some(&i) = self.consts.get(&ct) {
591             return self.print_backref(i);
592         }
593
594         let start = self.out.len();
595         let ty = ct.ty();
596
597         match ty.kind() {
598             ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Char => {
599                 self = ty.print(self)?;
600
601                 let mut bits = ct.eval_bits(self.tcx, ty::ParamEnv::reveal_all(), ty);
602
603                 // Negative integer values are mangled using `n` as a "sign prefix".
604                 if let ty::Int(ity) = ty.kind() {
605                     let val =
606                         Integer::from_int_ty(&self.tcx, *ity).size().sign_extend(bits) as i128;
607                     if val < 0 {
608                         self.push("n");
609                     }
610                     bits = val.unsigned_abs();
611                 }
612
613                 let _ = write!(self.out, "{bits:x}_");
614             }
615
616             // FIXME(valtrees): Remove the special case for `str`
617             // here and fully support unsized constants.
618             ty::Ref(_, inner_ty, mutbl) => {
619                 self.push(match mutbl {
620                     hir::Mutability::Not => "R",
621                     hir::Mutability::Mut => "Q",
622                 });
623
624                 match inner_ty.kind() {
625                     ty::Str if mutbl.is_not() => {
626                         match ct.kind() {
627                             ty::ConstKind::Value(valtree) => {
628                                 let slice =
629                                     valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
630                                         bug!(
631                                         "expected to get raw bytes from valtree {:?} for type {:}",
632                                         valtree, ty
633                                     )
634                                     });
635                                 let s = std::str::from_utf8(slice).expect("non utf8 str from miri");
636
637                                 self.push("e");
638
639                                 // FIXME(eddyb) use a specialized hex-encoding loop.
640                                 for byte in s.bytes() {
641                                     let _ = write!(self.out, "{byte:02x}");
642                                 }
643
644                                 self.push("_");
645                             }
646
647                             _ => {
648                                 bug!("symbol_names: unsupported `&str` constant: {:?}", ct);
649                             }
650                         }
651                     }
652                     _ => {
653                         let pointee_ty = ct
654                             .ty()
655                             .builtin_deref(true)
656                             .expect("tried to dereference on non-ptr type")
657                             .ty;
658                         let dereferenced_const = self.tcx.mk_const(ct.kind(), pointee_ty);
659                         self = dereferenced_const.print(self)?;
660                     }
661                 }
662             }
663
664             ty::Array(..) | ty::Tuple(..) | ty::Adt(..) | ty::Slice(_) => {
665                 let contents = self.tcx.destructure_const(ct);
666                 let fields = contents.fields.iter().copied();
667
668                 let print_field_list = |mut this: Self| {
669                     for field in fields.clone() {
670                         this = field.print(this)?;
671                     }
672                     this.push("E");
673                     Ok(this)
674                 };
675
676                 match *ct.ty().kind() {
677                     ty::Array(..) | ty::Slice(_) => {
678                         self.push("A");
679                         self = print_field_list(self)?;
680                     }
681                     ty::Tuple(..) => {
682                         self.push("T");
683                         self = print_field_list(self)?;
684                     }
685                     ty::Adt(def, substs) => {
686                         let variant_idx =
687                             contents.variant.expect("destructed const of adt without variant idx");
688                         let variant_def = &def.variant(variant_idx);
689
690                         self.push("V");
691                         self = self.print_def_path(variant_def.def_id, substs)?;
692
693                         match variant_def.ctor_kind() {
694                             Some(CtorKind::Const) => {
695                                 self.push("U");
696                             }
697                             Some(CtorKind::Fn) => {
698                                 self.push("T");
699                                 self = print_field_list(self)?;
700                             }
701                             None => {
702                                 self.push("S");
703                                 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
704                                     // HACK(eddyb) this mimics `path_append`,
705                                     // instead of simply using `field_def.ident`,
706                                     // just to be able to handle disambiguators.
707                                     let disambiguated_field =
708                                         self.tcx.def_key(field_def.did).disambiguated_data;
709                                     let field_name = disambiguated_field.data.get_opt_name();
710                                     self.push_disambiguator(
711                                         disambiguated_field.disambiguator as u64,
712                                     );
713                                     self.push_ident(field_name.unwrap_or(kw::Empty).as_str());
714
715                                     self = field.print(self)?;
716                                 }
717                                 self.push("E");
718                             }
719                         }
720                     }
721                     _ => unreachable!(),
722                 }
723             }
724             _ => {
725                 bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct.ty(), ct);
726             }
727         }
728
729         // Only cache consts that do not refer to an enclosing
730         // binder (which would change depending on context).
731         if !ct.has_escaping_bound_vars() {
732             self.consts.insert(ct, start);
733         }
734         Ok(self)
735     }
736
737     fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
738         self.push("C");
739         let stable_crate_id = self.tcx.def_path_hash(cnum.as_def_id()).stable_crate_id();
740         self.push_disambiguator(stable_crate_id.to_u64());
741         let name = self.tcx.crate_name(cnum);
742         self.push_ident(name.as_str());
743         Ok(self)
744     }
745
746     fn path_qualified(
747         mut self,
748         self_ty: Ty<'tcx>,
749         trait_ref: Option<ty::TraitRef<'tcx>>,
750     ) -> Result<Self::Path, Self::Error> {
751         assert!(trait_ref.is_some());
752         let trait_ref = trait_ref.unwrap();
753
754         self.push("Y");
755         self = self_ty.print(self)?;
756         self.print_def_path(trait_ref.def_id, trait_ref.substs)
757     }
758
759     fn path_append_impl(
760         self,
761         _: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
762         _: &DisambiguatedDefPathData,
763         _: Ty<'tcx>,
764         _: Option<ty::TraitRef<'tcx>>,
765     ) -> Result<Self::Path, Self::Error> {
766         // Inlined into `print_impl_path`
767         unreachable!()
768     }
769
770     fn path_append(
771         self,
772         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
773         disambiguated_data: &DisambiguatedDefPathData,
774     ) -> Result<Self::Path, Self::Error> {
775         let ns = match disambiguated_data.data {
776             // Extern block segments can be skipped, names from extern blocks
777             // are effectively living in their parent modules.
778             DefPathData::ForeignMod => return print_prefix(self),
779
780             // Uppercase categories are more stable than lowercase ones.
781             DefPathData::TypeNs(_) => 't',
782             DefPathData::ValueNs(_) => 'v',
783             DefPathData::ClosureExpr => 'C',
784             DefPathData::Ctor => 'c',
785             DefPathData::AnonConst => 'k',
786             DefPathData::ImplTrait => 'i',
787
788             // These should never show up as `path_append` arguments.
789             DefPathData::CrateRoot
790             | DefPathData::Use
791             | DefPathData::GlobalAsm
792             | DefPathData::Impl
793             | DefPathData::MacroNs(_)
794             | DefPathData::LifetimeNs(_) => {
795                 bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
796             }
797         };
798
799         let name = disambiguated_data.data.get_opt_name();
800
801         self.path_append_ns(
802             print_prefix,
803             ns,
804             disambiguated_data.disambiguator as u64,
805             name.unwrap_or(kw::Empty).as_str(),
806         )
807     }
808
809     fn path_generic_args(
810         mut self,
811         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
812         args: &[GenericArg<'tcx>],
813     ) -> Result<Self::Path, Self::Error> {
814         // Don't print any regions if they're all erased.
815         let print_regions = args.iter().any(|arg| match arg.unpack() {
816             GenericArgKind::Lifetime(r) => !r.is_erased(),
817             _ => false,
818         });
819         let args = args.iter().cloned().filter(|arg| match arg.unpack() {
820             GenericArgKind::Lifetime(_) => print_regions,
821             _ => true,
822         });
823
824         if args.clone().next().is_none() {
825             return print_prefix(self);
826         }
827
828         self.push("I");
829         self = print_prefix(self)?;
830         for arg in args {
831             match arg.unpack() {
832                 GenericArgKind::Lifetime(lt) => {
833                     self = lt.print(self)?;
834                 }
835                 GenericArgKind::Type(ty) => {
836                     self = ty.print(self)?;
837                 }
838                 GenericArgKind::Const(c) => {
839                     self.push("K");
840                     self = c.print(self)?;
841                 }
842             }
843         }
844         self.push("E");
845
846         Ok(self)
847     }
848 }