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