]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/print/pretty.rs
Rollup merge of #104359 - Nilstrieb:plus-one, r=fee1-dead
[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                 match movability {
686                     hir::Movability::Movable => {}
687                     hir::Movability::Static => p!("static "),
688                 }
689
690                 if !self.should_print_verbose() {
691                     p!("generator");
692                     // FIXME(eddyb) should use `def_span`.
693                     if let Some(did) = did.as_local() {
694                         let span = self.tcx().def_span(did);
695                         p!(write(
696                             "@{}",
697                             // This may end up in stderr diagnostics but it may also be emitted
698                             // into MIR. Hence we use the remapped path if available
699                             self.tcx().sess.source_map().span_to_embeddable_string(span)
700                         ));
701                     } else {
702                         p!(write("@"), print_def_path(did, substs));
703                     }
704                 } else {
705                     p!(print_def_path(did, substs));
706                     p!(" upvar_tys=(");
707                     if !substs.as_generator().is_valid() {
708                         p!("unavailable");
709                     } else {
710                         self = self.comma_sep(substs.as_generator().upvar_tys())?;
711                     }
712                     p!(")");
713
714                     if substs.as_generator().is_valid() {
715                         p!(" ", print(substs.as_generator().witness()));
716                     }
717                 }
718
719                 p!("]")
720             }
721             ty::GeneratorWitness(types) => {
722                 p!(in_binder(&types));
723             }
724             ty::Closure(did, substs) => {
725                 p!(write("["));
726                 if !self.should_print_verbose() {
727                     p!(write("closure"));
728                     // FIXME(eddyb) should use `def_span`.
729                     if let Some(did) = did.as_local() {
730                         if self.tcx().sess.opts.unstable_opts.span_free_formats {
731                             p!("@", print_def_path(did.to_def_id(), substs));
732                         } else {
733                             let span = self.tcx().def_span(did);
734                             p!(write(
735                                 "@{}",
736                                 // This may end up in stderr diagnostics but it may also be emitted
737                                 // into MIR. Hence we use the remapped path if available
738                                 self.tcx().sess.source_map().span_to_embeddable_string(span)
739                             ));
740                         }
741                     } else {
742                         p!(write("@"), print_def_path(did, substs));
743                     }
744                 } else {
745                     p!(print_def_path(did, substs));
746                     if !substs.as_closure().is_valid() {
747                         p!(" closure_substs=(unavailable)");
748                         p!(write(" substs={:?}", substs));
749                     } else {
750                         p!(" closure_kind_ty=", print(substs.as_closure().kind_ty()));
751                         p!(
752                             " closure_sig_as_fn_ptr_ty=",
753                             print(substs.as_closure().sig_as_fn_ptr_ty())
754                         );
755                         p!(" upvar_tys=(");
756                         self = self.comma_sep(substs.as_closure().upvar_tys())?;
757                         p!(")");
758                     }
759                 }
760                 p!("]");
761             }
762             ty::Array(ty, sz) => {
763                 p!("[", print(ty), "; ");
764                 if self.should_print_verbose() {
765                     p!(write("{:?}", sz));
766                 } else if let ty::ConstKind::Unevaluated(..) = sz.kind() {
767                     // Do not try to evaluate unevaluated constants. If we are const evaluating an
768                     // array length anon const, rustc will (with debug assertions) print the
769                     // constant's path. Which will end up here again.
770                     p!("_");
771                 } else if let Some(n) = sz.kind().try_to_bits(self.tcx().data_layout.pointer_size) {
772                     p!(write("{}", n));
773                 } else if let ty::ConstKind::Param(param) = sz.kind() {
774                     p!(print(param));
775                 } else {
776                     p!("_");
777                 }
778                 p!("]")
779             }
780             ty::Slice(ty) => p!("[", print(ty), "]"),
781         }
782
783         Ok(self)
784     }
785
786     fn pretty_print_opaque_impl_type(
787         mut self,
788         def_id: DefId,
789         substs: &'tcx ty::List<ty::GenericArg<'tcx>>,
790     ) -> Result<Self::Type, Self::Error> {
791         let tcx = self.tcx();
792
793         // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
794         // by looking up the projections associated with the def_id.
795         let bounds = tcx.bound_explicit_item_bounds(def_id);
796
797         let mut traits = FxIndexMap::default();
798         let mut fn_traits = FxIndexMap::default();
799         let mut is_sized = false;
800         let mut lifetimes = SmallVec::<[ty::Region<'tcx>; 1]>::new();
801
802         for (predicate, _) in bounds.subst_iter_copied(tcx, substs) {
803             let bound_predicate = predicate.kind();
804
805             match bound_predicate.skip_binder() {
806                 ty::PredicateKind::Trait(pred) => {
807                     let trait_ref = bound_predicate.rebind(pred.trait_ref);
808
809                     // Don't print + Sized, but rather + ?Sized if absent.
810                     if Some(trait_ref.def_id()) == tcx.lang_items().sized_trait() {
811                         is_sized = true;
812                         continue;
813                     }
814
815                     self.insert_trait_and_projection(trait_ref, None, &mut traits, &mut fn_traits);
816                 }
817                 ty::PredicateKind::Projection(pred) => {
818                     let proj_ref = bound_predicate.rebind(pred);
819                     let trait_ref = proj_ref.required_poly_trait_ref(tcx);
820
821                     // Projection type entry -- the def-id for naming, and the ty.
822                     let proj_ty = (proj_ref.projection_def_id(), proj_ref.term());
823
824                     self.insert_trait_and_projection(
825                         trait_ref,
826                         Some(proj_ty),
827                         &mut traits,
828                         &mut fn_traits,
829                     );
830                 }
831                 ty::PredicateKind::TypeOutlives(outlives) => {
832                     lifetimes.push(outlives.1);
833                 }
834                 _ => {}
835             }
836         }
837
838         write!(self, "impl ")?;
839
840         let mut first = true;
841         // Insert parenthesis around (Fn(A, B) -> C) if the opaque ty has more than one other trait
842         let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !is_sized;
843
844         for (fn_once_trait_ref, entry) in fn_traits {
845             write!(self, "{}", if first { "" } else { " + " })?;
846             write!(self, "{}", if paren_needed { "(" } else { "" })?;
847
848             self = self.wrap_binder(&fn_once_trait_ref, |trait_ref, mut cx| {
849                 define_scoped_cx!(cx);
850                 // Get the (single) generic ty (the args) of this FnOnce trait ref.
851                 let generics = tcx.generics_of(trait_ref.def_id);
852                 let args = generics.own_substs_no_defaults(tcx, trait_ref.substs);
853
854                 match (entry.return_ty, args[0].expect_ty()) {
855                     // We can only print `impl Fn() -> ()` if we have a tuple of args and we recorded
856                     // a return type.
857                     (Some(return_ty), arg_tys) if matches!(arg_tys.kind(), ty::Tuple(_)) => {
858                         let name = if entry.fn_trait_ref.is_some() {
859                             "Fn"
860                         } else if entry.fn_mut_trait_ref.is_some() {
861                             "FnMut"
862                         } else {
863                             "FnOnce"
864                         };
865
866                         p!(write("{}(", name));
867
868                         for (idx, ty) in arg_tys.tuple_fields().iter().enumerate() {
869                             if idx > 0 {
870                                 p!(", ");
871                             }
872                             p!(print(ty));
873                         }
874
875                         p!(")");
876                         if let Some(ty) = return_ty.skip_binder().ty() {
877                             if !ty.is_unit() {
878                                 p!(" -> ", print(return_ty));
879                             }
880                         }
881                         p!(write("{}", if paren_needed { ")" } else { "" }));
882
883                         first = false;
884                     }
885                     // If we got here, we can't print as a `impl Fn(A, B) -> C`. Just record the
886                     // trait_refs we collected in the OpaqueFnEntry as normal trait refs.
887                     _ => {
888                         if entry.has_fn_once {
889                             traits.entry(fn_once_trait_ref).or_default().extend(
890                                 // Group the return ty with its def id, if we had one.
891                                 entry
892                                     .return_ty
893                                     .map(|ty| (tcx.require_lang_item(LangItem::FnOnce, None), ty)),
894                             );
895                         }
896                         if let Some(trait_ref) = entry.fn_mut_trait_ref {
897                             traits.entry(trait_ref).or_default();
898                         }
899                         if let Some(trait_ref) = entry.fn_trait_ref {
900                             traits.entry(trait_ref).or_default();
901                         }
902                     }
903                 }
904
905                 Ok(cx)
906             })?;
907         }
908
909         // Print the rest of the trait types (that aren't Fn* family of traits)
910         for (trait_ref, assoc_items) in traits {
911             write!(self, "{}", if first { "" } else { " + " })?;
912
913             self = self.wrap_binder(&trait_ref, |trait_ref, mut cx| {
914                 define_scoped_cx!(cx);
915                 p!(print(trait_ref.print_only_trait_name()));
916
917                 let generics = tcx.generics_of(trait_ref.def_id);
918                 let args = generics.own_substs_no_defaults(tcx, trait_ref.substs);
919
920                 if !args.is_empty() || !assoc_items.is_empty() {
921                     let mut first = true;
922
923                     for ty in args {
924                         if first {
925                             p!("<");
926                             first = false;
927                         } else {
928                             p!(", ");
929                         }
930                         p!(print(ty));
931                     }
932
933                     for (assoc_item_def_id, term) in assoc_items {
934                         // Skip printing `<[generator@] as Generator<_>>::Return` from async blocks,
935                         // unless we can find out what generator return type it comes from.
936                         let term = if let Some(ty) = term.skip_binder().ty()
937                             && let ty::Projection(proj) = ty.kind()
938                             && let Some(assoc) = tcx.opt_associated_item(proj.item_def_id)
939                             && assoc.trait_container(tcx) == tcx.lang_items().gen_trait()
940                             && assoc.name == rustc_span::sym::Return
941                         {
942                             if let ty::Generator(_, substs, _) = substs.type_at(0).kind() {
943                                 let return_ty = substs.as_generator().return_ty();
944                                 if !return_ty.is_ty_var() {
945                                     return_ty.into()
946                                 } else {
947                                     continue;
948                                 }
949                             } else {
950                                 continue;
951                             }
952                         } else {
953                             term.skip_binder()
954                         };
955
956                         if first {
957                             p!("<");
958                             first = false;
959                         } else {
960                             p!(", ");
961                         }
962
963                         p!(write("{} = ", tcx.associated_item(assoc_item_def_id).name));
964
965                         match term.unpack() {
966                             TermKind::Ty(ty) => p!(print(ty)),
967                             TermKind::Const(c) => p!(print(c)),
968                         };
969                     }
970
971                     if !first {
972                         p!(">");
973                     }
974                 }
975
976                 first = false;
977                 Ok(cx)
978             })?;
979         }
980
981         if !is_sized {
982             write!(self, "{}?Sized", if first { "" } else { " + " })?;
983         } else if first {
984             write!(self, "Sized")?;
985         }
986
987         for re in lifetimes {
988             write!(self, " + ")?;
989             self = self.print_region(re)?;
990         }
991
992         Ok(self)
993     }
994
995     /// Insert the trait ref and optionally a projection type associated with it into either the
996     /// traits map or fn_traits map, depending on if the trait is in the Fn* family of traits.
997     fn insert_trait_and_projection(
998         &mut self,
999         trait_ref: ty::PolyTraitRef<'tcx>,
1000         proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
1001         traits: &mut FxIndexMap<
1002             ty::PolyTraitRef<'tcx>,
1003             FxIndexMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,
1004         >,
1005         fn_traits: &mut FxIndexMap<ty::PolyTraitRef<'tcx>, OpaqueFnEntry<'tcx>>,
1006     ) {
1007         let trait_def_id = trait_ref.def_id();
1008
1009         // If our trait_ref is FnOnce or any of its children, project it onto the parent FnOnce
1010         // super-trait ref and record it there.
1011         if let Some(fn_once_trait) = self.tcx().lang_items().fn_once_trait() {
1012             // If we have a FnOnce, then insert it into
1013             if trait_def_id == fn_once_trait {
1014                 let entry = fn_traits.entry(trait_ref).or_default();
1015                 // Optionally insert the return_ty as well.
1016                 if let Some((_, ty)) = proj_ty {
1017                     entry.return_ty = Some(ty);
1018                 }
1019                 entry.has_fn_once = true;
1020                 return;
1021             } else if Some(trait_def_id) == self.tcx().lang_items().fn_mut_trait() {
1022                 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
1023                     .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
1024                     .unwrap();
1025
1026                 fn_traits.entry(super_trait_ref).or_default().fn_mut_trait_ref = Some(trait_ref);
1027                 return;
1028             } else if Some(trait_def_id) == self.tcx().lang_items().fn_trait() {
1029                 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
1030                     .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
1031                     .unwrap();
1032
1033                 fn_traits.entry(super_trait_ref).or_default().fn_trait_ref = Some(trait_ref);
1034                 return;
1035             }
1036         }
1037
1038         // Otherwise, just group our traits and projection types.
1039         traits.entry(trait_ref).or_default().extend(proj_ty);
1040     }
1041
1042     fn pretty_print_bound_var(
1043         &mut self,
1044         debruijn: ty::DebruijnIndex,
1045         var: ty::BoundVar,
1046     ) -> Result<(), Self::Error> {
1047         if debruijn == ty::INNERMOST {
1048             write!(self, "^{}", var.index())
1049         } else {
1050             write!(self, "^{}_{}", debruijn.index(), var.index())
1051         }
1052     }
1053
1054     fn ty_infer_name(&self, _: ty::TyVid) -> Option<Symbol> {
1055         None
1056     }
1057
1058     fn const_infer_name(&self, _: ty::ConstVid<'tcx>) -> Option<Symbol> {
1059         None
1060     }
1061
1062     fn pretty_print_dyn_existential(
1063         mut self,
1064         predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1065     ) -> Result<Self::DynExistential, Self::Error> {
1066         // Generate the main trait ref, including associated types.
1067         let mut first = true;
1068
1069         if let Some(principal) = predicates.principal() {
1070             self = self.wrap_binder(&principal, |principal, mut cx| {
1071                 define_scoped_cx!(cx);
1072                 p!(print_def_path(principal.def_id, &[]));
1073
1074                 let mut resugared = false;
1075
1076                 // Special-case `Fn(...) -> ...` and re-sugar it.
1077                 let fn_trait_kind = cx.tcx().fn_trait_kind_from_lang_item(principal.def_id);
1078                 if !cx.should_print_verbose() && fn_trait_kind.is_some() {
1079                     if let ty::Tuple(tys) = principal.substs.type_at(0).kind() {
1080                         let mut projections = predicates.projection_bounds();
1081                         if let (Some(proj), None) = (projections.next(), projections.next()) {
1082                             p!(pretty_fn_sig(
1083                                 tys,
1084                                 false,
1085                                 proj.skip_binder().term.ty().expect("Return type was a const")
1086                             ));
1087                             resugared = true;
1088                         }
1089                     }
1090                 }
1091
1092                 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
1093                 // in order to place the projections inside the `<...>`.
1094                 if !resugared {
1095                     // Use a type that can't appear in defaults of type parameters.
1096                     let dummy_cx = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1097                     let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
1098
1099                     let args = cx
1100                         .tcx()
1101                         .generics_of(principal.def_id)
1102                         .own_substs_no_defaults(cx.tcx(), principal.substs);
1103
1104                     let mut projections = predicates.projection_bounds();
1105
1106                     let mut args = args.iter().cloned();
1107                     let arg0 = args.next();
1108                     let projection0 = projections.next();
1109                     if arg0.is_some() || projection0.is_some() {
1110                         let args = arg0.into_iter().chain(args);
1111                         let projections = projection0.into_iter().chain(projections);
1112
1113                         p!(generic_delimiters(|mut cx| {
1114                             cx = cx.comma_sep(args)?;
1115                             if arg0.is_some() && projection0.is_some() {
1116                                 write!(cx, ", ")?;
1117                             }
1118                             cx.comma_sep(projections)
1119                         }));
1120                     }
1121                 }
1122                 Ok(cx)
1123             })?;
1124
1125             first = false;
1126         }
1127
1128         define_scoped_cx!(self);
1129
1130         // Builtin bounds.
1131         // FIXME(eddyb) avoid printing twice (needed to ensure
1132         // that the auto traits are sorted *and* printed via cx).
1133         let mut auto_traits: Vec<_> = predicates.auto_traits().collect();
1134
1135         // The auto traits come ordered by `DefPathHash`. While
1136         // `DefPathHash` is *stable* in the sense that it depends on
1137         // neither the host nor the phase of the moon, it depends
1138         // "pseudorandomly" on the compiler version and the target.
1139         //
1140         // To avoid causing instabilities in compiletest
1141         // output, sort the auto-traits alphabetically.
1142         auto_traits.sort_by_cached_key(|did| with_no_trimmed_paths!(self.tcx().def_path_str(*did)));
1143
1144         for def_id in auto_traits {
1145             if !first {
1146                 p!(" + ");
1147             }
1148             first = false;
1149
1150             p!(print_def_path(def_id, &[]));
1151         }
1152
1153         Ok(self)
1154     }
1155
1156     fn pretty_fn_sig(
1157         mut self,
1158         inputs: &[Ty<'tcx>],
1159         c_variadic: bool,
1160         output: Ty<'tcx>,
1161     ) -> Result<Self, Self::Error> {
1162         define_scoped_cx!(self);
1163
1164         p!("(", comma_sep(inputs.iter().copied()));
1165         if c_variadic {
1166             if !inputs.is_empty() {
1167                 p!(", ");
1168             }
1169             p!("...");
1170         }
1171         p!(")");
1172         if !output.is_unit() {
1173             p!(" -> ", print(output));
1174         }
1175
1176         Ok(self)
1177     }
1178
1179     fn pretty_print_const(
1180         mut self,
1181         ct: ty::Const<'tcx>,
1182         print_ty: bool,
1183     ) -> Result<Self::Const, Self::Error> {
1184         define_scoped_cx!(self);
1185
1186         if self.should_print_verbose() {
1187             p!(write("Const({:?}: {:?})", ct.kind(), ct.ty()));
1188             return Ok(self);
1189         }
1190
1191         macro_rules! print_underscore {
1192             () => {{
1193                 if print_ty {
1194                     self = self.typed_value(
1195                         |mut this| {
1196                             write!(this, "_")?;
1197                             Ok(this)
1198                         },
1199                         |this| this.print_type(ct.ty()),
1200                         ": ",
1201                     )?;
1202                 } else {
1203                     write!(self, "_")?;
1204                 }
1205             }};
1206         }
1207
1208         match ct.kind() {
1209             ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => {
1210                 match self.tcx().def_kind(def.did) {
1211                     DefKind::Static(..) | DefKind::Const | DefKind::AssocConst => {
1212                         p!(print_value_path(def.did, substs))
1213                     }
1214                     _ => {
1215                         if def.is_local() {
1216                             let span = self.tcx().def_span(def.did);
1217                             if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
1218                                 p!(write("{}", snip))
1219                             } else {
1220                                 print_underscore!()
1221                             }
1222                         } else {
1223                             print_underscore!()
1224                         }
1225                     }
1226                 }
1227             }
1228             ty::ConstKind::Infer(infer_ct) => {
1229                 match infer_ct {
1230                     ty::InferConst::Var(ct_vid)
1231                         if let Some(name) = self.const_infer_name(ct_vid) =>
1232                             p!(write("{}", name)),
1233                     _ => print_underscore!(),
1234                 }
1235             }
1236             ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1237             ty::ConstKind::Value(value) => {
1238                 return self.pretty_print_const_valtree(value, ct.ty(), print_ty);
1239             }
1240
1241             ty::ConstKind::Bound(debruijn, bound_var) => {
1242                 self.pretty_print_bound_var(debruijn, bound_var)?
1243             }
1244             ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
1245             ty::ConstKind::Error(_) => p!("[const error]"),
1246         };
1247         Ok(self)
1248     }
1249
1250     fn pretty_print_const_scalar(
1251         self,
1252         scalar: Scalar,
1253         ty: Ty<'tcx>,
1254         print_ty: bool,
1255     ) -> Result<Self::Const, Self::Error> {
1256         match scalar {
1257             Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty, print_ty),
1258             Scalar::Int(int) => self.pretty_print_const_scalar_int(int, ty, print_ty),
1259         }
1260     }
1261
1262     fn pretty_print_const_scalar_ptr(
1263         mut self,
1264         ptr: Pointer,
1265         ty: Ty<'tcx>,
1266         print_ty: bool,
1267     ) -> Result<Self::Const, Self::Error> {
1268         define_scoped_cx!(self);
1269
1270         let (alloc_id, offset) = ptr.into_parts();
1271         match ty.kind() {
1272             // Byte strings (&[u8; N])
1273             ty::Ref(_, inner, _) => {
1274                 if let ty::Array(elem, len) = inner.kind() {
1275                     if let ty::Uint(ty::UintTy::U8) = elem.kind() {
1276                         if let ty::ConstKind::Value(ty::ValTree::Leaf(int)) = len.kind() {
1277                             match self.tcx().try_get_global_alloc(alloc_id) {
1278                                 Some(GlobalAlloc::Memory(alloc)) => {
1279                                     let len = int.assert_bits(self.tcx().data_layout.pointer_size);
1280                                     let range =
1281                                         AllocRange { start: offset, size: Size::from_bytes(len) };
1282                                     if let Ok(byte_str) =
1283                                         alloc.inner().get_bytes_strip_provenance(&self.tcx(), range)
1284                                     {
1285                                         p!(pretty_print_byte_str(byte_str))
1286                                     } else {
1287                                         p!("<too short allocation>")
1288                                     }
1289                                 }
1290                                 // FIXME: for statics, vtables, and functions, we could in principle print more detail.
1291                                 Some(GlobalAlloc::Static(def_id)) => {
1292                                     p!(write("<static({:?})>", def_id))
1293                                 }
1294                                 Some(GlobalAlloc::Function(_)) => p!("<function>"),
1295                                 Some(GlobalAlloc::VTable(..)) => p!("<vtable>"),
1296                                 None => p!("<dangling pointer>"),
1297                             }
1298                             return Ok(self);
1299                         }
1300                     }
1301                 }
1302             }
1303             ty::FnPtr(_) => {
1304                 // FIXME: We should probably have a helper method to share code with the "Byte strings"
1305                 // printing above (which also has to handle pointers to all sorts of things).
1306                 if let Some(GlobalAlloc::Function(instance)) =
1307                     self.tcx().try_get_global_alloc(alloc_id)
1308                 {
1309                     self = self.typed_value(
1310                         |this| this.print_value_path(instance.def_id(), instance.substs),
1311                         |this| this.print_type(ty),
1312                         " as ",
1313                     )?;
1314                     return Ok(self);
1315                 }
1316             }
1317             _ => {}
1318         }
1319         // Any pointer values not covered by a branch above
1320         self = self.pretty_print_const_pointer(ptr, ty, print_ty)?;
1321         Ok(self)
1322     }
1323
1324     fn pretty_print_const_scalar_int(
1325         mut self,
1326         int: ScalarInt,
1327         ty: Ty<'tcx>,
1328         print_ty: bool,
1329     ) -> Result<Self::Const, Self::Error> {
1330         define_scoped_cx!(self);
1331
1332         match ty.kind() {
1333             // Bool
1334             ty::Bool if int == ScalarInt::FALSE => p!("false"),
1335             ty::Bool if int == ScalarInt::TRUE => p!("true"),
1336             // Float
1337             ty::Float(ty::FloatTy::F32) => {
1338                 p!(write("{}f32", Single::try_from(int).unwrap()))
1339             }
1340             ty::Float(ty::FloatTy::F64) => {
1341                 p!(write("{}f64", Double::try_from(int).unwrap()))
1342             }
1343             // Int
1344             ty::Uint(_) | ty::Int(_) => {
1345                 let int =
1346                     ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1347                 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1348             }
1349             // Char
1350             ty::Char if char::try_from(int).is_ok() => {
1351                 p!(write("{:?}", char::try_from(int).unwrap()))
1352             }
1353             // Pointer types
1354             ty::Ref(..) | ty::RawPtr(_) | ty::FnPtr(_) => {
1355                 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
1356                 self = self.typed_value(
1357                     |mut this| {
1358                         write!(this, "0x{:x}", data)?;
1359                         Ok(this)
1360                     },
1361                     |this| this.print_type(ty),
1362                     " as ",
1363                 )?;
1364             }
1365             // Nontrivial types with scalar bit representation
1366             _ => {
1367                 let print = |mut this: Self| {
1368                     if int.size() == Size::ZERO {
1369                         write!(this, "transmute(())")?;
1370                     } else {
1371                         write!(this, "transmute(0x{:x})", int)?;
1372                     }
1373                     Ok(this)
1374                 };
1375                 self = if print_ty {
1376                     self.typed_value(print, |this| this.print_type(ty), ": ")?
1377                 } else {
1378                     print(self)?
1379                 };
1380             }
1381         }
1382         Ok(self)
1383     }
1384
1385     /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1386     /// from MIR where it is actually useful.
1387     fn pretty_print_const_pointer<Prov: Provenance>(
1388         mut self,
1389         _: Pointer<Prov>,
1390         ty: Ty<'tcx>,
1391         print_ty: bool,
1392     ) -> Result<Self::Const, Self::Error> {
1393         if print_ty {
1394             self.typed_value(
1395                 |mut this| {
1396                     this.write_str("&_")?;
1397                     Ok(this)
1398                 },
1399                 |this| this.print_type(ty),
1400                 ": ",
1401             )
1402         } else {
1403             self.write_str("&_")?;
1404             Ok(self)
1405         }
1406     }
1407
1408     fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1409         write!(self, "b\"{}\"", byte_str.escape_ascii())?;
1410         Ok(self)
1411     }
1412
1413     fn pretty_print_const_valtree(
1414         mut self,
1415         valtree: ty::ValTree<'tcx>,
1416         ty: Ty<'tcx>,
1417         print_ty: bool,
1418     ) -> Result<Self::Const, Self::Error> {
1419         define_scoped_cx!(self);
1420
1421         if self.should_print_verbose() {
1422             p!(write("ValTree({:?}: ", valtree), print(ty), ")");
1423             return Ok(self);
1424         }
1425
1426         let u8_type = self.tcx().types.u8;
1427         match (valtree, ty.kind()) {
1428             (ty::ValTree::Branch(_), ty::Ref(_, inner_ty, _)) => match inner_ty.kind() {
1429                 ty::Slice(t) if *t == u8_type => {
1430                     let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1431                         bug!(
1432                             "expected to convert valtree {:?} to raw bytes for type {:?}",
1433                             valtree,
1434                             t
1435                         )
1436                     });
1437                     return self.pretty_print_byte_str(bytes);
1438                 }
1439                 ty::Str => {
1440                     let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1441                         bug!("expected to convert valtree to raw bytes for type {:?}", ty)
1442                     });
1443                     p!(write("{:?}", String::from_utf8_lossy(bytes)));
1444                     return Ok(self);
1445                 }
1446                 _ => {
1447                     p!("&");
1448                     p!(pretty_print_const_valtree(valtree, *inner_ty, print_ty));
1449                     return Ok(self);
1450                 }
1451             },
1452             (ty::ValTree::Branch(_), ty::Array(t, _)) if *t == u8_type => {
1453                 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1454                     bug!("expected to convert valtree to raw bytes for type {:?}", t)
1455                 });
1456                 p!("*");
1457                 p!(pretty_print_byte_str(bytes));
1458                 return Ok(self);
1459             }
1460             // Aggregates, printed as array/tuple/struct/variant construction syntax.
1461             (ty::ValTree::Branch(_), ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) => {
1462                 let contents =
1463                     self.tcx().destructure_const(ty::Const::from_value(self.tcx(), valtree, ty));
1464                 let fields = contents.fields.iter().copied();
1465                 match *ty.kind() {
1466                     ty::Array(..) => {
1467                         p!("[", comma_sep(fields), "]");
1468                     }
1469                     ty::Tuple(..) => {
1470                         p!("(", comma_sep(fields));
1471                         if contents.fields.len() == 1 {
1472                             p!(",");
1473                         }
1474                         p!(")");
1475                     }
1476                     ty::Adt(def, _) if def.variants().is_empty() => {
1477                         self = self.typed_value(
1478                             |mut this| {
1479                                 write!(this, "unreachable()")?;
1480                                 Ok(this)
1481                             },
1482                             |this| this.print_type(ty),
1483                             ": ",
1484                         )?;
1485                     }
1486                     ty::Adt(def, substs) => {
1487                         let variant_idx =
1488                             contents.variant.expect("destructed const of adt without variant idx");
1489                         let variant_def = &def.variant(variant_idx);
1490                         p!(print_value_path(variant_def.def_id, substs));
1491                         match variant_def.ctor_kind() {
1492                             Some(CtorKind::Const) => {}
1493                             Some(CtorKind::Fn) => {
1494                                 p!("(", comma_sep(fields), ")");
1495                             }
1496                             None => {
1497                                 p!(" {{ ");
1498                                 let mut first = true;
1499                                 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1500                                     if !first {
1501                                         p!(", ");
1502                                     }
1503                                     p!(write("{}: ", field_def.name), print(field));
1504                                     first = false;
1505                                 }
1506                                 p!(" }}");
1507                             }
1508                         }
1509                     }
1510                     _ => unreachable!(),
1511                 }
1512                 return Ok(self);
1513             }
1514             (ty::ValTree::Leaf(leaf), ty::Ref(_, inner_ty, _)) => {
1515                 p!(write("&"));
1516                 return self.pretty_print_const_scalar_int(leaf, *inner_ty, print_ty);
1517             }
1518             (ty::ValTree::Leaf(leaf), _) => {
1519                 return self.pretty_print_const_scalar_int(leaf, ty, print_ty);
1520             }
1521             // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1522             // their fields instead of just dumping the memory.
1523             _ => {}
1524         }
1525
1526         // fallback
1527         if valtree == ty::ValTree::zst() {
1528             p!(write("<ZST>"));
1529         } else {
1530             p!(write("{:?}", valtree));
1531         }
1532         if print_ty {
1533             p!(": ", print(ty));
1534         }
1535         Ok(self)
1536     }
1537
1538     fn pretty_closure_as_impl(
1539         mut self,
1540         closure: ty::ClosureSubsts<'tcx>,
1541     ) -> Result<Self::Const, Self::Error> {
1542         let sig = closure.sig();
1543         let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn);
1544
1545         write!(self, "impl ")?;
1546         self.wrap_binder(&sig, |sig, mut cx| {
1547             define_scoped_cx!(cx);
1548
1549             p!(print(kind), "(");
1550             for (i, arg) in sig.inputs()[0].tuple_fields().iter().enumerate() {
1551                 if i > 0 {
1552                     p!(", ");
1553                 }
1554                 p!(print(arg));
1555             }
1556             p!(")");
1557
1558             if !sig.output().is_unit() {
1559                 p!(" -> ", print(sig.output()));
1560             }
1561
1562             Ok(cx)
1563         })
1564     }
1565
1566     fn should_print_verbose(&self) -> bool {
1567         self.tcx().sess.verbose()
1568     }
1569 }
1570
1571 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1572 pub struct FmtPrinter<'a, 'tcx>(Box<FmtPrinterData<'a, 'tcx>>);
1573
1574 pub struct FmtPrinterData<'a, 'tcx> {
1575     tcx: TyCtxt<'tcx>,
1576     fmt: String,
1577
1578     empty_path: bool,
1579     in_value: bool,
1580     pub print_alloc_ids: bool,
1581
1582     // set of all named (non-anonymous) region names
1583     used_region_names: FxHashSet<Symbol>,
1584
1585     region_index: usize,
1586     binder_depth: usize,
1587     printed_type_count: usize,
1588     type_length_limit: Limit,
1589     truncated: bool,
1590
1591     pub region_highlight_mode: RegionHighlightMode<'tcx>,
1592
1593     pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<Symbol> + 'a>>,
1594     pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid<'tcx>) -> Option<Symbol> + 'a>>,
1595 }
1596
1597 impl<'a, 'tcx> Deref for FmtPrinter<'a, 'tcx> {
1598     type Target = FmtPrinterData<'a, 'tcx>;
1599     fn deref(&self) -> &Self::Target {
1600         &self.0
1601     }
1602 }
1603
1604 impl DerefMut for FmtPrinter<'_, '_> {
1605     fn deref_mut(&mut self) -> &mut Self::Target {
1606         &mut self.0
1607     }
1608 }
1609
1610 impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
1611     pub fn new(tcx: TyCtxt<'tcx>, ns: Namespace) -> Self {
1612         Self::new_with_limit(tcx, ns, tcx.type_length_limit())
1613     }
1614
1615     pub fn new_with_limit(tcx: TyCtxt<'tcx>, ns: Namespace, type_length_limit: Limit) -> Self {
1616         FmtPrinter(Box::new(FmtPrinterData {
1617             tcx,
1618             // Estimated reasonable capacity to allocate upfront based on a few
1619             // benchmarks.
1620             fmt: String::with_capacity(64),
1621             empty_path: false,
1622             in_value: ns == Namespace::ValueNS,
1623             print_alloc_ids: false,
1624             used_region_names: Default::default(),
1625             region_index: 0,
1626             binder_depth: 0,
1627             printed_type_count: 0,
1628             type_length_limit,
1629             truncated: false,
1630             region_highlight_mode: RegionHighlightMode::new(tcx),
1631             ty_infer_name_resolver: None,
1632             const_infer_name_resolver: None,
1633         }))
1634     }
1635
1636     pub fn into_buffer(self) -> String {
1637         self.0.fmt
1638     }
1639 }
1640
1641 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1642 // (but also some things just print a `DefId` generally so maybe we need this?)
1643 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1644     match tcx.def_key(def_id).disambiguated_data.data {
1645         DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1646             Namespace::TypeNS
1647         }
1648
1649         DefPathData::ValueNs(..)
1650         | DefPathData::AnonConst
1651         | DefPathData::ClosureExpr
1652         | DefPathData::Ctor => Namespace::ValueNS,
1653
1654         DefPathData::MacroNs(..) => Namespace::MacroNS,
1655
1656         _ => Namespace::TypeNS,
1657     }
1658 }
1659
1660 impl<'t> TyCtxt<'t> {
1661     /// Returns a string identifying this `DefId`. This string is
1662     /// suitable for user output.
1663     pub fn def_path_str(self, def_id: DefId) -> String {
1664         self.def_path_str_with_substs(def_id, &[])
1665     }
1666
1667     pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1668         let ns = guess_def_namespace(self, def_id);
1669         debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1670         FmtPrinter::new(self, ns).print_def_path(def_id, substs).unwrap().into_buffer()
1671     }
1672
1673     pub fn value_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1674         let ns = guess_def_namespace(self, def_id);
1675         debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns);
1676         FmtPrinter::new(self, ns).print_value_path(def_id, substs).unwrap().into_buffer()
1677     }
1678 }
1679
1680 impl fmt::Write for FmtPrinter<'_, '_> {
1681     fn write_str(&mut self, s: &str) -> fmt::Result {
1682         self.fmt.push_str(s);
1683         Ok(())
1684     }
1685 }
1686
1687 impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
1688     type Error = fmt::Error;
1689
1690     type Path = Self;
1691     type Region = Self;
1692     type Type = Self;
1693     type DynExistential = Self;
1694     type Const = Self;
1695
1696     fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
1697         self.tcx
1698     }
1699
1700     fn print_def_path(
1701         mut self,
1702         def_id: DefId,
1703         substs: &'tcx [GenericArg<'tcx>],
1704     ) -> Result<Self::Path, Self::Error> {
1705         define_scoped_cx!(self);
1706
1707         if substs.is_empty() {
1708             match self.try_print_trimmed_def_path(def_id)? {
1709                 (cx, true) => return Ok(cx),
1710                 (cx, false) => self = cx,
1711             }
1712
1713             match self.try_print_visible_def_path(def_id)? {
1714                 (cx, true) => return Ok(cx),
1715                 (cx, false) => self = cx,
1716             }
1717         }
1718
1719         let key = self.tcx.def_key(def_id);
1720         if let DefPathData::Impl = key.disambiguated_data.data {
1721             // Always use types for non-local impls, where types are always
1722             // available, and filename/line-number is mostly uninteresting.
1723             let use_types = !def_id.is_local() || {
1724                 // Otherwise, use filename/line-number if forced.
1725                 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1726                 !force_no_types
1727             };
1728
1729             if !use_types {
1730                 // If no type info is available, fall back to
1731                 // pretty printing some span information. This should
1732                 // only occur very early in the compiler pipeline.
1733                 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1734                 let span = self.tcx.def_span(def_id);
1735
1736                 self = self.print_def_path(parent_def_id, &[])?;
1737
1738                 // HACK(eddyb) copy of `path_append` to avoid
1739                 // constructing a `DisambiguatedDefPathData`.
1740                 if !self.empty_path {
1741                     write!(self, "::")?;
1742                 }
1743                 write!(
1744                     self,
1745                     "<impl at {}>",
1746                     // This may end up in stderr diagnostics but it may also be emitted
1747                     // into MIR. Hence we use the remapped path if available
1748                     self.tcx.sess.source_map().span_to_embeddable_string(span)
1749                 )?;
1750                 self.empty_path = false;
1751
1752                 return Ok(self);
1753             }
1754         }
1755
1756         self.default_print_def_path(def_id, substs)
1757     }
1758
1759     fn print_region(self, region: ty::Region<'tcx>) -> Result<Self::Region, Self::Error> {
1760         self.pretty_print_region(region)
1761     }
1762
1763     fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1764         if self.type_length_limit.value_within_limit(self.printed_type_count) {
1765             self.printed_type_count += 1;
1766             self.pretty_print_type(ty)
1767         } else {
1768             self.truncated = true;
1769             write!(self, "...")?;
1770             Ok(self)
1771         }
1772     }
1773
1774     fn print_dyn_existential(
1775         self,
1776         predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1777     ) -> Result<Self::DynExistential, Self::Error> {
1778         self.pretty_print_dyn_existential(predicates)
1779     }
1780
1781     fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1782         self.pretty_print_const(ct, false)
1783     }
1784
1785     fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1786         self.empty_path = true;
1787         if cnum == LOCAL_CRATE {
1788             if self.tcx.sess.rust_2018() {
1789                 // We add the `crate::` keyword on Rust 2018, only when desired.
1790                 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1791                     write!(self, "{}", kw::Crate)?;
1792                     self.empty_path = false;
1793                 }
1794             }
1795         } else {
1796             write!(self, "{}", self.tcx.crate_name(cnum))?;
1797             self.empty_path = false;
1798         }
1799         Ok(self)
1800     }
1801
1802     fn path_qualified(
1803         mut self,
1804         self_ty: Ty<'tcx>,
1805         trait_ref: Option<ty::TraitRef<'tcx>>,
1806     ) -> Result<Self::Path, Self::Error> {
1807         self = self.pretty_path_qualified(self_ty, trait_ref)?;
1808         self.empty_path = false;
1809         Ok(self)
1810     }
1811
1812     fn path_append_impl(
1813         mut self,
1814         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1815         _disambiguated_data: &DisambiguatedDefPathData,
1816         self_ty: Ty<'tcx>,
1817         trait_ref: Option<ty::TraitRef<'tcx>>,
1818     ) -> Result<Self::Path, Self::Error> {
1819         self = self.pretty_path_append_impl(
1820             |mut cx| {
1821                 cx = print_prefix(cx)?;
1822                 if !cx.empty_path {
1823                     write!(cx, "::")?;
1824                 }
1825
1826                 Ok(cx)
1827             },
1828             self_ty,
1829             trait_ref,
1830         )?;
1831         self.empty_path = false;
1832         Ok(self)
1833     }
1834
1835     fn path_append(
1836         mut self,
1837         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1838         disambiguated_data: &DisambiguatedDefPathData,
1839     ) -> Result<Self::Path, Self::Error> {
1840         self = print_prefix(self)?;
1841
1842         // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1843         if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1844             return Ok(self);
1845         }
1846
1847         let name = disambiguated_data.data.name();
1848         if !self.empty_path {
1849             write!(self, "::")?;
1850         }
1851
1852         if let DefPathDataName::Named(name) = name {
1853             if Ident::with_dummy_span(name).is_raw_guess() {
1854                 write!(self, "r#")?;
1855             }
1856         }
1857
1858         let verbose = self.should_print_verbose();
1859         disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1860
1861         self.empty_path = false;
1862
1863         Ok(self)
1864     }
1865
1866     fn path_generic_args(
1867         mut self,
1868         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1869         args: &[GenericArg<'tcx>],
1870     ) -> Result<Self::Path, Self::Error> {
1871         self = print_prefix(self)?;
1872
1873         if args.first().is_some() {
1874             if self.in_value {
1875                 write!(self, "::")?;
1876             }
1877             self.generic_delimiters(|cx| cx.comma_sep(args.iter().cloned()))
1878         } else {
1879             Ok(self)
1880         }
1881     }
1882 }
1883
1884 impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
1885     fn ty_infer_name(&self, id: ty::TyVid) -> Option<Symbol> {
1886         self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
1887     }
1888
1889     fn const_infer_name(&self, id: ty::ConstVid<'tcx>) -> Option<Symbol> {
1890         self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
1891     }
1892
1893     fn print_value_path(
1894         mut self,
1895         def_id: DefId,
1896         substs: &'tcx [GenericArg<'tcx>],
1897     ) -> Result<Self::Path, Self::Error> {
1898         let was_in_value = std::mem::replace(&mut self.in_value, true);
1899         self = self.print_def_path(def_id, substs)?;
1900         self.in_value = was_in_value;
1901
1902         Ok(self)
1903     }
1904
1905     fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
1906     where
1907         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1908     {
1909         self.pretty_in_binder(value)
1910     }
1911
1912     fn wrap_binder<T, C: FnOnce(&T, Self) -> Result<Self, Self::Error>>(
1913         self,
1914         value: &ty::Binder<'tcx, T>,
1915         f: C,
1916     ) -> Result<Self, Self::Error>
1917     where
1918         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1919     {
1920         self.pretty_wrap_binder(value, f)
1921     }
1922
1923     fn typed_value(
1924         mut self,
1925         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1926         t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1927         conversion: &str,
1928     ) -> Result<Self::Const, Self::Error> {
1929         self.write_str("{")?;
1930         self = f(self)?;
1931         self.write_str(conversion)?;
1932         let was_in_value = std::mem::replace(&mut self.in_value, false);
1933         self = t(self)?;
1934         self.in_value = was_in_value;
1935         self.write_str("}")?;
1936         Ok(self)
1937     }
1938
1939     fn generic_delimiters(
1940         mut self,
1941         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1942     ) -> Result<Self, Self::Error> {
1943         write!(self, "<")?;
1944
1945         let was_in_value = std::mem::replace(&mut self.in_value, false);
1946         let mut inner = f(self)?;
1947         inner.in_value = was_in_value;
1948
1949         write!(inner, ">")?;
1950         Ok(inner)
1951     }
1952
1953     fn should_print_region(&self, region: ty::Region<'tcx>) -> bool {
1954         let highlight = self.region_highlight_mode;
1955         if highlight.region_highlighted(region).is_some() {
1956             return true;
1957         }
1958
1959         if self.should_print_verbose() {
1960             return true;
1961         }
1962
1963         let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
1964
1965         match *region {
1966             ty::ReEarlyBound(ref data) => {
1967                 data.name != kw::Empty && data.name != kw::UnderscoreLifetime
1968             }
1969
1970             ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
1971             | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1972             | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1973                 if let ty::BrNamed(_, name) = br {
1974                     if name != kw::Empty && name != kw::UnderscoreLifetime {
1975                         return true;
1976                     }
1977                 }
1978
1979                 if let Some((region, _)) = highlight.highlight_bound_region {
1980                     if br == region {
1981                         return true;
1982                     }
1983                 }
1984
1985                 false
1986             }
1987
1988             ty::ReVar(_) if identify_regions => true,
1989
1990             ty::ReVar(_) | ty::ReErased => false,
1991
1992             ty::ReStatic => true,
1993         }
1994     }
1995
1996     fn pretty_print_const_pointer<Prov: Provenance>(
1997         self,
1998         p: Pointer<Prov>,
1999         ty: Ty<'tcx>,
2000         print_ty: bool,
2001     ) -> Result<Self::Const, Self::Error> {
2002         let print = |mut this: Self| {
2003             define_scoped_cx!(this);
2004             if this.print_alloc_ids {
2005                 p!(write("{:?}", p));
2006             } else {
2007                 p!("&_");
2008             }
2009             Ok(this)
2010         };
2011         if print_ty {
2012             self.typed_value(print, |this| this.print_type(ty), ": ")
2013         } else {
2014             print(self)
2015         }
2016     }
2017 }
2018
2019 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
2020 impl<'tcx> FmtPrinter<'_, 'tcx> {
2021     pub fn pretty_print_region(mut self, region: ty::Region<'tcx>) -> Result<Self, fmt::Error> {
2022         define_scoped_cx!(self);
2023
2024         // Watch out for region highlights.
2025         let highlight = self.region_highlight_mode;
2026         if let Some(n) = highlight.region_highlighted(region) {
2027             p!(write("'{}", n));
2028             return Ok(self);
2029         }
2030
2031         if self.should_print_verbose() {
2032             p!(write("{:?}", region));
2033             return Ok(self);
2034         }
2035
2036         let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2037
2038         // These printouts are concise.  They do not contain all the information
2039         // the user might want to diagnose an error, but there is basically no way
2040         // to fit that into a short string.  Hence the recommendation to use
2041         // `explain_region()` or `note_and_explain_region()`.
2042         match *region {
2043             ty::ReEarlyBound(ref data) => {
2044                 if data.name != kw::Empty {
2045                     p!(write("{}", data.name));
2046                     return Ok(self);
2047                 }
2048             }
2049             ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
2050             | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
2051             | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
2052                 if let ty::BrNamed(_, name) = br {
2053                     if name != kw::Empty && name != kw::UnderscoreLifetime {
2054                         p!(write("{}", name));
2055                         return Ok(self);
2056                     }
2057                 }
2058
2059                 if let Some((region, counter)) = highlight.highlight_bound_region {
2060                     if br == region {
2061                         p!(write("'{}", counter));
2062                         return Ok(self);
2063                     }
2064                 }
2065             }
2066             ty::ReVar(region_vid) if identify_regions => {
2067                 p!(write("{:?}", region_vid));
2068                 return Ok(self);
2069             }
2070             ty::ReVar(_) => {}
2071             ty::ReErased => {}
2072             ty::ReStatic => {
2073                 p!("'static");
2074                 return Ok(self);
2075             }
2076         }
2077
2078         p!("'_");
2079
2080         Ok(self)
2081     }
2082 }
2083
2084 /// Folds through bound vars and placeholders, naming them
2085 struct RegionFolder<'a, 'tcx> {
2086     tcx: TyCtxt<'tcx>,
2087     current_index: ty::DebruijnIndex,
2088     region_map: BTreeMap<ty::BoundRegion, ty::Region<'tcx>>,
2089     name: &'a mut (
2090                 dyn FnMut(
2091         Option<ty::DebruijnIndex>, // Debruijn index of the folded late-bound region
2092         ty::DebruijnIndex,         // Index corresponding to binder level
2093         ty::BoundRegion,
2094     ) -> ty::Region<'tcx>
2095                     + 'a
2096             ),
2097 }
2098
2099 impl<'a, 'tcx> ty::TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
2100     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2101         self.tcx
2102     }
2103
2104     fn fold_binder<T: TypeFoldable<'tcx>>(
2105         &mut self,
2106         t: ty::Binder<'tcx, T>,
2107     ) -> ty::Binder<'tcx, T> {
2108         self.current_index.shift_in(1);
2109         let t = t.super_fold_with(self);
2110         self.current_index.shift_out(1);
2111         t
2112     }
2113
2114     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2115         match *t.kind() {
2116             _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2117                 return t.super_fold_with(self);
2118             }
2119             _ => {}
2120         }
2121         t
2122     }
2123
2124     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2125         let name = &mut self.name;
2126         let region = match *r {
2127             ty::ReLateBound(db, br) if db >= self.current_index => {
2128                 *self.region_map.entry(br).or_insert_with(|| name(Some(db), self.current_index, br))
2129             }
2130             ty::RePlaceholder(ty::PlaceholderRegion { name: kind, .. }) => {
2131                 // If this is an anonymous placeholder, don't rename. Otherwise, in some
2132                 // async fns, we get a `for<'r> Send` bound
2133                 match kind {
2134                     ty::BrAnon(..) | ty::BrEnv => r,
2135                     _ => {
2136                         // Index doesn't matter, since this is just for naming and these never get bound
2137                         let br = ty::BoundRegion { var: ty::BoundVar::from_u32(0), kind };
2138                         *self
2139                             .region_map
2140                             .entry(br)
2141                             .or_insert_with(|| name(None, self.current_index, br))
2142                     }
2143                 }
2144             }
2145             _ => return r,
2146         };
2147         if let ty::ReLateBound(debruijn1, br) = *region {
2148             assert_eq!(debruijn1, ty::INNERMOST);
2149             self.tcx.mk_region(ty::ReLateBound(self.current_index, br))
2150         } else {
2151             region
2152         }
2153     }
2154 }
2155
2156 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
2157 // `region_index` and `used_region_names`.
2158 impl<'tcx> FmtPrinter<'_, 'tcx> {
2159     pub fn name_all_regions<T>(
2160         mut self,
2161         value: &ty::Binder<'tcx, T>,
2162     ) -> Result<(Self, T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
2163     where
2164         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2165     {
2166         fn name_by_region_index(
2167             index: usize,
2168             available_names: &mut Vec<Symbol>,
2169             num_available: usize,
2170         ) -> Symbol {
2171             if let Some(name) = available_names.pop() {
2172                 name
2173             } else {
2174                 Symbol::intern(&format!("'z{}", index - num_available))
2175             }
2176         }
2177
2178         debug!("name_all_regions");
2179
2180         // Replace any anonymous late-bound regions with named
2181         // variants, using new unique identifiers, so that we can
2182         // clearly differentiate between named and unnamed regions in
2183         // the output. We'll probably want to tweak this over time to
2184         // decide just how much information to give.
2185         if self.binder_depth == 0 {
2186             self.prepare_region_info(value);
2187         }
2188
2189         debug!("self.used_region_names: {:?}", &self.used_region_names);
2190
2191         let mut empty = true;
2192         let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
2193             let w = if empty {
2194                 empty = false;
2195                 start
2196             } else {
2197                 cont
2198             };
2199             let _ = write!(cx, "{}", w);
2200         };
2201         let do_continue = |cx: &mut Self, cont: Symbol| {
2202             let _ = write!(cx, "{}", cont);
2203         };
2204
2205         define_scoped_cx!(self);
2206
2207         let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&format!("'{s}")));
2208
2209         let mut available_names = possible_names
2210             .filter(|name| !self.used_region_names.contains(&name))
2211             .collect::<Vec<_>>();
2212         debug!(?available_names);
2213         let num_available = available_names.len();
2214
2215         let mut region_index = self.region_index;
2216         let mut next_name = |this: &Self| {
2217             let mut name;
2218
2219             loop {
2220                 name = name_by_region_index(region_index, &mut available_names, num_available);
2221                 region_index += 1;
2222
2223                 if !this.used_region_names.contains(&name) {
2224                     break;
2225                 }
2226             }
2227
2228             name
2229         };
2230
2231         // If we want to print verbosely, then print *all* binders, even if they
2232         // aren't named. Eventually, we might just want this as the default, but
2233         // this is not *quite* right and changes the ordering of some output
2234         // anyways.
2235         let (new_value, map) = if self.should_print_verbose() {
2236             for var in value.bound_vars().iter() {
2237                 start_or_continue(&mut self, "for<", ", ");
2238                 write!(self, "{:?}", var)?;
2239             }
2240             start_or_continue(&mut self, "", "> ");
2241             (value.clone().skip_binder(), BTreeMap::default())
2242         } else {
2243             let tcx = self.tcx;
2244
2245             // Closure used in `RegionFolder` to create names for anonymous late-bound
2246             // regions. We use two `DebruijnIndex`es (one for the currently folded
2247             // late-bound region and the other for the binder level) to determine
2248             // whether a name has already been created for the currently folded region,
2249             // see issue #102392.
2250             let mut name = |lifetime_idx: Option<ty::DebruijnIndex>,
2251                             binder_level_idx: ty::DebruijnIndex,
2252                             br: ty::BoundRegion| {
2253                 let (name, kind) = match br.kind {
2254                     ty::BrAnon(..) | ty::BrEnv => {
2255                         let name = next_name(&self);
2256
2257                         if let Some(lt_idx) = lifetime_idx {
2258                             if lt_idx > binder_level_idx {
2259                                 let kind = ty::BrNamed(CRATE_DEF_ID.to_def_id(), name);
2260                                 return tcx.mk_region(ty::ReLateBound(
2261                                     ty::INNERMOST,
2262                                     ty::BoundRegion { var: br.var, kind },
2263                                 ));
2264                             }
2265                         }
2266
2267                         (name, ty::BrNamed(CRATE_DEF_ID.to_def_id(), name))
2268                     }
2269                     ty::BrNamed(def_id, kw::UnderscoreLifetime) => {
2270                         let name = next_name(&self);
2271
2272                         if let Some(lt_idx) = lifetime_idx {
2273                             if lt_idx > binder_level_idx {
2274                                 let kind = ty::BrNamed(def_id, name);
2275                                 return tcx.mk_region(ty::ReLateBound(
2276                                     ty::INNERMOST,
2277                                     ty::BoundRegion { var: br.var, kind },
2278                                 ));
2279                             }
2280                         }
2281
2282                         (name, ty::BrNamed(def_id, name))
2283                     }
2284                     ty::BrNamed(_, name) => {
2285                         if let Some(lt_idx) = lifetime_idx {
2286                             if lt_idx > binder_level_idx {
2287                                 let kind = br.kind;
2288                                 return tcx.mk_region(ty::ReLateBound(
2289                                     ty::INNERMOST,
2290                                     ty::BoundRegion { var: br.var, kind },
2291                                 ));
2292                             }
2293                         }
2294
2295                         (name, br.kind)
2296                     }
2297                 };
2298
2299                 start_or_continue(&mut self, "for<", ", ");
2300                 do_continue(&mut self, name);
2301                 tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BoundRegion { var: br.var, kind }))
2302             };
2303             let mut folder = RegionFolder {
2304                 tcx,
2305                 current_index: ty::INNERMOST,
2306                 name: &mut name,
2307                 region_map: BTreeMap::new(),
2308             };
2309             let new_value = value.clone().skip_binder().fold_with(&mut folder);
2310             let region_map = folder.region_map;
2311             start_or_continue(&mut self, "", "> ");
2312             (new_value, region_map)
2313         };
2314
2315         self.binder_depth += 1;
2316         self.region_index = region_index;
2317         Ok((self, new_value, map))
2318     }
2319
2320     pub fn pretty_in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, fmt::Error>
2321     where
2322         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2323     {
2324         let old_region_index = self.region_index;
2325         let (new, new_value, _) = self.name_all_regions(value)?;
2326         let mut inner = new_value.print(new)?;
2327         inner.region_index = old_region_index;
2328         inner.binder_depth -= 1;
2329         Ok(inner)
2330     }
2331
2332     pub fn pretty_wrap_binder<T, C: FnOnce(&T, Self) -> Result<Self, fmt::Error>>(
2333         self,
2334         value: &ty::Binder<'tcx, T>,
2335         f: C,
2336     ) -> Result<Self, fmt::Error>
2337     where
2338         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2339     {
2340         let old_region_index = self.region_index;
2341         let (new, new_value, _) = self.name_all_regions(value)?;
2342         let mut inner = f(&new_value, new)?;
2343         inner.region_index = old_region_index;
2344         inner.binder_depth -= 1;
2345         Ok(inner)
2346     }
2347
2348     fn prepare_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2349     where
2350         T: TypeVisitable<'tcx>,
2351     {
2352         struct RegionNameCollector<'tcx> {
2353             used_region_names: FxHashSet<Symbol>,
2354             type_collector: SsoHashSet<Ty<'tcx>>,
2355         }
2356
2357         impl<'tcx> RegionNameCollector<'tcx> {
2358             fn new() -> Self {
2359                 RegionNameCollector {
2360                     used_region_names: Default::default(),
2361                     type_collector: SsoHashSet::new(),
2362                 }
2363             }
2364         }
2365
2366         impl<'tcx> ty::visit::TypeVisitor<'tcx> for RegionNameCollector<'tcx> {
2367             type BreakTy = ();
2368
2369             fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
2370                 trace!("address: {:p}", r.0.0);
2371
2372                 // Collect all named lifetimes. These allow us to prevent duplication
2373                 // of already existing lifetime names when introducing names for
2374                 // anonymous late-bound regions.
2375                 if let Some(name) = r.get_name() {
2376                     self.used_region_names.insert(name);
2377                 }
2378
2379                 r.super_visit_with(self)
2380             }
2381
2382             // We collect types in order to prevent really large types from compiling for
2383             // a really long time. See issue #83150 for why this is necessary.
2384             fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
2385                 let not_previously_inserted = self.type_collector.insert(ty);
2386                 if not_previously_inserted {
2387                     ty.super_visit_with(self)
2388                 } else {
2389                     ControlFlow::CONTINUE
2390                 }
2391             }
2392         }
2393
2394         let mut collector = RegionNameCollector::new();
2395         value.visit_with(&mut collector);
2396         self.used_region_names = collector.used_region_names;
2397         self.region_index = 0;
2398     }
2399 }
2400
2401 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2402 where
2403     T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
2404 {
2405     type Output = P;
2406     type Error = P::Error;
2407
2408     fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
2409         cx.in_binder(self)
2410     }
2411 }
2412
2413 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
2414 where
2415     T: Print<'tcx, P, Output = P, Error = P::Error>,
2416     U: Print<'tcx, P, Output = P, Error = P::Error>,
2417 {
2418     type Output = P;
2419     type Error = P::Error;
2420     fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
2421         define_scoped_cx!(cx);
2422         p!(print(self.0), ": ", print(self.1));
2423         Ok(cx)
2424     }
2425 }
2426
2427 macro_rules! forward_display_to_print {
2428     ($($ty:ty),+) => {
2429         // Some of the $ty arguments may not actually use 'tcx
2430         $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty {
2431             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2432                 ty::tls::with(|tcx| {
2433                     let cx = tcx.lift(*self)
2434                         .expect("could not lift for printing")
2435                         .print(FmtPrinter::new(tcx, Namespace::TypeNS))?;
2436                     f.write_str(&cx.into_buffer())?;
2437                     Ok(())
2438                 })
2439             }
2440         })+
2441     };
2442 }
2443
2444 macro_rules! define_print_and_forward_display {
2445     (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
2446         $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
2447             type Output = P;
2448             type Error = fmt::Error;
2449             fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
2450                 #[allow(unused_mut)]
2451                 let mut $cx = $cx;
2452                 define_scoped_cx!($cx);
2453                 let _: () = $print;
2454                 #[allow(unreachable_code)]
2455                 Ok($cx)
2456             }
2457         })+
2458
2459         forward_display_to_print!($($ty),+);
2460     };
2461 }
2462
2463 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2464 /// the trait path. That is, it will print `Trait<U>` instead of
2465 /// `<T as Trait<U>>`.
2466 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2467 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2468
2469 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
2470     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2471         fmt::Display::fmt(self, f)
2472     }
2473 }
2474
2475 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2476 /// the trait name. That is, it will print `Trait` instead of
2477 /// `<T as Trait<U>>`.
2478 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2479 pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
2480
2481 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
2482     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2483         fmt::Display::fmt(self, f)
2484     }
2485 }
2486
2487 impl<'tcx> ty::TraitRef<'tcx> {
2488     pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2489         TraitRefPrintOnlyTraitPath(self)
2490     }
2491
2492     pub fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
2493         TraitRefPrintOnlyTraitName(self)
2494     }
2495 }
2496
2497 impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
2498     pub fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
2499         self.map_bound(|tr| tr.print_only_trait_path())
2500     }
2501 }
2502
2503 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2504 pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
2505
2506 impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
2507     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2508         fmt::Display::fmt(self, f)
2509     }
2510 }
2511
2512 impl<'tcx> ty::TraitPredicate<'tcx> {
2513     pub fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
2514         TraitPredPrintModifiersAndPath(self)
2515     }
2516 }
2517
2518 impl<'tcx> ty::PolyTraitPredicate<'tcx> {
2519     pub fn print_modifiers_and_trait_path(
2520         self,
2521     ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
2522         self.map_bound(TraitPredPrintModifiersAndPath)
2523     }
2524 }
2525
2526 #[derive(Debug, Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2527 pub struct PrintClosureAsImpl<'tcx> {
2528     pub closure: ty::ClosureSubsts<'tcx>,
2529 }
2530
2531 forward_display_to_print! {
2532     ty::Region<'tcx>,
2533     Ty<'tcx>,
2534     &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2535     ty::Const<'tcx>,
2536
2537     // HACK(eddyb) these are exhaustive instead of generic,
2538     // because `for<'tcx>` isn't possible yet.
2539     ty::PolyExistentialPredicate<'tcx>,
2540     ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2541     ty::Binder<'tcx, ty::ExistentialTraitRef<'tcx>>,
2542     ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>>,
2543     ty::Binder<'tcx, TraitRefPrintOnlyTraitName<'tcx>>,
2544     ty::Binder<'tcx, ty::FnSig<'tcx>>,
2545     ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2546     ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>>,
2547     ty::Binder<'tcx, ty::SubtypePredicate<'tcx>>,
2548     ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
2549     ty::Binder<'tcx, ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
2550     ty::Binder<'tcx, ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
2551
2552     ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
2553     ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
2554 }
2555
2556 define_print_and_forward_display! {
2557     (self, cx):
2558
2559     &'tcx ty::List<Ty<'tcx>> {
2560         p!("{{", comma_sep(self.iter()), "}}")
2561     }
2562
2563     ty::TypeAndMut<'tcx> {
2564         p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
2565     }
2566
2567     ty::ExistentialTraitRef<'tcx> {
2568         // Use a type that can't appear in defaults of type parameters.
2569         let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
2570         let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
2571         p!(print(trait_ref.print_only_trait_path()))
2572     }
2573
2574     ty::ExistentialProjection<'tcx> {
2575         let name = cx.tcx().associated_item(self.item_def_id).name;
2576         p!(write("{} = ", name), print(self.term))
2577     }
2578
2579     ty::ExistentialPredicate<'tcx> {
2580         match *self {
2581             ty::ExistentialPredicate::Trait(x) => p!(print(x)),
2582             ty::ExistentialPredicate::Projection(x) => p!(print(x)),
2583             ty::ExistentialPredicate::AutoTrait(def_id) => {
2584                 p!(print_def_path(def_id, &[]));
2585             }
2586         }
2587     }
2588
2589     ty::FnSig<'tcx> {
2590         p!(write("{}", self.unsafety.prefix_str()));
2591
2592         if self.abi != Abi::Rust {
2593             p!(write("extern {} ", self.abi));
2594         }
2595
2596         p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2597     }
2598
2599     ty::TraitRef<'tcx> {
2600         p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2601     }
2602
2603     TraitRefPrintOnlyTraitPath<'tcx> {
2604         p!(print_def_path(self.0.def_id, self.0.substs));
2605     }
2606
2607     TraitRefPrintOnlyTraitName<'tcx> {
2608         p!(print_def_path(self.0.def_id, &[]));
2609     }
2610
2611     TraitPredPrintModifiersAndPath<'tcx> {
2612         if let ty::BoundConstness::ConstIfConst = self.0.constness {
2613             p!("~const ")
2614         }
2615
2616         if let ty::ImplPolarity::Negative = self.0.polarity {
2617             p!("!")
2618         }
2619
2620         p!(print(self.0.trait_ref.print_only_trait_path()));
2621     }
2622
2623     PrintClosureAsImpl<'tcx> {
2624         p!(pretty_closure_as_impl(self.closure))
2625     }
2626
2627     ty::ParamTy {
2628         p!(write("{}", self.name))
2629     }
2630
2631     ty::ParamConst {
2632         p!(write("{}", self.name))
2633     }
2634
2635     ty::SubtypePredicate<'tcx> {
2636         p!(print(self.a), " <: ", print(self.b))
2637     }
2638
2639     ty::CoercePredicate<'tcx> {
2640         p!(print(self.a), " -> ", print(self.b))
2641     }
2642
2643     ty::TraitPredicate<'tcx> {
2644         p!(print(self.trait_ref.self_ty()), ": ");
2645         if let ty::BoundConstness::ConstIfConst = self.constness && cx.tcx().features().const_trait_impl {
2646             p!("~const ");
2647         }
2648         p!(print(self.trait_ref.print_only_trait_path()))
2649     }
2650
2651     ty::ProjectionPredicate<'tcx> {
2652         p!(print(self.projection_ty), " == ", print(self.term))
2653     }
2654
2655     ty::Term<'tcx> {
2656       match self.unpack() {
2657         ty::TermKind::Ty(ty) => p!(print(ty)),
2658         ty::TermKind::Const(c) => p!(print(c)),
2659       }
2660     }
2661
2662     ty::ProjectionTy<'tcx> {
2663         p!(print_def_path(self.item_def_id, self.substs));
2664     }
2665
2666     ty::ClosureKind {
2667         match *self {
2668             ty::ClosureKind::Fn => p!("Fn"),
2669             ty::ClosureKind::FnMut => p!("FnMut"),
2670             ty::ClosureKind::FnOnce => p!("FnOnce"),
2671         }
2672     }
2673
2674     ty::Predicate<'tcx> {
2675         let binder = self.kind();
2676         p!(print(binder))
2677     }
2678
2679     ty::PredicateKind<'tcx> {
2680         match *self {
2681             ty::PredicateKind::Trait(ref data) => {
2682                 p!(print(data))
2683             }
2684             ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
2685             ty::PredicateKind::Coerce(predicate) => p!(print(predicate)),
2686             ty::PredicateKind::RegionOutlives(predicate) => p!(print(predicate)),
2687             ty::PredicateKind::TypeOutlives(predicate) => p!(print(predicate)),
2688             ty::PredicateKind::Projection(predicate) => p!(print(predicate)),
2689             ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"),
2690             ty::PredicateKind::ObjectSafe(trait_def_id) => {
2691                 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
2692             }
2693             ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
2694                 p!("the closure `",
2695                 print_value_path(closure_def_id, &[]),
2696                 write("` implements the trait `{}`", kind))
2697             }
2698             ty::PredicateKind::ConstEvaluatable(ct) => {
2699                 p!("the constant `", print(ct), "` can be evaluated")
2700             }
2701             ty::PredicateKind::ConstEquate(c1, c2) => {
2702                 p!("the constant `", print(c1), "` equals `", print(c2), "`")
2703             }
2704             ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
2705                 p!("the type `", print(ty), "` is found in the environment")
2706             }
2707             ty::PredicateKind::Ambiguous => p!("ambiguous"),
2708         }
2709     }
2710
2711     GenericArg<'tcx> {
2712         match self.unpack() {
2713             GenericArgKind::Lifetime(lt) => p!(print(lt)),
2714             GenericArgKind::Type(ty) => p!(print(ty)),
2715             GenericArgKind::Const(ct) => p!(print(ct)),
2716         }
2717     }
2718 }
2719
2720 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2721     // Iterate all local crate items no matter where they are defined.
2722     let hir = tcx.hir();
2723     for id in hir.items() {
2724         if matches!(tcx.def_kind(id.owner_id), DefKind::Use) {
2725             continue;
2726         }
2727
2728         let item = hir.item(id);
2729         if item.ident.name == kw::Empty {
2730             continue;
2731         }
2732
2733         let def_id = item.owner_id.to_def_id();
2734         let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2735         collect_fn(&item.ident, ns, def_id);
2736     }
2737
2738     // Now take care of extern crate items.
2739     let queue = &mut Vec::new();
2740     let mut seen_defs: DefIdSet = Default::default();
2741
2742     for &cnum in tcx.crates(()).iter() {
2743         let def_id = cnum.as_def_id();
2744
2745         // Ignore crates that are not direct dependencies.
2746         match tcx.extern_crate(def_id) {
2747             None => continue,
2748             Some(extern_crate) => {
2749                 if !extern_crate.is_direct() {
2750                     continue;
2751                 }
2752             }
2753         }
2754
2755         queue.push(def_id);
2756     }
2757
2758     // Iterate external crate defs but be mindful about visibility
2759     while let Some(def) = queue.pop() {
2760         for child in tcx.module_children(def).iter() {
2761             if !child.vis.is_public() {
2762                 continue;
2763             }
2764
2765             match child.res {
2766                 def::Res::Def(DefKind::AssocTy, _) => {}
2767                 def::Res::Def(DefKind::TyAlias, _) => {}
2768                 def::Res::Def(defkind, def_id) => {
2769                     if let Some(ns) = defkind.ns() {
2770                         collect_fn(&child.ident, ns, def_id);
2771                     }
2772
2773                     if matches!(defkind, DefKind::Mod | DefKind::Enum | DefKind::Trait)
2774                         && seen_defs.insert(def_id)
2775                     {
2776                         queue.push(def_id);
2777                     }
2778                 }
2779                 _ => {}
2780             }
2781         }
2782     }
2783 }
2784
2785 /// The purpose of this function is to collect public symbols names that are unique across all
2786 /// crates in the build. Later, when printing about types we can use those names instead of the
2787 /// full exported path to them.
2788 ///
2789 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2790 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2791 /// path and print only the name.
2792 ///
2793 /// This has wide implications on error messages with types, for example, shortening
2794 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2795 ///
2796 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2797 fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> FxHashMap<DefId, Symbol> {
2798     let mut map: FxHashMap<DefId, Symbol> = FxHashMap::default();
2799
2800     if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2801         // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2802         // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2803         tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2804     }
2805
2806     let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2807         &mut FxHashMap::default();
2808
2809     for symbol_set in tcx.resolutions(()).glob_map.values() {
2810         for symbol in symbol_set {
2811             unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2812             unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2813             unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2814         }
2815     }
2816
2817     for_each_def(tcx, |ident, ns, def_id| {
2818         use std::collections::hash_map::Entry::{Occupied, Vacant};
2819
2820         match unique_symbols_rev.entry((ns, ident.name)) {
2821             Occupied(mut v) => match v.get() {
2822                 None => {}
2823                 Some(existing) => {
2824                     if *existing != def_id {
2825                         v.insert(None);
2826                     }
2827                 }
2828             },
2829             Vacant(v) => {
2830                 v.insert(Some(def_id));
2831             }
2832         }
2833     });
2834
2835     for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2836         use std::collections::hash_map::Entry::{Occupied, Vacant};
2837
2838         if let Some(def_id) = opt_def_id {
2839             match map.entry(def_id) {
2840                 Occupied(mut v) => {
2841                     // A single DefId can be known under multiple names (e.g.,
2842                     // with a `pub use ... as ...;`). We need to ensure that the
2843                     // name placed in this map is chosen deterministically, so
2844                     // if we find multiple names (`symbol`) resolving to the
2845                     // same `def_id`, we prefer the lexicographically smallest
2846                     // name.
2847                     //
2848                     // Any stable ordering would be fine here though.
2849                     if *v.get() != symbol {
2850                         if v.get().as_str() > symbol.as_str() {
2851                             v.insert(symbol);
2852                         }
2853                     }
2854                 }
2855                 Vacant(v) => {
2856                     v.insert(symbol);
2857                 }
2858             }
2859         }
2860     }
2861
2862     map
2863 }
2864
2865 pub fn provide(providers: &mut ty::query::Providers) {
2866     *providers = ty::query::Providers { trimmed_def_paths, ..*providers };
2867 }
2868
2869 #[derive(Default)]
2870 pub struct OpaqueFnEntry<'tcx> {
2871     // The trait ref is already stored as a key, so just track if we have it as a real predicate
2872     has_fn_once: bool,
2873     fn_mut_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2874     fn_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2875     return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,
2876 }