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