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