Skip to main content

rustc_middle/ty/print/
pretty.rs

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