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