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