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