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