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            (ty::ValTreeKind::Branch(fields), ty::Array(..) | ty::Tuple(..)) => {
1923                let fields_iter = fields.iter().copied();
1924
1925                match *cv.ty.kind() {
1926                    ty::Array(..) => {
1927                        write!(self, "[")?;
1928                        self.comma_sep(fields_iter)?;
1929                        write!(self, "]")?;
1930                    }
1931                    ty::Tuple(..) => {
1932                        write!(self, "(")?;
1933                        self.comma_sep(fields_iter)?;
1934                        if fields.len() == 1 {
1935                            write!(self, ",")?;
1936                        }
1937                        write!(self, ")")?;
1938                    }
1939                    _ => unreachable!(),
1940                }
1941                return Ok(());
1942            }
1943            (ty::ValTreeKind::Branch(_), ty::Adt(def, args)) => {
1944                let contents = cv.destructure_adt_const();
1945                let fields = contents.fields.iter().copied();
1946
1947                if def.variants().is_empty() {
1948                    self.typed_value(
1949                        |this| {
1950                            write!(this, "unreachable()")?;
1951                            Ok(())
1952                        },
1953                        |this| this.print_type(cv.ty),
1954                        ": ",
1955                    )?;
1956                } else {
1957                    let variant_idx = contents.variant;
1958                    let variant_def = &def.variant(variant_idx);
1959                    self.pretty_print_value_path(variant_def.def_id, args)?;
1960                    match variant_def.ctor_kind() {
1961                        Some(CtorKind::Const) => {}
1962                        Some(CtorKind::Fn) => {
1963                            write!(self, "(")?;
1964                            self.comma_sep(fields)?;
1965                            write!(self, ")")?;
1966                        }
1967                        None => {
1968                            write!(self, " {{ ")?;
1969                            let mut first = true;
1970                            for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1971                                if !first {
1972                                    write!(self, ", ")?;
1973                                }
1974                                write!(self, "{}: ", field_def.name)?;
1975                                field.print(self)?;
1976                                first = false;
1977                            }
1978                            write!(self, " }}")?;
1979                        }
1980                    }
1981                }
1982                return Ok(());
1983            }
1984            (ty::ValTreeKind::Leaf(leaf), ty::Ref(_, inner_ty, _)) => {
1985                write!(self, "&")?;
1986                return self.pretty_print_const_scalar_int(*leaf, inner_ty, print_ty);
1987            }
1988            (ty::ValTreeKind::Leaf(leaf), _) => {
1989                return self.pretty_print_const_scalar_int(*leaf, cv.ty, print_ty);
1990            }
1991            (_, ty::FnDef(def_id, args)) => {
1992                // Never allowed today, but we still encounter them in invalid const args.
1993                self.pretty_print_value_path(def_id, args)?;
1994                return Ok(());
1995            }
1996            // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1997            // their fields instead of just dumping the memory.
1998            _ => {}
1999        }
2000
2001        // fallback
2002        if cv.valtree.is_zst() {
2003            write!(self, "<ZST>")?;
2004        } else {
2005            write!(self, "{:?}", cv.valtree)?;
2006        }
2007        if print_ty {
2008            write!(self, ": ")?;
2009            cv.ty.print(self)?;
2010        }
2011        Ok(())
2012    }
2013
2014    fn pretty_print_closure_as_impl(
2015        &mut self,
2016        closure: ty::ClosureArgs<TyCtxt<'tcx>>,
2017    ) -> Result<(), PrintError> {
2018        let sig = closure.sig();
2019        let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn);
2020
2021        write!(self, "impl ")?;
2022        self.wrap_binder(&sig, WrapBinderMode::ForAll, |sig, p| {
2023            write!(p, "{kind}(")?;
2024            for (i, arg) in sig.inputs()[0].tuple_fields().iter().enumerate() {
2025                if i > 0 {
2026                    write!(p, ", ")?;
2027                }
2028                arg.print(p)?;
2029            }
2030            write!(p, ")")?;
2031
2032            if !sig.output().is_unit() {
2033                write!(p, " -> ")?;
2034                sig.output().print(p)?;
2035            }
2036
2037            Ok(())
2038        })
2039    }
2040
2041    fn pretty_print_bound_constness(
2042        &mut self,
2043        constness: ty::BoundConstness,
2044    ) -> Result<(), PrintError> {
2045        match constness {
2046            ty::BoundConstness::Const => write!(self, "const ")?,
2047            ty::BoundConstness::Maybe => write!(self, "[const] ")?,
2048        }
2049        Ok(())
2050    }
2051
2052    fn should_print_verbose(&self) -> bool {
2053        self.tcx().sess.verbose_internals()
2054    }
2055}
2056
2057pub(crate) fn pretty_print_const<'tcx>(
2058    c: ty::Const<'tcx>,
2059    fmt: &mut fmt::Formatter<'_>,
2060    print_types: bool,
2061) -> fmt::Result {
2062    ty::tls::with(|tcx| {
2063        let literal = tcx.lift(c).unwrap();
2064        let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
2065        p.print_alloc_ids = true;
2066        p.pretty_print_const(literal, print_types)?;
2067        fmt.write_str(&p.into_buffer())?;
2068        Ok(())
2069    })
2070}
2071
2072// HACK(eddyb) boxed to avoid moving around a large struct by-value.
2073pub struct FmtPrinter<'a, 'tcx>(Box<FmtPrinterData<'a, 'tcx>>);
2074
2075pub struct FmtPrinterData<'a, 'tcx> {
2076    tcx: TyCtxt<'tcx>,
2077    fmt: String,
2078
2079    empty_path: bool,
2080    in_value: bool,
2081    pub print_alloc_ids: bool,
2082
2083    // set of all named (non-anonymous) region names
2084    used_region_names: FxHashSet<Symbol>,
2085
2086    region_index: usize,
2087    binder_depth: usize,
2088    printed_type_count: usize,
2089    type_length_limit: Limit,
2090
2091    pub region_highlight_mode: RegionHighlightMode<'tcx>,
2092
2093    pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<Symbol> + 'a>>,
2094    pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid) -> Option<Symbol> + 'a>>,
2095}
2096
2097impl<'a, 'tcx> Deref for FmtPrinter<'a, 'tcx> {
2098    type Target = FmtPrinterData<'a, 'tcx>;
2099    fn deref(&self) -> &Self::Target {
2100        &self.0
2101    }
2102}
2103
2104impl DerefMut for FmtPrinter<'_, '_> {
2105    fn deref_mut(&mut self) -> &mut Self::Target {
2106        &mut self.0
2107    }
2108}
2109
2110impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
2111    pub fn new(tcx: TyCtxt<'tcx>, ns: Namespace) -> Self {
2112        let limit =
2113            if with_reduced_queries() { Limit::new(1048576) } else { tcx.type_length_limit() };
2114        Self::new_with_limit(tcx, ns, limit)
2115    }
2116
2117    pub fn print_string(
2118        tcx: TyCtxt<'tcx>,
2119        ns: Namespace,
2120        f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2121    ) -> Result<String, PrintError> {
2122        let mut c = FmtPrinter::new(tcx, ns);
2123        f(&mut c)?;
2124        Ok(c.into_buffer())
2125    }
2126
2127    pub fn new_with_limit(tcx: TyCtxt<'tcx>, ns: Namespace, type_length_limit: Limit) -> Self {
2128        FmtPrinter(Box::new(FmtPrinterData {
2129            tcx,
2130            // Estimated reasonable capacity to allocate upfront based on a few
2131            // benchmarks.
2132            fmt: String::with_capacity(64),
2133            empty_path: false,
2134            in_value: ns == Namespace::ValueNS,
2135            print_alloc_ids: false,
2136            used_region_names: Default::default(),
2137            region_index: 0,
2138            binder_depth: 0,
2139            printed_type_count: 0,
2140            type_length_limit,
2141            region_highlight_mode: RegionHighlightMode::default(),
2142            ty_infer_name_resolver: None,
2143            const_infer_name_resolver: None,
2144        }))
2145    }
2146
2147    pub fn into_buffer(self) -> String {
2148        self.0.fmt
2149    }
2150}
2151
2152fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
2153    match tcx.def_key(def_id).disambiguated_data.data {
2154        DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::OpaqueTy => {
2155            Namespace::TypeNS
2156        }
2157
2158        DefPathData::ValueNs(..)
2159        | DefPathData::AnonConst
2160        | DefPathData::LateAnonConst
2161        | DefPathData::Closure
2162        | DefPathData::Ctor => Namespace::ValueNS,
2163
2164        DefPathData::MacroNs(..) => Namespace::MacroNS,
2165
2166        _ => Namespace::TypeNS,
2167    }
2168}
2169
2170impl<'t> TyCtxt<'t> {
2171    /// Returns a string identifying this `DefId`. This string is
2172    /// suitable for user output.
2173    pub fn def_path_str(self, def_id: impl IntoQueryParam<DefId>) -> String {
2174        self.def_path_str_with_args(def_id, &[])
2175    }
2176
2177    /// For this one we determine the appropriate namespace for the `def_id`.
2178    pub fn def_path_str_with_args(
2179        self,
2180        def_id: impl IntoQueryParam<DefId>,
2181        args: &'t [GenericArg<'t>],
2182    ) -> String {
2183        let def_id = def_id.into_query_param();
2184        let ns = guess_def_namespace(self, def_id);
2185        debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
2186
2187        FmtPrinter::print_string(self, ns, |p| p.print_def_path(def_id, args)).unwrap()
2188    }
2189
2190    /// For this one we always use value namespace.
2191    pub fn value_path_str_with_args(
2192        self,
2193        def_id: impl IntoQueryParam<DefId>,
2194        args: &'t [GenericArg<'t>],
2195    ) -> String {
2196        let def_id = def_id.into_query_param();
2197        let ns = Namespace::ValueNS;
2198        debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns);
2199
2200        FmtPrinter::print_string(self, ns, |p| p.print_def_path(def_id, args)).unwrap()
2201    }
2202}
2203
2204impl fmt::Write for FmtPrinter<'_, '_> {
2205    fn write_str(&mut self, s: &str) -> fmt::Result {
2206        self.fmt.push_str(s);
2207        Ok(())
2208    }
2209}
2210
2211impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
2212    fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
2213        self.tcx
2214    }
2215
2216    fn print_def_path(
2217        &mut self,
2218        def_id: DefId,
2219        args: &'tcx [GenericArg<'tcx>],
2220    ) -> Result<(), PrintError> {
2221        if args.is_empty() {
2222            match self.try_print_trimmed_def_path(def_id)? {
2223                true => return Ok(()),
2224                false => {}
2225            }
2226
2227            match self.try_print_visible_def_path(def_id)? {
2228                true => return Ok(()),
2229                false => {}
2230            }
2231        }
2232
2233        let key = self.tcx.def_key(def_id);
2234        if let DefPathData::Impl = key.disambiguated_data.data {
2235            // Always use types for non-local impls, where types are always
2236            // available, and filename/line-number is mostly uninteresting.
2237            let use_types = !def_id.is_local() || {
2238                // Otherwise, use filename/line-number if forced.
2239                let force_no_types = with_forced_impl_filename_line();
2240                !force_no_types
2241            };
2242
2243            if !use_types {
2244                // If no type info is available, fall back to
2245                // pretty printing some span information. This should
2246                // only occur very early in the compiler pipeline.
2247                let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
2248                let span = self.tcx.def_span(def_id);
2249
2250                self.print_def_path(parent_def_id, &[])?;
2251
2252                // HACK(eddyb) copy of `print_path_with_simple` to avoid
2253                // constructing a `DisambiguatedDefPathData`.
2254                if !self.empty_path {
2255                    write!(self, "::")?;
2256                }
2257                write!(
2258                    self,
2259                    "<impl at {}>",
2260                    // This may end up in stderr diagnostics but it may also be emitted
2261                    // into MIR. Hence we use the remapped path if available
2262                    self.tcx.sess.source_map().span_to_diagnostic_string(span)
2263                )?;
2264                self.empty_path = false;
2265
2266                return Ok(());
2267            }
2268        }
2269
2270        self.default_print_def_path(def_id, args)
2271    }
2272
2273    fn print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), PrintError> {
2274        self.pretty_print_region(region)
2275    }
2276
2277    fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
2278        match ty.kind() {
2279            ty::Tuple(tys) if tys.len() == 0 && self.should_truncate() => {
2280                // Don't truncate `()`.
2281                self.printed_type_count += 1;
2282                self.pretty_print_type(ty)
2283            }
2284            ty::Adt(..)
2285            | ty::Foreign(_)
2286            | ty::Pat(..)
2287            | ty::RawPtr(..)
2288            | ty::Ref(..)
2289            | ty::FnDef(..)
2290            | ty::FnPtr(..)
2291            | ty::UnsafeBinder(..)
2292            | ty::Dynamic(..)
2293            | ty::Closure(..)
2294            | ty::CoroutineClosure(..)
2295            | ty::Coroutine(..)
2296            | ty::CoroutineWitness(..)
2297            | ty::Tuple(_)
2298            | ty::Alias(..)
2299            | ty::Param(_)
2300            | ty::Bound(..)
2301            | ty::Placeholder(_)
2302            | ty::Error(_)
2303                if self.should_truncate() =>
2304            {
2305                // We only truncate types that we know are likely to be much longer than 3 chars.
2306                // There's no point in replacing `i32` or `!`.
2307                write!(self, "...")?;
2308                Ok(())
2309            }
2310            _ => {
2311                self.printed_type_count += 1;
2312                self.pretty_print_type(ty)
2313            }
2314        }
2315    }
2316
2317    fn print_dyn_existential(
2318        &mut self,
2319        predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2320    ) -> Result<(), PrintError> {
2321        self.pretty_print_dyn_existential(predicates)
2322    }
2323
2324    fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
2325        self.pretty_print_const(ct, false)
2326    }
2327
2328    fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
2329        self.empty_path = true;
2330        if cnum == LOCAL_CRATE && !with_resolve_crate_name() {
2331            if self.tcx.sess.at_least_rust_2018() {
2332                // We add the `crate::` keyword on Rust 2018, only when desired.
2333                if with_crate_prefix() {
2334                    write!(self, "{}", kw::Crate)?;
2335                    self.empty_path = false;
2336                }
2337            }
2338        } else {
2339            write!(self, "{}", self.tcx.crate_name(cnum))?;
2340            self.empty_path = false;
2341        }
2342        Ok(())
2343    }
2344
2345    fn print_path_with_qualified(
2346        &mut self,
2347        self_ty: Ty<'tcx>,
2348        trait_ref: Option<ty::TraitRef<'tcx>>,
2349    ) -> Result<(), PrintError> {
2350        self.pretty_print_path_with_qualified(self_ty, trait_ref)?;
2351        self.empty_path = false;
2352        Ok(())
2353    }
2354
2355    fn print_path_with_impl(
2356        &mut self,
2357        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2358        self_ty: Ty<'tcx>,
2359        trait_ref: Option<ty::TraitRef<'tcx>>,
2360    ) -> Result<(), PrintError> {
2361        self.pretty_print_path_with_impl(
2362            |p| {
2363                print_prefix(p)?;
2364                if !p.empty_path {
2365                    write!(p, "::")?;
2366                }
2367
2368                Ok(())
2369            },
2370            self_ty,
2371            trait_ref,
2372        )?;
2373        self.empty_path = false;
2374        Ok(())
2375    }
2376
2377    fn print_path_with_simple(
2378        &mut self,
2379        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2380        disambiguated_data: &DisambiguatedDefPathData,
2381    ) -> Result<(), PrintError> {
2382        print_prefix(self)?;
2383
2384        // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
2385        if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
2386            return Ok(());
2387        }
2388
2389        let name = disambiguated_data.data.name();
2390        if !self.empty_path {
2391            write!(self, "::")?;
2392        }
2393
2394        if let DefPathDataName::Named(name) = name {
2395            if Ident::with_dummy_span(name).is_raw_guess() {
2396                write!(self, "r#")?;
2397            }
2398        }
2399
2400        let verbose = self.should_print_verbose();
2401        write!(self, "{}", disambiguated_data.as_sym(verbose))?;
2402
2403        self.empty_path = false;
2404
2405        Ok(())
2406    }
2407
2408    fn print_path_with_generic_args(
2409        &mut self,
2410        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2411        args: &[GenericArg<'tcx>],
2412    ) -> Result<(), PrintError> {
2413        print_prefix(self)?;
2414
2415        if !args.is_empty() {
2416            if self.in_value {
2417                write!(self, "::")?;
2418            }
2419            self.generic_delimiters(|p| p.comma_sep(args.iter().copied()))
2420        } else {
2421            Ok(())
2422        }
2423    }
2424}
2425
2426impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
2427    fn ty_infer_name(&self, id: ty::TyVid) -> Option<Symbol> {
2428        self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
2429    }
2430
2431    fn reset_type_limit(&mut self) {
2432        self.printed_type_count = 0;
2433    }
2434
2435    fn const_infer_name(&self, id: ty::ConstVid) -> Option<Symbol> {
2436        self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
2437    }
2438
2439    fn pretty_print_value_path(
2440        &mut self,
2441        def_id: DefId,
2442        args: &'tcx [GenericArg<'tcx>],
2443    ) -> Result<(), PrintError> {
2444        let was_in_value = std::mem::replace(&mut self.in_value, true);
2445        self.print_def_path(def_id, args)?;
2446        self.in_value = was_in_value;
2447
2448        Ok(())
2449    }
2450
2451    fn pretty_print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError>
2452    where
2453        T: Print<'tcx, Self> + TypeFoldable<TyCtxt<'tcx>>,
2454    {
2455        self.wrap_binder(value, WrapBinderMode::ForAll, |new_value, this| new_value.print(this))
2456    }
2457
2458    fn wrap_binder<T, C: FnOnce(&T, &mut Self) -> Result<(), PrintError>>(
2459        &mut self,
2460        value: &ty::Binder<'tcx, T>,
2461        mode: WrapBinderMode,
2462        f: C,
2463    ) -> Result<(), PrintError>
2464    where
2465        T: TypeFoldable<TyCtxt<'tcx>>,
2466    {
2467        let old_region_index = self.region_index;
2468        let (new_value, _) = self.name_all_regions(value, mode)?;
2469        f(&new_value, self)?;
2470        self.region_index = old_region_index;
2471        self.binder_depth -= 1;
2472        Ok(())
2473    }
2474
2475    fn typed_value(
2476        &mut self,
2477        f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2478        t: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2479        conversion: &str,
2480    ) -> Result<(), PrintError> {
2481        self.write_str("{")?;
2482        f(self)?;
2483        self.write_str(conversion)?;
2484        let was_in_value = std::mem::replace(&mut self.in_value, false);
2485        t(self)?;
2486        self.in_value = was_in_value;
2487        self.write_str("}")?;
2488        Ok(())
2489    }
2490
2491    fn generic_delimiters(
2492        &mut self,
2493        f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2494    ) -> Result<(), PrintError> {
2495        write!(self, "<")?;
2496
2497        let was_in_value = std::mem::replace(&mut self.in_value, false);
2498        f(self)?;
2499        self.in_value = was_in_value;
2500
2501        write!(self, ">")?;
2502        Ok(())
2503    }
2504
2505    fn should_truncate(&mut self) -> bool {
2506        !self.type_length_limit.value_within_limit(self.printed_type_count)
2507    }
2508
2509    fn should_print_optional_region(&self, region: ty::Region<'tcx>) -> bool {
2510        let highlight = self.region_highlight_mode;
2511        if highlight.region_highlighted(region).is_some() {
2512            return true;
2513        }
2514
2515        if self.should_print_verbose() {
2516            return true;
2517        }
2518
2519        if with_forced_trimmed_paths() {
2520            return false;
2521        }
2522
2523        let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2524
2525        match region.kind() {
2526            ty::ReEarlyParam(ref data) => data.is_named(),
2527
2528            ty::ReLateParam(ty::LateParamRegion { kind, .. }) => kind.is_named(self.tcx),
2529            ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2530            | ty::RePlaceholder(ty::Placeholder {
2531                bound: ty::BoundRegion { kind: br, .. }, ..
2532            }) => {
2533                if br.is_named(self.tcx) {
2534                    return true;
2535                }
2536
2537                if let Some((region, _)) = highlight.highlight_bound_region {
2538                    if br == region {
2539                        return true;
2540                    }
2541                }
2542
2543                false
2544            }
2545
2546            ty::ReVar(_) if identify_regions => true,
2547
2548            ty::ReVar(_) | ty::ReErased | ty::ReError(_) => false,
2549
2550            ty::ReStatic => true,
2551        }
2552    }
2553
2554    fn pretty_print_const_pointer<Prov: Provenance>(
2555        &mut self,
2556        p: Pointer<Prov>,
2557        ty: Ty<'tcx>,
2558    ) -> Result<(), PrintError> {
2559        let print = |this: &mut Self| {
2560            if this.print_alloc_ids {
2561                write!(this, "{p:?}")?;
2562            } else {
2563                write!(this, "&_")?;
2564            }
2565            Ok(())
2566        };
2567        self.typed_value(print, |this| this.print_type(ty), ": ")
2568    }
2569}
2570
2571// HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
2572impl<'tcx> FmtPrinter<'_, 'tcx> {
2573    pub fn pretty_print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), fmt::Error> {
2574        // Watch out for region highlights.
2575        let highlight = self.region_highlight_mode;
2576        if let Some(n) = highlight.region_highlighted(region) {
2577            write!(self, "'{n}")?;
2578            return Ok(());
2579        }
2580
2581        if self.should_print_verbose() {
2582            write!(self, "{region:?}")?;
2583            return Ok(());
2584        }
2585
2586        let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2587
2588        // These printouts are concise. They do not contain all the information
2589        // the user might want to diagnose an error, but there is basically no way
2590        // to fit that into a short string. Hence the recommendation to use
2591        // `explain_region()` or `note_and_explain_region()`.
2592        match region.kind() {
2593            ty::ReEarlyParam(data) => {
2594                write!(self, "{}", data.name)?;
2595                return Ok(());
2596            }
2597            ty::ReLateParam(ty::LateParamRegion { kind, .. }) => {
2598                if let Some(name) = kind.get_name(self.tcx) {
2599                    write!(self, "{name}")?;
2600                    return Ok(());
2601                }
2602            }
2603            ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2604            | ty::RePlaceholder(ty::Placeholder {
2605                bound: ty::BoundRegion { kind: br, .. }, ..
2606            }) => {
2607                if let Some(name) = br.get_name(self.tcx) {
2608                    write!(self, "{name}")?;
2609                    return Ok(());
2610                }
2611
2612                if let Some((region, counter)) = highlight.highlight_bound_region {
2613                    if br == region {
2614                        write!(self, "'{counter}")?;
2615                        return Ok(());
2616                    }
2617                }
2618            }
2619            ty::ReVar(region_vid) if identify_regions => {
2620                write!(self, "{region_vid:?}")?;
2621                return Ok(());
2622            }
2623            ty::ReVar(_) => {}
2624            ty::ReErased => {}
2625            ty::ReError(_) => {}
2626            ty::ReStatic => {
2627                write!(self, "'static")?;
2628                return Ok(());
2629            }
2630        }
2631
2632        write!(self, "'_")?;
2633
2634        Ok(())
2635    }
2636}
2637
2638/// Folds through bound vars and placeholders, naming them
2639struct RegionFolder<'a, 'tcx> {
2640    tcx: TyCtxt<'tcx>,
2641    current_index: ty::DebruijnIndex,
2642    region_map: UnordMap<ty::BoundRegion, ty::Region<'tcx>>,
2643    name: &'a mut (
2644                dyn FnMut(
2645        Option<ty::DebruijnIndex>, // Debruijn index of the folded late-bound region
2646        ty::DebruijnIndex,         // Index corresponding to binder level
2647        ty::BoundRegion,
2648    ) -> ty::Region<'tcx>
2649                    + 'a
2650            ),
2651}
2652
2653impl<'a, 'tcx> ty::TypeFolder<TyCtxt<'tcx>> for RegionFolder<'a, 'tcx> {
2654    fn cx(&self) -> TyCtxt<'tcx> {
2655        self.tcx
2656    }
2657
2658    fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>(
2659        &mut self,
2660        t: ty::Binder<'tcx, T>,
2661    ) -> ty::Binder<'tcx, T> {
2662        self.current_index.shift_in(1);
2663        let t = t.super_fold_with(self);
2664        self.current_index.shift_out(1);
2665        t
2666    }
2667
2668    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2669        match *t.kind() {
2670            _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2671                return t.super_fold_with(self);
2672            }
2673            _ => {}
2674        }
2675        t
2676    }
2677
2678    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2679        let name = &mut self.name;
2680        let region = match r.kind() {
2681            ty::ReBound(ty::BoundVarIndexKind::Bound(db), br) if db >= self.current_index => {
2682                *self.region_map.entry(br).or_insert_with(|| name(Some(db), self.current_index, br))
2683            }
2684            ty::RePlaceholder(ty::PlaceholderRegion {
2685                bound: ty::BoundRegion { kind, .. },
2686                ..
2687            }) => {
2688                // If this is an anonymous placeholder, don't rename. Otherwise, in some
2689                // async fns, we get a `for<'r> Send` bound
2690                match kind {
2691                    ty::BoundRegionKind::Anon | ty::BoundRegionKind::ClosureEnv => r,
2692                    _ => {
2693                        // Index doesn't matter, since this is just for naming and these never get bound
2694                        let br = ty::BoundRegion { var: ty::BoundVar::ZERO, kind };
2695                        *self
2696                            .region_map
2697                            .entry(br)
2698                            .or_insert_with(|| name(None, self.current_index, br))
2699                    }
2700                }
2701            }
2702            _ => return r,
2703        };
2704        if let ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn1), br) = region.kind() {
2705            assert_eq!(debruijn1, ty::INNERMOST);
2706            ty::Region::new_bound(self.tcx, self.current_index, br)
2707        } else {
2708            region
2709        }
2710    }
2711}
2712
2713// HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
2714// `region_index` and `used_region_names`.
2715impl<'tcx> FmtPrinter<'_, 'tcx> {
2716    pub fn name_all_regions<T>(
2717        &mut self,
2718        value: &ty::Binder<'tcx, T>,
2719        mode: WrapBinderMode,
2720    ) -> Result<(T, UnordMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
2721    where
2722        T: TypeFoldable<TyCtxt<'tcx>>,
2723    {
2724        fn name_by_region_index(
2725            index: usize,
2726            available_names: &mut Vec<Symbol>,
2727            num_available: usize,
2728        ) -> Symbol {
2729            if let Some(name) = available_names.pop() {
2730                name
2731            } else {
2732                Symbol::intern(&format!("'z{}", index - num_available))
2733            }
2734        }
2735
2736        debug!("name_all_regions");
2737
2738        // Replace any anonymous late-bound regions with named
2739        // variants, using new unique identifiers, so that we can
2740        // clearly differentiate between named and unnamed regions in
2741        // the output. We'll probably want to tweak this over time to
2742        // decide just how much information to give.
2743        if self.binder_depth == 0 {
2744            self.prepare_region_info(value);
2745        }
2746
2747        debug!("self.used_region_names: {:?}", self.used_region_names);
2748
2749        let mut empty = true;
2750        let mut start_or_continue = |p: &mut Self, start: &str, cont: &str| {
2751            let w = if empty {
2752                empty = false;
2753                start
2754            } else {
2755                cont
2756            };
2757            let _ = write!(p, "{w}");
2758        };
2759        let do_continue = |p: &mut Self, cont: Symbol| {
2760            let _ = write!(p, "{cont}");
2761        };
2762
2763        let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&format!("'{s}")));
2764
2765        let mut available_names = possible_names
2766            .filter(|name| !self.used_region_names.contains(name))
2767            .collect::<Vec<_>>();
2768        debug!(?available_names);
2769        let num_available = available_names.len();
2770
2771        let mut region_index = self.region_index;
2772        let mut next_name = |this: &Self| {
2773            let mut name;
2774
2775            loop {
2776                name = name_by_region_index(region_index, &mut available_names, num_available);
2777                region_index += 1;
2778
2779                if !this.used_region_names.contains(&name) {
2780                    break;
2781                }
2782            }
2783
2784            name
2785        };
2786
2787        // If we want to print verbosely, then print *all* binders, even if they
2788        // aren't named. Eventually, we might just want this as the default, but
2789        // this is not *quite* right and changes the ordering of some output
2790        // anyways.
2791        let (new_value, map) = if self.should_print_verbose() {
2792            for var in value.bound_vars().iter() {
2793                start_or_continue(self, mode.start_str(), ", ");
2794                write!(self, "{var:?}")?;
2795            }
2796            // Unconditionally render `unsafe<>`.
2797            if value.bound_vars().is_empty() && mode == WrapBinderMode::Unsafe {
2798                start_or_continue(self, mode.start_str(), "");
2799            }
2800            start_or_continue(self, "", "> ");
2801            (value.clone().skip_binder(), UnordMap::default())
2802        } else {
2803            let tcx = self.tcx;
2804
2805            let trim_path = with_forced_trimmed_paths();
2806            // Closure used in `RegionFolder` to create names for anonymous late-bound
2807            // regions. We use two `DebruijnIndex`es (one for the currently folded
2808            // late-bound region and the other for the binder level) to determine
2809            // whether a name has already been created for the currently folded region,
2810            // see issue #102392.
2811            let mut name = |lifetime_idx: Option<ty::DebruijnIndex>,
2812                            binder_level_idx: ty::DebruijnIndex,
2813                            br: ty::BoundRegion| {
2814                let (name, kind) = if let Some(name) = br.kind.get_name(tcx) {
2815                    (name, br.kind)
2816                } else {
2817                    let name = next_name(self);
2818                    (name, ty::BoundRegionKind::NamedAnon(name))
2819                };
2820
2821                if let Some(lt_idx) = lifetime_idx {
2822                    if lt_idx > binder_level_idx {
2823                        return ty::Region::new_bound(
2824                            tcx,
2825                            ty::INNERMOST,
2826                            ty::BoundRegion { var: br.var, kind },
2827                        );
2828                    }
2829                }
2830
2831                // Unconditionally render `unsafe<>`.
2832                if !trim_path || mode == WrapBinderMode::Unsafe {
2833                    start_or_continue(self, mode.start_str(), ", ");
2834                    do_continue(self, name);
2835                }
2836                ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { var: br.var, kind })
2837            };
2838            let mut folder = RegionFolder {
2839                tcx,
2840                current_index: ty::INNERMOST,
2841                name: &mut name,
2842                region_map: UnordMap::default(),
2843            };
2844            let new_value = value.clone().skip_binder().fold_with(&mut folder);
2845            let region_map = folder.region_map;
2846
2847            if mode == WrapBinderMode::Unsafe && region_map.is_empty() {
2848                start_or_continue(self, mode.start_str(), "");
2849            }
2850            start_or_continue(self, "", "> ");
2851
2852            (new_value, region_map)
2853        };
2854
2855        self.binder_depth += 1;
2856        self.region_index = region_index;
2857        Ok((new_value, map))
2858    }
2859
2860    fn prepare_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2861    where
2862        T: TypeFoldable<TyCtxt<'tcx>>,
2863    {
2864        struct RegionNameCollector<'tcx> {
2865            tcx: TyCtxt<'tcx>,
2866            used_region_names: FxHashSet<Symbol>,
2867            type_collector: SsoHashSet<Ty<'tcx>>,
2868        }
2869
2870        impl<'tcx> RegionNameCollector<'tcx> {
2871            fn new(tcx: TyCtxt<'tcx>) -> Self {
2872                RegionNameCollector {
2873                    tcx,
2874                    used_region_names: Default::default(),
2875                    type_collector: SsoHashSet::new(),
2876                }
2877            }
2878        }
2879
2880        impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for RegionNameCollector<'tcx> {
2881            fn visit_region(&mut self, r: ty::Region<'tcx>) {
2882                trace!("address: {:p}", r.0.0);
2883
2884                // Collect all named lifetimes. These allow us to prevent duplication
2885                // of already existing lifetime names when introducing names for
2886                // anonymous late-bound regions.
2887                if let Some(name) = r.get_name(self.tcx) {
2888                    self.used_region_names.insert(name);
2889                }
2890            }
2891
2892            // We collect types in order to prevent really large types from compiling for
2893            // a really long time. See issue #83150 for why this is necessary.
2894            fn visit_ty(&mut self, ty: Ty<'tcx>) {
2895                let not_previously_inserted = self.type_collector.insert(ty);
2896                if not_previously_inserted {
2897                    ty.super_visit_with(self)
2898                }
2899            }
2900        }
2901
2902        let mut collector = RegionNameCollector::new(self.tcx());
2903        value.visit_with(&mut collector);
2904        self.used_region_names = collector.used_region_names;
2905        self.region_index = 0;
2906    }
2907}
2908
2909impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2910where
2911    T: Print<'tcx, P> + TypeFoldable<TyCtxt<'tcx>>,
2912{
2913    fn print(&self, p: &mut P) -> Result<(), PrintError> {
2914        p.pretty_print_in_binder(self)
2915    }
2916}
2917
2918impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<'tcx, T>
2919where
2920    T: Print<'tcx, P>,
2921{
2922    fn print(&self, p: &mut P) -> Result<(), PrintError> {
2923        self.0.print(p)?;
2924        write!(p, ": ")?;
2925        self.1.print(p)?;
2926        Ok(())
2927    }
2928}
2929
2930/// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2931/// the trait path. That is, it will print `Trait<U>` instead of
2932/// `<T as Trait<U>>`.
2933#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
2934pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2935
2936impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintOnlyTraitPath<'tcx> {
2937    fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
2938        ty::tls::with(|tcx| {
2939            let trait_ref = tcx.short_string(self, path);
2940            rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
2941        })
2942    }
2943}
2944
2945impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
2946    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2947        fmt::Display::fmt(self, f)
2948    }
2949}
2950
2951/// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2952/// the trait path, and additionally tries to "sugar" `Fn(...)` trait bounds.
2953#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
2954pub struct TraitRefPrintSugared<'tcx>(ty::TraitRef<'tcx>);
2955
2956impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintSugared<'tcx> {
2957    fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
2958        ty::tls::with(|tcx| {
2959            let trait_ref = tcx.short_string(self, path);
2960            rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
2961        })
2962    }
2963}
2964
2965impl<'tcx> fmt::Debug for TraitRefPrintSugared<'tcx> {
2966    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2967        fmt::Display::fmt(self, f)
2968    }
2969}
2970
2971/// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2972/// the trait name. That is, it will print `Trait` instead of
2973/// `<T as Trait<U>>`.
2974#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2975pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
2976
2977impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
2978    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2979        fmt::Display::fmt(self, f)
2980    }
2981}
2982
2983#[extension(pub trait PrintTraitRefExt<'tcx>)]
2984impl<'tcx> ty::TraitRef<'tcx> {
2985    fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2986        TraitRefPrintOnlyTraitPath(self)
2987    }
2988
2989    fn print_trait_sugared(self) -> TraitRefPrintSugared<'tcx> {
2990        TraitRefPrintSugared(self)
2991    }
2992
2993    fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
2994        TraitRefPrintOnlyTraitName(self)
2995    }
2996}
2997
2998#[extension(pub trait PrintPolyTraitRefExt<'tcx>)]
2999impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
3000    fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
3001        self.map_bound(|tr| tr.print_only_trait_path())
3002    }
3003
3004    fn print_trait_sugared(self) -> ty::Binder<'tcx, TraitRefPrintSugared<'tcx>> {
3005        self.map_bound(|tr| tr.print_trait_sugared())
3006    }
3007}
3008
3009#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
3010pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
3011
3012impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
3013    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3014        fmt::Display::fmt(self, f)
3015    }
3016}
3017
3018#[extension(pub trait PrintTraitPredicateExt<'tcx>)]
3019impl<'tcx> ty::TraitPredicate<'tcx> {
3020    fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
3021        TraitPredPrintModifiersAndPath(self)
3022    }
3023}
3024
3025#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
3026pub struct TraitPredPrintWithBoundConstness<'tcx>(
3027    ty::TraitPredicate<'tcx>,
3028    Option<ty::BoundConstness>,
3029);
3030
3031impl<'tcx> fmt::Debug for TraitPredPrintWithBoundConstness<'tcx> {
3032    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3033        fmt::Display::fmt(self, f)
3034    }
3035}
3036
3037#[extension(pub trait PrintPolyTraitPredicateExt<'tcx>)]
3038impl<'tcx> ty::PolyTraitPredicate<'tcx> {
3039    fn print_modifiers_and_trait_path(
3040        self,
3041    ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
3042        self.map_bound(TraitPredPrintModifiersAndPath)
3043    }
3044
3045    fn print_with_bound_constness(
3046        self,
3047        constness: Option<ty::BoundConstness>,
3048    ) -> ty::Binder<'tcx, TraitPredPrintWithBoundConstness<'tcx>> {
3049        self.map_bound(|trait_pred| TraitPredPrintWithBoundConstness(trait_pred, constness))
3050    }
3051}
3052
3053#[derive(Debug, Copy, Clone, Lift)]
3054pub struct PrintClosureAsImpl<'tcx> {
3055    pub closure: ty::ClosureArgs<TyCtxt<'tcx>>,
3056}
3057
3058macro_rules! forward_display_to_print {
3059    ($($ty:ty),+) => {
3060        // Some of the $ty arguments may not actually use 'tcx
3061        $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty {
3062            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3063                ty::tls::with(|tcx| {
3064                    let mut p = FmtPrinter::new(tcx, Namespace::TypeNS);
3065                    tcx.lift(*self)
3066                        .expect("could not lift for printing")
3067                        .print(&mut p)?;
3068                    f.write_str(&p.into_buffer())?;
3069                    Ok(())
3070                })
3071            }
3072        })+
3073    };
3074}
3075
3076macro_rules! define_print {
3077    (($self:ident, $p:ident): $($ty:ty $print:block)+) => {
3078        $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
3079            fn print(&$self, $p: &mut P) -> Result<(), PrintError> {
3080                let _: () = $print;
3081                Ok(())
3082            }
3083        })+
3084    };
3085}
3086
3087macro_rules! define_print_and_forward_display {
3088    (($self:ident, $p:ident): $($ty:ty $print:block)+) => {
3089        define_print!(($self, $p): $($ty $print)*);
3090        forward_display_to_print!($($ty),+);
3091    };
3092}
3093
3094forward_display_to_print! {
3095    ty::Region<'tcx>,
3096    Ty<'tcx>,
3097    &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3098    ty::Const<'tcx>
3099}
3100
3101define_print! {
3102    (self, p):
3103
3104    ty::FnSig<'tcx> {
3105        write!(p, "{}", self.safety.prefix_str())?;
3106
3107        if self.abi != ExternAbi::Rust {
3108            write!(p, "extern {} ", self.abi)?;
3109        }
3110
3111        write!(p, "fn")?;
3112        p.pretty_print_fn_sig(self.inputs(), self.c_variadic, self.output())?;
3113    }
3114
3115    ty::TraitRef<'tcx> {
3116        write!(p, "<{} as {}>", self.self_ty(), self.print_only_trait_path())?;
3117    }
3118
3119    ty::AliasTy<'tcx> {
3120        let alias_term: ty::AliasTerm<'tcx> = (*self).into();
3121        alias_term.print(p)?;
3122    }
3123
3124    ty::AliasTerm<'tcx> {
3125        match self.kind(p.tcx()) {
3126            ty::AliasTermKind::InherentTy | ty::AliasTermKind::InherentConst => p.pretty_print_inherent_projection(*self)?,
3127            ty::AliasTermKind::ProjectionTy => {
3128                if !(p.should_print_verbose() || with_reduced_queries())
3129                    && p.tcx().is_impl_trait_in_trait(self.def_id)
3130                {
3131                    p.pretty_print_rpitit(self.def_id, self.args)?;
3132                } else {
3133                    p.print_def_path(self.def_id, self.args)?;
3134                }
3135            }
3136            ty::AliasTermKind::FreeTy
3137            | ty::AliasTermKind::FreeConst
3138            | ty::AliasTermKind::OpaqueTy
3139            | ty::AliasTermKind::UnevaluatedConst
3140            | ty::AliasTermKind::ProjectionConst => {
3141                p.print_def_path(self.def_id, self.args)?;
3142            }
3143        }
3144    }
3145
3146    ty::TraitPredicate<'tcx> {
3147        self.trait_ref.self_ty().print(p)?;
3148        write!(p, ": ")?;
3149        if let ty::PredicatePolarity::Negative = self.polarity {
3150            write!(p, "!")?;
3151        }
3152        self.trait_ref.print_trait_sugared().print(p)?;
3153    }
3154
3155    ty::HostEffectPredicate<'tcx> {
3156        let constness = match self.constness {
3157            ty::BoundConstness::Const => { "const" }
3158            ty::BoundConstness::Maybe => { "[const]" }
3159        };
3160        self.trait_ref.self_ty().print(p)?;
3161        write!(p, ": {constness} ")?;
3162        self.trait_ref.print_trait_sugared().print(p)?;
3163    }
3164
3165    ty::TypeAndMut<'tcx> {
3166        write!(p, "{}", self.mutbl.prefix_str())?;
3167        self.ty.print(p)?;
3168    }
3169
3170    ty::ClauseKind<'tcx> {
3171        match *self {
3172            ty::ClauseKind::Trait(ref data) => data.print(p)?,
3173            ty::ClauseKind::RegionOutlives(predicate) => predicate.print(p)?,
3174            ty::ClauseKind::TypeOutlives(predicate) => predicate.print(p)?,
3175            ty::ClauseKind::Projection(predicate) => predicate.print(p)?,
3176            ty::ClauseKind::HostEffect(predicate) => predicate.print(p)?,
3177            ty::ClauseKind::ConstArgHasType(ct, ty) => {
3178                write!(p, "the constant `")?;
3179                ct.print(p)?;
3180                write!(p, "` has type `")?;
3181                ty.print(p)?;
3182                write!(p, "`")?;
3183            },
3184            ty::ClauseKind::WellFormed(term) => {
3185                term.print(p)?;
3186                write!(p, " well-formed")?;
3187            }
3188            ty::ClauseKind::ConstEvaluatable(ct) => {
3189                write!(p, "the constant `")?;
3190                ct.print(p)?;
3191                write!(p, "` can be evaluated")?;
3192            }
3193            ty::ClauseKind::UnstableFeature(symbol) => {
3194                write!(p, "feature({symbol}) is enabled")?;
3195            }
3196        }
3197    }
3198
3199    ty::PredicateKind<'tcx> {
3200        match *self {
3201            ty::PredicateKind::Clause(data) => data.print(p)?,
3202            ty::PredicateKind::Subtype(predicate) => predicate.print(p)?,
3203            ty::PredicateKind::Coerce(predicate) => predicate.print(p)?,
3204            ty::PredicateKind::DynCompatible(trait_def_id) => {
3205                write!(p, "the trait `")?;
3206                p.print_def_path(trait_def_id, &[])?;
3207                write!(p, "` is dyn-compatible")?;
3208            }
3209            ty::PredicateKind::ConstEquate(c1, c2) => {
3210                write!(p, "the constant `")?;
3211                c1.print(p)?;
3212                write!(p, "` equals `")?;
3213                c2.print(p)?;
3214                write!(p, "`")?;
3215            }
3216            ty::PredicateKind::Ambiguous => write!(p, "ambiguous")?,
3217            ty::PredicateKind::NormalizesTo(data) => data.print(p)?,
3218            ty::PredicateKind::AliasRelate(t1, t2, dir) => {
3219                t1.print(p)?;
3220                write!(p, " {dir} ")?;
3221                t2.print(p)?;
3222            }
3223        }
3224    }
3225
3226    ty::ExistentialPredicate<'tcx> {
3227        match *self {
3228            ty::ExistentialPredicate::Trait(x) => x.print(p)?,
3229            ty::ExistentialPredicate::Projection(x) => x.print(p)?,
3230            ty::ExistentialPredicate::AutoTrait(def_id) => p.print_def_path(def_id, &[])?,
3231        }
3232    }
3233
3234    ty::ExistentialTraitRef<'tcx> {
3235        // Use a type that can't appear in defaults of type parameters.
3236        let dummy_self = Ty::new_fresh(p.tcx(), 0);
3237        let trait_ref = self.with_self_ty(p.tcx(), dummy_self);
3238        trait_ref.print_only_trait_path().print(p)?;
3239    }
3240
3241    ty::ExistentialProjection<'tcx> {
3242        let name = p.tcx().associated_item(self.def_id).name();
3243        // The args don't contain the self ty (as it has been erased) but the corresp.
3244        // generics do as the trait always has a self ty param. We need to offset.
3245        let args = &self.args[p.tcx().generics_of(self.def_id).parent_count - 1..];
3246        p.print_path_with_generic_args(|p| write!(p, "{name}"), args)?;
3247        write!(p, " = ")?;
3248        self.term.print(p)?;
3249    }
3250
3251    ty::ProjectionPredicate<'tcx> {
3252        self.projection_term.print(p)?;
3253        write!(p, " == ")?;
3254        p.reset_type_limit();
3255        self.term.print(p)?;
3256    }
3257
3258    ty::SubtypePredicate<'tcx> {
3259        self.a.print(p)?;
3260        write!(p, " <: ")?;
3261        p.reset_type_limit();
3262        self.b.print(p)?;
3263    }
3264
3265    ty::CoercePredicate<'tcx> {
3266        self.a.print(p)?;
3267        write!(p, " -> ")?;
3268        p.reset_type_limit();
3269        self.b.print(p)?;
3270    }
3271
3272    ty::NormalizesTo<'tcx> {
3273        self.alias.print(p)?;
3274        write!(p, " normalizes-to ")?;
3275        p.reset_type_limit();
3276        self.term.print(p)?;
3277    }
3278
3279    ty::PlaceholderType<'tcx> {
3280        match self.bound.kind {
3281            ty::BoundTyKind::Anon => write!(p, "{self:?}")?,
3282            ty::BoundTyKind::Param(def_id) => match p.should_print_verbose() {
3283                true => write!(p, "{self:?}")?,
3284                false => write!(p, "{}", p.tcx().item_name(def_id))?,
3285            },
3286        }
3287    }
3288}
3289
3290define_print_and_forward_display! {
3291    (self, p):
3292
3293    &'tcx ty::List<Ty<'tcx>> {
3294        write!(p, "{{")?;
3295        p.comma_sep(self.iter())?;
3296        write!(p, "}}")?;
3297    }
3298
3299    TraitRefPrintOnlyTraitPath<'tcx> {
3300        p.print_def_path(self.0.def_id, self.0.args)?;
3301    }
3302
3303    TraitRefPrintSugared<'tcx> {
3304        if !with_reduced_queries()
3305            && p.tcx().trait_def(self.0.def_id).paren_sugar
3306            && let ty::Tuple(args) = self.0.args.type_at(1).kind()
3307        {
3308            write!(p, "{}(", p.tcx().item_name(self.0.def_id))?;
3309            for (i, arg) in args.iter().enumerate() {
3310                if i > 0 {
3311                    write!(p, ", ")?;
3312                }
3313                arg.print(p)?;
3314            }
3315            write!(p, ")")?;
3316        } else {
3317            p.print_def_path(self.0.def_id, self.0.args)?;
3318        }
3319    }
3320
3321    TraitRefPrintOnlyTraitName<'tcx> {
3322        p.print_def_path(self.0.def_id, &[])?;
3323    }
3324
3325    TraitPredPrintModifiersAndPath<'tcx> {
3326        if let ty::PredicatePolarity::Negative = self.0.polarity {
3327            write!(p, "!")?;
3328        }
3329        self.0.trait_ref.print_trait_sugared().print(p)?;
3330    }
3331
3332    TraitPredPrintWithBoundConstness<'tcx> {
3333        self.0.trait_ref.self_ty().print(p)?;
3334        write!(p, ": ")?;
3335        if let Some(constness) = self.1 {
3336            p.pretty_print_bound_constness(constness)?;
3337        }
3338        if let ty::PredicatePolarity::Negative = self.0.polarity {
3339            write!(p, "!")?;
3340        }
3341        self.0.trait_ref.print_trait_sugared().print(p)?;
3342    }
3343
3344    PrintClosureAsImpl<'tcx> {
3345        p.pretty_print_closure_as_impl(self.closure)?;
3346    }
3347
3348    ty::ParamTy {
3349        write!(p, "{}", self.name)?;
3350    }
3351
3352    ty::ParamConst {
3353        write!(p, "{}", self.name)?;
3354    }
3355
3356    ty::Term<'tcx> {
3357      match self.kind() {
3358        ty::TermKind::Ty(ty) => ty.print(p)?,
3359        ty::TermKind::Const(c) => c.print(p)?,
3360      }
3361    }
3362
3363    ty::Predicate<'tcx> {
3364        self.kind().print(p)?;
3365    }
3366
3367    ty::Clause<'tcx> {
3368        self.kind().print(p)?;
3369    }
3370
3371    GenericArg<'tcx> {
3372        match self.kind() {
3373            GenericArgKind::Lifetime(lt) => lt.print(p)?,
3374            GenericArgKind::Type(ty) => ty.print(p)?,
3375            GenericArgKind::Const(ct) => ct.print(p)?,
3376        }
3377    }
3378}
3379
3380fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
3381    // Iterate all (non-anonymous) local crate items no matter where they are defined.
3382    for id in tcx.hir_free_items() {
3383        if tcx.def_kind(id.owner_id) == DefKind::Use {
3384            continue;
3385        }
3386
3387        let item = tcx.hir_item(id);
3388        let Some(ident) = item.kind.ident() else { continue };
3389
3390        let def_id = item.owner_id.to_def_id();
3391        let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
3392        collect_fn(&ident, ns, def_id);
3393    }
3394
3395    // Now take care of extern crate items.
3396    let queue = &mut Vec::new();
3397    let mut seen_defs: DefIdSet = Default::default();
3398
3399    for &cnum in tcx.crates(()).iter() {
3400        // Ignore crates that are not direct dependencies.
3401        match tcx.extern_crate(cnum) {
3402            None => continue,
3403            Some(extern_crate) => {
3404                if !extern_crate.is_direct() {
3405                    continue;
3406                }
3407            }
3408        }
3409
3410        queue.push(cnum.as_def_id());
3411    }
3412
3413    // Iterate external crate defs but be mindful about visibility
3414    while let Some(def) = queue.pop() {
3415        for child in tcx.module_children(def).iter() {
3416            if !child.vis.is_public() {
3417                continue;
3418            }
3419
3420            match child.res {
3421                def::Res::Def(DefKind::AssocTy, _) => {}
3422                def::Res::Def(DefKind::TyAlias, _) => {}
3423                def::Res::Def(defkind, def_id) => {
3424                    if let Some(ns) = defkind.ns() {
3425                        collect_fn(&child.ident, ns, def_id);
3426                    }
3427
3428                    if defkind.is_module_like() && seen_defs.insert(def_id) {
3429                        queue.push(def_id);
3430                    }
3431                }
3432                _ => {}
3433            }
3434        }
3435    }
3436}
3437
3438/// The purpose of this function is to collect public symbols names that are unique across all
3439/// crates in the build. Later, when printing about types we can use those names instead of the
3440/// full exported path to them.
3441///
3442/// So essentially, if a symbol name can only be imported from one place for a type, and as
3443/// long as it was not glob-imported anywhere in the current crate, we can trim its printed
3444/// path and print only the name.
3445///
3446/// This has wide implications on error messages with types, for example, shortening
3447/// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
3448///
3449/// The implementation uses similar import discovery logic to that of 'use' suggestions.
3450///
3451/// See also [`with_no_trimmed_paths!`].
3452// this is pub to be able to intra-doc-link it
3453pub fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> DefIdMap<Symbol> {
3454    // Trimming paths is expensive and not optimized, since we expect it to only be used for error
3455    // reporting. Record the fact that we did it, so we can abort if we later found it was
3456    // unnecessary.
3457    //
3458    // The `rustc_middle::ty::print::with_no_trimmed_paths` wrapper can be used to suppress this
3459    // checking, in exchange for full paths being formatted.
3460    tcx.sess.record_trimmed_def_paths();
3461
3462    // Once constructed, unique namespace+symbol pairs will have a `Some(_)` entry, while
3463    // non-unique pairs will have a `None` entry.
3464    let unique_symbols_rev: &mut FxIndexMap<(Namespace, Symbol), Option<DefId>> =
3465        &mut FxIndexMap::default();
3466
3467    for symbol_set in tcx.resolutions(()).glob_map.values() {
3468        for symbol in symbol_set {
3469            unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
3470            unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
3471            unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
3472        }
3473    }
3474
3475    for_each_def(tcx, |ident, ns, def_id| match unique_symbols_rev.entry((ns, ident.name)) {
3476        IndexEntry::Occupied(mut v) => match v.get() {
3477            None => {}
3478            Some(existing) => {
3479                if *existing != def_id {
3480                    v.insert(None);
3481                }
3482            }
3483        },
3484        IndexEntry::Vacant(v) => {
3485            v.insert(Some(def_id));
3486        }
3487    });
3488
3489    // Put the symbol from all the unique namespace+symbol pairs into `map`.
3490    let mut map: DefIdMap<Symbol> = Default::default();
3491    for ((_, symbol), opt_def_id) in unique_symbols_rev.drain(..) {
3492        use std::collections::hash_map::Entry::{Occupied, Vacant};
3493
3494        if let Some(def_id) = opt_def_id {
3495            match map.entry(def_id) {
3496                Occupied(mut v) => {
3497                    // A single DefId can be known under multiple names (e.g.,
3498                    // with a `pub use ... as ...;`). We need to ensure that the
3499                    // name placed in this map is chosen deterministically, so
3500                    // if we find multiple names (`symbol`) resolving to the
3501                    // same `def_id`, we prefer the lexicographically smallest
3502                    // name.
3503                    //
3504                    // Any stable ordering would be fine here though.
3505                    if *v.get() != symbol && v.get().as_str() > symbol.as_str() {
3506                        v.insert(symbol);
3507                    }
3508                }
3509                Vacant(v) => {
3510                    v.insert(symbol);
3511                }
3512            }
3513        }
3514    }
3515
3516    map
3517}
3518
3519pub fn provide(providers: &mut Providers) {
3520    *providers = Providers { trimmed_def_paths, ..*providers };
3521}
3522
3523pub struct OpaqueFnEntry<'tcx> {
3524    kind: ty::ClosureKind,
3525    return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,
3526}