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