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