]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_symbol_mangling/src/v0.rs
Rollup merge of #91519 - petrochenkov:cratexp2, r=Aaron1011
[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<&'tcx 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()
321             && substs.iter().any(|a| a.definitely_has_param_types_or_consts(self.tcx))
322         {
323             self = self.path_generic_args(
324                 |this| {
325                     this.path_append_ns(
326                         |cx| cx.print_def_path(parent_def_id, &[]),
327                         'I',
328                         key.disambiguated_data.disambiguator as u64,
329                         "",
330                     )
331                 },
332                 substs,
333             )?;
334         } else {
335             self.push_disambiguator(key.disambiguated_data.disambiguator as u64);
336             self = self.print_def_path(parent_def_id, &[])?;
337         }
338
339         self = self_ty.print(self)?;
340
341         if let Some(trait_ref) = impl_trait_ref {
342             self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?;
343         }
344
345         Ok(self)
346     }
347
348     fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
349         let i = match *region {
350             // Erased lifetimes use the index 0, for a
351             // shorter mangling of `L_`.
352             ty::ReErased => 0,
353
354             // Late-bound lifetimes use indices starting at 1,
355             // see `BinderLevel` for more details.
356             ty::ReLateBound(debruijn, ty::BoundRegion { kind: ty::BrAnon(i), .. }) => {
357                 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
358                 let depth = binder.lifetime_depths.start + i;
359
360                 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
361             }
362
363             _ => bug!("symbol_names: non-erased region `{:?}`", region),
364         };
365         self.push("L");
366         self.push_integer_62(i as u64);
367         Ok(self)
368     }
369
370     fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
371         // Basic types, never cached (single-character).
372         let basic_type = match ty.kind() {
373             ty::Bool => "b",
374             ty::Char => "c",
375             ty::Str => "e",
376             ty::Tuple(_) if ty.is_unit() => "u",
377             ty::Int(IntTy::I8) => "a",
378             ty::Int(IntTy::I16) => "s",
379             ty::Int(IntTy::I32) => "l",
380             ty::Int(IntTy::I64) => "x",
381             ty::Int(IntTy::I128) => "n",
382             ty::Int(IntTy::Isize) => "i",
383             ty::Uint(UintTy::U8) => "h",
384             ty::Uint(UintTy::U16) => "t",
385             ty::Uint(UintTy::U32) => "m",
386             ty::Uint(UintTy::U64) => "y",
387             ty::Uint(UintTy::U128) => "o",
388             ty::Uint(UintTy::Usize) => "j",
389             ty::Float(FloatTy::F32) => "f",
390             ty::Float(FloatTy::F64) => "d",
391             ty::Never => "z",
392
393             // Placeholders (should be demangled as `_`).
394             ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => "p",
395
396             _ => "",
397         };
398         if !basic_type.is_empty() {
399             self.push(basic_type);
400             return Ok(self);
401         }
402
403         if let Some(&i) = self.types.get(&ty) {
404             return self.print_backref(i);
405         }
406         let start = self.out.len();
407
408         match *ty.kind() {
409             // Basic types, handled above.
410             ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
411                 unreachable!()
412             }
413             ty::Tuple(_) if ty.is_unit() => unreachable!(),
414
415             // Placeholders, also handled as part of basic types.
416             ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => {
417                 unreachable!()
418             }
419
420             ty::Ref(r, ty, mutbl) => {
421                 self.push(match mutbl {
422                     hir::Mutability::Not => "R",
423                     hir::Mutability::Mut => "Q",
424                 });
425                 if *r != ty::ReErased {
426                     self = r.print(self)?;
427                 }
428                 self = ty.print(self)?;
429             }
430
431             ty::RawPtr(mt) => {
432                 self.push(match mt.mutbl {
433                     hir::Mutability::Not => "P",
434                     hir::Mutability::Mut => "O",
435                 });
436                 self = mt.ty.print(self)?;
437             }
438
439             ty::Array(ty, len) => {
440                 self.push("A");
441                 self = ty.print(self)?;
442                 self = self.print_const(len)?;
443             }
444             ty::Slice(ty) => {
445                 self.push("S");
446                 self = ty.print(self)?;
447             }
448
449             ty::Tuple(tys) => {
450                 self.push("T");
451                 for ty in tys.iter().map(|k| k.expect_ty()) {
452                     self = ty.print(self)?;
453                 }
454                 self.push("E");
455             }
456
457             // Mangle all nominal types as paths.
458             ty::Adt(&ty::AdtDef { did: def_id, .. }, substs)
459             | ty::FnDef(def_id, substs)
460             | ty::Opaque(def_id, substs)
461             | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
462             | ty::Closure(def_id, substs)
463             | ty::Generator(def_id, substs, _) => {
464                 self = self.print_def_path(def_id, substs)?;
465             }
466             ty::Foreign(def_id) => {
467                 self = self.print_def_path(def_id, &[])?;
468             }
469
470             ty::FnPtr(sig) => {
471                 self.push("F");
472                 self = self.in_binder(&sig, |mut cx, sig| {
473                     if sig.unsafety == hir::Unsafety::Unsafe {
474                         cx.push("U");
475                     }
476                     match sig.abi {
477                         Abi::Rust => {}
478                         Abi::C { unwind: false } => cx.push("KC"),
479                         abi => {
480                             cx.push("K");
481                             let name = abi.name();
482                             if name.contains('-') {
483                                 cx.push_ident(&name.replace('-', "_"));
484                             } else {
485                                 cx.push_ident(name);
486                             }
487                         }
488                     }
489                     for &ty in sig.inputs() {
490                         cx = ty.print(cx)?;
491                     }
492                     if sig.c_variadic {
493                         cx.push("v");
494                     }
495                     cx.push("E");
496                     sig.output().print(cx)
497                 })?;
498             }
499
500             ty::Dynamic(predicates, r) => {
501                 self.push("D");
502                 self = self.print_dyn_existential(predicates)?;
503                 self = r.print(self)?;
504             }
505
506             ty::GeneratorWitness(_) => bug!("symbol_names: unexpected `GeneratorWitness`"),
507         }
508
509         // Only cache types that do not refer to an enclosing
510         // binder (which would change depending on context).
511         if !ty.has_escaping_bound_vars() {
512             self.types.insert(ty, start);
513         }
514         Ok(self)
515     }
516
517     fn print_dyn_existential(
518         mut self,
519         predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
520     ) -> Result<Self::DynExistential, Self::Error> {
521         // Okay, so this is a bit tricky. Imagine we have a trait object like
522         // `dyn for<'a> Foo<'a, Bar = &'a ()>`. When we mangle this, the
523         // output looks really close to the syntax, where the `Bar = &'a ()` bit
524         // is under the same binders (`['a]`) as the `Foo<'a>` bit. However, we
525         // actually desugar these into two separate `ExistentialPredicate`s. We
526         // can't enter/exit the "binder scope" twice though, because then we
527         // would mangle the binders twice. (Also, side note, we merging these
528         // two is kind of difficult, because of potential HRTBs in the Projection
529         // predicate.)
530         //
531         // Also worth mentioning: imagine that we instead had
532         // `dyn for<'a> Foo<'a, Bar = &'a ()> + Send`. In this case, `Send` is
533         // under the same binders as `Foo`. Currently, this doesn't matter,
534         // because only *auto traits* are allowed other than the principal trait
535         // and all auto traits don't have any generics. Two things could
536         // make this not an "okay" mangling:
537         // 1) Instead of mangling only *used*
538         // bound vars, we want to mangle *all* bound vars (`for<'b> Send` is a
539         // valid trait predicate);
540         // 2) We allow multiple "principal" traits in the future, or at least
541         // allow in any form another trait predicate that can take generics.
542         //
543         // Here we assume that predicates have the following structure:
544         // [<Trait> [{<Projection>}]] [{<Auto>}]
545         // Since any predicates after the first one shouldn't change the binders,
546         // just put them all in the binders of the first.
547         self = self.in_binder(&predicates[0], |mut cx, _| {
548             for predicate in predicates.iter() {
549                 // It would be nice to be able to validate bound vars here, but
550                 // projections can actually include bound vars from super traits
551                 // because of HRTBs (only in the `Self` type). Also, auto traits
552                 // could have different bound vars *anyways*.
553                 match predicate.as_ref().skip_binder() {
554                     ty::ExistentialPredicate::Trait(trait_ref) => {
555                         // Use a type that can't appear in defaults of type parameters.
556                         let dummy_self = cx.tcx.mk_ty_infer(ty::FreshTy(0));
557                         let trait_ref = trait_ref.with_self_ty(cx.tcx, dummy_self);
558                         cx = cx.print_def_path(trait_ref.def_id, trait_ref.substs)?;
559                     }
560                     ty::ExistentialPredicate::Projection(projection) => {
561                         let name = cx.tcx.associated_item(projection.item_def_id).ident;
562                         cx.push("p");
563                         cx.push_ident(name.as_str());
564                         cx = projection.ty.print(cx)?;
565                     }
566                     ty::ExistentialPredicate::AutoTrait(def_id) => {
567                         cx = cx.print_def_path(*def_id, &[])?;
568                     }
569                 }
570             }
571             Ok(cx)
572         })?;
573
574         self.push("E");
575         Ok(self)
576     }
577
578     fn print_const(mut self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
579         // We only mangle a typed value if the const can be evaluated.
580         let ct = ct.eval(self.tcx, ty::ParamEnv::reveal_all());
581         match ct.val {
582             ty::ConstKind::Value(_) => {}
583
584             // Placeholders (should be demangled as `_`).
585             // NOTE(eddyb) despite `Unevaluated` having a `DefId` (and therefore
586             // a path), even for it we still need to encode a placeholder, as
587             // the path could refer back to e.g. an `impl` using the constant.
588             ty::ConstKind::Unevaluated(_)
589             | ty::ConstKind::Param(_)
590             | ty::ConstKind::Infer(_)
591             | ty::ConstKind::Bound(..)
592             | ty::ConstKind::Placeholder(_)
593             | ty::ConstKind::Error(_) => {
594                 // Never cached (single-character).
595                 self.push("p");
596                 return Ok(self);
597             }
598         }
599
600         if let Some(&i) = self.consts.get(&ct) {
601             return self.print_backref(i);
602         }
603         let start = self.out.len();
604
605         match ct.ty.kind() {
606             ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Char => {
607                 self = ct.ty.print(self)?;
608
609                 let mut bits = ct.eval_bits(self.tcx, ty::ParamEnv::reveal_all(), ct.ty);
610
611                 // Negative integer values are mangled using `n` as a "sign prefix".
612                 if let ty::Int(ity) = ct.ty.kind() {
613                     let val =
614                         Integer::from_int_ty(&self.tcx, *ity).size().sign_extend(bits) as i128;
615                     if val < 0 {
616                         self.push("n");
617                     }
618                     bits = val.unsigned_abs();
619                 }
620
621                 let _ = write!(self.out, "{:x}_", bits);
622             }
623
624             // HACK(eddyb) because `ty::Const` only supports sized values (for now),
625             // we can't use `deref_const` + supporting `str`, we have to specially
626             // handle `&str` and include both `&` ("R") and `str` ("e") prefixes.
627             ty::Ref(_, ty, hir::Mutability::Not) if *ty == self.tcx.types.str_ => {
628                 self.push("R");
629                 match ct.val {
630                     ty::ConstKind::Value(ConstValue::Slice { data, start, end }) => {
631                         // NOTE(eddyb) the following comment was kept from `ty::print::pretty`:
632                         // The `inspect` here is okay since we checked the bounds, and there are no
633                         // relocations (we have an active `str` reference here). We don't use this
634                         // result to affect interpreter execution.
635                         let slice =
636                             data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
637                         let s = std::str::from_utf8(slice).expect("non utf8 str from miri");
638
639                         self.push("e");
640                         // FIXME(eddyb) use a specialized hex-encoding loop.
641                         for byte in s.bytes() {
642                             let _ = write!(self.out, "{:02x}", byte);
643                         }
644                         self.push("_");
645                     }
646
647                     _ => {
648                         bug!("symbol_names: unsupported `&str` constant: {:?}", ct);
649                     }
650                 }
651             }
652
653             ty::Ref(_, _, mutbl) => {
654                 self.push(match mutbl {
655                     hir::Mutability::Not => "R",
656                     hir::Mutability::Mut => "Q",
657                 });
658                 self = self.tcx.deref_const(ty::ParamEnv::reveal_all().and(ct)).print(self)?;
659             }
660
661             ty::Array(..) | ty::Tuple(..) | ty::Adt(..) => {
662                 let contents = self.tcx.destructure_const(ty::ParamEnv::reveal_all().and(ct));
663                 let fields = contents.fields.iter().copied();
664
665                 let print_field_list = |mut this: Self| {
666                     for field in fields.clone() {
667                         this = field.print(this)?;
668                     }
669                     this.push("E");
670                     Ok(this)
671                 };
672
673                 match *ct.ty.kind() {
674                     ty::Array(..) => {
675                         self.push("A");
676                         self = print_field_list(self)?;
677                     }
678                     ty::Tuple(..) => {
679                         self.push("T");
680                         self = print_field_list(self)?;
681                     }
682                     ty::Adt(def, substs) => {
683                         let variant_idx =
684                             contents.variant.expect("destructed const of adt without variant idx");
685                         let variant_def = &def.variants[variant_idx];
686
687                         self.push("V");
688                         self = self.print_def_path(variant_def.def_id, substs)?;
689
690                         match variant_def.ctor_kind {
691                             CtorKind::Const => {
692                                 self.push("U");
693                             }
694                             CtorKind::Fn => {
695                                 self.push("T");
696                                 self = print_field_list(self)?;
697                             }
698                             CtorKind::Fictive => {
699                                 self.push("S");
700                                 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
701                                     // HACK(eddyb) this mimics `path_append`,
702                                     // instead of simply using `field_def.ident`,
703                                     // just to be able to handle disambiguators.
704                                     let disambiguated_field =
705                                         self.tcx.def_key(field_def.did).disambiguated_data;
706                                     let field_name = disambiguated_field.data.get_opt_name();
707                                     self.push_disambiguator(
708                                         disambiguated_field.disambiguator as u64,
709                                     );
710                                     self.push_ident(field_name.unwrap_or(kw::Empty).as_str());
711
712                                     self = field.print(self)?;
713                                 }
714                                 self.push("E");
715                             }
716                         }
717                     }
718                     _ => unreachable!(),
719                 }
720             }
721
722             _ => {
723                 bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct.ty, ct);
724             }
725         }
726
727         // Only cache consts that do not refer to an enclosing
728         // binder (which would change depending on context).
729         if !ct.has_escaping_bound_vars() {
730             self.consts.insert(ct, start);
731         }
732         Ok(self)
733     }
734
735     fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
736         self.push("C");
737         let stable_crate_id = self.tcx.def_path_hash(cnum.as_def_id()).stable_crate_id();
738         self.push_disambiguator(stable_crate_id.to_u64());
739         let name = self.tcx.crate_name(cnum);
740         self.push_ident(name.as_str());
741         Ok(self)
742     }
743
744     fn path_qualified(
745         mut self,
746         self_ty: Ty<'tcx>,
747         trait_ref: Option<ty::TraitRef<'tcx>>,
748     ) -> Result<Self::Path, Self::Error> {
749         assert!(trait_ref.is_some());
750         let trait_ref = trait_ref.unwrap();
751
752         self.push("Y");
753         self = self_ty.print(self)?;
754         self.print_def_path(trait_ref.def_id, trait_ref.substs)
755     }
756
757     fn path_append_impl(
758         self,
759         _: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
760         _: &DisambiguatedDefPathData,
761         _: Ty<'tcx>,
762         _: Option<ty::TraitRef<'tcx>>,
763     ) -> Result<Self::Path, Self::Error> {
764         // Inlined into `print_impl_path`
765         unreachable!()
766     }
767
768     fn path_append(
769         self,
770         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
771         disambiguated_data: &DisambiguatedDefPathData,
772     ) -> Result<Self::Path, Self::Error> {
773         let ns = match disambiguated_data.data {
774             // FIXME: It shouldn't be necessary to add anything for extern block segments,
775             // but we add 't' for backward compatibility.
776             DefPathData::ForeignMod => 't',
777
778             // Uppercase categories are more stable than lowercase ones.
779             DefPathData::TypeNs(_) => 't',
780             DefPathData::ValueNs(_) => 'v',
781             DefPathData::ClosureExpr => 'C',
782             DefPathData::Ctor => 'c',
783             DefPathData::AnonConst => 'k',
784             DefPathData::ImplTrait => 'i',
785
786             // These should never show up as `path_append` arguments.
787             DefPathData::CrateRoot
788             | DefPathData::Misc
789             | DefPathData::Impl
790             | DefPathData::MacroNs(_)
791             | DefPathData::LifetimeNs(_) => {
792                 bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
793             }
794         };
795
796         let name = disambiguated_data.data.get_opt_name();
797
798         self.path_append_ns(
799             print_prefix,
800             ns,
801             disambiguated_data.disambiguator as u64,
802             name.unwrap_or(kw::Empty).as_str(),
803         )
804     }
805
806     fn path_generic_args(
807         mut self,
808         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
809         args: &[GenericArg<'tcx>],
810     ) -> Result<Self::Path, Self::Error> {
811         // Don't print any regions if they're all erased.
812         let print_regions = args.iter().any(|arg| match arg.unpack() {
813             GenericArgKind::Lifetime(r) => *r != ty::ReErased,
814             _ => false,
815         });
816         let args = args.iter().cloned().filter(|arg| match arg.unpack() {
817             GenericArgKind::Lifetime(_) => print_regions,
818             _ => true,
819         });
820
821         if args.clone().next().is_none() {
822             return print_prefix(self);
823         }
824
825         self.push("I");
826         self = print_prefix(self)?;
827         for arg in args {
828             match arg.unpack() {
829                 GenericArgKind::Lifetime(lt) => {
830                     self = lt.print(self)?;
831                 }
832                 GenericArgKind::Type(ty) => {
833                     self = ty.print(self)?;
834                 }
835                 GenericArgKind::Const(c) => {
836                     self.push("K");
837                     self = c.print(self)?;
838                 }
839             }
840         }
841         self.push("E");
842
843         Ok(self)
844     }
845 }