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