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