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