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