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