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_hir::limit::Limit;
17use rustc_macros::{Lift, extension};
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
32thread_local! {
33 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = const { Cell::new(false) };
34 static SHOULD_PREFIX_WITH_CRATE_NAME: Cell<bool> = const { Cell::new(false) };
35 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = const { Cell::new(false) };
36 static NO_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
37 static FORCE_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
38 static REDUCED_QUERIES: Cell<bool> = const { Cell::new(false) };
39 static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) };
40 static NO_VISIBLE_PATH_IF_DOC_HIDDEN: Cell<bool> = const { Cell::new(false) };
41 static RTN_MODE: Cell<RtnMode> = const { Cell::new(RtnMode::ForDiagnostic) };
42}
43
44#[derive(Copy, Clone, PartialEq, Eq, Debug)]
46pub enum RtnMode {
47 ForDiagnostic,
49 ForSignature,
51 ForSuggestion,
53}
54
55macro_rules! define_helper {
56 ($($(#[$a:meta])* fn $name:ident($helper:ident, $tl:ident);)+) => {
57 $(
58 #[must_use]
59 pub struct $helper(bool);
60
61 impl $helper {
62 pub fn new() -> $helper {
63 $helper($tl.replace(true))
64 }
65 }
66
67 $(#[$a])*
68 pub macro $name($e:expr) {
69 {
70 let _guard = $helper::new();
71 $e
72 }
73 }
74
75 impl Drop for $helper {
76 fn drop(&mut self) {
77 $tl.set(self.0)
78 }
79 }
80
81 pub fn $name() -> bool {
82 $tl.get()
83 }
84 )+
85 }
86}
87
88define_helper!(
89 fn with_reduced_queries(ReducedQueriesGuard, REDUCED_QUERIES);
97 fn with_forced_impl_filename_line(ForcedImplGuard, FORCE_IMPL_FILENAME_LINE);
102 fn with_resolve_crate_name(CrateNamePrefixGuard, SHOULD_PREFIX_WITH_CRATE_NAME);
111 fn with_crate_prefix(CratePrefixGuard, SHOULD_PREFIX_WITH_CRATE);
115 fn with_no_trimmed_paths(NoTrimmedGuard, NO_TRIMMED_PATH);
119 fn with_forced_trimmed_paths(ForceTrimmedGuard, FORCE_TRIMMED_PATH);
120 fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH);
123 fn with_no_visible_paths_if_doc_hidden(NoVisibleIfDocHiddenGuard, NO_VISIBLE_PATH_IF_DOC_HIDDEN);
125);
126
127#[must_use]
128pub struct RtnModeHelper(RtnMode);
129
130impl RtnModeHelper {
131 pub fn with(mode: RtnMode) -> RtnModeHelper {
132 RtnModeHelper(RTN_MODE.with(|c| c.replace(mode)))
133 }
134}
135
136impl Drop for RtnModeHelper {
137 fn drop(&mut self) {
138 RTN_MODE.with(|c| c.set(self.0))
139 }
140}
141
142pub macro with_types_for_suggestion($e:expr) {{
147 let _guard = $crate::ty::print::pretty::RtnModeHelper::with(RtnMode::ForSuggestion);
148 $e
149}}
150
151pub macro with_types_for_signature($e:expr) {{
155 let _guard = $crate::ty::print::pretty::RtnModeHelper::with(RtnMode::ForSignature);
156 $e
157}}
158
159pub macro with_no_queries($e:expr) {{
161 $crate::ty::print::with_reduced_queries!($crate::ty::print::with_forced_impl_filename_line!(
162 $crate::ty::print::with_no_trimmed_paths!($crate::ty::print::with_no_visible_paths!(
163 $crate::ty::print::with_forced_impl_filename_line!($e)
164 ))
165 ))
166}}
167
168#[derive(Copy, Clone, Debug, PartialEq, Eq)]
169pub enum WrapBinderMode {
170 ForAll,
171 Unsafe,
172}
173impl WrapBinderMode {
174 pub fn start_str(self) -> &'static str {
175 match self {
176 WrapBinderMode::ForAll => "for<",
177 WrapBinderMode::Unsafe => "unsafe<",
178 }
179 }
180}
181
182#[derive(Copy, Clone, Default)]
190pub struct RegionHighlightMode<'tcx> {
191 highlight_regions: [Option<(ty::Region<'tcx>, usize)>; 3],
194
195 highlight_bound_region: Option<(ty::BoundRegionKind, usize)>,
203}
204
205impl<'tcx> RegionHighlightMode<'tcx> {
206 pub fn maybe_highlighting_region(
209 &mut self,
210 region: Option<ty::Region<'tcx>>,
211 number: Option<usize>,
212 ) {
213 if let Some(k) = region
214 && let Some(n) = number
215 {
216 self.highlighting_region(k, n);
217 }
218 }
219
220 pub fn highlighting_region(&mut self, region: ty::Region<'tcx>, number: usize) {
222 let num_slots = self.highlight_regions.len();
223 let first_avail_slot =
224 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
225 bug!("can only highlight {} placeholders at a time", num_slots,)
226 });
227 *first_avail_slot = Some((region, number));
228 }
229
230 pub fn highlighting_region_vid(
232 &mut self,
233 tcx: TyCtxt<'tcx>,
234 vid: ty::RegionVid,
235 number: usize,
236 ) {
237 self.highlighting_region(ty::Region::new_var(tcx, vid), number)
238 }
239
240 fn region_highlighted(&self, region: ty::Region<'tcx>) -> Option<usize> {
242 self.highlight_regions.iter().find_map(|h| match h {
243 Some((r, n)) if *r == region => Some(*n),
244 _ => None,
245 })
246 }
247
248 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) {
252 assert!(self.highlight_bound_region.is_none());
253 self.highlight_bound_region = Some((br, number));
254 }
255}
256
257pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
259 fn pretty_print_value_path(
261 &mut self,
262 def_id: DefId,
263 args: &'tcx [GenericArg<'tcx>],
264 ) -> Result<(), PrintError> {
265 self.print_def_path(def_id, args)
266 }
267
268 fn pretty_print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError>
269 where
270 T: Print<'tcx, Self> + TypeFoldable<TyCtxt<'tcx>>,
271 {
272 value.as_ref().skip_binder().print(self)
273 }
274
275 fn wrap_binder<T, F: FnOnce(&T, &mut Self) -> Result<(), fmt::Error>>(
276 &mut self,
277 value: &ty::Binder<'tcx, T>,
278 _mode: WrapBinderMode,
279 f: F,
280 ) -> Result<(), PrintError>
281 where
282 T: TypeFoldable<TyCtxt<'tcx>>,
283 {
284 f(value.as_ref().skip_binder(), self)
285 }
286
287 fn comma_sep<T>(&mut self, mut elems: impl Iterator<Item = T>) -> Result<(), PrintError>
289 where
290 T: Print<'tcx, Self>,
291 {
292 if let Some(first) = elems.next() {
293 first.print(self)?;
294 for elem in elems {
295 self.write_str(", ")?;
296 elem.print(self)?;
297 }
298 }
299 Ok(())
300 }
301
302 fn typed_value(
304 &mut self,
305 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
306 t: impl FnOnce(&mut Self) -> Result<(), PrintError>,
307 conversion: &str,
308 ) -> Result<(), PrintError> {
309 self.write_str("{")?;
310 f(self)?;
311 self.write_str(conversion)?;
312 t(self)?;
313 self.write_str("}")?;
314 Ok(())
315 }
316
317 fn parenthesized(
319 &mut self,
320 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
321 ) -> Result<(), PrintError> {
322 self.write_str("(")?;
323 f(self)?;
324 self.write_str(")")?;
325 Ok(())
326 }
327
328 fn maybe_parenthesized(
330 &mut self,
331 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
332 parenthesized: bool,
333 ) -> Result<(), PrintError> {
334 if parenthesized {
335 self.parenthesized(f)?;
336 } else {
337 f(self)?;
338 }
339 Ok(())
340 }
341
342 fn generic_delimiters(
344 &mut self,
345 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
346 ) -> Result<(), PrintError>;
347
348 fn should_truncate(&mut self) -> bool {
349 false
350 }
351
352 fn should_print_optional_region(&self, region: ty::Region<'tcx>) -> bool;
356
357 fn reset_type_limit(&mut self) {}
358
359 fn try_print_visible_def_path(&mut self, def_id: DefId) -> Result<bool, PrintError> {
365 if with_no_visible_paths() {
366 return Ok(false);
367 }
368
369 let mut callers = Vec::new();
370 self.try_print_visible_def_path_recur(def_id, &mut callers)
371 }
372
373 fn force_print_trimmed_def_path(&mut self, def_id: DefId) -> Result<bool, PrintError> {
379 let key = self.tcx().def_key(def_id);
380 let visible_parent_map = self.tcx().visible_parent_map(());
381 let kind = self.tcx().def_kind(def_id);
382
383 let get_local_name = |this: &Self, name, def_id, key: DefKey| {
384 if let Some(visible_parent) = visible_parent_map.get(&def_id)
385 && let actual_parent = this.tcx().opt_parent(def_id)
386 && let DefPathData::TypeNs(_) = key.disambiguated_data.data
387 && Some(*visible_parent) != actual_parent
388 {
389 this.tcx()
390 .module_children(ModDefId::new_unchecked(*visible_parent))
392 .iter()
393 .filter(|child| child.res.opt_def_id() == Some(def_id))
394 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
395 .map(|child| child.ident.name)
396 .unwrap_or(name)
397 } else {
398 name
399 }
400 };
401 if let DefKind::Variant = kind
402 && let Some(symbol) = self.tcx().trimmed_def_paths(()).get(&def_id)
403 {
404 self.write_str(get_local_name(self, *symbol, def_id, key).as_str())?;
406 return Ok(true);
407 }
408 if let Some(symbol) = key.get_opt_name() {
409 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = kind
410 && let Some(parent) = self.tcx().opt_parent(def_id)
411 && let parent_key = self.tcx().def_key(parent)
412 && let Some(symbol) = parent_key.get_opt_name()
413 {
414 self.write_str(get_local_name(self, symbol, parent, parent_key).as_str())?;
416 self.write_str("::")?;
417 } else if let DefKind::Variant = kind
418 && let Some(parent) = self.tcx().opt_parent(def_id)
419 && let parent_key = self.tcx().def_key(parent)
420 && let Some(symbol) = parent_key.get_opt_name()
421 {
422 self.write_str(get_local_name(self, symbol, parent, parent_key).as_str())?;
427 self.write_str("::")?;
428 } else if let DefKind::Struct
429 | DefKind::Union
430 | DefKind::Enum
431 | DefKind::Trait
432 | DefKind::TyAlias
433 | DefKind::Fn
434 | DefKind::Const
435 | DefKind::Static { .. } = kind
436 {
437 } else {
438 return Ok(false);
440 }
441 self.write_str(get_local_name(self, symbol, def_id, key).as_str())?;
442 return Ok(true);
443 }
444 Ok(false)
445 }
446
447 fn try_print_trimmed_def_path(&mut self, def_id: DefId) -> Result<bool, PrintError> {
449 if with_forced_trimmed_paths() && self.force_print_trimmed_def_path(def_id)? {
450 return Ok(true);
451 }
452 if self.tcx().sess.opts.unstable_opts.trim_diagnostic_paths
453 && self.tcx().sess.opts.trimmed_def_paths
454 && !with_no_trimmed_paths()
455 && !with_crate_prefix()
456 && let Some(symbol) = self.tcx().trimmed_def_paths(()).get(&def_id)
457 {
458 write!(self, "{}", Ident::with_dummy_span(*symbol))?;
459 Ok(true)
460 } else {
461 Ok(false)
462 }
463 }
464
465 fn try_print_visible_def_path_recur(
479 &mut self,
480 def_id: DefId,
481 callers: &mut Vec<DefId>,
482 ) -> Result<bool, PrintError> {
483 debug!("try_print_visible_def_path: def_id={:?}", def_id);
484
485 if let Some(cnum) = def_id.as_crate_root() {
488 if cnum == LOCAL_CRATE {
489 self.print_crate_name(cnum)?;
490 return Ok(true);
491 }
492
493 match self.tcx().extern_crate(cnum) {
504 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
505 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
506 if span.is_dummy() {
513 self.print_crate_name(cnum)?;
514 return Ok(true);
515 }
516
517 with_no_visible_paths!(self.print_def_path(def_id, &[])?);
523
524 return Ok(true);
525 }
526 (ExternCrateSource::Path, LOCAL_CRATE) => {
527 self.print_crate_name(cnum)?;
528 return Ok(true);
529 }
530 _ => {}
531 },
532 None => {
533 self.print_crate_name(cnum)?;
534 return Ok(true);
535 }
536 }
537 }
538
539 if def_id.is_local() {
540 return Ok(false);
541 }
542
543 let visible_parent_map = self.tcx().visible_parent_map(());
544
545 let mut cur_def_key = self.tcx().def_key(def_id);
546 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
547
548 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
550 let parent = DefId {
551 krate: def_id.krate,
552 index: cur_def_key
553 .parent
554 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
555 };
556
557 cur_def_key = self.tcx().def_key(parent);
558 }
559
560 let Some(visible_parent) = visible_parent_map.get(&def_id).cloned() else {
561 return Ok(false);
562 };
563
564 if self.tcx().is_doc_hidden(visible_parent) && with_no_visible_paths_if_doc_hidden() {
565 return Ok(false);
566 }
567
568 let actual_parent = self.tcx().opt_parent(def_id);
569 debug!(
570 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
571 visible_parent, actual_parent,
572 );
573
574 let mut data = cur_def_key.disambiguated_data.data;
575 debug!(
576 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
577 data, visible_parent, actual_parent,
578 );
579
580 match data {
581 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
613 let reexport = self
616 .tcx()
617 .module_children(ModDefId::new_unchecked(visible_parent))
619 .iter()
620 .filter(|child| child.res.opt_def_id() == Some(def_id))
621 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
622 .map(|child| child.ident.name);
623
624 if let Some(new_name) = reexport {
625 *name = new_name;
626 } else {
627 return Ok(false);
629 }
630 }
631 DefPathData::CrateRoot => {
633 data = DefPathData::TypeNs(self.tcx().crate_name(def_id.krate));
634 }
635 _ => {}
636 }
637 debug!("try_print_visible_def_path: data={:?}", data);
638
639 if callers.contains(&visible_parent) {
640 return Ok(false);
641 }
642 callers.push(visible_parent);
643 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
648 false => return Ok(false),
649 true => {}
650 }
651 callers.pop();
652 self.print_path_with_simple(
653 |_| Ok(()),
654 &DisambiguatedDefPathData { data, disambiguator: 0 },
655 )?;
656 Ok(true)
657 }
658
659 fn pretty_print_path_with_qualified(
660 &mut self,
661 self_ty: Ty<'tcx>,
662 trait_ref: Option<ty::TraitRef<'tcx>>,
663 ) -> Result<(), PrintError> {
664 if trait_ref.is_none() {
665 match self_ty.kind() {
669 ty::Adt(..)
670 | ty::Foreign(_)
671 | ty::Bool
672 | ty::Char
673 | ty::Str
674 | ty::Int(_)
675 | ty::Uint(_)
676 | ty::Float(_) => {
677 return self_ty.print(self);
678 }
679
680 _ => {}
681 }
682 }
683
684 self.generic_delimiters(|p| {
685 self_ty.print(p)?;
686 if let Some(trait_ref) = trait_ref {
687 write!(p, " as ")?;
688 trait_ref.print_only_trait_path().print(p)?;
689 }
690 Ok(())
691 })
692 }
693
694 fn pretty_print_path_with_impl(
695 &mut self,
696 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
697 self_ty: Ty<'tcx>,
698 trait_ref: Option<ty::TraitRef<'tcx>>,
699 ) -> Result<(), PrintError> {
700 print_prefix(self)?;
701
702 self.generic_delimiters(|p| {
703 write!(p, "impl ")?;
704 if let Some(trait_ref) = trait_ref {
705 trait_ref.print_only_trait_path().print(p)?;
706 write!(p, " for ")?;
707 }
708 self_ty.print(p)?;
709
710 Ok(())
711 })
712 }
713
714 fn pretty_print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
715 match *ty.kind() {
716 ty::Bool => write!(self, "bool")?,
717 ty::Char => write!(self, "char")?,
718 ty::Int(t) => write!(self, "{}", t.name_str())?,
719 ty::Uint(t) => write!(self, "{}", t.name_str())?,
720 ty::Float(t) => write!(self, "{}", t.name_str())?,
721 ty::Pat(ty, pat) => {
722 write!(self, "(")?;
723 ty.print(self)?;
724 write!(self, ") is {pat:?}")?;
725 }
726 ty::RawPtr(ty, mutbl) => {
727 write!(self, "*{} ", mutbl.ptr_str())?;
728 ty.print(self)?;
729 }
730 ty::Ref(r, ty, mutbl) => {
731 write!(self, "&")?;
732 if self.should_print_optional_region(r) {
733 r.print(self)?;
734 write!(self, " ")?;
735 }
736 ty::TypeAndMut { ty, mutbl }.print(self)?;
737 }
738 ty::Never => write!(self, "!")?,
739 ty::Tuple(tys) => {
740 write!(self, "(")?;
741 self.comma_sep(tys.iter())?;
742 if tys.len() == 1 {
743 write!(self, ",")?;
744 }
745 write!(self, ")")?;
746 }
747 ty::FnDef(def_id, args) => {
748 if with_reduced_queries() {
749 self.print_def_path(def_id, args)?;
750 } else {
751 let mut sig = self.tcx().fn_sig(def_id).instantiate(self.tcx(), args);
752 if self.tcx().codegen_fn_attrs(def_id).safe_target_features {
753 write!(self, "#[target_features] ")?;
754 sig = sig.map_bound(|mut sig| {
755 sig.safety = hir::Safety::Safe;
756 sig
757 });
758 }
759 sig.print(self)?;
760 write!(self, " {{")?;
761 self.pretty_print_value_path(def_id, args)?;
762 write!(self, "}}")?;
763 }
764 }
765 ty::FnPtr(ref sig_tys, hdr) => sig_tys.with(hdr).print(self)?,
766 ty::UnsafeBinder(ref bound_ty) => {
767 self.wrap_binder(bound_ty, WrapBinderMode::Unsafe, |ty, p| {
768 p.pretty_print_type(*ty)
769 })?;
770 }
771 ty::Infer(infer_ty) => {
772 if self.should_print_verbose() {
773 write!(self, "{:?}", ty.kind())?;
774 return Ok(());
775 }
776
777 if let ty::TyVar(ty_vid) = infer_ty {
778 if let Some(name) = self.ty_infer_name(ty_vid) {
779 write!(self, "{name}")?;
780 } else {
781 write!(self, "{infer_ty}")?;
782 }
783 } else {
784 write!(self, "{infer_ty}")?;
785 }
786 }
787 ty::Error(_) => write!(self, "{{type error}}")?,
788 ty::Param(ref param_ty) => param_ty.print(self)?,
789 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
790 ty::BoundTyKind::Anon => {
791 rustc_type_ir::debug_bound_var(self, debruijn, bound_ty.var)?
792 }
793 ty::BoundTyKind::Param(def_id) => match self.should_print_verbose() {
794 true => write!(self, "{:?}", ty.kind())?,
795 false => write!(self, "{}", self.tcx().item_name(def_id))?,
796 },
797 },
798 ty::Adt(def, args) => self.print_def_path(def.did(), args)?,
799 ty::Dynamic(data, r) => {
800 let print_r = self.should_print_optional_region(r);
801 if print_r {
802 write!(self, "(")?;
803 }
804 write!(self, "dyn ")?;
805 data.print(self)?;
806 if print_r {
807 write!(self, " + ")?;
808 r.print(self)?;
809 write!(self, ")")?;
810 }
811 }
812 ty::Foreign(def_id) => self.print_def_path(def_id, &[])?,
813 ty::Alias(ty::Projection | ty::Inherent | ty::Free, ref data) => data.print(self)?,
814 ty::Placeholder(placeholder) => placeholder.print(self)?,
815 ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
816 if self.should_print_verbose() {
825 write!(self, "Opaque({:?}, {})", def_id, args.print_as_list())?;
827 return Ok(());
828 }
829
830 let parent = self.tcx().parent(def_id);
831 match self.tcx().def_kind(parent) {
832 DefKind::TyAlias | DefKind::AssocTy => {
833 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id: d, .. }) =
836 *self.tcx().type_of(parent).instantiate_identity().kind()
837 {
838 if d == def_id {
839 self.print_def_path(parent, args)?;
842 return Ok(());
843 }
844 }
845 self.print_def_path(def_id, args)?;
847 return Ok(());
848 }
849 _ => {
850 if with_reduced_queries() {
851 self.print_def_path(def_id, &[])?;
852 return Ok(());
853 } else {
854 return self.pretty_print_opaque_impl_type(def_id, args);
855 }
856 }
857 }
858 }
859 ty::Str => write!(self, "str")?,
860 ty::Coroutine(did, args) => {
861 write!(self, "{{")?;
862 let coroutine_kind = self.tcx().coroutine_kind(did).unwrap();
863 let should_print_movability = self.should_print_verbose()
864 || matches!(coroutine_kind, hir::CoroutineKind::Coroutine(_));
865
866 if should_print_movability {
867 match coroutine_kind.movability() {
868 hir::Movability::Movable => {}
869 hir::Movability::Static => write!(self, "static ")?,
870 }
871 }
872
873 if !self.should_print_verbose() {
874 write!(self, "{coroutine_kind}")?;
875 if coroutine_kind.is_fn_like() {
876 let did_of_the_fn_item = self.tcx().parent(did);
883 write!(self, " of ")?;
884 self.print_def_path(did_of_the_fn_item, args)?;
885 write!(self, "()")?;
886 } else if let Some(local_did) = did.as_local() {
887 let span = self.tcx().def_span(local_did);
888 write!(
889 self,
890 "@{}",
891 self.tcx().sess.source_map().span_to_embeddable_string(span)
894 )?;
895 } else {
896 write!(self, "@")?;
897 self.print_def_path(did, args)?;
898 }
899 } else {
900 self.print_def_path(did, args)?;
901 write!(self, " upvar_tys=")?;
902 args.as_coroutine().tupled_upvars_ty().print(self)?;
903 write!(self, " resume_ty=")?;
904 args.as_coroutine().resume_ty().print(self)?;
905 write!(self, " yield_ty=")?;
906 args.as_coroutine().yield_ty().print(self)?;
907 write!(self, " return_ty=")?;
908 args.as_coroutine().return_ty().print(self)?;
909 }
910
911 write!(self, "}}")?
912 }
913 ty::CoroutineWitness(did, args) => {
914 write!(self, "{{")?;
915 if !self.tcx().sess.verbose_internals() {
916 write!(self, "coroutine witness")?;
917 if let Some(did) = did.as_local() {
918 let span = self.tcx().def_span(did);
919 write!(
920 self,
921 "@{}",
922 self.tcx().sess.source_map().span_to_embeddable_string(span)
925 )?;
926 } else {
927 write!(self, "@")?;
928 self.print_def_path(did, args)?;
929 }
930 } else {
931 self.print_def_path(did, args)?;
932 }
933
934 write!(self, "}}")?
935 }
936 ty::Closure(did, args) => {
937 write!(self, "{{")?;
938 if !self.should_print_verbose() {
939 write!(self, "closure")?;
940 if self.should_truncate() {
941 write!(self, "@...}}")?;
942 return Ok(());
943 } else {
944 if let Some(did) = did.as_local() {
945 if self.tcx().sess.opts.unstable_opts.span_free_formats {
946 write!(self, "@")?;
947 self.print_def_path(did.to_def_id(), args)?;
948 } else {
949 let span = self.tcx().def_span(did);
950 let preference = if with_forced_trimmed_paths() {
951 FileNameDisplayPreference::Short
952 } else {
953 FileNameDisplayPreference::Remapped
954 };
955 write!(
956 self,
957 "@{}",
958 self.tcx().sess.source_map().span_to_string(span, preference)
962 )?;
963 }
964 } else {
965 write!(self, "@")?;
966 self.print_def_path(did, args)?;
967 }
968 }
969 } else {
970 self.print_def_path(did, args)?;
971 write!(self, " closure_kind_ty=")?;
972 args.as_closure().kind_ty().print(self)?;
973 write!(self, " closure_sig_as_fn_ptr_ty=")?;
974 args.as_closure().sig_as_fn_ptr_ty().print(self)?;
975 write!(self, " upvar_tys=")?;
976 args.as_closure().tupled_upvars_ty().print(self)?;
977 }
978 write!(self, "}}")?;
979 }
980 ty::CoroutineClosure(did, args) => {
981 write!(self, "{{")?;
982 if !self.should_print_verbose() {
983 match self.tcx().coroutine_kind(self.tcx().coroutine_for_closure(did)).unwrap()
984 {
985 hir::CoroutineKind::Desugared(
986 hir::CoroutineDesugaring::Async,
987 hir::CoroutineSource::Closure,
988 ) => write!(self, "async closure")?,
989 hir::CoroutineKind::Desugared(
990 hir::CoroutineDesugaring::AsyncGen,
991 hir::CoroutineSource::Closure,
992 ) => write!(self, "async gen closure")?,
993 hir::CoroutineKind::Desugared(
994 hir::CoroutineDesugaring::Gen,
995 hir::CoroutineSource::Closure,
996 ) => write!(self, "gen closure")?,
997 _ => unreachable!(
998 "coroutine from coroutine-closure should have CoroutineSource::Closure"
999 ),
1000 }
1001 if let Some(did) = did.as_local() {
1002 if self.tcx().sess.opts.unstable_opts.span_free_formats {
1003 write!(self, "@")?;
1004 self.print_def_path(did.to_def_id(), args)?;
1005 } else {
1006 let span = self.tcx().def_span(did);
1007 let preference = if with_forced_trimmed_paths() {
1008 FileNameDisplayPreference::Short
1009 } else {
1010 FileNameDisplayPreference::Remapped
1011 };
1012 write!(
1013 self,
1014 "@{}",
1015 self.tcx().sess.source_map().span_to_string(span, preference)
1018 )?;
1019 }
1020 } else {
1021 write!(self, "@")?;
1022 self.print_def_path(did, args)?;
1023 }
1024 } else {
1025 self.print_def_path(did, args)?;
1026 write!(self, " closure_kind_ty=")?;
1027 args.as_coroutine_closure().kind_ty().print(self)?;
1028 write!(self, " signature_parts_ty=")?;
1029 args.as_coroutine_closure().signature_parts_ty().print(self)?;
1030 write!(self, " upvar_tys=")?;
1031 args.as_coroutine_closure().tupled_upvars_ty().print(self)?;
1032 write!(self, " coroutine_captures_by_ref_ty=")?;
1033 args.as_coroutine_closure().coroutine_captures_by_ref_ty().print(self)?;
1034 }
1035 write!(self, "}}")?;
1036 }
1037 ty::Array(ty, sz) => {
1038 write!(self, "[")?;
1039 ty.print(self)?;
1040 write!(self, "; ")?;
1041 sz.print(self)?;
1042 write!(self, "]")?;
1043 }
1044 ty::Slice(ty) => {
1045 write!(self, "[")?;
1046 ty.print(self)?;
1047 write!(self, "]")?;
1048 }
1049 }
1050
1051 Ok(())
1052 }
1053
1054 fn pretty_print_opaque_impl_type(
1055 &mut self,
1056 def_id: DefId,
1057 args: ty::GenericArgsRef<'tcx>,
1058 ) -> Result<(), PrintError> {
1059 let tcx = self.tcx();
1060
1061 let bounds = tcx.explicit_item_bounds(def_id);
1064
1065 let mut traits = FxIndexMap::default();
1066 let mut fn_traits = FxIndexMap::default();
1067 let mut lifetimes = SmallVec::<[ty::Region<'tcx>; 1]>::new();
1068
1069 let mut has_sized_bound = false;
1070 let mut has_negative_sized_bound = false;
1071 let mut has_meta_sized_bound = false;
1072
1073 for (predicate, _) in bounds.iter_instantiated_copied(tcx, args) {
1074 let bound_predicate = predicate.kind();
1075
1076 match bound_predicate.skip_binder() {
1077 ty::ClauseKind::Trait(pred) => {
1078 match tcx.as_lang_item(pred.def_id()) {
1081 Some(LangItem::Sized) => match pred.polarity {
1082 ty::PredicatePolarity::Positive => {
1083 has_sized_bound = true;
1084 continue;
1085 }
1086 ty::PredicatePolarity::Negative => has_negative_sized_bound = true,
1087 },
1088 Some(LangItem::MetaSized) => {
1089 has_meta_sized_bound = true;
1090 continue;
1091 }
1092 Some(LangItem::PointeeSized) => {
1093 bug!("`PointeeSized` is removed during lowering");
1094 }
1095 _ => (),
1096 }
1097
1098 self.insert_trait_and_projection(
1099 bound_predicate.rebind(pred),
1100 None,
1101 &mut traits,
1102 &mut fn_traits,
1103 );
1104 }
1105 ty::ClauseKind::Projection(pred) => {
1106 let proj = bound_predicate.rebind(pred);
1107 let trait_ref = proj.map_bound(|proj| TraitPredicate {
1108 trait_ref: proj.projection_term.trait_ref(tcx),
1109 polarity: ty::PredicatePolarity::Positive,
1110 });
1111
1112 self.insert_trait_and_projection(
1113 trait_ref,
1114 Some((proj.item_def_id(), proj.term())),
1115 &mut traits,
1116 &mut fn_traits,
1117 );
1118 }
1119 ty::ClauseKind::TypeOutlives(outlives) => {
1120 lifetimes.push(outlives.1);
1121 }
1122 _ => {}
1123 }
1124 }
1125
1126 write!(self, "impl ")?;
1127
1128 let mut first = true;
1129 let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !has_sized_bound;
1131
1132 for ((bound_args_and_self_ty, is_async), entry) in fn_traits {
1133 write!(self, "{}", if first { "" } else { " + " })?;
1134 write!(self, "{}", if paren_needed { "(" } else { "" })?;
1135
1136 let trait_def_id = if is_async {
1137 tcx.async_fn_trait_kind_to_def_id(entry.kind).expect("expected AsyncFn lang items")
1138 } else {
1139 tcx.fn_trait_kind_to_def_id(entry.kind).expect("expected Fn lang items")
1140 };
1141
1142 if let Some(return_ty) = entry.return_ty {
1143 self.wrap_binder(
1144 &bound_args_and_self_ty,
1145 WrapBinderMode::ForAll,
1146 |(args, _), p| {
1147 write!(p, "{}", tcx.item_name(trait_def_id))?;
1148 write!(p, "(")?;
1149
1150 for (idx, ty) in args.iter().enumerate() {
1151 if idx > 0 {
1152 write!(p, ", ")?;
1153 }
1154 ty.print(p)?;
1155 }
1156
1157 write!(p, ")")?;
1158 if let Some(ty) = return_ty.skip_binder().as_type() {
1159 if !ty.is_unit() {
1160 write!(p, " -> ")?;
1161 return_ty.print(p)?;
1162 }
1163 }
1164 write!(p, "{}", if paren_needed { ")" } else { "" })?;
1165
1166 first = false;
1167 Ok(())
1168 },
1169 )?;
1170 } else {
1171 traits.insert(
1173 bound_args_and_self_ty.map_bound(|(args, self_ty)| ty::TraitPredicate {
1174 polarity: ty::PredicatePolarity::Positive,
1175 trait_ref: ty::TraitRef::new(
1176 tcx,
1177 trait_def_id,
1178 [self_ty, Ty::new_tup(tcx, args)],
1179 ),
1180 }),
1181 FxIndexMap::default(),
1182 );
1183 }
1184 }
1185
1186 for (trait_pred, assoc_items) in traits {
1188 write!(self, "{}", if first { "" } else { " + " })?;
1189
1190 self.wrap_binder(&trait_pred, WrapBinderMode::ForAll, |trait_pred, p| {
1191 if trait_pred.polarity == ty::PredicatePolarity::Negative {
1192 write!(p, "!")?;
1193 }
1194 trait_pred.trait_ref.print_only_trait_name().print(p)?;
1195
1196 let generics = tcx.generics_of(trait_pred.def_id());
1197 let own_args = generics.own_args_no_defaults(tcx, trait_pred.trait_ref.args);
1198
1199 if !own_args.is_empty() || !assoc_items.is_empty() {
1200 let mut first = true;
1201
1202 for ty in own_args {
1203 if first {
1204 write!(p, "<")?;
1205 first = false;
1206 } else {
1207 write!(p, ", ")?;
1208 }
1209 ty.print(p)?;
1210 }
1211
1212 for (assoc_item_def_id, term) in assoc_items {
1213 if first {
1214 write!(p, "<")?;
1215 first = false;
1216 } else {
1217 write!(p, ", ")?;
1218 }
1219
1220 write!(p, "{} = ", tcx.associated_item(assoc_item_def_id).name())?;
1221
1222 match term.skip_binder().kind() {
1223 TermKind::Ty(ty) => ty.print(p)?,
1224 TermKind::Const(c) => c.print(p)?,
1225 };
1226 }
1227
1228 if !first {
1229 write!(p, ">")?;
1230 }
1231 }
1232
1233 first = false;
1234 Ok(())
1235 })?;
1236 }
1237
1238 let using_sized_hierarchy = self.tcx().features().sized_hierarchy();
1239 let add_sized = has_sized_bound && (first || has_negative_sized_bound);
1240 let add_maybe_sized =
1241 has_meta_sized_bound && !has_negative_sized_bound && !using_sized_hierarchy;
1242 let has_pointee_sized_bound =
1244 !has_sized_bound && !has_meta_sized_bound && !has_negative_sized_bound;
1245 if add_sized || add_maybe_sized {
1246 if !first {
1247 write!(self, " + ")?;
1248 }
1249 if add_maybe_sized {
1250 write!(self, "?")?;
1251 }
1252 write!(self, "Sized")?;
1253 } else if has_meta_sized_bound && using_sized_hierarchy {
1254 if !first {
1255 write!(self, " + ")?;
1256 }
1257 write!(self, "MetaSized")?;
1258 } else if has_pointee_sized_bound && using_sized_hierarchy {
1259 if !first {
1260 write!(self, " + ")?;
1261 }
1262 write!(self, "PointeeSized")?;
1263 }
1264
1265 if !with_forced_trimmed_paths() {
1266 for re in lifetimes {
1267 write!(self, " + ")?;
1268 self.print_region(re)?;
1269 }
1270 }
1271
1272 Ok(())
1273 }
1274
1275 fn insert_trait_and_projection(
1278 &mut self,
1279 trait_pred: ty::PolyTraitPredicate<'tcx>,
1280 proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
1281 traits: &mut FxIndexMap<
1282 ty::PolyTraitPredicate<'tcx>,
1283 FxIndexMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,
1284 >,
1285 fn_traits: &mut FxIndexMap<
1286 (ty::Binder<'tcx, (&'tcx ty::List<Ty<'tcx>>, Ty<'tcx>)>, bool),
1287 OpaqueFnEntry<'tcx>,
1288 >,
1289 ) {
1290 let tcx = self.tcx();
1291 let trait_def_id = trait_pred.def_id();
1292
1293 let fn_trait_and_async = if let Some(kind) = tcx.fn_trait_kind_from_def_id(trait_def_id) {
1294 Some((kind, false))
1295 } else if let Some(kind) = tcx.async_fn_trait_kind_from_def_id(trait_def_id) {
1296 Some((kind, true))
1297 } else {
1298 None
1299 };
1300
1301 if trait_pred.polarity() == ty::PredicatePolarity::Positive
1302 && let Some((kind, is_async)) = fn_trait_and_async
1303 && let ty::Tuple(types) = *trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
1304 {
1305 let entry = fn_traits
1306 .entry((trait_pred.rebind((types, trait_pred.skip_binder().self_ty())), is_async))
1307 .or_insert_with(|| OpaqueFnEntry { kind, return_ty: None });
1308 if kind.extends(entry.kind) {
1309 entry.kind = kind;
1310 }
1311 if let Some((proj_def_id, proj_ty)) = proj_ty
1312 && tcx.item_name(proj_def_id) == sym::Output
1313 {
1314 entry.return_ty = Some(proj_ty);
1315 }
1316 return;
1317 }
1318
1319 traits.entry(trait_pred).or_default().extend(proj_ty);
1321 }
1322
1323 fn pretty_print_inherent_projection(
1324 &mut self,
1325 alias_ty: ty::AliasTerm<'tcx>,
1326 ) -> Result<(), PrintError> {
1327 let def_key = self.tcx().def_key(alias_ty.def_id);
1328 self.print_path_with_generic_args(
1329 |p| {
1330 p.print_path_with_simple(
1331 |p| p.print_path_with_qualified(alias_ty.self_ty(), None),
1332 &def_key.disambiguated_data,
1333 )
1334 },
1335 &alias_ty.args[1..],
1336 )
1337 }
1338
1339 fn pretty_print_rpitit(
1340 &mut self,
1341 def_id: DefId,
1342 args: ty::GenericArgsRef<'tcx>,
1343 ) -> Result<(), PrintError> {
1344 let fn_args = if self.tcx().features().return_type_notation()
1345 && let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, .. }) =
1346 self.tcx().opt_rpitit_info(def_id)
1347 && let ty::Alias(_, alias_ty) =
1348 self.tcx().fn_sig(fn_def_id).skip_binder().output().skip_binder().kind()
1349 && alias_ty.def_id == def_id
1350 && let generics = self.tcx().generics_of(fn_def_id)
1351 && generics.own_params.iter().all(|param| matches!(param.kind, ty::GenericParamDefKind::Lifetime))
1353 {
1354 let num_args = generics.count();
1355 Some((fn_def_id, &args[..num_args]))
1356 } else {
1357 None
1358 };
1359
1360 match (fn_args, RTN_MODE.with(|c| c.get())) {
1361 (Some((fn_def_id, fn_args)), RtnMode::ForDiagnostic) => {
1362 self.pretty_print_opaque_impl_type(def_id, args)?;
1363 write!(self, " {{ ")?;
1364 self.print_def_path(fn_def_id, fn_args)?;
1365 write!(self, "(..) }}")?;
1366 }
1367 (Some((fn_def_id, fn_args)), RtnMode::ForSuggestion) => {
1368 self.print_def_path(fn_def_id, fn_args)?;
1369 write!(self, "(..)")?;
1370 }
1371 _ => {
1372 self.pretty_print_opaque_impl_type(def_id, args)?;
1373 }
1374 }
1375
1376 Ok(())
1377 }
1378
1379 fn ty_infer_name(&self, _: ty::TyVid) -> Option<Symbol> {
1380 None
1381 }
1382
1383 fn const_infer_name(&self, _: ty::ConstVid) -> Option<Symbol> {
1384 None
1385 }
1386
1387 fn pretty_print_dyn_existential(
1388 &mut self,
1389 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1390 ) -> Result<(), PrintError> {
1391 let mut first = true;
1393
1394 if let Some(bound_principal) = predicates.principal() {
1395 self.wrap_binder(&bound_principal, WrapBinderMode::ForAll, |principal, p| {
1396 p.print_def_path(principal.def_id, &[])?;
1397
1398 let mut resugared = false;
1399
1400 let fn_trait_kind = p.tcx().fn_trait_kind_from_def_id(principal.def_id);
1402 if !p.should_print_verbose() && fn_trait_kind.is_some() {
1403 if let ty::Tuple(tys) = principal.args.type_at(0).kind() {
1404 let mut projections = predicates.projection_bounds();
1405 if let (Some(proj), None) = (projections.next(), projections.next()) {
1406 p.pretty_print_fn_sig(
1407 tys,
1408 false,
1409 proj.skip_binder().term.as_type().expect("Return type was a const"),
1410 )?;
1411 resugared = true;
1412 }
1413 }
1414 }
1415
1416 if !resugared {
1419 let principal_with_self =
1420 principal.with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self);
1421
1422 let args = p
1423 .tcx()
1424 .generics_of(principal_with_self.def_id)
1425 .own_args_no_defaults(p.tcx(), principal_with_self.args);
1426
1427 let bound_principal_with_self = bound_principal
1428 .with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self);
1429
1430 let clause: ty::Clause<'tcx> = bound_principal_with_self.upcast(p.tcx());
1431 let super_projections: Vec<_> = elaborate::elaborate(p.tcx(), [clause])
1432 .filter_only_self()
1433 .filter_map(|clause| clause.as_projection_clause())
1434 .collect();
1435
1436 let mut projections: Vec<_> = predicates
1437 .projection_bounds()
1438 .filter(|&proj| {
1439 let proj_is_implied = super_projections.iter().any(|&super_proj| {
1441 let super_proj = super_proj.map_bound(|super_proj| {
1442 ty::ExistentialProjection::erase_self_ty(p.tcx(), super_proj)
1443 });
1444
1445 let proj = p.tcx().erase_and_anonymize_regions(proj);
1450 let super_proj = p.tcx().erase_and_anonymize_regions(super_proj);
1451
1452 proj == super_proj
1453 });
1454 !proj_is_implied
1455 })
1456 .map(|proj| {
1457 proj.skip_binder()
1460 })
1461 .collect();
1462
1463 projections
1464 .sort_by_cached_key(|proj| p.tcx().item_name(proj.def_id).to_string());
1465
1466 if !args.is_empty() || !projections.is_empty() {
1467 p.generic_delimiters(|p| {
1468 p.comma_sep(args.iter().copied())?;
1469 if !args.is_empty() && !projections.is_empty() {
1470 write!(p, ", ")?;
1471 }
1472 p.comma_sep(projections.iter().copied())
1473 })?;
1474 }
1475 }
1476 Ok(())
1477 })?;
1478
1479 first = false;
1480 }
1481
1482 let mut auto_traits: Vec<_> = predicates.auto_traits().collect();
1486
1487 auto_traits.sort_by_cached_key(|did| with_no_trimmed_paths!(self.tcx().def_path_str(*did)));
1495
1496 for def_id in auto_traits {
1497 if !first {
1498 write!(self, " + ")?;
1499 }
1500 first = false;
1501
1502 self.print_def_path(def_id, &[])?;
1503 }
1504
1505 Ok(())
1506 }
1507
1508 fn pretty_print_fn_sig(
1509 &mut self,
1510 inputs: &[Ty<'tcx>],
1511 c_variadic: bool,
1512 output: Ty<'tcx>,
1513 ) -> Result<(), PrintError> {
1514 write!(self, "(")?;
1515 self.comma_sep(inputs.iter().copied())?;
1516 if c_variadic {
1517 if !inputs.is_empty() {
1518 write!(self, ", ")?;
1519 }
1520 write!(self, "...")?;
1521 }
1522 write!(self, ")")?;
1523 if !output.is_unit() {
1524 write!(self, " -> ")?;
1525 output.print(self)?;
1526 }
1527
1528 Ok(())
1529 }
1530
1531 fn pretty_print_const(
1532 &mut self,
1533 ct: ty::Const<'tcx>,
1534 print_ty: bool,
1535 ) -> Result<(), PrintError> {
1536 if self.should_print_verbose() {
1537 write!(self, "{ct:?}")?;
1538 return Ok(());
1539 }
1540
1541 match ct.kind() {
1542 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args }) => {
1543 match self.tcx().def_kind(def) {
1544 DefKind::Const | DefKind::AssocConst => {
1545 self.pretty_print_value_path(def, args)?;
1546 }
1547 DefKind::AnonConst => {
1548 if def.is_local()
1549 && let span = self.tcx().def_span(def)
1550 && let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
1551 {
1552 write!(self, "{snip}")?;
1553 } else {
1554 write!(
1562 self,
1563 "{}::{}",
1564 self.tcx().crate_name(def.krate),
1565 self.tcx().def_path(def).to_string_no_crate_verbose()
1566 )?;
1567 }
1568 }
1569 defkind => bug!("`{:?}` has unexpected defkind {:?}", ct, defkind),
1570 }
1571 }
1572 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1573 ty::InferConst::Var(ct_vid) if let Some(name) = self.const_infer_name(ct_vid) => {
1574 write!(self, "{name}")?;
1575 }
1576 _ => write!(self, "_")?,
1577 },
1578 ty::ConstKind::Param(ParamConst { name, .. }) => write!(self, "{name}")?,
1579 ty::ConstKind::Value(cv) => {
1580 return self.pretty_print_const_valtree(cv, print_ty);
1581 }
1582
1583 ty::ConstKind::Bound(debruijn, bound_var) => {
1584 rustc_type_ir::debug_bound_var(self, debruijn, bound_var)?
1585 }
1586 ty::ConstKind::Placeholder(placeholder) => write!(self, "{placeholder:?}")?,
1587 ty::ConstKind::Expr(expr) => self.pretty_print_const_expr(expr, print_ty)?,
1590 ty::ConstKind::Error(_) => write!(self, "{{const error}}")?,
1591 };
1592 Ok(())
1593 }
1594
1595 fn pretty_print_const_expr(
1596 &mut self,
1597 expr: Expr<'tcx>,
1598 print_ty: bool,
1599 ) -> Result<(), PrintError> {
1600 match expr.kind {
1601 ty::ExprKind::Binop(op) => {
1602 let (_, _, c1, c2) = expr.binop_args();
1603
1604 let precedence = |binop: crate::mir::BinOp| binop.to_hir_binop().precedence();
1605 let op_precedence = precedence(op);
1606 let formatted_op = op.to_hir_binop().as_str();
1607 let (lhs_parenthesized, rhs_parenthesized) = match (c1.kind(), c2.kind()) {
1608 (
1609 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),
1610 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),
1611 ) => (precedence(lhs_op) < op_precedence, precedence(rhs_op) < op_precedence),
1612 (
1613 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),
1614 ty::ConstKind::Expr(_),
1615 ) => (precedence(lhs_op) < op_precedence, true),
1616 (
1617 ty::ConstKind::Expr(_),
1618 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),
1619 ) => (true, precedence(rhs_op) < op_precedence),
1620 (ty::ConstKind::Expr(_), ty::ConstKind::Expr(_)) => (true, true),
1621 (
1622 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),
1623 _,
1624 ) => (precedence(lhs_op) < op_precedence, false),
1625 (
1626 _,
1627 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),
1628 ) => (false, precedence(rhs_op) < op_precedence),
1629 (ty::ConstKind::Expr(_), _) => (true, false),
1630 (_, ty::ConstKind::Expr(_)) => (false, true),
1631 _ => (false, false),
1632 };
1633
1634 self.maybe_parenthesized(
1635 |this| this.pretty_print_const(c1, print_ty),
1636 lhs_parenthesized,
1637 )?;
1638 write!(self, " {formatted_op} ")?;
1639 self.maybe_parenthesized(
1640 |this| this.pretty_print_const(c2, print_ty),
1641 rhs_parenthesized,
1642 )?;
1643 }
1644 ty::ExprKind::UnOp(op) => {
1645 let (_, ct) = expr.unop_args();
1646
1647 use crate::mir::UnOp;
1648 let formatted_op = match op {
1649 UnOp::Not => "!",
1650 UnOp::Neg => "-",
1651 UnOp::PtrMetadata => "PtrMetadata",
1652 };
1653 let parenthesized = match ct.kind() {
1654 _ if op == UnOp::PtrMetadata => true,
1655 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::UnOp(c_op), .. }) => {
1656 c_op != op
1657 }
1658 ty::ConstKind::Expr(_) => true,
1659 _ => false,
1660 };
1661 write!(self, "{formatted_op}")?;
1662 self.maybe_parenthesized(
1663 |this| this.pretty_print_const(ct, print_ty),
1664 parenthesized,
1665 )?
1666 }
1667 ty::ExprKind::FunctionCall => {
1668 let (_, fn_def, fn_args) = expr.call_args();
1669
1670 write!(self, "(")?;
1671 self.pretty_print_const(fn_def, print_ty)?;
1672 write!(self, ")(")?;
1673 self.comma_sep(fn_args)?;
1674 write!(self, ")")?;
1675 }
1676 ty::ExprKind::Cast(kind) => {
1677 let (_, value, to_ty) = expr.cast_args();
1678
1679 use ty::abstract_const::CastKind;
1680 if kind == CastKind::As || (kind == CastKind::Use && self.should_print_verbose()) {
1681 let parenthesized = match value.kind() {
1682 ty::ConstKind::Expr(ty::Expr {
1683 kind: ty::ExprKind::Cast { .. }, ..
1684 }) => false,
1685 ty::ConstKind::Expr(_) => true,
1686 _ => false,
1687 };
1688 self.maybe_parenthesized(
1689 |this| {
1690 this.typed_value(
1691 |this| this.pretty_print_const(value, print_ty),
1692 |this| this.pretty_print_type(to_ty),
1693 " as ",
1694 )
1695 },
1696 parenthesized,
1697 )?;
1698 } else {
1699 self.pretty_print_const(value, print_ty)?
1700 }
1701 }
1702 }
1703 Ok(())
1704 }
1705
1706 fn pretty_print_const_scalar(
1707 &mut self,
1708 scalar: Scalar,
1709 ty: Ty<'tcx>,
1710 ) -> Result<(), PrintError> {
1711 match scalar {
1712 Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty),
1713 Scalar::Int(int) => {
1714 self.pretty_print_const_scalar_int(int, ty, true)
1715 }
1716 }
1717 }
1718
1719 fn pretty_print_const_scalar_ptr(
1720 &mut self,
1721 ptr: Pointer,
1722 ty: Ty<'tcx>,
1723 ) -> Result<(), PrintError> {
1724 let (prov, offset) = ptr.prov_and_relative_offset();
1725 match ty.kind() {
1726 ty::Ref(_, inner, _) => {
1728 if let ty::Array(elem, ct_len) = inner.kind()
1729 && let ty::Uint(ty::UintTy::U8) = elem.kind()
1730 && let Some(len) = ct_len.try_to_target_usize(self.tcx())
1731 {
1732 match self.tcx().try_get_global_alloc(prov.alloc_id()) {
1733 Some(GlobalAlloc::Memory(alloc)) => {
1734 let range = AllocRange { start: offset, size: Size::from_bytes(len) };
1735 if let Ok(byte_str) =
1736 alloc.inner().get_bytes_strip_provenance(&self.tcx(), range)
1737 {
1738 self.pretty_print_byte_str(byte_str)?;
1739 } else {
1740 write!(self, "<too short allocation>")?;
1741 }
1742 }
1743 Some(GlobalAlloc::Static(def_id)) => {
1745 write!(self, "<static({def_id:?})>")?;
1746 }
1747 Some(GlobalAlloc::Function { .. }) => write!(self, "<function>")?,
1748 Some(GlobalAlloc::VTable(..)) => write!(self, "<vtable>")?,
1749 Some(GlobalAlloc::TypeId { .. }) => write!(self, "<typeid>")?,
1750 None => write!(self, "<dangling pointer>")?,
1751 }
1752 return Ok(());
1753 }
1754 }
1755 ty::FnPtr(..) => {
1756 if let Some(GlobalAlloc::Function { instance, .. }) =
1759 self.tcx().try_get_global_alloc(prov.alloc_id())
1760 {
1761 self.typed_value(
1762 |this| this.pretty_print_value_path(instance.def_id(), instance.args),
1763 |this| this.print_type(ty),
1764 " as ",
1765 )?;
1766 return Ok(());
1767 }
1768 }
1769 _ => {}
1770 }
1771 self.pretty_print_const_pointer(ptr, ty)?;
1773 Ok(())
1774 }
1775
1776 fn pretty_print_const_scalar_int(
1777 &mut self,
1778 int: ScalarInt,
1779 ty: Ty<'tcx>,
1780 print_ty: bool,
1781 ) -> Result<(), PrintError> {
1782 match ty.kind() {
1783 ty::Bool if int == ScalarInt::FALSE => write!(self, "false")?,
1785 ty::Bool if int == ScalarInt::TRUE => write!(self, "true")?,
1786 ty::Float(fty) => match fty {
1788 ty::FloatTy::F16 => {
1789 let val = Half::try_from(int).unwrap();
1790 write!(self, "{}{}f16", val, if val.is_finite() { "" } else { "_" })?;
1791 }
1792 ty::FloatTy::F32 => {
1793 let val = Single::try_from(int).unwrap();
1794 write!(self, "{}{}f32", val, if val.is_finite() { "" } else { "_" })?;
1795 }
1796 ty::FloatTy::F64 => {
1797 let val = Double::try_from(int).unwrap();
1798 write!(self, "{}{}f64", val, if val.is_finite() { "" } else { "_" })?;
1799 }
1800 ty::FloatTy::F128 => {
1801 let val = Quad::try_from(int).unwrap();
1802 write!(self, "{}{}f128", val, if val.is_finite() { "" } else { "_" })?;
1803 }
1804 },
1805 ty::Uint(_) | ty::Int(_) => {
1807 let int =
1808 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1809 if print_ty { write!(self, "{int:#?}")? } else { write!(self, "{int:?}")? }
1810 }
1811 ty::Char if char::try_from(int).is_ok() => {
1813 write!(self, "{:?}", char::try_from(int).unwrap())?;
1814 }
1815 ty::Ref(..) | ty::RawPtr(_, _) | ty::FnPtr(..) => {
1817 let data = int.to_bits(self.tcx().data_layout.pointer_size());
1818 self.typed_value(
1819 |this| {
1820 write!(this, "0x{data:x}")?;
1821 Ok(())
1822 },
1823 |this| this.print_type(ty),
1824 " as ",
1825 )?;
1826 }
1827 ty::Pat(base_ty, pat) if self.tcx().validate_scalar_in_layout(int, ty) => {
1828 self.pretty_print_const_scalar_int(int, *base_ty, print_ty)?;
1829 write!(self, " is {pat:?}")?;
1830 }
1831 _ => {
1833 let print = |this: &mut Self| {
1834 if int.size() == Size::ZERO {
1835 write!(this, "transmute(())")?;
1836 } else {
1837 write!(this, "transmute(0x{int:x})")?;
1838 }
1839 Ok(())
1840 };
1841 if print_ty {
1842 self.typed_value(print, |this| this.print_type(ty), ": ")?
1843 } else {
1844 print(self)?
1845 };
1846 }
1847 }
1848 Ok(())
1849 }
1850
1851 fn pretty_print_const_pointer<Prov: Provenance>(
1854 &mut self,
1855 _: Pointer<Prov>,
1856 ty: Ty<'tcx>,
1857 ) -> Result<(), PrintError> {
1858 self.typed_value(
1859 |this| {
1860 this.write_str("&_")?;
1861 Ok(())
1862 },
1863 |this| this.print_type(ty),
1864 ": ",
1865 )
1866 }
1867
1868 fn pretty_print_byte_str(&mut self, byte_str: &'tcx [u8]) -> Result<(), PrintError> {
1869 write!(self, "b\"{}\"", byte_str.escape_ascii())?;
1870 Ok(())
1871 }
1872
1873 fn pretty_print_const_valtree(
1874 &mut self,
1875 cv: ty::Value<'tcx>,
1876 print_ty: bool,
1877 ) -> Result<(), PrintError> {
1878 if with_reduced_queries() || self.should_print_verbose() {
1879 write!(self, "ValTree({:?}: ", cv.valtree)?;
1880 cv.ty.print(self)?;
1881 write!(self, ")")?;
1882 return Ok(());
1883 }
1884
1885 let u8_type = self.tcx().types.u8;
1886 match (*cv.valtree, *cv.ty.kind()) {
1887 (ty::ValTreeKind::Branch(_), ty::Ref(_, inner_ty, _)) => match inner_ty.kind() {
1888 ty::Slice(t) if *t == u8_type => {
1889 let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {
1890 bug!(
1891 "expected to convert valtree {:?} to raw bytes for type {:?}",
1892 cv.valtree,
1893 t
1894 )
1895 });
1896 return self.pretty_print_byte_str(bytes);
1897 }
1898 ty::Str => {
1899 let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {
1900 bug!("expected to convert valtree to raw bytes for type {:?}", cv.ty)
1901 });
1902 write!(self, "{:?}", String::from_utf8_lossy(bytes))?;
1903 return Ok(());
1904 }
1905 _ => {
1906 let cv = ty::Value { valtree: cv.valtree, ty: inner_ty };
1907 write!(self, "&")?;
1908 self.pretty_print_const_valtree(cv, print_ty)?;
1909 return Ok(());
1910 }
1911 },
1912 (ty::ValTreeKind::Branch(_), ty::Array(t, _)) if t == u8_type => {
1913 let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {
1914 bug!("expected to convert valtree to raw bytes for type {:?}", t)
1915 });
1916 write!(self, "*")?;
1917 self.pretty_print_byte_str(bytes)?;
1918 return Ok(());
1919 }
1920 (ty::ValTreeKind::Branch(_), ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) => {
1922 let contents = self.tcx().destructure_const(ty::Const::new_value(
1923 self.tcx(),
1924 cv.valtree,
1925 cv.ty,
1926 ));
1927 let fields = contents.fields.iter().copied();
1928 match *cv.ty.kind() {
1929 ty::Array(..) => {
1930 write!(self, "[")?;
1931 self.comma_sep(fields)?;
1932 write!(self, "]")?;
1933 }
1934 ty::Tuple(..) => {
1935 write!(self, "(")?;
1936 self.comma_sep(fields)?;
1937 if contents.fields.len() == 1 {
1938 write!(self, ",")?;
1939 }
1940 write!(self, ")")?;
1941 }
1942 ty::Adt(def, _) if def.variants().is_empty() => {
1943 self.typed_value(
1944 |this| {
1945 write!(this, "unreachable()")?;
1946 Ok(())
1947 },
1948 |this| this.print_type(cv.ty),
1949 ": ",
1950 )?;
1951 }
1952 ty::Adt(def, args) => {
1953 let variant_idx =
1954 contents.variant.expect("destructed const of adt without variant idx");
1955 let variant_def = &def.variant(variant_idx);
1956 self.pretty_print_value_path(variant_def.def_id, args)?;
1957 match variant_def.ctor_kind() {
1958 Some(CtorKind::Const) => {}
1959 Some(CtorKind::Fn) => {
1960 write!(self, "(")?;
1961 self.comma_sep(fields)?;
1962 write!(self, ")")?;
1963 }
1964 None => {
1965 write!(self, " {{ ")?;
1966 let mut first = true;
1967 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1968 if !first {
1969 write!(self, ", ")?;
1970 }
1971 write!(self, "{}: ", field_def.name)?;
1972 field.print(self)?;
1973 first = false;
1974 }
1975 write!(self, " }}")?;
1976 }
1977 }
1978 }
1979 _ => unreachable!(),
1980 }
1981 return Ok(());
1982 }
1983 (ty::ValTreeKind::Leaf(leaf), ty::Ref(_, inner_ty, _)) => {
1984 write!(self, "&")?;
1985 return self.pretty_print_const_scalar_int(*leaf, inner_ty, print_ty);
1986 }
1987 (ty::ValTreeKind::Leaf(leaf), _) => {
1988 return self.pretty_print_const_scalar_int(*leaf, cv.ty, print_ty);
1989 }
1990 (_, ty::FnDef(def_id, args)) => {
1991 self.pretty_print_value_path(def_id, args)?;
1993 return Ok(());
1994 }
1995 _ => {}
1998 }
1999
2000 if cv.valtree.is_zst() {
2002 write!(self, "<ZST>")?;
2003 } else {
2004 write!(self, "{:?}", cv.valtree)?;
2005 }
2006 if print_ty {
2007 write!(self, ": ")?;
2008 cv.ty.print(self)?;
2009 }
2010 Ok(())
2011 }
2012
2013 fn pretty_print_closure_as_impl(
2014 &mut self,
2015 closure: ty::ClosureArgs<TyCtxt<'tcx>>,
2016 ) -> Result<(), PrintError> {
2017 let sig = closure.sig();
2018 let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn);
2019
2020 write!(self, "impl ")?;
2021 self.wrap_binder(&sig, WrapBinderMode::ForAll, |sig, p| {
2022 write!(p, "{kind}(")?;
2023 for (i, arg) in sig.inputs()[0].tuple_fields().iter().enumerate() {
2024 if i > 0 {
2025 write!(p, ", ")?;
2026 }
2027 arg.print(p)?;
2028 }
2029 write!(p, ")")?;
2030
2031 if !sig.output().is_unit() {
2032 write!(p, " -> ")?;
2033 sig.output().print(p)?;
2034 }
2035
2036 Ok(())
2037 })
2038 }
2039
2040 fn pretty_print_bound_constness(
2041 &mut self,
2042 constness: ty::BoundConstness,
2043 ) -> Result<(), PrintError> {
2044 match constness {
2045 ty::BoundConstness::Const => write!(self, "const ")?,
2046 ty::BoundConstness::Maybe => write!(self, "[const] ")?,
2047 }
2048 Ok(())
2049 }
2050
2051 fn should_print_verbose(&self) -> bool {
2052 self.tcx().sess.verbose_internals()
2053 }
2054}
2055
2056pub(crate) fn pretty_print_const<'tcx>(
2057 c: ty::Const<'tcx>,
2058 fmt: &mut fmt::Formatter<'_>,
2059 print_types: bool,
2060) -> fmt::Result {
2061 ty::tls::with(|tcx| {
2062 let literal = tcx.lift(c).unwrap();
2063 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
2064 p.print_alloc_ids = true;
2065 p.pretty_print_const(literal, print_types)?;
2066 fmt.write_str(&p.into_buffer())?;
2067 Ok(())
2068 })
2069}
2070
2071pub struct FmtPrinter<'a, 'tcx>(Box<FmtPrinterData<'a, 'tcx>>);
2073
2074pub struct FmtPrinterData<'a, 'tcx> {
2075 tcx: TyCtxt<'tcx>,
2076 fmt: String,
2077
2078 empty_path: bool,
2079 in_value: bool,
2080 pub print_alloc_ids: bool,
2081
2082 used_region_names: FxHashSet<Symbol>,
2084
2085 region_index: usize,
2086 binder_depth: usize,
2087 printed_type_count: usize,
2088 type_length_limit: Limit,
2089
2090 pub region_highlight_mode: RegionHighlightMode<'tcx>,
2091
2092 pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<Symbol> + 'a>>,
2093 pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid) -> Option<Symbol> + 'a>>,
2094}
2095
2096impl<'a, 'tcx> Deref for FmtPrinter<'a, 'tcx> {
2097 type Target = FmtPrinterData<'a, 'tcx>;
2098 fn deref(&self) -> &Self::Target {
2099 &self.0
2100 }
2101}
2102
2103impl DerefMut for FmtPrinter<'_, '_> {
2104 fn deref_mut(&mut self) -> &mut Self::Target {
2105 &mut self.0
2106 }
2107}
2108
2109impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
2110 pub fn new(tcx: TyCtxt<'tcx>, ns: Namespace) -> Self {
2111 let limit =
2112 if with_reduced_queries() { Limit::new(1048576) } else { tcx.type_length_limit() };
2113 Self::new_with_limit(tcx, ns, limit)
2114 }
2115
2116 pub fn print_string(
2117 tcx: TyCtxt<'tcx>,
2118 ns: Namespace,
2119 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2120 ) -> Result<String, PrintError> {
2121 let mut c = FmtPrinter::new(tcx, ns);
2122 f(&mut c)?;
2123 Ok(c.into_buffer())
2124 }
2125
2126 pub fn new_with_limit(tcx: TyCtxt<'tcx>, ns: Namespace, type_length_limit: Limit) -> Self {
2127 FmtPrinter(Box::new(FmtPrinterData {
2128 tcx,
2129 fmt: String::with_capacity(64),
2132 empty_path: false,
2133 in_value: ns == Namespace::ValueNS,
2134 print_alloc_ids: false,
2135 used_region_names: Default::default(),
2136 region_index: 0,
2137 binder_depth: 0,
2138 printed_type_count: 0,
2139 type_length_limit,
2140 region_highlight_mode: RegionHighlightMode::default(),
2141 ty_infer_name_resolver: None,
2142 const_infer_name_resolver: None,
2143 }))
2144 }
2145
2146 pub fn into_buffer(self) -> String {
2147 self.0.fmt
2148 }
2149}
2150
2151fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
2152 match tcx.def_key(def_id).disambiguated_data.data {
2153 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::OpaqueTy => {
2154 Namespace::TypeNS
2155 }
2156
2157 DefPathData::ValueNs(..)
2158 | DefPathData::AnonConst
2159 | DefPathData::Closure
2160 | DefPathData::Ctor => Namespace::ValueNS,
2161
2162 DefPathData::MacroNs(..) => Namespace::MacroNS,
2163
2164 _ => Namespace::TypeNS,
2165 }
2166}
2167
2168impl<'t> TyCtxt<'t> {
2169 pub fn def_path_str(self, def_id: impl IntoQueryParam<DefId>) -> String {
2172 self.def_path_str_with_args(def_id, &[])
2173 }
2174
2175 pub fn def_path_str_with_args(
2177 self,
2178 def_id: impl IntoQueryParam<DefId>,
2179 args: &'t [GenericArg<'t>],
2180 ) -> String {
2181 let def_id = def_id.into_query_param();
2182 let ns = guess_def_namespace(self, def_id);
2183 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
2184
2185 FmtPrinter::print_string(self, ns, |p| p.print_def_path(def_id, args)).unwrap()
2186 }
2187
2188 pub fn value_path_str_with_args(
2190 self,
2191 def_id: impl IntoQueryParam<DefId>,
2192 args: &'t [GenericArg<'t>],
2193 ) -> String {
2194 let def_id = def_id.into_query_param();
2195 let ns = Namespace::ValueNS;
2196 debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns);
2197
2198 FmtPrinter::print_string(self, ns, |p| p.print_def_path(def_id, args)).unwrap()
2199 }
2200}
2201
2202impl fmt::Write for FmtPrinter<'_, '_> {
2203 fn write_str(&mut self, s: &str) -> fmt::Result {
2204 self.fmt.push_str(s);
2205 Ok(())
2206 }
2207}
2208
2209impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
2210 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
2211 self.tcx
2212 }
2213
2214 fn print_def_path(
2215 &mut self,
2216 def_id: DefId,
2217 args: &'tcx [GenericArg<'tcx>],
2218 ) -> Result<(), PrintError> {
2219 if args.is_empty() {
2220 match self.try_print_trimmed_def_path(def_id)? {
2221 true => return Ok(()),
2222 false => {}
2223 }
2224
2225 match self.try_print_visible_def_path(def_id)? {
2226 true => return Ok(()),
2227 false => {}
2228 }
2229 }
2230
2231 let key = self.tcx.def_key(def_id);
2232 if let DefPathData::Impl = key.disambiguated_data.data {
2233 let use_types = !def_id.is_local() || {
2236 let force_no_types = with_forced_impl_filename_line();
2238 !force_no_types
2239 };
2240
2241 if !use_types {
2242 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
2246 let span = self.tcx.def_span(def_id);
2247
2248 self.print_def_path(parent_def_id, &[])?;
2249
2250 if !self.empty_path {
2253 write!(self, "::")?;
2254 }
2255 write!(
2256 self,
2257 "<impl at {}>",
2258 self.tcx.sess.source_map().span_to_embeddable_string(span)
2261 )?;
2262 self.empty_path = false;
2263
2264 return Ok(());
2265 }
2266 }
2267
2268 self.default_print_def_path(def_id, args)
2269 }
2270
2271 fn print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), PrintError> {
2272 self.pretty_print_region(region)
2273 }
2274
2275 fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
2276 match ty.kind() {
2277 ty::Tuple(tys) if tys.len() == 0 && self.should_truncate() => {
2278 self.printed_type_count += 1;
2280 self.pretty_print_type(ty)
2281 }
2282 ty::Adt(..)
2283 | ty::Foreign(_)
2284 | ty::Pat(..)
2285 | ty::RawPtr(..)
2286 | ty::Ref(..)
2287 | ty::FnDef(..)
2288 | ty::FnPtr(..)
2289 | ty::UnsafeBinder(..)
2290 | ty::Dynamic(..)
2291 | ty::Closure(..)
2292 | ty::CoroutineClosure(..)
2293 | ty::Coroutine(..)
2294 | ty::CoroutineWitness(..)
2295 | ty::Tuple(_)
2296 | ty::Alias(..)
2297 | ty::Param(_)
2298 | ty::Bound(..)
2299 | ty::Placeholder(_)
2300 | ty::Error(_)
2301 if self.should_truncate() =>
2302 {
2303 write!(self, "...")?;
2306 Ok(())
2307 }
2308 _ => {
2309 self.printed_type_count += 1;
2310 self.pretty_print_type(ty)
2311 }
2312 }
2313 }
2314
2315 fn print_dyn_existential(
2316 &mut self,
2317 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2318 ) -> Result<(), PrintError> {
2319 self.pretty_print_dyn_existential(predicates)
2320 }
2321
2322 fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
2323 self.pretty_print_const(ct, false)
2324 }
2325
2326 fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
2327 self.empty_path = true;
2328 if cnum == LOCAL_CRATE && !with_resolve_crate_name() {
2329 if self.tcx.sess.at_least_rust_2018() {
2330 if with_crate_prefix() {
2332 write!(self, "{}", kw::Crate)?;
2333 self.empty_path = false;
2334 }
2335 }
2336 } else {
2337 write!(self, "{}", self.tcx.crate_name(cnum))?;
2338 self.empty_path = false;
2339 }
2340 Ok(())
2341 }
2342
2343 fn print_path_with_qualified(
2344 &mut self,
2345 self_ty: Ty<'tcx>,
2346 trait_ref: Option<ty::TraitRef<'tcx>>,
2347 ) -> Result<(), PrintError> {
2348 self.pretty_print_path_with_qualified(self_ty, trait_ref)?;
2349 self.empty_path = false;
2350 Ok(())
2351 }
2352
2353 fn print_path_with_impl(
2354 &mut self,
2355 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2356 self_ty: Ty<'tcx>,
2357 trait_ref: Option<ty::TraitRef<'tcx>>,
2358 ) -> Result<(), PrintError> {
2359 self.pretty_print_path_with_impl(
2360 |p| {
2361 print_prefix(p)?;
2362 if !p.empty_path {
2363 write!(p, "::")?;
2364 }
2365
2366 Ok(())
2367 },
2368 self_ty,
2369 trait_ref,
2370 )?;
2371 self.empty_path = false;
2372 Ok(())
2373 }
2374
2375 fn print_path_with_simple(
2376 &mut self,
2377 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2378 disambiguated_data: &DisambiguatedDefPathData,
2379 ) -> Result<(), PrintError> {
2380 print_prefix(self)?;
2381
2382 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
2384 return Ok(());
2385 }
2386
2387 let name = disambiguated_data.data.name();
2388 if !self.empty_path {
2389 write!(self, "::")?;
2390 }
2391
2392 if let DefPathDataName::Named(name) = name {
2393 if Ident::with_dummy_span(name).is_raw_guess() {
2394 write!(self, "r#")?;
2395 }
2396 }
2397
2398 let verbose = self.should_print_verbose();
2399 write!(self, "{}", disambiguated_data.as_sym(verbose))?;
2400
2401 self.empty_path = false;
2402
2403 Ok(())
2404 }
2405
2406 fn print_path_with_generic_args(
2407 &mut self,
2408 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2409 args: &[GenericArg<'tcx>],
2410 ) -> Result<(), PrintError> {
2411 print_prefix(self)?;
2412
2413 if !args.is_empty() {
2414 if self.in_value {
2415 write!(self, "::")?;
2416 }
2417 self.generic_delimiters(|p| p.comma_sep(args.iter().copied()))
2418 } else {
2419 Ok(())
2420 }
2421 }
2422}
2423
2424impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
2425 fn ty_infer_name(&self, id: ty::TyVid) -> Option<Symbol> {
2426 self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
2427 }
2428
2429 fn reset_type_limit(&mut self) {
2430 self.printed_type_count = 0;
2431 }
2432
2433 fn const_infer_name(&self, id: ty::ConstVid) -> Option<Symbol> {
2434 self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
2435 }
2436
2437 fn pretty_print_value_path(
2438 &mut self,
2439 def_id: DefId,
2440 args: &'tcx [GenericArg<'tcx>],
2441 ) -> Result<(), PrintError> {
2442 let was_in_value = std::mem::replace(&mut self.in_value, true);
2443 self.print_def_path(def_id, args)?;
2444 self.in_value = was_in_value;
2445
2446 Ok(())
2447 }
2448
2449 fn pretty_print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError>
2450 where
2451 T: Print<'tcx, Self> + TypeFoldable<TyCtxt<'tcx>>,
2452 {
2453 self.wrap_binder(value, WrapBinderMode::ForAll, |new_value, this| new_value.print(this))
2454 }
2455
2456 fn wrap_binder<T, C: FnOnce(&T, &mut Self) -> Result<(), PrintError>>(
2457 &mut self,
2458 value: &ty::Binder<'tcx, T>,
2459 mode: WrapBinderMode,
2460 f: C,
2461 ) -> Result<(), PrintError>
2462 where
2463 T: TypeFoldable<TyCtxt<'tcx>>,
2464 {
2465 let old_region_index = self.region_index;
2466 let (new_value, _) = self.name_all_regions(value, mode)?;
2467 f(&new_value, self)?;
2468 self.region_index = old_region_index;
2469 self.binder_depth -= 1;
2470 Ok(())
2471 }
2472
2473 fn typed_value(
2474 &mut self,
2475 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2476 t: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2477 conversion: &str,
2478 ) -> Result<(), PrintError> {
2479 self.write_str("{")?;
2480 f(self)?;
2481 self.write_str(conversion)?;
2482 let was_in_value = std::mem::replace(&mut self.in_value, false);
2483 t(self)?;
2484 self.in_value = was_in_value;
2485 self.write_str("}")?;
2486 Ok(())
2487 }
2488
2489 fn generic_delimiters(
2490 &mut self,
2491 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2492 ) -> Result<(), PrintError> {
2493 write!(self, "<")?;
2494
2495 let was_in_value = std::mem::replace(&mut self.in_value, false);
2496 f(self)?;
2497 self.in_value = was_in_value;
2498
2499 write!(self, ">")?;
2500 Ok(())
2501 }
2502
2503 fn should_truncate(&mut self) -> bool {
2504 !self.type_length_limit.value_within_limit(self.printed_type_count)
2505 }
2506
2507 fn should_print_optional_region(&self, region: ty::Region<'tcx>) -> bool {
2508 let highlight = self.region_highlight_mode;
2509 if highlight.region_highlighted(region).is_some() {
2510 return true;
2511 }
2512
2513 if self.should_print_verbose() {
2514 return true;
2515 }
2516
2517 if with_forced_trimmed_paths() {
2518 return false;
2519 }
2520
2521 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2522
2523 match region.kind() {
2524 ty::ReEarlyParam(ref data) => data.is_named(),
2525
2526 ty::ReLateParam(ty::LateParamRegion { kind, .. }) => kind.is_named(self.tcx),
2527 ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2528 | ty::RePlaceholder(ty::Placeholder {
2529 bound: ty::BoundRegion { kind: br, .. }, ..
2530 }) => {
2531 if br.is_named(self.tcx) {
2532 return true;
2533 }
2534
2535 if let Some((region, _)) = highlight.highlight_bound_region {
2536 if br == region {
2537 return true;
2538 }
2539 }
2540
2541 false
2542 }
2543
2544 ty::ReVar(_) if identify_regions => true,
2545
2546 ty::ReVar(_) | ty::ReErased | ty::ReError(_) => false,
2547
2548 ty::ReStatic => true,
2549 }
2550 }
2551
2552 fn pretty_print_const_pointer<Prov: Provenance>(
2553 &mut self,
2554 p: Pointer<Prov>,
2555 ty: Ty<'tcx>,
2556 ) -> Result<(), PrintError> {
2557 let print = |this: &mut Self| {
2558 if this.print_alloc_ids {
2559 write!(this, "{p:?}")?;
2560 } else {
2561 write!(this, "&_")?;
2562 }
2563 Ok(())
2564 };
2565 self.typed_value(print, |this| this.print_type(ty), ": ")
2566 }
2567}
2568
2569impl<'tcx> FmtPrinter<'_, 'tcx> {
2571 pub fn pretty_print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), fmt::Error> {
2572 let highlight = self.region_highlight_mode;
2574 if let Some(n) = highlight.region_highlighted(region) {
2575 write!(self, "'{n}")?;
2576 return Ok(());
2577 }
2578
2579 if self.should_print_verbose() {
2580 write!(self, "{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 write!(self, "{}", data.name)?;
2593 return Ok(());
2594 }
2595 ty::ReLateParam(ty::LateParamRegion { kind, .. }) => {
2596 if let Some(name) = kind.get_name(self.tcx) {
2597 write!(self, "{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 write!(self, "{name}")?;
2607 return Ok(());
2608 }
2609
2610 if let Some((region, counter)) = highlight.highlight_bound_region {
2611 if br == region {
2612 write!(self, "'{counter}")?;
2613 return Ok(());
2614 }
2615 }
2616 }
2617 ty::ReVar(region_vid) if identify_regions => {
2618 write!(self, "{region_vid:?}")?;
2619 return Ok(());
2620 }
2621 ty::ReVar(_) => {}
2622 ty::ReErased => {}
2623 ty::ReError(_) => {}
2624 ty::ReStatic => {
2625 write!(self, "'static")?;
2626 return Ok(());
2627 }
2628 }
2629
2630 write!(self, "'_")?;
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(ty::BoundVarIndexKind::Bound(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(ty::BoundVarIndexKind::Bound(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 = |p: &mut Self, start: &str, cont: &str| {
2749 let w = if empty {
2750 empty = false;
2751 start
2752 } else {
2753 cont
2754 };
2755 let _ = write!(p, "{w}");
2756 };
2757 let do_continue = |p: &mut Self, cont: Symbol| {
2758 let _ = write!(p, "{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 fn prepare_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2859 where
2860 T: TypeFoldable<TyCtxt<'tcx>>,
2861 {
2862 struct RegionNameCollector<'tcx> {
2863 tcx: TyCtxt<'tcx>,
2864 used_region_names: FxHashSet<Symbol>,
2865 type_collector: SsoHashSet<Ty<'tcx>>,
2866 }
2867
2868 impl<'tcx> RegionNameCollector<'tcx> {
2869 fn new(tcx: TyCtxt<'tcx>) -> Self {
2870 RegionNameCollector {
2871 tcx,
2872 used_region_names: Default::default(),
2873 type_collector: SsoHashSet::new(),
2874 }
2875 }
2876 }
2877
2878 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for RegionNameCollector<'tcx> {
2879 fn visit_region(&mut self, r: ty::Region<'tcx>) {
2880 trace!("address: {:p}", r.0.0);
2881
2882 if let Some(name) = r.get_name(self.tcx) {
2886 self.used_region_names.insert(name);
2887 }
2888 }
2889
2890 fn visit_ty(&mut self, ty: Ty<'tcx>) {
2893 let not_previously_inserted = self.type_collector.insert(ty);
2894 if not_previously_inserted {
2895 ty.super_visit_with(self)
2896 }
2897 }
2898 }
2899
2900 let mut collector = RegionNameCollector::new(self.tcx());
2901 value.visit_with(&mut collector);
2902 self.used_region_names = collector.used_region_names;
2903 self.region_index = 0;
2904 }
2905}
2906
2907impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2908where
2909 T: Print<'tcx, P> + TypeFoldable<TyCtxt<'tcx>>,
2910{
2911 fn print(&self, p: &mut P) -> Result<(), PrintError> {
2912 p.pretty_print_in_binder(self)
2913 }
2914}
2915
2916impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<'tcx, T>
2917where
2918 T: Print<'tcx, P>,
2919{
2920 fn print(&self, p: &mut P) -> Result<(), PrintError> {
2921 self.0.print(p)?;
2922 write!(p, ": ")?;
2923 self.1.print(p)?;
2924 Ok(())
2925 }
2926}
2927
2928#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
2932pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2933
2934impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintOnlyTraitPath<'tcx> {
2935 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
2936 ty::tls::with(|tcx| {
2937 let trait_ref = tcx.short_string(self, path);
2938 rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
2939 })
2940 }
2941}
2942
2943impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
2944 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2945 fmt::Display::fmt(self, f)
2946 }
2947}
2948
2949#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
2952pub struct TraitRefPrintSugared<'tcx>(ty::TraitRef<'tcx>);
2953
2954impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintSugared<'tcx> {
2955 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
2956 ty::tls::with(|tcx| {
2957 let trait_ref = tcx.short_string(self, path);
2958 rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
2959 })
2960 }
2961}
2962
2963impl<'tcx> fmt::Debug for TraitRefPrintSugared<'tcx> {
2964 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2965 fmt::Display::fmt(self, f)
2966 }
2967}
2968
2969#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2973pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
2974
2975impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
2976 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2977 fmt::Display::fmt(self, f)
2978 }
2979}
2980
2981#[extension(pub trait PrintTraitRefExt<'tcx>)]
2982impl<'tcx> ty::TraitRef<'tcx> {
2983 fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2984 TraitRefPrintOnlyTraitPath(self)
2985 }
2986
2987 fn print_trait_sugared(self) -> TraitRefPrintSugared<'tcx> {
2988 TraitRefPrintSugared(self)
2989 }
2990
2991 fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
2992 TraitRefPrintOnlyTraitName(self)
2993 }
2994}
2995
2996#[extension(pub trait PrintPolyTraitRefExt<'tcx>)]
2997impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
2998 fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
2999 self.map_bound(|tr| tr.print_only_trait_path())
3000 }
3001
3002 fn print_trait_sugared(self) -> ty::Binder<'tcx, TraitRefPrintSugared<'tcx>> {
3003 self.map_bound(|tr| tr.print_trait_sugared())
3004 }
3005}
3006
3007#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
3008pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
3009
3010impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
3011 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3012 fmt::Display::fmt(self, f)
3013 }
3014}
3015
3016#[extension(pub trait PrintTraitPredicateExt<'tcx>)]
3017impl<'tcx> ty::TraitPredicate<'tcx> {
3018 fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
3019 TraitPredPrintModifiersAndPath(self)
3020 }
3021}
3022
3023#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
3024pub struct TraitPredPrintWithBoundConstness<'tcx>(
3025 ty::TraitPredicate<'tcx>,
3026 Option<ty::BoundConstness>,
3027);
3028
3029impl<'tcx> fmt::Debug for TraitPredPrintWithBoundConstness<'tcx> {
3030 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3031 fmt::Display::fmt(self, f)
3032 }
3033}
3034
3035#[extension(pub trait PrintPolyTraitPredicateExt<'tcx>)]
3036impl<'tcx> ty::PolyTraitPredicate<'tcx> {
3037 fn print_modifiers_and_trait_path(
3038 self,
3039 ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
3040 self.map_bound(TraitPredPrintModifiersAndPath)
3041 }
3042
3043 fn print_with_bound_constness(
3044 self,
3045 constness: Option<ty::BoundConstness>,
3046 ) -> ty::Binder<'tcx, TraitPredPrintWithBoundConstness<'tcx>> {
3047 self.map_bound(|trait_pred| TraitPredPrintWithBoundConstness(trait_pred, constness))
3048 }
3049}
3050
3051#[derive(Debug, Copy, Clone, Lift)]
3052pub struct PrintClosureAsImpl<'tcx> {
3053 pub closure: ty::ClosureArgs<TyCtxt<'tcx>>,
3054}
3055
3056macro_rules! forward_display_to_print {
3057 ($($ty:ty),+) => {
3058 $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty {
3060 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3061 ty::tls::with(|tcx| {
3062 let mut p = FmtPrinter::new(tcx, Namespace::TypeNS);
3063 tcx.lift(*self)
3064 .expect("could not lift for printing")
3065 .print(&mut p)?;
3066 f.write_str(&p.into_buffer())?;
3067 Ok(())
3068 })
3069 }
3070 })+
3071 };
3072}
3073
3074macro_rules! define_print {
3075 (($self:ident, $p:ident): $($ty:ty $print:block)+) => {
3076 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
3077 fn print(&$self, $p: &mut P) -> Result<(), PrintError> {
3078 let _: () = $print;
3079 Ok(())
3080 }
3081 })+
3082 };
3083}
3084
3085macro_rules! define_print_and_forward_display {
3086 (($self:ident, $p:ident): $($ty:ty $print:block)+) => {
3087 define_print!(($self, $p): $($ty $print)*);
3088 forward_display_to_print!($($ty),+);
3089 };
3090}
3091
3092forward_display_to_print! {
3093 ty::Region<'tcx>,
3094 Ty<'tcx>,
3095 &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3096 ty::Const<'tcx>
3097}
3098
3099define_print! {
3100 (self, p):
3101
3102 ty::FnSig<'tcx> {
3103 write!(p, "{}", self.safety.prefix_str())?;
3104
3105 if self.abi != ExternAbi::Rust {
3106 write!(p, "extern {} ", self.abi)?;
3107 }
3108
3109 write!(p, "fn")?;
3110 p.pretty_print_fn_sig(self.inputs(), self.c_variadic, self.output())?;
3111 }
3112
3113 ty::TraitRef<'tcx> {
3114 write!(p, "<{} as {}>", self.self_ty(), self.print_only_trait_path())?;
3115 }
3116
3117 ty::AliasTy<'tcx> {
3118 let alias_term: ty::AliasTerm<'tcx> = (*self).into();
3119 alias_term.print(p)?;
3120 }
3121
3122 ty::AliasTerm<'tcx> {
3123 match self.kind(p.tcx()) {
3124 ty::AliasTermKind::InherentTy | ty::AliasTermKind::InherentConst => p.pretty_print_inherent_projection(*self)?,
3125 ty::AliasTermKind::ProjectionTy => {
3126 if !(p.should_print_verbose() || with_reduced_queries())
3127 && p.tcx().is_impl_trait_in_trait(self.def_id)
3128 {
3129 p.pretty_print_rpitit(self.def_id, self.args)?;
3130 } else {
3131 p.print_def_path(self.def_id, self.args)?;
3132 }
3133 }
3134 ty::AliasTermKind::FreeTy
3135 | ty::AliasTermKind::FreeConst
3136 | ty::AliasTermKind::OpaqueTy
3137 | ty::AliasTermKind::UnevaluatedConst
3138 | ty::AliasTermKind::ProjectionConst => {
3139 p.print_def_path(self.def_id, self.args)?;
3140 }
3141 }
3142 }
3143
3144 ty::TraitPredicate<'tcx> {
3145 self.trait_ref.self_ty().print(p)?;
3146 write!(p, ": ")?;
3147 if let ty::PredicatePolarity::Negative = self.polarity {
3148 write!(p, "!")?;
3149 }
3150 self.trait_ref.print_trait_sugared().print(p)?;
3151 }
3152
3153 ty::HostEffectPredicate<'tcx> {
3154 let constness = match self.constness {
3155 ty::BoundConstness::Const => { "const" }
3156 ty::BoundConstness::Maybe => { "[const]" }
3157 };
3158 self.trait_ref.self_ty().print(p)?;
3159 write!(p, ": {constness} ")?;
3160 self.trait_ref.print_trait_sugared().print(p)?;
3161 }
3162
3163 ty::TypeAndMut<'tcx> {
3164 write!(p, "{}", self.mutbl.prefix_str())?;
3165 self.ty.print(p)?;
3166 }
3167
3168 ty::ClauseKind<'tcx> {
3169 match *self {
3170 ty::ClauseKind::Trait(ref data) => data.print(p)?,
3171 ty::ClauseKind::RegionOutlives(predicate) => predicate.print(p)?,
3172 ty::ClauseKind::TypeOutlives(predicate) => predicate.print(p)?,
3173 ty::ClauseKind::Projection(predicate) => predicate.print(p)?,
3174 ty::ClauseKind::HostEffect(predicate) => predicate.print(p)?,
3175 ty::ClauseKind::ConstArgHasType(ct, ty) => {
3176 write!(p, "the constant `")?;
3177 ct.print(p)?;
3178 write!(p, "` has type `")?;
3179 ty.print(p)?;
3180 write!(p, "`")?;
3181 },
3182 ty::ClauseKind::WellFormed(term) => {
3183 term.print(p)?;
3184 write!(p, " well-formed")?;
3185 }
3186 ty::ClauseKind::ConstEvaluatable(ct) => {
3187 write!(p, "the constant `")?;
3188 ct.print(p)?;
3189 write!(p, "` can be evaluated")?;
3190 }
3191 ty::ClauseKind::UnstableFeature(symbol) => {
3192 write!(p, "feature({symbol}) is enabled")?;
3193 }
3194 }
3195 }
3196
3197 ty::PredicateKind<'tcx> {
3198 match *self {
3199 ty::PredicateKind::Clause(data) => data.print(p)?,
3200 ty::PredicateKind::Subtype(predicate) => predicate.print(p)?,
3201 ty::PredicateKind::Coerce(predicate) => predicate.print(p)?,
3202 ty::PredicateKind::DynCompatible(trait_def_id) => {
3203 write!(p, "the trait `")?;
3204 p.print_def_path(trait_def_id, &[])?;
3205 write!(p, "` is dyn-compatible")?;
3206 }
3207 ty::PredicateKind::ConstEquate(c1, c2) => {
3208 write!(p, "the constant `")?;
3209 c1.print(p)?;
3210 write!(p, "` equals `")?;
3211 c2.print(p)?;
3212 write!(p, "`")?;
3213 }
3214 ty::PredicateKind::Ambiguous => write!(p, "ambiguous")?,
3215 ty::PredicateKind::NormalizesTo(data) => data.print(p)?,
3216 ty::PredicateKind::AliasRelate(t1, t2, dir) => {
3217 t1.print(p)?;
3218 write!(p, " {dir} ")?;
3219 t2.print(p)?;
3220 }
3221 }
3222 }
3223
3224 ty::ExistentialPredicate<'tcx> {
3225 match *self {
3226 ty::ExistentialPredicate::Trait(x) => x.print(p)?,
3227 ty::ExistentialPredicate::Projection(x) => x.print(p)?,
3228 ty::ExistentialPredicate::AutoTrait(def_id) => p.print_def_path(def_id, &[])?,
3229 }
3230 }
3231
3232 ty::ExistentialTraitRef<'tcx> {
3233 let dummy_self = Ty::new_fresh(p.tcx(), 0);
3235 let trait_ref = self.with_self_ty(p.tcx(), dummy_self);
3236 trait_ref.print_only_trait_path().print(p)?;
3237 }
3238
3239 ty::ExistentialProjection<'tcx> {
3240 let name = p.tcx().associated_item(self.def_id).name();
3241 let args = &self.args[p.tcx().generics_of(self.def_id).parent_count - 1..];
3244 p.print_path_with_generic_args(|p| write!(p, "{name}"), args)?;
3245 write!(p, " = ")?;
3246 self.term.print(p)?;
3247 }
3248
3249 ty::ProjectionPredicate<'tcx> {
3250 self.projection_term.print(p)?;
3251 write!(p, " == ")?;
3252 p.reset_type_limit();
3253 self.term.print(p)?;
3254 }
3255
3256 ty::SubtypePredicate<'tcx> {
3257 self.a.print(p)?;
3258 write!(p, " <: ")?;
3259 p.reset_type_limit();
3260 self.b.print(p)?;
3261 }
3262
3263 ty::CoercePredicate<'tcx> {
3264 self.a.print(p)?;
3265 write!(p, " -> ")?;
3266 p.reset_type_limit();
3267 self.b.print(p)?;
3268 }
3269
3270 ty::NormalizesTo<'tcx> {
3271 self.alias.print(p)?;
3272 write!(p, " normalizes-to ")?;
3273 p.reset_type_limit();
3274 self.term.print(p)?;
3275 }
3276}
3277
3278define_print_and_forward_display! {
3279 (self, p):
3280
3281 &'tcx ty::List<Ty<'tcx>> {
3282 write!(p, "{{")?;
3283 p.comma_sep(self.iter())?;
3284 write!(p, "}}")?;
3285 }
3286
3287 TraitRefPrintOnlyTraitPath<'tcx> {
3288 p.print_def_path(self.0.def_id, self.0.args)?;
3289 }
3290
3291 TraitRefPrintSugared<'tcx> {
3292 if !with_reduced_queries()
3293 && p.tcx().trait_def(self.0.def_id).paren_sugar
3294 && let ty::Tuple(args) = self.0.args.type_at(1).kind()
3295 {
3296 write!(p, "{}(", p.tcx().item_name(self.0.def_id))?;
3297 for (i, arg) in args.iter().enumerate() {
3298 if i > 0 {
3299 write!(p, ", ")?;
3300 }
3301 arg.print(p)?;
3302 }
3303 write!(p, ")")?;
3304 } else {
3305 p.print_def_path(self.0.def_id, self.0.args)?;
3306 }
3307 }
3308
3309 TraitRefPrintOnlyTraitName<'tcx> {
3310 p.print_def_path(self.0.def_id, &[])?;
3311 }
3312
3313 TraitPredPrintModifiersAndPath<'tcx> {
3314 if let ty::PredicatePolarity::Negative = self.0.polarity {
3315 write!(p, "!")?;
3316 }
3317 self.0.trait_ref.print_trait_sugared().print(p)?;
3318 }
3319
3320 TraitPredPrintWithBoundConstness<'tcx> {
3321 self.0.trait_ref.self_ty().print(p)?;
3322 write!(p, ": ")?;
3323 if let Some(constness) = self.1 {
3324 p.pretty_print_bound_constness(constness)?;
3325 }
3326 if let ty::PredicatePolarity::Negative = self.0.polarity {
3327 write!(p, "!")?;
3328 }
3329 self.0.trait_ref.print_trait_sugared().print(p)?;
3330 }
3331
3332 PrintClosureAsImpl<'tcx> {
3333 p.pretty_print_closure_as_impl(self.closure)?;
3334 }
3335
3336 ty::ParamTy {
3337 write!(p, "{}", self.name)?;
3338 }
3339
3340 ty::PlaceholderType {
3341 match self.bound.kind {
3342 ty::BoundTyKind::Anon => write!(p, "{self:?}")?,
3343 ty::BoundTyKind::Param(def_id) => match p.should_print_verbose() {
3344 true => write!(p, "{self:?}")?,
3345 false => write!(p, "{}", p.tcx().item_name(def_id))?,
3346 },
3347 }
3348 }
3349
3350 ty::ParamConst {
3351 write!(p, "{}", self.name)?;
3352 }
3353
3354 ty::Term<'tcx> {
3355 match self.kind() {
3356 ty::TermKind::Ty(ty) => ty.print(p)?,
3357 ty::TermKind::Const(c) => c.print(p)?,
3358 }
3359 }
3360
3361 ty::Predicate<'tcx> {
3362 self.kind().print(p)?;
3363 }
3364
3365 ty::Clause<'tcx> {
3366 self.kind().print(p)?;
3367 }
3368
3369 GenericArg<'tcx> {
3370 match self.kind() {
3371 GenericArgKind::Lifetime(lt) => lt.print(p)?,
3372 GenericArgKind::Type(ty) => ty.print(p)?,
3373 GenericArgKind::Const(ct) => ct.print(p)?,
3374 }
3375 }
3376}
3377
3378fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
3379 for id in tcx.hir_free_items() {
3381 if matches!(tcx.def_kind(id.owner_id), DefKind::Use) {
3382 continue;
3383 }
3384
3385 let item = tcx.hir_item(id);
3386 let Some(ident) = item.kind.ident() else { continue };
3387
3388 let def_id = item.owner_id.to_def_id();
3389 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
3390 collect_fn(&ident, ns, def_id);
3391 }
3392
3393 let queue = &mut Vec::new();
3395 let mut seen_defs: DefIdSet = Default::default();
3396
3397 for &cnum in tcx.crates(()).iter() {
3398 match tcx.extern_crate(cnum) {
3400 None => continue,
3401 Some(extern_crate) => {
3402 if !extern_crate.is_direct() {
3403 continue;
3404 }
3405 }
3406 }
3407
3408 queue.push(cnum.as_def_id());
3409 }
3410
3411 while let Some(def) = queue.pop() {
3413 for child in tcx.module_children(def).iter() {
3414 if !child.vis.is_public() {
3415 continue;
3416 }
3417
3418 match child.res {
3419 def::Res::Def(DefKind::AssocTy, _) => {}
3420 def::Res::Def(DefKind::TyAlias, _) => {}
3421 def::Res::Def(defkind, def_id) => {
3422 if let Some(ns) = defkind.ns() {
3423 collect_fn(&child.ident, ns, def_id);
3424 }
3425
3426 if defkind.is_module_like() && seen_defs.insert(def_id) {
3427 queue.push(def_id);
3428 }
3429 }
3430 _ => {}
3431 }
3432 }
3433 }
3434}
3435
3436pub fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> DefIdMap<Symbol> {
3452 tcx.sess.record_trimmed_def_paths();
3459
3460 let unique_symbols_rev: &mut FxIndexMap<(Namespace, Symbol), Option<DefId>> =
3463 &mut FxIndexMap::default();
3464
3465 for symbol_set in tcx.resolutions(()).glob_map.values() {
3466 for symbol in symbol_set {
3467 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
3468 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
3469 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
3470 }
3471 }
3472
3473 for_each_def(tcx, |ident, ns, def_id| match unique_symbols_rev.entry((ns, ident.name)) {
3474 IndexEntry::Occupied(mut v) => match v.get() {
3475 None => {}
3476 Some(existing) => {
3477 if *existing != def_id {
3478 v.insert(None);
3479 }
3480 }
3481 },
3482 IndexEntry::Vacant(v) => {
3483 v.insert(Some(def_id));
3484 }
3485 });
3486
3487 let mut map: DefIdMap<Symbol> = Default::default();
3489 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain(..) {
3490 use std::collections::hash_map::Entry::{Occupied, Vacant};
3491
3492 if let Some(def_id) = opt_def_id {
3493 match map.entry(def_id) {
3494 Occupied(mut v) => {
3495 if *v.get() != symbol && v.get().as_str() > symbol.as_str() {
3504 v.insert(symbol);
3505 }
3506 }
3507 Vacant(v) => {
3508 v.insert(symbol);
3509 }
3510 }
3511 }
3512 }
3513
3514 map
3515}
3516
3517pub fn provide(providers: &mut Providers) {
3518 *providers = Providers { trimmed_def_paths, ..*providers };
3519}
3520
3521pub struct OpaqueFnEntry<'tcx> {
3522 kind: ty::ClosureKind,
3523 return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,
3524}