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