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