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