]> git.lizzy.rs Git - rust.git/blob - src/librustc_middle/ty/print/pretty.rs
pin docs: add some forward references
[rust.git] / src / librustc_middle / ty / print / pretty.rs
1 use crate::middle::cstore::{ExternCrate, ExternCrateSource};
2 use crate::mir::interpret::{AllocId, ConstValue, GlobalAlloc, Pointer, Scalar};
3 use crate::ty::layout::IntegerExt;
4 use crate::ty::subst::{GenericArg, GenericArgKind, Subst};
5 use crate::ty::{self, ConstInt, DefIdTree, ParamConst, Ty, TyCtxt, TypeFoldable};
6 use rustc_apfloat::ieee::{Double, Single};
7 use rustc_apfloat::Float;
8 use rustc_ast::ast;
9 use rustc_attr::{SignedInt, UnsignedInt};
10 use rustc_hir as hir;
11 use rustc_hir::def::{CtorKind, DefKind, Namespace};
12 use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
13 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
14 use rustc_span::symbol::{kw, Ident, Symbol};
15 use rustc_target::abi::{Integer, Size};
16 use rustc_target::spec::abi::Abi;
17
18 use std::cell::Cell;
19 use std::char;
20 use std::collections::BTreeMap;
21 use std::fmt::{self, Write as _};
22 use std::ops::{Deref, DerefMut};
23
24 // `pretty` is a separate module only for organization.
25 use super::*;
26
27 macro_rules! p {
28     (@write($($data:expr),+)) => {
29         write!(scoped_cx!(), $($data),+)?
30     };
31     (@print($x:expr)) => {
32         scoped_cx!() = $x.print(scoped_cx!())?
33     };
34     (@$method:ident($($arg:expr),*)) => {
35         scoped_cx!() = scoped_cx!().$method($($arg),*)?
36     };
37     ($($kind:ident $data:tt),+) => {{
38         $(p!(@$kind $data);)+
39     }};
40 }
41 macro_rules! define_scoped_cx {
42     ($cx:ident) => {
43         #[allow(unused_macros)]
44         macro_rules! scoped_cx {
45             () => {
46                 $cx
47             };
48         }
49     };
50 }
51
52 thread_local! {
53     static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
54     static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
55     static NO_QUERIES: Cell<bool> = Cell::new(false);
56 }
57
58 /// Avoids running any queries during any prints that occur
59 /// during the closure. This may alter the appearance of some
60 /// types (e.g. forcing verbose printing for opaque types).
61 /// This method is used during some queries (e.g. `predicates_of`
62 /// for opaque types), to ensure that any debug printing that
63 /// occurs during the query computation does not end up recursively
64 /// calling the same query.
65 pub fn with_no_queries<F: FnOnce() -> R, R>(f: F) -> R {
66     NO_QUERIES.with(|no_queries| {
67         let old = no_queries.replace(true);
68         let result = f();
69         no_queries.set(old);
70         result
71     })
72 }
73
74 /// Force us to name impls with just the filename/line number. We
75 /// normally try to use types. But at some points, notably while printing
76 /// cycle errors, this can result in extra or suboptimal error output,
77 /// so this variable disables that check.
78 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
79     FORCE_IMPL_FILENAME_LINE.with(|force| {
80         let old = force.replace(true);
81         let result = f();
82         force.set(old);
83         result
84     })
85 }
86
87 /// Adds the `crate::` prefix to paths where appropriate.
88 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
89     SHOULD_PREFIX_WITH_CRATE.with(|flag| {
90         let old = flag.replace(true);
91         let result = f();
92         flag.set(old);
93         result
94     })
95 }
96
97 /// The "region highlights" are used to control region printing during
98 /// specific error messages. When a "region highlight" is enabled, it
99 /// gives an alternate way to print specific regions. For now, we
100 /// always print those regions using a number, so something like "`'0`".
101 ///
102 /// Regions not selected by the region highlight mode are presently
103 /// unaffected.
104 #[derive(Copy, Clone, Default)]
105 pub struct RegionHighlightMode {
106     /// If enabled, when we see the selected region, use "`'N`"
107     /// instead of the ordinary behavior.
108     highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
109
110     /// If enabled, when printing a "free region" that originated from
111     /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
112     /// have names print as normal.
113     ///
114     /// This is used when you have a signature like `fn foo(x: &u32,
115     /// y: &'a u32)` and we want to give a name to the region of the
116     /// reference `x`.
117     highlight_bound_region: Option<(ty::BoundRegion, usize)>,
118 }
119
120 impl RegionHighlightMode {
121     /// If `region` and `number` are both `Some`, invokes
122     /// `highlighting_region`.
123     pub fn maybe_highlighting_region(
124         &mut self,
125         region: Option<ty::Region<'_>>,
126         number: Option<usize>,
127     ) {
128         if let Some(k) = region {
129             if let Some(n) = number {
130                 self.highlighting_region(k, n);
131             }
132         }
133     }
134
135     /// Highlights the region inference variable `vid` as `'N`.
136     pub fn highlighting_region(&mut self, region: ty::Region<'_>, number: usize) {
137         let num_slots = self.highlight_regions.len();
138         let first_avail_slot =
139             self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
140                 bug!("can only highlight {} placeholders at a time", num_slots,)
141             });
142         *first_avail_slot = Some((*region, number));
143     }
144
145     /// Convenience wrapper for `highlighting_region`.
146     pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
147         self.highlighting_region(&ty::ReVar(vid), number)
148     }
149
150     /// Returns `Some(n)` with the number to use for the given region, if any.
151     fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
152         self.highlight_regions.iter().find_map(|h| match h {
153             Some((r, n)) if r == region => Some(*n),
154             _ => None,
155         })
156     }
157
158     /// Highlight the given bound region.
159     /// We can only highlight one bound region at a time. See
160     /// the field `highlight_bound_region` for more detailed notes.
161     pub fn highlighting_bound_region(&mut self, br: ty::BoundRegion, number: usize) {
162         assert!(self.highlight_bound_region.is_none());
163         self.highlight_bound_region = Some((br, number));
164     }
165 }
166
167 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
168 pub trait PrettyPrinter<'tcx>:
169     Printer<
170         'tcx,
171         Error = fmt::Error,
172         Path = Self,
173         Region = Self,
174         Type = Self,
175         DynExistential = Self,
176         Const = Self,
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 [GenericArg<'tcx>],
184     ) -> Result<Self::Path, Self::Error> {
185         self.print_def_path(def_id, substs)
186     }
187
188     fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
189     where
190         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
191     {
192         value.as_ref().skip_binder().print(self)
193     }
194
195     /// Prints comma-separated elements.
196     fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
197     where
198         T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
199     {
200         if let Some(first) = elems.next() {
201             self = first.print(self)?;
202             for elem in elems {
203                 self.write_str(", ")?;
204                 self = elem.print(self)?;
205             }
206         }
207         Ok(self)
208     }
209
210     /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
211     fn typed_value(
212         mut self,
213         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
214         t: impl FnOnce(Self) -> Result<Self, Self::Error>,
215         conversion: &str,
216     ) -> Result<Self::Const, Self::Error> {
217         self.write_str("{")?;
218         self = f(self)?;
219         self.write_str(conversion)?;
220         self = t(self)?;
221         self.write_str("}")?;
222         Ok(self)
223     }
224
225     /// Prints `<...>` around what `f` prints.
226     fn generic_delimiters(
227         self,
228         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
229     ) -> Result<Self, Self::Error>;
230
231     /// Returns `true` if the region should be printed in
232     /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
233     /// This is typically the case for all non-`'_` regions.
234     fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool;
235
236     // Defaults (should not be overridden):
237
238     /// If possible, this returns a global path resolving to `def_id` that is visible
239     /// from at least one local module, and returns `true`. If the crate defining `def_id` is
240     /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
241     fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
242         let mut callers = Vec::new();
243         self.try_print_visible_def_path_recur(def_id, &mut callers)
244     }
245
246     /// Does the work of `try_print_visible_def_path`, building the
247     /// full definition path recursively before attempting to
248     /// post-process it into the valid and visible version that
249     /// accounts for re-exports.
250     ///
251     /// This method should only be called by itself or
252     /// `try_print_visible_def_path`.
253     ///
254     /// `callers` is a chain of visible_parent's leading to `def_id`,
255     /// to support cycle detection during recursion.
256     fn try_print_visible_def_path_recur(
257         mut self,
258         def_id: DefId,
259         callers: &mut Vec<DefId>,
260     ) -> Result<(Self, bool), Self::Error> {
261         define_scoped_cx!(self);
262
263         debug!("try_print_visible_def_path: def_id={:?}", def_id);
264
265         // If `def_id` is a direct or injected extern crate, return the
266         // path to the crate followed by the path to the item within the crate.
267         if def_id.index == CRATE_DEF_INDEX {
268             let cnum = def_id.krate;
269
270             if cnum == LOCAL_CRATE {
271                 return Ok((self.path_crate(cnum)?, true));
272             }
273
274             // In local mode, when we encounter a crate other than
275             // LOCAL_CRATE, execution proceeds in one of two ways:
276             //
277             // 1. For a direct dependency, where user added an
278             //    `extern crate` manually, we put the `extern
279             //    crate` as the parent. So you wind up with
280             //    something relative to the current crate.
281             // 2. For an extern inferred from a path or an indirect crate,
282             //    where there is no explicit `extern crate`, we just prepend
283             //    the crate name.
284             match self.tcx().extern_crate(def_id) {
285                 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
286                     (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
287                         debug!("try_print_visible_def_path: def_id={:?}", def_id);
288                         return Ok((
289                             if !span.is_dummy() {
290                                 self.print_def_path(def_id, &[])?
291                             } else {
292                                 self.path_crate(cnum)?
293                             },
294                             true,
295                         ));
296                     }
297                     (ExternCrateSource::Path, LOCAL_CRATE) => {
298                         debug!("try_print_visible_def_path: def_id={:?}", def_id);
299                         return Ok((self.path_crate(cnum)?, true));
300                     }
301                     _ => {}
302                 },
303                 None => {
304                     return Ok((self.path_crate(cnum)?, true));
305                 }
306             }
307         }
308
309         if def_id.is_local() {
310             return Ok((self, false));
311         }
312
313         let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
314
315         let mut cur_def_key = self.tcx().def_key(def_id);
316         debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
317
318         // For a constructor, we want the name of its parent rather than <unnamed>.
319         if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
320             let parent = DefId {
321                 krate: def_id.krate,
322                 index: cur_def_key
323                     .parent
324                     .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
325             };
326
327             cur_def_key = self.tcx().def_key(parent);
328         }
329
330         let visible_parent = match visible_parent_map.get(&def_id).cloned() {
331             Some(parent) => parent,
332             None => return Ok((self, false)),
333         };
334         if callers.contains(&visible_parent) {
335             return Ok((self, false));
336         }
337         callers.push(visible_parent);
338         // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
339         // knowing ahead of time whether the entire path will succeed or not.
340         // To support printers that do not implement `PrettyPrinter`, a `Vec` or
341         // linked list on the stack would need to be built, before any printing.
342         match self.try_print_visible_def_path_recur(visible_parent, callers)? {
343             (cx, false) => return Ok((cx, false)),
344             (cx, true) => self = cx,
345         }
346         callers.pop();
347         let actual_parent = self.tcx().parent(def_id);
348         debug!(
349             "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
350             visible_parent, actual_parent,
351         );
352
353         let mut data = cur_def_key.disambiguated_data.data;
354         debug!(
355             "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
356             data, visible_parent, actual_parent,
357         );
358
359         match data {
360             // In order to output a path that could actually be imported (valid and visible),
361             // we need to handle re-exports correctly.
362             //
363             // For example, take `std::os::unix::process::CommandExt`, this trait is actually
364             // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
365             //
366             // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
367             // private so the "true" path to `CommandExt` isn't accessible.
368             //
369             // In this case, the `visible_parent_map` will look something like this:
370             //
371             // (child) -> (parent)
372             // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
373             // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
374             // `std::sys::unix::ext` -> `std::os`
375             //
376             // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
377             // `std::os`.
378             //
379             // When printing the path to `CommandExt` and looking at the `cur_def_key` that
380             // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
381             // to the parent - resulting in a mangled path like
382             // `std::os::ext::process::CommandExt`.
383             //
384             // Instead, we must detect that there was a re-export and instead print `unix`
385             // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
386             // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
387             // the visible parent (`std::os`). If these do not match, then we iterate over
388             // the children of the visible parent (as was done when computing
389             // `visible_parent_map`), looking for the specific child we currently have and then
390             // have access to the re-exported name.
391             DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
392                 let reexport = self
393                     .tcx()
394                     .item_children(visible_parent)
395                     .iter()
396                     .find(|child| child.res.opt_def_id() == Some(def_id))
397                     .map(|child| child.ident.name);
398                 if let Some(reexport) = reexport {
399                     *name = reexport;
400                 }
401             }
402             // Re-exported `extern crate` (#43189).
403             DefPathData::CrateRoot => {
404                 data = DefPathData::TypeNs(self.tcx().original_crate_name(def_id.krate));
405             }
406             _ => {}
407         }
408         debug!("try_print_visible_def_path: data={:?}", data);
409
410         Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
411     }
412
413     fn pretty_path_qualified(
414         self,
415         self_ty: Ty<'tcx>,
416         trait_ref: Option<ty::TraitRef<'tcx>>,
417     ) -> Result<Self::Path, Self::Error> {
418         if trait_ref.is_none() {
419             // Inherent impls. Try to print `Foo::bar` for an inherent
420             // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
421             // anything other than a simple path.
422             match self_ty.kind {
423                 ty::Adt(..)
424                 | ty::Foreign(_)
425                 | ty::Bool
426                 | ty::Char
427                 | ty::Str
428                 | ty::Int(_)
429                 | ty::Uint(_)
430                 | ty::Float(_) => {
431                     return self_ty.print(self);
432                 }
433
434                 _ => {}
435             }
436         }
437
438         self.generic_delimiters(|mut cx| {
439             define_scoped_cx!(cx);
440
441             p!(print(self_ty));
442             if let Some(trait_ref) = trait_ref {
443                 p!(write(" as "), print(trait_ref.print_only_trait_path()));
444             }
445             Ok(cx)
446         })
447     }
448
449     fn pretty_path_append_impl(
450         mut self,
451         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
452         self_ty: Ty<'tcx>,
453         trait_ref: Option<ty::TraitRef<'tcx>>,
454     ) -> Result<Self::Path, Self::Error> {
455         self = print_prefix(self)?;
456
457         self.generic_delimiters(|mut cx| {
458             define_scoped_cx!(cx);
459
460             p!(write("impl "));
461             if let Some(trait_ref) = trait_ref {
462                 p!(print(trait_ref.print_only_trait_path()), write(" for "));
463             }
464             p!(print(self_ty));
465
466             Ok(cx)
467         })
468     }
469
470     fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
471         define_scoped_cx!(self);
472
473         match ty.kind {
474             ty::Bool => p!(write("bool")),
475             ty::Char => p!(write("char")),
476             ty::Int(t) => p!(write("{}", t.name_str())),
477             ty::Uint(t) => p!(write("{}", t.name_str())),
478             ty::Float(t) => p!(write("{}", t.name_str())),
479             ty::RawPtr(ref tm) => {
480                 p!(write(
481                     "*{} ",
482                     match tm.mutbl {
483                         hir::Mutability::Mut => "mut",
484                         hir::Mutability::Not => "const",
485                     }
486                 ));
487                 p!(print(tm.ty))
488             }
489             ty::Ref(r, ty, mutbl) => {
490                 p!(write("&"));
491                 if self.region_should_not_be_omitted(r) {
492                     p!(print(r), write(" "));
493                 }
494                 p!(print(ty::TypeAndMut { ty, mutbl }))
495             }
496             ty::Never => p!(write("!")),
497             ty::Tuple(ref tys) => {
498                 p!(write("("), comma_sep(tys.iter()));
499                 if tys.len() == 1 {
500                     p!(write(","));
501                 }
502                 p!(write(")"))
503             }
504             ty::FnDef(def_id, substs) => {
505                 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
506                 p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}"));
507             }
508             ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
509             ty::Infer(infer_ty) => {
510                 if let ty::TyVar(ty_vid) = infer_ty {
511                     if let Some(name) = self.infer_ty_name(ty_vid) {
512                         p!(write("{}", name))
513                     } else {
514                         p!(write("{}", infer_ty))
515                     }
516                 } else {
517                     p!(write("{}", infer_ty))
518                 }
519             }
520             ty::Error(_) => p!(write("[type error]")),
521             ty::Param(ref param_ty) => p!(write("{}", param_ty)),
522             ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
523                 ty::BoundTyKind::Anon => self.pretty_print_bound_var(debruijn, bound_ty.var)?,
524                 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
525             },
526             ty::Adt(def, substs) => {
527                 p!(print_def_path(def.did, substs));
528             }
529             ty::Dynamic(data, r) => {
530                 let print_r = self.region_should_not_be_omitted(r);
531                 if print_r {
532                     p!(write("("));
533                 }
534                 p!(write("dyn "), print(data));
535                 if print_r {
536                     p!(write(" + "), print(r), write(")"));
537                 }
538             }
539             ty::Foreign(def_id) => {
540                 p!(print_def_path(def_id, &[]));
541             }
542             ty::Projection(ref data) => p!(print(data)),
543             ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
544             ty::Opaque(def_id, substs) => {
545                 // FIXME(eddyb) print this with `print_def_path`.
546                 // We use verbose printing in 'NO_QUERIES' mode, to
547                 // avoid needing to call `predicates_of`. This should
548                 // only affect certain debug messages (e.g. messages printed
549                 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
550                 // and should have no effect on any compiler output.
551                 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
552                     p!(write("Opaque({:?}, {:?})", def_id, substs));
553                     return Ok(self);
554                 }
555
556                 return Ok(with_no_queries(|| {
557                     let def_key = self.tcx().def_key(def_id);
558                     if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
559                         p!(write("{}", name));
560                         // FIXME(eddyb) print this with `print_def_path`.
561                         if !substs.is_empty() {
562                             p!(write("::"));
563                             p!(generic_delimiters(|cx| cx.comma_sep(substs.iter())));
564                         }
565                         return Ok(self);
566                     }
567                     // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
568                     // by looking up the projections associated with the def_id.
569                     let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
570
571                     let mut first = true;
572                     let mut is_sized = false;
573                     p!(write("impl"));
574                     for predicate in bounds.predicates {
575                         // Note: We can't use `to_opt_poly_trait_ref` here as `predicate`
576                         // may contain unbound variables. We therefore do this manually.
577                         //
578                         // FIXME(lcnr): Find out why exactly this is the case :)
579                         if let ty::PredicateAtom::Trait(pred, _) =
580                             predicate.bound_atom(self.tcx()).skip_binder()
581                         {
582                             let trait_ref = ty::Binder::bind(pred.trait_ref);
583                             // Don't print +Sized, but rather +?Sized if absent.
584                             if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
585                                 is_sized = true;
586                                 continue;
587                             }
588
589                             p!(
590                                 write("{}", if first { " " } else { "+" }),
591                                 print(trait_ref.print_only_trait_path())
592                             );
593                             first = false;
594                         }
595                     }
596                     if !is_sized {
597                         p!(write("{}?Sized", if first { " " } else { "+" }));
598                     } else if first {
599                         p!(write(" Sized"));
600                     }
601                     Ok(self)
602                 })?);
603             }
604             ty::Str => p!(write("str")),
605             ty::Generator(did, substs, movability) => {
606                 match movability {
607                     hir::Movability::Movable => p!(write("[generator")),
608                     hir::Movability::Static => p!(write("[static generator")),
609                 }
610
611                 // FIXME(eddyb) should use `def_span`.
612                 if let Some(did) = did.as_local() {
613                     let hir_id = self.tcx().hir().as_local_hir_id(did);
614                     let span = self.tcx().hir().span(hir_id);
615                     p!(write("@{}", self.tcx().sess.source_map().span_to_string(span)));
616
617                     if substs.as_generator().is_valid() {
618                         let upvar_tys = substs.as_generator().upvar_tys();
619                         let mut sep = " ";
620                         for (&var_id, upvar_ty) in self
621                             .tcx()
622                             .upvars_mentioned(did)
623                             .as_ref()
624                             .iter()
625                             .flat_map(|v| v.keys())
626                             .zip(upvar_tys)
627                         {
628                             p!(write("{}{}:", sep, self.tcx().hir().name(var_id)), print(upvar_ty));
629                             sep = ", ";
630                         }
631                     }
632                 } else {
633                     p!(write("@{}", self.tcx().def_path_str(did)));
634
635                     if substs.as_generator().is_valid() {
636                         let upvar_tys = substs.as_generator().upvar_tys();
637                         let mut sep = " ";
638                         for (index, upvar_ty) in upvar_tys.enumerate() {
639                             p!(write("{}{}:", sep, index), print(upvar_ty));
640                             sep = ", ";
641                         }
642                     }
643                 }
644
645                 if substs.as_generator().is_valid() {
646                     p!(write(" "), print(substs.as_generator().witness()));
647                 }
648
649                 p!(write("]"))
650             }
651             ty::GeneratorWitness(types) => {
652                 p!(in_binder(&types));
653             }
654             ty::Closure(did, substs) => {
655                 p!(write("[closure"));
656
657                 // FIXME(eddyb) should use `def_span`.
658                 if let Some(did) = did.as_local() {
659                     let hir_id = self.tcx().hir().as_local_hir_id(did);
660                     if self.tcx().sess.opts.debugging_opts.span_free_formats {
661                         p!(write("@"), print_def_path(did.to_def_id(), substs));
662                     } else {
663                         let span = self.tcx().hir().span(hir_id);
664                         p!(write("@{}", self.tcx().sess.source_map().span_to_string(span)));
665                     }
666
667                     if substs.as_closure().is_valid() {
668                         let upvar_tys = substs.as_closure().upvar_tys();
669                         let mut sep = " ";
670                         for (&var_id, upvar_ty) in self
671                             .tcx()
672                             .upvars_mentioned(did)
673                             .as_ref()
674                             .iter()
675                             .flat_map(|v| v.keys())
676                             .zip(upvar_tys)
677                         {
678                             p!(write("{}{}:", sep, self.tcx().hir().name(var_id)), print(upvar_ty));
679                             sep = ", ";
680                         }
681                     }
682                 } else {
683                     p!(write("@{}", self.tcx().def_path_str(did)));
684
685                     if substs.as_closure().is_valid() {
686                         let upvar_tys = substs.as_closure().upvar_tys();
687                         let mut sep = " ";
688                         for (index, upvar_ty) in upvar_tys.enumerate() {
689                             p!(write("{}{}:", sep, index), print(upvar_ty));
690                             sep = ", ";
691                         }
692                     }
693                 }
694
695                 if self.tcx().sess.verbose() && substs.as_closure().is_valid() {
696                     p!(write(" closure_kind_ty="), print(substs.as_closure().kind_ty()));
697                     p!(
698                         write(" closure_sig_as_fn_ptr_ty="),
699                         print(substs.as_closure().sig_as_fn_ptr_ty())
700                     );
701                 }
702
703                 p!(write("]"))
704             }
705             ty::Array(ty, sz) => {
706                 p!(write("["), print(ty), write("; "));
707                 if self.tcx().sess.verbose() {
708                     p!(write("{:?}", sz));
709                 } else if let ty::ConstKind::Unevaluated(..) = sz.val {
710                     // Do not try to evaluate unevaluated constants. If we are const evaluating an
711                     // array length anon const, rustc will (with debug assertions) print the
712                     // constant's path. Which will end up here again.
713                     p!(write("_"));
714                 } else if let Some(n) = sz.val.try_to_bits(self.tcx().data_layout.pointer_size) {
715                     p!(write("{}", n));
716                 } else if let ty::ConstKind::Param(param) = sz.val {
717                     p!(write("{}", param));
718                 } else {
719                     p!(write("_"));
720                 }
721                 p!(write("]"))
722             }
723             ty::Slice(ty) => p!(write("["), print(ty), write("]")),
724         }
725
726         Ok(self)
727     }
728
729     fn pretty_print_bound_var(
730         &mut self,
731         debruijn: ty::DebruijnIndex,
732         var: ty::BoundVar,
733     ) -> Result<(), Self::Error> {
734         if debruijn == ty::INNERMOST {
735             write!(self, "^{}", var.index())
736         } else {
737             write!(self, "^{}_{}", debruijn.index(), var.index())
738         }
739     }
740
741     fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
742         None
743     }
744
745     fn pretty_print_dyn_existential(
746         mut self,
747         predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
748     ) -> Result<Self::DynExistential, Self::Error> {
749         define_scoped_cx!(self);
750
751         // Generate the main trait ref, including associated types.
752         let mut first = true;
753
754         if let Some(principal) = predicates.principal() {
755             p!(print_def_path(principal.def_id, &[]));
756
757             let mut resugared = false;
758
759             // Special-case `Fn(...) -> ...` and resugar it.
760             let fn_trait_kind = self.tcx().fn_trait_kind_from_lang_item(principal.def_id);
761             if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
762                 if let ty::Tuple(ref args) = principal.substs.type_at(0).kind {
763                     let mut projections = predicates.projection_bounds();
764                     if let (Some(proj), None) = (projections.next(), projections.next()) {
765                         let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
766                         p!(pretty_fn_sig(&tys, false, proj.ty));
767                         resugared = true;
768                     }
769                 }
770             }
771
772             // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
773             // in order to place the projections inside the `<...>`.
774             if !resugared {
775                 // Use a type that can't appear in defaults of type parameters.
776                 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
777                 let principal = principal.with_self_ty(self.tcx(), dummy_self);
778
779                 let args = self.generic_args_to_print(
780                     self.tcx().generics_of(principal.def_id),
781                     principal.substs,
782                 );
783
784                 // Don't print `'_` if there's no unerased regions.
785                 let print_regions = args.iter().any(|arg| match arg.unpack() {
786                     GenericArgKind::Lifetime(r) => *r != ty::ReErased,
787                     _ => false,
788                 });
789                 let mut args = args.iter().cloned().filter(|arg| match arg.unpack() {
790                     GenericArgKind::Lifetime(_) => print_regions,
791                     _ => true,
792                 });
793                 let mut projections = predicates.projection_bounds();
794
795                 let arg0 = args.next();
796                 let projection0 = projections.next();
797                 if arg0.is_some() || projection0.is_some() {
798                     let args = arg0.into_iter().chain(args);
799                     let projections = projection0.into_iter().chain(projections);
800
801                     p!(generic_delimiters(|mut cx| {
802                         cx = cx.comma_sep(args)?;
803                         if arg0.is_some() && projection0.is_some() {
804                             write!(cx, ", ")?;
805                         }
806                         cx.comma_sep(projections)
807                     }));
808                 }
809             }
810             first = false;
811         }
812
813         // Builtin bounds.
814         // FIXME(eddyb) avoid printing twice (needed to ensure
815         // that the auto traits are sorted *and* printed via cx).
816         let mut auto_traits: Vec<_> =
817             predicates.auto_traits().map(|did| (self.tcx().def_path_str(did), did)).collect();
818
819         // The auto traits come ordered by `DefPathHash`. While
820         // `DefPathHash` is *stable* in the sense that it depends on
821         // neither the host nor the phase of the moon, it depends
822         // "pseudorandomly" on the compiler version and the target.
823         //
824         // To avoid that causing instabilities in compiletest
825         // output, sort the auto-traits alphabetically.
826         auto_traits.sort();
827
828         for (_, def_id) in auto_traits {
829             if !first {
830                 p!(write(" + "));
831             }
832             first = false;
833
834             p!(print_def_path(def_id, &[]));
835         }
836
837         Ok(self)
838     }
839
840     fn pretty_fn_sig(
841         mut self,
842         inputs: &[Ty<'tcx>],
843         c_variadic: bool,
844         output: Ty<'tcx>,
845     ) -> Result<Self, Self::Error> {
846         define_scoped_cx!(self);
847
848         p!(write("("), comma_sep(inputs.iter().copied()));
849         if c_variadic {
850             if !inputs.is_empty() {
851                 p!(write(", "));
852             }
853             p!(write("..."));
854         }
855         p!(write(")"));
856         if !output.is_unit() {
857             p!(write(" -> "), print(output));
858         }
859
860         Ok(self)
861     }
862
863     fn pretty_print_const(
864         mut self,
865         ct: &'tcx ty::Const<'tcx>,
866         print_ty: bool,
867     ) -> Result<Self::Const, Self::Error> {
868         define_scoped_cx!(self);
869
870         if self.tcx().sess.verbose() {
871             p!(write("Const({:?}: {:?})", ct.val, ct.ty));
872             return Ok(self);
873         }
874
875         macro_rules! print_underscore {
876             () => {{
877                 if print_ty {
878                     self = self.typed_value(
879                         |mut this| {
880                             write!(this, "_")?;
881                             Ok(this)
882                         },
883                         |this| this.print_type(ct.ty),
884                         ": ",
885                     )?;
886                 } else {
887                     write!(self, "_")?;
888                 }
889             }};
890         }
891
892         match ct.val {
893             ty::ConstKind::Unevaluated(def, substs, promoted) => {
894                 if let Some(promoted) = promoted {
895                     p!(print_value_path(def.did, substs));
896                     p!(write("::{:?}", promoted));
897                 } else {
898                     match self.tcx().def_kind(def.did) {
899                         DefKind::Static | DefKind::Const | DefKind::AssocConst => {
900                             p!(print_value_path(def.did, substs))
901                         }
902                         _ => {
903                             if def.is_local() {
904                                 let span = self.tcx().def_span(def.did);
905                                 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
906                                 {
907                                     p!(write("{}", snip))
908                                 } else {
909                                     print_underscore!()
910                                 }
911                             } else {
912                                 print_underscore!()
913                             }
914                         }
915                     }
916                 }
917             }
918             ty::ConstKind::Infer(..) => print_underscore!(),
919             ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
920             ty::ConstKind::Value(value) => {
921                 return self.pretty_print_const_value(value, ct.ty, print_ty);
922             }
923
924             ty::ConstKind::Bound(debruijn, bound_var) => {
925                 self.pretty_print_bound_var(debruijn, bound_var)?
926             }
927             ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
928             ty::ConstKind::Error(_) => p!(write("[const error]")),
929         };
930         Ok(self)
931     }
932
933     fn pretty_print_const_scalar(
934         mut self,
935         scalar: Scalar,
936         ty: Ty<'tcx>,
937         print_ty: bool,
938     ) -> Result<Self::Const, Self::Error> {
939         define_scoped_cx!(self);
940
941         match (scalar, &ty.kind) {
942             // Byte strings (&[u8; N])
943             (
944                 Scalar::Ptr(ptr),
945                 ty::Ref(
946                     _,
947                     ty::TyS {
948                         kind:
949                             ty::Array(
950                                 ty::TyS { kind: ty::Uint(ast::UintTy::U8), .. },
951                                 ty::Const {
952                                     val:
953                                         ty::ConstKind::Value(ConstValue::Scalar(Scalar::Raw {
954                                             data,
955                                             ..
956                                         })),
957                                     ..
958                                 },
959                             ),
960                         ..
961                     },
962                     _,
963                 ),
964             ) => match self.tcx().get_global_alloc(ptr.alloc_id) {
965                 Some(GlobalAlloc::Memory(alloc)) => {
966                     if let Ok(byte_str) = alloc.get_bytes(&self.tcx(), ptr, Size::from_bytes(*data))
967                     {
968                         p!(pretty_print_byte_str(byte_str))
969                     } else {
970                         p!(write("<too short allocation>"))
971                     }
972                 }
973                 // FIXME: for statics and functions, we could in principle print more detail.
974                 Some(GlobalAlloc::Static(def_id)) => p!(write("<static({:?})>", def_id)),
975                 Some(GlobalAlloc::Function(_)) => p!(write("<function>")),
976                 None => p!(write("<dangling pointer>")),
977             },
978             // Bool
979             (Scalar::Raw { data: 0, .. }, ty::Bool) => p!(write("false")),
980             (Scalar::Raw { data: 1, .. }, ty::Bool) => p!(write("true")),
981             // Float
982             (Scalar::Raw { data, .. }, ty::Float(ast::FloatTy::F32)) => {
983                 p!(write("{}f32", Single::from_bits(data)))
984             }
985             (Scalar::Raw { data, .. }, ty::Float(ast::FloatTy::F64)) => {
986                 p!(write("{}f64", Double::from_bits(data)))
987             }
988             // Int
989             (Scalar::Raw { data, .. }, ty::Uint(ui)) => {
990                 let size = Integer::from_attr(&self.tcx(), UnsignedInt(*ui)).size();
991                 let int = ConstInt::new(data, size, false, ty.is_ptr_sized_integral());
992                 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
993             }
994             (Scalar::Raw { data, .. }, ty::Int(i)) => {
995                 let size = Integer::from_attr(&self.tcx(), SignedInt(*i)).size();
996                 let int = ConstInt::new(data, size, true, ty.is_ptr_sized_integral());
997                 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
998             }
999             // Char
1000             (Scalar::Raw { data, .. }, ty::Char) if char::from_u32(data as u32).is_some() => {
1001                 p!(write("{:?}", char::from_u32(data as u32).unwrap()))
1002             }
1003             // Raw pointers
1004             (Scalar::Raw { data, .. }, ty::RawPtr(_)) => {
1005                 self = self.typed_value(
1006                     |mut this| {
1007                         write!(this, "0x{:x}", data)?;
1008                         Ok(this)
1009                     },
1010                     |this| this.print_type(ty),
1011                     " as ",
1012                 )?;
1013             }
1014             (Scalar::Ptr(ptr), ty::FnPtr(_)) => {
1015                 // FIXME: this can ICE when the ptr is dangling or points to a non-function.
1016                 // We should probably have a helper method to share code with the "Byte strings"
1017                 // printing above (which also has to handle pointers to all sorts of things).
1018                 let instance = self.tcx().global_alloc(ptr.alloc_id).unwrap_fn();
1019                 self = self.typed_value(
1020                     |this| this.print_value_path(instance.def_id(), instance.substs),
1021                     |this| this.print_type(ty),
1022                     " as ",
1023                 )?;
1024             }
1025             // For function type zsts just printing the path is enough
1026             (Scalar::Raw { size: 0, .. }, ty::FnDef(d, s)) => p!(print_value_path(*d, s)),
1027             // Nontrivial types with scalar bit representation
1028             (Scalar::Raw { data, size }, _) => {
1029                 let print = |mut this: Self| {
1030                     if size == 0 {
1031                         write!(this, "transmute(())")?;
1032                     } else {
1033                         write!(this, "transmute(0x{:01$x})", data, size as usize * 2)?;
1034                     }
1035                     Ok(this)
1036                 };
1037                 self = if print_ty {
1038                     self.typed_value(print, |this| this.print_type(ty), ": ")?
1039                 } else {
1040                     print(self)?
1041                 };
1042             }
1043             // Any pointer values not covered by a branch above
1044             (Scalar::Ptr(p), _) => {
1045                 self = self.pretty_print_const_pointer(p, ty, print_ty)?;
1046             }
1047         }
1048         Ok(self)
1049     }
1050
1051     /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1052     /// from MIR where it is actually useful.
1053     fn pretty_print_const_pointer(
1054         mut self,
1055         _: Pointer,
1056         ty: Ty<'tcx>,
1057         print_ty: bool,
1058     ) -> Result<Self::Const, Self::Error> {
1059         if print_ty {
1060             self.typed_value(
1061                 |mut this| {
1062                     this.write_str("&_")?;
1063                     Ok(this)
1064                 },
1065                 |this| this.print_type(ty),
1066                 ": ",
1067             )
1068         } else {
1069             self.write_str("&_")?;
1070             Ok(self)
1071         }
1072     }
1073
1074     fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1075         define_scoped_cx!(self);
1076         p!(write("b\""));
1077         for &c in byte_str {
1078             for e in std::ascii::escape_default(c) {
1079                 self.write_char(e as char)?;
1080             }
1081         }
1082         p!(write("\""));
1083         Ok(self)
1084     }
1085
1086     fn pretty_print_const_value(
1087         mut self,
1088         ct: ConstValue<'tcx>,
1089         ty: Ty<'tcx>,
1090         print_ty: bool,
1091     ) -> Result<Self::Const, Self::Error> {
1092         define_scoped_cx!(self);
1093
1094         if self.tcx().sess.verbose() {
1095             p!(write("ConstValue({:?}: ", ct), print(ty), write(")"));
1096             return Ok(self);
1097         }
1098
1099         let u8_type = self.tcx().types.u8;
1100
1101         match (ct, &ty.kind) {
1102             // Byte/string slices, printed as (byte) string literals.
1103             (
1104                 ConstValue::Slice { data, start, end },
1105                 ty::Ref(_, ty::TyS { kind: ty::Slice(t), .. }, _),
1106             ) if *t == u8_type => {
1107                 // The `inspect` here is okay since we checked the bounds, and there are
1108                 // no relocations (we have an active slice reference here). We don't use
1109                 // this result to affect interpreter execution.
1110                 let byte_str = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1111                 self.pretty_print_byte_str(byte_str)
1112             }
1113             (
1114                 ConstValue::Slice { data, start, end },
1115                 ty::Ref(_, ty::TyS { kind: ty::Str, .. }, _),
1116             ) => {
1117                 // The `inspect` here is okay since we checked the bounds, and there are no
1118                 // relocations (we have an active `str` reference here). We don't use this
1119                 // result to affect interpreter execution.
1120                 let slice = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1121                 let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
1122                 p!(write("{:?}", s));
1123                 Ok(self)
1124             }
1125             (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
1126                 let n = n.val.try_to_bits(self.tcx().data_layout.pointer_size).unwrap();
1127                 // cast is ok because we already checked for pointer size (32 or 64 bit) above
1128                 let n = Size::from_bytes(n);
1129                 let ptr = Pointer::new(AllocId(0), offset);
1130
1131                 let byte_str = alloc.get_bytes(&self.tcx(), ptr, n).unwrap();
1132                 p!(write("*"));
1133                 p!(pretty_print_byte_str(byte_str));
1134                 Ok(self)
1135             }
1136
1137             // Aggregates, printed as array/tuple/struct/variant construction syntax.
1138             //
1139             // NB: the `has_param_types_or_consts` check ensures that we can use
1140             // the `destructure_const` query with an empty `ty::ParamEnv` without
1141             // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1142             // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1143             // to be able to destructure the tuple into `(0u8, *mut T)
1144             //
1145             // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
1146             // correct `ty::ParamEnv` to allow printing *all* constant values.
1147             (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_param_types_or_consts() => {
1148                 let contents = self.tcx().destructure_const(
1149                     ty::ParamEnv::reveal_all()
1150                         .and(self.tcx().mk_const(ty::Const { val: ty::ConstKind::Value(ct), ty })),
1151                 );
1152                 let fields = contents.fields.iter().copied();
1153
1154                 match ty.kind {
1155                     ty::Array(..) => {
1156                         p!(write("["), comma_sep(fields), write("]"));
1157                     }
1158                     ty::Tuple(..) => {
1159                         p!(write("("), comma_sep(fields));
1160                         if contents.fields.len() == 1 {
1161                             p!(write(","));
1162                         }
1163                         p!(write(")"));
1164                     }
1165                     ty::Adt(def, substs) if def.variants.is_empty() => {
1166                         p!(print_value_path(def.did, substs));
1167                     }
1168                     ty::Adt(def, substs) => {
1169                         let variant_id =
1170                             contents.variant.expect("destructed const of adt without variant id");
1171                         let variant_def = &def.variants[variant_id];
1172                         p!(print_value_path(variant_def.def_id, substs));
1173
1174                         match variant_def.ctor_kind {
1175                             CtorKind::Const => {}
1176                             CtorKind::Fn => {
1177                                 p!(write("("), comma_sep(fields), write(")"));
1178                             }
1179                             CtorKind::Fictive => {
1180                                 p!(write(" {{ "));
1181                                 let mut first = true;
1182                                 for (field_def, field) in variant_def.fields.iter().zip(fields) {
1183                                     if !first {
1184                                         p!(write(", "));
1185                                     }
1186                                     p!(write("{}: ", field_def.ident), print(field));
1187                                     first = false;
1188                                 }
1189                                 p!(write(" }}"));
1190                             }
1191                         }
1192                     }
1193                     _ => unreachable!(),
1194                 }
1195
1196                 Ok(self)
1197             }
1198
1199             (ConstValue::Scalar(scalar), _) => self.pretty_print_const_scalar(scalar, ty, print_ty),
1200
1201             // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1202             // their fields instead of just dumping the memory.
1203             _ => {
1204                 // fallback
1205                 p!(write("{:?}", ct));
1206                 if print_ty {
1207                     p!(write(": "), print(ty));
1208                 }
1209                 Ok(self)
1210             }
1211         }
1212     }
1213 }
1214
1215 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1216 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1217
1218 pub struct FmtPrinterData<'a, 'tcx, F> {
1219     tcx: TyCtxt<'tcx>,
1220     fmt: F,
1221
1222     empty_path: bool,
1223     in_value: bool,
1224     pub print_alloc_ids: bool,
1225
1226     used_region_names: FxHashSet<Symbol>,
1227     region_index: usize,
1228     binder_depth: usize,
1229
1230     pub region_highlight_mode: RegionHighlightMode,
1231
1232     pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
1233 }
1234
1235 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1236     type Target = FmtPrinterData<'a, 'tcx, F>;
1237     fn deref(&self) -> &Self::Target {
1238         &self.0
1239     }
1240 }
1241
1242 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1243     fn deref_mut(&mut self) -> &mut Self::Target {
1244         &mut self.0
1245     }
1246 }
1247
1248 impl<F> FmtPrinter<'a, 'tcx, F> {
1249     pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1250         FmtPrinter(Box::new(FmtPrinterData {
1251             tcx,
1252             fmt,
1253             empty_path: false,
1254             in_value: ns == Namespace::ValueNS,
1255             print_alloc_ids: false,
1256             used_region_names: Default::default(),
1257             region_index: 0,
1258             binder_depth: 0,
1259             region_highlight_mode: RegionHighlightMode::default(),
1260             name_resolver: None,
1261         }))
1262     }
1263 }
1264
1265 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1266 // (but also some things just print a `DefId` generally so maybe we need this?)
1267 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1268     match tcx.def_key(def_id).disambiguated_data.data {
1269         DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1270             Namespace::TypeNS
1271         }
1272
1273         DefPathData::ValueNs(..)
1274         | DefPathData::AnonConst
1275         | DefPathData::ClosureExpr
1276         | DefPathData::Ctor => Namespace::ValueNS,
1277
1278         DefPathData::MacroNs(..) => Namespace::MacroNS,
1279
1280         _ => Namespace::TypeNS,
1281     }
1282 }
1283
1284 impl TyCtxt<'t> {
1285     /// Returns a string identifying this `DefId`. This string is
1286     /// suitable for user output.
1287     pub fn def_path_str(self, def_id: DefId) -> String {
1288         self.def_path_str_with_substs(def_id, &[])
1289     }
1290
1291     pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1292         let ns = guess_def_namespace(self, def_id);
1293         debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1294         let mut s = String::new();
1295         let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1296         s
1297     }
1298 }
1299
1300 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1301     fn write_str(&mut self, s: &str) -> fmt::Result {
1302         self.fmt.write_str(s)
1303     }
1304 }
1305
1306 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1307     type Error = fmt::Error;
1308
1309     type Path = Self;
1310     type Region = Self;
1311     type Type = Self;
1312     type DynExistential = Self;
1313     type Const = Self;
1314
1315     fn tcx(&'a self) -> TyCtxt<'tcx> {
1316         self.tcx
1317     }
1318
1319     fn print_def_path(
1320         mut self,
1321         def_id: DefId,
1322         substs: &'tcx [GenericArg<'tcx>],
1323     ) -> Result<Self::Path, Self::Error> {
1324         define_scoped_cx!(self);
1325
1326         if substs.is_empty() {
1327             match self.try_print_visible_def_path(def_id)? {
1328                 (cx, true) => return Ok(cx),
1329                 (cx, false) => self = cx,
1330             }
1331         }
1332
1333         let key = self.tcx.def_key(def_id);
1334         if let DefPathData::Impl = key.disambiguated_data.data {
1335             // Always use types for non-local impls, where types are always
1336             // available, and filename/line-number is mostly uninteresting.
1337             let use_types = !def_id.is_local() || {
1338                 // Otherwise, use filename/line-number if forced.
1339                 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1340                 !force_no_types
1341             };
1342
1343             if !use_types {
1344                 // If no type info is available, fall back to
1345                 // pretty printing some span information. This should
1346                 // only occur very early in the compiler pipeline.
1347                 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1348                 let span = self.tcx.def_span(def_id);
1349
1350                 self = self.print_def_path(parent_def_id, &[])?;
1351
1352                 // HACK(eddyb) copy of `path_append` to avoid
1353                 // constructing a `DisambiguatedDefPathData`.
1354                 if !self.empty_path {
1355                     write!(self, "::")?;
1356                 }
1357                 write!(self, "<impl at {}>", self.tcx.sess.source_map().span_to_string(span))?;
1358                 self.empty_path = false;
1359
1360                 return Ok(self);
1361             }
1362         }
1363
1364         self.default_print_def_path(def_id, substs)
1365     }
1366
1367     fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1368         self.pretty_print_region(region)
1369     }
1370
1371     fn print_type(self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1372         self.pretty_print_type(ty)
1373     }
1374
1375     fn print_dyn_existential(
1376         self,
1377         predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1378     ) -> Result<Self::DynExistential, Self::Error> {
1379         self.pretty_print_dyn_existential(predicates)
1380     }
1381
1382     fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1383         self.pretty_print_const(ct, true)
1384     }
1385
1386     fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1387         self.empty_path = true;
1388         if cnum == LOCAL_CRATE {
1389             if self.tcx.sess.rust_2018() {
1390                 // We add the `crate::` keyword on Rust 2018, only when desired.
1391                 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1392                     write!(self, "{}", kw::Crate)?;
1393                     self.empty_path = false;
1394                 }
1395             }
1396         } else {
1397             write!(self, "{}", self.tcx.crate_name(cnum))?;
1398             self.empty_path = false;
1399         }
1400         Ok(self)
1401     }
1402
1403     fn path_qualified(
1404         mut self,
1405         self_ty: Ty<'tcx>,
1406         trait_ref: Option<ty::TraitRef<'tcx>>,
1407     ) -> Result<Self::Path, Self::Error> {
1408         self = self.pretty_path_qualified(self_ty, trait_ref)?;
1409         self.empty_path = false;
1410         Ok(self)
1411     }
1412
1413     fn path_append_impl(
1414         mut self,
1415         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1416         _disambiguated_data: &DisambiguatedDefPathData,
1417         self_ty: Ty<'tcx>,
1418         trait_ref: Option<ty::TraitRef<'tcx>>,
1419     ) -> Result<Self::Path, Self::Error> {
1420         self = self.pretty_path_append_impl(
1421             |mut cx| {
1422                 cx = print_prefix(cx)?;
1423                 if !cx.empty_path {
1424                     write!(cx, "::")?;
1425                 }
1426
1427                 Ok(cx)
1428             },
1429             self_ty,
1430             trait_ref,
1431         )?;
1432         self.empty_path = false;
1433         Ok(self)
1434     }
1435
1436     fn path_append(
1437         mut self,
1438         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1439         disambiguated_data: &DisambiguatedDefPathData,
1440     ) -> Result<Self::Path, Self::Error> {
1441         self = print_prefix(self)?;
1442
1443         // Skip `::{{constructor}}` on tuple/unit structs.
1444         if let DefPathData::Ctor = disambiguated_data.data {
1445             return Ok(self);
1446         }
1447
1448         // FIXME(eddyb) `name` should never be empty, but it
1449         // currently is for `extern { ... }` "foreign modules".
1450         let name = disambiguated_data.data.as_symbol();
1451         if name != kw::Invalid {
1452             if !self.empty_path {
1453                 write!(self, "::")?;
1454             }
1455             if Ident::with_dummy_span(name).is_raw_guess() {
1456                 write!(self, "r#")?;
1457             }
1458             write!(self, "{}", name)?;
1459
1460             // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1461             // might be nicer to use something else, e.g. `{closure#3}`.
1462             let dis = disambiguated_data.disambiguator;
1463             let print_dis = disambiguated_data.data.get_opt_name().is_none()
1464                 || dis != 0 && self.tcx.sess.verbose();
1465             if print_dis {
1466                 write!(self, "#{}", dis)?;
1467             }
1468
1469             self.empty_path = false;
1470         }
1471
1472         Ok(self)
1473     }
1474
1475     fn path_generic_args(
1476         mut self,
1477         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1478         args: &[GenericArg<'tcx>],
1479     ) -> Result<Self::Path, Self::Error> {
1480         self = print_prefix(self)?;
1481
1482         // Don't print `'_` if there's no unerased regions.
1483         let print_regions = args.iter().any(|arg| match arg.unpack() {
1484             GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1485             _ => false,
1486         });
1487         let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1488             GenericArgKind::Lifetime(_) => print_regions,
1489             _ => true,
1490         });
1491
1492         if args.clone().next().is_some() {
1493             if self.in_value {
1494                 write!(self, "::")?;
1495             }
1496             self.generic_delimiters(|cx| cx.comma_sep(args))
1497         } else {
1498             Ok(self)
1499         }
1500     }
1501 }
1502
1503 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1504     fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1505         self.0.name_resolver.as_ref().and_then(|func| func(id))
1506     }
1507
1508     fn print_value_path(
1509         mut self,
1510         def_id: DefId,
1511         substs: &'tcx [GenericArg<'tcx>],
1512     ) -> Result<Self::Path, Self::Error> {
1513         let was_in_value = std::mem::replace(&mut self.in_value, true);
1514         self = self.print_def_path(def_id, substs)?;
1515         self.in_value = was_in_value;
1516
1517         Ok(self)
1518     }
1519
1520     fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1521     where
1522         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1523     {
1524         self.pretty_in_binder(value)
1525     }
1526
1527     fn typed_value(
1528         mut self,
1529         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1530         t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1531         conversion: &str,
1532     ) -> Result<Self::Const, Self::Error> {
1533         self.write_str("{")?;
1534         self = f(self)?;
1535         self.write_str(conversion)?;
1536         let was_in_value = std::mem::replace(&mut self.in_value, false);
1537         self = t(self)?;
1538         self.in_value = was_in_value;
1539         self.write_str("}")?;
1540         Ok(self)
1541     }
1542
1543     fn generic_delimiters(
1544         mut self,
1545         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1546     ) -> Result<Self, Self::Error> {
1547         write!(self, "<")?;
1548
1549         let was_in_value = std::mem::replace(&mut self.in_value, false);
1550         let mut inner = f(self)?;
1551         inner.in_value = was_in_value;
1552
1553         write!(inner, ">")?;
1554         Ok(inner)
1555     }
1556
1557     fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1558         let highlight = self.region_highlight_mode;
1559         if highlight.region_highlighted(region).is_some() {
1560             return true;
1561         }
1562
1563         if self.tcx.sess.verbose() {
1564             return true;
1565         }
1566
1567         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1568
1569         match *region {
1570             ty::ReEarlyBound(ref data) => {
1571                 data.name != kw::Invalid && data.name != kw::UnderscoreLifetime
1572             }
1573
1574             ty::ReLateBound(_, br)
1575             | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1576             | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1577                 if let ty::BrNamed(_, name) = br {
1578                     if name != kw::Invalid && name != kw::UnderscoreLifetime {
1579                         return true;
1580                     }
1581                 }
1582
1583                 if let Some((region, _)) = highlight.highlight_bound_region {
1584                     if br == region {
1585                         return true;
1586                     }
1587                 }
1588
1589                 false
1590             }
1591
1592             ty::ReVar(_) if identify_regions => true,
1593
1594             ty::ReVar(_) | ty::ReErased => false,
1595
1596             ty::ReStatic | ty::ReEmpty(_) => true,
1597         }
1598     }
1599
1600     fn pretty_print_const_pointer(
1601         self,
1602         p: Pointer,
1603         ty: Ty<'tcx>,
1604         print_ty: bool,
1605     ) -> Result<Self::Const, Self::Error> {
1606         let print = |mut this: Self| {
1607             define_scoped_cx!(this);
1608             if this.print_alloc_ids {
1609                 p!(write("{:?}", p));
1610             } else {
1611                 p!(write("&_"));
1612             }
1613             Ok(this)
1614         };
1615         if print_ty {
1616             self.typed_value(print, |this| this.print_type(ty), ": ")
1617         } else {
1618             print(self)
1619         }
1620     }
1621 }
1622
1623 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1624 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1625     pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1626         define_scoped_cx!(self);
1627
1628         // Watch out for region highlights.
1629         let highlight = self.region_highlight_mode;
1630         if let Some(n) = highlight.region_highlighted(region) {
1631             p!(write("'{}", n));
1632             return Ok(self);
1633         }
1634
1635         if self.tcx.sess.verbose() {
1636             p!(write("{:?}", region));
1637             return Ok(self);
1638         }
1639
1640         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1641
1642         // These printouts are concise.  They do not contain all the information
1643         // the user might want to diagnose an error, but there is basically no way
1644         // to fit that into a short string.  Hence the recommendation to use
1645         // `explain_region()` or `note_and_explain_region()`.
1646         match *region {
1647             ty::ReEarlyBound(ref data) => {
1648                 if data.name != kw::Invalid {
1649                     p!(write("{}", data.name));
1650                     return Ok(self);
1651                 }
1652             }
1653             ty::ReLateBound(_, br)
1654             | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1655             | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1656                 if let ty::BrNamed(_, name) = br {
1657                     if name != kw::Invalid && name != kw::UnderscoreLifetime {
1658                         p!(write("{}", name));
1659                         return Ok(self);
1660                     }
1661                 }
1662
1663                 if let Some((region, counter)) = highlight.highlight_bound_region {
1664                     if br == region {
1665                         p!(write("'{}", counter));
1666                         return Ok(self);
1667                     }
1668                 }
1669             }
1670             ty::ReVar(region_vid) if identify_regions => {
1671                 p!(write("{:?}", region_vid));
1672                 return Ok(self);
1673             }
1674             ty::ReVar(_) => {}
1675             ty::ReErased => {}
1676             ty::ReStatic => {
1677                 p!(write("'static"));
1678                 return Ok(self);
1679             }
1680             ty::ReEmpty(ty::UniverseIndex::ROOT) => {
1681                 p!(write("'<empty>"));
1682                 return Ok(self);
1683             }
1684             ty::ReEmpty(ui) => {
1685                 p!(write("'<empty:{:?}>", ui));
1686                 return Ok(self);
1687             }
1688         }
1689
1690         p!(write("'_"));
1691
1692         Ok(self)
1693     }
1694 }
1695
1696 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1697 // `region_index` and `used_region_names`.
1698 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1699     pub fn name_all_regions<T>(
1700         mut self,
1701         value: &ty::Binder<T>,
1702     ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error>
1703     where
1704         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1705     {
1706         fn name_by_region_index(index: usize) -> Symbol {
1707             match index {
1708                 0 => Symbol::intern("'r"),
1709                 1 => Symbol::intern("'s"),
1710                 i => Symbol::intern(&format!("'t{}", i - 2)),
1711             }
1712         }
1713
1714         // Replace any anonymous late-bound regions with named
1715         // variants, using new unique identifiers, so that we can
1716         // clearly differentiate between named and unnamed regions in
1717         // the output. We'll probably want to tweak this over time to
1718         // decide just how much information to give.
1719         if self.binder_depth == 0 {
1720             self.prepare_late_bound_region_info(value);
1721         }
1722
1723         let mut empty = true;
1724         let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1725             write!(
1726                 cx,
1727                 "{}",
1728                 if empty {
1729                     empty = false;
1730                     start
1731                 } else {
1732                     cont
1733                 }
1734             )
1735         };
1736
1737         define_scoped_cx!(self);
1738
1739         let mut region_index = self.region_index;
1740         let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1741             let _ = start_or_continue(&mut self, "for<", ", ");
1742             let br = match br {
1743                 ty::BrNamed(_, name) => {
1744                     let _ = write!(self, "{}", name);
1745                     br
1746                 }
1747                 ty::BrAnon(_) | ty::BrEnv => {
1748                     let name = loop {
1749                         let name = name_by_region_index(region_index);
1750                         region_index += 1;
1751                         if !self.used_region_names.contains(&name) {
1752                             break name;
1753                         }
1754                     };
1755                     let _ = write!(self, "{}", name);
1756                     ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1757                 }
1758             };
1759             self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1760         });
1761         start_or_continue(&mut self, "", "> ")?;
1762
1763         self.binder_depth += 1;
1764         self.region_index = region_index;
1765         Ok((self, new_value))
1766     }
1767
1768     pub fn pretty_in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1769     where
1770         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1771     {
1772         let old_region_index = self.region_index;
1773         let (new, new_value) = self.name_all_regions(value)?;
1774         let mut inner = new_value.0.print(new)?;
1775         inner.region_index = old_region_index;
1776         inner.binder_depth -= 1;
1777         Ok(inner)
1778     }
1779
1780     fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1781     where
1782         T: TypeFoldable<'tcx>,
1783     {
1784         struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<Symbol>);
1785         impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1786             fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1787                 if let ty::ReLateBound(_, ty::BrNamed(_, name)) = *r {
1788                     self.0.insert(name);
1789                 }
1790                 r.super_visit_with(self)
1791             }
1792         }
1793
1794         self.used_region_names.clear();
1795         let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1796         value.visit_with(&mut collector);
1797         self.region_index = 0;
1798     }
1799 }
1800
1801 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1802 where
1803     T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1804 {
1805     type Output = P;
1806     type Error = P::Error;
1807     fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1808         cx.in_binder(self)
1809     }
1810 }
1811
1812 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1813 where
1814     T: Print<'tcx, P, Output = P, Error = P::Error>,
1815     U: Print<'tcx, P, Output = P, Error = P::Error>,
1816 {
1817     type Output = P;
1818     type Error = P::Error;
1819     fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1820         define_scoped_cx!(cx);
1821         p!(print(self.0), write(": "), print(self.1));
1822         Ok(cx)
1823     }
1824 }
1825
1826 macro_rules! forward_display_to_print {
1827     ($($ty:ty),+) => {
1828         $(impl fmt::Display for $ty {
1829             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1830                 ty::tls::with(|tcx| {
1831                     tcx.lift(self)
1832                         .expect("could not lift for printing")
1833                         .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1834                     Ok(())
1835                 })
1836             }
1837         })+
1838     };
1839 }
1840
1841 macro_rules! define_print_and_forward_display {
1842     (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1843         $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1844             type Output = P;
1845             type Error = fmt::Error;
1846             fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1847                 #[allow(unused_mut)]
1848                 let mut $cx = $cx;
1849                 define_scoped_cx!($cx);
1850                 let _: () = $print;
1851                 #[allow(unreachable_code)]
1852                 Ok($cx)
1853             }
1854         })+
1855
1856         forward_display_to_print!($($ty),+);
1857     };
1858 }
1859
1860 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1861 impl fmt::Display for ty::RegionKind {
1862     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1863         ty::tls::with(|tcx| {
1864             self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1865             Ok(())
1866         })
1867     }
1868 }
1869
1870 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
1871 /// the trait path. That is, it will print `Trait<U>` instead of
1872 /// `<T as Trait<U>>`.
1873 #[derive(Copy, Clone, TypeFoldable, Lift)]
1874 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
1875
1876 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
1877     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1878         fmt::Display::fmt(self, f)
1879     }
1880 }
1881
1882 impl ty::TraitRef<'tcx> {
1883     pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
1884         TraitRefPrintOnlyTraitPath(self)
1885     }
1886 }
1887
1888 impl ty::Binder<ty::TraitRef<'tcx>> {
1889     pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> {
1890         self.map_bound(|tr| tr.print_only_trait_path())
1891     }
1892 }
1893
1894 forward_display_to_print! {
1895     Ty<'tcx>,
1896     &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1897     &'tcx ty::Const<'tcx>,
1898
1899     // HACK(eddyb) these are exhaustive instead of generic,
1900     // because `for<'tcx>` isn't possible yet.
1901     ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1902     ty::Binder<ty::TraitRef<'tcx>>,
1903     ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>,
1904     ty::Binder<ty::FnSig<'tcx>>,
1905     ty::Binder<ty::TraitPredicate<'tcx>>,
1906     ty::Binder<ty::SubtypePredicate<'tcx>>,
1907     ty::Binder<ty::ProjectionPredicate<'tcx>>,
1908     ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1909     ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1910
1911     ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1912     ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1913 }
1914
1915 define_print_and_forward_display! {
1916     (self, cx):
1917
1918     &'tcx ty::List<Ty<'tcx>> {
1919         p!(write("{{"), comma_sep(self.iter()), write("}}"))
1920     }
1921
1922     ty::TypeAndMut<'tcx> {
1923         p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
1924     }
1925
1926     ty::ExistentialTraitRef<'tcx> {
1927         // Use a type that can't appear in defaults of type parameters.
1928         let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1929         let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1930         p!(print(trait_ref.print_only_trait_path()))
1931     }
1932
1933     ty::ExistentialProjection<'tcx> {
1934         let name = cx.tcx().associated_item(self.item_def_id).ident;
1935         p!(write("{} = ", name), print(self.ty))
1936     }
1937
1938     ty::ExistentialPredicate<'tcx> {
1939         match *self {
1940             ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1941             ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1942             ty::ExistentialPredicate::AutoTrait(def_id) => {
1943                 p!(print_def_path(def_id, &[]));
1944             }
1945         }
1946     }
1947
1948     ty::FnSig<'tcx> {
1949         p!(write("{}", self.unsafety.prefix_str()));
1950
1951         if self.abi != Abi::Rust {
1952             p!(write("extern {} ", self.abi));
1953         }
1954
1955         p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1956     }
1957
1958     ty::InferTy {
1959         if cx.tcx().sess.verbose() {
1960             p!(write("{:?}", self));
1961             return Ok(cx);
1962         }
1963         match *self {
1964             ty::TyVar(_) => p!(write("_")),
1965             ty::IntVar(_) => p!(write("{}", "{integer}")),
1966             ty::FloatVar(_) => p!(write("{}", "{float}")),
1967             ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1968             ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1969             ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1970         }
1971     }
1972
1973     ty::TraitRef<'tcx> {
1974         p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
1975     }
1976
1977     TraitRefPrintOnlyTraitPath<'tcx> {
1978         p!(print_def_path(self.0.def_id, self.0.substs));
1979     }
1980
1981     ty::ParamTy {
1982         p!(write("{}", self.name))
1983     }
1984
1985     ty::ParamConst {
1986         p!(write("{}", self.name))
1987     }
1988
1989     ty::SubtypePredicate<'tcx> {
1990         p!(print(self.a), write(" <: "), print(self.b))
1991     }
1992
1993     ty::TraitPredicate<'tcx> {
1994         p!(print(self.trait_ref.self_ty()), write(": "),
1995            print(self.trait_ref.print_only_trait_path()))
1996     }
1997
1998     ty::ProjectionPredicate<'tcx> {
1999         p!(print(self.projection_ty), write(" == "), print(self.ty))
2000     }
2001
2002     ty::ProjectionTy<'tcx> {
2003         p!(print_def_path(self.item_def_id, self.substs));
2004     }
2005
2006     ty::ClosureKind {
2007         match *self {
2008             ty::ClosureKind::Fn => p!(write("Fn")),
2009             ty::ClosureKind::FnMut => p!(write("FnMut")),
2010             ty::ClosureKind::FnOnce => p!(write("FnOnce")),
2011         }
2012     }
2013
2014     ty::Predicate<'tcx> {
2015         match self.kind() {
2016             &ty::PredicateKind::Atom(atom) => p!(print(atom)),
2017             ty::PredicateKind::ForAll(binder) => p!(print(binder)),
2018         }
2019     }
2020
2021     ty::PredicateAtom<'tcx> {
2022         match *self {
2023             ty::PredicateAtom::Trait(ref data, constness) => {
2024                 if let hir::Constness::Const = constness {
2025                     p!(write("const "));
2026                 }
2027                 p!(print(data))
2028             }
2029             ty::PredicateAtom::Subtype(predicate) => p!(print(predicate)),
2030             ty::PredicateAtom::RegionOutlives(predicate) => p!(print(predicate)),
2031             ty::PredicateAtom::TypeOutlives(predicate) => p!(print(predicate)),
2032             ty::PredicateAtom::Projection(predicate) => p!(print(predicate)),
2033             ty::PredicateAtom::WellFormed(arg) => p!(print(arg), write(" well-formed")),
2034             ty::PredicateAtom::ObjectSafe(trait_def_id) => {
2035                 p!(write("the trait `"),
2036                 print_def_path(trait_def_id, &[]),
2037                 write("` is object-safe"))
2038             }
2039             ty::PredicateAtom::ClosureKind(closure_def_id, _closure_substs, kind) => {
2040                 p!(write("the closure `"),
2041                 print_value_path(closure_def_id, &[]),
2042                 write("` implements the trait `{}`", kind))
2043             }
2044             ty::PredicateAtom::ConstEvaluatable(def, substs) => {
2045                 p!(write("the constant `"),
2046                 print_value_path(def.did, substs),
2047                 write("` can be evaluated"))
2048             }
2049             ty::PredicateAtom::ConstEquate(c1, c2) => {
2050                 p!(write("the constant `"),
2051                 print(c1),
2052                 write("` equals `"),
2053                 print(c2),
2054                 write("`"))
2055             }
2056         }
2057     }
2058
2059     GenericArg<'tcx> {
2060         match self.unpack() {
2061             GenericArgKind::Lifetime(lt) => p!(print(lt)),
2062             GenericArgKind::Type(ty) => p!(print(ty)),
2063             GenericArgKind::Const(ct) => p!(print(ct)),
2064         }
2065     }
2066 }