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