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