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