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