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