Skip to main content

rustc_middle/ty/print/
pretty.rs

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