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