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 proj = cx.tcx().anonymize_bound_vars(proj);
1457 let super_proj = cx.tcx().erase_regions(super_proj);
1458 let super_proj = cx.tcx().anonymize_bound_vars(super_proj);
1459
1460 proj == super_proj
1461 });
1462 !proj_is_implied
1463 })
1464 .map(|proj| {
1465 proj.skip_binder()
1468 })
1469 .collect();
1470
1471 projections
1472 .sort_by_cached_key(|proj| cx.tcx().item_name(proj.def_id).to_string());
1473
1474 if !args.is_empty() || !projections.is_empty() {
1475 p!(generic_delimiters(|cx| {
1476 cx.comma_sep(args.iter().copied())?;
1477 if !args.is_empty() && !projections.is_empty() {
1478 write!(cx, ", ")?;
1479 }
1480 cx.comma_sep(projections.iter().copied())
1481 }));
1482 }
1483 }
1484 Ok(())
1485 })?;
1486
1487 first = false;
1488 }
1489
1490 define_scoped_cx!(self);
1491
1492 let mut auto_traits: Vec<_> = predicates.auto_traits().collect();
1496
1497 auto_traits.sort_by_cached_key(|did| with_no_trimmed_paths!(self.tcx().def_path_str(*did)));
1505
1506 for def_id in auto_traits {
1507 if !first {
1508 p!(" + ");
1509 }
1510 first = false;
1511
1512 p!(print_def_path(def_id, &[]));
1513 }
1514
1515 Ok(())
1516 }
1517
1518 fn pretty_fn_sig(
1519 &mut self,
1520 inputs: &[Ty<'tcx>],
1521 c_variadic: bool,
1522 output: Ty<'tcx>,
1523 ) -> Result<(), PrintError> {
1524 define_scoped_cx!(self);
1525
1526 p!("(", comma_sep(inputs.iter().copied()));
1527 if c_variadic {
1528 if !inputs.is_empty() {
1529 p!(", ");
1530 }
1531 p!("...");
1532 }
1533 p!(")");
1534 if !output.is_unit() {
1535 p!(" -> ", print(output));
1536 }
1537
1538 Ok(())
1539 }
1540
1541 fn pretty_print_const(
1542 &mut self,
1543 ct: ty::Const<'tcx>,
1544 print_ty: bool,
1545 ) -> Result<(), PrintError> {
1546 define_scoped_cx!(self);
1547
1548 if self.should_print_verbose() {
1549 p!(write("{:?}", ct));
1550 return Ok(());
1551 }
1552
1553 match ct.kind() {
1554 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args }) => {
1555 match self.tcx().def_kind(def) {
1556 DefKind::Const | DefKind::AssocConst => {
1557 p!(print_value_path(def, args))
1558 }
1559 DefKind::AnonConst => {
1560 if def.is_local()
1561 && let span = self.tcx().def_span(def)
1562 && let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
1563 {
1564 p!(write("{}", snip))
1565 } else {
1566 p!(write(
1572 "{}::{}",
1573 self.tcx().crate_name(def.krate),
1574 self.tcx().def_path(def).to_string_no_crate_verbose()
1575 ))
1576 }
1577 }
1578 defkind => bug!("`{:?}` has unexpected defkind {:?}", ct, defkind),
1579 }
1580 }
1581 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1582 ty::InferConst::Var(ct_vid) if let Some(name) = self.const_infer_name(ct_vid) => {
1583 p!(write("{}", name))
1584 }
1585 _ => write!(self, "_")?,
1586 },
1587 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1588 ty::ConstKind::Value(cv) => {
1589 return self.pretty_print_const_valtree(cv, print_ty);
1590 }
1591
1592 ty::ConstKind::Bound(debruijn, bound_var) => {
1593 rustc_type_ir::debug_bound_var(self, debruijn, bound_var)?
1594 }
1595 ty::ConstKind::Placeholder(placeholder) => p!(write("{placeholder:?}")),
1596 ty::ConstKind::Expr(expr) => self.pretty_print_const_expr(expr, print_ty)?,
1599 ty::ConstKind::Error(_) => p!("{{const error}}"),
1600 };
1601 Ok(())
1602 }
1603
1604 fn pretty_print_const_expr(
1605 &mut self,
1606 expr: Expr<'tcx>,
1607 print_ty: bool,
1608 ) -> Result<(), PrintError> {
1609 define_scoped_cx!(self);
1610 match expr.kind {
1611 ty::ExprKind::Binop(op) => {
1612 let (_, _, c1, c2) = expr.binop_args();
1613
1614 let precedence = |binop: crate::mir::BinOp| binop.to_hir_binop().precedence();
1615 let op_precedence = precedence(op);
1616 let formatted_op = op.to_hir_binop().as_str();
1617 let (lhs_parenthesized, rhs_parenthesized) = match (c1.kind(), c2.kind()) {
1618 (
1619 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),
1620 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),
1621 ) => (precedence(lhs_op) < op_precedence, precedence(rhs_op) < op_precedence),
1622 (
1623 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),
1624 ty::ConstKind::Expr(_),
1625 ) => (precedence(lhs_op) < op_precedence, true),
1626 (
1627 ty::ConstKind::Expr(_),
1628 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),
1629 ) => (true, precedence(rhs_op) < op_precedence),
1630 (ty::ConstKind::Expr(_), ty::ConstKind::Expr(_)) => (true, true),
1631 (
1632 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),
1633 _,
1634 ) => (precedence(lhs_op) < op_precedence, false),
1635 (
1636 _,
1637 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),
1638 ) => (false, precedence(rhs_op) < op_precedence),
1639 (ty::ConstKind::Expr(_), _) => (true, false),
1640 (_, ty::ConstKind::Expr(_)) => (false, true),
1641 _ => (false, false),
1642 };
1643
1644 self.maybe_parenthesized(
1645 |this| this.pretty_print_const(c1, print_ty),
1646 lhs_parenthesized,
1647 )?;
1648 p!(write(" {formatted_op} "));
1649 self.maybe_parenthesized(
1650 |this| this.pretty_print_const(c2, print_ty),
1651 rhs_parenthesized,
1652 )?;
1653 }
1654 ty::ExprKind::UnOp(op) => {
1655 let (_, ct) = expr.unop_args();
1656
1657 use crate::mir::UnOp;
1658 let formatted_op = match op {
1659 UnOp::Not => "!",
1660 UnOp::Neg => "-",
1661 UnOp::PtrMetadata => "PtrMetadata",
1662 };
1663 let parenthesized = match ct.kind() {
1664 _ if op == UnOp::PtrMetadata => true,
1665 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::UnOp(c_op), .. }) => {
1666 c_op != op
1667 }
1668 ty::ConstKind::Expr(_) => true,
1669 _ => false,
1670 };
1671 p!(write("{formatted_op}"));
1672 self.maybe_parenthesized(
1673 |this| this.pretty_print_const(ct, print_ty),
1674 parenthesized,
1675 )?
1676 }
1677 ty::ExprKind::FunctionCall => {
1678 let (_, fn_def, fn_args) = expr.call_args();
1679
1680 write!(self, "(")?;
1681 self.pretty_print_const(fn_def, print_ty)?;
1682 p!(")(", comma_sep(fn_args), ")");
1683 }
1684 ty::ExprKind::Cast(kind) => {
1685 let (_, value, to_ty) = expr.cast_args();
1686
1687 use ty::abstract_const::CastKind;
1688 if kind == CastKind::As || (kind == CastKind::Use && self.should_print_verbose()) {
1689 let parenthesized = match value.kind() {
1690 ty::ConstKind::Expr(ty::Expr {
1691 kind: ty::ExprKind::Cast { .. }, ..
1692 }) => false,
1693 ty::ConstKind::Expr(_) => true,
1694 _ => false,
1695 };
1696 self.maybe_parenthesized(
1697 |this| {
1698 this.typed_value(
1699 |this| this.pretty_print_const(value, print_ty),
1700 |this| this.pretty_print_type(to_ty),
1701 " as ",
1702 )
1703 },
1704 parenthesized,
1705 )?;
1706 } else {
1707 self.pretty_print_const(value, print_ty)?
1708 }
1709 }
1710 }
1711 Ok(())
1712 }
1713
1714 fn pretty_print_const_scalar(
1715 &mut self,
1716 scalar: Scalar,
1717 ty: Ty<'tcx>,
1718 ) -> Result<(), PrintError> {
1719 match scalar {
1720 Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty),
1721 Scalar::Int(int) => {
1722 self.pretty_print_const_scalar_int(int, ty, true)
1723 }
1724 }
1725 }
1726
1727 fn pretty_print_const_scalar_ptr(
1728 &mut self,
1729 ptr: Pointer,
1730 ty: Ty<'tcx>,
1731 ) -> Result<(), PrintError> {
1732 define_scoped_cx!(self);
1733
1734 let (prov, offset) = ptr.into_parts();
1735 match ty.kind() {
1736 ty::Ref(_, inner, _) => {
1738 if let ty::Array(elem, ct_len) = inner.kind()
1739 && let ty::Uint(ty::UintTy::U8) = elem.kind()
1740 && let Some(len) = ct_len.try_to_target_usize(self.tcx())
1741 {
1742 match self.tcx().try_get_global_alloc(prov.alloc_id()) {
1743 Some(GlobalAlloc::Memory(alloc)) => {
1744 let range = AllocRange { start: offset, size: Size::from_bytes(len) };
1745 if let Ok(byte_str) =
1746 alloc.inner().get_bytes_strip_provenance(&self.tcx(), range)
1747 {
1748 p!(pretty_print_byte_str(byte_str))
1749 } else {
1750 p!("<too short allocation>")
1751 }
1752 }
1753 Some(GlobalAlloc::Static(def_id)) => {
1755 p!(write("<static({:?})>", def_id))
1756 }
1757 Some(GlobalAlloc::Function { .. }) => p!("<function>"),
1758 Some(GlobalAlloc::VTable(..)) => p!("<vtable>"),
1759 None => p!("<dangling pointer>"),
1760 }
1761 return Ok(());
1762 }
1763 }
1764 ty::FnPtr(..) => {
1765 if let Some(GlobalAlloc::Function { instance, .. }) =
1768 self.tcx().try_get_global_alloc(prov.alloc_id())
1769 {
1770 self.typed_value(
1771 |this| this.print_value_path(instance.def_id(), instance.args),
1772 |this| this.print_type(ty),
1773 " as ",
1774 )?;
1775 return Ok(());
1776 }
1777 }
1778 _ => {}
1779 }
1780 self.pretty_print_const_pointer(ptr, ty)?;
1782 Ok(())
1783 }
1784
1785 fn pretty_print_const_scalar_int(
1786 &mut self,
1787 int: ScalarInt,
1788 ty: Ty<'tcx>,
1789 print_ty: bool,
1790 ) -> Result<(), PrintError> {
1791 define_scoped_cx!(self);
1792
1793 match ty.kind() {
1794 ty::Bool if int == ScalarInt::FALSE => p!("false"),
1796 ty::Bool if int == ScalarInt::TRUE => p!("true"),
1797 ty::Float(fty) => match fty {
1799 ty::FloatTy::F16 => {
1800 let val = Half::try_from(int).unwrap();
1801 p!(write("{}{}f16", val, if val.is_finite() { "" } else { "_" }))
1802 }
1803 ty::FloatTy::F32 => {
1804 let val = Single::try_from(int).unwrap();
1805 p!(write("{}{}f32", val, if val.is_finite() { "" } else { "_" }))
1806 }
1807 ty::FloatTy::F64 => {
1808 let val = Double::try_from(int).unwrap();
1809 p!(write("{}{}f64", val, if val.is_finite() { "" } else { "_" }))
1810 }
1811 ty::FloatTy::F128 => {
1812 let val = Quad::try_from(int).unwrap();
1813 p!(write("{}{}f128", val, if val.is_finite() { "" } else { "_" }))
1814 }
1815 },
1816 ty::Uint(_) | ty::Int(_) => {
1818 let int =
1819 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1820 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1821 }
1822 ty::Char if char::try_from(int).is_ok() => {
1824 p!(write("{:?}", char::try_from(int).unwrap()))
1825 }
1826 ty::Ref(..) | ty::RawPtr(_, _) | ty::FnPtr(..) => {
1828 let data = int.to_bits(self.tcx().data_layout.pointer_size);
1829 self.typed_value(
1830 |this| {
1831 write!(this, "0x{data:x}")?;
1832 Ok(())
1833 },
1834 |this| this.print_type(ty),
1835 " as ",
1836 )?;
1837 }
1838 ty::Pat(base_ty, pat) if self.tcx().validate_scalar_in_layout(int, ty) => {
1839 self.pretty_print_const_scalar_int(int, *base_ty, print_ty)?;
1840 p!(write(" is {pat:?}"));
1841 }
1842 _ => {
1844 let print = |this: &mut Self| {
1845 if int.size() == Size::ZERO {
1846 write!(this, "transmute(())")?;
1847 } else {
1848 write!(this, "transmute(0x{int:x})")?;
1849 }
1850 Ok(())
1851 };
1852 if print_ty {
1853 self.typed_value(print, |this| this.print_type(ty), ": ")?
1854 } else {
1855 print(self)?
1856 };
1857 }
1858 }
1859 Ok(())
1860 }
1861
1862 fn pretty_print_const_pointer<Prov: Provenance>(
1865 &mut self,
1866 _: Pointer<Prov>,
1867 ty: Ty<'tcx>,
1868 ) -> Result<(), PrintError> {
1869 self.typed_value(
1870 |this| {
1871 this.write_str("&_")?;
1872 Ok(())
1873 },
1874 |this| this.print_type(ty),
1875 ": ",
1876 )
1877 }
1878
1879 fn pretty_print_byte_str(&mut self, byte_str: &'tcx [u8]) -> Result<(), PrintError> {
1880 write!(self, "b\"{}\"", byte_str.escape_ascii())?;
1881 Ok(())
1882 }
1883
1884 fn pretty_print_const_valtree(
1885 &mut self,
1886 cv: ty::Value<'tcx>,
1887 print_ty: bool,
1888 ) -> Result<(), PrintError> {
1889 define_scoped_cx!(self);
1890
1891 if self.should_print_verbose() {
1892 p!(write("ValTree({:?}: ", cv.valtree), print(cv.ty), ")");
1893 return Ok(());
1894 }
1895
1896 let u8_type = self.tcx().types.u8;
1897 match (*cv.valtree, *cv.ty.kind()) {
1898 (ty::ValTreeKind::Branch(_), ty::Ref(_, inner_ty, _)) => match inner_ty.kind() {
1899 ty::Slice(t) if *t == u8_type => {
1900 let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {
1901 bug!(
1902 "expected to convert valtree {:?} to raw bytes for type {:?}",
1903 cv.valtree,
1904 t
1905 )
1906 });
1907 return self.pretty_print_byte_str(bytes);
1908 }
1909 ty::Str => {
1910 let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {
1911 bug!("expected to convert valtree to raw bytes for type {:?}", cv.ty)
1912 });
1913 p!(write("{:?}", String::from_utf8_lossy(bytes)));
1914 return Ok(());
1915 }
1916 _ => {
1917 let cv = ty::Value { valtree: cv.valtree, ty: inner_ty };
1918 p!("&");
1919 p!(pretty_print_const_valtree(cv, print_ty));
1920 return Ok(());
1921 }
1922 },
1923 (ty::ValTreeKind::Branch(_), ty::Array(t, _)) if t == u8_type => {
1924 let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {
1925 bug!("expected to convert valtree to raw bytes for type {:?}", t)
1926 });
1927 p!("*");
1928 p!(pretty_print_byte_str(bytes));
1929 return Ok(());
1930 }
1931 (ty::ValTreeKind::Branch(_), ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) => {
1933 let contents = self.tcx().destructure_const(ty::Const::new_value(
1934 self.tcx(),
1935 cv.valtree,
1936 cv.ty,
1937 ));
1938 let fields = contents.fields.iter().copied();
1939 match *cv.ty.kind() {
1940 ty::Array(..) => {
1941 p!("[", comma_sep(fields), "]");
1942 }
1943 ty::Tuple(..) => {
1944 p!("(", comma_sep(fields));
1945 if contents.fields.len() == 1 {
1946 p!(",");
1947 }
1948 p!(")");
1949 }
1950 ty::Adt(def, _) if def.variants().is_empty() => {
1951 self.typed_value(
1952 |this| {
1953 write!(this, "unreachable()")?;
1954 Ok(())
1955 },
1956 |this| this.print_type(cv.ty),
1957 ": ",
1958 )?;
1959 }
1960 ty::Adt(def, args) => {
1961 let variant_idx =
1962 contents.variant.expect("destructed const of adt without variant idx");
1963 let variant_def = &def.variant(variant_idx);
1964 p!(print_value_path(variant_def.def_id, args));
1965 match variant_def.ctor_kind() {
1966 Some(CtorKind::Const) => {}
1967 Some(CtorKind::Fn) => {
1968 p!("(", comma_sep(fields), ")");
1969 }
1970 None => {
1971 p!(" {{ ");
1972 let mut first = true;
1973 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1974 if !first {
1975 p!(", ");
1976 }
1977 p!(write("{}: ", field_def.name), print(field));
1978 first = false;
1979 }
1980 p!(" }}");
1981 }
1982 }
1983 }
1984 _ => unreachable!(),
1985 }
1986 return Ok(());
1987 }
1988 (ty::ValTreeKind::Leaf(leaf), ty::Ref(_, inner_ty, _)) => {
1989 p!(write("&"));
1990 return self.pretty_print_const_scalar_int(*leaf, inner_ty, print_ty);
1991 }
1992 (ty::ValTreeKind::Leaf(leaf), _) => {
1993 return self.pretty_print_const_scalar_int(*leaf, cv.ty, print_ty);
1994 }
1995 (_, ty::FnDef(def_id, args)) => {
1996 p!(print_value_path(def_id, args));
1998 return Ok(());
1999 }
2000 _ => {}
2003 }
2004
2005 if cv.valtree.is_zst() {
2007 p!(write("<ZST>"));
2008 } else {
2009 p!(write("{:?}", cv.valtree));
2010 }
2011 if print_ty {
2012 p!(": ", print(cv.ty));
2013 }
2014 Ok(())
2015 }
2016
2017 fn pretty_closure_as_impl(
2018 &mut self,
2019 closure: ty::ClosureArgs<TyCtxt<'tcx>>,
2020 ) -> Result<(), PrintError> {
2021 let sig = closure.sig();
2022 let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn);
2023
2024 write!(self, "impl ")?;
2025 self.wrap_binder(&sig, WrapBinderMode::ForAll, |sig, cx| {
2026 define_scoped_cx!(cx);
2027
2028 p!(write("{kind}("));
2029 for (i, arg) in sig.inputs()[0].tuple_fields().iter().enumerate() {
2030 if i > 0 {
2031 p!(", ");
2032 }
2033 p!(print(arg));
2034 }
2035 p!(")");
2036
2037 if !sig.output().is_unit() {
2038 p!(" -> ", print(sig.output()));
2039 }
2040
2041 Ok(())
2042 })
2043 }
2044
2045 fn pretty_print_bound_constness(
2046 &mut self,
2047 constness: ty::BoundConstness,
2048 ) -> Result<(), PrintError> {
2049 define_scoped_cx!(self);
2050
2051 match constness {
2052 ty::BoundConstness::Const => {
2053 p!("const ");
2054 }
2055 ty::BoundConstness::Maybe => {
2056 p!("~const ");
2057 }
2058 }
2059 Ok(())
2060 }
2061
2062 fn should_print_verbose(&self) -> bool {
2063 self.tcx().sess.verbose_internals()
2064 }
2065}
2066
2067pub(crate) fn pretty_print_const<'tcx>(
2068 c: ty::Const<'tcx>,
2069 fmt: &mut fmt::Formatter<'_>,
2070 print_types: bool,
2071) -> fmt::Result {
2072 ty::tls::with(|tcx| {
2073 let literal = tcx.lift(c).unwrap();
2074 let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2075 cx.print_alloc_ids = true;
2076 cx.pretty_print_const(literal, print_types)?;
2077 fmt.write_str(&cx.into_buffer())?;
2078 Ok(())
2079 })
2080}
2081
2082pub struct FmtPrinter<'a, 'tcx>(Box<FmtPrinterData<'a, 'tcx>>);
2084
2085pub struct FmtPrinterData<'a, 'tcx> {
2086 tcx: TyCtxt<'tcx>,
2087 fmt: String,
2088
2089 empty_path: bool,
2090 in_value: bool,
2091 pub print_alloc_ids: bool,
2092
2093 used_region_names: FxHashSet<Symbol>,
2095
2096 region_index: usize,
2097 binder_depth: usize,
2098 printed_type_count: usize,
2099 type_length_limit: Limit,
2100
2101 pub region_highlight_mode: RegionHighlightMode<'tcx>,
2102
2103 pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<Symbol> + 'a>>,
2104 pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid) -> Option<Symbol> + 'a>>,
2105}
2106
2107impl<'a, 'tcx> Deref for FmtPrinter<'a, 'tcx> {
2108 type Target = FmtPrinterData<'a, 'tcx>;
2109 fn deref(&self) -> &Self::Target {
2110 &self.0
2111 }
2112}
2113
2114impl DerefMut for FmtPrinter<'_, '_> {
2115 fn deref_mut(&mut self) -> &mut Self::Target {
2116 &mut self.0
2117 }
2118}
2119
2120impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
2121 pub fn new(tcx: TyCtxt<'tcx>, ns: Namespace) -> Self {
2122 let limit =
2123 if with_reduced_queries() { Limit::new(1048576) } else { tcx.type_length_limit() };
2124 Self::new_with_limit(tcx, ns, limit)
2125 }
2126
2127 pub fn print_string(
2128 tcx: TyCtxt<'tcx>,
2129 ns: Namespace,
2130 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2131 ) -> Result<String, PrintError> {
2132 let mut c = FmtPrinter::new(tcx, ns);
2133 f(&mut c)?;
2134 Ok(c.into_buffer())
2135 }
2136
2137 pub fn new_with_limit(tcx: TyCtxt<'tcx>, ns: Namespace, type_length_limit: Limit) -> Self {
2138 FmtPrinter(Box::new(FmtPrinterData {
2139 tcx,
2140 fmt: String::with_capacity(64),
2143 empty_path: false,
2144 in_value: ns == Namespace::ValueNS,
2145 print_alloc_ids: false,
2146 used_region_names: Default::default(),
2147 region_index: 0,
2148 binder_depth: 0,
2149 printed_type_count: 0,
2150 type_length_limit,
2151 region_highlight_mode: RegionHighlightMode::default(),
2152 ty_infer_name_resolver: None,
2153 const_infer_name_resolver: None,
2154 }))
2155 }
2156
2157 pub fn into_buffer(self) -> String {
2158 self.0.fmt
2159 }
2160}
2161
2162fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
2165 match tcx.def_key(def_id).disambiguated_data.data {
2166 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::OpaqueTy => {
2167 Namespace::TypeNS
2168 }
2169
2170 DefPathData::ValueNs(..)
2171 | DefPathData::AnonConst
2172 | DefPathData::Closure
2173 | DefPathData::Ctor => Namespace::ValueNS,
2174
2175 DefPathData::MacroNs(..) => Namespace::MacroNS,
2176
2177 _ => Namespace::TypeNS,
2178 }
2179}
2180
2181impl<'t> TyCtxt<'t> {
2182 pub fn def_path_str(self, def_id: impl IntoQueryParam<DefId>) -> String {
2185 self.def_path_str_with_args(def_id, &[])
2186 }
2187
2188 pub fn def_path_str_with_args(
2189 self,
2190 def_id: impl IntoQueryParam<DefId>,
2191 args: &'t [GenericArg<'t>],
2192 ) -> String {
2193 let def_id = def_id.into_query_param();
2194 let ns = guess_def_namespace(self, def_id);
2195 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
2196
2197 FmtPrinter::print_string(self, ns, |cx| cx.print_def_path(def_id, args)).unwrap()
2198 }
2199
2200 pub fn value_path_str_with_args(
2201 self,
2202 def_id: impl IntoQueryParam<DefId>,
2203 args: &'t [GenericArg<'t>],
2204 ) -> String {
2205 let def_id = def_id.into_query_param();
2206 let ns = guess_def_namespace(self, def_id);
2207 debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns);
2208
2209 FmtPrinter::print_string(self, ns, |cx| cx.print_value_path(def_id, args)).unwrap()
2210 }
2211}
2212
2213impl fmt::Write for FmtPrinter<'_, '_> {
2214 fn write_str(&mut self, s: &str) -> fmt::Result {
2215 self.fmt.push_str(s);
2216 Ok(())
2217 }
2218}
2219
2220impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
2221 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
2222 self.tcx
2223 }
2224
2225 fn print_def_path(
2226 &mut self,
2227 def_id: DefId,
2228 args: &'tcx [GenericArg<'tcx>],
2229 ) -> Result<(), PrintError> {
2230 if args.is_empty() {
2231 match self.try_print_trimmed_def_path(def_id)? {
2232 true => return Ok(()),
2233 false => {}
2234 }
2235
2236 match self.try_print_visible_def_path(def_id)? {
2237 true => return Ok(()),
2238 false => {}
2239 }
2240 }
2241
2242 let key = self.tcx.def_key(def_id);
2243 if let DefPathData::Impl = key.disambiguated_data.data {
2244 let use_types = !def_id.is_local() || {
2247 let force_no_types = with_forced_impl_filename_line();
2249 !force_no_types
2250 };
2251
2252 if !use_types {
2253 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
2257 let span = self.tcx.def_span(def_id);
2258
2259 self.print_def_path(parent_def_id, &[])?;
2260
2261 if !self.empty_path {
2264 write!(self, "::")?;
2265 }
2266 write!(
2267 self,
2268 "<impl at {}>",
2269 self.tcx.sess.source_map().span_to_embeddable_string(span)
2272 )?;
2273 self.empty_path = false;
2274
2275 return Ok(());
2276 }
2277 }
2278
2279 self.default_print_def_path(def_id, args)
2280 }
2281
2282 fn print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), PrintError> {
2283 self.pretty_print_region(region)
2284 }
2285
2286 fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
2287 match ty.kind() {
2288 ty::Tuple(tys) if tys.len() == 0 && self.should_truncate() => {
2289 self.printed_type_count += 1;
2291 self.pretty_print_type(ty)
2292 }
2293 ty::Adt(..)
2294 | ty::Foreign(_)
2295 | ty::Pat(..)
2296 | ty::RawPtr(..)
2297 | ty::Ref(..)
2298 | ty::FnDef(..)
2299 | ty::FnPtr(..)
2300 | ty::UnsafeBinder(..)
2301 | ty::Dynamic(..)
2302 | ty::Closure(..)
2303 | ty::CoroutineClosure(..)
2304 | ty::Coroutine(..)
2305 | ty::CoroutineWitness(..)
2306 | ty::Tuple(_)
2307 | ty::Alias(..)
2308 | ty::Param(_)
2309 | ty::Bound(..)
2310 | ty::Placeholder(_)
2311 | ty::Error(_)
2312 if self.should_truncate() =>
2313 {
2314 write!(self, "...")?;
2317 Ok(())
2318 }
2319 _ => {
2320 self.printed_type_count += 1;
2321 self.pretty_print_type(ty)
2322 }
2323 }
2324 }
2325
2326 fn should_truncate(&mut self) -> bool {
2327 !self.type_length_limit.value_within_limit(self.printed_type_count)
2328 }
2329
2330 fn print_dyn_existential(
2331 &mut self,
2332 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2333 ) -> Result<(), PrintError> {
2334 self.pretty_print_dyn_existential(predicates)
2335 }
2336
2337 fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
2338 self.pretty_print_const(ct, false)
2339 }
2340
2341 fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
2342 self.empty_path = true;
2343 if cnum == LOCAL_CRATE {
2344 if self.tcx.sess.at_least_rust_2018() {
2345 if with_crate_prefix() {
2347 write!(self, "{}", kw::Crate)?;
2348 self.empty_path = false;
2349 }
2350 }
2351 } else {
2352 write!(self, "{}", self.tcx.crate_name(cnum))?;
2353 self.empty_path = false;
2354 }
2355 Ok(())
2356 }
2357
2358 fn path_qualified(
2359 &mut self,
2360 self_ty: Ty<'tcx>,
2361 trait_ref: Option<ty::TraitRef<'tcx>>,
2362 ) -> Result<(), PrintError> {
2363 self.pretty_path_qualified(self_ty, trait_ref)?;
2364 self.empty_path = false;
2365 Ok(())
2366 }
2367
2368 fn path_append_impl(
2369 &mut self,
2370 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2371 _disambiguated_data: &DisambiguatedDefPathData,
2372 self_ty: Ty<'tcx>,
2373 trait_ref: Option<ty::TraitRef<'tcx>>,
2374 ) -> Result<(), PrintError> {
2375 self.pretty_path_append_impl(
2376 |cx| {
2377 print_prefix(cx)?;
2378 if !cx.empty_path {
2379 write!(cx, "::")?;
2380 }
2381
2382 Ok(())
2383 },
2384 self_ty,
2385 trait_ref,
2386 )?;
2387 self.empty_path = false;
2388 Ok(())
2389 }
2390
2391 fn path_append(
2392 &mut self,
2393 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2394 disambiguated_data: &DisambiguatedDefPathData,
2395 ) -> Result<(), PrintError> {
2396 print_prefix(self)?;
2397
2398 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
2400 return Ok(());
2401 }
2402
2403 let name = disambiguated_data.data.name();
2404 if !self.empty_path {
2405 write!(self, "::")?;
2406 }
2407
2408 if let DefPathDataName::Named(name) = name {
2409 if Ident::with_dummy_span(name).is_raw_guess() {
2410 write!(self, "r#")?;
2411 }
2412 }
2413
2414 let verbose = self.should_print_verbose();
2415 disambiguated_data.fmt_maybe_verbose(self, verbose)?;
2416
2417 self.empty_path = false;
2418
2419 Ok(())
2420 }
2421
2422 fn path_generic_args(
2423 &mut self,
2424 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2425 args: &[GenericArg<'tcx>],
2426 ) -> Result<(), PrintError> {
2427 print_prefix(self)?;
2428
2429 if !args.is_empty() {
2430 if self.in_value {
2431 write!(self, "::")?;
2432 }
2433 self.generic_delimiters(|cx| cx.comma_sep(args.iter().copied()))
2434 } else {
2435 Ok(())
2436 }
2437 }
2438}
2439
2440impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
2441 fn ty_infer_name(&self, id: ty::TyVid) -> Option<Symbol> {
2442 self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
2443 }
2444
2445 fn reset_type_limit(&mut self) {
2446 self.printed_type_count = 0;
2447 }
2448
2449 fn const_infer_name(&self, id: ty::ConstVid) -> Option<Symbol> {
2450 self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
2451 }
2452
2453 fn print_value_path(
2454 &mut self,
2455 def_id: DefId,
2456 args: &'tcx [GenericArg<'tcx>],
2457 ) -> Result<(), PrintError> {
2458 let was_in_value = std::mem::replace(&mut self.in_value, true);
2459 self.print_def_path(def_id, args)?;
2460 self.in_value = was_in_value;
2461
2462 Ok(())
2463 }
2464
2465 fn print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError>
2466 where
2467 T: Print<'tcx, Self> + TypeFoldable<TyCtxt<'tcx>>,
2468 {
2469 self.pretty_print_in_binder(value)
2470 }
2471
2472 fn wrap_binder<T, C: FnOnce(&T, &mut Self) -> Result<(), PrintError>>(
2473 &mut self,
2474 value: &ty::Binder<'tcx, T>,
2475 mode: WrapBinderMode,
2476 f: C,
2477 ) -> Result<(), PrintError>
2478 where
2479 T: TypeFoldable<TyCtxt<'tcx>>,
2480 {
2481 self.pretty_wrap_binder(value, mode, f)
2482 }
2483
2484 fn typed_value(
2485 &mut self,
2486 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2487 t: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2488 conversion: &str,
2489 ) -> Result<(), PrintError> {
2490 self.write_str("{")?;
2491 f(self)?;
2492 self.write_str(conversion)?;
2493 let was_in_value = std::mem::replace(&mut self.in_value, false);
2494 t(self)?;
2495 self.in_value = was_in_value;
2496 self.write_str("}")?;
2497 Ok(())
2498 }
2499
2500 fn generic_delimiters(
2501 &mut self,
2502 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2503 ) -> Result<(), PrintError> {
2504 write!(self, "<")?;
2505
2506 let was_in_value = std::mem::replace(&mut self.in_value, false);
2507 f(self)?;
2508 self.in_value = was_in_value;
2509
2510 write!(self, ">")?;
2511 Ok(())
2512 }
2513
2514 fn should_print_region(&self, region: ty::Region<'tcx>) -> bool {
2515 let highlight = self.region_highlight_mode;
2516 if highlight.region_highlighted(region).is_some() {
2517 return true;
2518 }
2519
2520 if self.should_print_verbose() {
2521 return true;
2522 }
2523
2524 if with_forced_trimmed_paths() {
2525 return false;
2526 }
2527
2528 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2529
2530 match region.kind() {
2531 ty::ReEarlyParam(ref data) => data.has_name(),
2532
2533 ty::ReLateParam(ty::LateParamRegion { kind, .. }) => kind.is_named(),
2534 ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2535 | ty::RePlaceholder(ty::Placeholder {
2536 bound: ty::BoundRegion { kind: br, .. }, ..
2537 }) => {
2538 if br.is_named() {
2539 return true;
2540 }
2541
2542 if let Some((region, _)) = highlight.highlight_bound_region {
2543 if br == region {
2544 return true;
2545 }
2546 }
2547
2548 false
2549 }
2550
2551 ty::ReVar(_) if identify_regions => true,
2552
2553 ty::ReVar(_) | ty::ReErased | ty::ReError(_) => false,
2554
2555 ty::ReStatic => true,
2556 }
2557 }
2558
2559 fn pretty_print_const_pointer<Prov: Provenance>(
2560 &mut self,
2561 p: Pointer<Prov>,
2562 ty: Ty<'tcx>,
2563 ) -> Result<(), PrintError> {
2564 let print = |this: &mut Self| {
2565 define_scoped_cx!(this);
2566 if this.print_alloc_ids {
2567 p!(write("{:?}", p));
2568 } else {
2569 p!("&_");
2570 }
2571 Ok(())
2572 };
2573 self.typed_value(print, |this| this.print_type(ty), ": ")
2574 }
2575}
2576
2577impl<'tcx> FmtPrinter<'_, 'tcx> {
2579 pub fn pretty_print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), fmt::Error> {
2580 define_scoped_cx!(self);
2581
2582 let highlight = self.region_highlight_mode;
2584 if let Some(n) = highlight.region_highlighted(region) {
2585 p!(write("'{}", n));
2586 return Ok(());
2587 }
2588
2589 if self.should_print_verbose() {
2590 p!(write("{:?}", region));
2591 return Ok(());
2592 }
2593
2594 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2595
2596 match region.kind() {
2601 ty::ReEarlyParam(data) => {
2602 p!(write("{}", data.name));
2603 return Ok(());
2604 }
2605 ty::ReLateParam(ty::LateParamRegion { kind, .. }) => {
2606 if let Some(name) = kind.get_name() {
2607 p!(write("{}", name));
2608 return Ok(());
2609 }
2610 }
2611 ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2612 | ty::RePlaceholder(ty::Placeholder {
2613 bound: ty::BoundRegion { kind: br, .. }, ..
2614 }) => {
2615 if let ty::BoundRegionKind::Named(_, name) = br
2616 && br.is_named()
2617 {
2618 p!(write("{}", name));
2619 return Ok(());
2620 }
2621
2622 if let Some((region, counter)) = highlight.highlight_bound_region {
2623 if br == region {
2624 p!(write("'{}", counter));
2625 return Ok(());
2626 }
2627 }
2628 }
2629 ty::ReVar(region_vid) if identify_regions => {
2630 p!(write("{:?}", region_vid));
2631 return Ok(());
2632 }
2633 ty::ReVar(_) => {}
2634 ty::ReErased => {}
2635 ty::ReError(_) => {}
2636 ty::ReStatic => {
2637 p!("'static");
2638 return Ok(());
2639 }
2640 }
2641
2642 p!("'_");
2643
2644 Ok(())
2645 }
2646}
2647
2648struct RegionFolder<'a, 'tcx> {
2650 tcx: TyCtxt<'tcx>,
2651 current_index: ty::DebruijnIndex,
2652 region_map: UnordMap<ty::BoundRegion, ty::Region<'tcx>>,
2653 name: &'a mut (
2654 dyn FnMut(
2655 Option<ty::DebruijnIndex>, ty::DebruijnIndex, ty::BoundRegion,
2658 ) -> ty::Region<'tcx>
2659 + 'a
2660 ),
2661}
2662
2663impl<'a, 'tcx> ty::TypeFolder<TyCtxt<'tcx>> for RegionFolder<'a, 'tcx> {
2664 fn cx(&self) -> TyCtxt<'tcx> {
2665 self.tcx
2666 }
2667
2668 fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>(
2669 &mut self,
2670 t: ty::Binder<'tcx, T>,
2671 ) -> ty::Binder<'tcx, T> {
2672 self.current_index.shift_in(1);
2673 let t = t.super_fold_with(self);
2674 self.current_index.shift_out(1);
2675 t
2676 }
2677
2678 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2679 match *t.kind() {
2680 _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2681 return t.super_fold_with(self);
2682 }
2683 _ => {}
2684 }
2685 t
2686 }
2687
2688 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2689 let name = &mut self.name;
2690 let region = match r.kind() {
2691 ty::ReBound(db, br) if db >= self.current_index => {
2692 *self.region_map.entry(br).or_insert_with(|| name(Some(db), self.current_index, br))
2693 }
2694 ty::RePlaceholder(ty::PlaceholderRegion {
2695 bound: ty::BoundRegion { kind, .. },
2696 ..
2697 }) => {
2698 match kind {
2701 ty::BoundRegionKind::Anon | ty::BoundRegionKind::ClosureEnv => r,
2702 _ => {
2703 let br = ty::BoundRegion { var: ty::BoundVar::ZERO, kind };
2705 *self
2706 .region_map
2707 .entry(br)
2708 .or_insert_with(|| name(None, self.current_index, br))
2709 }
2710 }
2711 }
2712 _ => return r,
2713 };
2714 if let ty::ReBound(debruijn1, br) = region.kind() {
2715 assert_eq!(debruijn1, ty::INNERMOST);
2716 ty::Region::new_bound(self.tcx, self.current_index, br)
2717 } else {
2718 region
2719 }
2720 }
2721}
2722
2723impl<'tcx> FmtPrinter<'_, 'tcx> {
2726 pub fn name_all_regions<T>(
2727 &mut self,
2728 value: &ty::Binder<'tcx, T>,
2729 mode: WrapBinderMode,
2730 ) -> Result<(T, UnordMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
2731 where
2732 T: TypeFoldable<TyCtxt<'tcx>>,
2733 {
2734 fn name_by_region_index(
2735 index: usize,
2736 available_names: &mut Vec<Symbol>,
2737 num_available: usize,
2738 ) -> Symbol {
2739 if let Some(name) = available_names.pop() {
2740 name
2741 } else {
2742 Symbol::intern(&format!("'z{}", index - num_available))
2743 }
2744 }
2745
2746 debug!("name_all_regions");
2747
2748 if self.binder_depth == 0 {
2754 self.prepare_region_info(value);
2755 }
2756
2757 debug!("self.used_region_names: {:?}", self.used_region_names);
2758
2759 let mut empty = true;
2760 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
2761 let w = if empty {
2762 empty = false;
2763 start
2764 } else {
2765 cont
2766 };
2767 let _ = write!(cx, "{w}");
2768 };
2769 let do_continue = |cx: &mut Self, cont: Symbol| {
2770 let _ = write!(cx, "{cont}");
2771 };
2772
2773 let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&format!("'{s}")));
2774
2775 let mut available_names = possible_names
2776 .filter(|name| !self.used_region_names.contains(name))
2777 .collect::<Vec<_>>();
2778 debug!(?available_names);
2779 let num_available = available_names.len();
2780
2781 let mut region_index = self.region_index;
2782 let mut next_name = |this: &Self| {
2783 let mut name;
2784
2785 loop {
2786 name = name_by_region_index(region_index, &mut available_names, num_available);
2787 region_index += 1;
2788
2789 if !this.used_region_names.contains(&name) {
2790 break;
2791 }
2792 }
2793
2794 name
2795 };
2796
2797 let (new_value, map) = if self.should_print_verbose() {
2802 for var in value.bound_vars().iter() {
2803 start_or_continue(self, mode.start_str(), ", ");
2804 write!(self, "{var:?}")?;
2805 }
2806 if value.bound_vars().is_empty() && mode == WrapBinderMode::Unsafe {
2808 start_or_continue(self, mode.start_str(), "");
2809 }
2810 start_or_continue(self, "", "> ");
2811 (value.clone().skip_binder(), UnordMap::default())
2812 } else {
2813 let tcx = self.tcx;
2814
2815 let trim_path = with_forced_trimmed_paths();
2816 let mut name = |lifetime_idx: Option<ty::DebruijnIndex>,
2822 binder_level_idx: ty::DebruijnIndex,
2823 br: ty::BoundRegion| {
2824 let (name, kind) = match br.kind {
2825 ty::BoundRegionKind::Anon | ty::BoundRegionKind::ClosureEnv => {
2826 let name = next_name(self);
2827
2828 if let Some(lt_idx) = lifetime_idx {
2829 if lt_idx > binder_level_idx {
2830 let kind =
2831 ty::BoundRegionKind::Named(CRATE_DEF_ID.to_def_id(), name);
2832 return ty::Region::new_bound(
2833 tcx,
2834 ty::INNERMOST,
2835 ty::BoundRegion { var: br.var, kind },
2836 );
2837 }
2838 }
2839
2840 (name, ty::BoundRegionKind::Named(CRATE_DEF_ID.to_def_id(), name))
2841 }
2842 ty::BoundRegionKind::Named(def_id, kw::UnderscoreLifetime) => {
2843 let name = next_name(self);
2844
2845 if let Some(lt_idx) = lifetime_idx {
2846 if lt_idx > binder_level_idx {
2847 let kind = ty::BoundRegionKind::Named(def_id, name);
2848 return ty::Region::new_bound(
2849 tcx,
2850 ty::INNERMOST,
2851 ty::BoundRegion { var: br.var, kind },
2852 );
2853 }
2854 }
2855
2856 (name, ty::BoundRegionKind::Named(def_id, name))
2857 }
2858 ty::BoundRegionKind::Named(_, name) => {
2859 if let Some(lt_idx) = lifetime_idx {
2860 if lt_idx > binder_level_idx {
2861 let kind = br.kind;
2862 return ty::Region::new_bound(
2863 tcx,
2864 ty::INNERMOST,
2865 ty::BoundRegion { var: br.var, kind },
2866 );
2867 }
2868 }
2869
2870 (name, br.kind)
2871 }
2872 };
2873
2874 if !trim_path || mode == WrapBinderMode::Unsafe {
2876 start_or_continue(self, mode.start_str(), ", ");
2877 do_continue(self, name);
2878 }
2879 ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { var: br.var, kind })
2880 };
2881 let mut folder = RegionFolder {
2882 tcx,
2883 current_index: ty::INNERMOST,
2884 name: &mut name,
2885 region_map: UnordMap::default(),
2886 };
2887 let new_value = value.clone().skip_binder().fold_with(&mut folder);
2888 let region_map = folder.region_map;
2889
2890 if mode == WrapBinderMode::Unsafe && region_map.is_empty() {
2891 start_or_continue(self, mode.start_str(), "");
2892 }
2893 start_or_continue(self, "", "> ");
2894
2895 (new_value, region_map)
2896 };
2897
2898 self.binder_depth += 1;
2899 self.region_index = region_index;
2900 Ok((new_value, map))
2901 }
2902
2903 pub fn pretty_print_in_binder<T>(
2904 &mut self,
2905 value: &ty::Binder<'tcx, T>,
2906 ) -> Result<(), fmt::Error>
2907 where
2908 T: Print<'tcx, Self> + TypeFoldable<TyCtxt<'tcx>>,
2909 {
2910 let old_region_index = self.region_index;
2911 let (new_value, _) = self.name_all_regions(value, WrapBinderMode::ForAll)?;
2912 new_value.print(self)?;
2913 self.region_index = old_region_index;
2914 self.binder_depth -= 1;
2915 Ok(())
2916 }
2917
2918 pub fn pretty_wrap_binder<T, C: FnOnce(&T, &mut Self) -> Result<(), fmt::Error>>(
2919 &mut self,
2920 value: &ty::Binder<'tcx, T>,
2921 mode: WrapBinderMode,
2922 f: C,
2923 ) -> Result<(), fmt::Error>
2924 where
2925 T: TypeFoldable<TyCtxt<'tcx>>,
2926 {
2927 let old_region_index = self.region_index;
2928 let (new_value, _) = self.name_all_regions(value, mode)?;
2929 f(&new_value, self)?;
2930 self.region_index = old_region_index;
2931 self.binder_depth -= 1;
2932 Ok(())
2933 }
2934
2935 fn prepare_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2936 where
2937 T: TypeFoldable<TyCtxt<'tcx>>,
2938 {
2939 struct RegionNameCollector<'tcx> {
2940 used_region_names: FxHashSet<Symbol>,
2941 type_collector: SsoHashSet<Ty<'tcx>>,
2942 }
2943
2944 impl<'tcx> RegionNameCollector<'tcx> {
2945 fn new() -> Self {
2946 RegionNameCollector {
2947 used_region_names: Default::default(),
2948 type_collector: SsoHashSet::new(),
2949 }
2950 }
2951 }
2952
2953 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for RegionNameCollector<'tcx> {
2954 fn visit_region(&mut self, r: ty::Region<'tcx>) {
2955 trace!("address: {:p}", r.0.0);
2956
2957 if let Some(name) = r.get_name() {
2961 self.used_region_names.insert(name);
2962 }
2963 }
2964
2965 fn visit_ty(&mut self, ty: Ty<'tcx>) {
2968 let not_previously_inserted = self.type_collector.insert(ty);
2969 if not_previously_inserted {
2970 ty.super_visit_with(self)
2971 }
2972 }
2973 }
2974
2975 let mut collector = RegionNameCollector::new();
2976 value.visit_with(&mut collector);
2977 self.used_region_names = collector.used_region_names;
2978 self.region_index = 0;
2979 }
2980}
2981
2982impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2983where
2984 T: Print<'tcx, P> + TypeFoldable<TyCtxt<'tcx>>,
2985{
2986 fn print(&self, cx: &mut P) -> Result<(), PrintError> {
2987 cx.print_in_binder(self)
2988 }
2989}
2990
2991impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<'tcx, T>
2992where
2993 T: Print<'tcx, P>,
2994{
2995 fn print(&self, cx: &mut P) -> Result<(), PrintError> {
2996 define_scoped_cx!(cx);
2997 p!(print(self.0), ": ", print(self.1));
2998 Ok(())
2999 }
3000}
3001
3002#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
3006pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
3007
3008impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintOnlyTraitPath<'tcx> {
3009 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
3010 ty::tls::with(|tcx| {
3011 let trait_ref = tcx.short_string(self, path);
3012 rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
3013 })
3014 }
3015}
3016
3017impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
3018 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3019 fmt::Display::fmt(self, f)
3020 }
3021}
3022
3023#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
3026pub struct TraitRefPrintSugared<'tcx>(ty::TraitRef<'tcx>);
3027
3028impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintSugared<'tcx> {
3029 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
3030 ty::tls::with(|tcx| {
3031 let trait_ref = tcx.short_string(self, path);
3032 rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
3033 })
3034 }
3035}
3036
3037impl<'tcx> fmt::Debug for TraitRefPrintSugared<'tcx> {
3038 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3039 fmt::Display::fmt(self, f)
3040 }
3041}
3042
3043#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
3047pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
3048
3049impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
3050 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3051 fmt::Display::fmt(self, f)
3052 }
3053}
3054
3055#[extension(pub trait PrintTraitRefExt<'tcx>)]
3056impl<'tcx> ty::TraitRef<'tcx> {
3057 fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
3058 TraitRefPrintOnlyTraitPath(self)
3059 }
3060
3061 fn print_trait_sugared(self) -> TraitRefPrintSugared<'tcx> {
3062 TraitRefPrintSugared(self)
3063 }
3064
3065 fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
3066 TraitRefPrintOnlyTraitName(self)
3067 }
3068}
3069
3070#[extension(pub trait PrintPolyTraitRefExt<'tcx>)]
3071impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
3072 fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
3073 self.map_bound(|tr| tr.print_only_trait_path())
3074 }
3075
3076 fn print_trait_sugared(self) -> ty::Binder<'tcx, TraitRefPrintSugared<'tcx>> {
3077 self.map_bound(|tr| tr.print_trait_sugared())
3078 }
3079}
3080
3081#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
3082pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
3083
3084impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
3085 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3086 fmt::Display::fmt(self, f)
3087 }
3088}
3089
3090#[extension(pub trait PrintTraitPredicateExt<'tcx>)]
3091impl<'tcx> ty::TraitPredicate<'tcx> {
3092 fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
3093 TraitPredPrintModifiersAndPath(self)
3094 }
3095}
3096
3097#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
3098pub struct TraitPredPrintWithBoundConstness<'tcx>(
3099 ty::TraitPredicate<'tcx>,
3100 Option<ty::BoundConstness>,
3101);
3102
3103impl<'tcx> fmt::Debug for TraitPredPrintWithBoundConstness<'tcx> {
3104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3105 fmt::Display::fmt(self, f)
3106 }
3107}
3108
3109#[extension(pub trait PrintPolyTraitPredicateExt<'tcx>)]
3110impl<'tcx> ty::PolyTraitPredicate<'tcx> {
3111 fn print_modifiers_and_trait_path(
3112 self,
3113 ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
3114 self.map_bound(TraitPredPrintModifiersAndPath)
3115 }
3116
3117 fn print_with_bound_constness(
3118 self,
3119 constness: Option<ty::BoundConstness>,
3120 ) -> ty::Binder<'tcx, TraitPredPrintWithBoundConstness<'tcx>> {
3121 self.map_bound(|trait_pred| TraitPredPrintWithBoundConstness(trait_pred, constness))
3122 }
3123}
3124
3125#[derive(Debug, Copy, Clone, Lift)]
3126pub struct PrintClosureAsImpl<'tcx> {
3127 pub closure: ty::ClosureArgs<TyCtxt<'tcx>>,
3128}
3129
3130macro_rules! forward_display_to_print {
3131 ($($ty:ty),+) => {
3132 $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty {
3134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3135 ty::tls::with(|tcx| {
3136 let mut cx = FmtPrinter::new(tcx, Namespace::TypeNS);
3137 tcx.lift(*self)
3138 .expect("could not lift for printing")
3139 .print(&mut cx)?;
3140 f.write_str(&cx.into_buffer())?;
3141 Ok(())
3142 })
3143 }
3144 })+
3145 };
3146}
3147
3148macro_rules! define_print {
3149 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
3150 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
3151 fn print(&$self, $cx: &mut P) -> Result<(), PrintError> {
3152 define_scoped_cx!($cx);
3153 let _: () = $print;
3154 Ok(())
3155 }
3156 })+
3157 };
3158}
3159
3160macro_rules! define_print_and_forward_display {
3161 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
3162 define_print!(($self, $cx): $($ty $print)*);
3163 forward_display_to_print!($($ty),+);
3164 };
3165}
3166
3167forward_display_to_print! {
3168 ty::Region<'tcx>,
3169 Ty<'tcx>,
3170 &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3171 ty::Const<'tcx>
3172}
3173
3174define_print! {
3175 (self, cx):
3176
3177 ty::FnSig<'tcx> {
3178 p!(write("{}", self.safety.prefix_str()));
3179
3180 if self.abi != ExternAbi::Rust {
3181 p!(write("extern {} ", self.abi));
3182 }
3183
3184 p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
3185 }
3186
3187 ty::TraitRef<'tcx> {
3188 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
3189 }
3190
3191 ty::AliasTy<'tcx> {
3192 let alias_term: ty::AliasTerm<'tcx> = (*self).into();
3193 p!(print(alias_term))
3194 }
3195
3196 ty::AliasTerm<'tcx> {
3197 match self.kind(cx.tcx()) {
3198 ty::AliasTermKind::InherentTy | ty::AliasTermKind::InherentConst => p!(pretty_print_inherent_projection(*self)),
3199 ty::AliasTermKind::ProjectionTy => {
3200 if !(cx.should_print_verbose() || with_reduced_queries())
3201 && cx.tcx().is_impl_trait_in_trait(self.def_id)
3202 {
3203 p!(pretty_print_rpitit(self.def_id, self.args))
3204 } else {
3205 p!(print_def_path(self.def_id, self.args));
3206 }
3207 }
3208 ty::AliasTermKind::FreeTy
3209 | ty::AliasTermKind::FreeConst
3210 | ty::AliasTermKind::OpaqueTy
3211 | ty::AliasTermKind::UnevaluatedConst
3212 | ty::AliasTermKind::ProjectionConst => {
3213 p!(print_def_path(self.def_id, self.args));
3214 }
3215 }
3216 }
3217
3218 ty::TraitPredicate<'tcx> {
3219 p!(print(self.trait_ref.self_ty()), ": ");
3220 if let ty::PredicatePolarity::Negative = self.polarity {
3221 p!("!");
3222 }
3223 p!(print(self.trait_ref.print_trait_sugared()))
3224 }
3225
3226 ty::HostEffectPredicate<'tcx> {
3227 let constness = match self.constness {
3228 ty::BoundConstness::Const => { "const" }
3229 ty::BoundConstness::Maybe => { "~const" }
3230 };
3231 p!(print(self.trait_ref.self_ty()), ": {constness} ");
3232 p!(print(self.trait_ref.print_trait_sugared()))
3233 }
3234
3235 ty::TypeAndMut<'tcx> {
3236 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
3237 }
3238
3239 ty::ClauseKind<'tcx> {
3240 match *self {
3241 ty::ClauseKind::Trait(ref data) => {
3242 p!(print(data))
3243 }
3244 ty::ClauseKind::RegionOutlives(predicate) => p!(print(predicate)),
3245 ty::ClauseKind::TypeOutlives(predicate) => p!(print(predicate)),
3246 ty::ClauseKind::Projection(predicate) => p!(print(predicate)),
3247 ty::ClauseKind::HostEffect(predicate) => p!(print(predicate)),
3248 ty::ClauseKind::ConstArgHasType(ct, ty) => {
3249 p!("the constant `", print(ct), "` has type `", print(ty), "`")
3250 },
3251 ty::ClauseKind::WellFormed(term) => p!(print(term), " well-formed"),
3252 ty::ClauseKind::ConstEvaluatable(ct) => {
3253 p!("the constant `", print(ct), "` can be evaluated")
3254 }
3255 }
3256 }
3257
3258 ty::PredicateKind<'tcx> {
3259 match *self {
3260 ty::PredicateKind::Clause(data) => {
3261 p!(print(data))
3262 }
3263 ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
3264 ty::PredicateKind::Coerce(predicate) => p!(print(predicate)),
3265 ty::PredicateKind::DynCompatible(trait_def_id) => {
3266 p!("the trait `", print_def_path(trait_def_id, &[]), "` is dyn-compatible")
3267 }
3268 ty::PredicateKind::ConstEquate(c1, c2) => {
3269 p!("the constant `", print(c1), "` equals `", print(c2), "`")
3270 }
3271 ty::PredicateKind::Ambiguous => p!("ambiguous"),
3272 ty::PredicateKind::NormalizesTo(data) => p!(print(data)),
3273 ty::PredicateKind::AliasRelate(t1, t2, dir) => p!(print(t1), write(" {} ", dir), print(t2)),
3274 }
3275 }
3276
3277 ty::ExistentialPredicate<'tcx> {
3278 match *self {
3279 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
3280 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
3281 ty::ExistentialPredicate::AutoTrait(def_id) => {
3282 p!(print_def_path(def_id, &[]));
3283 }
3284 }
3285 }
3286
3287 ty::ExistentialTraitRef<'tcx> {
3288 let dummy_self = Ty::new_fresh(cx.tcx(), 0);
3290 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
3291 p!(print(trait_ref.print_only_trait_path()))
3292 }
3293
3294 ty::ExistentialProjection<'tcx> {
3295 let name = cx.tcx().associated_item(self.def_id).name();
3296 let args = &self.args[cx.tcx().generics_of(self.def_id).parent_count - 1..];
3299 p!(path_generic_args(|cx| write!(cx, "{name}"), args), " = ", print(self.term))
3300 }
3301
3302 ty::ProjectionPredicate<'tcx> {
3303 p!(print(self.projection_term), " == ");
3304 cx.reset_type_limit();
3305 p!(print(self.term))
3306 }
3307
3308 ty::SubtypePredicate<'tcx> {
3309 p!(print(self.a), " <: ");
3310 cx.reset_type_limit();
3311 p!(print(self.b))
3312 }
3313
3314 ty::CoercePredicate<'tcx> {
3315 p!(print(self.a), " -> ");
3316 cx.reset_type_limit();
3317 p!(print(self.b))
3318 }
3319
3320 ty::NormalizesTo<'tcx> {
3321 p!(print(self.alias), " normalizes-to ");
3322 cx.reset_type_limit();
3323 p!(print(self.term))
3324 }
3325}
3326
3327define_print_and_forward_display! {
3328 (self, cx):
3329
3330 &'tcx ty::List<Ty<'tcx>> {
3331 p!("{{", comma_sep(self.iter()), "}}")
3332 }
3333
3334 TraitRefPrintOnlyTraitPath<'tcx> {
3335 p!(print_def_path(self.0.def_id, self.0.args));
3336 }
3337
3338 TraitRefPrintSugared<'tcx> {
3339 if !with_reduced_queries()
3340 && cx.tcx().trait_def(self.0.def_id).paren_sugar
3341 && let ty::Tuple(args) = self.0.args.type_at(1).kind()
3342 {
3343 p!(write("{}", cx.tcx().item_name(self.0.def_id)), "(");
3344 for (i, arg) in args.iter().enumerate() {
3345 if i > 0 {
3346 p!(", ");
3347 }
3348 p!(print(arg));
3349 }
3350 p!(")");
3351 } else {
3352 p!(print_def_path(self.0.def_id, self.0.args));
3353 }
3354 }
3355
3356 TraitRefPrintOnlyTraitName<'tcx> {
3357 p!(print_def_path(self.0.def_id, &[]));
3358 }
3359
3360 TraitPredPrintModifiersAndPath<'tcx> {
3361 if let ty::PredicatePolarity::Negative = self.0.polarity {
3362 p!("!")
3363 }
3364 p!(print(self.0.trait_ref.print_trait_sugared()));
3365 }
3366
3367 TraitPredPrintWithBoundConstness<'tcx> {
3368 p!(print(self.0.trait_ref.self_ty()), ": ");
3369 if let Some(constness) = self.1 {
3370 p!(pretty_print_bound_constness(constness));
3371 }
3372 if let ty::PredicatePolarity::Negative = self.0.polarity {
3373 p!("!");
3374 }
3375 p!(print(self.0.trait_ref.print_trait_sugared()))
3376 }
3377
3378 PrintClosureAsImpl<'tcx> {
3379 p!(pretty_closure_as_impl(self.closure))
3380 }
3381
3382 ty::ParamTy {
3383 p!(write("{}", self.name))
3384 }
3385
3386 ty::ParamConst {
3387 p!(write("{}", self.name))
3388 }
3389
3390 ty::Term<'tcx> {
3391 match self.unpack() {
3392 ty::TermKind::Ty(ty) => p!(print(ty)),
3393 ty::TermKind::Const(c) => p!(print(c)),
3394 }
3395 }
3396
3397 ty::Predicate<'tcx> {
3398 p!(print(self.kind()))
3399 }
3400
3401 ty::Clause<'tcx> {
3402 p!(print(self.kind()))
3403 }
3404
3405 GenericArg<'tcx> {
3406 match self.unpack() {
3407 GenericArgKind::Lifetime(lt) => p!(print(lt)),
3408 GenericArgKind::Type(ty) => p!(print(ty)),
3409 GenericArgKind::Const(ct) => p!(print(ct)),
3410 }
3411 }
3412}
3413
3414fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
3415 for id in tcx.hir_free_items() {
3417 if matches!(tcx.def_kind(id.owner_id), DefKind::Use) {
3418 continue;
3419 }
3420
3421 let item = tcx.hir_item(id);
3422 let Some(ident) = item.kind.ident() else { continue };
3423
3424 let def_id = item.owner_id.to_def_id();
3425 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
3426 collect_fn(&ident, ns, def_id);
3427 }
3428
3429 let queue = &mut Vec::new();
3431 let mut seen_defs: DefIdSet = Default::default();
3432
3433 for &cnum in tcx.crates(()).iter() {
3434 match tcx.extern_crate(cnum) {
3436 None => continue,
3437 Some(extern_crate) => {
3438 if !extern_crate.is_direct() {
3439 continue;
3440 }
3441 }
3442 }
3443
3444 queue.push(cnum.as_def_id());
3445 }
3446
3447 while let Some(def) = queue.pop() {
3449 for child in tcx.module_children(def).iter() {
3450 if !child.vis.is_public() {
3451 continue;
3452 }
3453
3454 match child.res {
3455 def::Res::Def(DefKind::AssocTy, _) => {}
3456 def::Res::Def(DefKind::TyAlias, _) => {}
3457 def::Res::Def(defkind, def_id) => {
3458 if let Some(ns) = defkind.ns() {
3459 collect_fn(&child.ident, ns, def_id);
3460 }
3461
3462 if matches!(defkind, DefKind::Mod | DefKind::Enum | DefKind::Trait)
3463 && seen_defs.insert(def_id)
3464 {
3465 queue.push(def_id);
3466 }
3467 }
3468 _ => {}
3469 }
3470 }
3471 }
3472}
3473
3474pub fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> DefIdMap<Symbol> {
3490 tcx.sess.record_trimmed_def_paths();
3497
3498 let unique_symbols_rev: &mut FxIndexMap<(Namespace, Symbol), Option<DefId>> =
3501 &mut FxIndexMap::default();
3502
3503 for symbol_set in tcx.resolutions(()).glob_map.values() {
3504 for symbol in symbol_set {
3505 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
3506 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
3507 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
3508 }
3509 }
3510
3511 for_each_def(tcx, |ident, ns, def_id| match unique_symbols_rev.entry((ns, ident.name)) {
3512 IndexEntry::Occupied(mut v) => match v.get() {
3513 None => {}
3514 Some(existing) => {
3515 if *existing != def_id {
3516 v.insert(None);
3517 }
3518 }
3519 },
3520 IndexEntry::Vacant(v) => {
3521 v.insert(Some(def_id));
3522 }
3523 });
3524
3525 let mut map: DefIdMap<Symbol> = Default::default();
3527 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain(..) {
3528 use std::collections::hash_map::Entry::{Occupied, Vacant};
3529
3530 if let Some(def_id) = opt_def_id {
3531 match map.entry(def_id) {
3532 Occupied(mut v) => {
3533 if *v.get() != symbol && v.get().as_str() > symbol.as_str() {
3542 v.insert(symbol);
3543 }
3544 }
3545 Vacant(v) => {
3546 v.insert(symbol);
3547 }
3548 }
3549 }
3550 }
3551
3552 map
3553}
3554
3555pub fn provide(providers: &mut Providers) {
3556 *providers = Providers { trimmed_def_paths, ..*providers };
3557}
3558
3559pub struct OpaqueFnEntry<'tcx> {
3560 kind: ty::ClosureKind,
3561 return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,
3562}