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