]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_symbol_mangling/src/v0.rs
Auto merge of #81362 - ssomers:btree_drainy_refactor_8, r=Mark-Simulacrum
[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_id::{CrateNum, DefId};
5 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
6 use rustc_middle::ty::print::{Print, Printer};
7 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst};
8 use rustc_middle::ty::{self, FloatTy, Instance, IntTy, Ty, TyCtxt, TypeFoldable, UintTy};
9 use rustc_target::spec::abi::Abi;
10
11 use std::fmt::Write;
12 use std::ops::Range;
13
14 pub(super) fn mangle(
15     tcx: TyCtxt<'tcx>,
16     instance: Instance<'tcx>,
17     instantiating_crate: Option<CrateNum>,
18 ) -> String {
19     let def_id = instance.def_id();
20     // FIXME(eddyb) this should ideally not be needed.
21     let substs = tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), instance.substs);
22
23     let prefix = "_R";
24     let mut cx = SymbolMangler {
25         tcx,
26         compress: Some(Box::new(CompressionCaches {
27             start_offset: prefix.len(),
28
29             paths: FxHashMap::default(),
30             types: FxHashMap::default(),
31             consts: FxHashMap::default(),
32         })),
33         binders: vec![],
34         out: String::from(prefix),
35     };
36
37     // Append `::{shim:...#0}` to shims that can coexist with a non-shim instance.
38     let shim_kind = match instance.def {
39         ty::InstanceDef::VtableShim(_) => Some("vtable"),
40         ty::InstanceDef::ReifyShim(_) => Some("reify"),
41
42         _ => None,
43     };
44
45     cx = if let Some(shim_kind) = shim_kind {
46         cx.path_append_ns(|cx| cx.print_def_path(def_id, substs), 'S', 0, shim_kind).unwrap()
47     } else {
48         cx.print_def_path(def_id, substs).unwrap()
49     };
50     if let Some(instantiating_crate) = instantiating_crate {
51         cx = cx.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap();
52     }
53     cx.out
54 }
55
56 struct CompressionCaches<'tcx> {
57     // The length of the prefix in `out` (e.g. 2 for `_R`).
58     start_offset: usize,
59
60     // The values are start positions in `out`, in bytes.
61     paths: FxHashMap<(DefId, &'tcx [GenericArg<'tcx>]), usize>,
62     types: FxHashMap<Ty<'tcx>, usize>,
63     consts: FxHashMap<&'tcx ty::Const<'tcx>, usize>,
64 }
65
66 struct BinderLevel {
67     /// The range of distances from the root of what's
68     /// being printed, to the lifetimes in a binder.
69     /// Specifically, a `BrAnon(i)` lifetime has depth
70     /// `lifetime_depths.start + i`, going away from the
71     /// the root and towards its use site, as `i` increases.
72     /// This is used to flatten rustc's pairing of `BrAnon`
73     /// (intra-binder disambiguation) with a `DebruijnIndex`
74     /// (binder addressing), to "true" de Bruijn indices,
75     /// by subtracting the depth of a certain lifetime, from
76     /// the innermost depth at its use site.
77     lifetime_depths: Range<u32>,
78 }
79
80 struct SymbolMangler<'tcx> {
81     tcx: TyCtxt<'tcx>,
82     compress: Option<Box<CompressionCaches<'tcx>>>,
83     binders: Vec<BinderLevel>,
84     out: String,
85 }
86
87 impl SymbolMangler<'tcx> {
88     fn push(&mut self, s: &str) {
89         self.out.push_str(s);
90     }
91
92     /// Push a `_`-terminated base 62 integer, using the format
93     /// specified in the RFC as `<base-62-number>`, that is:
94     /// * `x = 0` is encoded as just the `"_"` terminator
95     /// * `x > 0` is encoded as `x - 1` in base 62, followed by `"_"`,
96     ///   e.g. `1` becomes `"0_"`, `62` becomes `"Z_"`, etc.
97     fn push_integer_62(&mut self, x: u64) {
98         if let Some(x) = x.checked_sub(1) {
99             base_n::push_str(x as u128, 62, &mut self.out);
100         }
101         self.push("_");
102     }
103
104     /// Push a `tag`-prefixed base 62 integer, when larger than `0`, that is:
105     /// * `x = 0` is encoded as `""` (nothing)
106     /// * `x > 0` is encoded as the `tag` followed by `push_integer_62(x - 1)`
107     ///   e.g. `1` becomes `tag + "_"`, `2` becomes `tag + "0_"`, etc.
108     fn push_opt_integer_62(&mut self, tag: &str, x: u64) {
109         if let Some(x) = x.checked_sub(1) {
110             self.push(tag);
111             self.push_integer_62(x);
112         }
113     }
114
115     fn push_disambiguator(&mut self, dis: u64) {
116         self.push_opt_integer_62("s", dis);
117     }
118
119     fn push_ident(&mut self, ident: &str) {
120         let mut use_punycode = false;
121         for b in ident.bytes() {
122             match b {
123                 b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
124                 0x80..=0xff => use_punycode = true,
125                 _ => bug!("symbol_names: bad byte {} in ident {:?}", b, ident),
126             }
127         }
128
129         let punycode_string;
130         let ident = if use_punycode {
131             self.push("u");
132
133             // FIXME(eddyb) we should probably roll our own punycode implementation.
134             let mut punycode_bytes = match punycode::encode(ident) {
135                 Ok(s) => s.into_bytes(),
136                 Err(()) => bug!("symbol_names: punycode encoding failed for ident {:?}", ident),
137             };
138
139             // Replace `-` with `_`.
140             if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
141                 *c = b'_';
142             }
143
144             // FIXME(eddyb) avoid rechecking UTF-8 validity.
145             punycode_string = String::from_utf8(punycode_bytes).unwrap();
146             &punycode_string
147         } else {
148             ident
149         };
150
151         let _ = write!(self.out, "{}", ident.len());
152
153         // Write a separating `_` if necessary (leading digit or `_`).
154         if let Some('_' | '0'..='9') = ident.chars().next() {
155             self.push("_");
156         }
157
158         self.push(ident);
159     }
160
161     fn path_append_ns(
162         mut self,
163         print_prefix: impl FnOnce(Self) -> Result<Self, !>,
164         ns: char,
165         disambiguator: u64,
166         name: &str,
167     ) -> Result<Self, !> {
168         self.push("N");
169         self.out.push(ns);
170         self = print_prefix(self)?;
171         self.push_disambiguator(disambiguator as u64);
172         self.push_ident(name);
173         Ok(self)
174     }
175
176     fn print_backref(mut self, i: usize) -> Result<Self, !> {
177         self.push("B");
178         self.push_integer_62((i - self.compress.as_ref().unwrap().start_offset) as u64);
179         Ok(self)
180     }
181
182     fn in_binder<T>(
183         mut self,
184         value: &ty::Binder<T>,
185         print_value: impl FnOnce(Self, &T) -> Result<Self, !>,
186     ) -> Result<Self, !>
187     where
188         T: TypeFoldable<'tcx>,
189     {
190         let regions = if value.has_late_bound_regions() {
191             self.tcx.collect_referenced_late_bound_regions(value)
192         } else {
193             FxHashSet::default()
194         };
195
196         let mut lifetime_depths =
197             self.binders.last().map(|b| b.lifetime_depths.end).map_or(0..0, |i| i..i);
198
199         let lifetimes = regions
200             .into_iter()
201             .map(|br| match br {
202                 ty::BrAnon(i) => i,
203                 _ => bug!("symbol_names: non-anonymized region `{:?}` in `{:?}`", br, value),
204             })
205             .max()
206             .map_or(0, |max| max + 1);
207
208         self.push_opt_integer_62("G", lifetimes as u64);
209         lifetime_depths.end += lifetimes;
210
211         self.binders.push(BinderLevel { lifetime_depths });
212         self = print_value(self, value.as_ref().skip_binder())?;
213         self.binders.pop();
214
215         Ok(self)
216     }
217 }
218
219 impl Printer<'tcx> for SymbolMangler<'tcx> {
220     type Error = !;
221
222     type Path = Self;
223     type Region = Self;
224     type Type = Self;
225     type DynExistential = Self;
226     type Const = Self;
227
228     fn tcx(&self) -> TyCtxt<'tcx> {
229         self.tcx
230     }
231
232     fn print_def_path(
233         mut self,
234         def_id: DefId,
235         substs: &'tcx [GenericArg<'tcx>],
236     ) -> Result<Self::Path, Self::Error> {
237         if let Some(&i) = self.compress.as_ref().and_then(|c| c.paths.get(&(def_id, substs))) {
238             return self.print_backref(i);
239         }
240         let start = self.out.len();
241
242         self = self.default_print_def_path(def_id, substs)?;
243
244         // Only cache paths that do not refer to an enclosing
245         // binder (which would change depending on context).
246         if !substs.iter().any(|k| k.has_escaping_bound_vars()) {
247             if let Some(c) = &mut self.compress {
248                 c.paths.insert((def_id, substs), start);
249             }
250         }
251         Ok(self)
252     }
253
254     fn print_impl_path(
255         mut self,
256         impl_def_id: DefId,
257         substs: &'tcx [GenericArg<'tcx>],
258         mut self_ty: Ty<'tcx>,
259         mut impl_trait_ref: Option<ty::TraitRef<'tcx>>,
260     ) -> Result<Self::Path, Self::Error> {
261         let key = self.tcx.def_key(impl_def_id);
262         let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
263
264         let mut param_env = self.tcx.param_env_reveal_all_normalized(impl_def_id);
265         if !substs.is_empty() {
266             param_env = param_env.subst(self.tcx, substs);
267         }
268
269         match &mut impl_trait_ref {
270             Some(impl_trait_ref) => {
271                 assert_eq!(impl_trait_ref.self_ty(), self_ty);
272                 *impl_trait_ref = self.tcx.normalize_erasing_regions(param_env, *impl_trait_ref);
273                 self_ty = impl_trait_ref.self_ty();
274             }
275             None => {
276                 self_ty = self.tcx.normalize_erasing_regions(param_env, self_ty);
277             }
278         }
279
280         self.push(match impl_trait_ref {
281             Some(_) => "X",
282             None => "M",
283         });
284
285         // Encode impl generic params if the substitutions contain parameters (implying
286         // polymorphization is enabled) and this isn't an inherent impl.
287         if impl_trait_ref.is_some() && substs.iter().any(|a| a.has_param_types_or_consts()) {
288             self = self.path_generic_args(
289                 |this| {
290                     this.path_append_ns(
291                         |cx| cx.print_def_path(parent_def_id, &[]),
292                         'I',
293                         key.disambiguated_data.disambiguator as u64,
294                         "",
295                     )
296                 },
297                 substs,
298             )?;
299         } else {
300             self.push_disambiguator(key.disambiguated_data.disambiguator as u64);
301             self = self.print_def_path(parent_def_id, &[])?;
302         }
303
304         self = self_ty.print(self)?;
305
306         if let Some(trait_ref) = impl_trait_ref {
307             self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?;
308         }
309
310         Ok(self)
311     }
312
313     fn print_region(mut self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
314         let i = match *region {
315             // Erased lifetimes use the index 0, for a
316             // shorter mangling of `L_`.
317             ty::ReErased => 0,
318
319             // Late-bound lifetimes use indices starting at 1,
320             // see `BinderLevel` for more details.
321             ty::ReLateBound(debruijn, ty::BoundRegion { kind: ty::BrAnon(i) }) => {
322                 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
323                 let depth = binder.lifetime_depths.start + i;
324
325                 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
326             }
327
328             _ => bug!("symbol_names: non-erased region `{:?}`", region),
329         };
330         self.push("L");
331         self.push_integer_62(i as u64);
332         Ok(self)
333     }
334
335     fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
336         // Basic types, never cached (single-character).
337         let basic_type = match ty.kind() {
338             ty::Bool => "b",
339             ty::Char => "c",
340             ty::Str => "e",
341             ty::Tuple(_) if ty.is_unit() => "u",
342             ty::Int(IntTy::I8) => "a",
343             ty::Int(IntTy::I16) => "s",
344             ty::Int(IntTy::I32) => "l",
345             ty::Int(IntTy::I64) => "x",
346             ty::Int(IntTy::I128) => "n",
347             ty::Int(IntTy::Isize) => "i",
348             ty::Uint(UintTy::U8) => "h",
349             ty::Uint(UintTy::U16) => "t",
350             ty::Uint(UintTy::U32) => "m",
351             ty::Uint(UintTy::U64) => "y",
352             ty::Uint(UintTy::U128) => "o",
353             ty::Uint(UintTy::Usize) => "j",
354             ty::Float(FloatTy::F32) => "f",
355             ty::Float(FloatTy::F64) => "d",
356             ty::Never => "z",
357
358             // Placeholders (should be demangled as `_`).
359             ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => "p",
360
361             _ => "",
362         };
363         if !basic_type.is_empty() {
364             self.push(basic_type);
365             return Ok(self);
366         }
367
368         if let Some(&i) = self.compress.as_ref().and_then(|c| c.types.get(&ty)) {
369             return self.print_backref(i);
370         }
371         let start = self.out.len();
372
373         match *ty.kind() {
374             // Basic types, handled above.
375             ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
376                 unreachable!()
377             }
378             ty::Tuple(_) if ty.is_unit() => unreachable!(),
379
380             // Placeholders, also handled as part of basic types.
381             ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => {
382                 unreachable!()
383             }
384
385             ty::Ref(r, ty, mutbl) => {
386                 self.push(match mutbl {
387                     hir::Mutability::Not => "R",
388                     hir::Mutability::Mut => "Q",
389                 });
390                 if *r != ty::ReErased {
391                     self = r.print(self)?;
392                 }
393                 self = ty.print(self)?;
394             }
395
396             ty::RawPtr(mt) => {
397                 self.push(match mt.mutbl {
398                     hir::Mutability::Not => "P",
399                     hir::Mutability::Mut => "O",
400                 });
401                 self = mt.ty.print(self)?;
402             }
403
404             ty::Array(ty, len) => {
405                 self.push("A");
406                 self = ty.print(self)?;
407                 self = self.print_const(len)?;
408             }
409             ty::Slice(ty) => {
410                 self.push("S");
411                 self = ty.print(self)?;
412             }
413
414             ty::Tuple(tys) => {
415                 self.push("T");
416                 for ty in tys.iter().map(|k| k.expect_ty()) {
417                     self = ty.print(self)?;
418                 }
419                 self.push("E");
420             }
421
422             // Mangle all nominal types as paths.
423             ty::Adt(&ty::AdtDef { did: def_id, .. }, substs)
424             | ty::FnDef(def_id, substs)
425             | ty::Opaque(def_id, substs)
426             | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
427             | ty::Closure(def_id, substs)
428             | ty::Generator(def_id, substs, _) => {
429                 self = self.print_def_path(def_id, substs)?;
430             }
431             ty::Foreign(def_id) => {
432                 self = self.print_def_path(def_id, &[])?;
433             }
434
435             ty::FnPtr(sig) => {
436                 self.push("F");
437                 self = self.in_binder(&sig, |mut cx, sig| {
438                     if sig.unsafety == hir::Unsafety::Unsafe {
439                         cx.push("U");
440                     }
441                     match sig.abi {
442                         Abi::Rust => {}
443                         Abi::C => cx.push("KC"),
444                         abi => {
445                             cx.push("K");
446                             let name = abi.name();
447                             if name.contains('-') {
448                                 cx.push_ident(&name.replace('-', "_"));
449                             } else {
450                                 cx.push_ident(name);
451                             }
452                         }
453                     }
454                     for &ty in sig.inputs() {
455                         cx = ty.print(cx)?;
456                     }
457                     if sig.c_variadic {
458                         cx.push("v");
459                     }
460                     cx.push("E");
461                     sig.output().print(cx)
462                 })?;
463             }
464
465             ty::Dynamic(predicates, r) => {
466                 self.push("D");
467                 self = self.print_dyn_existential(predicates)?;
468                 self = r.print(self)?;
469             }
470
471             ty::GeneratorWitness(_) => bug!("symbol_names: unexpected `GeneratorWitness`"),
472         }
473
474         // Only cache types that do not refer to an enclosing
475         // binder (which would change depending on context).
476         if !ty.has_escaping_bound_vars() {
477             if let Some(c) = &mut self.compress {
478                 c.types.insert(ty, start);
479             }
480         }
481         Ok(self)
482     }
483
484     fn print_dyn_existential(
485         mut self,
486         predicates: &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>,
487     ) -> Result<Self::DynExistential, Self::Error> {
488         for predicate in predicates {
489             self = self.in_binder(&predicate, |mut cx, predicate| {
490                 match predicate {
491                     ty::ExistentialPredicate::Trait(trait_ref) => {
492                         // Use a type that can't appear in defaults of type parameters.
493                         let dummy_self = cx.tcx.mk_ty_infer(ty::FreshTy(0));
494                         let trait_ref = trait_ref.with_self_ty(cx.tcx, dummy_self);
495                         cx = cx.print_def_path(trait_ref.def_id, trait_ref.substs)?;
496                     }
497                     ty::ExistentialPredicate::Projection(projection) => {
498                         let name = cx.tcx.associated_item(projection.item_def_id).ident;
499                         cx.push("p");
500                         cx.push_ident(&name.as_str());
501                         cx = projection.ty.print(cx)?;
502                     }
503                     ty::ExistentialPredicate::AutoTrait(def_id) => {
504                         cx = cx.print_def_path(*def_id, &[])?;
505                     }
506                 }
507                 Ok(cx)
508             })?;
509         }
510         self.push("E");
511         Ok(self)
512     }
513
514     fn print_const(mut self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
515         if let Some(&i) = self.compress.as_ref().and_then(|c| c.consts.get(&ct)) {
516             return self.print_backref(i);
517         }
518         let start = self.out.len();
519
520         let mut neg = false;
521         let val = match ct.ty.kind() {
522             ty::Uint(_) | ty::Bool | ty::Char => {
523                 ct.try_eval_bits(self.tcx, ty::ParamEnv::reveal_all(), ct.ty)
524             }
525             ty::Int(_) => {
526                 let param_env = ty::ParamEnv::reveal_all();
527                 ct.try_eval_bits(self.tcx, param_env, ct.ty).and_then(|b| {
528                     let sz = self.tcx.layout_of(param_env.and(ct.ty)).ok()?.size;
529                     let val = sz.sign_extend(b) as i128;
530                     if val < 0 {
531                         neg = true;
532                     }
533                     Some(val.unsigned_abs())
534                 })
535             }
536             _ => {
537                 bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct.ty, ct);
538             }
539         };
540
541         if let Some(bits) = val {
542             // We only print the type if the const can be evaluated.
543             self = ct.ty.print(self)?;
544             let _ = write!(self.out, "{}{:x}_", if neg { "n" } else { "" }, bits);
545         } else {
546             // NOTE(eddyb) despite having the path, we need to
547             // encode a placeholder, as the path could refer
548             // back to e.g. an `impl` using the constant.
549             self.push("p");
550         }
551
552         // Only cache consts that do not refer to an enclosing
553         // binder (which would change depending on context).
554         if !ct.has_escaping_bound_vars() {
555             if let Some(c) = &mut self.compress {
556                 c.consts.insert(ct, start);
557             }
558         }
559         Ok(self)
560     }
561
562     fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
563         self.push("C");
564         let fingerprint = self.tcx.crate_disambiguator(cnum).to_fingerprint();
565         self.push_disambiguator(fingerprint.to_smaller_hash());
566         let name = self.tcx.original_crate_name(cnum).as_str();
567         self.push_ident(&name);
568         Ok(self)
569     }
570
571     fn path_qualified(
572         mut self,
573         self_ty: Ty<'tcx>,
574         trait_ref: Option<ty::TraitRef<'tcx>>,
575     ) -> Result<Self::Path, Self::Error> {
576         assert!(trait_ref.is_some());
577         let trait_ref = trait_ref.unwrap();
578
579         self.push("Y");
580         self = self_ty.print(self)?;
581         self.print_def_path(trait_ref.def_id, trait_ref.substs)
582     }
583
584     fn path_append_impl(
585         self,
586         _: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
587         _: &DisambiguatedDefPathData,
588         _: Ty<'tcx>,
589         _: Option<ty::TraitRef<'tcx>>,
590     ) -> Result<Self::Path, Self::Error> {
591         // Inlined into `print_impl_path`
592         unreachable!()
593     }
594
595     fn path_append(
596         self,
597         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
598         disambiguated_data: &DisambiguatedDefPathData,
599     ) -> Result<Self::Path, Self::Error> {
600         let ns = match disambiguated_data.data {
601             // Uppercase categories are more stable than lowercase ones.
602             DefPathData::TypeNs(_) => 't',
603             DefPathData::ValueNs(_) => 'v',
604             DefPathData::ClosureExpr => 'C',
605             DefPathData::Ctor => 'c',
606             DefPathData::AnonConst => 'k',
607             DefPathData::ImplTrait => 'i',
608
609             // These should never show up as `path_append` arguments.
610             DefPathData::CrateRoot
611             | DefPathData::Misc
612             | DefPathData::Impl
613             | DefPathData::MacroNs(_)
614             | DefPathData::LifetimeNs(_) => {
615                 bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
616             }
617         };
618
619         let name = disambiguated_data.data.get_opt_name().map(|s| s.as_str());
620
621         self.path_append_ns(
622             print_prefix,
623             ns,
624             disambiguated_data.disambiguator as u64,
625             name.as_ref().map_or("", |s| &s[..]),
626         )
627     }
628
629     fn path_generic_args(
630         mut self,
631         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
632         args: &[GenericArg<'tcx>],
633     ) -> Result<Self::Path, Self::Error> {
634         // Don't print any regions if they're all erased.
635         let print_regions = args.iter().any(|arg| match arg.unpack() {
636             GenericArgKind::Lifetime(r) => *r != ty::ReErased,
637             _ => false,
638         });
639         let args = args.iter().cloned().filter(|arg| match arg.unpack() {
640             GenericArgKind::Lifetime(_) => print_regions,
641             _ => true,
642         });
643
644         if args.clone().next().is_none() {
645             return print_prefix(self);
646         }
647
648         self.push("I");
649         self = print_prefix(self)?;
650         for arg in args {
651             match arg.unpack() {
652                 GenericArgKind::Lifetime(lt) => {
653                     self = lt.print(self)?;
654                 }
655                 GenericArgKind::Type(ty) => {
656                     self = ty.print(self)?;
657                 }
658                 GenericArgKind::Const(c) => {
659                     self.push("K");
660                     self = c.print(self)?;
661                 }
662             }
663         }
664         self.push("E");
665
666         Ok(self)
667     }
668 }