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