Skip to main content

rustc_middle/ty/print/
pretty.rs

1use std::cell::Cell;
2use std::fmt::{self, Write as _};
3use std::iter;
4use std::ops::{Deref, DerefMut};
5
6use rustc_abi::{ExternAbi, Size};
7use rustc_apfloat::Float;
8use rustc_apfloat::ieee::{Double, Half, Quad, Single};
9use rustc_data_structures::Limit;
10use rustc_data_structures::fx::{FxIndexMap, IndexEntry};
11use rustc_data_structures::unord::UnordMap;
12use rustc_hir as hir;
13use rustc_hir::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_session::cstore::{ExternCrate, ExternCrateSource};
19use rustc_span::{Ident, RemapPathScopeComponents, Symbol, kw, sym};
20use rustc_type_ir::{FieldInfo, Unnormalized, Upcast as _, elaborate};
21use smallvec::SmallVec;
22
23// `pretty` is a separate module only for organization.
24use super::*;
25use crate::mir::interpret::{AllocRange, GlobalAlloc, Pointer, Provenance, Scalar};
26use crate::query::{IntoQueryKey, Providers};
27use crate::ty::region::RegionExt;
28use crate::ty::{
29    ConstInt, Expr, GenericArgKind, ParamConst, ScalarInt, Term, TermKind, TraitPredicate,
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::PredicatePolarity::Positive => {
1064                                has_sized_bound = true;
1065                                continue;
1066                            }
1067                            ty::PredicatePolarity::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| TraitPredicate {
1089                        trait_ref: proj.projection_term.trait_ref(tcx),
1090                        polarity: ty::PredicatePolarity::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::TraitPredicate {
1155                        polarity: ty::PredicatePolarity::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::PredicatePolarity::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::PolyTraitPredicate<'tcx>,
1261        proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
1262        traits: &mut FxIndexMap<
1263            ty::PolyTraitPredicate<'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::PredicatePolarity::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.consts().next().is_none()
2309                                    && arg_args.types().next().is_none()
2310                                {
2311                                    // Single param type with no type or const parameters:
2312                                    // `Foo<Bar<'a>>`.
2313                                    true
2314                                } else {
2315                                    // Single param type with multiple type or const parameters:
2316                                    // `Foo<Bar<Baz, Qux>>`. We don't want to recurse into those,
2317                                    // we'll replace the whole thing with `...`.
2318                                    false
2319                                }
2320                            } else {
2321                                // Single type param that *isn't* a type with parameters, like a
2322                                // primitive: `Foo<i32>`.
2323                                true
2324                            }
2325                        } else {
2326                            // No type param: `Foo`.
2327                            true
2328                        }
2329                    }
2330                    && self.tcx.item_name(def.did()).as_str().len() < 7 =>
2331            {
2332                // Don't fully truncate types that have "short names" and at most one type or const
2333                // param. We do use the short path for them (only item name instead of full path).
2334                { let _guard = ForceTrimmedGuard::new(); self.pretty_print_type(ty) }with_forced_trimmed_paths!(self.pretty_print_type(ty))
2335            }
2336
2337            ty::Alias(_, alias)
2338                if self.should_truncate()
2339                    && let ty::AliasTyKind::Opaque { def_id } = alias.kind
2340                    && self.region_highlight_mode.keep_regions
2341                    && self
2342                        .tcx
2343                        .explicit_item_bounds(def_id)
2344                        .iter_instantiated_copied(self.tcx, alias.args)
2345                        .map(Unnormalized::skip_norm_wip)
2346                        .any(|(value, _)| value.has_bound_vars()) =>
2347            {
2348                // `<impl for<'a> Trait as Trait>`
2349                self.printed_type_count += 1;
2350                self.pretty_print_type(ty)
2351            }
2352
2353            ty::Adt(..)
2354            | ty::Foreign(_)
2355            | ty::Pat(..)
2356            | ty::RawPtr(..)
2357            | ty::Ref(..)
2358            | ty::FnDef(..)
2359            | ty::FnPtr(..)
2360            | ty::UnsafeBinder(..)
2361            | ty::Dynamic(..)
2362            | ty::CoroutineClosure(..)
2363            | ty::Coroutine(..)
2364            | ty::CoroutineWitness(..)
2365            | ty::Tuple(_)
2366            | ty::Alias(..)
2367            | ty::Bound(..)
2368            | ty::Placeholder(_)
2369            | ty::Error(_)
2370                if self.should_truncate() && !has_regions =>
2371            {
2372                // We only truncate types that we know are likely to be much longer than 3 chars.
2373                // There's no point in replacing `i32` or `!`.
2374                self.write_fmt(format_args!("_"))write!(self, "_")?;
2375                Ok(())
2376            }
2377            ty::Ref(..) if self.should_truncate() && has_regions => self.pretty_print_type(ty),
2378            ty::Closure(..) => self.pretty_print_type(ty),
2379            _ => {
2380                self.printed_type_count += 1;
2381                self.pretty_print_type(ty)
2382            }
2383        }
2384    }
2385
2386    fn print_dyn_existential(
2387        &mut self,
2388        predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2389    ) -> Result<(), PrintError> {
2390        self.pretty_print_dyn_existential(predicates)
2391    }
2392
2393    fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
2394        self.pretty_print_const(ct, false)
2395    }
2396
2397    fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
2398        self.empty_path = true;
2399        if cnum == LOCAL_CRATE && !with_resolve_crate_name() {
2400            if self.tcx.sess.at_least_rust_2018() {
2401                // We add the `crate::` keyword on Rust 2018, only when desired.
2402                if with_crate_prefix() {
2403                    self.write_fmt(format_args!("{0}", kw::Crate))write!(self, "{}", kw::Crate)?;
2404                    self.empty_path = false;
2405                }
2406            }
2407        } else {
2408            self.write_fmt(format_args!("{0}", self.tcx.crate_name(cnum)))write!(self, "{}", self.tcx.crate_name(cnum))?;
2409            self.empty_path = false;
2410        }
2411        Ok(())
2412    }
2413
2414    fn print_path_with_qualified(
2415        &mut self,
2416        self_ty: Ty<'tcx>,
2417        trait_ref: Option<ty::TraitRef<'tcx>>,
2418    ) -> Result<(), PrintError> {
2419        self.pretty_print_path_with_qualified(self_ty, trait_ref)?;
2420        self.empty_path = false;
2421        Ok(())
2422    }
2423
2424    fn print_path_with_impl(
2425        &mut self,
2426        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2427        self_ty: Ty<'tcx>,
2428        trait_ref: Option<ty::TraitRef<'tcx>>,
2429    ) -> Result<(), PrintError> {
2430        self.pretty_print_path_with_impl(
2431            |p| {
2432                print_prefix(p)?;
2433                if !p.empty_path {
2434                    p.write_fmt(format_args!("::"))write!(p, "::")?;
2435                }
2436
2437                Ok(())
2438            },
2439            self_ty,
2440            trait_ref,
2441        )?;
2442        self.empty_path = false;
2443        Ok(())
2444    }
2445
2446    fn print_path_with_simple(
2447        &mut self,
2448        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2449        disambiguated_data: &DisambiguatedDefPathData,
2450    ) -> Result<(), PrintError> {
2451        print_prefix(self)?;
2452
2453        // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
2454        if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
2455            return Ok(());
2456        }
2457
2458        let name = disambiguated_data.data.name();
2459        if !self.empty_path {
2460            self.write_fmt(format_args!("::"))write!(self, "::")?;
2461        }
2462
2463        if let DefPathDataName::Named(name) = name {
2464            if Ident::with_dummy_span(name).is_raw_guess() {
2465                self.write_fmt(format_args!("r#"))write!(self, "r#")?;
2466            }
2467        }
2468
2469        let verbose = self.should_print_verbose();
2470        self.write_fmt(format_args!("{0}", disambiguated_data.as_sym(verbose)))write!(self, "{}", disambiguated_data.as_sym(verbose))?;
2471
2472        self.empty_path = false;
2473
2474        Ok(())
2475    }
2476
2477    fn print_path_with_generic_args(
2478        &mut self,
2479        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2480        args: &[GenericArg<'tcx>],
2481    ) -> Result<(), PrintError> {
2482        print_prefix(self)?;
2483
2484        if !args.is_empty() {
2485            if self.in_value {
2486                self.write_fmt(format_args!("::"))write!(self, "::")?;
2487            }
2488            self.generic_delimiters(|p| p.comma_sep(args.iter().copied()))
2489        } else {
2490            Ok(())
2491        }
2492    }
2493}
2494
2495impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
2496    fn ty_infer_name(&self, id: ty::TyVid) -> Option<Symbol> {
2497        self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
2498    }
2499
2500    fn reset_type_limit(&mut self) {
2501        self.printed_type_count = 0;
2502    }
2503
2504    fn const_infer_name(&self, id: ty::ConstVid) -> Option<Symbol> {
2505        self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
2506    }
2507
2508    fn pretty_print_value_path(
2509        &mut self,
2510        def_id: DefId,
2511        args: &'tcx [GenericArg<'tcx>],
2512    ) -> Result<(), PrintError> {
2513        let was_in_value = std::mem::replace(&mut self.in_value, true);
2514        self.print_def_path(def_id, args)?;
2515        self.in_value = was_in_value;
2516
2517        Ok(())
2518    }
2519
2520    fn pretty_print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError>
2521    where
2522        T: Print<Self> + TypeFoldable<TyCtxt<'tcx>>,
2523    {
2524        self.wrap_binder(value, WrapBinderMode::ForAll, |new_value, this| new_value.print(this))
2525    }
2526
2527    fn wrap_binder<T, C: FnOnce(&T, &mut Self) -> Result<(), PrintError>>(
2528        &mut self,
2529        value: &ty::Binder<'tcx, T>,
2530        mode: WrapBinderMode,
2531        f: C,
2532    ) -> Result<(), PrintError>
2533    where
2534        T: TypeFoldable<TyCtxt<'tcx>>,
2535    {
2536        let old_region_index = self.region_index;
2537        let (new_value, _) = self.name_all_regions(value, mode)?;
2538        f(&new_value, self)?;
2539        self.region_index = old_region_index;
2540        self.binder_depth -= 1;
2541        Ok(())
2542    }
2543
2544    fn typed_value(
2545        &mut self,
2546        f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2547        t: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2548        conversion: &str,
2549    ) -> Result<(), PrintError> {
2550        self.write_str("{")?;
2551        f(self)?;
2552        self.write_str(conversion)?;
2553        let was_in_value = std::mem::replace(&mut self.in_value, false);
2554        t(self)?;
2555        self.in_value = was_in_value;
2556        self.write_str("}")?;
2557        Ok(())
2558    }
2559
2560    fn generic_delimiters(
2561        &mut self,
2562        f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2563    ) -> Result<(), PrintError> {
2564        self.write_fmt(format_args!("<"))write!(self, "<")?;
2565
2566        let was_in_value = std::mem::replace(&mut self.in_value, false);
2567        f(self)?;
2568        self.in_value = was_in_value;
2569
2570        self.write_fmt(format_args!(">"))write!(self, ">")?;
2571        Ok(())
2572    }
2573
2574    fn should_truncate(&mut self) -> bool {
2575        !self.type_length_limit.value_within_limit(self.printed_type_count)
2576    }
2577
2578    fn should_print_optional_region(&self, region: ty::Region<'tcx>) -> bool {
2579        let highlight = self.region_highlight_mode;
2580        if highlight.region_highlighted(region).is_some() {
2581            return true;
2582        }
2583
2584        if self.should_print_verbose() {
2585            return true;
2586        }
2587
2588        if with_forced_trimmed_paths() {
2589            return false;
2590        }
2591
2592        let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2593
2594        match region.kind() {
2595            ty::ReEarlyParam(ref data) => data.is_named(),
2596
2597            ty::ReLateParam(ty::LateParamRegion { kind, .. }) => kind.is_named(self.tcx),
2598            ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2599            | ty::RePlaceholder(ty::Placeholder {
2600                bound: ty::BoundRegion { kind: br, .. }, ..
2601            }) => {
2602                if br.is_named(self.tcx) {
2603                    return true;
2604                }
2605
2606                if let Some((region, _)) = highlight.highlight_bound_region {
2607                    if br == region {
2608                        return true;
2609                    }
2610                }
2611
2612                false
2613            }
2614
2615            ty::ReVar(_) if identify_regions => true,
2616
2617            ty::ReVar(_) | ty::ReErased | ty::ReError(_) => false,
2618
2619            ty::ReStatic => true,
2620        }
2621    }
2622
2623    fn pretty_print_const_pointer<Prov: Provenance>(
2624        &mut self,
2625        p: Pointer<Prov>,
2626        ty: Ty<'tcx>,
2627    ) -> Result<(), PrintError> {
2628        let print = |this: &mut Self| {
2629            if this.print_alloc_ids {
2630                this.write_fmt(format_args!("{0:?}", p))write!(this, "{p:?}")?;
2631            } else {
2632                this.write_fmt(format_args!("&_"))write!(this, "&_")?;
2633            }
2634            Ok(())
2635        };
2636        self.typed_value(print, |this| this.print_type(ty), ": ")
2637    }
2638}
2639
2640// HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
2641impl<'tcx> FmtPrinter<'_, 'tcx> {
2642    pub fn pretty_print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), fmt::Error> {
2643        // Watch out for region highlights.
2644        let highlight = self.region_highlight_mode;
2645        if let Some(n) = highlight.region_highlighted(region) {
2646            self.write_fmt(format_args!("\'{0}", n))write!(self, "'{n}")?;
2647            return Ok(());
2648        }
2649
2650        if self.should_print_verbose() {
2651            self.write_fmt(format_args!("{0:?}", region))write!(self, "{region:?}")?;
2652            return Ok(());
2653        }
2654
2655        let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2656
2657        // These printouts are concise. They do not contain all the information
2658        // the user might want to diagnose an error, but there is basically no way
2659        // to fit that into a short string. Hence the recommendation to use
2660        // `explain_region()` or `note_and_explain_region()`.
2661        match region.kind() {
2662            ty::ReEarlyParam(data) => {
2663                self.write_fmt(format_args!("{0}", data.name))write!(self, "{}", data.name)?;
2664                return Ok(());
2665            }
2666            ty::ReLateParam(ty::LateParamRegion { kind, .. }) => {
2667                if let Some(name) = kind.get_name(self.tcx) {
2668                    self.write_fmt(format_args!("{0}", name))write!(self, "{name}")?;
2669                    return Ok(());
2670                }
2671            }
2672            ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2673            | ty::RePlaceholder(ty::Placeholder {
2674                bound: ty::BoundRegion { kind: br, .. }, ..
2675            }) => {
2676                if let Some(name) = br.get_name(self.tcx) {
2677                    self.write_fmt(format_args!("{0}", name))write!(self, "{name}")?;
2678                    return Ok(());
2679                }
2680
2681                if let Some((region, counter)) = highlight.highlight_bound_region {
2682                    if br == region {
2683                        self.write_fmt(format_args!("\'{0}", counter))write!(self, "'{counter}")?;
2684                        return Ok(());
2685                    }
2686                }
2687            }
2688            ty::ReVar(region_vid) if identify_regions => {
2689                self.write_fmt(format_args!("{0:?}", region_vid))write!(self, "{region_vid:?}")?;
2690                return Ok(());
2691            }
2692            ty::ReVar(_) => {}
2693            ty::ReErased => {}
2694            ty::ReError(_) => {}
2695            ty::ReStatic => {
2696                self.write_fmt(format_args!("\'static"))write!(self, "'static")?;
2697                return Ok(());
2698            }
2699        }
2700
2701        self.write_fmt(format_args!("\'_"))write!(self, "'_")?;
2702
2703        Ok(())
2704    }
2705}
2706
2707/// Folds through bound vars and placeholders, naming them
2708struct RegionFolder<'a, 'tcx> {
2709    tcx: TyCtxt<'tcx>,
2710    current_index: ty::DebruijnIndex,
2711    region_map: UnordMap<ty::BoundRegion<'tcx>, ty::Region<'tcx>>,
2712    name: &'a mut (
2713                dyn FnMut(
2714        Option<ty::DebruijnIndex>, // Debruijn index of the folded late-bound region
2715        ty::DebruijnIndex,         // Index corresponding to binder level
2716        ty::BoundRegion<'tcx>,
2717    ) -> ty::Region<'tcx>
2718                    + 'a
2719            ),
2720}
2721
2722impl<'a, 'tcx> ty::TypeFolder<TyCtxt<'tcx>> for RegionFolder<'a, 'tcx> {
2723    fn cx(&self) -> TyCtxt<'tcx> {
2724        self.tcx
2725    }
2726
2727    fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>(
2728        &mut self,
2729        t: ty::Binder<'tcx, T>,
2730    ) -> ty::Binder<'tcx, T> {
2731        self.current_index.shift_in(1);
2732        let t = t.super_fold_with(self);
2733        self.current_index.shift_out(1);
2734        t
2735    }
2736
2737    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2738        match *t.kind() {
2739            _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2740                return t.super_fold_with(self);
2741            }
2742            _ => {}
2743        }
2744        t
2745    }
2746
2747    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2748        let name = &mut self.name;
2749        let region = match r.kind() {
2750            ty::ReBound(ty::BoundVarIndexKind::Bound(db), br) if db >= self.current_index => {
2751                *self.region_map.entry(br).or_insert_with(|| name(Some(db), self.current_index, br))
2752            }
2753            ty::RePlaceholder(ty::PlaceholderRegion {
2754                bound: ty::BoundRegion { kind, .. },
2755                ..
2756            }) => {
2757                // If this is an anonymous placeholder, don't rename. Otherwise, in some
2758                // async fns, we get a `for<'r> Send` bound
2759                match kind {
2760                    ty::BoundRegionKind::Anon | ty::BoundRegionKind::ClosureEnv => r,
2761                    _ => {
2762                        // Index doesn't matter, since this is just for naming and these never get bound
2763                        let br = ty::BoundRegion { var: ty::BoundVar::ZERO, kind };
2764                        *self
2765                            .region_map
2766                            .entry(br)
2767                            .or_insert_with(|| name(None, self.current_index, br))
2768                    }
2769                }
2770            }
2771            _ => return r,
2772        };
2773        if let ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn1), br) = region.kind() {
2774            {
    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);
2775            ty::Region::new_bound(self.tcx, self.current_index, br)
2776        } else {
2777            region
2778        }
2779    }
2780}
2781
2782// HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
2783// `region_index` and `used_region_names`.
2784impl<'tcx> FmtPrinter<'_, 'tcx> {
2785    pub fn name_all_regions<T>(
2786        &mut self,
2787        value: &ty::Binder<'tcx, T>,
2788        mode: WrapBinderMode,
2789    ) -> Result<(T, UnordMap<ty::BoundRegion<'tcx>, ty::Region<'tcx>>), fmt::Error>
2790    where
2791        T: TypeFoldable<TyCtxt<'tcx>>,
2792    {
2793        fn name_by_region_index(
2794            index: usize,
2795            available_names: &mut Vec<Symbol>,
2796            num_available: usize,
2797        ) -> Symbol {
2798            if let Some(name) = available_names.pop() {
2799                name
2800            } else {
2801                Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'z{0}", index - num_available))
    })format!("'z{}", index - num_available))
2802            }
2803        }
2804
2805        {
    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:2805",
                        "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(2805u32),
                        ::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");
2806
2807        // Replace any anonymous late-bound regions with named
2808        // variants, using new unique identifiers, so that we can
2809        // clearly differentiate between named and unnamed regions in
2810        // the output. We'll probably want to tweak this over time to
2811        // decide just how much information to give.
2812        if self.binder_depth == 0 {
2813            self.prepare_region_info(value);
2814        }
2815
2816        {
    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:2816",
                        "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(2816u32),
                        ::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);
2817
2818        let mut empty = true;
2819        let mut start_or_continue = |p: &mut Self, start: &str, cont: &str| {
2820            let w = if empty {
2821                empty = false;
2822                start
2823            } else {
2824                cont
2825            };
2826            let _ = p.write_fmt(format_args!("{0}", w))write!(p, "{w}");
2827        };
2828        let do_continue = |p: &mut Self, cont: Symbol| {
2829            let _ = p.write_fmt(format_args!("{0}", cont))write!(p, "{cont}");
2830        };
2831
2832        let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", s))
    })format!("'{s}")));
2833
2834        let mut available_names = possible_names
2835            .filter(|name| !self.used_region_names.contains(name))
2836            .collect::<Vec<_>>();
2837        {
    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:2837",
                        "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(2837u32),
                        ::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);
2838        let num_available = available_names.len();
2839
2840        let mut region_index = self.region_index;
2841        let mut next_name = |this: &Self| {
2842            let mut name;
2843
2844            loop {
2845                name = name_by_region_index(region_index, &mut available_names, num_available);
2846                region_index += 1;
2847
2848                if !this.used_region_names.contains(&name) {
2849                    break;
2850                }
2851            }
2852
2853            name
2854        };
2855
2856        // If we want to print verbosely, then print *all* binders, even if they
2857        // aren't named. Eventually, we might just want this as the default, but
2858        // this is not *quite* right and changes the ordering of some output
2859        // anyways.
2860        let (new_value, map) = if self.should_print_verbose() {
2861            for var in value.bound_vars().iter() {
2862                start_or_continue(self, mode.start_str(), ", ");
2863                self.write_fmt(format_args!("{0:?}", var))write!(self, "{var:?}")?;
2864            }
2865            // Unconditionally render `unsafe<>`.
2866            if value.bound_vars().is_empty() && mode == WrapBinderMode::Unsafe {
2867                start_or_continue(self, mode.start_str(), "");
2868            }
2869            start_or_continue(self, "", "> ");
2870            (value.clone().skip_binder(), UnordMap::default())
2871        } else {
2872            let tcx = self.tcx;
2873
2874            let trim_path = with_forced_trimmed_paths();
2875            // Closure used in `RegionFolder` to create names for anonymous late-bound
2876            // regions. We use two `DebruijnIndex`es (one for the currently folded
2877            // late-bound region and the other for the binder level) to determine
2878            // whether a name has already been created for the currently folded region,
2879            // see issue #102392.
2880            let mut name = |lifetime_idx: Option<ty::DebruijnIndex>,
2881                            binder_level_idx: ty::DebruijnIndex,
2882                            br: ty::BoundRegion<'tcx>| {
2883                let (name, kind) = if let Some(name) = br.kind.get_name(tcx) {
2884                    (name, br.kind)
2885                } else {
2886                    let name = next_name(self);
2887                    (name, ty::BoundRegionKind::NamedForPrinting(name))
2888                };
2889
2890                if let Some(lt_idx) = lifetime_idx {
2891                    if lt_idx > binder_level_idx {
2892                        return ty::Region::new_bound(
2893                            tcx,
2894                            ty::INNERMOST,
2895                            ty::BoundRegion { var: br.var, kind },
2896                        );
2897                    }
2898                }
2899
2900                // Unconditionally render `unsafe<>`.
2901                if !trim_path || mode == WrapBinderMode::Unsafe {
2902                    start_or_continue(self, mode.start_str(), ", ");
2903                    do_continue(self, name);
2904                }
2905                ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { var: br.var, kind })
2906            };
2907            let mut folder = RegionFolder {
2908                tcx,
2909                current_index: ty::INNERMOST,
2910                name: &mut name,
2911                region_map: UnordMap::default(),
2912            };
2913            let new_value = value.clone().skip_binder().fold_with(&mut folder);
2914            let region_map = folder.region_map;
2915
2916            if mode == WrapBinderMode::Unsafe && region_map.is_empty() {
2917                start_or_continue(self, mode.start_str(), "");
2918            }
2919            start_or_continue(self, "", "> ");
2920
2921            (new_value, region_map)
2922        };
2923
2924        self.binder_depth += 1;
2925        self.region_index = region_index;
2926        Ok((new_value, map))
2927    }
2928
2929    fn prepare_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2930    where
2931        T: TypeFoldable<TyCtxt<'tcx>>,
2932    {
2933        struct RegionNameCollector<'tcx> {
2934            tcx: TyCtxt<'tcx>,
2935            used_region_names: FxHashSet<Symbol>,
2936            type_collector: SsoHashSet<Ty<'tcx>>,
2937        }
2938
2939        impl<'tcx> RegionNameCollector<'tcx> {
2940            fn new(tcx: TyCtxt<'tcx>) -> Self {
2941                RegionNameCollector {
2942                    tcx,
2943                    used_region_names: Default::default(),
2944                    type_collector: SsoHashSet::new(),
2945                }
2946            }
2947        }
2948
2949        impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for RegionNameCollector<'tcx> {
2950            fn visit_region(&mut self, r: ty::Region<'tcx>) {
2951                {
    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:2951",
                        "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(2951u32),
                        ::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);
2952
2953                // Collect all named lifetimes. These allow us to prevent duplication
2954                // of already existing lifetime names when introducing names for
2955                // anonymous late-bound regions.
2956                if let Some(name) = r.get_name(self.tcx) {
2957                    self.used_region_names.insert(name);
2958                }
2959            }
2960
2961            // We collect types in order to prevent really large types from compiling for
2962            // a really long time. See issue #83150 for why this is necessary.
2963            fn visit_ty(&mut self, ty: Ty<'tcx>) {
2964                let not_previously_inserted = self.type_collector.insert(ty);
2965                if not_previously_inserted {
2966                    ty.super_visit_with(self)
2967                }
2968            }
2969        }
2970
2971        let mut collector = RegionNameCollector::new(self.tcx());
2972        value.visit_with(&mut collector);
2973        self.used_region_names = collector.used_region_names;
2974        self.region_index = 0;
2975    }
2976}
2977
2978impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<P> for ty::Binder<'tcx, T>
2979where
2980    T: Print<P> + TypeFoldable<TyCtxt<'tcx>>,
2981{
2982    fn print(&self, p: &mut P) -> Result<(), PrintError> {
2983        p.pretty_print_in_binder(self)
2984    }
2985}
2986
2987impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<P> for ty::OutlivesClause<'tcx, T>
2988where
2989    T: Print<P>,
2990{
2991    fn print(&self, p: &mut P) -> Result<(), PrintError> {
2992        self.0.print(p)?;
2993        p.write_fmt(format_args!(": "))write!(p, ": ")?;
2994        self.1.print(p)?;
2995        Ok(())
2996    }
2997}
2998
2999/// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
3000/// the trait path. That is, it will print `Trait<U>` instead of
3001/// `<T as Trait<U>>`.
3002#[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)]
3003pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
3004
3005impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintOnlyTraitPath<'tcx> {
3006    fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
3007        ty::tls::with(|tcx| {
3008            let trait_ref = tcx.short_string(tcx.lift(self), path);
3009            rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
3010        })
3011    }
3012}
3013
3014impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
3015    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3016        fmt::Display::fmt(self, f)
3017    }
3018}
3019
3020/// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
3021/// the trait path, and additionally tries to "sugar" `Fn(...)` trait bounds.
3022#[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)]
3023pub struct TraitRefPrintSugared<'tcx>(ty::TraitRef<'tcx>);
3024
3025impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintSugared<'tcx> {
3026    fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
3027        ty::tls::with(|tcx| {
3028            let trait_ref = tcx.short_string(tcx.lift(self), path);
3029            rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
3030        })
3031    }
3032}
3033
3034impl<'tcx> fmt::Debug for TraitRefPrintSugared<'tcx> {
3035    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3036        fmt::Display::fmt(self, f)
3037    }
3038}
3039
3040/// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
3041/// the trait name. That is, it will print `Trait` instead of
3042/// `<T as Trait<U>>`.
3043#[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)]
3044pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
3045
3046impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
3047    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3048        fmt::Display::fmt(self, f)
3049    }
3050}
3051
3052impl<'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>)]
3053impl<'tcx> ty::TraitRef<'tcx> {
3054    fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
3055        TraitRefPrintOnlyTraitPath(self)
3056    }
3057
3058    fn print_trait_sugared(self) -> TraitRefPrintSugared<'tcx> {
3059        TraitRefPrintSugared(self)
3060    }
3061
3062    fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
3063        TraitRefPrintOnlyTraitName(self)
3064    }
3065}
3066
3067impl<'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>)]
3068impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
3069    fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
3070        self.map_bound(|tr| tr.print_only_trait_path())
3071    }
3072
3073    fn print_trait_sugared(self) -> ty::Binder<'tcx, TraitRefPrintSugared<'tcx>> {
3074        self.map_bound(|tr| tr.print_trait_sugared())
3075    }
3076}
3077
3078#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for TraitPredPrintModifiersAndPath<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TraitPredPrintModifiersAndPath<'tcx> {
    #[inline]
    fn clone(&self) -> TraitPredPrintModifiersAndPath<'tcx> {
        let _: ::core::clone::AssertParamIsClone<ty::TraitPredicate<'tcx>>;
        *self
    }
}Clone, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TraitPredPrintModifiersAndPath<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        TraitPredPrintModifiersAndPath(__binding_0) => {
                            TraitPredPrintModifiersAndPath(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    TraitPredPrintModifiersAndPath(__binding_0) => {
                        TraitPredPrintModifiersAndPath(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TraitPredPrintModifiersAndPath<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    TraitPredPrintModifiersAndPath(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable, const _: () =
    {
        impl<'tcx, '__lifted>
            ::rustc_middle::ty::Lift<::rustc_middle::ty::TyCtxt<'__lifted>>
            for TraitPredPrintModifiersAndPath<'tcx> {
            type Lifted = TraitPredPrintModifiersAndPath<'__lifted>;
            fn lift_to_interner(self,
                __tcx: ::rustc_middle::ty::TyCtxt<'__lifted>)
                -> TraitPredPrintModifiersAndPath<'__lifted> {
                match self {
                    TraitPredPrintModifiersAndPath(__binding_0) => {
                        TraitPredPrintModifiersAndPath(__tcx.lift(__binding_0))
                    }
                }
            }
        }
    };Lift, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for TraitPredPrintModifiersAndPath<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash)]
3079pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
3080
3081impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
3082    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3083        fmt::Display::fmt(self, f)
3084    }
3085}
3086
3087impl<'tcx> PrintTraitPredicateExt<'tcx> for ty::TraitPredicate<'tcx> {
    fn print_modifiers_and_trait_path(self)
        -> TraitPredPrintModifiersAndPath<'tcx> {
        TraitPredPrintModifiersAndPath(self)
    }
}#[extension(pub trait PrintTraitPredicateExt<'tcx>)]
3088impl<'tcx> ty::TraitPredicate<'tcx> {
3089    fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
3090        TraitPredPrintModifiersAndPath(self)
3091    }
3092}
3093
3094#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for TraitPredPrintWithBoundConstness<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TraitPredPrintWithBoundConstness<'tcx> {
    #[inline]
    fn clone(&self) -> TraitPredPrintWithBoundConstness<'tcx> {
        let _: ::core::clone::AssertParamIsClone<ty::TraitPredicate<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Option<ty::BoundConstness>>;
        *self
    }
}Clone, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TraitPredPrintWithBoundConstness<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        TraitPredPrintWithBoundConstness(__binding_0, __binding_1)
                            => {
                            TraitPredPrintWithBoundConstness(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?)
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    TraitPredPrintWithBoundConstness(__binding_0, __binding_1)
                        => {
                        TraitPredPrintWithBoundConstness(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder))
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TraitPredPrintWithBoundConstness<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    TraitPredPrintWithBoundConstness(ref __binding_0,
                        ref __binding_1) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable, const _: () =
    {
        impl<'tcx, '__lifted>
            ::rustc_middle::ty::Lift<::rustc_middle::ty::TyCtxt<'__lifted>>
            for TraitPredPrintWithBoundConstness<'tcx> {
            type Lifted = TraitPredPrintWithBoundConstness<'__lifted>;
            fn lift_to_interner(self,
                __tcx: ::rustc_middle::ty::TyCtxt<'__lifted>)
                -> TraitPredPrintWithBoundConstness<'__lifted> {
                match self {
                    TraitPredPrintWithBoundConstness(__binding_0, __binding_1)
                        => {
                        TraitPredPrintWithBoundConstness(__tcx.lift(__binding_0),
                            __tcx.lift(__binding_1))
                    }
                }
            }
        }
    };Lift, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for TraitPredPrintWithBoundConstness<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state);
        ::core::hash::Hash::hash(&self.1, state)
    }
}Hash)]
3095pub struct TraitPredPrintWithBoundConstness<'tcx>(
3096    ty::TraitPredicate<'tcx>,
3097    Option<ty::BoundConstness>,
3098);
3099
3100impl<'tcx> fmt::Debug for TraitPredPrintWithBoundConstness<'tcx> {
3101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3102        fmt::Display::fmt(self, f)
3103    }
3104}
3105
3106impl<'tcx> PrintPolyTraitPredicateExt<'tcx> for ty::PolyTraitPredicate<'tcx> {
    fn print_modifiers_and_trait_path(self)
        -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
        self.map_bound(TraitPredPrintModifiersAndPath)
    }
    fn print_with_bound_constness(self, constness: Option<ty::BoundConstness>)
        -> ty::Binder<'tcx, TraitPredPrintWithBoundConstness<'tcx>> {
        self.map_bound(|trait_pred|
                TraitPredPrintWithBoundConstness(trait_pred, constness))
    }
}#[extension(pub trait PrintPolyTraitPredicateExt<'tcx>)]
3107impl<'tcx> ty::PolyTraitPredicate<'tcx> {
3108    fn print_modifiers_and_trait_path(
3109        self,
3110    ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
3111        self.map_bound(TraitPredPrintModifiersAndPath)
3112    }
3113
3114    fn print_with_bound_constness(
3115        self,
3116        constness: Option<ty::BoundConstness>,
3117    ) -> ty::Binder<'tcx, TraitPredPrintWithBoundConstness<'tcx>> {
3118        self.map_bound(|trait_pred| TraitPredPrintWithBoundConstness(trait_pred, constness))
3119    }
3120}
3121
3122#[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)]
3123pub struct PrintClosureAsImpl<'tcx> {
3124    pub closure: ty::ClosureArgs<TyCtxt<'tcx>>,
3125}
3126
3127macro_rules! forward_display_to_print {
3128    ($($ty:ty),+) => {
3129        $(
3130            #[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
3131            impl<'tcx> fmt::Display for $ty {
3132                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3133                    ty::tls::with(|tcx| {
3134                        let mut p = FmtPrinter::new(tcx, Namespace::TypeNS);
3135                        tcx.lift(*self)
3136                            .print(&mut p)?;
3137                        f.write_str(&p.into_buffer())?;
3138                        Ok(())
3139                    })
3140                }
3141            }
3142        )+
3143    };
3144}
3145
3146macro_rules! define_print {
3147    (($self:ident, $p:ident): $($ty:ty $print:block)+) => {
3148        $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for $ty {
3149            fn print(&$self, $p: &mut P) -> Result<(), PrintError> {
3150                let _: () = $print;
3151                Ok(())
3152            }
3153        })+
3154    };
3155}
3156
3157macro_rules! define_print_and_forward_display {
3158    (($self:ident, $p:ident): $($ty:ty $print:block)+) => {
3159        define_print!(($self, $p): $($ty $print)*);
3160        forward_display_to_print!($($ty),+);
3161    };
3162}
3163
3164#[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! {
3165    Ty<'tcx>,
3166    &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3167    ty::Const<'tcx>
3168}
3169
3170impl<'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! {
3171    (self, p):
3172
3173    ty::FnSig<'tcx> {
3174        write!(p, "{}", self.safety().prefix_str())?;
3175
3176        if self.abi() != ExternAbi::Rust {
3177            write!(p, "extern {} ", self.abi())?;
3178        }
3179
3180        write!(p, "fn")?;
3181        p.pretty_print_fn_sig(self.inputs(), self.c_variadic(), self.splatted(), self.output())?;
3182    }
3183
3184    ty::TraitRef<'tcx> {
3185        write!(p, "<{} as {}>", self.self_ty(), self.print_only_trait_path())?;
3186    }
3187
3188    ty::AliasTy<'tcx> {
3189        let alias_term: ty::AliasTerm<'tcx> = (*self).into();
3190        alias_term.print(p)?;
3191    }
3192
3193    ty::AliasTerm<'tcx> {
3194        match self.kind {
3195            ty::AliasTermKind::InherentTy { .. } | ty::AliasTermKind::InherentConst { .. } => {
3196                p.pretty_print_inherent_projection(*self)?;
3197            }
3198            ty::AliasTermKind::ProjectionTy { def_id } => {
3199                if !(p.should_print_verbose() || with_reduced_queries())
3200                    && p.tcx().is_impl_trait_in_trait(def_id)
3201                {
3202                    p.pretty_print_rpitit(def_id, self.args)?;
3203                } else {
3204                    p.print_def_path(def_id, self.args)?;
3205                }
3206            }
3207            ty::AliasTermKind::FreeTy { def_id }
3208            | ty::AliasTermKind::FreeConst { def_id }
3209            | ty::AliasTermKind::OpaqueTy { def_id }
3210            | ty::AliasTermKind::AnonConst { def_id }
3211            | ty::AliasTermKind::ProjectionConst { def_id } => {
3212                p.print_def_path(def_id, self.args)?;
3213            }
3214        }
3215    }
3216
3217    ty::TraitPredicate<'tcx> {
3218        self.trait_ref.self_ty().print(p)?;
3219        write!(p, ": ")?;
3220        if let ty::PredicatePolarity::Negative = self.polarity {
3221            write!(p, "!")?;
3222        }
3223        self.trait_ref.print_trait_sugared().print(p)?;
3224    }
3225
3226    ty::HostEffectPredicate<'tcx> {
3227        let constness = match self.constness {
3228            ty::BoundConstness::Const => { "const" }
3229            ty::BoundConstness::Maybe => { "[const]" }
3230        };
3231        self.trait_ref.self_ty().print(p)?;
3232        write!(p, ": {constness} ")?;
3233        self.trait_ref.print_trait_sugared().print(p)?;
3234    }
3235
3236    ty::TypeAndMut<'tcx> {
3237        write!(p, "{}", self.mutbl.prefix_str())?;
3238        self.ty.print(p)?;
3239    }
3240
3241    ty::ClauseKind<'tcx> {
3242        match *self {
3243            ty::ClauseKind::Trait(ref data) => data.print(p)?,
3244            ty::ClauseKind::RegionOutlives(predicate) => predicate.print(p)?,
3245            ty::ClauseKind::TypeOutlives(predicate) => predicate.print(p)?,
3246            ty::ClauseKind::Projection(predicate) => predicate.print(p)?,
3247            ty::ClauseKind::HostEffect(predicate) => predicate.print(p)?,
3248            ty::ClauseKind::ConstArgHasType(ct, ty) => {
3249                write!(p, "the constant `")?;
3250                ct.print(p)?;
3251                write!(p, "` has type `")?;
3252                ty.print(p)?;
3253                write!(p, "`")?;
3254            },
3255            ty::ClauseKind::WellFormed(term) => {
3256                term.print(p)?;
3257                write!(p, " well-formed")?;
3258            }
3259            ty::ClauseKind::ConstEvaluatable(ct) => {
3260                write!(p, "the constant `")?;
3261                ct.print(p)?;
3262                write!(p, "` can be evaluated")?;
3263            }
3264            ty::ClauseKind::UnstableFeature(symbol) => {
3265                write!(p, "feature({symbol}) is enabled")?;
3266            }
3267        }
3268    }
3269
3270    ty::PredicateKind<'tcx> {
3271        match *self {
3272            ty::PredicateKind::Clause(data) => data.print(p)?,
3273            ty::PredicateKind::Subtype(predicate) => predicate.print(p)?,
3274            ty::PredicateKind::Coerce(predicate) => predicate.print(p)?,
3275            ty::PredicateKind::DynCompatible(trait_def_id) => {
3276                write!(p, "the trait `")?;
3277                p.print_def_path(trait_def_id, &[])?;
3278                write!(p, "` is dyn-compatible")?;
3279            }
3280            ty::PredicateKind::ConstEquate(c1, c2) => {
3281                write!(p, "the constant `")?;
3282                c1.print(p)?;
3283                write!(p, "` equals `")?;
3284                c2.print(p)?;
3285                write!(p, "`")?;
3286            }
3287            ty::PredicateKind::Ambiguous => write!(p, "ambiguous")?,
3288            ty::PredicateKind::NormalizesTo(data) => data.print(p)?,
3289        }
3290    }
3291
3292    ty::ExistentialPredicate<'tcx> {
3293        match *self {
3294            ty::ExistentialPredicate::Trait(x) => x.print(p)?,
3295            ty::ExistentialPredicate::Projection(x) => x.print(p)?,
3296            ty::ExistentialPredicate::AutoTrait(def_id) => p.print_def_path(def_id, &[])?,
3297        }
3298    }
3299
3300    ty::ExistentialTraitRef<'tcx> {
3301        // Dummy Self is safe to use as it can't appear in generic param defaults which is important
3302        // later on for correctly eliding generic args that coincide with their default.
3303        let trait_ref = self.with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self);
3304        trait_ref.print_only_trait_path().print(p)?;
3305    }
3306
3307    ty::ExistentialProjection<'tcx> {
3308        let name = p.tcx().associated_item(self.def_id).name();
3309        // The args don't contain the self ty (as it has been erased) but the corresp.
3310        // generics do as the trait always has a self ty param. We need to offset.
3311        let args = &self.args[p.tcx().generics_of(self.def_id).parent_count - 1..];
3312        p.print_path_with_generic_args(|p| write!(p, "{name}"), args)?;
3313        write!(p, " = ")?;
3314        self.term.print(p)?;
3315    }
3316
3317    ty::ProjectionPredicate<'tcx> {
3318        self.projection_term.print(p)?;
3319        write!(p, " == ")?;
3320        p.reset_type_limit();
3321        self.term.print(p)?;
3322    }
3323
3324    ty::SubtypePredicate<'tcx> {
3325        self.a.print(p)?;
3326        write!(p, " <: ")?;
3327        p.reset_type_limit();
3328        self.b.print(p)?;
3329    }
3330
3331    ty::CoercePredicate<'tcx> {
3332        self.a.print(p)?;
3333        write!(p, " -> ")?;
3334        p.reset_type_limit();
3335        self.b.print(p)?;
3336    }
3337
3338    ty::NormalizesTo<'tcx> {
3339        self.alias.print(p)?;
3340        write!(p, " normalizes-to ")?;
3341        p.reset_type_limit();
3342        self.term.print(p)?;
3343    }
3344
3345    ty::PlaceholderType<'tcx> {
3346        match self.bound.kind {
3347            ty::BoundTyKind::Anon => write!(p, "{self:?}")?,
3348            ty::BoundTyKind::Param(def_id) => match p.should_print_verbose() {
3349                true => write!(p, "{self:?}")?,
3350                false => write!(p, "{}", p.tcx().item_name(def_id))?,
3351            },
3352        }
3353    }
3354}
3355
3356#[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! {
3357    (self, p):
3358
3359    &'tcx ty::List<Ty<'tcx>> {
3360        write!(p, "{{")?;
3361        p.comma_sep(self.iter())?;
3362        write!(p, "}}")?;
3363    }
3364
3365    TraitRefPrintOnlyTraitPath<'tcx> {
3366        p.print_def_path(self.0.def_id, self.0.args)?;
3367    }
3368
3369    TraitRefPrintSugared<'tcx> {
3370        if !with_reduced_queries()
3371            && p.tcx().trait_def(self.0.def_id).paren_sugar
3372            && let Some(args_ty) = self.0.args.get(1).and_then(|arg| arg.as_type())
3373            && let ty::Tuple(args) = args_ty.kind()
3374        {
3375            write!(p, "{}(", p.tcx().item_name(self.0.def_id))?;
3376            for (i, arg) in args.iter().enumerate() {
3377                if i > 0 {
3378                    write!(p, ", ")?;
3379                }
3380                arg.print(p)?;
3381            }
3382            write!(p, ")")?;
3383        } else {
3384            p.print_def_path(self.0.def_id, self.0.args)?;
3385        }
3386    }
3387
3388    TraitRefPrintOnlyTraitName<'tcx> {
3389        p.print_def_path(self.0.def_id, &[])?;
3390    }
3391
3392    TraitPredPrintModifiersAndPath<'tcx> {
3393        if let ty::PredicatePolarity::Negative = self.0.polarity {
3394            write!(p, "!")?;
3395        }
3396        self.0.trait_ref.print_trait_sugared().print(p)?;
3397    }
3398
3399    TraitPredPrintWithBoundConstness<'tcx> {
3400        self.0.trait_ref.self_ty().print(p)?;
3401        write!(p, ": ")?;
3402        if let Some(constness) = self.1 {
3403            p.pretty_print_bound_constness(constness)?;
3404        }
3405        if let ty::PredicatePolarity::Negative = self.0.polarity {
3406            write!(p, "!")?;
3407        }
3408        self.0.trait_ref.print_trait_sugared().print(p)?;
3409    }
3410
3411    PrintClosureAsImpl<'tcx> {
3412        p.pretty_print_closure_as_impl(self.closure)?;
3413    }
3414
3415    ty::ParamTy {
3416        write!(p, "{}", self.name)?;
3417    }
3418
3419    ty::ParamConst {
3420        write!(p, "{}", self.name)?;
3421    }
3422
3423    ty::Term<'tcx> {
3424      match self.kind() {
3425        ty::TermKind::Ty(ty) => ty.print(p)?,
3426        ty::TermKind::Const(c) => c.print(p)?,
3427      }
3428    }
3429
3430    ty::Predicate<'tcx> {
3431        self.kind().print(p)?;
3432    }
3433
3434    ty::Clause<'tcx> {
3435        self.kind().print(p)?;
3436    }
3437
3438    ty::UserTypeKind<'tcx> {
3439        match *self {
3440            Self::Ty(ty) => {
3441                write!(p, "Ty(")?;
3442                ty.print(p)?;
3443            }
3444            Self::TypeOf(def_id, ty::UserArgs { args, user_self_ty }) => {
3445                write!(p, "TypeOf(")?;
3446                p.print_def_path(def_id, args)?;
3447                if let Some(ty::UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
3448                    write!(p, " at <impl ")?;
3449                    let key = p.tcx().def_key(impl_def_id);
3450                    let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
3451                    p.print_def_path(parent_def_id, &[])?;
3452                    write!(p, "::<{}> for ", key.disambiguated_data.as_sym(false))?;
3453                    self_ty.print(p)?;
3454                    write!(p, ">")?;
3455                }
3456            }
3457        }
3458        write!(p, ")")?;
3459    }
3460
3461    GenericArg<'tcx> {
3462        match self.kind() {
3463            GenericArgKind::Lifetime(lt) => lt.print(p)?,
3464            GenericArgKind::Type(ty) => ty.print(p)?,
3465            GenericArgKind::Const(ct) => ct.print(p)?,
3466        }
3467    }
3468}
3469
3470fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
3471    // Iterate all (non-anonymous) local crate items no matter where they are defined.
3472    for id in tcx.hir_free_items() {
3473        if tcx.def_kind(id.owner_id) == DefKind::Use {
3474            continue;
3475        }
3476
3477        let item = tcx.hir_item(id);
3478        let Some(ident) = item.kind.ident() else { continue };
3479
3480        let def_id = item.owner_id.to_def_id();
3481        let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
3482        collect_fn(&ident, ns, def_id);
3483    }
3484
3485    // Now take care of extern crate items.
3486    let queue = &mut Vec::new();
3487    let mut seen_defs: DefIdSet = Default::default();
3488
3489    for &cnum in tcx.crates(()).iter() {
3490        // Ignore crates that are not direct dependencies.
3491        match tcx.extern_crate(cnum) {
3492            None => continue,
3493            Some(extern_crate) => {
3494                if !extern_crate.is_direct() {
3495                    continue;
3496                }
3497            }
3498        }
3499
3500        queue.push(cnum.as_def_id());
3501    }
3502
3503    // Iterate external crate defs but be mindful about visibility
3504    while let Some(def) = queue.pop() {
3505        for child in tcx.module_children(def).iter() {
3506            if !child.vis.is_public() {
3507                continue;
3508            }
3509
3510            match child.res {
3511                def::Res::Def(DefKind::AssocTy, _) => {}
3512                def::Res::Def(DefKind::TyAlias, _) => {}
3513                def::Res::Def(defkind, def_id) => {
3514                    // Ignore external `#[doc(hidden)]` items and their descendants.
3515                    // They shouldn't prevent other items from being considered
3516                    // unique, and should be printed with a full path if necessary.
3517                    if tcx.is_doc_hidden(def_id) {
3518                        continue;
3519                    }
3520
3521                    if let Some(ns) = defkind.ns() {
3522                        collect_fn(&child.ident, ns, def_id);
3523                    }
3524
3525                    if defkind.is_module_like() && seen_defs.insert(def_id) {
3526                        queue.push(def_id);
3527                    }
3528                }
3529                _ => {}
3530            }
3531        }
3532    }
3533}
3534
3535/// The purpose of this function is to collect public symbols names that are unique across all
3536/// crates in the build. Later, when printing about types we can use those names instead of the
3537/// full exported path to them.
3538///
3539/// So essentially, if a symbol name can only be imported from one place for a type, and as
3540/// long as it was not glob-imported anywhere in the current crate, we can trim its printed
3541/// path and print only the name.
3542///
3543/// This has wide implications on error messages with types, for example, shortening
3544/// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
3545///
3546/// The implementation uses similar import discovery logic to that of 'use' suggestions.
3547///
3548/// See also [`with_no_trimmed_paths!`].
3549// this is pub to be able to intra-doc-link it
3550pub fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> DefIdMap<Symbol> {
3551    // Trimming paths is expensive and not optimized, since we expect it to only be used for error
3552    // reporting. Record the fact that we did it, so we can abort if we later found it was
3553    // unnecessary.
3554    //
3555    // The `rustc_middle::ty::print::with_no_trimmed_paths` wrapper can be used to suppress this
3556    // checking, in exchange for full paths being formatted.
3557    tcx.sess.record_trimmed_def_paths();
3558
3559    // Once constructed, unique namespace+symbol pairs will have a `Some(_)` entry, while
3560    // non-unique pairs will have a `None` entry.
3561    let unique_symbols_rev: &mut FxIndexMap<(Namespace, Symbol), Option<DefId>> =
3562        &mut FxIndexMap::default();
3563
3564    for symbol_set in tcx.resolutions(()).glob_map.values() {
3565        for symbol in symbol_set {
3566            unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
3567            unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
3568            unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
3569        }
3570    }
3571
3572    for_each_def(tcx, |ident, ns, def_id| match unique_symbols_rev.entry((ns, ident.name)) {
3573        IndexEntry::Occupied(mut v) => match v.get() {
3574            None => {}
3575            Some(existing) => {
3576                if *existing != def_id {
3577                    v.insert(None);
3578                }
3579            }
3580        },
3581        IndexEntry::Vacant(v) => {
3582            v.insert(Some(def_id));
3583        }
3584    });
3585
3586    // Put the symbol from all the unique namespace+symbol pairs into `map`.
3587    let mut map: DefIdMap<Symbol> = Default::default();
3588    for ((_, symbol), opt_def_id) in unique_symbols_rev.drain(..) {
3589        use std::collections::hash_map::Entry::{Occupied, Vacant};
3590
3591        if let Some(def_id) = opt_def_id {
3592            match map.entry(def_id) {
3593                Occupied(mut v) => {
3594                    // A single DefId can be known under multiple names (e.g.,
3595                    // with a `pub use ... as ...;`). We need to ensure that the
3596                    // name placed in this map is chosen deterministically, so
3597                    // if we find multiple names (`symbol`) resolving to the
3598                    // same `def_id`, we prefer the lexicographically smallest
3599                    // name.
3600                    //
3601                    // Any stable ordering would be fine here though.
3602                    if *v.get() != symbol && v.get().as_str() > symbol.as_str() {
3603                        v.insert(symbol);
3604                    }
3605                }
3606                Vacant(v) => {
3607                    v.insert(symbol);
3608                }
3609            }
3610        }
3611    }
3612
3613    map
3614}
3615
3616pub fn provide(providers: &mut Providers) {
3617    *providers = Providers { trimmed_def_paths, ..*providers };
3618}
3619
3620pub struct OpaqueFnEntry<'tcx> {
3621    kind: ty::ClosureKind,
3622    return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,
3623}