Skip to main content

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