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