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