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