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