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