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