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