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