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