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