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