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