]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/print/pretty.rs
Rollup merge of #85766 - workingjubilee:file-options, r=yaahc
[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                         p!(write(" substs={:?}", substs));
748                     } else {
749                         p!(" closure_kind_ty=", print(substs.as_closure().kind_ty()));
750                         p!(
751                             " closure_sig_as_fn_ptr_ty=",
752                             print(substs.as_closure().sig_as_fn_ptr_ty())
753                         );
754                         p!(" upvar_tys=(");
755                         self = self.comma_sep(substs.as_closure().upvar_tys())?;
756                         p!(")");
757                     }
758                 }
759                 p!("]");
760             }
761             ty::Array(ty, sz) => {
762                 p!("[", print(ty), "; ");
763                 if self.tcx().sess.verbose() {
764                     p!(write("{:?}", sz));
765                 } else if let ty::ConstKind::Unevaluated(..) = sz.val {
766                     // Do not try to evaluate unevaluated constants. If we are const evaluating an
767                     // array length anon const, rustc will (with debug assertions) print the
768                     // constant's path. Which will end up here again.
769                     p!("_");
770                 } else if let Some(n) = sz.val.try_to_bits(self.tcx().data_layout.pointer_size) {
771                     p!(write("{}", n));
772                 } else if let ty::ConstKind::Param(param) = sz.val {
773                     p!(write("{}", param));
774                 } else {
775                     p!("_");
776                 }
777                 p!("]")
778             }
779             ty::Slice(ty) => p!("[", print(ty), "]"),
780         }
781
782         Ok(self)
783     }
784
785     fn pretty_print_bound_var(
786         &mut self,
787         debruijn: ty::DebruijnIndex,
788         var: ty::BoundVar,
789     ) -> Result<(), Self::Error> {
790         if debruijn == ty::INNERMOST {
791             write!(self, "^{}", var.index())
792         } else {
793             write!(self, "^{}_{}", debruijn.index(), var.index())
794         }
795     }
796
797     fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
798         None
799     }
800
801     fn pretty_print_dyn_existential(
802         mut self,
803         predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
804     ) -> Result<Self::DynExistential, Self::Error> {
805         // Generate the main trait ref, including associated types.
806         let mut first = true;
807
808         if let Some(principal) = predicates.principal() {
809             self = self.wrap_binder(&principal, |principal, mut cx| {
810                 define_scoped_cx!(cx);
811                 p!(print_def_path(principal.def_id, &[]));
812
813                 let mut resugared = false;
814
815                 // Special-case `Fn(...) -> ...` and resugar it.
816                 let fn_trait_kind = cx.tcx().fn_trait_kind_from_lang_item(principal.def_id);
817                 if !cx.tcx().sess.verbose() && fn_trait_kind.is_some() {
818                     if let ty::Tuple(ref args) = principal.substs.type_at(0).kind() {
819                         let mut projections = predicates.projection_bounds();
820                         if let (Some(proj), None) = (projections.next(), projections.next()) {
821                             let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
822                             p!(pretty_fn_sig(&tys, false, proj.skip_binder().ty));
823                             resugared = true;
824                         }
825                     }
826                 }
827
828                 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
829                 // in order to place the projections inside the `<...>`.
830                 if !resugared {
831                     // Use a type that can't appear in defaults of type parameters.
832                     let dummy_cx = cx.tcx().mk_ty_infer(ty::FreshTy(0));
833                     let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
834
835                     let args = cx.generic_args_to_print(
836                         cx.tcx().generics_of(principal.def_id),
837                         principal.substs,
838                     );
839
840                     // Don't print `'_` if there's no unerased regions.
841                     let print_regions = args.iter().any(|arg| match arg.unpack() {
842                         GenericArgKind::Lifetime(r) => *r != ty::ReErased,
843                         _ => false,
844                     });
845                     let mut args = args.iter().cloned().filter(|arg| match arg.unpack() {
846                         GenericArgKind::Lifetime(_) => print_regions,
847                         _ => true,
848                     });
849                     let mut projections = predicates.projection_bounds();
850
851                     let arg0 = args.next();
852                     let projection0 = projections.next();
853                     if arg0.is_some() || projection0.is_some() {
854                         let args = arg0.into_iter().chain(args);
855                         let projections = projection0.into_iter().chain(projections);
856
857                         p!(generic_delimiters(|mut cx| {
858                             cx = cx.comma_sep(args)?;
859                             if arg0.is_some() && projection0.is_some() {
860                                 write!(cx, ", ")?;
861                             }
862                             cx.comma_sep(projections)
863                         }));
864                     }
865                 }
866                 Ok(cx)
867             })?;
868
869             first = false;
870         }
871
872         define_scoped_cx!(self);
873
874         // Builtin bounds.
875         // FIXME(eddyb) avoid printing twice (needed to ensure
876         // that the auto traits are sorted *and* printed via cx).
877         let mut auto_traits: Vec<_> =
878             predicates.auto_traits().map(|did| (self.tcx().def_path_str(did), did)).collect();
879
880         // The auto traits come ordered by `DefPathHash`. While
881         // `DefPathHash` is *stable* in the sense that it depends on
882         // neither the host nor the phase of the moon, it depends
883         // "pseudorandomly" on the compiler version and the target.
884         //
885         // To avoid that causing instabilities in compiletest
886         // output, sort the auto-traits alphabetically.
887         auto_traits.sort();
888
889         for (_, def_id) in auto_traits {
890             if !first {
891                 p!(" + ");
892             }
893             first = false;
894
895             p!(print_def_path(def_id, &[]));
896         }
897
898         Ok(self)
899     }
900
901     fn pretty_fn_sig(
902         mut self,
903         inputs: &[Ty<'tcx>],
904         c_variadic: bool,
905         output: Ty<'tcx>,
906     ) -> Result<Self, Self::Error> {
907         define_scoped_cx!(self);
908
909         p!("(", comma_sep(inputs.iter().copied()));
910         if c_variadic {
911             if !inputs.is_empty() {
912                 p!(", ");
913             }
914             p!("...");
915         }
916         p!(")");
917         if !output.is_unit() {
918             p!(" -> ", print(output));
919         }
920
921         Ok(self)
922     }
923
924     fn pretty_print_const(
925         mut self,
926         ct: &'tcx ty::Const<'tcx>,
927         print_ty: bool,
928     ) -> Result<Self::Const, Self::Error> {
929         define_scoped_cx!(self);
930
931         if self.tcx().sess.verbose() {
932             p!(write("Const({:?}: {:?})", ct.val, ct.ty));
933             return Ok(self);
934         }
935
936         macro_rules! print_underscore {
937             () => {{
938                 if print_ty {
939                     self = self.typed_value(
940                         |mut this| {
941                             write!(this, "_")?;
942                             Ok(this)
943                         },
944                         |this| this.print_type(ct.ty),
945                         ": ",
946                     )?;
947                 } else {
948                     write!(self, "_")?;
949                 }
950             }};
951         }
952
953         match ct.val {
954             ty::ConstKind::Unevaluated(uv) => {
955                 if let Some(promoted) = uv.promoted {
956                     let substs = uv.substs_.unwrap();
957                     p!(print_value_path(uv.def.did, substs));
958                     p!(write("::{:?}", promoted));
959                 } else {
960                     let tcx = self.tcx();
961                     match tcx.def_kind(uv.def.did) {
962                         DefKind::Static | DefKind::Const | DefKind::AssocConst => {
963                             p!(print_value_path(uv.def.did, uv.substs(tcx)))
964                         }
965                         _ => {
966                             if uv.def.is_local() {
967                                 let span = tcx.def_span(uv.def.did);
968                                 if let Ok(snip) = tcx.sess.source_map().span_to_snippet(span) {
969                                     p!(write("{}", snip))
970                                 } else {
971                                     print_underscore!()
972                                 }
973                             } else {
974                                 print_underscore!()
975                             }
976                         }
977                     }
978                 }
979             }
980             ty::ConstKind::Infer(..) => print_underscore!(),
981             ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
982             ty::ConstKind::Value(value) => {
983                 return self.pretty_print_const_value(value, ct.ty, print_ty);
984             }
985
986             ty::ConstKind::Bound(debruijn, bound_var) => {
987                 self.pretty_print_bound_var(debruijn, bound_var)?
988             }
989             ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
990             ty::ConstKind::Error(_) => p!("[const error]"),
991         };
992         Ok(self)
993     }
994
995     fn pretty_print_const_scalar(
996         self,
997         scalar: Scalar,
998         ty: Ty<'tcx>,
999         print_ty: bool,
1000     ) -> Result<Self::Const, Self::Error> {
1001         match scalar {
1002             Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty, print_ty),
1003             Scalar::Int(int) => self.pretty_print_const_scalar_int(int, ty, print_ty),
1004         }
1005     }
1006
1007     fn pretty_print_const_scalar_ptr(
1008         mut self,
1009         ptr: Pointer,
1010         ty: Ty<'tcx>,
1011         print_ty: bool,
1012     ) -> Result<Self::Const, Self::Error> {
1013         define_scoped_cx!(self);
1014
1015         let (alloc_id, offset) = ptr.into_parts();
1016         match ty.kind() {
1017             // Byte strings (&[u8; N])
1018             ty::Ref(
1019                 _,
1020                 ty::TyS {
1021                     kind:
1022                         ty::Array(
1023                             ty::TyS { kind: ty::Uint(ty::UintTy::U8), .. },
1024                             ty::Const {
1025                                 val: ty::ConstKind::Value(ConstValue::Scalar(int)), ..
1026                             },
1027                         ),
1028                     ..
1029                 },
1030                 _,
1031             ) => match self.tcx().get_global_alloc(alloc_id) {
1032                 Some(GlobalAlloc::Memory(alloc)) => {
1033                     let len = int.assert_bits(self.tcx().data_layout.pointer_size);
1034                     let range = AllocRange { start: offset, size: Size::from_bytes(len) };
1035                     if let Ok(byte_str) = alloc.get_bytes(&self.tcx(), range) {
1036                         p!(pretty_print_byte_str(byte_str))
1037                     } else {
1038                         p!("<too short allocation>")
1039                     }
1040                 }
1041                 // FIXME: for statics and functions, we could in principle print more detail.
1042                 Some(GlobalAlloc::Static(def_id)) => p!(write("<static({:?})>", def_id)),
1043                 Some(GlobalAlloc::Function(_)) => p!("<function>"),
1044                 None => p!("<dangling pointer>"),
1045             },
1046             ty::FnPtr(_) => {
1047                 // FIXME: We should probably have a helper method to share code with the "Byte strings"
1048                 // printing above (which also has to handle pointers to all sorts of things).
1049                 match self.tcx().get_global_alloc(alloc_id) {
1050                     Some(GlobalAlloc::Function(instance)) => {
1051                         self = self.typed_value(
1052                             |this| this.print_value_path(instance.def_id(), instance.substs),
1053                             |this| this.print_type(ty),
1054                             " as ",
1055                         )?;
1056                     }
1057                     _ => self = self.pretty_print_const_pointer(ptr, ty, print_ty)?,
1058                 }
1059             }
1060             // Any pointer values not covered by a branch above
1061             _ => {
1062                 self = self.pretty_print_const_pointer(ptr, ty, print_ty)?;
1063             }
1064         }
1065         Ok(self)
1066     }
1067
1068     fn pretty_print_const_scalar_int(
1069         mut self,
1070         int: ScalarInt,
1071         ty: Ty<'tcx>,
1072         print_ty: bool,
1073     ) -> Result<Self::Const, Self::Error> {
1074         define_scoped_cx!(self);
1075
1076         match ty.kind() {
1077             // Bool
1078             ty::Bool if int == ScalarInt::FALSE => p!("false"),
1079             ty::Bool if int == ScalarInt::TRUE => p!("true"),
1080             // Float
1081             ty::Float(ty::FloatTy::F32) => {
1082                 p!(write("{}f32", Single::try_from(int).unwrap()))
1083             }
1084             ty::Float(ty::FloatTy::F64) => {
1085                 p!(write("{}f64", Double::try_from(int).unwrap()))
1086             }
1087             // Int
1088             ty::Uint(_) | ty::Int(_) => {
1089                 let int =
1090                     ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1091                 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1092             }
1093             // Char
1094             ty::Char if char::try_from(int).is_ok() => {
1095                 p!(write("{:?}", char::try_from(int).unwrap()))
1096             }
1097             // Pointer types
1098             ty::Ref(..) | ty::RawPtr(_) | ty::FnPtr(_) => {
1099                 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
1100                 self = self.typed_value(
1101                     |mut this| {
1102                         write!(this, "0x{:x}", data)?;
1103                         Ok(this)
1104                     },
1105                     |this| this.print_type(ty),
1106                     " as ",
1107                 )?;
1108             }
1109             // For function type zsts just printing the path is enough
1110             ty::FnDef(d, s) if int == ScalarInt::ZST => {
1111                 p!(print_value_path(*d, s))
1112             }
1113             // Nontrivial types with scalar bit representation
1114             _ => {
1115                 let print = |mut this: Self| {
1116                     if int.size() == Size::ZERO {
1117                         write!(this, "transmute(())")?;
1118                     } else {
1119                         write!(this, "transmute(0x{:x})", int)?;
1120                     }
1121                     Ok(this)
1122                 };
1123                 self = if print_ty {
1124                     self.typed_value(print, |this| this.print_type(ty), ": ")?
1125                 } else {
1126                     print(self)?
1127                 };
1128             }
1129         }
1130         Ok(self)
1131     }
1132
1133     /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1134     /// from MIR where it is actually useful.
1135     fn pretty_print_const_pointer<Tag: Provenance>(
1136         mut self,
1137         _: Pointer<Tag>,
1138         ty: Ty<'tcx>,
1139         print_ty: bool,
1140     ) -> Result<Self::Const, Self::Error> {
1141         if print_ty {
1142             self.typed_value(
1143                 |mut this| {
1144                     this.write_str("&_")?;
1145                     Ok(this)
1146                 },
1147                 |this| this.print_type(ty),
1148                 ": ",
1149             )
1150         } else {
1151             self.write_str("&_")?;
1152             Ok(self)
1153         }
1154     }
1155
1156     fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1157         define_scoped_cx!(self);
1158         p!("b\"");
1159         for &c in byte_str {
1160             for e in std::ascii::escape_default(c) {
1161                 self.write_char(e as char)?;
1162             }
1163         }
1164         p!("\"");
1165         Ok(self)
1166     }
1167
1168     fn pretty_print_const_value(
1169         mut self,
1170         ct: ConstValue<'tcx>,
1171         ty: Ty<'tcx>,
1172         print_ty: bool,
1173     ) -> Result<Self::Const, Self::Error> {
1174         define_scoped_cx!(self);
1175
1176         if self.tcx().sess.verbose() {
1177             p!(write("ConstValue({:?}: ", ct), print(ty), ")");
1178             return Ok(self);
1179         }
1180
1181         let u8_type = self.tcx().types.u8;
1182
1183         match (ct, ty.kind()) {
1184             // Byte/string slices, printed as (byte) string literals.
1185             (
1186                 ConstValue::Slice { data, start, end },
1187                 ty::Ref(_, ty::TyS { kind: ty::Slice(t), .. }, _),
1188             ) if *t == u8_type => {
1189                 // The `inspect` here is okay since we checked the bounds, and there are
1190                 // no relocations (we have an active slice reference here). We don't use
1191                 // this result to affect interpreter execution.
1192                 let byte_str = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1193                 self.pretty_print_byte_str(byte_str)
1194             }
1195             (
1196                 ConstValue::Slice { data, start, end },
1197                 ty::Ref(_, ty::TyS { kind: ty::Str, .. }, _),
1198             ) => {
1199                 // The `inspect` here is okay since we checked the bounds, and there are no
1200                 // relocations (we have an active `str` reference here). We don't use this
1201                 // result to affect interpreter execution.
1202                 let slice = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1203                 let s = std::str::from_utf8(slice).expect("non utf8 str from miri");
1204                 p!(write("{:?}", s));
1205                 Ok(self)
1206             }
1207             (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
1208                 let n = n.val.try_to_bits(self.tcx().data_layout.pointer_size).unwrap();
1209                 // cast is ok because we already checked for pointer size (32 or 64 bit) above
1210                 let range = AllocRange { start: offset, size: Size::from_bytes(n) };
1211
1212                 let byte_str = alloc.get_bytes(&self.tcx(), range).unwrap();
1213                 p!("*");
1214                 p!(pretty_print_byte_str(byte_str));
1215                 Ok(self)
1216             }
1217
1218             // Aggregates, printed as array/tuple/struct/variant construction syntax.
1219             //
1220             // NB: the `potentially_has_param_types_or_consts` check ensures that we can use
1221             // the `destructure_const` query with an empty `ty::ParamEnv` without
1222             // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1223             // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1224             // to be able to destructure the tuple into `(0u8, *mut T)
1225             //
1226             // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
1227             // correct `ty::ParamEnv` to allow printing *all* constant values.
1228             (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..))
1229                 if !ty.potentially_has_param_types_or_consts() =>
1230             {
1231                 let contents = self.tcx().destructure_const(
1232                     ty::ParamEnv::reveal_all()
1233                         .and(self.tcx().mk_const(ty::Const { val: ty::ConstKind::Value(ct), ty })),
1234                 );
1235                 let fields = contents.fields.iter().copied();
1236
1237                 match *ty.kind() {
1238                     ty::Array(..) => {
1239                         p!("[", comma_sep(fields), "]");
1240                     }
1241                     ty::Tuple(..) => {
1242                         p!("(", comma_sep(fields));
1243                         if contents.fields.len() == 1 {
1244                             p!(",");
1245                         }
1246                         p!(")");
1247                     }
1248                     ty::Adt(def, _) if def.variants.is_empty() => {
1249                         self = self.typed_value(
1250                             |mut this| {
1251                                 write!(this, "unreachable()")?;
1252                                 Ok(this)
1253                             },
1254                             |this| this.print_type(ty),
1255                             ": ",
1256                         )?;
1257                     }
1258                     ty::Adt(def, substs) => {
1259                         let variant_idx =
1260                             contents.variant.expect("destructed const of adt without variant idx");
1261                         let variant_def = &def.variants[variant_idx];
1262                         p!(print_value_path(variant_def.def_id, substs));
1263
1264                         match variant_def.ctor_kind {
1265                             CtorKind::Const => {}
1266                             CtorKind::Fn => {
1267                                 p!("(", comma_sep(fields), ")");
1268                             }
1269                             CtorKind::Fictive => {
1270                                 p!(" {{ ");
1271                                 let mut first = true;
1272                                 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1273                                     if !first {
1274                                         p!(", ");
1275                                     }
1276                                     p!(write("{}: ", field_def.ident), print(field));
1277                                     first = false;
1278                                 }
1279                                 p!(" }}");
1280                             }
1281                         }
1282                     }
1283                     _ => unreachable!(),
1284                 }
1285
1286                 Ok(self)
1287             }
1288
1289             (ConstValue::Scalar(scalar), _) => self.pretty_print_const_scalar(scalar, ty, print_ty),
1290
1291             // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1292             // their fields instead of just dumping the memory.
1293             _ => {
1294                 // fallback
1295                 p!(write("{:?}", ct));
1296                 if print_ty {
1297                     p!(": ", print(ty));
1298                 }
1299                 Ok(self)
1300             }
1301         }
1302     }
1303 }
1304
1305 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1306 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1307
1308 pub struct FmtPrinterData<'a, 'tcx, F> {
1309     tcx: TyCtxt<'tcx>,
1310     fmt: F,
1311
1312     empty_path: bool,
1313     in_value: bool,
1314     pub print_alloc_ids: bool,
1315
1316     used_region_names: FxHashSet<Symbol>,
1317     region_index: usize,
1318     binder_depth: usize,
1319     printed_type_count: usize,
1320
1321     pub region_highlight_mode: RegionHighlightMode,
1322
1323     pub name_resolver: Option<Box<&'a dyn Fn(ty::TyVid) -> Option<String>>>,
1324 }
1325
1326 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1327     type Target = FmtPrinterData<'a, 'tcx, F>;
1328     fn deref(&self) -> &Self::Target {
1329         &self.0
1330     }
1331 }
1332
1333 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1334     fn deref_mut(&mut self) -> &mut Self::Target {
1335         &mut self.0
1336     }
1337 }
1338
1339 impl<F> FmtPrinter<'a, 'tcx, F> {
1340     pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1341         FmtPrinter(Box::new(FmtPrinterData {
1342             tcx,
1343             fmt,
1344             empty_path: false,
1345             in_value: ns == Namespace::ValueNS,
1346             print_alloc_ids: false,
1347             used_region_names: Default::default(),
1348             region_index: 0,
1349             binder_depth: 0,
1350             printed_type_count: 0,
1351             region_highlight_mode: RegionHighlightMode::default(),
1352             name_resolver: None,
1353         }))
1354     }
1355 }
1356
1357 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1358 // (but also some things just print a `DefId` generally so maybe we need this?)
1359 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1360     match tcx.def_key(def_id).disambiguated_data.data {
1361         DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1362             Namespace::TypeNS
1363         }
1364
1365         DefPathData::ValueNs(..)
1366         | DefPathData::AnonConst
1367         | DefPathData::ClosureExpr
1368         | DefPathData::Ctor => Namespace::ValueNS,
1369
1370         DefPathData::MacroNs(..) => Namespace::MacroNS,
1371
1372         _ => Namespace::TypeNS,
1373     }
1374 }
1375
1376 impl TyCtxt<'t> {
1377     /// Returns a string identifying this `DefId`. This string is
1378     /// suitable for user output.
1379     pub fn def_path_str(self, def_id: DefId) -> String {
1380         self.def_path_str_with_substs(def_id, &[])
1381     }
1382
1383     pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1384         let ns = guess_def_namespace(self, def_id);
1385         debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1386         let mut s = String::new();
1387         let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1388         s
1389     }
1390 }
1391
1392 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1393     fn write_str(&mut self, s: &str) -> fmt::Result {
1394         self.fmt.write_str(s)
1395     }
1396 }
1397
1398 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1399     type Error = fmt::Error;
1400
1401     type Path = Self;
1402     type Region = Self;
1403     type Type = Self;
1404     type DynExistential = Self;
1405     type Const = Self;
1406
1407     fn tcx(&'a self) -> TyCtxt<'tcx> {
1408         self.tcx
1409     }
1410
1411     fn print_def_path(
1412         mut self,
1413         def_id: DefId,
1414         substs: &'tcx [GenericArg<'tcx>],
1415     ) -> Result<Self::Path, Self::Error> {
1416         define_scoped_cx!(self);
1417
1418         if substs.is_empty() {
1419             match self.try_print_trimmed_def_path(def_id)? {
1420                 (cx, true) => return Ok(cx),
1421                 (cx, false) => self = cx,
1422             }
1423
1424             match self.try_print_visible_def_path(def_id)? {
1425                 (cx, true) => return Ok(cx),
1426                 (cx, false) => self = cx,
1427             }
1428         }
1429
1430         let key = self.tcx.def_key(def_id);
1431         if let DefPathData::Impl = key.disambiguated_data.data {
1432             // Always use types for non-local impls, where types are always
1433             // available, and filename/line-number is mostly uninteresting.
1434             let use_types = !def_id.is_local() || {
1435                 // Otherwise, use filename/line-number if forced.
1436                 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1437                 !force_no_types
1438             };
1439
1440             if !use_types {
1441                 // If no type info is available, fall back to
1442                 // pretty printing some span information. This should
1443                 // only occur very early in the compiler pipeline.
1444                 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1445                 let span = self.tcx.def_span(def_id);
1446
1447                 self = self.print_def_path(parent_def_id, &[])?;
1448
1449                 // HACK(eddyb) copy of `path_append` to avoid
1450                 // constructing a `DisambiguatedDefPathData`.
1451                 if !self.empty_path {
1452                     write!(self, "::")?;
1453                 }
1454                 write!(
1455                     self,
1456                     "<impl at {}>",
1457                     // This may end up in stderr diagnostics but it may also be emitted
1458                     // into MIR. Hence we use the remapped path if available
1459                     self.tcx.sess.source_map().span_to_embeddable_string(span)
1460                 )?;
1461                 self.empty_path = false;
1462
1463                 return Ok(self);
1464             }
1465         }
1466
1467         self.default_print_def_path(def_id, substs)
1468     }
1469
1470     fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1471         self.pretty_print_region(region)
1472     }
1473
1474     fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1475         let type_length_limit = self.tcx.type_length_limit();
1476         if type_length_limit.value_within_limit(self.printed_type_count) {
1477             self.printed_type_count += 1;
1478             self.pretty_print_type(ty)
1479         } else {
1480             write!(self, "...")?;
1481             Ok(self)
1482         }
1483     }
1484
1485     fn print_dyn_existential(
1486         self,
1487         predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1488     ) -> Result<Self::DynExistential, Self::Error> {
1489         self.pretty_print_dyn_existential(predicates)
1490     }
1491
1492     fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1493         self.pretty_print_const(ct, true)
1494     }
1495
1496     fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1497         self.empty_path = true;
1498         if cnum == LOCAL_CRATE {
1499             if self.tcx.sess.rust_2018() {
1500                 // We add the `crate::` keyword on Rust 2018, only when desired.
1501                 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1502                     write!(self, "{}", kw::Crate)?;
1503                     self.empty_path = false;
1504                 }
1505             }
1506         } else {
1507             write!(self, "{}", self.tcx.crate_name(cnum))?;
1508             self.empty_path = false;
1509         }
1510         Ok(self)
1511     }
1512
1513     fn path_qualified(
1514         mut self,
1515         self_ty: Ty<'tcx>,
1516         trait_ref: Option<ty::TraitRef<'tcx>>,
1517     ) -> Result<Self::Path, Self::Error> {
1518         self = self.pretty_path_qualified(self_ty, trait_ref)?;
1519         self.empty_path = false;
1520         Ok(self)
1521     }
1522
1523     fn path_append_impl(
1524         mut self,
1525         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1526         _disambiguated_data: &DisambiguatedDefPathData,
1527         self_ty: Ty<'tcx>,
1528         trait_ref: Option<ty::TraitRef<'tcx>>,
1529     ) -> Result<Self::Path, Self::Error> {
1530         self = self.pretty_path_append_impl(
1531             |mut cx| {
1532                 cx = print_prefix(cx)?;
1533                 if !cx.empty_path {
1534                     write!(cx, "::")?;
1535                 }
1536
1537                 Ok(cx)
1538             },
1539             self_ty,
1540             trait_ref,
1541         )?;
1542         self.empty_path = false;
1543         Ok(self)
1544     }
1545
1546     fn path_append(
1547         mut self,
1548         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1549         disambiguated_data: &DisambiguatedDefPathData,
1550     ) -> Result<Self::Path, Self::Error> {
1551         self = print_prefix(self)?;
1552
1553         // Skip `::{{constructor}}` on tuple/unit structs.
1554         if let DefPathData::Ctor = disambiguated_data.data {
1555             return Ok(self);
1556         }
1557
1558         // FIXME(eddyb) `name` should never be empty, but it
1559         // currently is for `extern { ... }` "foreign modules".
1560         let name = disambiguated_data.data.name();
1561         if name != DefPathDataName::Named(kw::Empty) {
1562             if !self.empty_path {
1563                 write!(self, "::")?;
1564             }
1565
1566             if let DefPathDataName::Named(name) = name {
1567                 if Ident::with_dummy_span(name).is_raw_guess() {
1568                     write!(self, "r#")?;
1569                 }
1570             }
1571
1572             let verbose = self.tcx.sess.verbose();
1573             disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1574
1575             self.empty_path = false;
1576         }
1577
1578         Ok(self)
1579     }
1580
1581     fn path_generic_args(
1582         mut self,
1583         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1584         args: &[GenericArg<'tcx>],
1585     ) -> Result<Self::Path, Self::Error> {
1586         self = print_prefix(self)?;
1587
1588         // Don't print `'_` if there's no unerased regions.
1589         let print_regions = args.iter().any(|arg| match arg.unpack() {
1590             GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1591             _ => false,
1592         });
1593         let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1594             GenericArgKind::Lifetime(_) => print_regions,
1595             _ => true,
1596         });
1597
1598         if args.clone().next().is_some() {
1599             if self.in_value {
1600                 write!(self, "::")?;
1601             }
1602             self.generic_delimiters(|cx| cx.comma_sep(args))
1603         } else {
1604             Ok(self)
1605         }
1606     }
1607 }
1608
1609 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1610     fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1611         self.0.name_resolver.as_ref().and_then(|func| func(id))
1612     }
1613
1614     fn print_value_path(
1615         mut self,
1616         def_id: DefId,
1617         substs: &'tcx [GenericArg<'tcx>],
1618     ) -> Result<Self::Path, Self::Error> {
1619         let was_in_value = std::mem::replace(&mut self.in_value, true);
1620         self = self.print_def_path(def_id, substs)?;
1621         self.in_value = was_in_value;
1622
1623         Ok(self)
1624     }
1625
1626     fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
1627     where
1628         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1629     {
1630         self.pretty_in_binder(value)
1631     }
1632
1633     fn wrap_binder<T, C: Fn(&T, Self) -> Result<Self, Self::Error>>(
1634         self,
1635         value: &ty::Binder<'tcx, T>,
1636         f: C,
1637     ) -> Result<Self, Self::Error>
1638     where
1639         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1640     {
1641         self.pretty_wrap_binder(value, f)
1642     }
1643
1644     fn typed_value(
1645         mut self,
1646         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1647         t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1648         conversion: &str,
1649     ) -> Result<Self::Const, Self::Error> {
1650         self.write_str("{")?;
1651         self = f(self)?;
1652         self.write_str(conversion)?;
1653         let was_in_value = std::mem::replace(&mut self.in_value, false);
1654         self = t(self)?;
1655         self.in_value = was_in_value;
1656         self.write_str("}")?;
1657         Ok(self)
1658     }
1659
1660     fn generic_delimiters(
1661         mut self,
1662         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1663     ) -> Result<Self, Self::Error> {
1664         write!(self, "<")?;
1665
1666         let was_in_value = std::mem::replace(&mut self.in_value, false);
1667         let mut inner = f(self)?;
1668         inner.in_value = was_in_value;
1669
1670         write!(inner, ">")?;
1671         Ok(inner)
1672     }
1673
1674     fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1675         let highlight = self.region_highlight_mode;
1676         if highlight.region_highlighted(region).is_some() {
1677             return true;
1678         }
1679
1680         if self.tcx.sess.verbose() {
1681             return true;
1682         }
1683
1684         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1685
1686         match *region {
1687             ty::ReEarlyBound(ref data) => {
1688                 data.name != kw::Empty && data.name != kw::UnderscoreLifetime
1689             }
1690
1691             ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
1692             | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1693             | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1694                 if let ty::BrNamed(_, name) = br {
1695                     if name != kw::Empty && name != kw::UnderscoreLifetime {
1696                         return true;
1697                     }
1698                 }
1699
1700                 if let Some((region, _)) = highlight.highlight_bound_region {
1701                     if br == region {
1702                         return true;
1703                     }
1704                 }
1705
1706                 false
1707             }
1708
1709             ty::ReVar(_) if identify_regions => true,
1710
1711             ty::ReVar(_) | ty::ReErased => false,
1712
1713             ty::ReStatic | ty::ReEmpty(_) => true,
1714         }
1715     }
1716
1717     fn pretty_print_const_pointer<Tag: Provenance>(
1718         self,
1719         p: Pointer<Tag>,
1720         ty: Ty<'tcx>,
1721         print_ty: bool,
1722     ) -> Result<Self::Const, Self::Error> {
1723         let print = |mut this: Self| {
1724             define_scoped_cx!(this);
1725             if this.print_alloc_ids {
1726                 p!(write("{:?}", p));
1727             } else {
1728                 p!("&_");
1729             }
1730             Ok(this)
1731         };
1732         if print_ty {
1733             self.typed_value(print, |this| this.print_type(ty), ": ")
1734         } else {
1735             print(self)
1736         }
1737     }
1738 }
1739
1740 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1741 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1742     pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1743         define_scoped_cx!(self);
1744
1745         // Watch out for region highlights.
1746         let highlight = self.region_highlight_mode;
1747         if let Some(n) = highlight.region_highlighted(region) {
1748             p!(write("'{}", n));
1749             return Ok(self);
1750         }
1751
1752         if self.tcx.sess.verbose() {
1753             p!(write("{:?}", region));
1754             return Ok(self);
1755         }
1756
1757         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1758
1759         // These printouts are concise.  They do not contain all the information
1760         // the user might want to diagnose an error, but there is basically no way
1761         // to fit that into a short string.  Hence the recommendation to use
1762         // `explain_region()` or `note_and_explain_region()`.
1763         match *region {
1764             ty::ReEarlyBound(ref data) => {
1765                 if data.name != kw::Empty {
1766                     p!(write("{}", data.name));
1767                     return Ok(self);
1768                 }
1769             }
1770             ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
1771             | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1772             | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1773                 if let ty::BrNamed(_, name) = br {
1774                     if name != kw::Empty && name != kw::UnderscoreLifetime {
1775                         p!(write("{}", name));
1776                         return Ok(self);
1777                     }
1778                 }
1779
1780                 if let Some((region, counter)) = highlight.highlight_bound_region {
1781                     if br == region {
1782                         p!(write("'{}", counter));
1783                         return Ok(self);
1784                     }
1785                 }
1786             }
1787             ty::ReVar(region_vid) if identify_regions => {
1788                 p!(write("{:?}", region_vid));
1789                 return Ok(self);
1790             }
1791             ty::ReVar(_) => {}
1792             ty::ReErased => {}
1793             ty::ReStatic => {
1794                 p!("'static");
1795                 return Ok(self);
1796             }
1797             ty::ReEmpty(ty::UniverseIndex::ROOT) => {
1798                 p!("'<empty>");
1799                 return Ok(self);
1800             }
1801             ty::ReEmpty(ui) => {
1802                 p!(write("'<empty:{:?}>", ui));
1803                 return Ok(self);
1804             }
1805         }
1806
1807         p!("'_");
1808
1809         Ok(self)
1810     }
1811 }
1812
1813 /// Folds through bound vars and placeholders, naming them
1814 struct RegionFolder<'a, 'tcx> {
1815     tcx: TyCtxt<'tcx>,
1816     current_index: ty::DebruijnIndex,
1817     region_map: BTreeMap<ty::BoundRegion, ty::Region<'tcx>>,
1818     name: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
1819 }
1820
1821 impl<'a, 'tcx> ty::TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
1822     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1823         self.tcx
1824     }
1825
1826     fn fold_binder<T: TypeFoldable<'tcx>>(
1827         &mut self,
1828         t: ty::Binder<'tcx, T>,
1829     ) -> ty::Binder<'tcx, T> {
1830         self.current_index.shift_in(1);
1831         let t = t.super_fold_with(self);
1832         self.current_index.shift_out(1);
1833         t
1834     }
1835
1836     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
1837         match *t.kind() {
1838             _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
1839                 return t.super_fold_with(self);
1840             }
1841             _ => {}
1842         }
1843         t
1844     }
1845
1846     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
1847         let name = &mut self.name;
1848         let region = match *r {
1849             ty::ReLateBound(_, br) => self.region_map.entry(br).or_insert_with(|| name(br)),
1850             ty::RePlaceholder(ty::PlaceholderRegion { name: kind, .. }) => {
1851                 // If this is an anonymous placeholder, don't rename. Otherwise, in some
1852                 // async fns, we get a `for<'r> Send` bound
1853                 match kind {
1854                     ty::BrAnon(_) | ty::BrEnv => r,
1855                     _ => {
1856                         // Index doesn't matter, since this is just for naming and these never get bound
1857                         let br = ty::BoundRegion { var: ty::BoundVar::from_u32(0), kind };
1858                         self.region_map.entry(br).or_insert_with(|| name(br))
1859                     }
1860                 }
1861             }
1862             _ => return r,
1863         };
1864         if let ty::ReLateBound(debruijn1, br) = *region {
1865             assert_eq!(debruijn1, ty::INNERMOST);
1866             self.tcx.mk_region(ty::ReLateBound(self.current_index, br))
1867         } else {
1868             region
1869         }
1870     }
1871 }
1872
1873 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1874 // `region_index` and `used_region_names`.
1875 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1876     pub fn name_all_regions<T>(
1877         mut self,
1878         value: &ty::Binder<'tcx, T>,
1879     ) -> Result<(Self, T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
1880     where
1881         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1882     {
1883         fn name_by_region_index(index: usize) -> Symbol {
1884             match index {
1885                 0 => Symbol::intern("'r"),
1886                 1 => Symbol::intern("'s"),
1887                 i => Symbol::intern(&format!("'t{}", i - 2)),
1888             }
1889         }
1890
1891         // Replace any anonymous late-bound regions with named
1892         // variants, using new unique identifiers, so that we can
1893         // clearly differentiate between named and unnamed regions in
1894         // the output. We'll probably want to tweak this over time to
1895         // decide just how much information to give.
1896         if self.binder_depth == 0 {
1897             self.prepare_late_bound_region_info(value);
1898         }
1899
1900         let mut empty = true;
1901         let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1902             let w = if empty {
1903                 empty = false;
1904                 start
1905             } else {
1906                 cont
1907             };
1908             let _ = write!(cx, "{}", w);
1909         };
1910         let do_continue = |cx: &mut Self, cont: Symbol| {
1911             let _ = write!(cx, "{}", cont);
1912         };
1913
1914         define_scoped_cx!(self);
1915
1916         let mut region_index = self.region_index;
1917         // If we want to print verbosly, then print *all* binders, even if they
1918         // aren't named. Eventually, we might just want this as the default, but
1919         // this is not *quite* right and changes the ordering of some output
1920         // anyways.
1921         let (new_value, map) = if self.tcx().sess.verbose() {
1922             // anon index + 1 (BrEnv takes 0) -> name
1923             let mut region_map: BTreeMap<u32, Symbol> = BTreeMap::default();
1924             let bound_vars = value.bound_vars();
1925             for var in bound_vars {
1926                 match var {
1927                     ty::BoundVariableKind::Region(ty::BrNamed(_, name)) => {
1928                         start_or_continue(&mut self, "for<", ", ");
1929                         do_continue(&mut self, name);
1930                     }
1931                     ty::BoundVariableKind::Region(ty::BrAnon(i)) => {
1932                         start_or_continue(&mut self, "for<", ", ");
1933                         let name = loop {
1934                             let name = name_by_region_index(region_index);
1935                             region_index += 1;
1936                             if !self.used_region_names.contains(&name) {
1937                                 break name;
1938                             }
1939                         };
1940                         do_continue(&mut self, name);
1941                         region_map.insert(i + 1, name);
1942                     }
1943                     ty::BoundVariableKind::Region(ty::BrEnv) => {
1944                         start_or_continue(&mut self, "for<", ", ");
1945                         let name = loop {
1946                             let name = name_by_region_index(region_index);
1947                             region_index += 1;
1948                             if !self.used_region_names.contains(&name) {
1949                                 break name;
1950                             }
1951                         };
1952                         do_continue(&mut self, name);
1953                         region_map.insert(0, name);
1954                     }
1955                     _ => continue,
1956                 }
1957             }
1958             start_or_continue(&mut self, "", "> ");
1959
1960             self.tcx.replace_late_bound_regions(value.clone(), |br| {
1961                 let kind = match br.kind {
1962                     ty::BrNamed(_, _) => br.kind,
1963                     ty::BrAnon(i) => {
1964                         let name = region_map[&(i + 1)];
1965                         ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1966                     }
1967                     ty::BrEnv => {
1968                         let name = region_map[&0];
1969                         ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1970                     }
1971                 };
1972                 self.tcx.mk_region(ty::ReLateBound(
1973                     ty::INNERMOST,
1974                     ty::BoundRegion { var: br.var, kind },
1975                 ))
1976             })
1977         } else {
1978             let tcx = self.tcx;
1979             let mut name = |br: ty::BoundRegion| {
1980                 start_or_continue(&mut self, "for<", ", ");
1981                 let kind = match br.kind {
1982                     ty::BrNamed(_, name) => {
1983                         do_continue(&mut self, name);
1984                         br.kind
1985                     }
1986                     ty::BrAnon(_) | ty::BrEnv => {
1987                         let name = loop {
1988                             let name = name_by_region_index(region_index);
1989                             region_index += 1;
1990                             if !self.used_region_names.contains(&name) {
1991                                 break name;
1992                             }
1993                         };
1994                         do_continue(&mut self, name);
1995                         ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1996                     }
1997                 };
1998                 tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BoundRegion { var: br.var, kind }))
1999             };
2000             let mut folder = RegionFolder {
2001                 tcx,
2002                 current_index: ty::INNERMOST,
2003                 name: &mut name,
2004                 region_map: BTreeMap::new(),
2005             };
2006             let new_value = value.clone().skip_binder().fold_with(&mut folder);
2007             let region_map = folder.region_map;
2008             start_or_continue(&mut self, "", "> ");
2009             (new_value, region_map)
2010         };
2011
2012         self.binder_depth += 1;
2013         self.region_index = region_index;
2014         Ok((self, new_value, map))
2015     }
2016
2017     pub fn pretty_in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, fmt::Error>
2018     where
2019         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2020     {
2021         let old_region_index = self.region_index;
2022         let (new, new_value, _) = self.name_all_regions(value)?;
2023         let mut inner = new_value.print(new)?;
2024         inner.region_index = old_region_index;
2025         inner.binder_depth -= 1;
2026         Ok(inner)
2027     }
2028
2029     pub fn pretty_wrap_binder<T, C: Fn(&T, Self) -> Result<Self, fmt::Error>>(
2030         self,
2031         value: &ty::Binder<'tcx, T>,
2032         f: C,
2033     ) -> Result<Self, fmt::Error>
2034     where
2035         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2036     {
2037         let old_region_index = self.region_index;
2038         let (new, new_value, _) = self.name_all_regions(value)?;
2039         let mut inner = f(&new_value, new)?;
2040         inner.region_index = old_region_index;
2041         inner.binder_depth -= 1;
2042         Ok(inner)
2043     }
2044
2045     #[instrument(skip(self), level = "debug")]
2046     fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2047     where
2048         T: TypeFoldable<'tcx>,
2049     {
2050         struct LateBoundRegionNameCollector<'a, 'tcx> {
2051             tcx: TyCtxt<'tcx>,
2052             used_region_names: &'a mut FxHashSet<Symbol>,
2053             type_collector: SsoHashSet<Ty<'tcx>>,
2054         }
2055
2056         impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_, 'tcx> {
2057             type BreakTy = ();
2058
2059             fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
2060                 Some(self.tcx)
2061             }
2062
2063             #[instrument(skip(self), level = "trace")]
2064             fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
2065                 trace!("address: {:p}", r);
2066                 if let ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) = *r {
2067                     self.used_region_names.insert(name);
2068                 } else if let ty::RePlaceholder(ty::PlaceholderRegion {
2069                     name: ty::BrNamed(_, name),
2070                     ..
2071                 }) = *r
2072                 {
2073                     self.used_region_names.insert(name);
2074                 }
2075                 r.super_visit_with(self)
2076             }
2077
2078             // We collect types in order to prevent really large types from compiling for
2079             // a really long time. See issue #83150 for why this is necessary.
2080             #[instrument(skip(self), level = "trace")]
2081             fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
2082                 let not_previously_inserted = self.type_collector.insert(ty);
2083                 if not_previously_inserted {
2084                     ty.super_visit_with(self)
2085                 } else {
2086                     ControlFlow::CONTINUE
2087                 }
2088             }
2089         }
2090
2091         self.used_region_names.clear();
2092         let mut collector = LateBoundRegionNameCollector {
2093             tcx: self.tcx,
2094             used_region_names: &mut self.used_region_names,
2095             type_collector: SsoHashSet::new(),
2096         };
2097         value.visit_with(&mut collector);
2098         self.region_index = 0;
2099     }
2100 }
2101
2102 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2103 where
2104     T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
2105 {
2106     type Output = P;
2107     type Error = P::Error;
2108     fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
2109         cx.in_binder(self)
2110     }
2111 }
2112
2113 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
2114 where
2115     T: Print<'tcx, P, Output = P, Error = P::Error>,
2116     U: Print<'tcx, P, Output = P, Error = P::Error>,
2117 {
2118     type Output = P;
2119     type Error = P::Error;
2120     fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
2121         define_scoped_cx!(cx);
2122         p!(print(self.0), ": ", print(self.1));
2123         Ok(cx)
2124     }
2125 }
2126
2127 macro_rules! forward_display_to_print {
2128     ($($ty:ty),+) => {
2129         $(impl fmt::Display for $ty {
2130             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2131                 ty::tls::with(|tcx| {
2132                     tcx.lift(*self)
2133                         .expect("could not lift for printing")
2134                         .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
2135                     Ok(())
2136                 })
2137             }
2138         })+
2139     };
2140 }
2141
2142 macro_rules! define_print_and_forward_display {
2143     (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
2144         $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
2145             type Output = P;
2146             type Error = fmt::Error;
2147             fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
2148                 #[allow(unused_mut)]
2149                 let mut $cx = $cx;
2150                 define_scoped_cx!($cx);
2151                 let _: () = $print;
2152                 #[allow(unreachable_code)]
2153                 Ok($cx)
2154             }
2155         })+
2156
2157         forward_display_to_print!($($ty),+);
2158     };
2159 }
2160
2161 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
2162 impl fmt::Display for ty::RegionKind {
2163     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2164         ty::tls::with(|tcx| {
2165             self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
2166             Ok(())
2167         })
2168     }
2169 }
2170
2171 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2172 /// the trait path. That is, it will print `Trait<U>` instead of
2173 /// `<T as Trait<U>>`.
2174 #[derive(Copy, Clone, TypeFoldable, Lift)]
2175 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2176
2177 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
2178     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2179         fmt::Display::fmt(self, f)
2180     }
2181 }
2182
2183 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2184 /// the trait name. That is, it will print `Trait` instead of
2185 /// `<T as Trait<U>>`.
2186 #[derive(Copy, Clone, TypeFoldable, Lift)]
2187 pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
2188
2189 impl fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
2190     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2191         fmt::Display::fmt(self, f)
2192     }
2193 }
2194
2195 impl ty::TraitRef<'tcx> {
2196     pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2197         TraitRefPrintOnlyTraitPath(self)
2198     }
2199
2200     pub fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
2201         TraitRefPrintOnlyTraitName(self)
2202     }
2203 }
2204
2205 impl ty::Binder<'tcx, ty::TraitRef<'tcx>> {
2206     pub fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
2207         self.map_bound(|tr| tr.print_only_trait_path())
2208     }
2209 }
2210
2211 forward_display_to_print! {
2212     Ty<'tcx>,
2213     &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2214     &'tcx ty::Const<'tcx>,
2215
2216     // HACK(eddyb) these are exhaustive instead of generic,
2217     // because `for<'tcx>` isn't possible yet.
2218     ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>,
2219     ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2220     ty::Binder<'tcx, ty::ExistentialTraitRef<'tcx>>,
2221     ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>>,
2222     ty::Binder<'tcx, TraitRefPrintOnlyTraitName<'tcx>>,
2223     ty::Binder<'tcx, ty::FnSig<'tcx>>,
2224     ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2225     ty::Binder<'tcx, ty::SubtypePredicate<'tcx>>,
2226     ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
2227     ty::Binder<'tcx, ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
2228     ty::Binder<'tcx, ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
2229
2230     ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
2231     ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
2232 }
2233
2234 define_print_and_forward_display! {
2235     (self, cx):
2236
2237     &'tcx ty::List<Ty<'tcx>> {
2238         p!("{{", comma_sep(self.iter()), "}}")
2239     }
2240
2241     ty::TypeAndMut<'tcx> {
2242         p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
2243     }
2244
2245     ty::ExistentialTraitRef<'tcx> {
2246         // Use a type that can't appear in defaults of type parameters.
2247         let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
2248         let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
2249         p!(print(trait_ref.print_only_trait_path()))
2250     }
2251
2252     ty::ExistentialProjection<'tcx> {
2253         let name = cx.tcx().associated_item(self.item_def_id).ident;
2254         p!(write("{} = ", name), print(self.ty))
2255     }
2256
2257     ty::ExistentialPredicate<'tcx> {
2258         match *self {
2259             ty::ExistentialPredicate::Trait(x) => p!(print(x)),
2260             ty::ExistentialPredicate::Projection(x) => p!(print(x)),
2261             ty::ExistentialPredicate::AutoTrait(def_id) => {
2262                 p!(print_def_path(def_id, &[]));
2263             }
2264         }
2265     }
2266
2267     ty::FnSig<'tcx> {
2268         p!(write("{}", self.unsafety.prefix_str()));
2269
2270         if self.abi != Abi::Rust {
2271             p!(write("extern {} ", self.abi));
2272         }
2273
2274         p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2275     }
2276
2277     ty::TraitRef<'tcx> {
2278         p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2279     }
2280
2281     TraitRefPrintOnlyTraitPath<'tcx> {
2282         p!(print_def_path(self.0.def_id, self.0.substs));
2283     }
2284
2285     TraitRefPrintOnlyTraitName<'tcx> {
2286         p!(print_def_path(self.0.def_id, &[]));
2287     }
2288
2289     ty::ParamTy {
2290         p!(write("{}", self.name))
2291     }
2292
2293     ty::ParamConst {
2294         p!(write("{}", self.name))
2295     }
2296
2297     ty::SubtypePredicate<'tcx> {
2298         p!(print(self.a), " <: ", print(self.b))
2299     }
2300
2301     ty::CoercePredicate<'tcx> {
2302         p!(print(self.a), " -> ", print(self.b))
2303     }
2304
2305     ty::TraitPredicate<'tcx> {
2306         p!(print(self.trait_ref.self_ty()), ": ",
2307            print(self.trait_ref.print_only_trait_path()))
2308     }
2309
2310     ty::ProjectionPredicate<'tcx> {
2311         p!(print(self.projection_ty), " == ", print(self.ty))
2312     }
2313
2314     ty::ProjectionTy<'tcx> {
2315         p!(print_def_path(self.item_def_id, self.substs));
2316     }
2317
2318     ty::ClosureKind {
2319         match *self {
2320             ty::ClosureKind::Fn => p!("Fn"),
2321             ty::ClosureKind::FnMut => p!("FnMut"),
2322             ty::ClosureKind::FnOnce => p!("FnOnce"),
2323         }
2324     }
2325
2326     ty::Predicate<'tcx> {
2327         let binder = self.kind();
2328         p!(print(binder))
2329     }
2330
2331     ty::PredicateKind<'tcx> {
2332         match *self {
2333             ty::PredicateKind::Trait(ref data) => {
2334                 p!(print(data))
2335             }
2336             ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
2337             ty::PredicateKind::Coerce(predicate) => p!(print(predicate)),
2338             ty::PredicateKind::RegionOutlives(predicate) => p!(print(predicate)),
2339             ty::PredicateKind::TypeOutlives(predicate) => p!(print(predicate)),
2340             ty::PredicateKind::Projection(predicate) => p!(print(predicate)),
2341             ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"),
2342             ty::PredicateKind::ObjectSafe(trait_def_id) => {
2343                 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
2344             }
2345             ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
2346                 p!("the closure `",
2347                 print_value_path(closure_def_id, &[]),
2348                 write("` implements the trait `{}`", kind))
2349             }
2350             ty::PredicateKind::ConstEvaluatable(uv) => {
2351                 p!("the constant `", print_value_path(uv.def.did, uv.substs_.map_or(&[], |x| x)), "` can be evaluated")
2352             }
2353             ty::PredicateKind::ConstEquate(c1, c2) => {
2354                 p!("the constant `", print(c1), "` equals `", print(c2), "`")
2355             }
2356             ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
2357                 p!("the type `", print(ty), "` is found in the environment")
2358             }
2359         }
2360     }
2361
2362     GenericArg<'tcx> {
2363         match self.unpack() {
2364             GenericArgKind::Lifetime(lt) => p!(print(lt)),
2365             GenericArgKind::Type(ty) => p!(print(ty)),
2366             GenericArgKind::Const(ct) => p!(print(ct)),
2367         }
2368     }
2369 }
2370
2371 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2372     // Iterate all local crate items no matter where they are defined.
2373     let hir = tcx.hir();
2374     for item in hir.items() {
2375         if item.ident.name.as_str().is_empty() || matches!(item.kind, ItemKind::Use(_, _)) {
2376             continue;
2377         }
2378
2379         let def_id = item.def_id.to_def_id();
2380         let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2381         collect_fn(&item.ident, ns, def_id);
2382     }
2383
2384     // Now take care of extern crate items.
2385     let queue = &mut Vec::new();
2386     let mut seen_defs: DefIdSet = Default::default();
2387
2388     for &cnum in tcx.crates(()).iter() {
2389         let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2390
2391         // Ignore crates that are not direct dependencies.
2392         match tcx.extern_crate(def_id) {
2393             None => continue,
2394             Some(extern_crate) => {
2395                 if !extern_crate.is_direct() {
2396                     continue;
2397                 }
2398             }
2399         }
2400
2401         queue.push(def_id);
2402     }
2403
2404     // Iterate external crate defs but be mindful about visibility
2405     while let Some(def) = queue.pop() {
2406         for child in tcx.item_children(def).iter() {
2407             if !child.vis.is_public() {
2408                 continue;
2409             }
2410
2411             match child.res {
2412                 def::Res::Def(DefKind::AssocTy, _) => {}
2413                 def::Res::Def(DefKind::TyAlias, _) => {}
2414                 def::Res::Def(defkind, def_id) => {
2415                     if let Some(ns) = defkind.ns() {
2416                         collect_fn(&child.ident, ns, def_id);
2417                     }
2418
2419                     if seen_defs.insert(def_id) {
2420                         queue.push(def_id);
2421                     }
2422                 }
2423                 _ => {}
2424             }
2425         }
2426     }
2427 }
2428
2429 /// The purpose of this function is to collect public symbols names that are unique across all
2430 /// crates in the build. Later, when printing about types we can use those names instead of the
2431 /// full exported path to them.
2432 ///
2433 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2434 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2435 /// path and print only the name.
2436 ///
2437 /// This has wide implications on error messages with types, for example, shortening
2438 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2439 ///
2440 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2441 fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> FxHashMap<DefId, Symbol> {
2442     let mut map: FxHashMap<DefId, Symbol> = FxHashMap::default();
2443
2444     if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2445         // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2446         // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2447         tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2448     }
2449
2450     let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2451         &mut FxHashMap::default();
2452
2453     for symbol_set in tcx.resolutions(()).glob_map.values() {
2454         for symbol in symbol_set {
2455             unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2456             unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2457             unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2458         }
2459     }
2460
2461     for_each_def(tcx, |ident, ns, def_id| {
2462         use std::collections::hash_map::Entry::{Occupied, Vacant};
2463
2464         match unique_symbols_rev.entry((ns, ident.name)) {
2465             Occupied(mut v) => match v.get() {
2466                 None => {}
2467                 Some(existing) => {
2468                     if *existing != def_id {
2469                         v.insert(None);
2470                     }
2471                 }
2472             },
2473             Vacant(v) => {
2474                 v.insert(Some(def_id));
2475             }
2476         }
2477     });
2478
2479     for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2480         use std::collections::hash_map::Entry::{Occupied, Vacant};
2481
2482         if let Some(def_id) = opt_def_id {
2483             match map.entry(def_id) {
2484                 Occupied(mut v) => {
2485                     // A single DefId can be known under multiple names (e.g.,
2486                     // with a `pub use ... as ...;`). We need to ensure that the
2487                     // name placed in this map is chosen deterministically, so
2488                     // if we find multiple names (`symbol`) resolving to the
2489                     // same `def_id`, we prefer the lexicographically smallest
2490                     // name.
2491                     //
2492                     // Any stable ordering would be fine here though.
2493                     if *v.get() != symbol {
2494                         if v.get().as_str() > symbol.as_str() {
2495                             v.insert(symbol);
2496                         }
2497                     }
2498                 }
2499                 Vacant(v) => {
2500                     v.insert(symbol);
2501                 }
2502             }
2503         }
2504     }
2505
2506     map
2507 }
2508
2509 pub fn provide(providers: &mut ty::query::Providers) {
2510     *providers = ty::query::Providers { trimmed_def_paths, ..*providers };
2511 }