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