]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/print/pretty.rs
Remove leftover AwaitOrigin
[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 Some(n) = sz.assert_usize(self.tcx()) {
700                     p!(write("{}", n));
701                 } else {
702                     p!(write("_"));
703                 }
704                 p!(write("]"))
705             }
706             ty::Slice(ty) => {
707                 p!(write("["), print(ty), write("]"))
708             }
709         }
710
711         Ok(self)
712     }
713
714     fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
715         None
716     }
717
718     fn pretty_print_dyn_existential(
719         mut self,
720         predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
721     ) -> Result<Self::DynExistential, Self::Error> {
722         define_scoped_cx!(self);
723
724         // Generate the main trait ref, including associated types.
725         let mut first = true;
726
727         if let Some(principal) = predicates.principal() {
728             p!(print_def_path(principal.def_id, &[]));
729
730             let mut resugared = false;
731
732             // Special-case `Fn(...) -> ...` and resugar it.
733             let fn_trait_kind = self.tcx().lang_items().fn_trait_kind(principal.def_id);
734             if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
735                 if let ty::Tuple(ref args) = principal.substs.type_at(0).sty {
736                     let mut projections = predicates.projection_bounds();
737                     if let (Some(proj), None) = (projections.next(), projections.next()) {
738                         let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
739                         p!(pretty_fn_sig(&tys, false, proj.ty));
740                         resugared = true;
741                     }
742                 }
743             }
744
745             // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
746             // in order to place the projections inside the `<...>`.
747             if !resugared {
748                 // Use a type that can't appear in defaults of type parameters.
749                 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
750                 let principal = principal.with_self_ty(self.tcx(), dummy_self);
751
752                 let args = self.generic_args_to_print(
753                     self.tcx().generics_of(principal.def_id),
754                     principal.substs,
755                 );
756
757                 // Don't print `'_` if there's no unerased regions.
758                 let print_regions = args.iter().any(|arg| {
759                     match arg.unpack() {
760                         UnpackedKind::Lifetime(r) => *r != ty::ReErased,
761                         _ => false,
762                     }
763                 });
764                 let mut args = args.iter().cloned().filter(|arg| {
765                     match arg.unpack() {
766                         UnpackedKind::Lifetime(_) => print_regions,
767                         _ => true,
768                     }
769                 });
770                 let mut projections = predicates.projection_bounds();
771
772                 let arg0 = args.next();
773                 let projection0 = projections.next();
774                 if arg0.is_some() || projection0.is_some() {
775                     let args = arg0.into_iter().chain(args);
776                     let projections = projection0.into_iter().chain(projections);
777
778                     p!(generic_delimiters(|mut cx| {
779                         cx = cx.comma_sep(args)?;
780                         if arg0.is_some() && projection0.is_some() {
781                             write!(cx, ", ")?;
782                         }
783                         cx.comma_sep(projections)
784                     }));
785                 }
786             }
787             first = false;
788         }
789
790         // Builtin bounds.
791         // FIXME(eddyb) avoid printing twice (needed to ensure
792         // that the auto traits are sorted *and* printed via cx).
793         let mut auto_traits: Vec<_> = predicates.auto_traits().map(|did| {
794             (self.tcx().def_path_str(did), did)
795         }).collect();
796
797         // The auto traits come ordered by `DefPathHash`. While
798         // `DefPathHash` is *stable* in the sense that it depends on
799         // neither the host nor the phase of the moon, it depends
800         // "pseudorandomly" on the compiler version and the target.
801         //
802         // To avoid that causing instabilities in compiletest
803         // output, sort the auto-traits alphabetically.
804         auto_traits.sort();
805
806         for (_, def_id) in auto_traits {
807             if !first {
808                 p!(write(" + "));
809             }
810             first = false;
811
812             p!(print_def_path(def_id, &[]));
813         }
814
815         Ok(self)
816     }
817
818     fn pretty_fn_sig(
819         mut self,
820         inputs: &[Ty<'tcx>],
821         c_variadic: bool,
822         output: Ty<'tcx>,
823     ) -> Result<Self, Self::Error> {
824         define_scoped_cx!(self);
825
826         p!(write("("));
827         let mut inputs = inputs.iter();
828         if let Some(&ty) = inputs.next() {
829             p!(print(ty));
830             for &ty in inputs {
831                 p!(write(", "), print(ty));
832             }
833             if c_variadic {
834                 p!(write(", ..."));
835             }
836         }
837         p!(write(")"));
838         if !output.is_unit() {
839             p!(write(" -> "), print(output));
840         }
841
842         Ok(self)
843     }
844
845     fn pretty_print_const(
846         mut self,
847         ct: &'tcx ty::Const<'tcx>,
848     ) -> Result<Self::Const, Self::Error> {
849         define_scoped_cx!(self);
850
851         let u8 = self.tcx().types.u8;
852         if let ty::FnDef(did, substs) = ct.ty.sty {
853             p!(print_value_path(did, substs));
854             return Ok(self);
855         }
856         if let ConstValue::Unevaluated(did, substs) = ct.val {
857             match self.tcx().def_kind(did) {
858                 | Some(DefKind::Static)
859                 | Some(DefKind::Const)
860                 | Some(DefKind::AssocConst) => p!(print_value_path(did, substs)),
861                 _ => if did.is_local() {
862                     let span = self.tcx().def_span(did);
863                     if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
864                         p!(write("{}", snip))
865                     } else {
866                         p!(write("_: "), print(ct.ty))
867                     }
868                 } else {
869                     p!(write("_: "), print(ct.ty))
870                 },
871             }
872             return Ok(self);
873         }
874         if let ConstValue::Infer(..) = ct.val {
875             p!(write("_: "), print(ct.ty));
876             return Ok(self);
877         }
878         if let ConstValue::Param(ParamConst { name, .. }) = ct.val {
879             p!(write("{}", name));
880             return Ok(self);
881         }
882         if let ConstValue::Scalar(Scalar::Raw { data, .. }) = ct.val {
883             match ct.ty.sty {
884                 ty::Bool => {
885                     p!(write("{}", if data == 0 { "false" } else { "true" }));
886                     return Ok(self);
887                 },
888                 ty::Float(ast::FloatTy::F32) => {
889                     p!(write("{}f32", Single::from_bits(data)));
890                     return Ok(self);
891                 },
892                 ty::Float(ast::FloatTy::F64) => {
893                     p!(write("{}f64", Double::from_bits(data)));
894                     return Ok(self);
895                 },
896                 ty::Uint(ui) => {
897                     p!(write("{}{}", data, ui));
898                     return Ok(self);
899                 },
900                 ty::Int(i) =>{
901                     let ty = self.tcx().lift_to_global(&ct.ty).unwrap();
902                     let size = self.tcx().layout_of(ty::ParamEnv::empty().and(ty))
903                         .unwrap()
904                         .size;
905                     p!(write("{}{}", sign_extend(data, size) as i128, i));
906                     return Ok(self);
907                 },
908                 ty::Char => {
909                     p!(write("{:?}", ::std::char::from_u32(data as u32).unwrap()));
910                     return Ok(self);
911                 }
912                 _ => {},
913             }
914         }
915         if let ty::Ref(_, ref_ty, _) = ct.ty.sty {
916             let byte_str = match (ct.val, &ref_ty.sty) {
917                 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => {
918                     let n = n.unwrap_usize(self.tcx());
919                     Some(self.tcx()
920                         .alloc_map.lock()
921                         .unwrap_memory(ptr.alloc_id)
922                         .get_bytes(&self.tcx(), ptr, Size::from_bytes(n)).unwrap())
923                 },
924                 (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => {
925                     Some(&data.bytes[start..end])
926                 },
927                 (ConstValue::Slice { data, start, end }, ty::Str) => {
928                     let slice = &data.bytes[start..end];
929                     let s = ::std::str::from_utf8(slice)
930                         .expect("non utf8 str from miri");
931                     p!(write("{:?}", s));
932                     return Ok(self);
933                 },
934                 _ => None,
935             };
936             if let Some(byte_str) = byte_str {
937                 p!(write("b\""));
938                 for &c in byte_str {
939                     for e in std::ascii::escape_default(c) {
940                         self.write_char(e as char)?;
941                     }
942                 }
943                 p!(write("\""));
944                 return Ok(self);
945             }
946         }
947         p!(write("{:?} : ", ct.val), print(ct.ty));
948
949         Ok(self)
950     }
951 }
952
953 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
954 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
955
956 pub struct FmtPrinterData<'a, 'tcx, F> {
957     tcx: TyCtxt<'tcx>,
958     fmt: F,
959
960     empty_path: bool,
961     in_value: bool,
962
963     used_region_names: FxHashSet<InternedString>,
964     region_index: usize,
965     binder_depth: usize,
966
967     pub region_highlight_mode: RegionHighlightMode,
968
969     pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
970 }
971
972 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
973     type Target = FmtPrinterData<'a, 'tcx, F>;
974     fn deref(&self) -> &Self::Target {
975         &self.0
976     }
977 }
978
979 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
980     fn deref_mut(&mut self) -> &mut Self::Target {
981         &mut self.0
982     }
983 }
984
985 impl<F> FmtPrinter<'a, 'tcx, F> {
986     pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
987         FmtPrinter(Box::new(FmtPrinterData {
988             tcx,
989             fmt,
990             empty_path: false,
991             in_value: ns == Namespace::ValueNS,
992             used_region_names: Default::default(),
993             region_index: 0,
994             binder_depth: 0,
995             region_highlight_mode: RegionHighlightMode::default(),
996             name_resolver: None,
997         }))
998     }
999 }
1000
1001 impl TyCtxt<'_> {
1002     // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1003     // (but also some things just print a `DefId` generally so maybe we need this?)
1004     fn guess_def_namespace(self, def_id: DefId) -> Namespace {
1005         match self.def_key(def_id).disambiguated_data.data {
1006             DefPathData::TypeNs(..)
1007             | DefPathData::CrateRoot
1008             | DefPathData::ImplTrait => Namespace::TypeNS,
1009
1010             DefPathData::ValueNs(..)
1011             | DefPathData::AnonConst
1012             | DefPathData::ClosureExpr
1013             | DefPathData::Ctor => Namespace::ValueNS,
1014
1015             DefPathData::MacroNs(..) => Namespace::MacroNS,
1016
1017             _ => Namespace::TypeNS,
1018         }
1019     }
1020
1021     /// Returns a string identifying this `DefId`. This string is
1022     /// suitable for user output.
1023     pub fn def_path_str(self, def_id: DefId) -> String {
1024         let ns = self.guess_def_namespace(def_id);
1025         debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1026         let mut s = String::new();
1027         let _ = FmtPrinter::new(self, &mut s, ns)
1028             .print_def_path(def_id, &[]);
1029         s
1030     }
1031 }
1032
1033 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1034     fn write_str(&mut self, s: &str) -> fmt::Result {
1035         self.fmt.write_str(s)
1036     }
1037 }
1038
1039 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1040     type Error = fmt::Error;
1041
1042     type Path = Self;
1043     type Region = Self;
1044     type Type = Self;
1045     type DynExistential = Self;
1046     type Const = Self;
1047
1048     fn tcx(&'a self) -> TyCtxt<'tcx> {
1049         self.tcx
1050     }
1051
1052     fn print_def_path(
1053         mut self,
1054         def_id: DefId,
1055         substs: &'tcx [Kind<'tcx>],
1056     ) -> Result<Self::Path, Self::Error> {
1057         define_scoped_cx!(self);
1058
1059         if substs.is_empty() {
1060             match self.try_print_visible_def_path(def_id)? {
1061                 (cx, true) => return Ok(cx),
1062                 (cx, false) => self = cx,
1063             }
1064         }
1065
1066         let key = self.tcx.def_key(def_id);
1067         if let DefPathData::Impl = key.disambiguated_data.data {
1068             // Always use types for non-local impls, where types are always
1069             // available, and filename/line-number is mostly uninteresting.
1070             let use_types =
1071                 !def_id.is_local() || {
1072                     // Otherwise, use filename/line-number if forced.
1073                     let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1074                     !force_no_types
1075                 };
1076
1077             if !use_types {
1078                 // If no type info is available, fall back to
1079                 // pretty printing some span information. This should
1080                 // only occur very early in the compiler pipeline.
1081                 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1082                 let span = self.tcx.def_span(def_id);
1083
1084                 self = self.print_def_path(parent_def_id, &[])?;
1085
1086                 // HACK(eddyb) copy of `path_append` to avoid
1087                 // constructing a `DisambiguatedDefPathData`.
1088                 if !self.empty_path {
1089                     write!(self, "::")?;
1090                 }
1091                 write!(self, "<impl at {:?}>", span)?;
1092                 self.empty_path = false;
1093
1094                 return Ok(self);
1095             }
1096         }
1097
1098         self.default_print_def_path(def_id, substs)
1099     }
1100
1101     fn print_region(
1102         self,
1103         region: ty::Region<'_>,
1104     ) -> Result<Self::Region, Self::Error> {
1105         self.pretty_print_region(region)
1106     }
1107
1108     fn print_type(
1109         self,
1110         ty: Ty<'tcx>,
1111     ) -> Result<Self::Type, Self::Error> {
1112         self.pretty_print_type(ty)
1113     }
1114
1115     fn print_dyn_existential(
1116         self,
1117         predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1118     ) -> Result<Self::DynExistential, Self::Error> {
1119         self.pretty_print_dyn_existential(predicates)
1120     }
1121
1122     fn print_const(
1123         self,
1124         ct: &'tcx ty::Const<'tcx>,
1125     ) -> Result<Self::Const, Self::Error> {
1126         self.pretty_print_const(ct)
1127     }
1128
1129     fn path_crate(
1130         mut self,
1131         cnum: CrateNum,
1132     ) -> Result<Self::Path, Self::Error> {
1133         self.empty_path = true;
1134         if cnum == LOCAL_CRATE {
1135             if self.tcx.sess.rust_2018() {
1136                 // We add the `crate::` keyword on Rust 2018, only when desired.
1137                 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1138                     write!(self, "{}", kw::Crate)?;
1139                     self.empty_path = false;
1140                 }
1141             }
1142         } else {
1143             write!(self, "{}", self.tcx.crate_name(cnum))?;
1144             self.empty_path = false;
1145         }
1146         Ok(self)
1147     }
1148     fn path_qualified(
1149         mut self,
1150         self_ty: Ty<'tcx>,
1151         trait_ref: Option<ty::TraitRef<'tcx>>,
1152     ) -> Result<Self::Path, Self::Error> {
1153         self = self.pretty_path_qualified(self_ty, trait_ref)?;
1154         self.empty_path = false;
1155         Ok(self)
1156     }
1157
1158     fn path_append_impl(
1159         mut self,
1160         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1161         _disambiguated_data: &DisambiguatedDefPathData,
1162         self_ty: Ty<'tcx>,
1163         trait_ref: Option<ty::TraitRef<'tcx>>,
1164     ) -> Result<Self::Path, Self::Error> {
1165         self = self.pretty_path_append_impl(|mut cx| {
1166             cx = print_prefix(cx)?;
1167             if !cx.empty_path {
1168                 write!(cx, "::")?;
1169             }
1170
1171             Ok(cx)
1172         }, self_ty, trait_ref)?;
1173         self.empty_path = false;
1174         Ok(self)
1175     }
1176     fn path_append(
1177         mut self,
1178         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1179         disambiguated_data: &DisambiguatedDefPathData,
1180     ) -> Result<Self::Path, Self::Error> {
1181         self = print_prefix(self)?;
1182
1183         // Skip `::{{constructor}}` on tuple/unit structs.
1184         match disambiguated_data.data {
1185             DefPathData::Ctor => return Ok(self),
1186             _ => {}
1187         }
1188
1189         // FIXME(eddyb) `name` should never be empty, but it
1190         // currently is for `extern { ... }` "foreign modules".
1191         let name = disambiguated_data.data.as_interned_str().as_str();
1192         if !name.is_empty() {
1193             if !self.empty_path {
1194                 write!(self, "::")?;
1195             }
1196             write!(self, "{}", name)?;
1197
1198             // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1199             // might be nicer to use something else, e.g. `{closure#3}`.
1200             let dis = disambiguated_data.disambiguator;
1201             let print_dis =
1202                 disambiguated_data.data.get_opt_name().is_none() ||
1203                 dis != 0 && self.tcx.sess.verbose();
1204             if print_dis {
1205                 write!(self, "#{}", dis)?;
1206             }
1207
1208             self.empty_path = false;
1209         }
1210
1211         Ok(self)
1212     }
1213     fn path_generic_args(
1214         mut self,
1215         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1216         args: &[Kind<'tcx>],
1217     ) -> Result<Self::Path, Self::Error> {
1218         self = print_prefix(self)?;
1219
1220         // Don't print `'_` if there's no unerased regions.
1221         let print_regions = args.iter().any(|arg| {
1222             match arg.unpack() {
1223                 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
1224                 _ => false,
1225             }
1226         });
1227         let args = args.iter().cloned().filter(|arg| {
1228             match arg.unpack() {
1229                 UnpackedKind::Lifetime(_) => print_regions,
1230                 _ => true,
1231             }
1232         });
1233
1234         if args.clone().next().is_some() {
1235             if self.in_value {
1236                 write!(self, "::")?;
1237             }
1238             self.generic_delimiters(|cx| cx.comma_sep(args))
1239         } else {
1240             Ok(self)
1241         }
1242     }
1243 }
1244
1245 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1246     fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1247         self.0.name_resolver.as_ref().and_then(|func| func(id))
1248     }
1249
1250     fn print_value_path(
1251         mut self,
1252         def_id: DefId,
1253         substs: &'tcx [Kind<'tcx>],
1254     ) -> Result<Self::Path, Self::Error> {
1255         let was_in_value = std::mem::replace(&mut self.in_value, true);
1256         self = self.print_def_path(def_id, substs)?;
1257         self.in_value = was_in_value;
1258
1259         Ok(self)
1260     }
1261
1262     fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1263     where
1264         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1265     {
1266         self.pretty_in_binder(value)
1267     }
1268
1269     fn generic_delimiters(
1270         mut self,
1271         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1272     ) -> Result<Self, Self::Error> {
1273         write!(self, "<")?;
1274
1275         let was_in_value = std::mem::replace(&mut self.in_value, false);
1276         let mut inner = f(self)?;
1277         inner.in_value = was_in_value;
1278
1279         write!(inner, ">")?;
1280         Ok(inner)
1281     }
1282
1283     fn region_should_not_be_omitted(
1284         &self,
1285         region: ty::Region<'_>,
1286     ) -> bool {
1287         let highlight = self.region_highlight_mode;
1288         if highlight.region_highlighted(region).is_some() {
1289             return true;
1290         }
1291
1292         if self.tcx.sess.verbose() {
1293             return true;
1294         }
1295
1296         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1297
1298         match *region {
1299             ty::ReEarlyBound(ref data) => {
1300                 data.name.as_symbol() != kw::Invalid &&
1301                 data.name.as_symbol() != kw::UnderscoreLifetime
1302             }
1303
1304             ty::ReLateBound(_, br) |
1305             ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1306             ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1307                 if let ty::BrNamed(_, name) = br {
1308                     if name.as_symbol() != kw::Invalid &&
1309                        name.as_symbol() != kw::UnderscoreLifetime {
1310                         return true;
1311                     }
1312                 }
1313
1314                 if let Some((region, _)) = highlight.highlight_bound_region {
1315                     if br == region {
1316                         return true;
1317                     }
1318                 }
1319
1320                 false
1321             }
1322
1323             ty::ReScope(_) |
1324             ty::ReVar(_) if identify_regions => true,
1325
1326             ty::ReVar(_) |
1327             ty::ReScope(_) |
1328             ty::ReErased => false,
1329
1330             ty::ReStatic |
1331             ty::ReEmpty |
1332             ty::ReClosureBound(_) => true,
1333         }
1334     }
1335 }
1336
1337 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1338 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1339     pub fn pretty_print_region(
1340         mut self,
1341         region: ty::Region<'_>,
1342     ) -> Result<Self, fmt::Error> {
1343         define_scoped_cx!(self);
1344
1345         // Watch out for region highlights.
1346         let highlight = self.region_highlight_mode;
1347         if let Some(n) = highlight.region_highlighted(region) {
1348             p!(write("'{}", n));
1349             return Ok(self);
1350         }
1351
1352         if self.tcx.sess.verbose() {
1353             p!(write("{:?}", region));
1354             return Ok(self);
1355         }
1356
1357         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1358
1359         // These printouts are concise.  They do not contain all the information
1360         // the user might want to diagnose an error, but there is basically no way
1361         // to fit that into a short string.  Hence the recommendation to use
1362         // `explain_region()` or `note_and_explain_region()`.
1363         match *region {
1364             ty::ReEarlyBound(ref data) => {
1365                 if data.name.as_symbol() != kw::Invalid {
1366                     p!(write("{}", data.name));
1367                     return Ok(self);
1368                 }
1369             }
1370             ty::ReLateBound(_, br) |
1371             ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1372             ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1373                 if let ty::BrNamed(_, name) = br {
1374                     if name.as_symbol() != kw::Invalid &&
1375                        name.as_symbol() != kw::UnderscoreLifetime {
1376                         p!(write("{}", name));
1377                         return Ok(self);
1378                     }
1379                 }
1380
1381                 if let Some((region, counter)) = highlight.highlight_bound_region {
1382                     if br == region {
1383                         p!(write("'{}", counter));
1384                         return Ok(self);
1385                     }
1386                 }
1387             }
1388             ty::ReScope(scope) if identify_regions => {
1389                 match scope.data {
1390                     region::ScopeData::Node =>
1391                         p!(write("'{}s", scope.item_local_id().as_usize())),
1392                     region::ScopeData::CallSite =>
1393                         p!(write("'{}cs", scope.item_local_id().as_usize())),
1394                     region::ScopeData::Arguments =>
1395                         p!(write("'{}as", scope.item_local_id().as_usize())),
1396                     region::ScopeData::Destruction =>
1397                         p!(write("'{}ds", scope.item_local_id().as_usize())),
1398                     region::ScopeData::Remainder(first_statement_index) => p!(write(
1399                         "'{}_{}rs",
1400                         scope.item_local_id().as_usize(),
1401                         first_statement_index.index()
1402                     )),
1403                 }
1404                 return Ok(self);
1405             }
1406             ty::ReVar(region_vid) if identify_regions => {
1407                 p!(write("{:?}", region_vid));
1408                 return Ok(self);
1409             }
1410             ty::ReVar(_) => {}
1411             ty::ReScope(_) |
1412             ty::ReErased => {}
1413             ty::ReStatic => {
1414                 p!(write("'static"));
1415                 return Ok(self);
1416             }
1417             ty::ReEmpty => {
1418                 p!(write("'<empty>"));
1419                 return Ok(self);
1420             }
1421
1422             // The user should never encounter these in unsubstituted form.
1423             ty::ReClosureBound(vid) => {
1424                 p!(write("{:?}", vid));
1425                 return Ok(self);
1426             }
1427         }
1428
1429         p!(write("'_"));
1430
1431         Ok(self)
1432     }
1433 }
1434
1435 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1436 // `region_index` and `used_region_names`.
1437 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1438     pub fn pretty_in_binder<T>(mut self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1439     where
1440         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1441     {
1442         fn name_by_region_index(index: usize) -> InternedString {
1443             match index {
1444                 0 => InternedString::intern("'r"),
1445                 1 => InternedString::intern("'s"),
1446                 i => InternedString::intern(&format!("'t{}", i-2)),
1447             }
1448         }
1449
1450         // Replace any anonymous late-bound regions with named
1451         // variants, using gensym'd identifiers, so that we can
1452         // clearly differentiate between named and unnamed regions in
1453         // the output. We'll probably want to tweak this over time to
1454         // decide just how much information to give.
1455         if self.binder_depth == 0 {
1456             self.prepare_late_bound_region_info(value);
1457         }
1458
1459         let mut empty = true;
1460         let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1461             write!(cx, "{}", if empty {
1462                 empty = false;
1463                 start
1464             } else {
1465                 cont
1466             })
1467         };
1468
1469         define_scoped_cx!(self);
1470
1471         let old_region_index = self.region_index;
1472         let mut region_index = old_region_index;
1473         let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1474             let _ = start_or_continue(&mut self, "for<", ", ");
1475             let br = match br {
1476                 ty::BrNamed(_, name) => {
1477                     let _ = write!(self, "{}", name);
1478                     br
1479                 }
1480                 ty::BrAnon(_) |
1481                 ty::BrEnv => {
1482                     let name = loop {
1483                         let name = name_by_region_index(region_index);
1484                         region_index += 1;
1485                         if !self.used_region_names.contains(&name) {
1486                             break name;
1487                         }
1488                     };
1489                     let _ = write!(self, "{}", name);
1490                     ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1491                 }
1492             };
1493             self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1494         }).0;
1495         start_or_continue(&mut self, "", "> ")?;
1496
1497         self.binder_depth += 1;
1498         self.region_index = region_index;
1499         let mut inner = new_value.print(self)?;
1500         inner.region_index = old_region_index;
1501         inner.binder_depth -= 1;
1502         Ok(inner)
1503     }
1504
1505     fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1506         where T: TypeFoldable<'tcx>
1507     {
1508
1509         struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<InternedString>);
1510         impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1511             fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1512                 match *r {
1513                     ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1514                         self.0.insert(name);
1515                     },
1516                     _ => {},
1517                 }
1518                 r.super_visit_with(self)
1519             }
1520         }
1521
1522         self.used_region_names.clear();
1523         let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1524         value.visit_with(&mut collector);
1525         self.region_index = 0;
1526     }
1527 }
1528
1529 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1530 where
1531     T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1532 {
1533     type Output = P;
1534     type Error = P::Error;
1535     fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1536         cx.in_binder(self)
1537     }
1538 }
1539
1540 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1541 where
1542     T: Print<'tcx, P, Output = P, Error = P::Error>,
1543     U: Print<'tcx, P, Output = P, Error = P::Error>,
1544 {
1545     type Output = P;
1546     type Error = P::Error;
1547     fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1548         define_scoped_cx!(cx);
1549         p!(print(self.0), write(" : "), print(self.1));
1550         Ok(cx)
1551     }
1552 }
1553
1554 macro_rules! forward_display_to_print {
1555     ($($ty:ty),+) => {
1556         $(impl fmt::Display for $ty {
1557             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1558                 ty::tls::with(|tcx| {
1559                     tcx.lift(self)
1560                         .expect("could not lift for printing")
1561                         .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1562                     Ok(())
1563                 })
1564             }
1565         })+
1566     };
1567 }
1568
1569 macro_rules! define_print_and_forward_display {
1570     (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1571         $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1572             type Output = P;
1573             type Error = fmt::Error;
1574             fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1575                 #[allow(unused_mut)]
1576                 let mut $cx = $cx;
1577                 define_scoped_cx!($cx);
1578                 let _: () = $print;
1579                 #[allow(unreachable_code)]
1580                 Ok($cx)
1581             }
1582         })+
1583
1584         forward_display_to_print!($($ty),+);
1585     };
1586 }
1587
1588 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1589 impl fmt::Display for ty::RegionKind {
1590     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1591         ty::tls::with(|tcx| {
1592             self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1593             Ok(())
1594         })
1595     }
1596 }
1597
1598 forward_display_to_print! {
1599     Ty<'tcx>,
1600     &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1601     &'tcx ty::Const<'tcx>,
1602
1603     // HACK(eddyb) these are exhaustive instead of generic,
1604     // because `for<'tcx>` isn't possible yet.
1605     ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1606     ty::Binder<ty::TraitRef<'tcx>>,
1607     ty::Binder<ty::FnSig<'tcx>>,
1608     ty::Binder<ty::TraitPredicate<'tcx>>,
1609     ty::Binder<ty::SubtypePredicate<'tcx>>,
1610     ty::Binder<ty::ProjectionPredicate<'tcx>>,
1611     ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1612     ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1613
1614     ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1615     ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1616 }
1617
1618 define_print_and_forward_display! {
1619     (self, cx):
1620
1621     &'tcx ty::List<Ty<'tcx>> {
1622         p!(write("{{"));
1623         let mut tys = self.iter();
1624         if let Some(&ty) = tys.next() {
1625             p!(print(ty));
1626             for &ty in tys {
1627                 p!(write(", "), print(ty));
1628             }
1629         }
1630         p!(write("}}"))
1631     }
1632
1633     ty::TypeAndMut<'tcx> {
1634         p!(write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
1635             print(self.ty))
1636     }
1637
1638     ty::ExistentialTraitRef<'tcx> {
1639         // Use a type that can't appear in defaults of type parameters.
1640         let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1641         let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1642         p!(print(trait_ref))
1643     }
1644
1645     ty::ExistentialProjection<'tcx> {
1646         let name = cx.tcx().associated_item(self.item_def_id).ident;
1647         p!(write("{} = ", name), print(self.ty))
1648     }
1649
1650     ty::ExistentialPredicate<'tcx> {
1651         match *self {
1652             ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1653             ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1654             ty::ExistentialPredicate::AutoTrait(def_id) => {
1655                 p!(print_def_path(def_id, &[]));
1656             }
1657         }
1658     }
1659
1660     ty::FnSig<'tcx> {
1661         if self.unsafety == hir::Unsafety::Unsafe {
1662             p!(write("unsafe "));
1663         }
1664
1665         if self.abi != Abi::Rust {
1666             p!(write("extern {} ", self.abi));
1667         }
1668
1669         p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1670     }
1671
1672     ty::InferTy {
1673         if cx.tcx().sess.verbose() {
1674             p!(write("{:?}", self));
1675             return Ok(cx);
1676         }
1677         match *self {
1678             ty::TyVar(_) => p!(write("_")),
1679             ty::IntVar(_) => p!(write("{}", "{integer}")),
1680             ty::FloatVar(_) => p!(write("{}", "{float}")),
1681             ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1682             ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1683             ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1684         }
1685     }
1686
1687     ty::TraitRef<'tcx> {
1688         p!(print_def_path(self.def_id, self.substs));
1689     }
1690
1691     ty::ParamTy {
1692         p!(write("{}", self.name))
1693     }
1694
1695     ty::ParamConst {
1696         p!(write("{}", self.name))
1697     }
1698
1699     ty::SubtypePredicate<'tcx> {
1700         p!(print(self.a), write(" <: "), print(self.b))
1701     }
1702
1703     ty::TraitPredicate<'tcx> {
1704         p!(print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1705     }
1706
1707     ty::ProjectionPredicate<'tcx> {
1708         p!(print(self.projection_ty), write(" == "), print(self.ty))
1709     }
1710
1711     ty::ProjectionTy<'tcx> {
1712         p!(print_def_path(self.item_def_id, self.substs));
1713     }
1714
1715     ty::ClosureKind {
1716         match *self {
1717             ty::ClosureKind::Fn => p!(write("Fn")),
1718             ty::ClosureKind::FnMut => p!(write("FnMut")),
1719             ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1720         }
1721     }
1722
1723     ty::Predicate<'tcx> {
1724         match *self {
1725             ty::Predicate::Trait(ref data) => p!(print(data)),
1726             ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1727             ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1728             ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1729             ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1730             ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1731             ty::Predicate::ObjectSafe(trait_def_id) => {
1732                 p!(write("the trait `"),
1733                    print_def_path(trait_def_id, &[]),
1734                    write("` is object-safe"))
1735             }
1736             ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1737                 p!(write("the closure `"),
1738                    print_value_path(closure_def_id, &[]),
1739                    write("` implements the trait `{}`", kind))
1740             }
1741             ty::Predicate::ConstEvaluatable(def_id, substs) => {
1742                 p!(write("the constant `"),
1743                    print_value_path(def_id, substs),
1744                    write("` can be evaluated"))
1745             }
1746         }
1747     }
1748
1749     Kind<'tcx> {
1750         match self.unpack() {
1751             UnpackedKind::Lifetime(lt) => p!(print(lt)),
1752             UnpackedKind::Type(ty) => p!(print(ty)),
1753             UnpackedKind::Const(ct) => p!(print(ct)),
1754         }
1755     }
1756 }