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