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