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::LateAnonConst
2160 | DefPathData::Closure
2161 | DefPathData::Ctor => Namespace::ValueNS,
2162
2163 DefPathData::MacroNs(..) => Namespace::MacroNS,
2164
2165 _ => Namespace::TypeNS,
2166 }
2167}
2168
2169impl<'t> TyCtxt<'t> {
2170 pub fn def_path_str(self, def_id: impl IntoQueryParam<DefId>) -> String {
2173 self.def_path_str_with_args(def_id, &[])
2174 }
2175
2176 pub fn def_path_str_with_args(
2178 self,
2179 def_id: impl IntoQueryParam<DefId>,
2180 args: &'t [GenericArg<'t>],
2181 ) -> String {
2182 let def_id = def_id.into_query_param();
2183 let ns = guess_def_namespace(self, def_id);
2184 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
2185
2186 FmtPrinter::print_string(self, ns, |p| p.print_def_path(def_id, args)).unwrap()
2187 }
2188
2189 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 = Namespace::ValueNS;
2197 debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns);
2198
2199 FmtPrinter::print_string(self, ns, |p| p.print_def_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 print_dyn_existential(
2317 &mut self,
2318 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2319 ) -> Result<(), PrintError> {
2320 self.pretty_print_dyn_existential(predicates)
2321 }
2322
2323 fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
2324 self.pretty_print_const(ct, false)
2325 }
2326
2327 fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
2328 self.empty_path = true;
2329 if cnum == LOCAL_CRATE && !with_resolve_crate_name() {
2330 if self.tcx.sess.at_least_rust_2018() {
2331 if with_crate_prefix() {
2333 write!(self, "{}", kw::Crate)?;
2334 self.empty_path = false;
2335 }
2336 }
2337 } else {
2338 write!(self, "{}", self.tcx.crate_name(cnum))?;
2339 self.empty_path = false;
2340 }
2341 Ok(())
2342 }
2343
2344 fn print_path_with_qualified(
2345 &mut self,
2346 self_ty: Ty<'tcx>,
2347 trait_ref: Option<ty::TraitRef<'tcx>>,
2348 ) -> Result<(), PrintError> {
2349 self.pretty_print_path_with_qualified(self_ty, trait_ref)?;
2350 self.empty_path = false;
2351 Ok(())
2352 }
2353
2354 fn print_path_with_impl(
2355 &mut self,
2356 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2357 self_ty: Ty<'tcx>,
2358 trait_ref: Option<ty::TraitRef<'tcx>>,
2359 ) -> Result<(), PrintError> {
2360 self.pretty_print_path_with_impl(
2361 |p| {
2362 print_prefix(p)?;
2363 if !p.empty_path {
2364 write!(p, "::")?;
2365 }
2366
2367 Ok(())
2368 },
2369 self_ty,
2370 trait_ref,
2371 )?;
2372 self.empty_path = false;
2373 Ok(())
2374 }
2375
2376 fn print_path_with_simple(
2377 &mut self,
2378 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2379 disambiguated_data: &DisambiguatedDefPathData,
2380 ) -> Result<(), PrintError> {
2381 print_prefix(self)?;
2382
2383 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
2385 return Ok(());
2386 }
2387
2388 let name = disambiguated_data.data.name();
2389 if !self.empty_path {
2390 write!(self, "::")?;
2391 }
2392
2393 if let DefPathDataName::Named(name) = name {
2394 if Ident::with_dummy_span(name).is_raw_guess() {
2395 write!(self, "r#")?;
2396 }
2397 }
2398
2399 let verbose = self.should_print_verbose();
2400 write!(self, "{}", disambiguated_data.as_sym(verbose))?;
2401
2402 self.empty_path = false;
2403
2404 Ok(())
2405 }
2406
2407 fn print_path_with_generic_args(
2408 &mut self,
2409 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2410 args: &[GenericArg<'tcx>],
2411 ) -> Result<(), PrintError> {
2412 print_prefix(self)?;
2413
2414 if !args.is_empty() {
2415 if self.in_value {
2416 write!(self, "::")?;
2417 }
2418 self.generic_delimiters(|p| p.comma_sep(args.iter().copied()))
2419 } else {
2420 Ok(())
2421 }
2422 }
2423}
2424
2425impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
2426 fn ty_infer_name(&self, id: ty::TyVid) -> Option<Symbol> {
2427 self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
2428 }
2429
2430 fn reset_type_limit(&mut self) {
2431 self.printed_type_count = 0;
2432 }
2433
2434 fn const_infer_name(&self, id: ty::ConstVid) -> Option<Symbol> {
2435 self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
2436 }
2437
2438 fn pretty_print_value_path(
2439 &mut self,
2440 def_id: DefId,
2441 args: &'tcx [GenericArg<'tcx>],
2442 ) -> Result<(), PrintError> {
2443 let was_in_value = std::mem::replace(&mut self.in_value, true);
2444 self.print_def_path(def_id, args)?;
2445 self.in_value = was_in_value;
2446
2447 Ok(())
2448 }
2449
2450 fn pretty_print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError>
2451 where
2452 T: Print<'tcx, Self> + TypeFoldable<TyCtxt<'tcx>>,
2453 {
2454 self.wrap_binder(value, WrapBinderMode::ForAll, |new_value, this| new_value.print(this))
2455 }
2456
2457 fn wrap_binder<T, C: FnOnce(&T, &mut Self) -> Result<(), PrintError>>(
2458 &mut self,
2459 value: &ty::Binder<'tcx, T>,
2460 mode: WrapBinderMode,
2461 f: C,
2462 ) -> Result<(), PrintError>
2463 where
2464 T: TypeFoldable<TyCtxt<'tcx>>,
2465 {
2466 let old_region_index = self.region_index;
2467 let (new_value, _) = self.name_all_regions(value, mode)?;
2468 f(&new_value, self)?;
2469 self.region_index = old_region_index;
2470 self.binder_depth -= 1;
2471 Ok(())
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_truncate(&mut self) -> bool {
2505 !self.type_length_limit.value_within_limit(self.printed_type_count)
2506 }
2507
2508 fn should_print_optional_region(&self, region: ty::Region<'tcx>) -> bool {
2509 let highlight = self.region_highlight_mode;
2510 if highlight.region_highlighted(region).is_some() {
2511 return true;
2512 }
2513
2514 if self.should_print_verbose() {
2515 return true;
2516 }
2517
2518 if with_forced_trimmed_paths() {
2519 return false;
2520 }
2521
2522 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2523
2524 match region.kind() {
2525 ty::ReEarlyParam(ref data) => data.is_named(),
2526
2527 ty::ReLateParam(ty::LateParamRegion { kind, .. }) => kind.is_named(self.tcx),
2528 ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2529 | ty::RePlaceholder(ty::Placeholder {
2530 bound: ty::BoundRegion { kind: br, .. }, ..
2531 }) => {
2532 if br.is_named(self.tcx) {
2533 return true;
2534 }
2535
2536 if let Some((region, _)) = highlight.highlight_bound_region {
2537 if br == region {
2538 return true;
2539 }
2540 }
2541
2542 false
2543 }
2544
2545 ty::ReVar(_) if identify_regions => true,
2546
2547 ty::ReVar(_) | ty::ReErased | ty::ReError(_) => false,
2548
2549 ty::ReStatic => true,
2550 }
2551 }
2552
2553 fn pretty_print_const_pointer<Prov: Provenance>(
2554 &mut self,
2555 p: Pointer<Prov>,
2556 ty: Ty<'tcx>,
2557 ) -> Result<(), PrintError> {
2558 let print = |this: &mut Self| {
2559 if this.print_alloc_ids {
2560 write!(this, "{p:?}")?;
2561 } else {
2562 write!(this, "&_")?;
2563 }
2564 Ok(())
2565 };
2566 self.typed_value(print, |this| this.print_type(ty), ": ")
2567 }
2568}
2569
2570impl<'tcx> FmtPrinter<'_, 'tcx> {
2572 pub fn pretty_print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), fmt::Error> {
2573 let highlight = self.region_highlight_mode;
2575 if let Some(n) = highlight.region_highlighted(region) {
2576 write!(self, "'{n}")?;
2577 return Ok(());
2578 }
2579
2580 if self.should_print_verbose() {
2581 write!(self, "{region:?}")?;
2582 return Ok(());
2583 }
2584
2585 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2586
2587 match region.kind() {
2592 ty::ReEarlyParam(data) => {
2593 write!(self, "{}", data.name)?;
2594 return Ok(());
2595 }
2596 ty::ReLateParam(ty::LateParamRegion { kind, .. }) => {
2597 if let Some(name) = kind.get_name(self.tcx) {
2598 write!(self, "{name}")?;
2599 return Ok(());
2600 }
2601 }
2602 ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2603 | ty::RePlaceholder(ty::Placeholder {
2604 bound: ty::BoundRegion { kind: br, .. }, ..
2605 }) => {
2606 if let Some(name) = br.get_name(self.tcx) {
2607 write!(self, "{name}")?;
2608 return Ok(());
2609 }
2610
2611 if let Some((region, counter)) = highlight.highlight_bound_region {
2612 if br == region {
2613 write!(self, "'{counter}")?;
2614 return Ok(());
2615 }
2616 }
2617 }
2618 ty::ReVar(region_vid) if identify_regions => {
2619 write!(self, "{region_vid:?}")?;
2620 return Ok(());
2621 }
2622 ty::ReVar(_) => {}
2623 ty::ReErased => {}
2624 ty::ReError(_) => {}
2625 ty::ReStatic => {
2626 write!(self, "'static")?;
2627 return Ok(());
2628 }
2629 }
2630
2631 write!(self, "'_")?;
2632
2633 Ok(())
2634 }
2635}
2636
2637struct RegionFolder<'a, 'tcx> {
2639 tcx: TyCtxt<'tcx>,
2640 current_index: ty::DebruijnIndex,
2641 region_map: UnordMap<ty::BoundRegion, ty::Region<'tcx>>,
2642 name: &'a mut (
2643 dyn FnMut(
2644 Option<ty::DebruijnIndex>, ty::DebruijnIndex, ty::BoundRegion,
2647 ) -> ty::Region<'tcx>
2648 + 'a
2649 ),
2650}
2651
2652impl<'a, 'tcx> ty::TypeFolder<TyCtxt<'tcx>> for RegionFolder<'a, 'tcx> {
2653 fn cx(&self) -> TyCtxt<'tcx> {
2654 self.tcx
2655 }
2656
2657 fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>(
2658 &mut self,
2659 t: ty::Binder<'tcx, T>,
2660 ) -> ty::Binder<'tcx, T> {
2661 self.current_index.shift_in(1);
2662 let t = t.super_fold_with(self);
2663 self.current_index.shift_out(1);
2664 t
2665 }
2666
2667 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2668 match *t.kind() {
2669 _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2670 return t.super_fold_with(self);
2671 }
2672 _ => {}
2673 }
2674 t
2675 }
2676
2677 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2678 let name = &mut self.name;
2679 let region = match r.kind() {
2680 ty::ReBound(ty::BoundVarIndexKind::Bound(db), br) if db >= self.current_index => {
2681 *self.region_map.entry(br).or_insert_with(|| name(Some(db), self.current_index, br))
2682 }
2683 ty::RePlaceholder(ty::PlaceholderRegion {
2684 bound: ty::BoundRegion { kind, .. },
2685 ..
2686 }) => {
2687 match kind {
2690 ty::BoundRegionKind::Anon | ty::BoundRegionKind::ClosureEnv => r,
2691 _ => {
2692 let br = ty::BoundRegion { var: ty::BoundVar::ZERO, kind };
2694 *self
2695 .region_map
2696 .entry(br)
2697 .or_insert_with(|| name(None, self.current_index, br))
2698 }
2699 }
2700 }
2701 _ => return r,
2702 };
2703 if let ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn1), br) = region.kind() {
2704 assert_eq!(debruijn1, ty::INNERMOST);
2705 ty::Region::new_bound(self.tcx, self.current_index, br)
2706 } else {
2707 region
2708 }
2709 }
2710}
2711
2712impl<'tcx> FmtPrinter<'_, 'tcx> {
2715 pub fn name_all_regions<T>(
2716 &mut self,
2717 value: &ty::Binder<'tcx, T>,
2718 mode: WrapBinderMode,
2719 ) -> Result<(T, UnordMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
2720 where
2721 T: TypeFoldable<TyCtxt<'tcx>>,
2722 {
2723 fn name_by_region_index(
2724 index: usize,
2725 available_names: &mut Vec<Symbol>,
2726 num_available: usize,
2727 ) -> Symbol {
2728 if let Some(name) = available_names.pop() {
2729 name
2730 } else {
2731 Symbol::intern(&format!("'z{}", index - num_available))
2732 }
2733 }
2734
2735 debug!("name_all_regions");
2736
2737 if self.binder_depth == 0 {
2743 self.prepare_region_info(value);
2744 }
2745
2746 debug!("self.used_region_names: {:?}", self.used_region_names);
2747
2748 let mut empty = true;
2749 let mut start_or_continue = |p: &mut Self, start: &str, cont: &str| {
2750 let w = if empty {
2751 empty = false;
2752 start
2753 } else {
2754 cont
2755 };
2756 let _ = write!(p, "{w}");
2757 };
2758 let do_continue = |p: &mut Self, cont: Symbol| {
2759 let _ = write!(p, "{cont}");
2760 };
2761
2762 let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&format!("'{s}")));
2763
2764 let mut available_names = possible_names
2765 .filter(|name| !self.used_region_names.contains(name))
2766 .collect::<Vec<_>>();
2767 debug!(?available_names);
2768 let num_available = available_names.len();
2769
2770 let mut region_index = self.region_index;
2771 let mut next_name = |this: &Self| {
2772 let mut name;
2773
2774 loop {
2775 name = name_by_region_index(region_index, &mut available_names, num_available);
2776 region_index += 1;
2777
2778 if !this.used_region_names.contains(&name) {
2779 break;
2780 }
2781 }
2782
2783 name
2784 };
2785
2786 let (new_value, map) = if self.should_print_verbose() {
2791 for var in value.bound_vars().iter() {
2792 start_or_continue(self, mode.start_str(), ", ");
2793 write!(self, "{var:?}")?;
2794 }
2795 if value.bound_vars().is_empty() && mode == WrapBinderMode::Unsafe {
2797 start_or_continue(self, mode.start_str(), "");
2798 }
2799 start_or_continue(self, "", "> ");
2800 (value.clone().skip_binder(), UnordMap::default())
2801 } else {
2802 let tcx = self.tcx;
2803
2804 let trim_path = with_forced_trimmed_paths();
2805 let mut name = |lifetime_idx: Option<ty::DebruijnIndex>,
2811 binder_level_idx: ty::DebruijnIndex,
2812 br: ty::BoundRegion| {
2813 let (name, kind) = if let Some(name) = br.kind.get_name(tcx) {
2814 (name, br.kind)
2815 } else {
2816 let name = next_name(self);
2817 (name, ty::BoundRegionKind::NamedAnon(name))
2818 };
2819
2820 if let Some(lt_idx) = lifetime_idx {
2821 if lt_idx > binder_level_idx {
2822 return ty::Region::new_bound(
2823 tcx,
2824 ty::INNERMOST,
2825 ty::BoundRegion { var: br.var, kind },
2826 );
2827 }
2828 }
2829
2830 if !trim_path || mode == WrapBinderMode::Unsafe {
2832 start_or_continue(self, mode.start_str(), ", ");
2833 do_continue(self, name);
2834 }
2835 ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { var: br.var, kind })
2836 };
2837 let mut folder = RegionFolder {
2838 tcx,
2839 current_index: ty::INNERMOST,
2840 name: &mut name,
2841 region_map: UnordMap::default(),
2842 };
2843 let new_value = value.clone().skip_binder().fold_with(&mut folder);
2844 let region_map = folder.region_map;
2845
2846 if mode == WrapBinderMode::Unsafe && region_map.is_empty() {
2847 start_or_continue(self, mode.start_str(), "");
2848 }
2849 start_or_continue(self, "", "> ");
2850
2851 (new_value, region_map)
2852 };
2853
2854 self.binder_depth += 1;
2855 self.region_index = region_index;
2856 Ok((new_value, map))
2857 }
2858
2859 fn prepare_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2860 where
2861 T: TypeFoldable<TyCtxt<'tcx>>,
2862 {
2863 struct RegionNameCollector<'tcx> {
2864 tcx: TyCtxt<'tcx>,
2865 used_region_names: FxHashSet<Symbol>,
2866 type_collector: SsoHashSet<Ty<'tcx>>,
2867 }
2868
2869 impl<'tcx> RegionNameCollector<'tcx> {
2870 fn new(tcx: TyCtxt<'tcx>) -> Self {
2871 RegionNameCollector {
2872 tcx,
2873 used_region_names: Default::default(),
2874 type_collector: SsoHashSet::new(),
2875 }
2876 }
2877 }
2878
2879 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for RegionNameCollector<'tcx> {
2880 fn visit_region(&mut self, r: ty::Region<'tcx>) {
2881 trace!("address: {:p}", r.0.0);
2882
2883 if let Some(name) = r.get_name(self.tcx) {
2887 self.used_region_names.insert(name);
2888 }
2889 }
2890
2891 fn visit_ty(&mut self, ty: Ty<'tcx>) {
2894 let not_previously_inserted = self.type_collector.insert(ty);
2895 if not_previously_inserted {
2896 ty.super_visit_with(self)
2897 }
2898 }
2899 }
2900
2901 let mut collector = RegionNameCollector::new(self.tcx());
2902 value.visit_with(&mut collector);
2903 self.used_region_names = collector.used_region_names;
2904 self.region_index = 0;
2905 }
2906}
2907
2908impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2909where
2910 T: Print<'tcx, P> + TypeFoldable<TyCtxt<'tcx>>,
2911{
2912 fn print(&self, p: &mut P) -> Result<(), PrintError> {
2913 p.pretty_print_in_binder(self)
2914 }
2915}
2916
2917impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<'tcx, T>
2918where
2919 T: Print<'tcx, P>,
2920{
2921 fn print(&self, p: &mut P) -> Result<(), PrintError> {
2922 self.0.print(p)?;
2923 write!(p, ": ")?;
2924 self.1.print(p)?;
2925 Ok(())
2926 }
2927}
2928
2929#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
2933pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2934
2935impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintOnlyTraitPath<'tcx> {
2936 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
2937 ty::tls::with(|tcx| {
2938 let trait_ref = tcx.short_string(self, path);
2939 rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
2940 })
2941 }
2942}
2943
2944impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
2945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2946 fmt::Display::fmt(self, f)
2947 }
2948}
2949
2950#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
2953pub struct TraitRefPrintSugared<'tcx>(ty::TraitRef<'tcx>);
2954
2955impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintSugared<'tcx> {
2956 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
2957 ty::tls::with(|tcx| {
2958 let trait_ref = tcx.short_string(self, path);
2959 rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
2960 })
2961 }
2962}
2963
2964impl<'tcx> fmt::Debug for TraitRefPrintSugared<'tcx> {
2965 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2966 fmt::Display::fmt(self, f)
2967 }
2968}
2969
2970#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2974pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
2975
2976impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
2977 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2978 fmt::Display::fmt(self, f)
2979 }
2980}
2981
2982#[extension(pub trait PrintTraitRefExt<'tcx>)]
2983impl<'tcx> ty::TraitRef<'tcx> {
2984 fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2985 TraitRefPrintOnlyTraitPath(self)
2986 }
2987
2988 fn print_trait_sugared(self) -> TraitRefPrintSugared<'tcx> {
2989 TraitRefPrintSugared(self)
2990 }
2991
2992 fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
2993 TraitRefPrintOnlyTraitName(self)
2994 }
2995}
2996
2997#[extension(pub trait PrintPolyTraitRefExt<'tcx>)]
2998impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
2999 fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
3000 self.map_bound(|tr| tr.print_only_trait_path())
3001 }
3002
3003 fn print_trait_sugared(self) -> ty::Binder<'tcx, TraitRefPrintSugared<'tcx>> {
3004 self.map_bound(|tr| tr.print_trait_sugared())
3005 }
3006}
3007
3008#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
3009pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
3010
3011impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
3012 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3013 fmt::Display::fmt(self, f)
3014 }
3015}
3016
3017#[extension(pub trait PrintTraitPredicateExt<'tcx>)]
3018impl<'tcx> ty::TraitPredicate<'tcx> {
3019 fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
3020 TraitPredPrintModifiersAndPath(self)
3021 }
3022}
3023
3024#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)]
3025pub struct TraitPredPrintWithBoundConstness<'tcx>(
3026 ty::TraitPredicate<'tcx>,
3027 Option<ty::BoundConstness>,
3028);
3029
3030impl<'tcx> fmt::Debug for TraitPredPrintWithBoundConstness<'tcx> {
3031 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3032 fmt::Display::fmt(self, f)
3033 }
3034}
3035
3036#[extension(pub trait PrintPolyTraitPredicateExt<'tcx>)]
3037impl<'tcx> ty::PolyTraitPredicate<'tcx> {
3038 fn print_modifiers_and_trait_path(
3039 self,
3040 ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
3041 self.map_bound(TraitPredPrintModifiersAndPath)
3042 }
3043
3044 fn print_with_bound_constness(
3045 self,
3046 constness: Option<ty::BoundConstness>,
3047 ) -> ty::Binder<'tcx, TraitPredPrintWithBoundConstness<'tcx>> {
3048 self.map_bound(|trait_pred| TraitPredPrintWithBoundConstness(trait_pred, constness))
3049 }
3050}
3051
3052#[derive(Debug, Copy, Clone, Lift)]
3053pub struct PrintClosureAsImpl<'tcx> {
3054 pub closure: ty::ClosureArgs<TyCtxt<'tcx>>,
3055}
3056
3057macro_rules! forward_display_to_print {
3058 ($($ty:ty),+) => {
3059 $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty {
3061 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3062 ty::tls::with(|tcx| {
3063 let mut p = FmtPrinter::new(tcx, Namespace::TypeNS);
3064 tcx.lift(*self)
3065 .expect("could not lift for printing")
3066 .print(&mut p)?;
3067 f.write_str(&p.into_buffer())?;
3068 Ok(())
3069 })
3070 }
3071 })+
3072 };
3073}
3074
3075macro_rules! define_print {
3076 (($self:ident, $p:ident): $($ty:ty $print:block)+) => {
3077 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
3078 fn print(&$self, $p: &mut P) -> Result<(), PrintError> {
3079 let _: () = $print;
3080 Ok(())
3081 }
3082 })+
3083 };
3084}
3085
3086macro_rules! define_print_and_forward_display {
3087 (($self:ident, $p:ident): $($ty:ty $print:block)+) => {
3088 define_print!(($self, $p): $($ty $print)*);
3089 forward_display_to_print!($($ty),+);
3090 };
3091}
3092
3093forward_display_to_print! {
3094 ty::Region<'tcx>,
3095 Ty<'tcx>,
3096 &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3097 ty::Const<'tcx>
3098}
3099
3100define_print! {
3101 (self, p):
3102
3103 ty::FnSig<'tcx> {
3104 write!(p, "{}", self.safety.prefix_str())?;
3105
3106 if self.abi != ExternAbi::Rust {
3107 write!(p, "extern {} ", self.abi)?;
3108 }
3109
3110 write!(p, "fn")?;
3111 p.pretty_print_fn_sig(self.inputs(), self.c_variadic, self.output())?;
3112 }
3113
3114 ty::TraitRef<'tcx> {
3115 write!(p, "<{} as {}>", self.self_ty(), self.print_only_trait_path())?;
3116 }
3117
3118 ty::AliasTy<'tcx> {
3119 let alias_term: ty::AliasTerm<'tcx> = (*self).into();
3120 alias_term.print(p)?;
3121 }
3122
3123 ty::AliasTerm<'tcx> {
3124 match self.kind(p.tcx()) {
3125 ty::AliasTermKind::InherentTy | ty::AliasTermKind::InherentConst => p.pretty_print_inherent_projection(*self)?,
3126 ty::AliasTermKind::ProjectionTy => {
3127 if !(p.should_print_verbose() || with_reduced_queries())
3128 && p.tcx().is_impl_trait_in_trait(self.def_id)
3129 {
3130 p.pretty_print_rpitit(self.def_id, self.args)?;
3131 } else {
3132 p.print_def_path(self.def_id, self.args)?;
3133 }
3134 }
3135 ty::AliasTermKind::FreeTy
3136 | ty::AliasTermKind::FreeConst
3137 | ty::AliasTermKind::OpaqueTy
3138 | ty::AliasTermKind::UnevaluatedConst
3139 | ty::AliasTermKind::ProjectionConst => {
3140 p.print_def_path(self.def_id, self.args)?;
3141 }
3142 }
3143 }
3144
3145 ty::TraitPredicate<'tcx> {
3146 self.trait_ref.self_ty().print(p)?;
3147 write!(p, ": ")?;
3148 if let ty::PredicatePolarity::Negative = self.polarity {
3149 write!(p, "!")?;
3150 }
3151 self.trait_ref.print_trait_sugared().print(p)?;
3152 }
3153
3154 ty::HostEffectPredicate<'tcx> {
3155 let constness = match self.constness {
3156 ty::BoundConstness::Const => { "const" }
3157 ty::BoundConstness::Maybe => { "[const]" }
3158 };
3159 self.trait_ref.self_ty().print(p)?;
3160 write!(p, ": {constness} ")?;
3161 self.trait_ref.print_trait_sugared().print(p)?;
3162 }
3163
3164 ty::TypeAndMut<'tcx> {
3165 write!(p, "{}", self.mutbl.prefix_str())?;
3166 self.ty.print(p)?;
3167 }
3168
3169 ty::ClauseKind<'tcx> {
3170 match *self {
3171 ty::ClauseKind::Trait(ref data) => data.print(p)?,
3172 ty::ClauseKind::RegionOutlives(predicate) => predicate.print(p)?,
3173 ty::ClauseKind::TypeOutlives(predicate) => predicate.print(p)?,
3174 ty::ClauseKind::Projection(predicate) => predicate.print(p)?,
3175 ty::ClauseKind::HostEffect(predicate) => predicate.print(p)?,
3176 ty::ClauseKind::ConstArgHasType(ct, ty) => {
3177 write!(p, "the constant `")?;
3178 ct.print(p)?;
3179 write!(p, "` has type `")?;
3180 ty.print(p)?;
3181 write!(p, "`")?;
3182 },
3183 ty::ClauseKind::WellFormed(term) => {
3184 term.print(p)?;
3185 write!(p, " well-formed")?;
3186 }
3187 ty::ClauseKind::ConstEvaluatable(ct) => {
3188 write!(p, "the constant `")?;
3189 ct.print(p)?;
3190 write!(p, "` can be evaluated")?;
3191 }
3192 ty::ClauseKind::UnstableFeature(symbol) => {
3193 write!(p, "feature({symbol}) is enabled")?;
3194 }
3195 }
3196 }
3197
3198 ty::PredicateKind<'tcx> {
3199 match *self {
3200 ty::PredicateKind::Clause(data) => data.print(p)?,
3201 ty::PredicateKind::Subtype(predicate) => predicate.print(p)?,
3202 ty::PredicateKind::Coerce(predicate) => predicate.print(p)?,
3203 ty::PredicateKind::DynCompatible(trait_def_id) => {
3204 write!(p, "the trait `")?;
3205 p.print_def_path(trait_def_id, &[])?;
3206 write!(p, "` is dyn-compatible")?;
3207 }
3208 ty::PredicateKind::ConstEquate(c1, c2) => {
3209 write!(p, "the constant `")?;
3210 c1.print(p)?;
3211 write!(p, "` equals `")?;
3212 c2.print(p)?;
3213 write!(p, "`")?;
3214 }
3215 ty::PredicateKind::Ambiguous => write!(p, "ambiguous")?,
3216 ty::PredicateKind::NormalizesTo(data) => data.print(p)?,
3217 ty::PredicateKind::AliasRelate(t1, t2, dir) => {
3218 t1.print(p)?;
3219 write!(p, " {dir} ")?;
3220 t2.print(p)?;
3221 }
3222 }
3223 }
3224
3225 ty::ExistentialPredicate<'tcx> {
3226 match *self {
3227 ty::ExistentialPredicate::Trait(x) => x.print(p)?,
3228 ty::ExistentialPredicate::Projection(x) => x.print(p)?,
3229 ty::ExistentialPredicate::AutoTrait(def_id) => p.print_def_path(def_id, &[])?,
3230 }
3231 }
3232
3233 ty::ExistentialTraitRef<'tcx> {
3234 let dummy_self = Ty::new_fresh(p.tcx(), 0);
3236 let trait_ref = self.with_self_ty(p.tcx(), dummy_self);
3237 trait_ref.print_only_trait_path().print(p)?;
3238 }
3239
3240 ty::ExistentialProjection<'tcx> {
3241 let name = p.tcx().associated_item(self.def_id).name();
3242 let args = &self.args[p.tcx().generics_of(self.def_id).parent_count - 1..];
3245 p.print_path_with_generic_args(|p| write!(p, "{name}"), args)?;
3246 write!(p, " = ")?;
3247 self.term.print(p)?;
3248 }
3249
3250 ty::ProjectionPredicate<'tcx> {
3251 self.projection_term.print(p)?;
3252 write!(p, " == ")?;
3253 p.reset_type_limit();
3254 self.term.print(p)?;
3255 }
3256
3257 ty::SubtypePredicate<'tcx> {
3258 self.a.print(p)?;
3259 write!(p, " <: ")?;
3260 p.reset_type_limit();
3261 self.b.print(p)?;
3262 }
3263
3264 ty::CoercePredicate<'tcx> {
3265 self.a.print(p)?;
3266 write!(p, " -> ")?;
3267 p.reset_type_limit();
3268 self.b.print(p)?;
3269 }
3270
3271 ty::NormalizesTo<'tcx> {
3272 self.alias.print(p)?;
3273 write!(p, " normalizes-to ")?;
3274 p.reset_type_limit();
3275 self.term.print(p)?;
3276 }
3277}
3278
3279define_print_and_forward_display! {
3280 (self, p):
3281
3282 &'tcx ty::List<Ty<'tcx>> {
3283 write!(p, "{{")?;
3284 p.comma_sep(self.iter())?;
3285 write!(p, "}}")?;
3286 }
3287
3288 TraitRefPrintOnlyTraitPath<'tcx> {
3289 p.print_def_path(self.0.def_id, self.0.args)?;
3290 }
3291
3292 TraitRefPrintSugared<'tcx> {
3293 if !with_reduced_queries()
3294 && p.tcx().trait_def(self.0.def_id).paren_sugar
3295 && let ty::Tuple(args) = self.0.args.type_at(1).kind()
3296 {
3297 write!(p, "{}(", p.tcx().item_name(self.0.def_id))?;
3298 for (i, arg) in args.iter().enumerate() {
3299 if i > 0 {
3300 write!(p, ", ")?;
3301 }
3302 arg.print(p)?;
3303 }
3304 write!(p, ")")?;
3305 } else {
3306 p.print_def_path(self.0.def_id, self.0.args)?;
3307 }
3308 }
3309
3310 TraitRefPrintOnlyTraitName<'tcx> {
3311 p.print_def_path(self.0.def_id, &[])?;
3312 }
3313
3314 TraitPredPrintModifiersAndPath<'tcx> {
3315 if let ty::PredicatePolarity::Negative = self.0.polarity {
3316 write!(p, "!")?;
3317 }
3318 self.0.trait_ref.print_trait_sugared().print(p)?;
3319 }
3320
3321 TraitPredPrintWithBoundConstness<'tcx> {
3322 self.0.trait_ref.self_ty().print(p)?;
3323 write!(p, ": ")?;
3324 if let Some(constness) = self.1 {
3325 p.pretty_print_bound_constness(constness)?;
3326 }
3327 if let ty::PredicatePolarity::Negative = self.0.polarity {
3328 write!(p, "!")?;
3329 }
3330 self.0.trait_ref.print_trait_sugared().print(p)?;
3331 }
3332
3333 PrintClosureAsImpl<'tcx> {
3334 p.pretty_print_closure_as_impl(self.closure)?;
3335 }
3336
3337 ty::ParamTy {
3338 write!(p, "{}", self.name)?;
3339 }
3340
3341 ty::PlaceholderType {
3342 match self.bound.kind {
3343 ty::BoundTyKind::Anon => write!(p, "{self:?}")?,
3344 ty::BoundTyKind::Param(def_id) => match p.should_print_verbose() {
3345 true => write!(p, "{self:?}")?,
3346 false => write!(p, "{}", p.tcx().item_name(def_id))?,
3347 },
3348 }
3349 }
3350
3351 ty::ParamConst {
3352 write!(p, "{}", self.name)?;
3353 }
3354
3355 ty::Term<'tcx> {
3356 match self.kind() {
3357 ty::TermKind::Ty(ty) => ty.print(p)?,
3358 ty::TermKind::Const(c) => c.print(p)?,
3359 }
3360 }
3361
3362 ty::Predicate<'tcx> {
3363 self.kind().print(p)?;
3364 }
3365
3366 ty::Clause<'tcx> {
3367 self.kind().print(p)?;
3368 }
3369
3370 GenericArg<'tcx> {
3371 match self.kind() {
3372 GenericArgKind::Lifetime(lt) => lt.print(p)?,
3373 GenericArgKind::Type(ty) => ty.print(p)?,
3374 GenericArgKind::Const(ct) => ct.print(p)?,
3375 }
3376 }
3377}
3378
3379fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
3380 for id in tcx.hir_free_items() {
3382 if matches!(tcx.def_kind(id.owner_id), DefKind::Use) {
3383 continue;
3384 }
3385
3386 let item = tcx.hir_item(id);
3387 let Some(ident) = item.kind.ident() else { continue };
3388
3389 let def_id = item.owner_id.to_def_id();
3390 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
3391 collect_fn(&ident, ns, def_id);
3392 }
3393
3394 let queue = &mut Vec::new();
3396 let mut seen_defs: DefIdSet = Default::default();
3397
3398 for &cnum in tcx.crates(()).iter() {
3399 match tcx.extern_crate(cnum) {
3401 None => continue,
3402 Some(extern_crate) => {
3403 if !extern_crate.is_direct() {
3404 continue;
3405 }
3406 }
3407 }
3408
3409 queue.push(cnum.as_def_id());
3410 }
3411
3412 while let Some(def) = queue.pop() {
3414 for child in tcx.module_children(def).iter() {
3415 if !child.vis.is_public() {
3416 continue;
3417 }
3418
3419 match child.res {
3420 def::Res::Def(DefKind::AssocTy, _) => {}
3421 def::Res::Def(DefKind::TyAlias, _) => {}
3422 def::Res::Def(defkind, def_id) => {
3423 if let Some(ns) = defkind.ns() {
3424 collect_fn(&child.ident, ns, def_id);
3425 }
3426
3427 if defkind.is_module_like() && seen_defs.insert(def_id) {
3428 queue.push(def_id);
3429 }
3430 }
3431 _ => {}
3432 }
3433 }
3434 }
3435}
3436
3437pub fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> DefIdMap<Symbol> {
3453 tcx.sess.record_trimmed_def_paths();
3460
3461 let unique_symbols_rev: &mut FxIndexMap<(Namespace, Symbol), Option<DefId>> =
3464 &mut FxIndexMap::default();
3465
3466 for symbol_set in tcx.resolutions(()).glob_map.values() {
3467 for symbol in symbol_set {
3468 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
3469 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
3470 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
3471 }
3472 }
3473
3474 for_each_def(tcx, |ident, ns, def_id| match unique_symbols_rev.entry((ns, ident.name)) {
3475 IndexEntry::Occupied(mut v) => match v.get() {
3476 None => {}
3477 Some(existing) => {
3478 if *existing != def_id {
3479 v.insert(None);
3480 }
3481 }
3482 },
3483 IndexEntry::Vacant(v) => {
3484 v.insert(Some(def_id));
3485 }
3486 });
3487
3488 let mut map: DefIdMap<Symbol> = Default::default();
3490 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain(..) {
3491 use std::collections::hash_map::Entry::{Occupied, Vacant};
3492
3493 if let Some(def_id) = opt_def_id {
3494 match map.entry(def_id) {
3495 Occupied(mut v) => {
3496 if *v.get() != symbol && v.get().as_str() > symbol.as_str() {
3505 v.insert(symbol);
3506 }
3507 }
3508 Vacant(v) => {
3509 v.insert(symbol);
3510 }
3511 }
3512 }
3513 }
3514
3515 map
3516}
3517
3518pub fn provide(providers: &mut Providers) {
3519 *providers = Providers { trimmed_def_paths, ..*providers };
3520}
3521
3522pub struct OpaqueFnEntry<'tcx> {
3523 kind: ty::ClosureKind,
3524 return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,
3525}