]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/print/pretty.rs
Rollup merge of #63285 - Mark-Simulacrum:rm-await-origin, r=Centril
[rust.git] / src / librustc / ty / print / pretty.rs
1 use crate::hir;
2 use crate::hir::def::{Namespace, DefKind};
3 use crate::hir::map::{DefPathData, DisambiguatedDefPathData};
4 use crate::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
5 use crate::middle::cstore::{ExternCrate, ExternCrateSource};
6 use crate::middle::region;
7 use crate::ty::{self, DefIdTree, ParamConst, Ty, TyCtxt, TypeFoldable};
8 use crate::ty::subst::{Kind, Subst, UnpackedKind};
9 use crate::ty::layout::Size;
10 use crate::mir::interpret::{ConstValue, sign_extend, Scalar};
11 use syntax::ast;
12 use rustc_apfloat::ieee::{Double, Single};
13 use rustc_apfloat::Float;
14 use rustc_target::spec::abi::Abi;
15 use syntax::symbol::{kw, InternedString};
16
17 use std::cell::Cell;
18 use std::fmt::{self, Write as _};
19 use std::ops::{Deref, DerefMut};
20
21 // `pretty` is a separate module only for organization.
22 use super::*;
23
24 macro_rules! p {
25     (@write($($data:expr),+)) => {
26         write!(scoped_cx!(), $($data),+)?
27     };
28     (@print($x:expr)) => {
29         scoped_cx!() = $x.print(scoped_cx!())?
30     };
31     (@$method:ident($($arg:expr),*)) => {
32         scoped_cx!() = scoped_cx!().$method($($arg),*)?
33     };
34     ($($kind:ident $data:tt),+) => {{
35         $(p!(@$kind $data);)+
36     }};
37 }
38 macro_rules! define_scoped_cx {
39     ($cx:ident) => {
40         #[allow(unused_macros)]
41         macro_rules! scoped_cx {
42             () => ($cx)
43         }
44     };
45 }
46
47 thread_local! {
48     static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
49     static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
50 }
51
52 /// Force us to name impls with just the filename/line number. We
53 /// normally try to use types. But at some points, notably while printing
54 /// cycle errors, this can result in extra or suboptimal error output,
55 /// so this variable disables that check.
56 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
57     FORCE_IMPL_FILENAME_LINE.with(|force| {
58         let old = force.get();
59         force.set(true);
60         let result = f();
61         force.set(old);
62         result
63     })
64 }
65
66 /// Adds the `crate::` prefix to paths where appropriate.
67 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
68     SHOULD_PREFIX_WITH_CRATE.with(|flag| {
69         let old = flag.get();
70         flag.set(true);
71         let result = f();
72         flag.set(old);
73         result
74     })
75 }
76
77 /// The "region highlights" are used to control region printing during
78 /// specific error messages. When a "region highlight" is enabled, it
79 /// gives an alternate way to print specific regions. For now, we
80 /// always print those regions using a number, so something like "`'0`".
81 ///
82 /// Regions not selected by the region highlight mode are presently
83 /// unaffected.
84 #[derive(Copy, Clone, Default)]
85 pub struct RegionHighlightMode {
86     /// If enabled, when we see the selected region, use "`'N`"
87     /// instead of the ordinary behavior.
88     highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
89
90     /// If enabled, when printing a "free region" that originated from
91     /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
92     /// have names print as normal.
93     ///
94     /// This is used when you have a signature like `fn foo(x: &u32,
95     /// y: &'a u32)` and we want to give a name to the region of the
96     /// reference `x`.
97     highlight_bound_region: Option<(ty::BoundRegion, usize)>,
98 }
99
100 impl RegionHighlightMode {
101     /// If `region` and `number` are both `Some`, invokes
102     /// `highlighting_region`.
103     pub fn maybe_highlighting_region(
104         &mut self,
105         region: Option<ty::Region<'_>>,
106         number: Option<usize>,
107     ) {
108         if let Some(k) = region {
109             if let Some(n) = number {
110                 self.highlighting_region(k, n);
111             }
112         }
113     }
114
115     /// Highlights the region inference variable `vid` as `'N`.
116     pub fn highlighting_region(
117         &mut self,
118         region: ty::Region<'_>,
119         number: usize,
120     ) {
121         let num_slots = self.highlight_regions.len();
122         let first_avail_slot = self.highlight_regions.iter_mut()
123             .filter(|s| s.is_none())
124             .next()
125             .unwrap_or_else(|| {
126                 bug!(
127                     "can only highlight {} placeholders at a time",
128                     num_slots,
129                 )
130             });
131         *first_avail_slot = Some((*region, number));
132     }
133
134     /// Convenience wrapper for `highlighting_region`.
135     pub fn highlighting_region_vid(
136         &mut self,
137         vid: ty::RegionVid,
138         number: usize,
139     ) {
140         self.highlighting_region(&ty::ReVar(vid), number)
141     }
142
143     /// Returns `Some(n)` with the number to use for the given region, if any.
144     fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
145         self
146             .highlight_regions
147             .iter()
148             .filter_map(|h| match h {
149                 Some((r, n)) if r == region => Some(*n),
150                 _ => None,
151             })
152             .next()
153     }
154
155     /// Highlight the given bound region.
156     /// We can only highlight one bound region at a time. See
157     /// the field `highlight_bound_region` for more detailed notes.
158     pub fn highlighting_bound_region(
159         &mut self,
160         br: ty::BoundRegion,
161         number: usize,
162     ) {
163         assert!(self.highlight_bound_region.is_none());
164         self.highlight_bound_region = Some((br, number));
165     }
166 }
167
168 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
169 pub trait PrettyPrinter<'tcx>:
170     Printer<
171         'tcx,
172         Error = fmt::Error,
173         Path = Self,
174         Region = Self,
175         Type = Self,
176         DynExistential = Self,
177         Const = Self,
178     > + fmt::Write
179 {
180     /// Like `print_def_path` but for value paths.
181     fn print_value_path(
182         self,
183         def_id: DefId,
184         substs: &'tcx [Kind<'tcx>],
185     ) -> Result<Self::Path, Self::Error> {
186         self.print_def_path(def_id, substs)
187     }
188
189     fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
190     where
191         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
192     {
193         value.skip_binder().print(self)
194     }
195
196     /// Print comma-separated elements.
197     fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
198     where
199         T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
200     {
201         if let Some(first) = elems.next() {
202             self = first.print(self)?;
203             for elem in elems {
204                 self.write_str(", ")?;
205                 self = elem.print(self)?;
206             }
207         }
208         Ok(self)
209     }
210
211     /// Print `<...>` around what `f` prints.
212     fn generic_delimiters(
213         self,
214         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
215     ) -> Result<Self, Self::Error>;
216
217     /// Return `true` if the region should be printed in
218     /// optional positions, e.g. `&'a T` or `dyn Tr + 'b`.
219     /// This is typically the case for all non-`'_` regions.
220     fn region_should_not_be_omitted(
221         &self,
222         region: ty::Region<'_>,
223     ) -> bool;
224
225     // Defaults (should not be overriden):
226
227     /// If possible, this returns a global path resolving to `def_id` that is visible
228     /// from at least one local module and returns true. If the crate defining `def_id` is
229     /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
230     fn try_print_visible_def_path(
231         self,
232         def_id: DefId,
233     ) -> Result<(Self, bool), Self::Error> {
234         let mut callers = Vec::new();
235         self.try_print_visible_def_path_recur(def_id, &mut callers)
236     }
237
238     /// Does the work of `try_print_visible_def_path`, building the
239     /// full definition path recursively before attempting to
240     /// post-process it into the valid and visible version that
241     /// accounts for re-exports.
242     ///
243     /// This method should only be callled by itself or
244     /// `try_print_visible_def_path`.
245     ///
246     /// `callers` is a chain of visible_parent's leading to `def_id`,
247     /// to support cycle detection during recursion.
248     fn try_print_visible_def_path_recur(
249         mut self,
250         def_id: DefId,
251         callers: &mut Vec<DefId>,
252     ) -> Result<(Self, bool), Self::Error> {
253         define_scoped_cx!(self);
254
255         debug!("try_print_visible_def_path: def_id={:?}", def_id);
256
257         // If `def_id` is a direct or injected extern crate, return the
258         // path to the crate followed by the path to the item within the crate.
259         if def_id.index == CRATE_DEF_INDEX {
260             let cnum = def_id.krate;
261
262             if cnum == LOCAL_CRATE {
263                 return Ok((self.path_crate(cnum)?, true));
264             }
265
266             // In local mode, when we encounter a crate other than
267             // LOCAL_CRATE, execution proceeds in one of two ways:
268             //
269             // 1. for a direct dependency, where user added an
270             //    `extern crate` manually, we put the `extern
271             //    crate` as the parent. So you wind up with
272             //    something relative to the current crate.
273             // 2. for an extern inferred from a path or an indirect crate,
274             //    where there is no explicit `extern crate`, we just prepend
275             //    the crate name.
276             match self.tcx().extern_crate(def_id) {
277                 Some(&ExternCrate {
278                     src: ExternCrateSource::Extern(def_id),
279                     direct: true,
280                     span,
281                     ..
282                 }) => {
283                     debug!("try_print_visible_def_path: def_id={:?}", def_id);
284                     return Ok((if !span.is_dummy() {
285                         self.print_def_path(def_id, &[])?
286                     } else {
287                         self.path_crate(cnum)?
288                     }, true));
289                 }
290                 None => {
291                     return Ok((self.path_crate(cnum)?, true));
292                 }
293                 _ => {},
294             }
295         }
296
297         if def_id.is_local() {
298             return Ok((self, false));
299         }
300
301         let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
302
303         let mut cur_def_key = self.tcx().def_key(def_id);
304         debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
305
306         // For a constructor we want the name of its parent rather than <unnamed>.
307         match cur_def_key.disambiguated_data.data {
308             DefPathData::Ctor => {
309                 let parent = DefId {
310                     krate: def_id.krate,
311                     index: cur_def_key.parent
312                         .expect("DefPathData::Ctor/VariantData missing a parent"),
313                 };
314
315                 cur_def_key = self.tcx().def_key(parent);
316             },
317             _ => {},
318         }
319
320         let visible_parent = match visible_parent_map.get(&def_id).cloned() {
321             Some(parent) => parent,
322             None => return Ok((self, false)),
323         };
324         if callers.contains(&visible_parent) {
325             return Ok((self, false));
326         }
327         callers.push(visible_parent);
328         // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
329         // knowing ahead of time whether the entire path will succeed or not.
330         // To support printers that do not implement `PrettyPrinter`, a `Vec` or
331         // linked list on the stack would need to be built, before any printing.
332         match self.try_print_visible_def_path_recur(visible_parent, callers)? {
333             (cx, false) => return Ok((cx, false)),
334             (cx, true) => self = cx,
335         }
336         callers.pop();
337         let actual_parent = self.tcx().parent(def_id);
338         debug!(
339             "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
340             visible_parent, actual_parent,
341         );
342
343         let mut data = cur_def_key.disambiguated_data.data;
344         debug!(
345             "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
346             data, visible_parent, actual_parent,
347         );
348
349         match data {
350             // In order to output a path that could actually be imported (valid and visible),
351             // we need to handle re-exports correctly.
352             //
353             // For example, take `std::os::unix::process::CommandExt`, this trait is actually
354             // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
355             //
356             // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
357             // private so the "true" path to `CommandExt` isn't accessible.
358             //
359             // In this case, the `visible_parent_map` will look something like this:
360             //
361             // (child) -> (parent)
362             // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
363             // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
364             // `std::sys::unix::ext` -> `std::os`
365             //
366             // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
367             // `std::os`.
368             //
369             // When printing the path to `CommandExt` and looking at the `cur_def_key` that
370             // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
371             // to the parent - resulting in a mangled path like
372             // `std::os::ext::process::CommandExt`.
373             //
374             // Instead, we must detect that there was a re-export and instead print `unix`
375             // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
376             // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
377             // the visible parent (`std::os`). If these do not match, then we iterate over
378             // the children of the visible parent (as was done when computing
379             // `visible_parent_map`), looking for the specific child we currently have and then
380             // have access to the re-exported name.
381             DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
382                 let reexport = self.tcx().item_children(visible_parent)
383                     .iter()
384                     .find(|child| child.res.def_id() == def_id)
385                     .map(|child| child.ident.as_interned_str());
386                 if let Some(reexport) = reexport {
387                     *name = reexport;
388                 }
389             }
390             // Re-exported `extern crate` (#43189).
391             DefPathData::CrateRoot => {
392                 data = DefPathData::TypeNs(
393                     self.tcx().original_crate_name(def_id.krate).as_interned_str(),
394                 );
395             }
396             _ => {}
397         }
398         debug!("try_print_visible_def_path: data={:?}", data);
399
400         Ok((self.path_append(Ok, &DisambiguatedDefPathData {
401             data,
402             disambiguator: 0,
403         })?, true))
404     }
405
406     fn pretty_path_qualified(
407         self,
408         self_ty: Ty<'tcx>,
409         trait_ref: Option<ty::TraitRef<'tcx>>,
410     ) -> Result<Self::Path, Self::Error> {
411         if trait_ref.is_none() {
412             // Inherent impls. Try to print `Foo::bar` for an inherent
413             // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
414             // anything other than a simple path.
415             match self_ty.sty {
416                 ty::Adt(..) | ty::Foreign(_) |
417                 ty::Bool | ty::Char | ty::Str |
418                 ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
419                     return self_ty.print(self);
420                 }
421
422                 _ => {}
423             }
424         }
425
426         self.generic_delimiters(|mut cx| {
427             define_scoped_cx!(cx);
428
429             p!(print(self_ty));
430             if let Some(trait_ref) = trait_ref {
431                 p!(write(" as "), print(trait_ref));
432             }
433             Ok(cx)
434         })
435     }
436
437     fn pretty_path_append_impl(
438         mut self,
439         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
440         self_ty: Ty<'tcx>,
441         trait_ref: Option<ty::TraitRef<'tcx>>,
442     ) -> Result<Self::Path, Self::Error> {
443         self = print_prefix(self)?;
444
445         self.generic_delimiters(|mut cx| {
446             define_scoped_cx!(cx);
447
448             p!(write("impl "));
449             if let Some(trait_ref) = trait_ref {
450                 p!(print(trait_ref), write(" for "));
451             }
452             p!(print(self_ty));
453
454             Ok(cx)
455         })
456     }
457
458     fn pretty_print_type(
459         mut self,
460         ty: Ty<'tcx>,
461     ) -> Result<Self::Type, Self::Error> {
462         define_scoped_cx!(self);
463
464         match ty.sty {
465             ty::Bool => p!(write("bool")),
466             ty::Char => p!(write("char")),
467             ty::Int(t) => p!(write("{}", t.ty_to_string())),
468             ty::Uint(t) => p!(write("{}", t.ty_to_string())),
469             ty::Float(t) => p!(write("{}", t.ty_to_string())),
470             ty::RawPtr(ref tm) => {
471                 p!(write("*{} ", match tm.mutbl {
472                     hir::MutMutable => "mut",
473                     hir::MutImmutable => "const",
474                 }));
475                 p!(print(tm.ty))
476             }
477             ty::Ref(r, ty, mutbl) => {
478                 p!(write("&"));
479                 if self.region_should_not_be_omitted(r) {
480                     p!(print(r), write(" "));
481                 }
482                 p!(print(ty::TypeAndMut { ty, mutbl }))
483             }
484             ty::Never => p!(write("!")),
485             ty::Tuple(ref tys) => {
486                 p!(write("("));
487                 let mut tys = tys.iter();
488                 if let Some(&ty) = tys.next() {
489                     p!(print(ty), write(","));
490                     if let Some(&ty) = tys.next() {
491                         p!(write(" "), print(ty));
492                         for &ty in tys {
493                             p!(write(", "), print(ty));
494                         }
495                     }
496                 }
497                 p!(write(")"))
498             }
499             ty::FnDef(def_id, substs) => {
500                 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
501                 p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}"));
502             }
503             ty::FnPtr(ref bare_fn) => {
504                 p!(print(bare_fn))
505             }
506             ty::Infer(infer_ty) => {
507                 if let ty::TyVar(ty_vid) = infer_ty {
508                     if let Some(name) = self.infer_ty_name(ty_vid) {
509                         p!(write("{}", name))
510                     } else {
511                         p!(write("{}", infer_ty))
512                     }
513                 } else {
514                     p!(write("{}", infer_ty))
515                 }
516             },
517             ty::Error => p!(write("[type error]")),
518             ty::Param(ref param_ty) => p!(write("{}", param_ty)),
519             ty::Bound(debruijn, bound_ty) => {
520                 match bound_ty.kind {
521                     ty::BoundTyKind::Anon => {
522                         if debruijn == ty::INNERMOST {
523                             p!(write("^{}", bound_ty.var.index()))
524                         } else {
525                             p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
526                         }
527                     }
528
529                     ty::BoundTyKind::Param(p) => p!(write("{}", p)),
530                 }
531             }
532             ty::Adt(def, substs) => {
533                 p!(print_def_path(def.did, substs));
534             }
535             ty::Dynamic(data, r) => {
536                 let print_r = self.region_should_not_be_omitted(r);
537                 if print_r {
538                     p!(write("("));
539                 }
540                 p!(write("dyn "), print(data));
541                 if print_r {
542                     p!(write(" + "), print(r), write(")"));
543                 }
544             }
545             ty::Foreign(def_id) => {
546                 p!(print_def_path(def_id, &[]));
547             }
548             ty::Projection(ref data) => p!(print(data)),
549             ty::UnnormalizedProjection(ref data) => {
550                 p!(write("Unnormalized("), print(data), write(")"))
551             }
552             ty::Placeholder(placeholder) => {
553                 p!(write("Placeholder({:?})", placeholder))
554             }
555             ty::Opaque(def_id, substs) => {
556                 // FIXME(eddyb) print this with `print_def_path`.
557                 if self.tcx().sess.verbose() {
558                     p!(write("Opaque({:?}, {:?})", def_id, substs));
559                     return Ok(self);
560                 }
561
562                 let def_key = self.tcx().def_key(def_id);
563                 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
564                     p!(write("{}", name));
565                     let mut substs = substs.iter();
566                     // FIXME(eddyb) print this with `print_def_path`.
567                     if let Some(first) = substs.next() {
568                         p!(write("::<"));
569                         p!(print(first));
570                         for subst in substs {
571                             p!(write(", "), print(subst));
572                         }
573                         p!(write(">"));
574                     }
575                     return Ok(self);
576                 }
577                 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
578                 // by looking up the projections associated with the def_id.
579                 let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
580
581                 let mut first = true;
582                 let mut is_sized = false;
583                 p!(write("impl"));
584                 for predicate in bounds.predicates {
585                     if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
586                         // Don't print +Sized, but rather +?Sized if absent.
587                         if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
588                             is_sized = true;
589                             continue;
590                         }
591
592                         p!(
593                                 write("{}", if first { " " } else { "+" }),
594                                 print(trait_ref));
595                         first = false;
596                     }
597                 }
598                 if !is_sized {
599                     p!(write("{}?Sized", if first { " " } else { "+" }));
600                 } else if first {
601                     p!(write(" Sized"));
602                 }
603             }
604             ty::Str => p!(write("str")),
605             ty::Generator(did, substs, movability) => {
606                 let upvar_tys = substs.upvar_tys(did, self.tcx());
607                 let witness = substs.witness(did, self.tcx());
608                 if movability == hir::GeneratorMovability::Movable {
609                     p!(write("[generator"));
610                 } else {
611                     p!(write("[static generator"));
612                 }
613
614                 // FIXME(eddyb) should use `def_span`.
615                 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
616                     p!(write("@{:?}", self.tcx().hir().span(hir_id)));
617                     let mut sep = " ";
618                     for (&var_id, upvar_ty) in self.tcx().upvars(did)
619                         .as_ref()
620                         .iter()
621                         .flat_map(|v| v.keys())
622                         .zip(upvar_tys)
623                     {
624                         p!(
625                             write("{}{}:",
626                                     sep,
627                                     self.tcx().hir().name(var_id)),
628                             print(upvar_ty));
629                         sep = ", ";
630                     }
631                 } else {
632                     // cross-crate closure types should only be
633                     // visible in codegen bug reports, I imagine.
634                     p!(write("@{:?}", did));
635                     let mut sep = " ";
636                     for (index, upvar_ty) in upvar_tys.enumerate() {
637                         p!(
638                                 write("{}{}:", sep, index),
639                                 print(upvar_ty));
640                         sep = ", ";
641                     }
642                 }
643
644                 p!(write(" "), print(witness), write("]"))
645             },
646             ty::GeneratorWitness(types) => {
647                 p!(in_binder(&types));
648             }
649             ty::Closure(did, substs) => {
650                 let upvar_tys = substs.upvar_tys(did, self.tcx());
651                 p!(write("[closure"));
652
653                 // FIXME(eddyb) should use `def_span`.
654                 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
655                     if self.tcx().sess.opts.debugging_opts.span_free_formats {
656                         p!(write("@{:?}", hir_id));
657                     } else {
658                         p!(write("@{:?}", self.tcx().hir().span(hir_id)));
659                     }
660                     let mut sep = " ";
661                     for (&var_id, upvar_ty) in self.tcx().upvars(did)
662                         .as_ref()
663                         .iter()
664                         .flat_map(|v| v.keys())
665                         .zip(upvar_tys)
666                     {
667                         p!(
668                             write("{}{}:",
669                                     sep,
670                                     self.tcx().hir().name(var_id)),
671                             print(upvar_ty));
672                         sep = ", ";
673                     }
674                 } else {
675                     // cross-crate closure types should only be
676                     // visible in codegen bug reports, I imagine.
677                     p!(write("@{:?}", did));
678                     let mut sep = " ";
679                     for (index, upvar_ty) in upvar_tys.enumerate() {
680                         p!(
681                                 write("{}{}:", sep, index),
682                                 print(upvar_ty));
683                         sep = ", ";
684                     }
685                 }
686
687                 if self.tcx().sess.verbose() {
688                     p!(write(
689                         " closure_kind_ty={:?} closure_sig_ty={:?}",
690                         substs.closure_kind_ty(did, self.tcx()),
691                         substs.closure_sig_ty(did, self.tcx())
692                     ));
693                 }
694
695                 p!(write("]"))
696             },
697             ty::Array(ty, sz) => {
698                 p!(write("["), print(ty), write("; "));
699                 if let ConstValue::Unevaluated(..) = sz.val {
700                     // do not try to evalute unevaluated constants. If we are const evaluating an
701                     // array length anon const, rustc will (with debug assertions) print the
702                     // constant's path. Which will end up here again.
703                     p!(write("_"));
704                 } else if let Some(n) = sz.try_eval_usize(self.tcx(), ty::ParamEnv::empty()) {
705                     p!(write("{}", n));
706                 } else {
707                     p!(write("_"));
708                 }
709                 p!(write("]"))
710             }
711             ty::Slice(ty) => {
712                 p!(write("["), print(ty), write("]"))
713             }
714         }
715
716         Ok(self)
717     }
718
719     fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
720         None
721     }
722
723     fn pretty_print_dyn_existential(
724         mut self,
725         predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
726     ) -> Result<Self::DynExistential, Self::Error> {
727         define_scoped_cx!(self);
728
729         // Generate the main trait ref, including associated types.
730         let mut first = true;
731
732         if let Some(principal) = predicates.principal() {
733             p!(print_def_path(principal.def_id, &[]));
734
735             let mut resugared = false;
736
737             // Special-case `Fn(...) -> ...` and resugar it.
738             let fn_trait_kind = self.tcx().lang_items().fn_trait_kind(principal.def_id);
739             if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
740                 if let ty::Tuple(ref args) = principal.substs.type_at(0).sty {
741                     let mut projections = predicates.projection_bounds();
742                     if let (Some(proj), None) = (projections.next(), projections.next()) {
743                         let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
744                         p!(pretty_fn_sig(&tys, false, proj.ty));
745                         resugared = true;
746                     }
747                 }
748             }
749
750             // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
751             // in order to place the projections inside the `<...>`.
752             if !resugared {
753                 // Use a type that can't appear in defaults of type parameters.
754                 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
755                 let principal = principal.with_self_ty(self.tcx(), dummy_self);
756
757                 let args = self.generic_args_to_print(
758                     self.tcx().generics_of(principal.def_id),
759                     principal.substs,
760                 );
761
762                 // Don't print `'_` if there's no unerased regions.
763                 let print_regions = args.iter().any(|arg| {
764                     match arg.unpack() {
765                         UnpackedKind::Lifetime(r) => *r != ty::ReErased,
766                         _ => false,
767                     }
768                 });
769                 let mut args = args.iter().cloned().filter(|arg| {
770                     match arg.unpack() {
771                         UnpackedKind::Lifetime(_) => print_regions,
772                         _ => true,
773                     }
774                 });
775                 let mut projections = predicates.projection_bounds();
776
777                 let arg0 = args.next();
778                 let projection0 = projections.next();
779                 if arg0.is_some() || projection0.is_some() {
780                     let args = arg0.into_iter().chain(args);
781                     let projections = projection0.into_iter().chain(projections);
782
783                     p!(generic_delimiters(|mut cx| {
784                         cx = cx.comma_sep(args)?;
785                         if arg0.is_some() && projection0.is_some() {
786                             write!(cx, ", ")?;
787                         }
788                         cx.comma_sep(projections)
789                     }));
790                 }
791             }
792             first = false;
793         }
794
795         // Builtin bounds.
796         // FIXME(eddyb) avoid printing twice (needed to ensure
797         // that the auto traits are sorted *and* printed via cx).
798         let mut auto_traits: Vec<_> = predicates.auto_traits().map(|did| {
799             (self.tcx().def_path_str(did), did)
800         }).collect();
801
802         // The auto traits come ordered by `DefPathHash`. While
803         // `DefPathHash` is *stable* in the sense that it depends on
804         // neither the host nor the phase of the moon, it depends
805         // "pseudorandomly" on the compiler version and the target.
806         //
807         // To avoid that causing instabilities in compiletest
808         // output, sort the auto-traits alphabetically.
809         auto_traits.sort();
810
811         for (_, def_id) in auto_traits {
812             if !first {
813                 p!(write(" + "));
814             }
815             first = false;
816
817             p!(print_def_path(def_id, &[]));
818         }
819
820         Ok(self)
821     }
822
823     fn pretty_fn_sig(
824         mut self,
825         inputs: &[Ty<'tcx>],
826         c_variadic: bool,
827         output: Ty<'tcx>,
828     ) -> Result<Self, Self::Error> {
829         define_scoped_cx!(self);
830
831         p!(write("("));
832         let mut inputs = inputs.iter();
833         if let Some(&ty) = inputs.next() {
834             p!(print(ty));
835             for &ty in inputs {
836                 p!(write(", "), print(ty));
837             }
838             if c_variadic {
839                 p!(write(", ..."));
840             }
841         }
842         p!(write(")"));
843         if !output.is_unit() {
844             p!(write(" -> "), print(output));
845         }
846
847         Ok(self)
848     }
849
850     fn pretty_print_const(
851         mut self,
852         ct: &'tcx ty::Const<'tcx>,
853     ) -> Result<Self::Const, Self::Error> {
854         define_scoped_cx!(self);
855
856         let u8 = self.tcx().types.u8;
857         if let ty::FnDef(did, substs) = ct.ty.sty {
858             p!(print_value_path(did, substs));
859             return Ok(self);
860         }
861         if let ConstValue::Unevaluated(did, substs) = ct.val {
862             match self.tcx().def_kind(did) {
863                 | Some(DefKind::Static)
864                 | Some(DefKind::Const)
865                 | Some(DefKind::AssocConst) => p!(print_value_path(did, substs)),
866                 _ => if did.is_local() {
867                     let span = self.tcx().def_span(did);
868                     if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
869                         p!(write("{}", snip))
870                     } else {
871                         p!(write("_: "), print(ct.ty))
872                     }
873                 } else {
874                     p!(write("_: "), print(ct.ty))
875                 },
876             }
877             return Ok(self);
878         }
879         if let ConstValue::Infer(..) = ct.val {
880             p!(write("_: "), print(ct.ty));
881             return Ok(self);
882         }
883         if let ConstValue::Param(ParamConst { name, .. }) = ct.val {
884             p!(write("{}", name));
885             return Ok(self);
886         }
887         if let ConstValue::Scalar(Scalar::Raw { data, .. }) = ct.val {
888             match ct.ty.sty {
889                 ty::Bool => {
890                     p!(write("{}", if data == 0 { "false" } else { "true" }));
891                     return Ok(self);
892                 },
893                 ty::Float(ast::FloatTy::F32) => {
894                     p!(write("{}f32", Single::from_bits(data)));
895                     return Ok(self);
896                 },
897                 ty::Float(ast::FloatTy::F64) => {
898                     p!(write("{}f64", Double::from_bits(data)));
899                     return Ok(self);
900                 },
901                 ty::Uint(ui) => {
902                     p!(write("{}{}", data, ui));
903                     return Ok(self);
904                 },
905                 ty::Int(i) =>{
906                     let ty = self.tcx().lift_to_global(&ct.ty).unwrap();
907                     let size = self.tcx().layout_of(ty::ParamEnv::empty().and(ty))
908                         .unwrap()
909                         .size;
910                     p!(write("{}{}", sign_extend(data, size) as i128, i));
911                     return Ok(self);
912                 },
913                 ty::Char => {
914                     p!(write("{:?}", ::std::char::from_u32(data as u32).unwrap()));
915                     return Ok(self);
916                 }
917                 _ => {},
918             }
919         }
920         if let ty::Ref(_, ref_ty, _) = ct.ty.sty {
921             let byte_str = match (ct.val, &ref_ty.sty) {
922                 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => {
923                     let n = n.eval_usize(self.tcx(), ty::ParamEnv::empty());
924                     Some(self.tcx()
925                         .alloc_map.lock()
926                         .unwrap_memory(ptr.alloc_id)
927                         .get_bytes(&self.tcx(), ptr, Size::from_bytes(n)).unwrap())
928                 },
929                 (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => {
930                     Some(&data.bytes[start..end])
931                 },
932                 (ConstValue::Slice { data, start, end }, ty::Str) => {
933                     let slice = &data.bytes[start..end];
934                     let s = ::std::str::from_utf8(slice)
935                         .expect("non utf8 str from miri");
936                     p!(write("{:?}", s));
937                     return Ok(self);
938                 },
939                 _ => None,
940             };
941             if let Some(byte_str) = byte_str {
942                 p!(write("b\""));
943                 for &c in byte_str {
944                     for e in std::ascii::escape_default(c) {
945                         self.write_char(e as char)?;
946                     }
947                 }
948                 p!(write("\""));
949                 return Ok(self);
950             }
951         }
952         p!(write("{:?} : ", ct.val), print(ct.ty));
953
954         Ok(self)
955     }
956 }
957
958 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
959 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
960
961 pub struct FmtPrinterData<'a, 'tcx, F> {
962     tcx: TyCtxt<'tcx>,
963     fmt: F,
964
965     empty_path: bool,
966     in_value: bool,
967
968     used_region_names: FxHashSet<InternedString>,
969     region_index: usize,
970     binder_depth: usize,
971
972     pub region_highlight_mode: RegionHighlightMode,
973
974     pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
975 }
976
977 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
978     type Target = FmtPrinterData<'a, 'tcx, F>;
979     fn deref(&self) -> &Self::Target {
980         &self.0
981     }
982 }
983
984 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
985     fn deref_mut(&mut self) -> &mut Self::Target {
986         &mut self.0
987     }
988 }
989
990 impl<F> FmtPrinter<'a, 'tcx, F> {
991     pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
992         FmtPrinter(Box::new(FmtPrinterData {
993             tcx,
994             fmt,
995             empty_path: false,
996             in_value: ns == Namespace::ValueNS,
997             used_region_names: Default::default(),
998             region_index: 0,
999             binder_depth: 0,
1000             region_highlight_mode: RegionHighlightMode::default(),
1001             name_resolver: None,
1002         }))
1003     }
1004 }
1005
1006 impl TyCtxt<'_> {
1007     // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1008     // (but also some things just print a `DefId` generally so maybe we need this?)
1009     fn guess_def_namespace(self, def_id: DefId) -> Namespace {
1010         match self.def_key(def_id).disambiguated_data.data {
1011             DefPathData::TypeNs(..)
1012             | DefPathData::CrateRoot
1013             | DefPathData::ImplTrait => Namespace::TypeNS,
1014
1015             DefPathData::ValueNs(..)
1016             | DefPathData::AnonConst
1017             | DefPathData::ClosureExpr
1018             | DefPathData::Ctor => Namespace::ValueNS,
1019
1020             DefPathData::MacroNs(..) => Namespace::MacroNS,
1021
1022             _ => Namespace::TypeNS,
1023         }
1024     }
1025
1026     /// Returns a string identifying this `DefId`. This string is
1027     /// suitable for user output.
1028     pub fn def_path_str(self, def_id: DefId) -> String {
1029         let ns = self.guess_def_namespace(def_id);
1030         debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1031         let mut s = String::new();
1032         let _ = FmtPrinter::new(self, &mut s, ns)
1033             .print_def_path(def_id, &[]);
1034         s
1035     }
1036 }
1037
1038 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1039     fn write_str(&mut self, s: &str) -> fmt::Result {
1040         self.fmt.write_str(s)
1041     }
1042 }
1043
1044 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1045     type Error = fmt::Error;
1046
1047     type Path = Self;
1048     type Region = Self;
1049     type Type = Self;
1050     type DynExistential = Self;
1051     type Const = Self;
1052
1053     fn tcx(&'a self) -> TyCtxt<'tcx> {
1054         self.tcx
1055     }
1056
1057     fn print_def_path(
1058         mut self,
1059         def_id: DefId,
1060         substs: &'tcx [Kind<'tcx>],
1061     ) -> Result<Self::Path, Self::Error> {
1062         define_scoped_cx!(self);
1063
1064         if substs.is_empty() {
1065             match self.try_print_visible_def_path(def_id)? {
1066                 (cx, true) => return Ok(cx),
1067                 (cx, false) => self = cx,
1068             }
1069         }
1070
1071         let key = self.tcx.def_key(def_id);
1072         if let DefPathData::Impl = key.disambiguated_data.data {
1073             // Always use types for non-local impls, where types are always
1074             // available, and filename/line-number is mostly uninteresting.
1075             let use_types =
1076                 !def_id.is_local() || {
1077                     // Otherwise, use filename/line-number if forced.
1078                     let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1079                     !force_no_types
1080                 };
1081
1082             if !use_types {
1083                 // If no type info is available, fall back to
1084                 // pretty printing some span information. This should
1085                 // only occur very early in the compiler pipeline.
1086                 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1087                 let span = self.tcx.def_span(def_id);
1088
1089                 self = self.print_def_path(parent_def_id, &[])?;
1090
1091                 // HACK(eddyb) copy of `path_append` to avoid
1092                 // constructing a `DisambiguatedDefPathData`.
1093                 if !self.empty_path {
1094                     write!(self, "::")?;
1095                 }
1096                 write!(self, "<impl at {:?}>", span)?;
1097                 self.empty_path = false;
1098
1099                 return Ok(self);
1100             }
1101         }
1102
1103         self.default_print_def_path(def_id, substs)
1104     }
1105
1106     fn print_region(
1107         self,
1108         region: ty::Region<'_>,
1109     ) -> Result<Self::Region, Self::Error> {
1110         self.pretty_print_region(region)
1111     }
1112
1113     fn print_type(
1114         self,
1115         ty: Ty<'tcx>,
1116     ) -> Result<Self::Type, Self::Error> {
1117         self.pretty_print_type(ty)
1118     }
1119
1120     fn print_dyn_existential(
1121         self,
1122         predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1123     ) -> Result<Self::DynExistential, Self::Error> {
1124         self.pretty_print_dyn_existential(predicates)
1125     }
1126
1127     fn print_const(
1128         self,
1129         ct: &'tcx ty::Const<'tcx>,
1130     ) -> Result<Self::Const, Self::Error> {
1131         self.pretty_print_const(ct)
1132     }
1133
1134     fn path_crate(
1135         mut self,
1136         cnum: CrateNum,
1137     ) -> Result<Self::Path, Self::Error> {
1138         self.empty_path = true;
1139         if cnum == LOCAL_CRATE {
1140             if self.tcx.sess.rust_2018() {
1141                 // We add the `crate::` keyword on Rust 2018, only when desired.
1142                 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1143                     write!(self, "{}", kw::Crate)?;
1144                     self.empty_path = false;
1145                 }
1146             }
1147         } else {
1148             write!(self, "{}", self.tcx.crate_name(cnum))?;
1149             self.empty_path = false;
1150         }
1151         Ok(self)
1152     }
1153     fn path_qualified(
1154         mut self,
1155         self_ty: Ty<'tcx>,
1156         trait_ref: Option<ty::TraitRef<'tcx>>,
1157     ) -> Result<Self::Path, Self::Error> {
1158         self = self.pretty_path_qualified(self_ty, trait_ref)?;
1159         self.empty_path = false;
1160         Ok(self)
1161     }
1162
1163     fn path_append_impl(
1164         mut self,
1165         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1166         _disambiguated_data: &DisambiguatedDefPathData,
1167         self_ty: Ty<'tcx>,
1168         trait_ref: Option<ty::TraitRef<'tcx>>,
1169     ) -> Result<Self::Path, Self::Error> {
1170         self = self.pretty_path_append_impl(|mut cx| {
1171             cx = print_prefix(cx)?;
1172             if !cx.empty_path {
1173                 write!(cx, "::")?;
1174             }
1175
1176             Ok(cx)
1177         }, self_ty, trait_ref)?;
1178         self.empty_path = false;
1179         Ok(self)
1180     }
1181     fn path_append(
1182         mut self,
1183         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1184         disambiguated_data: &DisambiguatedDefPathData,
1185     ) -> Result<Self::Path, Self::Error> {
1186         self = print_prefix(self)?;
1187
1188         // Skip `::{{constructor}}` on tuple/unit structs.
1189         match disambiguated_data.data {
1190             DefPathData::Ctor => return Ok(self),
1191             _ => {}
1192         }
1193
1194         // FIXME(eddyb) `name` should never be empty, but it
1195         // currently is for `extern { ... }` "foreign modules".
1196         let name = disambiguated_data.data.as_interned_str().as_str();
1197         if !name.is_empty() {
1198             if !self.empty_path {
1199                 write!(self, "::")?;
1200             }
1201             write!(self, "{}", name)?;
1202
1203             // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1204             // might be nicer to use something else, e.g. `{closure#3}`.
1205             let dis = disambiguated_data.disambiguator;
1206             let print_dis =
1207                 disambiguated_data.data.get_opt_name().is_none() ||
1208                 dis != 0 && self.tcx.sess.verbose();
1209             if print_dis {
1210                 write!(self, "#{}", dis)?;
1211             }
1212
1213             self.empty_path = false;
1214         }
1215
1216         Ok(self)
1217     }
1218     fn path_generic_args(
1219         mut self,
1220         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1221         args: &[Kind<'tcx>],
1222     ) -> Result<Self::Path, Self::Error> {
1223         self = print_prefix(self)?;
1224
1225         // Don't print `'_` if there's no unerased regions.
1226         let print_regions = args.iter().any(|arg| {
1227             match arg.unpack() {
1228                 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
1229                 _ => false,
1230             }
1231         });
1232         let args = args.iter().cloned().filter(|arg| {
1233             match arg.unpack() {
1234                 UnpackedKind::Lifetime(_) => print_regions,
1235                 _ => true,
1236             }
1237         });
1238
1239         if args.clone().next().is_some() {
1240             if self.in_value {
1241                 write!(self, "::")?;
1242             }
1243             self.generic_delimiters(|cx| cx.comma_sep(args))
1244         } else {
1245             Ok(self)
1246         }
1247     }
1248 }
1249
1250 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1251     fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1252         self.0.name_resolver.as_ref().and_then(|func| func(id))
1253     }
1254
1255     fn print_value_path(
1256         mut self,
1257         def_id: DefId,
1258         substs: &'tcx [Kind<'tcx>],
1259     ) -> Result<Self::Path, Self::Error> {
1260         let was_in_value = std::mem::replace(&mut self.in_value, true);
1261         self = self.print_def_path(def_id, substs)?;
1262         self.in_value = was_in_value;
1263
1264         Ok(self)
1265     }
1266
1267     fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1268     where
1269         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1270     {
1271         self.pretty_in_binder(value)
1272     }
1273
1274     fn generic_delimiters(
1275         mut self,
1276         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1277     ) -> Result<Self, Self::Error> {
1278         write!(self, "<")?;
1279
1280         let was_in_value = std::mem::replace(&mut self.in_value, false);
1281         let mut inner = f(self)?;
1282         inner.in_value = was_in_value;
1283
1284         write!(inner, ">")?;
1285         Ok(inner)
1286     }
1287
1288     fn region_should_not_be_omitted(
1289         &self,
1290         region: ty::Region<'_>,
1291     ) -> bool {
1292         let highlight = self.region_highlight_mode;
1293         if highlight.region_highlighted(region).is_some() {
1294             return true;
1295         }
1296
1297         if self.tcx.sess.verbose() {
1298             return true;
1299         }
1300
1301         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1302
1303         match *region {
1304             ty::ReEarlyBound(ref data) => {
1305                 data.name.as_symbol() != kw::Invalid &&
1306                 data.name.as_symbol() != kw::UnderscoreLifetime
1307             }
1308
1309             ty::ReLateBound(_, br) |
1310             ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1311             ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1312                 if let ty::BrNamed(_, name) = br {
1313                     if name.as_symbol() != kw::Invalid &&
1314                        name.as_symbol() != kw::UnderscoreLifetime {
1315                         return true;
1316                     }
1317                 }
1318
1319                 if let Some((region, _)) = highlight.highlight_bound_region {
1320                     if br == region {
1321                         return true;
1322                     }
1323                 }
1324
1325                 false
1326             }
1327
1328             ty::ReScope(_) |
1329             ty::ReVar(_) if identify_regions => true,
1330
1331             ty::ReVar(_) |
1332             ty::ReScope(_) |
1333             ty::ReErased => false,
1334
1335             ty::ReStatic |
1336             ty::ReEmpty |
1337             ty::ReClosureBound(_) => true,
1338         }
1339     }
1340 }
1341
1342 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1343 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1344     pub fn pretty_print_region(
1345         mut self,
1346         region: ty::Region<'_>,
1347     ) -> Result<Self, fmt::Error> {
1348         define_scoped_cx!(self);
1349
1350         // Watch out for region highlights.
1351         let highlight = self.region_highlight_mode;
1352         if let Some(n) = highlight.region_highlighted(region) {
1353             p!(write("'{}", n));
1354             return Ok(self);
1355         }
1356
1357         if self.tcx.sess.verbose() {
1358             p!(write("{:?}", region));
1359             return Ok(self);
1360         }
1361
1362         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1363
1364         // These printouts are concise.  They do not contain all the information
1365         // the user might want to diagnose an error, but there is basically no way
1366         // to fit that into a short string.  Hence the recommendation to use
1367         // `explain_region()` or `note_and_explain_region()`.
1368         match *region {
1369             ty::ReEarlyBound(ref data) => {
1370                 if data.name.as_symbol() != kw::Invalid {
1371                     p!(write("{}", data.name));
1372                     return Ok(self);
1373                 }
1374             }
1375             ty::ReLateBound(_, br) |
1376             ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1377             ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1378                 if let ty::BrNamed(_, name) = br {
1379                     if name.as_symbol() != kw::Invalid &&
1380                        name.as_symbol() != kw::UnderscoreLifetime {
1381                         p!(write("{}", name));
1382                         return Ok(self);
1383                     }
1384                 }
1385
1386                 if let Some((region, counter)) = highlight.highlight_bound_region {
1387                     if br == region {
1388                         p!(write("'{}", counter));
1389                         return Ok(self);
1390                     }
1391                 }
1392             }
1393             ty::ReScope(scope) if identify_regions => {
1394                 match scope.data {
1395                     region::ScopeData::Node =>
1396                         p!(write("'{}s", scope.item_local_id().as_usize())),
1397                     region::ScopeData::CallSite =>
1398                         p!(write("'{}cs", scope.item_local_id().as_usize())),
1399                     region::ScopeData::Arguments =>
1400                         p!(write("'{}as", scope.item_local_id().as_usize())),
1401                     region::ScopeData::Destruction =>
1402                         p!(write("'{}ds", scope.item_local_id().as_usize())),
1403                     region::ScopeData::Remainder(first_statement_index) => p!(write(
1404                         "'{}_{}rs",
1405                         scope.item_local_id().as_usize(),
1406                         first_statement_index.index()
1407                     )),
1408                 }
1409                 return Ok(self);
1410             }
1411             ty::ReVar(region_vid) if identify_regions => {
1412                 p!(write("{:?}", region_vid));
1413                 return Ok(self);
1414             }
1415             ty::ReVar(_) => {}
1416             ty::ReScope(_) |
1417             ty::ReErased => {}
1418             ty::ReStatic => {
1419                 p!(write("'static"));
1420                 return Ok(self);
1421             }
1422             ty::ReEmpty => {
1423                 p!(write("'<empty>"));
1424                 return Ok(self);
1425             }
1426
1427             // The user should never encounter these in unsubstituted form.
1428             ty::ReClosureBound(vid) => {
1429                 p!(write("{:?}", vid));
1430                 return Ok(self);
1431             }
1432         }
1433
1434         p!(write("'_"));
1435
1436         Ok(self)
1437     }
1438 }
1439
1440 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1441 // `region_index` and `used_region_names`.
1442 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1443     pub fn pretty_in_binder<T>(mut self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1444     where
1445         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1446     {
1447         fn name_by_region_index(index: usize) -> InternedString {
1448             match index {
1449                 0 => InternedString::intern("'r"),
1450                 1 => InternedString::intern("'s"),
1451                 i => InternedString::intern(&format!("'t{}", i-2)),
1452             }
1453         }
1454
1455         // Replace any anonymous late-bound regions with named
1456         // variants, using gensym'd identifiers, so that we can
1457         // clearly differentiate between named and unnamed regions in
1458         // the output. We'll probably want to tweak this over time to
1459         // decide just how much information to give.
1460         if self.binder_depth == 0 {
1461             self.prepare_late_bound_region_info(value);
1462         }
1463
1464         let mut empty = true;
1465         let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1466             write!(cx, "{}", if empty {
1467                 empty = false;
1468                 start
1469             } else {
1470                 cont
1471             })
1472         };
1473
1474         define_scoped_cx!(self);
1475
1476         let old_region_index = self.region_index;
1477         let mut region_index = old_region_index;
1478         let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1479             let _ = start_or_continue(&mut self, "for<", ", ");
1480             let br = match br {
1481                 ty::BrNamed(_, name) => {
1482                     let _ = write!(self, "{}", name);
1483                     br
1484                 }
1485                 ty::BrAnon(_) |
1486                 ty::BrEnv => {
1487                     let name = loop {
1488                         let name = name_by_region_index(region_index);
1489                         region_index += 1;
1490                         if !self.used_region_names.contains(&name) {
1491                             break name;
1492                         }
1493                     };
1494                     let _ = write!(self, "{}", name);
1495                     ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1496                 }
1497             };
1498             self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1499         }).0;
1500         start_or_continue(&mut self, "", "> ")?;
1501
1502         self.binder_depth += 1;
1503         self.region_index = region_index;
1504         let mut inner = new_value.print(self)?;
1505         inner.region_index = old_region_index;
1506         inner.binder_depth -= 1;
1507         Ok(inner)
1508     }
1509
1510     fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1511         where T: TypeFoldable<'tcx>
1512     {
1513
1514         struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<InternedString>);
1515         impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1516             fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1517                 match *r {
1518                     ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1519                         self.0.insert(name);
1520                     },
1521                     _ => {},
1522                 }
1523                 r.super_visit_with(self)
1524             }
1525         }
1526
1527         self.used_region_names.clear();
1528         let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1529         value.visit_with(&mut collector);
1530         self.region_index = 0;
1531     }
1532 }
1533
1534 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1535 where
1536     T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1537 {
1538     type Output = P;
1539     type Error = P::Error;
1540     fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1541         cx.in_binder(self)
1542     }
1543 }
1544
1545 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1546 where
1547     T: Print<'tcx, P, Output = P, Error = P::Error>,
1548     U: Print<'tcx, P, Output = P, Error = P::Error>,
1549 {
1550     type Output = P;
1551     type Error = P::Error;
1552     fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1553         define_scoped_cx!(cx);
1554         p!(print(self.0), write(" : "), print(self.1));
1555         Ok(cx)
1556     }
1557 }
1558
1559 macro_rules! forward_display_to_print {
1560     ($($ty:ty),+) => {
1561         $(impl fmt::Display for $ty {
1562             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1563                 ty::tls::with(|tcx| {
1564                     tcx.lift(self)
1565                         .expect("could not lift for printing")
1566                         .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1567                     Ok(())
1568                 })
1569             }
1570         })+
1571     };
1572 }
1573
1574 macro_rules! define_print_and_forward_display {
1575     (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1576         $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1577             type Output = P;
1578             type Error = fmt::Error;
1579             fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1580                 #[allow(unused_mut)]
1581                 let mut $cx = $cx;
1582                 define_scoped_cx!($cx);
1583                 let _: () = $print;
1584                 #[allow(unreachable_code)]
1585                 Ok($cx)
1586             }
1587         })+
1588
1589         forward_display_to_print!($($ty),+);
1590     };
1591 }
1592
1593 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1594 impl fmt::Display for ty::RegionKind {
1595     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1596         ty::tls::with(|tcx| {
1597             self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1598             Ok(())
1599         })
1600     }
1601 }
1602
1603 forward_display_to_print! {
1604     Ty<'tcx>,
1605     &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1606     &'tcx ty::Const<'tcx>,
1607
1608     // HACK(eddyb) these are exhaustive instead of generic,
1609     // because `for<'tcx>` isn't possible yet.
1610     ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1611     ty::Binder<ty::TraitRef<'tcx>>,
1612     ty::Binder<ty::FnSig<'tcx>>,
1613     ty::Binder<ty::TraitPredicate<'tcx>>,
1614     ty::Binder<ty::SubtypePredicate<'tcx>>,
1615     ty::Binder<ty::ProjectionPredicate<'tcx>>,
1616     ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1617     ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1618
1619     ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1620     ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1621 }
1622
1623 define_print_and_forward_display! {
1624     (self, cx):
1625
1626     &'tcx ty::List<Ty<'tcx>> {
1627         p!(write("{{"));
1628         let mut tys = self.iter();
1629         if let Some(&ty) = tys.next() {
1630             p!(print(ty));
1631             for &ty in tys {
1632                 p!(write(", "), print(ty));
1633             }
1634         }
1635         p!(write("}}"))
1636     }
1637
1638     ty::TypeAndMut<'tcx> {
1639         p!(write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
1640             print(self.ty))
1641     }
1642
1643     ty::ExistentialTraitRef<'tcx> {
1644         // Use a type that can't appear in defaults of type parameters.
1645         let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1646         let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1647         p!(print(trait_ref))
1648     }
1649
1650     ty::ExistentialProjection<'tcx> {
1651         let name = cx.tcx().associated_item(self.item_def_id).ident;
1652         p!(write("{} = ", name), print(self.ty))
1653     }
1654
1655     ty::ExistentialPredicate<'tcx> {
1656         match *self {
1657             ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1658             ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1659             ty::ExistentialPredicate::AutoTrait(def_id) => {
1660                 p!(print_def_path(def_id, &[]));
1661             }
1662         }
1663     }
1664
1665     ty::FnSig<'tcx> {
1666         if self.unsafety == hir::Unsafety::Unsafe {
1667             p!(write("unsafe "));
1668         }
1669
1670         if self.abi != Abi::Rust {
1671             p!(write("extern {} ", self.abi));
1672         }
1673
1674         p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1675     }
1676
1677     ty::InferTy {
1678         if cx.tcx().sess.verbose() {
1679             p!(write("{:?}", self));
1680             return Ok(cx);
1681         }
1682         match *self {
1683             ty::TyVar(_) => p!(write("_")),
1684             ty::IntVar(_) => p!(write("{}", "{integer}")),
1685             ty::FloatVar(_) => p!(write("{}", "{float}")),
1686             ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1687             ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1688             ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1689         }
1690     }
1691
1692     ty::TraitRef<'tcx> {
1693         p!(print_def_path(self.def_id, self.substs));
1694     }
1695
1696     ty::ParamTy {
1697         p!(write("{}", self.name))
1698     }
1699
1700     ty::ParamConst {
1701         p!(write("{}", self.name))
1702     }
1703
1704     ty::SubtypePredicate<'tcx> {
1705         p!(print(self.a), write(" <: "), print(self.b))
1706     }
1707
1708     ty::TraitPredicate<'tcx> {
1709         p!(print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1710     }
1711
1712     ty::ProjectionPredicate<'tcx> {
1713         p!(print(self.projection_ty), write(" == "), print(self.ty))
1714     }
1715
1716     ty::ProjectionTy<'tcx> {
1717         p!(print_def_path(self.item_def_id, self.substs));
1718     }
1719
1720     ty::ClosureKind {
1721         match *self {
1722             ty::ClosureKind::Fn => p!(write("Fn")),
1723             ty::ClosureKind::FnMut => p!(write("FnMut")),
1724             ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1725         }
1726     }
1727
1728     ty::Predicate<'tcx> {
1729         match *self {
1730             ty::Predicate::Trait(ref data) => p!(print(data)),
1731             ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1732             ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1733             ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1734             ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1735             ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1736             ty::Predicate::ObjectSafe(trait_def_id) => {
1737                 p!(write("the trait `"),
1738                    print_def_path(trait_def_id, &[]),
1739                    write("` is object-safe"))
1740             }
1741             ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1742                 p!(write("the closure `"),
1743                    print_value_path(closure_def_id, &[]),
1744                    write("` implements the trait `{}`", kind))
1745             }
1746             ty::Predicate::ConstEvaluatable(def_id, substs) => {
1747                 p!(write("the constant `"),
1748                    print_value_path(def_id, substs),
1749                    write("` can be evaluated"))
1750             }
1751         }
1752     }
1753
1754     Kind<'tcx> {
1755         match self.unpack() {
1756             UnpackedKind::Lifetime(lt) => p!(print(lt)),
1757             UnpackedKind::Type(ty) => p!(print(ty)),
1758             UnpackedKind::Const(ct) => p!(print(ct)),
1759         }
1760     }
1761 }