]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_symbol_mangling/src/v0.rs
New upstream version 1.48.0~beta.8+dfsg1
[rustc.git] / compiler / rustc_symbol_mangling / src / 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 if let Some('_' | '0'..='9') = ident.chars().next() {
156 self.push("_");
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
189 T: TypeFoldable<'tcx>,
190 {
191 let regions = if value.has_late_bound_regions() {
192 self.tcx.collect_referenced_late_bound_regions(value)
193 } else {
194 FxHashSet::default()
195 };
196
197 let mut lifetime_depths =
198 self.binders.last().map(|b| b.lifetime_depths.end).map_or(0..0, |i| i..i);
199
200 let lifetimes = regions
201 .into_iter()
202 .map(|br| {
203 match br {
204 ty::BrAnon(i) => {
205 // FIXME(eddyb) for some reason, `anonymize_late_bound_regions` starts at `1`.
206 assert_ne!(i, 0);
207 i - 1
208 }
209 _ => bug!("symbol_names: non-anonymized region `{:?}` in `{:?}`", br, value),
210 }
211 })
212 .max()
213 .map_or(0, |max| max + 1);
214
215 self.push_opt_integer_62("G", lifetimes as u64);
216 lifetime_depths.end += lifetimes;
217
218 self.binders.push(BinderLevel { lifetime_depths });
219 self = print_value(self, value.as_ref().skip_binder())?;
220 self.binders.pop();
221
222 Ok(self)
223 }
224 }
225
226 impl Printer<'tcx> for SymbolMangler<'tcx> {
227 type Error = !;
228
229 type Path = Self;
230 type Region = Self;
231 type Type = Self;
232 type DynExistential = Self;
233 type Const = Self;
234
235 fn tcx(&self) -> TyCtxt<'tcx> {
236 self.tcx
237 }
238
239 fn print_def_path(
240 mut self,
241 def_id: DefId,
242 substs: &'tcx [GenericArg<'tcx>],
243 ) -> Result<Self::Path, Self::Error> {
244 if let Some(&i) = self.compress.as_ref().and_then(|c| c.paths.get(&(def_id, substs))) {
245 return self.print_backref(i);
246 }
247 let start = self.out.len();
248
249 self = self.default_print_def_path(def_id, substs)?;
250
251 // Only cache paths that do not refer to an enclosing
252 // binder (which would change depending on context).
253 if !substs.iter().any(|k| k.has_escaping_bound_vars()) {
254 if let Some(c) = &mut self.compress {
255 c.paths.insert((def_id, substs), start);
256 }
257 }
258 Ok(self)
259 }
260
261 fn print_impl_path(
262 self,
263 impl_def_id: DefId,
264 substs: &'tcx [GenericArg<'tcx>],
265 mut self_ty: Ty<'tcx>,
266 mut impl_trait_ref: Option<ty::TraitRef<'tcx>>,
267 ) -> Result<Self::Path, Self::Error> {
268 let key = self.tcx.def_key(impl_def_id);
269 let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
270
271 let mut param_env = self.tcx.param_env_reveal_all_normalized(impl_def_id);
272 if !substs.is_empty() {
273 param_env = param_env.subst(self.tcx, substs);
274 }
275
276 match &mut impl_trait_ref {
277 Some(impl_trait_ref) => {
278 assert_eq!(impl_trait_ref.self_ty(), self_ty);
279 *impl_trait_ref = self.tcx.normalize_erasing_regions(param_env, *impl_trait_ref);
280 self_ty = impl_trait_ref.self_ty();
281 }
282 None => {
283 self_ty = self.tcx.normalize_erasing_regions(param_env, self_ty);
284 }
285 }
286
287 self.path_append_impl(
288 |cx| cx.print_def_path(parent_def_id, &[]),
289 &key.disambiguated_data,
290 self_ty,
291 impl_trait_ref,
292 )
293 }
294
295 fn print_region(mut self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
296 let i = match *region {
297 // Erased lifetimes use the index 0, for a
298 // shorter mangling of `L_`.
299 ty::ReErased => 0,
300
301 // Late-bound lifetimes use indices starting at 1,
302 // see `BinderLevel` for more details.
303 ty::ReLateBound(debruijn, ty::BrAnon(i)) => {
304 // FIXME(eddyb) for some reason, `anonymize_late_bound_regions` starts at `1`.
305 assert_ne!(i, 0);
306 let i = i - 1;
307
308 let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
309 let depth = binder.lifetime_depths.start + i;
310
311 1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
312 }
313
314 _ => bug!("symbol_names: non-erased region `{:?}`", region),
315 };
316 self.push("L");
317 self.push_integer_62(i as u64);
318 Ok(self)
319 }
320
321 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
322 // Basic types, never cached (single-character).
323 let basic_type = match ty.kind() {
324 ty::Bool => "b",
325 ty::Char => "c",
326 ty::Str => "e",
327 ty::Tuple(_) if ty.is_unit() => "u",
328 ty::Int(IntTy::I8) => "a",
329 ty::Int(IntTy::I16) => "s",
330 ty::Int(IntTy::I32) => "l",
331 ty::Int(IntTy::I64) => "x",
332 ty::Int(IntTy::I128) => "n",
333 ty::Int(IntTy::Isize) => "i",
334 ty::Uint(UintTy::U8) => "h",
335 ty::Uint(UintTy::U16) => "t",
336 ty::Uint(UintTy::U32) => "m",
337 ty::Uint(UintTy::U64) => "y",
338 ty::Uint(UintTy::U128) => "o",
339 ty::Uint(UintTy::Usize) => "j",
340 ty::Float(FloatTy::F32) => "f",
341 ty::Float(FloatTy::F64) => "d",
342 ty::Never => "z",
343
344 // Placeholders (should be demangled as `_`).
345 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => "p",
346
347 _ => "",
348 };
349 if !basic_type.is_empty() {
350 self.push(basic_type);
351 return Ok(self);
352 }
353
354 if let Some(&i) = self.compress.as_ref().and_then(|c| c.types.get(&ty)) {
355 return self.print_backref(i);
356 }
357 let start = self.out.len();
358
359 match *ty.kind() {
360 // Basic types, handled above.
361 ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
362 unreachable!()
363 }
364 ty::Tuple(_) if ty.is_unit() => unreachable!(),
365
366 // Placeholders, also handled as part of basic types.
367 ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => {
368 unreachable!()
369 }
370
371 ty::Ref(r, ty, mutbl) => {
372 self.push(match mutbl {
373 hir::Mutability::Not => "R",
374 hir::Mutability::Mut => "Q",
375 });
376 if *r != ty::ReErased {
377 self = r.print(self)?;
378 }
379 self = ty.print(self)?;
380 }
381
382 ty::RawPtr(mt) => {
383 self.push(match mt.mutbl {
384 hir::Mutability::Not => "P",
385 hir::Mutability::Mut => "O",
386 });
387 self = mt.ty.print(self)?;
388 }
389
390 ty::Array(ty, len) => {
391 self.push("A");
392 self = ty.print(self)?;
393 self = self.print_const(len)?;
394 }
395 ty::Slice(ty) => {
396 self.push("S");
397 self = ty.print(self)?;
398 }
399
400 ty::Tuple(tys) => {
401 self.push("T");
402 for ty in tys.iter().map(|k| k.expect_ty()) {
403 self = ty.print(self)?;
404 }
405 self.push("E");
406 }
407
408 // Mangle all nominal types as paths.
409 ty::Adt(&ty::AdtDef { did: def_id, .. }, substs)
410 | ty::FnDef(def_id, substs)
411 | ty::Opaque(def_id, substs)
412 | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
413 | ty::Closure(def_id, substs)
414 | ty::Generator(def_id, substs, _) => {
415 self = self.print_def_path(def_id, substs)?;
416 }
417 ty::Foreign(def_id) => {
418 self = self.print_def_path(def_id, &[])?;
419 }
420
421 ty::FnPtr(sig) => {
422 self.push("F");
423 self = self.in_binder(&sig, |mut cx, sig| {
424 if sig.unsafety == hir::Unsafety::Unsafe {
425 cx.push("U");
426 }
427 match sig.abi {
428 Abi::Rust => {}
429 Abi::C => cx.push("KC"),
430 abi => {
431 cx.push("K");
432 let name = abi.name();
433 if name.contains('-') {
434 cx.push_ident(&name.replace('-', "_"));
435 } else {
436 cx.push_ident(name);
437 }
438 }
439 }
440 for &ty in sig.inputs() {
441 cx = ty.print(cx)?;
442 }
443 if sig.c_variadic {
444 cx.push("v");
445 }
446 cx.push("E");
447 sig.output().print(cx)
448 })?;
449 }
450
451 ty::Dynamic(predicates, r) => {
452 self.push("D");
453 self = self.in_binder(&predicates, |cx, predicates| {
454 cx.print_dyn_existential(predicates)
455 })?;
456 self = r.print(self)?;
457 }
458
459 ty::GeneratorWitness(_) => bug!("symbol_names: unexpected `GeneratorWitness`"),
460 }
461
462 // Only cache types that do not refer to an enclosing
463 // binder (which would change depending on context).
464 if !ty.has_escaping_bound_vars() {
465 if let Some(c) = &mut self.compress {
466 c.types.insert(ty, start);
467 }
468 }
469 Ok(self)
470 }
471
472 fn print_dyn_existential(
473 mut self,
474 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
475 ) -> Result<Self::DynExistential, Self::Error> {
476 for predicate in predicates {
477 match predicate {
478 ty::ExistentialPredicate::Trait(trait_ref) => {
479 // Use a type that can't appear in defaults of type parameters.
480 let dummy_self = self.tcx.mk_ty_infer(ty::FreshTy(0));
481 let trait_ref = trait_ref.with_self_ty(self.tcx, dummy_self);
482 self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?;
483 }
484 ty::ExistentialPredicate::Projection(projection) => {
485 let name = self.tcx.associated_item(projection.item_def_id).ident;
486 self.push("p");
487 self.push_ident(&name.as_str());
488 self = projection.ty.print(self)?;
489 }
490 ty::ExistentialPredicate::AutoTrait(def_id) => {
491 self = self.print_def_path(def_id, &[])?;
492 }
493 }
494 }
495 self.push("E");
496 Ok(self)
497 }
498
499 fn print_const(mut self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
500 if let Some(&i) = self.compress.as_ref().and_then(|c| c.consts.get(&ct)) {
501 return self.print_backref(i);
502 }
503 let start = self.out.len();
504
505 match ct.ty.kind() {
506 ty::Uint(_) => {}
507 ty::Bool => {}
508 _ => {
509 bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct.ty, ct);
510 }
511 }
512 self = ct.ty.print(self)?;
513
514 if let Some(bits) = ct.try_eval_bits(self.tcx, ty::ParamEnv::reveal_all(), ct.ty) {
515 let _ = write!(self.out, "{:x}_", bits);
516 } else {
517 // NOTE(eddyb) despite having the path, we need to
518 // encode a placeholder, as the path could refer
519 // back to e.g. an `impl` using the constant.
520 self.push("p");
521 }
522
523 // Only cache consts that do not refer to an enclosing
524 // binder (which would change depending on context).
525 if !ct.has_escaping_bound_vars() {
526 if let Some(c) = &mut self.compress {
527 c.consts.insert(ct, start);
528 }
529 }
530 Ok(self)
531 }
532
533 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
534 self.push("C");
535 let fingerprint = self.tcx.crate_disambiguator(cnum).to_fingerprint();
536 self.push_disambiguator(fingerprint.to_smaller_hash());
537 let name = self.tcx.original_crate_name(cnum).as_str();
538 self.push_ident(&name);
539 Ok(self)
540 }
541 fn path_qualified(
542 mut self,
543 self_ty: Ty<'tcx>,
544 trait_ref: Option<ty::TraitRef<'tcx>>,
545 ) -> Result<Self::Path, Self::Error> {
546 assert!(trait_ref.is_some());
547 let trait_ref = trait_ref.unwrap();
548
549 self.push("Y");
550 self = self_ty.print(self)?;
551 self.print_def_path(trait_ref.def_id, trait_ref.substs)
552 }
553
554 fn path_append_impl(
555 mut self,
556 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
557 disambiguated_data: &DisambiguatedDefPathData,
558 self_ty: Ty<'tcx>,
559 trait_ref: Option<ty::TraitRef<'tcx>>,
560 ) -> Result<Self::Path, Self::Error> {
561 self.push(match trait_ref {
562 Some(_) => "X",
563 None => "M",
564 });
565 self.push_disambiguator(disambiguated_data.disambiguator as u64);
566 self = print_prefix(self)?;
567 self = self_ty.print(self)?;
568 if let Some(trait_ref) = trait_ref {
569 self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?;
570 }
571 Ok(self)
572 }
573 fn path_append(
574 self,
575 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
576 disambiguated_data: &DisambiguatedDefPathData,
577 ) -> Result<Self::Path, Self::Error> {
578 let ns = match disambiguated_data.data {
579 // Uppercase categories are more stable than lowercase ones.
580 DefPathData::TypeNs(_) => 't',
581 DefPathData::ValueNs(_) => 'v',
582 DefPathData::ClosureExpr => 'C',
583 DefPathData::Ctor => 'c',
584 DefPathData::AnonConst => 'k',
585 DefPathData::ImplTrait => 'i',
586
587 // These should never show up as `path_append` arguments.
588 DefPathData::CrateRoot
589 | DefPathData::Misc
590 | DefPathData::Impl
591 | DefPathData::MacroNs(_)
592 | DefPathData::LifetimeNs(_) => {
593 bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data)
594 }
595 };
596
597 let name = disambiguated_data.data.get_opt_name().map(|s| s.as_str());
598
599 self.path_append_ns(
600 print_prefix,
601 ns,
602 disambiguated_data.disambiguator as u64,
603 name.as_ref().map_or("", |s| &s[..]),
604 )
605 }
606 fn path_generic_args(
607 mut self,
608 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
609 args: &[GenericArg<'tcx>],
610 ) -> Result<Self::Path, Self::Error> {
611 // Don't print any regions if they're all erased.
612 let print_regions = args.iter().any(|arg| match arg.unpack() {
613 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
614 _ => false,
615 });
616 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
617 GenericArgKind::Lifetime(_) => print_regions,
618 _ => true,
619 });
620
621 if args.clone().next().is_none() {
622 return print_prefix(self);
623 }
624
625 self.push("I");
626 self = print_prefix(self)?;
627 for arg in args {
628 match arg.unpack() {
629 GenericArgKind::Lifetime(lt) => {
630 self = lt.print(self)?;
631 }
632 GenericArgKind::Type(ty) => {
633 self = ty.print(self)?;
634 }
635 GenericArgKind::Const(c) => {
636 self.push("K");
637 self = c.print(self)?;
638 }
639 }
640 }
641 self.push("E");
642
643 Ok(self)
644 }
645 }