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