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::{CRATE_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
23use 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#[derive(Copy, Clone, PartialEq, Eq, Debug)]
72pub enum RtnMode {
73 ForDiagnostic,
75 ForSignature,
77 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 fn with_reduced_queries(ReducedQueriesGuard, REDUCED_QUERIES);
123 fn with_forced_impl_filename_line(ForcedImplGuard, FORCE_IMPL_FILENAME_LINE);
128 fn with_crate_prefix(CratePrefixGuard, SHOULD_PREFIX_WITH_CRATE);
130 fn with_no_trimmed_paths(NoTrimmedGuard, NO_TRIMMED_PATH);
134 fn with_forced_trimmed_paths(ForceTrimmedGuard, FORCE_TRIMMED_PATH);
135 fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH);
138 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
157pub macro with_types_for_suggestion($e:expr) {{
162 let _guard = $crate::ty::print::pretty::RtnModeHelper::with(RtnMode::ForSuggestion);
163 $e
164}}
165
166pub macro with_types_for_signature($e:expr) {{
170 let _guard = $crate::ty::print::pretty::RtnModeHelper::with(RtnMode::ForSignature);
171 $e
172}}
173
174pub 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#[derive(Copy, Clone, Default)]
205pub struct RegionHighlightMode<'tcx> {
206 highlight_regions: [Option<(ty::Region<'tcx>, usize)>; 3],
209
210 highlight_bound_region: Option<(ty::BoundRegionKind, usize)>,
218}
219
220impl<'tcx> RegionHighlightMode<'tcx> {
221 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 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 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 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 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
272pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
274 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 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 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 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 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 fn generic_delimiters(
359 &mut self,
360 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
361 ) -> Result<(), PrintError>;
362
363 fn should_print_region(&self, region: ty::Region<'tcx>) -> bool;
367
368 fn reset_type_limit(&mut self) {}
369
370 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 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 .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 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 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 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 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 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 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 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 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 if span.is_dummy() {
524 self.path_crate(cnum)?;
525 return Ok(true);
526 }
527
528 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 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 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
624 let reexport = self
627 .tcx()
628 .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 return Ok(false);
640 }
641 }
642 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 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 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(_, s) => match self.should_print_verbose() {
799 true => p!(write("{:?}", ty.kind())),
800 false => p!(write("{s}")),
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 ty::DynStar => p!("dyn* "),
814 }
815 p!(print(data));
816 if print_r {
817 p!(" + ", print(r), ")");
818 }
819 }
820 ty::Foreign(def_id) => {
821 p!(print_def_path(def_id, &[]));
822 }
823 ty::Alias(ty::Projection | ty::Inherent | ty::Free, ref data) => {
824 p!(print(data))
825 }
826 ty::Placeholder(placeholder) => match placeholder.bound.kind {
827 ty::BoundTyKind::Anon => p!(write("{placeholder:?}")),
828 ty::BoundTyKind::Param(_, name) => match self.should_print_verbose() {
829 true => p!(write("{:?}", ty.kind())),
830 false => p!(write("{name}")),
831 },
832 },
833 ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
834 if self.should_print_verbose() {
843 p!(write("Opaque({:?}, {})", def_id, args.print_as_list()));
845 return Ok(());
846 }
847
848 let parent = self.tcx().parent(def_id);
849 match self.tcx().def_kind(parent) {
850 DefKind::TyAlias | DefKind::AssocTy => {
851 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id: d, .. }) =
854 *self.tcx().type_of(parent).instantiate_identity().kind()
855 {
856 if d == def_id {
857 p!(print_def_path(parent, args));
860 return Ok(());
861 }
862 }
863 p!(print_def_path(def_id, args));
865 return Ok(());
866 }
867 _ => {
868 if with_reduced_queries() {
869 p!(print_def_path(def_id, &[]));
870 return Ok(());
871 } else {
872 return self.pretty_print_opaque_impl_type(def_id, args);
873 }
874 }
875 }
876 }
877 ty::Str => p!("str"),
878 ty::Coroutine(did, args) => {
879 p!("{{");
880 let coroutine_kind = self.tcx().coroutine_kind(did).unwrap();
881 let should_print_movability = self.should_print_verbose()
882 || matches!(coroutine_kind, hir::CoroutineKind::Coroutine(_));
883
884 if should_print_movability {
885 match coroutine_kind.movability() {
886 hir::Movability::Movable => {}
887 hir::Movability::Static => p!("static "),
888 }
889 }
890
891 if !self.should_print_verbose() {
892 p!(write("{}", coroutine_kind));
893 if coroutine_kind.is_fn_like() {
894 let did_of_the_fn_item = self.tcx().parent(did);
901 p!(" of ", print_def_path(did_of_the_fn_item, args), "()");
902 } else if let Some(local_did) = did.as_local() {
903 let span = self.tcx().def_span(local_did);
904 p!(write(
905 "@{}",
906 self.tcx().sess.source_map().span_to_embeddable_string(span)
909 ));
910 } else {
911 p!("@", print_def_path(did, args));
912 }
913 } else {
914 p!(print_def_path(did, args));
915 p!(
916 " upvar_tys=",
917 print(args.as_coroutine().tupled_upvars_ty()),
918 " resume_ty=",
919 print(args.as_coroutine().resume_ty()),
920 " yield_ty=",
921 print(args.as_coroutine().yield_ty()),
922 " return_ty=",
923 print(args.as_coroutine().return_ty()),
924 " witness=",
925 print(args.as_coroutine().witness())
926 );
927 }
928
929 p!("}}")
930 }
931 ty::CoroutineWitness(did, args) => {
932 p!(write("{{"));
933 if !self.tcx().sess.verbose_internals() {
934 p!("coroutine witness");
935 if let Some(did) = did.as_local() {
936 let span = self.tcx().def_span(did);
937 p!(write(
938 "@{}",
939 self.tcx().sess.source_map().span_to_embeddable_string(span)
942 ));
943 } else {
944 p!(write("@"), print_def_path(did, args));
945 }
946 } else {
947 p!(print_def_path(did, args));
948 }
949
950 p!("}}")
951 }
952 ty::Closure(did, args) => {
953 p!(write("{{"));
954 if !self.should_print_verbose() {
955 p!(write("closure"));
956 if self.should_truncate() {
957 write!(self, "@...}}")?;
958 return Ok(());
959 } else {
960 if let Some(did) = did.as_local() {
961 if self.tcx().sess.opts.unstable_opts.span_free_formats {
962 p!("@", print_def_path(did.to_def_id(), args));
963 } else {
964 let span = self.tcx().def_span(did);
965 let preference = if with_forced_trimmed_paths() {
966 FileNameDisplayPreference::Short
967 } else {
968 FileNameDisplayPreference::Remapped
969 };
970 p!(write(
971 "@{}",
972 self.tcx().sess.source_map().span_to_string(span, preference)
975 ));
976 }
977 } else {
978 p!(write("@"), print_def_path(did, args));
979 }
980 }
981 } else {
982 p!(print_def_path(did, args));
983 p!(
984 " closure_kind_ty=",
985 print(args.as_closure().kind_ty()),
986 " closure_sig_as_fn_ptr_ty=",
987 print(args.as_closure().sig_as_fn_ptr_ty()),
988 " upvar_tys=",
989 print(args.as_closure().tupled_upvars_ty())
990 );
991 }
992 p!("}}");
993 }
994 ty::CoroutineClosure(did, args) => {
995 p!(write("{{"));
996 if !self.should_print_verbose() {
997 match self.tcx().coroutine_kind(self.tcx().coroutine_for_closure(did)).unwrap()
998 {
999 hir::CoroutineKind::Desugared(
1000 hir::CoroutineDesugaring::Async,
1001 hir::CoroutineSource::Closure,
1002 ) => p!("async closure"),
1003 hir::CoroutineKind::Desugared(
1004 hir::CoroutineDesugaring::AsyncGen,
1005 hir::CoroutineSource::Closure,
1006 ) => p!("async gen closure"),
1007 hir::CoroutineKind::Desugared(
1008 hir::CoroutineDesugaring::Gen,
1009 hir::CoroutineSource::Closure,
1010 ) => p!("gen closure"),
1011 _ => unreachable!(
1012 "coroutine from coroutine-closure should have CoroutineSource::Closure"
1013 ),
1014 }
1015 if let Some(did) = did.as_local() {
1016 if self.tcx().sess.opts.unstable_opts.span_free_formats {
1017 p!("@", print_def_path(did.to_def_id(), args));
1018 } else {
1019 let span = self.tcx().def_span(did);
1020 let preference = if with_forced_trimmed_paths() {
1021 FileNameDisplayPreference::Short
1022 } else {
1023 FileNameDisplayPreference::Remapped
1024 };
1025 p!(write(
1026 "@{}",
1027 self.tcx().sess.source_map().span_to_string(span, preference)
1030 ));
1031 }
1032 } else {
1033 p!(write("@"), print_def_path(did, args));
1034 }
1035 } else {
1036 p!(print_def_path(did, args));
1037 p!(
1038 " closure_kind_ty=",
1039 print(args.as_coroutine_closure().kind_ty()),
1040 " signature_parts_ty=",
1041 print(args.as_coroutine_closure().signature_parts_ty()),
1042 " upvar_tys=",
1043 print(args.as_coroutine_closure().tupled_upvars_ty()),
1044 " coroutine_captures_by_ref_ty=",
1045 print(args.as_coroutine_closure().coroutine_captures_by_ref_ty()),
1046 " coroutine_witness_ty=",
1047 print(args.as_coroutine_closure().coroutine_witness_ty())
1048 );
1049 }
1050 p!("}}");
1051 }
1052 ty::Array(ty, sz) => p!("[", print(ty), "; ", print(sz), "]"),
1053 ty::Slice(ty) => p!("[", print(ty), "]"),
1054 }
1055
1056 Ok(())
1057 }
1058
1059 fn pretty_print_opaque_impl_type(
1060 &mut self,
1061 def_id: DefId,
1062 args: ty::GenericArgsRef<'tcx>,
1063 ) -> Result<(), PrintError> {
1064 let tcx = self.tcx();
1065
1066 let bounds = tcx.explicit_item_bounds(def_id);
1069
1070 let mut traits = FxIndexMap::default();
1071 let mut fn_traits = FxIndexMap::default();
1072 let mut has_sized_bound = false;
1073 let mut has_negative_sized_bound = false;
1074 let mut lifetimes = SmallVec::<[ty::Region<'tcx>; 1]>::new();
1075
1076 for (predicate, _) in bounds.iter_instantiated_copied(tcx, args) {
1077 let bound_predicate = predicate.kind();
1078
1079 match bound_predicate.skip_binder() {
1080 ty::ClauseKind::Trait(pred) => {
1081 if tcx.is_lang_item(pred.def_id(), LangItem::Sized) {
1083 match pred.polarity {
1084 ty::PredicatePolarity::Positive => {
1085 has_sized_bound = true;
1086 continue;
1087 }
1088 ty::PredicatePolarity::Negative => has_negative_sized_bound = true,
1089 }
1090 }
1091
1092 self.insert_trait_and_projection(
1093 bound_predicate.rebind(pred),
1094 None,
1095 &mut traits,
1096 &mut fn_traits,
1097 );
1098 }
1099 ty::ClauseKind::Projection(pred) => {
1100 let proj = bound_predicate.rebind(pred);
1101 let trait_ref = proj.map_bound(|proj| TraitPredicate {
1102 trait_ref: proj.projection_term.trait_ref(tcx),
1103 polarity: ty::PredicatePolarity::Positive,
1104 });
1105
1106 self.insert_trait_and_projection(
1107 trait_ref,
1108 Some((proj.item_def_id(), proj.term())),
1109 &mut traits,
1110 &mut fn_traits,
1111 );
1112 }
1113 ty::ClauseKind::TypeOutlives(outlives) => {
1114 lifetimes.push(outlives.1);
1115 }
1116 _ => {}
1117 }
1118 }
1119
1120 write!(self, "impl ")?;
1121
1122 let mut first = true;
1123 let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !has_sized_bound;
1125
1126 for ((bound_args_and_self_ty, is_async), entry) in fn_traits {
1127 write!(self, "{}", if first { "" } else { " + " })?;
1128 write!(self, "{}", if paren_needed { "(" } else { "" })?;
1129
1130 let trait_def_id = if is_async {
1131 tcx.async_fn_trait_kind_to_def_id(entry.kind).expect("expected AsyncFn lang items")
1132 } else {
1133 tcx.fn_trait_kind_to_def_id(entry.kind).expect("expected Fn lang items")
1134 };
1135
1136 if let Some(return_ty) = entry.return_ty {
1137 self.wrap_binder(
1138 &bound_args_and_self_ty,
1139 WrapBinderMode::ForAll,
1140 |(args, _), cx| {
1141 define_scoped_cx!(cx);
1142 p!(write("{}", tcx.item_name(trait_def_id)));
1143 p!("(");
1144
1145 for (idx, ty) in args.iter().enumerate() {
1146 if idx > 0 {
1147 p!(", ");
1148 }
1149 p!(print(ty));
1150 }
1151
1152 p!(")");
1153 if let Some(ty) = return_ty.skip_binder().as_type() {
1154 if !ty.is_unit() {
1155 p!(" -> ", print(return_ty));
1156 }
1157 }
1158 p!(write("{}", if paren_needed { ")" } else { "" }));
1159
1160 first = false;
1161 Ok(())
1162 },
1163 )?;
1164 } else {
1165 traits.insert(
1167 bound_args_and_self_ty.map_bound(|(args, self_ty)| ty::TraitPredicate {
1168 polarity: ty::PredicatePolarity::Positive,
1169 trait_ref: ty::TraitRef::new(
1170 tcx,
1171 trait_def_id,
1172 [self_ty, Ty::new_tup(tcx, args)],
1173 ),
1174 }),
1175 FxIndexMap::default(),
1176 );
1177 }
1178 }
1179
1180 for (trait_pred, assoc_items) in traits {
1182 write!(self, "{}", if first { "" } else { " + " })?;
1183
1184 self.wrap_binder(&trait_pred, WrapBinderMode::ForAll, |trait_pred, cx| {
1185 define_scoped_cx!(cx);
1186
1187 if trait_pred.polarity == ty::PredicatePolarity::Negative {
1188 p!("!");
1189 }
1190 p!(print(trait_pred.trait_ref.print_only_trait_name()));
1191
1192 let generics = tcx.generics_of(trait_pred.def_id());
1193 let own_args = generics.own_args_no_defaults(tcx, trait_pred.trait_ref.args);
1194
1195 if !own_args.is_empty() || !assoc_items.is_empty() {
1196 let mut first = true;
1197
1198 for ty in own_args {
1199 if first {
1200 p!("<");
1201 first = false;
1202 } else {
1203 p!(", ");
1204 }
1205 p!(print(ty));
1206 }
1207
1208 for (assoc_item_def_id, term) in assoc_items {
1209 let term = if let Some(ty) = term.skip_binder().as_type()
1212 && let ty::Alias(ty::Projection, proj) = ty.kind()
1213 && let Some(assoc) = tcx.opt_associated_item(proj.def_id)
1214 && assoc
1215 .trait_container(tcx)
1216 .is_some_and(|def_id| tcx.is_lang_item(def_id, LangItem::Coroutine))
1217 && assoc.opt_name() == Some(rustc_span::sym::Return)
1218 {
1219 if let ty::Coroutine(_, args) = args.type_at(0).kind() {
1220 let return_ty = args.as_coroutine().return_ty();
1221 if !return_ty.is_ty_var() {
1222 return_ty.into()
1223 } else {
1224 continue;
1225 }
1226 } else {
1227 continue;
1228 }
1229 } else {
1230 term.skip_binder()
1231 };
1232
1233 if first {
1234 p!("<");
1235 first = false;
1236 } else {
1237 p!(", ");
1238 }
1239
1240 p!(write("{} = ", tcx.associated_item(assoc_item_def_id).name()));
1241
1242 match term.unpack() {
1243 TermKind::Ty(ty) => p!(print(ty)),
1244 TermKind::Const(c) => p!(print(c)),
1245 };
1246 }
1247
1248 if !first {
1249 p!(">");
1250 }
1251 }
1252
1253 first = false;
1254 Ok(())
1255 })?;
1256 }
1257
1258 let add_sized = has_sized_bound && (first || has_negative_sized_bound);
1259 let add_maybe_sized = !has_sized_bound && !has_negative_sized_bound;
1260 if add_sized || add_maybe_sized {
1261 if !first {
1262 write!(self, " + ")?;
1263 }
1264 if add_maybe_sized {
1265 write!(self, "?")?;
1266 }
1267 write!(self, "Sized")?;
1268 }
1269
1270 if !with_forced_trimmed_paths() {
1271 for re in lifetimes {
1272 write!(self, " + ")?;
1273 self.print_region(re)?;
1274 }
1275 }
1276
1277 Ok(())
1278 }
1279
1280 fn insert_trait_and_projection(
1283 &mut self,
1284 trait_pred: ty::PolyTraitPredicate<'tcx>,
1285 proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
1286 traits: &mut FxIndexMap<
1287 ty::PolyTraitPredicate<'tcx>,
1288 FxIndexMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,
1289 >,
1290 fn_traits: &mut FxIndexMap<
1291 (ty::Binder<'tcx, (&'tcx ty::List<Ty<'tcx>>, Ty<'tcx>)>, bool),
1292 OpaqueFnEntry<'tcx>,
1293 >,
1294 ) {
1295 let tcx = self.tcx();
1296 let trait_def_id = trait_pred.def_id();
1297
1298 let fn_trait_and_async = if let Some(kind) = tcx.fn_trait_kind_from_def_id(trait_def_id) {
1299 Some((kind, false))
1300 } else if let Some(kind) = tcx.async_fn_trait_kind_from_def_id(trait_def_id) {
1301 Some((kind, true))
1302 } else {
1303 None
1304 };
1305
1306 if trait_pred.polarity() == ty::PredicatePolarity::Positive
1307 && let Some((kind, is_async)) = fn_trait_and_async
1308 && let ty::Tuple(types) = *trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
1309 {
1310 let entry = fn_traits
1311 .entry((trait_pred.rebind((types, trait_pred.skip_binder().self_ty())), is_async))
1312 .or_insert_with(|| OpaqueFnEntry { kind, return_ty: None });
1313 if kind.extends(entry.kind) {
1314 entry.kind = kind;
1315 }
1316 if let Some((proj_def_id, proj_ty)) = proj_ty
1317 && tcx.item_name(proj_def_id) == sym::Output
1318 {
1319 entry.return_ty = Some(proj_ty);
1320 }
1321 return;
1322 }
1323
1324 traits.entry(trait_pred).or_default().extend(proj_ty);
1326 }
1327
1328 fn pretty_print_inherent_projection(
1329 &mut self,
1330 alias_ty: ty::AliasTerm<'tcx>,
1331 ) -> Result<(), PrintError> {
1332 let def_key = self.tcx().def_key(alias_ty.def_id);
1333 self.path_generic_args(
1334 |cx| {
1335 cx.path_append(
1336 |cx| cx.path_qualified(alias_ty.self_ty(), None),
1337 &def_key.disambiguated_data,
1338 )
1339 },
1340 &alias_ty.args[1..],
1341 )
1342 }
1343
1344 fn pretty_print_rpitit(
1345 &mut self,
1346 def_id: DefId,
1347 args: ty::GenericArgsRef<'tcx>,
1348 ) -> Result<(), PrintError> {
1349 let fn_args = if self.tcx().features().return_type_notation()
1350 && let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, .. }) =
1351 self.tcx().opt_rpitit_info(def_id)
1352 && let ty::Alias(_, alias_ty) =
1353 self.tcx().fn_sig(fn_def_id).skip_binder().output().skip_binder().kind()
1354 && alias_ty.def_id == def_id
1355 && let generics = self.tcx().generics_of(fn_def_id)
1356 && generics.own_params.iter().all(|param| matches!(param.kind, ty::GenericParamDefKind::Lifetime))
1358 {
1359 let num_args = generics.count();
1360 Some((fn_def_id, &args[..num_args]))
1361 } else {
1362 None
1363 };
1364
1365 match (fn_args, RTN_MODE.with(|c| c.get())) {
1366 (Some((fn_def_id, fn_args)), RtnMode::ForDiagnostic) => {
1367 self.pretty_print_opaque_impl_type(def_id, args)?;
1368 write!(self, " {{ ")?;
1369 self.print_def_path(fn_def_id, fn_args)?;
1370 write!(self, "(..) }}")?;
1371 }
1372 (Some((fn_def_id, fn_args)), RtnMode::ForSuggestion) => {
1373 self.print_def_path(fn_def_id, fn_args)?;
1374 write!(self, "(..)")?;
1375 }
1376 _ => {
1377 self.pretty_print_opaque_impl_type(def_id, args)?;
1378 }
1379 }
1380
1381 Ok(())
1382 }
1383
1384 fn ty_infer_name(&self, _: ty::TyVid) -> Option<Symbol> {
1385 None
1386 }
1387
1388 fn const_infer_name(&self, _: ty::ConstVid) -> Option<Symbol> {
1389 None
1390 }
1391
1392 fn pretty_print_dyn_existential(
1393 &mut self,
1394 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1395 ) -> Result<(), PrintError> {
1396 let mut first = true;
1398
1399 if let Some(bound_principal) = predicates.principal() {
1400 self.wrap_binder(&bound_principal, WrapBinderMode::ForAll, |principal, cx| {
1401 define_scoped_cx!(cx);
1402 p!(print_def_path(principal.def_id, &[]));
1403
1404 let mut resugared = false;
1405
1406 let fn_trait_kind = cx.tcx().fn_trait_kind_from_def_id(principal.def_id);
1408 if !cx.should_print_verbose() && fn_trait_kind.is_some() {
1409 if let ty::Tuple(tys) = principal.args.type_at(0).kind() {
1410 let mut projections = predicates.projection_bounds();
1411 if let (Some(proj), None) = (projections.next(), projections.next()) {
1412 p!(pretty_fn_sig(
1413 tys,
1414 false,
1415 proj.skip_binder().term.as_type().expect("Return type was a const")
1416 ));
1417 resugared = true;
1418 }
1419 }
1420 }
1421
1422 if !resugared {
1425 let principal_with_self =
1426 principal.with_self_ty(cx.tcx(), cx.tcx().types.trait_object_dummy_self);
1427
1428 let args = cx
1429 .tcx()
1430 .generics_of(principal_with_self.def_id)
1431 .own_args_no_defaults(cx.tcx(), principal_with_self.args);
1432
1433 let bound_principal_with_self = bound_principal
1434 .with_self_ty(cx.tcx(), cx.tcx().types.trait_object_dummy_self);
1435
1436 let clause: ty::Clause<'tcx> = bound_principal_with_self.upcast(cx.tcx());
1437 let super_projections: Vec<_> = elaborate::elaborate(cx.tcx(), [clause])
1438 .filter_only_self()
1439 .filter_map(|clause| clause.as_projection_clause())
1440 .collect();
1441
1442 let mut projections: Vec<_> = predicates
1443 .projection_bounds()
1444 .filter(|&proj| {
1445 let proj_is_implied = super_projections.iter().any(|&super_proj| {
1447 let super_proj = super_proj.map_bound(|super_proj| {
1448 ty::ExistentialProjection::erase_self_ty(cx.tcx(), super_proj)
1449 });
1450
1451 let proj = cx.tcx().erase_regions(proj);
1456 let super_proj = cx.tcx().erase_regions(super_proj);
1457
1458 proj == super_proj
1459 });
1460 !proj_is_implied
1461 })
1462 .map(|proj| {
1463 proj.skip_binder()
1466 })
1467 .collect();
1468
1469 projections
1470 .sort_by_cached_key(|proj| cx.tcx().item_name(proj.def_id).to_string());
1471
1472 if !args.is_empty() || !projections.is_empty() {
1473 p!(generic_delimiters(|cx| {
1474 cx.comma_sep(args.iter().copied())?;
1475 if !args.is_empty() && !projections.is_empty() {
1476 write!(cx, ", ")?;
1477 }
1478 cx.comma_sep(projections.iter().copied())
1479 }));
1480 }
1481 }
1482 Ok(())
1483 })?;
1484
1485 first = false;
1486 }
1487
1488 define_scoped_cx!(self);
1489
1490 let mut auto_traits: Vec<_> = predicates.auto_traits().collect();
1494
1495 auto_traits.sort_by_cached_key(|did| with_no_trimmed_paths!(self.tcx().def_path_str(*did)));
1503
1504 for def_id in auto_traits {
1505 if !first {
1506 p!(" + ");
1507 }
1508 first = false;
1509
1510 p!(print_def_path(def_id, &[]));
1511 }
1512
1513 Ok(())
1514 }
1515
1516 fn pretty_fn_sig(
1517 &mut self,
1518 inputs: &[Ty<'tcx>],
1519 c_variadic: bool,
1520 output: Ty<'tcx>,
1521 ) -> Result<(), PrintError> {
1522 define_scoped_cx!(self);
1523
1524 p!("(", comma_sep(inputs.iter().copied()));
1525 if c_variadic {
1526 if !inputs.is_empty() {
1527 p!(", ");
1528 }
1529 p!("...");
1530 }
1531 p!(")");
1532 if !output.is_unit() {
1533 p!(" -> ", print(output));
1534 }
1535
1536 Ok(())
1537 }
1538
1539 fn pretty_print_const(
1540 &mut self,
1541 ct: ty::Const<'tcx>,
1542 print_ty: bool,
1543 ) -> Result<(), PrintError> {
1544 define_scoped_cx!(self);
1545
1546 if self.should_print_verbose() {
1547 p!(write("{:?}", ct));
1548 return Ok(());
1549 }
1550
1551 match ct.kind() {
1552 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args }) => {
1553 match self.tcx().def_kind(def) {
1554 DefKind::Const | DefKind::AssocConst => {
1555 p!(print_value_path(def, args))
1556 }
1557 DefKind::AnonConst => {
1558 if def.is_local()
1559 && let span = self.tcx().def_span(def)
1560 && let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
1561 {
1562 p!(write("{}", snip))
1563 } else {
1564 p!(write(
1570 "{}::{}",
1571 self.tcx().crate_name(def.krate),
1572 self.tcx().def_path(def).to_string_no_crate_verbose()
1573 ))
1574 }
1575 }
1576 defkind => bug!("`{:?}` has unexpected defkind {:?}", ct, defkind),
1577 }
1578 }
1579 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1580 ty::InferConst::Var(ct_vid) if let Some(name) = self.const_infer_name(ct_vid) => {
1581 p!(write("{}", name))
1582 }
1583 _ => write!(self, "_")?,
1584 },
1585 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1586 ty::ConstKind::Value(cv) => {
1587 return self.pretty_print_const_valtree(cv, print_ty);
1588 }
1589
1590 ty::ConstKind::Bound(debruijn, bound_var) => {
1591 rustc_type_ir::debug_bound_var(self, debruijn, bound_var)?
1592 }
1593 ty::ConstKind::Placeholder(placeholder) => p!(write("{placeholder:?}")),
1594 ty::ConstKind::Expr(expr) => self.pretty_print_const_expr(expr, print_ty)?,
1597 ty::ConstKind::Error(_) => p!("{{const error}}"),
1598 };
1599 Ok(())
1600 }
1601
1602 fn pretty_print_const_expr(
1603 &mut self,
1604 expr: Expr<'tcx>,
1605 print_ty: bool,
1606 ) -> Result<(), PrintError> {
1607 define_scoped_cx!(self);
1608 match expr.kind {
1609 ty::ExprKind::Binop(op) => {
1610 let (_, _, c1, c2) = expr.binop_args();
1611
1612 let precedence = |binop: crate::mir::BinOp| binop.to_hir_binop().precedence();
1613 let op_precedence = precedence(op);
1614 let formatted_op = op.to_hir_binop().as_str();
1615 let (lhs_parenthesized, rhs_parenthesized) = match (c1.kind(), c2.kind()) {
1616 (
1617 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),
1618 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),
1619 ) => (precedence(lhs_op) < op_precedence, precedence(rhs_op) < op_precedence),
1620 (
1621 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),
1622 ty::ConstKind::Expr(_),
1623 ) => (precedence(lhs_op) < op_precedence, true),
1624 (
1625 ty::ConstKind::Expr(_),
1626 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),
1627 ) => (true, precedence(rhs_op) < op_precedence),
1628 (ty::ConstKind::Expr(_), ty::ConstKind::Expr(_)) => (true, true),
1629 (
1630 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),
1631 _,
1632 ) => (precedence(lhs_op) < op_precedence, false),
1633 (
1634 _,
1635 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),
1636 ) => (false, precedence(rhs_op) < op_precedence),
1637 (ty::ConstKind::Expr(_), _) => (true, false),
1638 (_, ty::ConstKind::Expr(_)) => (false, true),
1639 _ => (false, false),
1640 };
1641
1642 self.maybe_parenthesized(
1643 |this| this.pretty_print_const(c1, print_ty),
1644 lhs_parenthesized,
1645 )?;
1646 p!(write(" {formatted_op} "));
1647 self.maybe_parenthesized(
1648 |this| this.pretty_print_const(c2, print_ty),
1649 rhs_parenthesized,
1650 )?;
1651 }
1652 ty::ExprKind::UnOp(op) => {
1653 let (_, ct) = expr.unop_args();
1654
1655 use crate::mir::UnOp;
1656 let formatted_op = match op {
1657 UnOp::Not => "!",
1658 UnOp::Neg => "-",
1659 UnOp::PtrMetadata => "PtrMetadata",
1660 };
1661 let parenthesized = match ct.kind() {
1662 _ if op == UnOp::PtrMetadata => true,
1663 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::UnOp(c_op), .. }) => {
1664 c_op != op
1665 }
1666 ty::ConstKind::Expr(_) => true,
1667 _ => false,
1668 };
1669 p!(write("{formatted_op}"));
1670 self.maybe_parenthesized(
1671 |this| this.pretty_print_const(ct, print_ty),
1672 parenthesized,
1673 )?
1674 }
1675 ty::ExprKind::FunctionCall => {
1676 let (_, fn_def, fn_args) = expr.call_args();
1677
1678 write!(self, "(")?;
1679 self.pretty_print_const(fn_def, print_ty)?;
1680 p!(")(", comma_sep(fn_args), ")");
1681 }
1682 ty::ExprKind::Cast(kind) => {
1683 let (_, value, to_ty) = expr.cast_args();
1684
1685 use ty::abstract_const::CastKind;
1686 if kind == CastKind::As || (kind == CastKind::Use && self.should_print_verbose()) {
1687 let parenthesized = match value.kind() {
1688 ty::ConstKind::Expr(ty::Expr {
1689 kind: ty::ExprKind::Cast { .. }, ..
1690 }) => false,
1691 ty::ConstKind::Expr(_) => true,
1692 _ => false,
1693 };
1694 self.maybe_parenthesized(
1695 |this| {
1696 this.typed_value(
1697 |this| this.pretty_print_const(value, print_ty),
1698 |this| this.pretty_print_type(to_ty),
1699 " as ",
1700 )
1701 },
1702 parenthesized,
1703 )?;
1704 } else {
1705 self.pretty_print_const(value, print_ty)?
1706 }
1707 }
1708 }
1709 Ok(())
1710 }
1711
1712 fn pretty_print_const_scalar(
1713 &mut self,
1714 scalar: Scalar,
1715 ty: Ty<'tcx>,
1716 ) -> Result<(), PrintError> {
1717 match scalar {
1718 Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty),
1719 Scalar::Int(int) => {
1720 self.pretty_print_const_scalar_int(int, ty, true)
1721 }
1722 }
1723 }
1724
1725 fn pretty_print_const_scalar_ptr(
1726 &mut self,
1727 ptr: Pointer,
1728 ty: Ty<'tcx>,
1729 ) -> Result<(), PrintError> {
1730 define_scoped_cx!(self);
1731
1732 let (prov, offset) = ptr.into_parts();
1733 match ty.kind() {
1734 ty::Ref(_, inner, _) => {
1736 if let ty::Array(elem, ct_len) = inner.kind()
1737 && let ty::Uint(ty::UintTy::U8) = elem.kind()
1738 && let Some(len) = ct_len.try_to_target_usize(self.tcx())
1739 {
1740 match self.tcx().try_get_global_alloc(prov.alloc_id()) {
1741 Some(GlobalAlloc::Memory(alloc)) => {
1742 let range = AllocRange { start: offset, size: Size::from_bytes(len) };
1743 if let Ok(byte_str) =
1744 alloc.inner().get_bytes_strip_provenance(&self.tcx(), range)
1745 {
1746 p!(pretty_print_byte_str(byte_str))
1747 } else {
1748 p!("<too short allocation>")
1749 }
1750 }
1751 Some(GlobalAlloc::Static(def_id)) => {
1753 p!(write("<static({:?})>", def_id))
1754 }
1755 Some(GlobalAlloc::Function { .. }) => p!("<function>"),
1756 Some(GlobalAlloc::VTable(..)) => p!("<vtable>"),
1757 None => p!("<dangling pointer>"),
1758 }
1759 return Ok(());
1760 }
1761 }
1762 ty::FnPtr(..) => {
1763 if let Some(GlobalAlloc::Function { instance, .. }) =
1766 self.tcx().try_get_global_alloc(prov.alloc_id())
1767 {
1768 self.typed_value(
1769 |this| this.print_value_path(instance.def_id(), instance.args),
1770 |this| this.print_type(ty),
1771 " as ",
1772 )?;
1773 return Ok(());
1774 }
1775 }
1776 _ => {}
1777 }
1778 self.pretty_print_const_pointer(ptr, ty)?;
1780 Ok(())
1781 }
1782
1783 fn pretty_print_const_scalar_int(
1784 &mut self,
1785 int: ScalarInt,
1786 ty: Ty<'tcx>,
1787 print_ty: bool,
1788 ) -> Result<(), PrintError> {
1789 define_scoped_cx!(self);
1790
1791 match ty.kind() {
1792 ty::Bool if int == ScalarInt::FALSE => p!("false"),
1794 ty::Bool if int == ScalarInt::TRUE => p!("true"),
1795 ty::Float(fty) => match fty {
1797 ty::FloatTy::F16 => {
1798 let val = Half::try_from(int).unwrap();
1799 p!(write("{}{}f16", val, if val.is_finite() { "" } else { "_" }))
1800 }
1801 ty::FloatTy::F32 => {
1802 let val = Single::try_from(int).unwrap();
1803 p!(write("{}{}f32", val, if val.is_finite() { "" } else { "_" }))
1804 }
1805 ty::FloatTy::F64 => {
1806 let val = Double::try_from(int).unwrap();
1807 p!(write("{}{}f64", val, if val.is_finite() { "" } else { "_" }))
1808 }
1809 ty::FloatTy::F128 => {
1810 let val = Quad::try_from(int).unwrap();
1811 p!(write("{}{}f128", val, if val.is_finite() { "" } else { "_" }))
1812 }
1813 },
1814 ty::Uint(_) | ty::Int(_) => {
1816 let int =
1817 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1818 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1819 }
1820 ty::Char if char::try_from(int).is_ok() => {
1822 p!(write("{:?}", char::try_from(int).unwrap()))
1823 }
1824 ty::Ref(..) | ty::RawPtr(_, _) | ty::FnPtr(..) => {
1826 let data = int.to_bits(self.tcx().data_layout.pointer_size);
1827 self.typed_value(
1828 |this| {
1829 write!(this, "0x{data:x}")?;
1830 Ok(())
1831 },
1832 |this| this.print_type(ty),
1833 " as ",
1834 )?;
1835 }
1836 ty::Pat(base_ty, pat) if self.tcx().validate_scalar_in_layout(int, ty) => {
1837 self.pretty_print_const_scalar_int(int, *base_ty, print_ty)?;
1838 p!(write(" is {pat:?}"));
1839 }
1840 _ => {
1842 let print = |this: &mut Self| {
1843 if int.size() == Size::ZERO {
1844 write!(this, "transmute(())")?;
1845 } else {
1846 write!(this, "transmute(0x{int:x})")?;
1847 }
1848 Ok(())
1849 };
1850 if print_ty {
1851 self.typed_value(print, |this| this.print_type(ty), ": ")?
1852 } else {
1853 print(self)?
1854 };
1855 }
1856 }
1857 Ok(())
1858 }
1859
1860 fn pretty_print_const_pointer<Prov: Provenance>(
1863 &mut self,
1864 _: Pointer<Prov>,
1865 ty: Ty<'tcx>,
1866 ) -> Result<(), PrintError> {
1867 self.typed_value(
1868 |this| {
1869 this.write_str("&_")?;
1870 Ok(())
1871 },
1872 |this| this.print_type(ty),
1873 ": ",
1874 )
1875 }
1876
1877 fn pretty_print_byte_str(&mut self, byte_str: &'tcx [u8]) -> Result<(), PrintError> {
1878 write!(self, "b\"{}\"", byte_str.escape_ascii())?;
1879 Ok(())
1880 }
1881
1882 fn pretty_print_const_valtree(
1883 &mut self,
1884 cv: ty::Value<'tcx>,
1885 print_ty: bool,
1886 ) -> Result<(), PrintError> {
1887 define_scoped_cx!(self);
1888
1889 if self.should_print_verbose() {
1890 p!(write("ValTree({:?}: ", cv.valtree), print(cv.ty), ")");
1891 return Ok(());
1892 }
1893
1894 let u8_type = self.tcx().types.u8;
1895 match (*cv.valtree, *cv.ty.kind()) {
1896 (ty::ValTreeKind::Branch(_), ty::Ref(_, inner_ty, _)) => match inner_ty.kind() {
1897 ty::Slice(t) if *t == u8_type => {
1898 let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {
1899 bug!(
1900 "expected to convert valtree {:?} to raw bytes for type {:?}",
1901 cv.valtree,
1902 t
1903 )
1904 });
1905 return self.pretty_print_byte_str(bytes);
1906 }
1907 ty::Str => {
1908 let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {
1909 bug!("expected to convert valtree to raw bytes for type {:?}", cv.ty)
1910 });
1911 p!(write("{:?}", String::from_utf8_lossy(bytes)));
1912 return Ok(());
1913 }
1914 _ => {
1915 let cv = ty::Value { valtree: cv.valtree, ty: inner_ty };
1916 p!("&");
1917 p!(pretty_print_const_valtree(cv, print_ty));
1918 return Ok(());
1919 }
1920 },
1921 (ty::ValTreeKind::Branch(_), ty::Array(t, _)) if t == u8_type => {
1922 let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {
1923 bug!("expected to convert valtree to raw bytes for type {:?}", t)
1924 });
1925 p!("*");
1926 p!(pretty_print_byte_str(bytes));
1927 return Ok(());
1928 }
1929 (ty::ValTreeKind::Branch(_), ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) => {
1931 let contents = self.tcx().destructure_const(ty::Const::new_value(
1932 self.tcx(),
1933 cv.valtree,
1934 cv.ty,
1935 ));
1936 let fields = contents.fields.iter().copied();
1937 match *cv.ty.kind() {
1938 ty::Array(..) => {
1939 p!("[", comma_sep(fields), "]");
1940 }
1941 ty::Tuple(..) => {
1942 p!("(", comma_sep(fields));
1943 if contents.fields.len() == 1 {
1944 p!(",");
1945 }
1946 p!(")");
1947 }
1948 ty::Adt(def, _) if def.variants().is_empty() => {
1949 self.typed_value(
1950 |this| {
1951 write!(this, "unreachable()")?;
1952 Ok(())
1953 },
1954 |this| this.print_type(cv.ty),
1955 ": ",
1956 )?;
1957 }
1958 ty::Adt(def, args) => {
1959 let variant_idx =
1960 contents.variant.expect("destructed const of adt without variant idx");
1961 let variant_def = &def.variant(variant_idx);
1962 p!(print_value_path(variant_def.def_id, args));
1963 match variant_def.ctor_kind() {
1964 Some(CtorKind::Const) => {}
1965 Some(CtorKind::Fn) => {
1966 p!("(", comma_sep(fields), ")");
1967 }
1968 None => {
1969 p!(" {{ ");
1970 let mut first = true;
1971 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1972 if !first {
1973 p!(", ");
1974 }
1975 p!(write("{}: ", field_def.name), print(field));
1976 first = false;
1977 }
1978 p!(" }}");
1979 }
1980 }
1981 }
1982 _ => unreachable!(),
1983 }
1984 return Ok(());
1985 }
1986 (ty::ValTreeKind::Leaf(leaf), ty::Ref(_, inner_ty, _)) => {
1987 p!(write("&"));
1988 return self.pretty_print_const_scalar_int(*leaf, inner_ty, print_ty);
1989 }
1990 (ty::ValTreeKind::Leaf(leaf), _) => {
1991 return self.pretty_print_const_scalar_int(*leaf, cv.ty, print_ty);
1992 }
1993 (_, ty::FnDef(def_id, args)) => {
1994 p!(print_value_path(def_id, args));
1996 return Ok(());
1997 }
1998 _ => {}
2001 }
2002
2003 if cv.valtree.is_zst() {
2005 p!(write("<ZST>"));
2006 } else {
2007 p!(write("{:?}", cv.valtree));
2008 }
2009 if print_ty {
2010 p!(": ", print(cv.ty));
2011 }
2012 Ok(())
2013 }
2014
2015 fn pretty_closure_as_impl(
2016 &mut self,
2017 closure: ty::ClosureArgs<TyCtxt<'tcx>>,
2018 ) -> Result<(), PrintError> {
2019 let sig = closure.sig();
2020 let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn);
2021
2022 write!(self, "impl ")?;
2023 self.wrap_binder(&sig, WrapBinderMode::ForAll, |sig, cx| {
2024 define_scoped_cx!(cx);
2025
2026 p!(write("{kind}("));
2027 for (i, arg) in sig.inputs()[0].tuple_fields().iter().enumerate() {
2028 if i > 0 {
2029 p!(", ");
2030 }
2031 p!(print(arg));
2032 }
2033 p!(")");
2034
2035 if !sig.output().is_unit() {
2036 p!(" -> ", print(sig.output()));
2037 }
2038
2039 Ok(())
2040 })
2041 }
2042
2043 fn pretty_print_bound_constness(
2044 &mut self,
2045 constness: ty::BoundConstness,
2046 ) -> Result<(), PrintError> {
2047 define_scoped_cx!(self);
2048
2049 match constness {
2050 ty::BoundConstness::Const => {
2051 p!("const ");
2052 }
2053 ty::BoundConstness::Maybe => {
2054 p!("~const ");
2055 }
2056 }
2057 Ok(())
2058 }
2059
2060 fn should_print_verbose(&self) -> bool {
2061 self.tcx().sess.verbose_internals()
2062 }
2063}
2064
2065pub(crate) fn pretty_print_const<'tcx>(
2066 c: ty::Const<'tcx>,
2067 fmt: &mut fmt::Formatter<'_>,
2068 print_types: bool,
2069) -> fmt::Result {
2070 ty::tls::with(|tcx| {
2071 let literal = tcx.lift(c).unwrap();
2072 let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2073 cx.print_alloc_ids = true;
2074 cx.pretty_print_const(literal, print_types)?;
2075 fmt.write_str(&cx.into_buffer())?;
2076 Ok(())
2077 })
2078}
2079
2080pub struct FmtPrinter<'a, 'tcx>(Box<FmtPrinterData<'a, 'tcx>>);
2082
2083pub struct FmtPrinterData<'a, 'tcx> {
2084 tcx: TyCtxt<'tcx>,
2085 fmt: String,
2086
2087 empty_path: bool,
2088 in_value: bool,
2089 pub print_alloc_ids: bool,
2090
2091 used_region_names: FxHashSet<Symbol>,
2093
2094 region_index: usize,
2095 binder_depth: usize,
2096 printed_type_count: usize,
2097 type_length_limit: Limit,
2098
2099 pub region_highlight_mode: RegionHighlightMode<'tcx>,
2100
2101 pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<Symbol> + 'a>>,
2102 pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid) -> Option<Symbol> + 'a>>,
2103}
2104
2105impl<'a, 'tcx> Deref for FmtPrinter<'a, 'tcx> {
2106 type Target = FmtPrinterData<'a, 'tcx>;
2107 fn deref(&self) -> &Self::Target {
2108 &self.0
2109 }
2110}
2111
2112impl DerefMut for FmtPrinter<'_, '_> {
2113 fn deref_mut(&mut self) -> &mut Self::Target {
2114 &mut self.0
2115 }
2116}
2117
2118impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
2119 pub fn new(tcx: TyCtxt<'tcx>, ns: Namespace) -> Self {
2120 let limit =
2121 if with_reduced_queries() { Limit::new(1048576) } else { tcx.type_length_limit() };
2122 Self::new_with_limit(tcx, ns, limit)
2123 }
2124
2125 pub fn print_string(
2126 tcx: TyCtxt<'tcx>,
2127 ns: Namespace,
2128 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2129 ) -> Result<String, PrintError> {
2130 let mut c = FmtPrinter::new(tcx, ns);
2131 f(&mut c)?;
2132 Ok(c.into_buffer())
2133 }
2134
2135 pub fn new_with_limit(tcx: TyCtxt<'tcx>, ns: Namespace, type_length_limit: Limit) -> Self {
2136 FmtPrinter(Box::new(FmtPrinterData {
2137 tcx,
2138 fmt: String::with_capacity(64),
2141 empty_path: false,
2142 in_value: ns == Namespace::ValueNS,
2143 print_alloc_ids: false,
2144 used_region_names: Default::default(),
2145 region_index: 0,
2146 binder_depth: 0,
2147 printed_type_count: 0,
2148 type_length_limit,
2149 region_highlight_mode: RegionHighlightMode::default(),
2150 ty_infer_name_resolver: None,
2151 const_infer_name_resolver: None,
2152 }))
2153 }
2154
2155 pub fn into_buffer(self) -> String {
2156 self.0.fmt
2157 }
2158}
2159
2160fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
2163 match tcx.def_key(def_id).disambiguated_data.data {
2164 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::OpaqueTy => {
2165 Namespace::TypeNS
2166 }
2167
2168 DefPathData::ValueNs(..)
2169 | DefPathData::AnonConst
2170 | DefPathData::Closure
2171 | DefPathData::Ctor => Namespace::ValueNS,
2172
2173 DefPathData::MacroNs(..) => Namespace::MacroNS,
2174
2175 _ => Namespace::TypeNS,
2176 }
2177}
2178
2179impl<'t> TyCtxt<'t> {
2180 pub fn def_path_str(self, def_id: impl IntoQueryParam<DefId>) -> String {
2183 self.def_path_str_with_args(def_id, &[])
2184 }
2185
2186 pub fn def_path_str_with_args(
2187 self,
2188 def_id: impl IntoQueryParam<DefId>,
2189 args: &'t [GenericArg<'t>],
2190 ) -> String {
2191 let def_id = def_id.into_query_param();
2192 let ns = guess_def_namespace(self, def_id);
2193 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
2194
2195 FmtPrinter::print_string(self, ns, |cx| cx.print_def_path(def_id, args)).unwrap()
2196 }
2197
2198 pub fn value_path_str_with_args(
2199 self,
2200 def_id: impl IntoQueryParam<DefId>,
2201 args: &'t [GenericArg<'t>],
2202 ) -> String {
2203 let def_id = def_id.into_query_param();
2204 let ns = guess_def_namespace(self, def_id);
2205 debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns);
2206
2207 FmtPrinter::print_string(self, ns, |cx| cx.print_value_path(def_id, args)).unwrap()
2208 }
2209}
2210
2211impl fmt::Write for FmtPrinter<'_, '_> {
2212 fn write_str(&mut self, s: &str) -> fmt::Result {
2213 self.fmt.push_str(s);
2214 Ok(())
2215 }
2216}
2217
2218impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
2219 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
2220 self.tcx
2221 }
2222
2223 fn print_def_path(
2224 &mut self,
2225 def_id: DefId,
2226 args: &'tcx [GenericArg<'tcx>],
2227 ) -> Result<(), PrintError> {
2228 if args.is_empty() {
2229 match self.try_print_trimmed_def_path(def_id)? {
2230 true => return Ok(()),
2231 false => {}
2232 }
2233
2234 match self.try_print_visible_def_path(def_id)? {
2235 true => return Ok(()),
2236 false => {}
2237 }
2238 }
2239
2240 let key = self.tcx.def_key(def_id);
2241 if let DefPathData::Impl = key.disambiguated_data.data {
2242 let use_types = !def_id.is_local() || {
2245 let force_no_types = with_forced_impl_filename_line();
2247 !force_no_types
2248 };
2249
2250 if !use_types {
2251 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
2255 let span = self.tcx.def_span(def_id);
2256
2257 self.print_def_path(parent_def_id, &[])?;
2258
2259 if !self.empty_path {
2262 write!(self, "::")?;
2263 }
2264 write!(
2265 self,
2266 "<impl at {}>",
2267 self.tcx.sess.source_map().span_to_embeddable_string(span)
2270 )?;
2271 self.empty_path = false;
2272
2273 return Ok(());
2274 }
2275 }
2276
2277 self.default_print_def_path(def_id, args)
2278 }
2279
2280 fn print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), PrintError> {
2281 self.pretty_print_region(region)
2282 }
2283
2284 fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
2285 match ty.kind() {
2286 ty::Tuple(tys) if tys.len() == 0 && self.should_truncate() => {
2287 self.printed_type_count += 1;
2289 self.pretty_print_type(ty)
2290 }
2291 ty::Adt(..)
2292 | ty::Foreign(_)
2293 | ty::Pat(..)
2294 | ty::RawPtr(..)
2295 | ty::Ref(..)
2296 | ty::FnDef(..)
2297 | ty::FnPtr(..)
2298 | ty::UnsafeBinder(..)
2299 | ty::Dynamic(..)
2300 | ty::Closure(..)
2301 | ty::CoroutineClosure(..)
2302 | ty::Coroutine(..)
2303 | ty::CoroutineWitness(..)
2304 | ty::Tuple(_)
2305 | ty::Alias(..)
2306 | ty::Param(_)
2307 | ty::Bound(..)
2308 | ty::Placeholder(_)
2309 | ty::Error(_)
2310 if self.should_truncate() =>
2311 {
2312 write!(self, "...")?;
2315 Ok(())
2316 }
2317 _ => {
2318 self.printed_type_count += 1;
2319 self.pretty_print_type(ty)
2320 }
2321 }
2322 }
2323
2324 fn should_truncate(&mut self) -> bool {
2325 !self.type_length_limit.value_within_limit(self.printed_type_count)
2326 }
2327
2328 fn print_dyn_existential(
2329 &mut self,
2330 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2331 ) -> Result<(), PrintError> {
2332 self.pretty_print_dyn_existential(predicates)
2333 }
2334
2335 fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
2336 self.pretty_print_const(ct, false)
2337 }
2338
2339 fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
2340 self.empty_path = true;
2341 if cnum == LOCAL_CRATE {
2342 if self.tcx.sess.at_least_rust_2018() {
2343 if with_crate_prefix() {
2345 write!(self, "{}", kw::Crate)?;
2346 self.empty_path = false;
2347 }
2348 }
2349 } else {
2350 write!(self, "{}", self.tcx.crate_name(cnum))?;
2351 self.empty_path = false;
2352 }
2353 Ok(())
2354 }
2355
2356 fn path_qualified(
2357 &mut self,
2358 self_ty: Ty<'tcx>,
2359 trait_ref: Option<ty::TraitRef<'tcx>>,
2360 ) -> Result<(), PrintError> {
2361 self.pretty_path_qualified(self_ty, trait_ref)?;
2362 self.empty_path = false;
2363 Ok(())
2364 }
2365
2366 fn path_append_impl(
2367 &mut self,
2368 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2369 _disambiguated_data: &DisambiguatedDefPathData,
2370 self_ty: Ty<'tcx>,
2371 trait_ref: Option<ty::TraitRef<'tcx>>,
2372 ) -> Result<(), PrintError> {
2373 self.pretty_path_append_impl(
2374 |cx| {
2375 print_prefix(cx)?;
2376 if !cx.empty_path {
2377 write!(cx, "::")?;
2378 }
2379
2380 Ok(())
2381 },
2382 self_ty,
2383 trait_ref,
2384 )?;
2385 self.empty_path = false;
2386 Ok(())
2387 }
2388
2389 fn path_append(
2390 &mut self,
2391 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2392 disambiguated_data: &DisambiguatedDefPathData,
2393 ) -> Result<(), PrintError> {
2394 print_prefix(self)?;
2395
2396 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
2398 return Ok(());
2399 }
2400
2401 let name = disambiguated_data.data.name();
2402 if !self.empty_path {
2403 write!(self, "::")?;
2404 }
2405
2406 if let DefPathDataName::Named(name) = name {
2407 if Ident::with_dummy_span(name).is_raw_guess() {
2408 write!(self, "r#")?;
2409 }
2410 }
2411
2412 let verbose = self.should_print_verbose();
2413 disambiguated_data.fmt_maybe_verbose(self, verbose)?;
2414
2415 self.empty_path = false;
2416
2417 Ok(())
2418 }
2419
2420 fn path_generic_args(
2421 &mut self,
2422 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2423 args: &[GenericArg<'tcx>],
2424 ) -> Result<(), PrintError> {
2425 print_prefix(self)?;
2426
2427 if !args.is_empty() {
2428 if self.in_value {
2429 write!(self, "::")?;
2430 }
2431 self.generic_delimiters(|cx| cx.comma_sep(args.iter().copied()))
2432 } else {
2433 Ok(())
2434 }
2435 }
2436}
2437
2438impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
2439 fn ty_infer_name(&self, id: ty::TyVid) -> Option<Symbol> {
2440 self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
2441 }
2442
2443 fn reset_type_limit(&mut self) {
2444 self.printed_type_count = 0;
2445 }
2446
2447 fn const_infer_name(&self, id: ty::ConstVid) -> Option<Symbol> {
2448 self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
2449 }
2450
2451 fn print_value_path(
2452 &mut self,
2453 def_id: DefId,
2454 args: &'tcx [GenericArg<'tcx>],
2455 ) -> Result<(), PrintError> {
2456 let was_in_value = std::mem::replace(&mut self.in_value, true);
2457 self.print_def_path(def_id, args)?;
2458 self.in_value = was_in_value;
2459
2460 Ok(())
2461 }
2462
2463 fn print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError>
2464 where
2465 T: Print<'tcx, Self> + TypeFoldable<TyCtxt<'tcx>>,
2466 {
2467 self.pretty_print_in_binder(value)
2468 }
2469
2470 fn wrap_binder<T, C: FnOnce(&T, &mut Self) -> Result<(), PrintError>>(
2471 &mut self,
2472 value: &ty::Binder<'tcx, T>,
2473 mode: WrapBinderMode,
2474 f: C,
2475 ) -> Result<(), PrintError>
2476 where
2477 T: TypeFoldable<TyCtxt<'tcx>>,
2478 {
2479 self.pretty_wrap_binder(value, mode, f)
2480 }
2481
2482 fn typed_value(
2483 &mut self,
2484 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2485 t: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2486 conversion: &str,
2487 ) -> Result<(), PrintError> {
2488 self.write_str("{")?;
2489 f(self)?;
2490 self.write_str(conversion)?;
2491 let was_in_value = std::mem::replace(&mut self.in_value, false);
2492 t(self)?;
2493 self.in_value = was_in_value;
2494 self.write_str("}")?;
2495 Ok(())
2496 }
2497
2498 fn generic_delimiters(
2499 &mut self,
2500 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2501 ) -> Result<(), PrintError> {
2502 write!(self, "<")?;
2503
2504 let was_in_value = std::mem::replace(&mut self.in_value, false);
2505 f(self)?;
2506 self.in_value = was_in_value;
2507
2508 write!(self, ">")?;
2509 Ok(())
2510 }
2511
2512 fn should_print_region(&self, region: ty::Region<'tcx>) -> bool {
2513 let highlight = self.region_highlight_mode;
2514 if highlight.region_highlighted(region).is_some() {
2515 return true;
2516 }
2517
2518 if self.should_print_verbose() {
2519 return true;
2520 }
2521
2522 if with_forced_trimmed_paths() {
2523 return false;
2524 }
2525
2526 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2527
2528 match region.kind() {
2529 ty::ReEarlyParam(ref data) => data.has_name(),
2530
2531 ty::ReLateParam(ty::LateParamRegion { kind, .. }) => kind.is_named(),
2532 ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2533 | ty::RePlaceholder(ty::Placeholder {
2534 bound: ty::BoundRegion { kind: br, .. }, ..
2535 }) => {
2536 if br.is_named() {
2537 return true;
2538 }
2539
2540 if let Some((region, _)) = highlight.highlight_bound_region {
2541 if br == region {
2542 return true;
2543 }
2544 }
2545
2546 false
2547 }
2548
2549 ty::ReVar(_) if identify_regions => true,
2550
2551 ty::ReVar(_) | ty::ReErased | ty::ReError(_) => false,
2552
2553 ty::ReStatic => true,
2554 }
2555 }
2556
2557 fn pretty_print_const_pointer<Prov: Provenance>(
2558 &mut self,
2559 p: Pointer<Prov>,
2560 ty: Ty<'tcx>,
2561 ) -> Result<(), PrintError> {
2562 let print = |this: &mut Self| {
2563 define_scoped_cx!(this);
2564 if this.print_alloc_ids {
2565 p!(write("{:?}", p));
2566 } else {
2567 p!("&_");
2568 }
2569 Ok(())
2570 };
2571 self.typed_value(print, |this| this.print_type(ty), ": ")
2572 }
2573}
2574
2575impl<'tcx> FmtPrinter<'_, 'tcx> {
2577 pub fn pretty_print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), fmt::Error> {
2578 define_scoped_cx!(self);
2579
2580 let highlight = self.region_highlight_mode;
2582 if let Some(n) = highlight.region_highlighted(region) {
2583 p!(write("'{}", n));
2584 return Ok(());
2585 }
2586
2587 if self.should_print_verbose() {
2588 p!(write("{:?}", region));
2589 return Ok(());
2590 }
2591
2592 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2593
2594 match region.kind() {
2599 ty::ReEarlyParam(data) => {
2600 p!(write("{}", data.name));
2601 return Ok(());
2602 }
2603 ty::ReLateParam(ty::LateParamRegion { kind, .. }) => {
2604 if let Some(name) = kind.get_name() {
2605 p!(write("{}", name));
2606 return Ok(());
2607 }
2608 }
2609 ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2610 | ty::RePlaceholder(ty::Placeholder {
2611 bound: ty::BoundRegion { kind: br, .. }, ..
2612 }) => {
2613 if let ty::BoundRegionKind::Named(_, name) = br
2614 && br.is_named()
2615 {
2616 p!(write("{}", name));
2617 return Ok(());
2618 }
2619
2620 if let Some((region, counter)) = highlight.highlight_bound_region {
2621 if br == region {
2622 p!(write("'{}", counter));
2623 return Ok(());
2624 }
2625 }
2626 }
2627 ty::ReVar(region_vid) if identify_regions => {
2628 p!(write("{:?}", region_vid));
2629 return Ok(());
2630 }
2631 ty::ReVar(_) => {}
2632 ty::ReErased => {}
2633 ty::ReError(_) => {}
2634 ty::ReStatic => {
2635 p!("'static");
2636 return Ok(());
2637 }
2638 }
2639
2640 p!("'_");
2641
2642 Ok(())
2643 }
2644}
2645
2646struct RegionFolder<'a, 'tcx> {
2648 tcx: TyCtxt<'tcx>,
2649 current_index: ty::DebruijnIndex,
2650 region_map: UnordMap<ty::BoundRegion, ty::Region<'tcx>>,
2651 name: &'a mut (
2652 dyn FnMut(
2653 Option<ty::DebruijnIndex>, ty::DebruijnIndex, ty::BoundRegion,
2656 ) -> ty::Region<'tcx>
2657 + 'a
2658 ),
2659}
2660
2661impl<'a, 'tcx> ty::TypeFolder<TyCtxt<'tcx>> for RegionFolder<'a, 'tcx> {
2662 fn cx(&self) -> TyCtxt<'tcx> {
2663 self.tcx
2664 }
2665
2666 fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>(
2667 &mut self,
2668 t: ty::Binder<'tcx, T>,
2669 ) -> ty::Binder<'tcx, T> {
2670 self.current_index.shift_in(1);
2671 let t = t.super_fold_with(self);
2672 self.current_index.shift_out(1);
2673 t
2674 }
2675
2676 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2677 match *t.kind() {
2678 _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2679 return t.super_fold_with(self);
2680 }
2681 _ => {}
2682 }
2683 t
2684 }
2685
2686 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2687 let name = &mut self.name;
2688 let region = match r.kind() {
2689 ty::ReBound(db, br) if db >= self.current_index => {
2690 *self.region_map.entry(br).or_insert_with(|| name(Some(db), self.current_index, br))
2691 }
2692 ty::RePlaceholder(ty::PlaceholderRegion {
2693 bound: ty::BoundRegion { kind, .. },
2694 ..
2695 }) => {
2696 match kind {
2699 ty::BoundRegionKind::Anon | ty::BoundRegionKind::ClosureEnv => r,
2700 _ => {
2701 let br = ty::BoundRegion { var: ty::BoundVar::ZERO, kind };
2703 *self
2704 .region_map
2705 .entry(br)
2706 .or_insert_with(|| name(None, self.current_index, br))
2707 }
2708 }
2709 }
2710 _ => return r,
2711 };
2712 if let ty::ReBound(debruijn1, br) = region.kind() {
2713 assert_eq!(debruijn1, ty::INNERMOST);
2714 ty::Region::new_bound(self.tcx, self.current_index, br)
2715 } else {
2716 region
2717 }
2718 }
2719}
2720
2721impl<'tcx> FmtPrinter<'_, 'tcx> {
2724 pub fn name_all_regions<T>(
2725 &mut self,
2726 value: &ty::Binder<'tcx, T>,
2727 mode: WrapBinderMode,
2728 ) -> Result<(T, UnordMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
2729 where
2730 T: TypeFoldable<TyCtxt<'tcx>>,
2731 {
2732 fn name_by_region_index(
2733 index: usize,
2734 available_names: &mut Vec<Symbol>,
2735 num_available: usize,
2736 ) -> Symbol {
2737 if let Some(name) = available_names.pop() {
2738 name
2739 } else {
2740 Symbol::intern(&format!("'z{}", index - num_available))
2741 }
2742 }
2743
2744 debug!("name_all_regions");
2745
2746 if self.binder_depth == 0 {
2752 self.prepare_region_info(value);
2753 }
2754
2755 debug!("self.used_region_names: {:?}", self.used_region_names);
2756
2757 let mut empty = true;
2758 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
2759 let w = if empty {
2760 empty = false;
2761 start
2762 } else {
2763 cont
2764 };
2765 let _ = write!(cx, "{w}");
2766 };
2767 let do_continue = |cx: &mut Self, cont: Symbol| {
2768 let _ = write!(cx, "{cont}");
2769 };
2770
2771 let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&format!("'{s}")));
2772
2773 let mut available_names = possible_names
2774 .filter(|name| !self.used_region_names.contains(name))
2775 .collect::<Vec<_>>();
2776 debug!(?available_names);
2777 let num_available = available_names.len();
2778
2779 let mut region_index = self.region_index;
2780 let mut next_name = |this: &Self| {
2781 let mut name;
2782
2783 loop {
2784 name = name_by_region_index(region_index, &mut available_names, num_available);
2785 region_index += 1;
2786
2787 if !this.used_region_names.contains(&name) {
2788 break;
2789 }
2790 }
2791
2792 name
2793 };
2794
2795 let (new_value, map) = if self.should_print_verbose() {
2800 for var in value.bound_vars().iter() {
2801 start_or_continue(self, mode.start_str(), ", ");
2802 write!(self, "{var:?}")?;
2803 }
2804 if value.bound_vars().is_empty() && mode == WrapBinderMode::Unsafe {
2806 start_or_continue(self, mode.start_str(), "");
2807 }
2808 start_or_continue(self, "", "> ");
2809 (value.clone().skip_binder(), UnordMap::default())
2810 } else {
2811 let tcx = self.tcx;
2812
2813 let trim_path = with_forced_trimmed_paths();
2814 let mut name = |lifetime_idx: Option<ty::DebruijnIndex>,
2820 binder_level_idx: ty::DebruijnIndex,
2821 br: ty::BoundRegion| {
2822 let (name, kind) = match br.kind {
2823 ty::BoundRegionKind::Anon | ty::BoundRegionKind::ClosureEnv => {
2824 let name = next_name(self);
2825
2826 if let Some(lt_idx) = lifetime_idx {
2827 if lt_idx > binder_level_idx {
2828 let kind =
2829 ty::BoundRegionKind::Named(CRATE_DEF_ID.to_def_id(), name);
2830 return ty::Region::new_bound(
2831 tcx,
2832 ty::INNERMOST,
2833 ty::BoundRegion { var: br.var, kind },
2834 );
2835 }
2836 }
2837
2838 (name, ty::BoundRegionKind::Named(CRATE_DEF_ID.to_def_id(), name))
2839 }
2840 ty::BoundRegionKind::Named(def_id, kw::UnderscoreLifetime) => {
2841 let name = next_name(self);
2842
2843 if let Some(lt_idx) = lifetime_idx {
2844 if lt_idx > binder_level_idx {
2845 let kind = ty::BoundRegionKind::Named(def_id, name);
2846 return ty::Region::new_bound(
2847 tcx,
2848 ty::INNERMOST,
2849 ty::BoundRegion { var: br.var, kind },
2850 );
2851 }
2852 }
2853
2854 (name, ty::BoundRegionKind::Named(def_id, name))
2855 }
2856 ty::BoundRegionKind::Named(_, name) => {
2857 if let Some(lt_idx) = lifetime_idx {
2858 if lt_idx > binder_level_idx {
2859 let kind = br.kind;
2860 return ty::Region::new_bound(
2861 tcx,
2862 ty::INNERMOST,
2863 ty::BoundRegion { var: br.var, kind },
2864 );
2865 }
2866 }
2867
2868 (name, br.kind)
2869 }
2870 };
2871
2872 if !trim_path || mode == WrapBinderMode::Unsafe {
2874 start_or_continue(self, mode.start_str(), ", ");
2875 do_continue(self, name);
2876 }
2877 ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { var: br.var, kind })
2878 };
2879 let mut folder = RegionFolder {
2880 tcx,
2881 current_index: ty::INNERMOST,
2882 name: &mut name,
2883 region_map: UnordMap::default(),
2884 };
2885 let new_value = value.clone().skip_binder().fold_with(&mut folder);
2886 let region_map = folder.region_map;
2887
2888 if mode == WrapBinderMode::Unsafe && region_map.is_empty() {
2889 start_or_continue(self, mode.start_str(), "");
2890 }
2891 start_or_continue(self, "", "> ");
2892
2893 (new_value, region_map)
2894 };
2895
2896 self.binder_depth += 1;
2897 self.region_index = region_index;
2898 Ok((new_value, map))
2899 }
2900
2901 pub fn pretty_print_in_binder<T>(
2902 &mut self,
2903 value: &ty::Binder<'tcx, T>,
2904 ) -> Result<(), fmt::Error>
2905 where
2906 T: Print<'tcx, Self> + TypeFoldable<TyCtxt<'tcx>>,
2907 {
2908 let old_region_index = self.region_index;
2909 let (new_value, _) = self.name_all_regions(value, WrapBinderMode::ForAll)?;
2910 new_value.print(self)?;
2911 self.region_index = old_region_index;
2912 self.binder_depth -= 1;
2913 Ok(())
2914 }
2915
2916 pub fn pretty_wrap_binder<T, C: FnOnce(&T, &mut Self) -> Result<(), fmt::Error>>(
2917 &mut self,
2918 value: &ty::Binder<'tcx, T>,
2919 mode: WrapBinderMode,
2920 f: C,
2921 ) -> Result<(), fmt::Error>
2922 where
2923 T: TypeFoldable<TyCtxt<'tcx>>,
2924 {
2925 let old_region_index = self.region_index;
2926 let (new_value, _) = self.name_all_regions(value, mode)?;
2927 f(&new_value, self)?;
2928 self.region_index = old_region_index;
2929 self.binder_depth -= 1;
2930 Ok(())
2931 }
2932
2933 fn prepare_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2934 where
2935 T: TypeFoldable<TyCtxt<'tcx>>,
2936 {
2937 struct RegionNameCollector<'tcx> {
2938 used_region_names: FxHashSet<Symbol>,
2939 type_collector: SsoHashSet<Ty<'tcx>>,
2940 }
2941
2942 impl<'tcx> RegionNameCollector<'tcx> {
2943 fn new() -> Self {
2944 RegionNameCollector {
2945 used_region_names: Default::default(),
2946 type_collector: SsoHashSet::new(),
2947 }
2948 }
2949 }
2950
2951 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for RegionNameCollector<'tcx> {
2952 fn visit_region(&mut self, r: ty::Region<'tcx>) {
2953 trace!("address: {:p}", r.0.0);
2954
2955 if let Some(name) = r.get_name() {
2959 self.used_region_names.insert(name);
2960 }
2961 }
2962
2963 fn visit_ty(&mut self, ty: Ty<'tcx>) {
2966 let not_previously_inserted = self.type_collector.insert(ty);
2967 if not_previously_inserted {
2968 ty.super_visit_with(self)
2969 }
2970 }
2971 }
2972
2973 let mut collector = RegionNameCollector::new();
2974 value.visit_with(&mut collector);
2975 self.used_region_names = collector.used_region_names;
2976 self.region_index = 0;
2977 }
2978}
2979
2980impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2981where
2982 T: Print<'tcx, P> + TypeFoldable<TyCtxt<'tcx>>,
2983{
2984 fn print(&self, cx: &mut P) -> Result<(), PrintError> {
2985 cx.print_in_binder(self)
2986 }
2987}
2988
2989impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<'tcx, T>
2990where
2991 T: Print<'tcx, P>,
2992{
2993 fn print(&self, cx: &mut P) -> Result<(), PrintError> {
2994 define_scoped_cx!(cx);
2995 p!(print(self.0), ": ", print(self.1));
2996 Ok(())
2997 }
2998}
2999
3000#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
3004pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
3005
3006impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintOnlyTraitPath<'tcx> {
3007 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
3008 ty::tls::with(|tcx| {
3009 let trait_ref = tcx.short_string(self, path);
3010 rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
3011 })
3012 }
3013}
3014
3015impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
3016 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3017 fmt::Display::fmt(self, f)
3018 }
3019}
3020
3021#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
3024pub struct TraitRefPrintSugared<'tcx>(ty::TraitRef<'tcx>);
3025
3026impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintSugared<'tcx> {
3027 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
3028 ty::tls::with(|tcx| {
3029 let trait_ref = tcx.short_string(self, path);
3030 rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
3031 })
3032 }
3033}
3034
3035impl<'tcx> fmt::Debug for TraitRefPrintSugared<'tcx> {
3036 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3037 fmt::Display::fmt(self, f)
3038 }
3039}
3040
3041#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
3045pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
3046
3047impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
3048 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3049 fmt::Display::fmt(self, f)
3050 }
3051}
3052
3053#[extension(pub trait PrintTraitRefExt<'tcx>)]
3054impl<'tcx> ty::TraitRef<'tcx> {
3055 fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
3056 TraitRefPrintOnlyTraitPath(self)
3057 }
3058
3059 fn print_trait_sugared(self) -> TraitRefPrintSugared<'tcx> {
3060 TraitRefPrintSugared(self)
3061 }
3062
3063 fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
3064 TraitRefPrintOnlyTraitName(self)
3065 }
3066}
3067
3068#[extension(pub trait PrintPolyTraitRefExt<'tcx>)]
3069impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
3070 fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
3071 self.map_bound(|tr| tr.print_only_trait_path())
3072 }
3073
3074 fn print_trait_sugared(self) -> ty::Binder<'tcx, TraitRefPrintSugared<'tcx>> {
3075 self.map_bound(|tr| tr.print_trait_sugared())
3076 }
3077}
3078
3079#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
3080pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
3081
3082impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
3083 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3084 fmt::Display::fmt(self, f)
3085 }
3086}
3087
3088#[extension(pub trait PrintTraitPredicateExt<'tcx>)]
3089impl<'tcx> ty::TraitPredicate<'tcx> {
3090 fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
3091 TraitPredPrintModifiersAndPath(self)
3092 }
3093}
3094
3095#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
3096pub struct TraitPredPrintWithBoundConstness<'tcx>(
3097 ty::TraitPredicate<'tcx>,
3098 Option<ty::BoundConstness>,
3099);
3100
3101impl<'tcx> fmt::Debug for TraitPredPrintWithBoundConstness<'tcx> {
3102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3103 fmt::Display::fmt(self, f)
3104 }
3105}
3106
3107#[extension(pub trait PrintPolyTraitPredicateExt<'tcx>)]
3108impl<'tcx> ty::PolyTraitPredicate<'tcx> {
3109 fn print_modifiers_and_trait_path(
3110 self,
3111 ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
3112 self.map_bound(TraitPredPrintModifiersAndPath)
3113 }
3114
3115 fn print_with_bound_constness(
3116 self,
3117 constness: Option<ty::BoundConstness>,
3118 ) -> ty::Binder<'tcx, TraitPredPrintWithBoundConstness<'tcx>> {
3119 self.map_bound(|trait_pred| TraitPredPrintWithBoundConstness(trait_pred, constness))
3120 }
3121}
3122
3123#[derive(Debug, Copy, Clone, Lift)]
3124pub struct PrintClosureAsImpl<'tcx> {
3125 pub closure: ty::ClosureArgs<TyCtxt<'tcx>>,
3126}
3127
3128macro_rules! forward_display_to_print {
3129 ($($ty:ty),+) => {
3130 $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty {
3132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3133 ty::tls::with(|tcx| {
3134 let mut cx = FmtPrinter::new(tcx, Namespace::TypeNS);
3135 tcx.lift(*self)
3136 .expect("could not lift for printing")
3137 .print(&mut cx)?;
3138 f.write_str(&cx.into_buffer())?;
3139 Ok(())
3140 })
3141 }
3142 })+
3143 };
3144}
3145
3146macro_rules! define_print {
3147 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
3148 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
3149 fn print(&$self, $cx: &mut P) -> Result<(), PrintError> {
3150 define_scoped_cx!($cx);
3151 let _: () = $print;
3152 Ok(())
3153 }
3154 })+
3155 };
3156}
3157
3158macro_rules! define_print_and_forward_display {
3159 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
3160 define_print!(($self, $cx): $($ty $print)*);
3161 forward_display_to_print!($($ty),+);
3162 };
3163}
3164
3165forward_display_to_print! {
3166 ty::Region<'tcx>,
3167 Ty<'tcx>,
3168 &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3169 ty::Const<'tcx>
3170}
3171
3172define_print! {
3173 (self, cx):
3174
3175 ty::FnSig<'tcx> {
3176 p!(write("{}", self.safety.prefix_str()));
3177
3178 if self.abi != ExternAbi::Rust {
3179 p!(write("extern {} ", self.abi));
3180 }
3181
3182 p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
3183 }
3184
3185 ty::TraitRef<'tcx> {
3186 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
3187 }
3188
3189 ty::AliasTy<'tcx> {
3190 let alias_term: ty::AliasTerm<'tcx> = (*self).into();
3191 p!(print(alias_term))
3192 }
3193
3194 ty::AliasTerm<'tcx> {
3195 match self.kind(cx.tcx()) {
3196 ty::AliasTermKind::InherentTy | ty::AliasTermKind::InherentConst => p!(pretty_print_inherent_projection(*self)),
3197 ty::AliasTermKind::ProjectionTy => {
3198 if !(cx.should_print_verbose() || with_reduced_queries())
3199 && cx.tcx().is_impl_trait_in_trait(self.def_id)
3200 {
3201 p!(pretty_print_rpitit(self.def_id, self.args))
3202 } else {
3203 p!(print_def_path(self.def_id, self.args));
3204 }
3205 }
3206 ty::AliasTermKind::FreeTy
3207 | ty::AliasTermKind::FreeConst
3208 | ty::AliasTermKind::OpaqueTy
3209 | ty::AliasTermKind::UnevaluatedConst
3210 | ty::AliasTermKind::ProjectionConst => {
3211 p!(print_def_path(self.def_id, self.args));
3212 }
3213 }
3214 }
3215
3216 ty::TraitPredicate<'tcx> {
3217 p!(print(self.trait_ref.self_ty()), ": ");
3218 if let ty::PredicatePolarity::Negative = self.polarity {
3219 p!("!");
3220 }
3221 p!(print(self.trait_ref.print_trait_sugared()))
3222 }
3223
3224 ty::HostEffectPredicate<'tcx> {
3225 let constness = match self.constness {
3226 ty::BoundConstness::Const => { "const" }
3227 ty::BoundConstness::Maybe => { "~const" }
3228 };
3229 p!(print(self.trait_ref.self_ty()), ": {constness} ");
3230 p!(print(self.trait_ref.print_trait_sugared()))
3231 }
3232
3233 ty::TypeAndMut<'tcx> {
3234 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
3235 }
3236
3237 ty::ClauseKind<'tcx> {
3238 match *self {
3239 ty::ClauseKind::Trait(ref data) => {
3240 p!(print(data))
3241 }
3242 ty::ClauseKind::RegionOutlives(predicate) => p!(print(predicate)),
3243 ty::ClauseKind::TypeOutlives(predicate) => p!(print(predicate)),
3244 ty::ClauseKind::Projection(predicate) => p!(print(predicate)),
3245 ty::ClauseKind::HostEffect(predicate) => p!(print(predicate)),
3246 ty::ClauseKind::ConstArgHasType(ct, ty) => {
3247 p!("the constant `", print(ct), "` has type `", print(ty), "`")
3248 },
3249 ty::ClauseKind::WellFormed(term) => p!(print(term), " well-formed"),
3250 ty::ClauseKind::ConstEvaluatable(ct) => {
3251 p!("the constant `", print(ct), "` can be evaluated")
3252 }
3253 }
3254 }
3255
3256 ty::PredicateKind<'tcx> {
3257 match *self {
3258 ty::PredicateKind::Clause(data) => {
3259 p!(print(data))
3260 }
3261 ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
3262 ty::PredicateKind::Coerce(predicate) => p!(print(predicate)),
3263 ty::PredicateKind::DynCompatible(trait_def_id) => {
3264 p!("the trait `", print_def_path(trait_def_id, &[]), "` is dyn-compatible")
3265 }
3266 ty::PredicateKind::ConstEquate(c1, c2) => {
3267 p!("the constant `", print(c1), "` equals `", print(c2), "`")
3268 }
3269 ty::PredicateKind::Ambiguous => p!("ambiguous"),
3270 ty::PredicateKind::NormalizesTo(data) => p!(print(data)),
3271 ty::PredicateKind::AliasRelate(t1, t2, dir) => p!(print(t1), write(" {} ", dir), print(t2)),
3272 }
3273 }
3274
3275 ty::ExistentialPredicate<'tcx> {
3276 match *self {
3277 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
3278 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
3279 ty::ExistentialPredicate::AutoTrait(def_id) => {
3280 p!(print_def_path(def_id, &[]));
3281 }
3282 }
3283 }
3284
3285 ty::ExistentialTraitRef<'tcx> {
3286 let dummy_self = Ty::new_fresh(cx.tcx(), 0);
3288 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
3289 p!(print(trait_ref.print_only_trait_path()))
3290 }
3291
3292 ty::ExistentialProjection<'tcx> {
3293 let name = cx.tcx().associated_item(self.def_id).name();
3294 let args = &self.args[cx.tcx().generics_of(self.def_id).parent_count - 1..];
3297 p!(path_generic_args(|cx| write!(cx, "{name}"), args), " = ", print(self.term))
3298 }
3299
3300 ty::ProjectionPredicate<'tcx> {
3301 p!(print(self.projection_term), " == ");
3302 cx.reset_type_limit();
3303 p!(print(self.term))
3304 }
3305
3306 ty::SubtypePredicate<'tcx> {
3307 p!(print(self.a), " <: ");
3308 cx.reset_type_limit();
3309 p!(print(self.b))
3310 }
3311
3312 ty::CoercePredicate<'tcx> {
3313 p!(print(self.a), " -> ");
3314 cx.reset_type_limit();
3315 p!(print(self.b))
3316 }
3317
3318 ty::NormalizesTo<'tcx> {
3319 p!(print(self.alias), " normalizes-to ");
3320 cx.reset_type_limit();
3321 p!(print(self.term))
3322 }
3323}
3324
3325define_print_and_forward_display! {
3326 (self, cx):
3327
3328 &'tcx ty::List<Ty<'tcx>> {
3329 p!("{{", comma_sep(self.iter()), "}}")
3330 }
3331
3332 TraitRefPrintOnlyTraitPath<'tcx> {
3333 p!(print_def_path(self.0.def_id, self.0.args));
3334 }
3335
3336 TraitRefPrintSugared<'tcx> {
3337 if !with_reduced_queries()
3338 && cx.tcx().trait_def(self.0.def_id).paren_sugar
3339 && let ty::Tuple(args) = self.0.args.type_at(1).kind()
3340 {
3341 p!(write("{}", cx.tcx().item_name(self.0.def_id)), "(");
3342 for (i, arg) in args.iter().enumerate() {
3343 if i > 0 {
3344 p!(", ");
3345 }
3346 p!(print(arg));
3347 }
3348 p!(")");
3349 } else {
3350 p!(print_def_path(self.0.def_id, self.0.args));
3351 }
3352 }
3353
3354 TraitRefPrintOnlyTraitName<'tcx> {
3355 p!(print_def_path(self.0.def_id, &[]));
3356 }
3357
3358 TraitPredPrintModifiersAndPath<'tcx> {
3359 if let ty::PredicatePolarity::Negative = self.0.polarity {
3360 p!("!")
3361 }
3362 p!(print(self.0.trait_ref.print_trait_sugared()));
3363 }
3364
3365 TraitPredPrintWithBoundConstness<'tcx> {
3366 p!(print(self.0.trait_ref.self_ty()), ": ");
3367 if let Some(constness) = self.1 {
3368 p!(pretty_print_bound_constness(constness));
3369 }
3370 if let ty::PredicatePolarity::Negative = self.0.polarity {
3371 p!("!");
3372 }
3373 p!(print(self.0.trait_ref.print_trait_sugared()))
3374 }
3375
3376 PrintClosureAsImpl<'tcx> {
3377 p!(pretty_closure_as_impl(self.closure))
3378 }
3379
3380 ty::ParamTy {
3381 p!(write("{}", self.name))
3382 }
3383
3384 ty::ParamConst {
3385 p!(write("{}", self.name))
3386 }
3387
3388 ty::Term<'tcx> {
3389 match self.unpack() {
3390 ty::TermKind::Ty(ty) => p!(print(ty)),
3391 ty::TermKind::Const(c) => p!(print(c)),
3392 }
3393 }
3394
3395 ty::Predicate<'tcx> {
3396 p!(print(self.kind()))
3397 }
3398
3399 ty::Clause<'tcx> {
3400 p!(print(self.kind()))
3401 }
3402
3403 GenericArg<'tcx> {
3404 match self.unpack() {
3405 GenericArgKind::Lifetime(lt) => p!(print(lt)),
3406 GenericArgKind::Type(ty) => p!(print(ty)),
3407 GenericArgKind::Const(ct) => p!(print(ct)),
3408 }
3409 }
3410}
3411
3412fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
3413 for id in tcx.hir_free_items() {
3415 if matches!(tcx.def_kind(id.owner_id), DefKind::Use) {
3416 continue;
3417 }
3418
3419 let item = tcx.hir_item(id);
3420 let Some(ident) = item.kind.ident() else { continue };
3421
3422 let def_id = item.owner_id.to_def_id();
3423 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
3424 collect_fn(&ident, ns, def_id);
3425 }
3426
3427 let queue = &mut Vec::new();
3429 let mut seen_defs: DefIdSet = Default::default();
3430
3431 for &cnum in tcx.crates(()).iter() {
3432 match tcx.extern_crate(cnum) {
3434 None => continue,
3435 Some(extern_crate) => {
3436 if !extern_crate.is_direct() {
3437 continue;
3438 }
3439 }
3440 }
3441
3442 queue.push(cnum.as_def_id());
3443 }
3444
3445 while let Some(def) = queue.pop() {
3447 for child in tcx.module_children(def).iter() {
3448 if !child.vis.is_public() {
3449 continue;
3450 }
3451
3452 match child.res {
3453 def::Res::Def(DefKind::AssocTy, _) => {}
3454 def::Res::Def(DefKind::TyAlias, _) => {}
3455 def::Res::Def(defkind, def_id) => {
3456 if let Some(ns) = defkind.ns() {
3457 collect_fn(&child.ident, ns, def_id);
3458 }
3459
3460 if matches!(defkind, DefKind::Mod | DefKind::Enum | DefKind::Trait)
3461 && seen_defs.insert(def_id)
3462 {
3463 queue.push(def_id);
3464 }
3465 }
3466 _ => {}
3467 }
3468 }
3469 }
3470}
3471
3472pub fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> DefIdMap<Symbol> {
3488 tcx.sess.record_trimmed_def_paths();
3495
3496 let unique_symbols_rev: &mut FxIndexMap<(Namespace, Symbol), Option<DefId>> =
3499 &mut FxIndexMap::default();
3500
3501 for symbol_set in tcx.resolutions(()).glob_map.values() {
3502 for symbol in symbol_set {
3503 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
3504 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
3505 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
3506 }
3507 }
3508
3509 for_each_def(tcx, |ident, ns, def_id| match unique_symbols_rev.entry((ns, ident.name)) {
3510 IndexEntry::Occupied(mut v) => match v.get() {
3511 None => {}
3512 Some(existing) => {
3513 if *existing != def_id {
3514 v.insert(None);
3515 }
3516 }
3517 },
3518 IndexEntry::Vacant(v) => {
3519 v.insert(Some(def_id));
3520 }
3521 });
3522
3523 let mut map: DefIdMap<Symbol> = Default::default();
3525 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain(..) {
3526 use std::collections::hash_map::Entry::{Occupied, Vacant};
3527
3528 if let Some(def_id) = opt_def_id {
3529 match map.entry(def_id) {
3530 Occupied(mut v) => {
3531 if *v.get() != symbol && v.get().as_str() > symbol.as_str() {
3540 v.insert(symbol);
3541 }
3542 }
3543 Vacant(v) => {
3544 v.insert(symbol);
3545 }
3546 }
3547 }
3548 }
3549
3550 map
3551}
3552
3553pub fn provide(providers: &mut Providers) {
3554 *providers = Providers { trimmed_def_paths, ..*providers };
3555}
3556
3557pub struct OpaqueFnEntry<'tcx> {
3558 kind: ty::ClosureKind,
3559 return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,
3560}