rustc_middle/ty/print/
pretty.rs

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