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