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_attr_ir::lang_items::LangItem;
10use rustc_crate_store::{ExternCrate, ExternCrateSource};
11use rustc_data_structures::fx::{FxIndexMap, IndexEntry};
12use rustc_data_structures::unord::UnordMap;
13use rustc_hir as hir;
14use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
15use rustc_hir::def_id::{DefIdMap, DefIdSet, LOCAL_CRATE, ModId};
16use rustc_hir::definitions::{DefKey, DefPathDataName};
17use rustc_macros::{Lift, extension};
18use rustc_span::{Ident, RemapPathScopeComponents, Symbol, bug, kw, sym};
19use rustc_structures::Limit;
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, TraitClause,
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>>() {
|__rust_std_internal_init|
{
#[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 {
|__rust_std_internal_init|
{
#[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]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for RtnMode {
}
#[automatically_derived]impl ::core::clone::Clone for RtnMode {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for RtnMode {
}
#[automatically_derived]impl ::core::cmp::PartialEq for RtnMode {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for RtnMode { }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 ReducedQueriesGuard(bool);
impl ReducedQueriesGuard {
pub fn new() -> ReducedQueriesGuard {
ReducedQueriesGuard(REDUCED_QUERIES.replace(true))
}
}
#[doc = r" Avoids running select queries during any prints that occur"]
#[doc = r" during the closure. This may alter the appearance of some"]
#[doc = r" types (e.g. forcing verbose printing for opaque types)."]
#[doc =
r" This method is used during some queries (e.g. `explicit_item_bounds`"]
#[doc = r" for opaque types), to ensure that any debug printing that"]
#[doc = r" occurs during the query computation does not end up recursively"]
#[doc = r" calling the same query."]
pub macro with_reduced_queries {
($e : expr) => { { let _guard = ReducedQueriesGuard :: new(); $e } }
}
impl Drop for ReducedQueriesGuard {
fn drop(&mut self) { REDUCED_QUERIES.set(self.0) }
}
pub fn with_reduced_queries() -> bool { REDUCED_QUERIES.get() }
#[must_use]
pub struct ForcedImplGuard(bool);
impl ForcedImplGuard {
pub fn new() -> ForcedImplGuard {
ForcedImplGuard(FORCE_IMPL_FILENAME_LINE.replace(true))
}
}
#[doc = r" Force us to name impls with just the filename/line number. We"]
#[doc =
r" normally try to use types. But at some points, notably while printing"]
#[doc =
r" cycle errors, this can result in extra or suboptimal error output,"]
#[doc = r" so this variable disables that check."]
pub macro with_forced_impl_filename_line {
($e : expr) => { { let _guard = ForcedImplGuard :: new(); $e } }
}
impl Drop for ForcedImplGuard {
fn drop(&mut self) { FORCE_IMPL_FILENAME_LINE.set(self.0) }
}
pub fn with_forced_impl_filename_line() -> bool {
FORCE_IMPL_FILENAME_LINE.get()
}
#[must_use]
pub struct CrateNamePrefixGuard(bool);
impl CrateNamePrefixGuard {
pub fn new() -> CrateNamePrefixGuard {
CrateNamePrefixGuard(SHOULD_PREFIX_WITH_CRATE_NAME.replace(true))
}
}
#[doc = r" Adds the crate name prefix to paths where appropriate."]
#[doc =
r" Unlike `with_crate_prefix`, this unconditionally uses `tcx.crate_name` instead of sometimes"]
#[doc = r" using `crate::` for local items."]
#[doc = r""]
#[doc = r" Overrides `with_crate_prefix`."]
pub macro with_resolve_crate_name {
($e : expr) => { { let _guard = CrateNamePrefixGuard :: new(); $e } }
}
impl Drop for CrateNamePrefixGuard {
fn drop(&mut self) { SHOULD_PREFIX_WITH_CRATE_NAME.set(self.0) }
}
pub fn with_resolve_crate_name() -> bool {
SHOULD_PREFIX_WITH_CRATE_NAME.get()
}
#[must_use]
pub struct CratePrefixGuard(bool);
impl CratePrefixGuard {
pub fn new() -> CratePrefixGuard {
CratePrefixGuard(SHOULD_PREFIX_WITH_CRATE.replace(true))
}
}
#[doc = r" Adds the `crate::` prefix to paths where appropriate."]
#[doc = r""]
#[doc = r" Ignored if `with_resolve_crate_name` is active."]
pub macro with_crate_prefix {
($e : expr) => { { let _guard = CratePrefixGuard :: new(); $e } }
}
impl Drop for CratePrefixGuard {
fn drop(&mut self) { SHOULD_PREFIX_WITH_CRATE.set(self.0) }
}
pub fn with_crate_prefix() -> bool { SHOULD_PREFIX_WITH_CRATE.get() }
#[must_use]
pub struct NoTrimmedGuard(bool);
impl NoTrimmedGuard {
pub fn new() -> NoTrimmedGuard {
NoTrimmedGuard(NO_TRIMMED_PATH.replace(true))
}
}
#[doc =
r" Prevent path trimming if it is turned on. Path trimming affects `Display` impl"]
#[doc =
r" of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,"]
#[doc = r" if no other `Vec` is found."]
pub macro with_no_trimmed_paths {
($e : expr) => { { let _guard = NoTrimmedGuard :: new(); $e } }
}
impl Drop for NoTrimmedGuard {
fn drop(&mut self) { NO_TRIMMED_PATH.set(self.0) }
}
pub fn with_no_trimmed_paths() -> bool { NO_TRIMMED_PATH.get() }
#[must_use]
pub struct ForceTrimmedGuard(bool);
impl ForceTrimmedGuard {
pub fn new() -> ForceTrimmedGuard {
ForceTrimmedGuard(FORCE_TRIMMED_PATH.replace(true))
}
}
pub macro with_forced_trimmed_paths {
($e : expr) => { { let _guard = ForceTrimmedGuard :: new(); $e } }
}
impl Drop for ForceTrimmedGuard {
fn drop(&mut self) { FORCE_TRIMMED_PATH.set(self.0) }
}
pub fn with_forced_trimmed_paths() -> bool { FORCE_TRIMMED_PATH.get() }
#[must_use]
pub struct NoVisibleGuard(bool);
impl NoVisibleGuard {
pub fn new() -> NoVisibleGuard {
NoVisibleGuard(NO_VISIBLE_PATH.replace(true))
}
}
#[doc =
r" Prevent selection of visible paths. `Display` impl of DefId will prefer"]
#[doc = r" visible (public) reexports of types as paths."]
pub macro with_no_visible_paths {
($e : expr) => { { let _guard = NoVisibleGuard :: new(); $e } }
}
impl Drop for NoVisibleGuard {
fn drop(&mut self) { NO_VISIBLE_PATH.set(self.0) }
}
pub fn with_no_visible_paths() -> bool { NO_VISIBLE_PATH.get() }
#[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]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for WrapBinderMode {
}
#[automatically_derived]impl ::core::clone::Clone for WrapBinderMode {
#[inline]
fn clone(&self) -> Self { *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::marker::StructuralPartialEq for
WrapBinderMode {
}
#[automatically_derived]impl ::core::cmp::PartialEq for WrapBinderMode {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for WrapBinderMode { }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]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for RegionHighlightMode<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for
RegionHighlightMode<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _:
::core::clone::AssertParamIsClone<[Option<(ty::Region<'tcx>,
usize)>; 3]>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _:
::core::clone::AssertParamIsClone<Option<(ty::BoundRegionKind<'tcx>,
usize)>>;
*self
}
}Clone, #[automatically_derived]impl<'tcx> ::core::default::Default for
RegionHighlightMode<'tcx> {
#[inline]
fn default() -> Self {
RegionHighlightMode {
highlight_regions: ::core::default::Default::default(),
keep_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 pub keep_regions: bool,
196
197 highlight_bound_region: Option<(ty::BoundRegionKind<'tcx>, usize)>,
205}
206
207impl<'tcx> RegionHighlightMode<'tcx> {
208 pub fn maybe_highlighting_region(
211 &mut self,
212 region: Option<ty::Region<'tcx>>,
213 number: Option<usize>,
214 ) {
215 self.keep_regions = true;
216 if let Some(k) = region
217 && let Some(n) = number
218 {
219 self.highlighting_region(k, n);
220 }
221 }
222
223 pub fn highlighting_region(&mut self, region: ty::Region<'tcx>, number: usize) {
225 let num_slots = self.highlight_regions.len();
226 let first_avail_slot =
227 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
228 ::rustc_span::macros::bug_impl(None,
format_args!("can only highlight {0} placeholders at a time", num_slots),
Location::caller())bug!("can only highlight {} placeholders at a time", num_slots,)
229 });
230 *first_avail_slot = Some((region, number));
231 self.keep_regions = true;
232 }
233
234 pub fn highlighting_region_vid(
236 &mut self,
237 tcx: TyCtxt<'tcx>,
238 vid: ty::RegionVid,
239 number: usize,
240 ) {
241 self.highlighting_region(ty::Region::new_var(tcx, vid), number)
242 }
243
244 fn region_highlighted(&self, region: ty::Region<'tcx>) -> Option<usize> {
246 self.highlight_regions.iter().find_map(|h| match h {
247 Some((r, n)) if *r == region => Some(*n),
248 _ => None,
249 })
250 }
251
252 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind<'tcx>, number: usize) {
256 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());
257 self.highlight_bound_region = Some((br, number));
258 }
259}
260
261pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
263 fn pretty_print_value_path(
265 &mut self,
266 def_id: DefId,
267 args: ty::GenericArgs<'tcx>,
268 ) -> Result<(), PrintError> {
269 self.print_def_path(def_id, args)
270 }
271
272 fn pretty_print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError>
273 where
274 T: Print<Self> + TypeFoldable<TyCtxt<'tcx>>,
275 {
276 value.as_ref().skip_binder().print(self)
277 }
278
279 fn wrap_binder<T, F: FnOnce(&T, &mut Self) -> Result<(), fmt::Error>>(
280 &mut self,
281 value: &ty::Binder<'tcx, T>,
282 _mode: WrapBinderMode,
283 f: F,
284 ) -> Result<(), PrintError>
285 where
286 T: TypeFoldable<TyCtxt<'tcx>>,
287 {
288 f(value.as_ref().skip_binder(), self)
289 }
290
291 fn comma_sep<T>(&mut self, mut elems: impl Iterator<Item = T>) -> Result<(), PrintError>
294 where
295 T: Print<Self>,
296 {
297 if let Some(first) = elems.next() {
298 first.print(self)?;
299 for elem in elems {
300 if self.comma_sep_has_space() {
301 self.write_str(", ")?;
302 } else {
303 self.write_str(",")?;
304 }
305 elem.print(self)?;
306 }
307 }
308 Ok(())
309 }
310
311 fn comma_sep_has_space(&self) -> bool {
312 true
313 }
314
315 fn typed_value(
317 &mut self,
318 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
319 t: impl FnOnce(&mut Self) -> Result<(), PrintError>,
320 conversion: &str,
321 ) -> Result<(), PrintError> {
322 self.write_str("{")?;
323 f(self)?;
324 self.write_str(conversion)?;
325 t(self)?;
326 self.write_str("}")?;
327 Ok(())
328 }
329
330 fn parenthesized(
332 &mut self,
333 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
334 ) -> Result<(), PrintError> {
335 self.write_str("(")?;
336 f(self)?;
337 self.write_str(")")?;
338 Ok(())
339 }
340
341 fn maybe_parenthesized(
343 &mut self,
344 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
345 parenthesized: bool,
346 ) -> Result<(), PrintError> {
347 if parenthesized {
348 self.parenthesized(f)?;
349 } else {
350 f(self)?;
351 }
352 Ok(())
353 }
354
355 fn generic_delimiters(
357 &mut self,
358 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
359 ) -> Result<(), PrintError>;
360
361 fn should_truncate(&mut self) -> bool {
362 false
363 }
364
365 fn should_print_optional_region(&self, region: ty::Region<'tcx>) -> bool;
369
370 fn reset_type_limit(&mut self) {}
371
372 fn try_print_visible_def_path(&mut self, def_id: DefId) -> Result<bool, PrintError> {
378 if with_no_visible_paths() {
379 return Ok(false);
380 }
381
382 let mut callers = Vec::new();
383 self.try_print_visible_def_path_recur(def_id, &mut callers)
384 }
385
386 fn force_print_trimmed_def_path(&mut self, def_id: DefId) -> Result<bool, PrintError> {
392 let key = self.tcx().def_key(def_id);
393 let visible_parent_map = self.tcx().visible_parent_map(());
394 let kind = self.tcx().def_kind(def_id);
395
396 let get_local_name = |this: &Self, name, def_id, key: DefKey| {
397 if let Some(visible_parent) = visible_parent_map.get(&def_id)
398 && let actual_parent = this.tcx().opt_parent(def_id)
399 && let DefPathData::TypeNs(_) = key.disambiguated_data.data
400 && Some(*visible_parent) != actual_parent
401 {
402 this.tcx()
403 .module_children(ModId::new_unchecked(*visible_parent))
404 .iter()
405 .filter(|child| child.res.opt_def_id() == Some(def_id))
406 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
407 .map(|child| child.ident.name)
408 .unwrap_or(name)
409 } else {
410 name
411 }
412 };
413 if let DefKind::Variant = kind
414 && let Some(symbol) = self.tcx().trimmed_def_paths(()).get(&def_id)
415 {
416 self.write_str(get_local_name(self, *symbol, def_id, key).as_str())?;
418 return Ok(true);
419 }
420 if let Some(symbol) = key.get_opt_name() {
421 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = kind
422 && let Some(parent) = self.tcx().opt_parent(def_id)
423 && let parent_key = self.tcx().def_key(parent)
424 && let Some(symbol) = parent_key.get_opt_name()
425 {
426 self.write_str(get_local_name(self, symbol, parent, parent_key).as_str())?;
428 self.write_str("::")?;
429 } else if let DefKind::Variant = kind
430 && let Some(parent) = self.tcx().opt_parent(def_id)
431 && let parent_key = self.tcx().def_key(parent)
432 && let Some(symbol) = parent_key.get_opt_name()
433 {
434 self.write_str(get_local_name(self, symbol, parent, parent_key).as_str())?;
439 self.write_str("::")?;
440 } else if let DefKind::Struct
441 | DefKind::Union
442 | DefKind::Enum
443 | DefKind::Trait
444 | DefKind::TyAlias
445 | DefKind::Fn
446 | DefKind::Const
447 | DefKind::Static { .. } = kind
448 {
449 } else {
450 return Ok(false);
452 }
453 self.write_str(get_local_name(self, symbol, def_id, key).as_str())?;
454 return Ok(true);
455 }
456 Ok(false)
457 }
458
459 fn try_print_trimmed_def_path(&mut self, def_id: DefId) -> Result<bool, PrintError> {
461 if with_forced_trimmed_paths() && self.force_print_trimmed_def_path(def_id)? {
462 return Ok(true);
463 }
464 if self.tcx().sess.opts.unstable_opts.trim_diagnostic_paths
465 && self.tcx().sess.opts.trimmed_def_paths
466 && !with_no_trimmed_paths()
467 && !with_crate_prefix()
468 && let Some(symbol) = self.tcx().trimmed_def_paths(()).get(&def_id)
469 {
470 self.write_fmt(format_args!("{0}", Ident::with_dummy_span(*symbol)))write!(self, "{}", Ident::with_dummy_span(*symbol))?;
471 Ok(true)
472 } else {
473 Ok(false)
474 }
475 }
476
477 fn try_print_visible_def_path_recur(
491 &mut self,
492 def_id: DefId,
493 callers: &mut Vec<DefId>,
494 ) -> Result<bool, PrintError> {
495 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs:495",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(495u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("try_print_visible_def_path: def_id={0:?}",
def_id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("try_print_visible_def_path: def_id={:?}", def_id);
496
497 if let Some(cnum) = def_id.as_crate_root() {
500 if cnum == LOCAL_CRATE {
501 self.print_crate_name(cnum)?;
502 return Ok(true);
503 }
504
505 match self.tcx().extern_crate(cnum) {
516 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
517 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
518 if span.is_dummy() {
525 self.print_crate_name(cnum)?;
526 return Ok(true);
527 }
528
529 {
let _guard = NoVisibleGuard::new();
self.print_def_path(def_id, ty::GenericArgs::empty())?
};with_no_visible_paths!(
535 self.print_def_path(def_id, ty::GenericArgs::empty())?
536 );
537
538 return Ok(true);
539 }
540 (ExternCrateSource::Path, LOCAL_CRATE) => {
541 self.print_crate_name(cnum)?;
542 return Ok(true);
543 }
544 _ => {}
545 },
546 None => {
547 self.print_crate_name(cnum)?;
548 return Ok(true);
549 }
550 }
551 }
552
553 if def_id.is_local() {
554 return Ok(false);
555 }
556
557 let visible_parent_map = self.tcx().visible_parent_map(());
558
559 let mut cur_def_key = self.tcx().def_key(def_id);
560 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs:560",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(560u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("try_print_visible_def_path: cur_def_key={0:?}",
cur_def_key) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
561
562 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
564 let parent = DefId {
565 krate: def_id.krate,
566 index: cur_def_key
567 .parent
568 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
569 };
570
571 cur_def_key = self.tcx().def_key(parent);
572 }
573
574 let Some(visible_parent) = visible_parent_map.get(&def_id).cloned() else {
575 return Ok(false);
576 };
577
578 if self.tcx().is_doc_hidden(visible_parent) && with_no_visible_paths_if_doc_hidden() {
579 return Ok(false);
580 }
581
582 let actual_parent = self.tcx().opt_parent(def_id);
583 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs:583",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(583u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("try_print_visible_def_path: visible_parent={0:?} actual_parent={1:?}",
visible_parent, actual_parent) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
584 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
585 visible_parent, actual_parent,
586 );
587
588 let mut data = cur_def_key.disambiguated_data.data;
589 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs:589",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(589u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
});
} else { ; }
};debug!(
590 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
591 data, visible_parent, actual_parent,
592 );
593
594 match data {
595 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
627 let reexport = self
630 .tcx()
631 .module_children(ModId::new_unchecked(visible_parent))
632 .iter()
633 .filter(|child| child.res.opt_def_id() == Some(def_id))
634 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
635 .map(|child| child.ident.name);
636
637 if let Some(new_name) = reexport {
638 *name = new_name;
639 } else {
640 return Ok(false);
642 }
643 }
644 DefPathData::CrateRoot => {
646 data = DefPathData::TypeNs(self.tcx().crate_name(def_id.krate));
647 }
648 _ => {}
649 }
650 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs:650",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(650u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("try_print_visible_def_path: data={0:?}",
data) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("try_print_visible_def_path: data={:?}", data);
651
652 if callers.contains(&visible_parent) {
653 return Ok(false);
654 }
655 callers.push(visible_parent);
656 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
661 false => return Ok(false),
662 true => {}
663 }
664 callers.pop();
665 self.print_path_with_simple(
666 |_| Ok(()),
667 &DisambiguatedDefPathData { data, disambiguator: 0 },
668 )?;
669 Ok(true)
670 }
671
672 fn pretty_print_path_with_qualified(
673 &mut self,
674 self_ty: Ty<'tcx>,
675 trait_ref: Option<ty::TraitRef<'tcx>>,
676 ) -> Result<(), PrintError> {
677 if trait_ref.is_none() {
678 match self_ty.kind() {
682 ty::Adt(..)
683 | ty::Foreign(_)
684 | ty::Bool
685 | ty::Char
686 | ty::Str
687 | ty::Int(_)
688 | ty::Uint(_)
689 | ty::Float(_) => {
690 return self_ty.print(self);
691 }
692
693 _ => {}
694 }
695 }
696
697 self.generic_delimiters(|p| {
698 self_ty.print(p)?;
699 if let Some(trait_ref) = trait_ref {
700 p.write_fmt(format_args!(" as "))write!(p, " as ")?;
701 trait_ref.print_only_trait_path().print(p)?;
702 }
703 Ok(())
704 })
705 }
706
707 fn pretty_print_path_with_impl(
708 &mut self,
709 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
710 self_ty: Ty<'tcx>,
711 trait_ref: Option<ty::TraitRef<'tcx>>,
712 ) -> Result<(), PrintError> {
713 print_prefix(self)?;
714
715 self.generic_delimiters(|p| {
716 p.write_fmt(format_args!("impl "))write!(p, "impl ")?;
717 if let Some(trait_ref) = trait_ref {
718 trait_ref.print_only_trait_path().print(p)?;
719 p.write_fmt(format_args!(" for "))write!(p, " for ")?;
720 }
721 self_ty.print(p)?;
722
723 Ok(())
724 })
725 }
726
727 fn pretty_print_closure_inner(
728 &mut self,
729 did: DefId,
730 args: ty::GenericArgs<'tcx>,
731 ) -> Result<(), PrintError> {
732 if self.should_truncate() {
733 self.write_fmt(format_args!("@..."))write!(self, "@...")
734 } else if self.tcx().sess.opts.unstable_opts.span_free_formats {
735 self.write_fmt(format_args!("@"))write!(self, "@")?;
736 self.print_def_path(did, args)
737 } else if let Some(did) = did.as_local() {
738 let span = self.tcx().def_span(did);
739 let loc = if with_forced_trimmed_paths() {
740 self.tcx()
741 .sess
742 .source_map()
743 .span_to_short_string(span, RemapPathScopeComponents::DIAGNOSTICS)
744 } else {
745 self.tcx().sess.source_map().span_to_diagnostic_string(span)
746 };
747 self.write_fmt(format_args!("@{0}", loc))write!(
748 self,
749 "@{}",
750 loc
754 )
755 } else {
756 self.write_fmt(format_args!("@"))write!(self, "@")?;
757 self.print_def_path(did, args)
758 }
759 }
760
761 fn pretty_print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
762 match *ty.kind() {
763 ty::Bool => self.write_fmt(format_args!("bool"))write!(self, "bool")?,
764 ty::Char => self.write_fmt(format_args!("char"))write!(self, "char")?,
765 ty::Int(t) => self.write_fmt(format_args!("{0}", t.name_str()))write!(self, "{}", t.name_str())?,
766 ty::Uint(t) => self.write_fmt(format_args!("{0}", t.name_str()))write!(self, "{}", t.name_str())?,
767 ty::Float(t) => self.write_fmt(format_args!("{0}", t.name_str()))write!(self, "{}", t.name_str())?,
768 ty::Pat(ty, pat) => {
769 self.write_fmt(format_args!("pattern_type!("))write!(self, "pattern_type!(")?;
770 ty.print(self)?;
771 self.write_fmt(format_args!(" is {0:?})", pat))write!(self, " is {pat:?})")?;
772 }
773 ty::RawPtr(ty, mutbl) => {
774 self.write_fmt(format_args!("*{0} ", mutbl.ptr_str()))write!(self, "*{} ", mutbl.ptr_str())?;
775 ty.print(self)?;
776 }
777 ty::Ref(r, ty, mutbl) => {
778 self.write_fmt(format_args!("&"))write!(self, "&")?;
779 if self.should_print_optional_region(r) {
780 r.print(self)?;
781 self.write_fmt(format_args!(" "))write!(self, " ")?;
782 }
783 ty::TypeAndMut { ty, mutbl }.print(self)?;
784 }
785 ty::Never => self.write_fmt(format_args!("!"))write!(self, "!")?,
786 ty::Tuple(tys) => {
787 self.write_fmt(format_args!("("))write!(self, "(")?;
788 self.comma_sep(tys.iter())?;
789 if tys.len() == 1 {
790 self.write_fmt(format_args!(","))write!(self, ",")?;
791 }
792 self.write_fmt(format_args!(")"))write!(self, ")")?;
793 }
794 ty::FnDef(def_id, args) => {
795 let args = args.no_bound_vars().unwrap();
796 if with_reduced_queries() {
797 self.print_def_path(def_id, args)?;
798 } else {
799 let mut sig =
800 self.tcx().fn_sig(def_id).instantiate(self.tcx(), args).skip_norm_wip();
801 if self.tcx().codegen_fn_attrs(def_id).safe_target_features {
802 self.write_fmt(format_args!("#[target_feature(..)] "))write!(self, "#[target_feature(..)] ")?;
803 sig = sig.map_bound(|mut sig| {
804 sig.fn_sig_kind = sig.fn_sig_kind.set_safety(hir::Safety::Safe);
805 sig
806 });
807 }
808 sig.print(self)?;
809 self.write_fmt(format_args!(" {{"))write!(self, " {{")?;
810 self.pretty_print_value_path(def_id, args)?;
811 self.write_fmt(format_args!("}}"))write!(self, "}}")?;
812 }
813 }
814 ty::FnPtr(ref sig_tys, hdr) => sig_tys.with(hdr).print(self)?,
815 ty::UnsafeBinder(ref bound_ty) => {
816 self.wrap_binder(bound_ty, WrapBinderMode::Unsafe, |ty, p| {
817 p.pretty_print_type(*ty)
818 })?;
819 }
820 ty::Infer(infer_ty) => {
821 if self.should_print_verbose() {
822 self.write_fmt(format_args!("{0:?}", ty.kind()))write!(self, "{:?}", ty.kind())?;
823 return Ok(());
824 }
825
826 if let ty::TyVar(ty_vid) = infer_ty {
827 if let Some(name) = self.ty_infer_name(ty_vid) {
828 self.write_fmt(format_args!("{0}", name))write!(self, "{name}")?;
829 } else {
830 self.write_fmt(format_args!("{0}", infer_ty))write!(self, "{infer_ty}")?;
831 }
832 } else {
833 self.write_fmt(format_args!("{0}", infer_ty))write!(self, "{infer_ty}")?;
834 }
835 }
836 ty::Error(_) => self.write_fmt(format_args!("{{type error}}"))write!(self, "{{type error}}")?,
837 ty::Param(ref param_ty) => param_ty.print(self)?,
838 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
839 ty::BoundTyKind::Anon => {
840 rustc_type_ir::debug_bound_var(self, debruijn, bound_ty.var)?
841 }
842 ty::BoundTyKind::Param(def_id) => match self.should_print_verbose() {
843 true => self.write_fmt(format_args!("{0:?}", ty.kind()))write!(self, "{:?}", ty.kind())?,
844 false => self.write_fmt(format_args!("{0}", self.tcx().item_name(def_id)))write!(self, "{}", self.tcx().item_name(def_id))?,
845 },
846 },
847 ty::Adt(def, args)
848 if let Some(FieldInfo { base, variant, name, .. }) =
849 def.field_representing_type_info(self.tcx(), args) =>
850 {
851 if let Some(variant) = variant {
852 self.write_fmt(format_args!("field_of!({0}, {1}.{2})", base, variant, name))write!(self, "field_of!({base}, {variant}.{name})")?;
853 } else {
854 self.write_fmt(format_args!("field_of!({0}, {1})", base, name))write!(self, "field_of!({base}, {name})")?;
855 }
856 }
857 ty::Adt(def, args) => self.print_def_path(def.did(), args)?,
858 ty::Dynamic(data, r) => {
859 let print_r = self.should_print_optional_region(r);
860 if print_r {
861 self.write_fmt(format_args!("("))write!(self, "(")?;
862 }
863 self.write_fmt(format_args!("dyn "))write!(self, "dyn ")?;
864 data.print(self)?;
865 if print_r {
866 self.write_fmt(format_args!(" + "))write!(self, " + ")?;
867 r.print(self)?;
868 self.write_fmt(format_args!(")"))write!(self, ")")?;
869 }
870 }
871 ty::Foreign(def_id) => self.print_def_path(def_id, ty::GenericArgs::empty())?,
872 ty::Alias(
873 _,
874 ref data @ ty::AliasTy {
875 kind: ty::Projection { .. } | ty::Inherent { .. } | ty::Free { .. },
876 ..
877 },
878 ) => data.print(self)?,
879 ty::Placeholder(placeholder) => placeholder.print(self)?,
880 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
881 if self.should_print_verbose() {
890 self.write_fmt(format_args!("Opaque({0:?}, {1})", def_id,
args.print_as_list()))write!(self, "Opaque({:?}, {})", def_id, args.print_as_list())?;
892 return Ok(());
893 }
894
895 let parent = self.tcx().parent(def_id);
896 match self.tcx().def_kind(parent) {
897 DefKind::TyAlias | DefKind::AssocTy => {
898 if let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id: d }, .. }) =
901 *self
902 .tcx()
903 .type_of(parent)
904 .instantiate_identity()
905 .skip_norm_wip()
906 .kind()
907 {
908 if d == def_id {
909 self.print_def_path(parent, args)?;
912 return Ok(());
913 }
914 }
915 self.print_def_path(def_id, args)?;
917 return Ok(());
918 }
919 _ => {
920 if with_reduced_queries() {
921 self.print_def_path(def_id, ty::GenericArgs::empty())?;
922 return Ok(());
923 } else {
924 return self.pretty_print_opaque_impl_type(def_id, args);
925 }
926 }
927 }
928 }
929 ty::Str => self.write_fmt(format_args!("str"))write!(self, "str")?,
930 ty::Coroutine(did, args) => {
931 self.write_fmt(format_args!("{{"))write!(self, "{{")?;
932 let coroutine_kind = self.tcx().coroutine_kind(did).unwrap();
933 let should_print_movability = self.should_print_verbose()
934 || #[allow(non_exhaustive_omitted_patterns)] match coroutine_kind {
hir::CoroutineKind::Coroutine(_) => true,
_ => false,
}matches!(coroutine_kind, hir::CoroutineKind::Coroutine(_));
935
936 if should_print_movability {
937 match coroutine_kind.movability() {
938 hir::Movability::Movable => {}
939 hir::Movability::Static => self.write_fmt(format_args!("static "))write!(self, "static ")?,
940 }
941 }
942
943 if !self.should_print_verbose() {
944 self.write_fmt(format_args!("{0}", coroutine_kind))write!(self, "{coroutine_kind}")?;
945 if coroutine_kind.is_fn_like() {
946 self.write_fmt(format_args!(" of "))write!(self, " of ")?;
953 let did_of_the_fn_item = self.tcx().parent(did);
954 self.print_def_path(did_of_the_fn_item, args)?;
955 self.write_fmt(format_args!("()"))write!(self, "()")?;
956 } else {
957 self.pretty_print_closure_inner(did, args)?;
958 }
959 } else {
960 self.print_def_path(did, args)?;
961 self.write_fmt(format_args!(" upvar_tys="))write!(self, " upvar_tys=")?;
962 args.as_coroutine().tupled_upvars_ty().print(self)?;
963 self.write_fmt(format_args!(" resume_ty="))write!(self, " resume_ty=")?;
964 args.as_coroutine().resume_ty().print(self)?;
965 self.write_fmt(format_args!(" yield_ty="))write!(self, " yield_ty=")?;
966 args.as_coroutine().yield_ty().print(self)?;
967 self.write_fmt(format_args!(" return_ty="))write!(self, " return_ty=")?;
968 args.as_coroutine().return_ty().print(self)?;
969 }
970
971 self.write_fmt(format_args!("}}"))write!(self, "}}")?
972 }
973 ty::CoroutineWitness(did, args) => {
974 self.write_fmt(format_args!("{{"))write!(self, "{{")?;
975 if !self.should_print_verbose() {
976 self.write_fmt(format_args!("coroutine witness"))write!(self, "coroutine witness")?;
977 self.pretty_print_closure_inner(did, args)?;
978 } else {
979 self.print_def_path(did, args)?;
980 }
981 self.write_fmt(format_args!("}}"))write!(self, "}}")?
982 }
983 ty::Closure(did, args) => {
984 self.write_fmt(format_args!("{{"))write!(self, "{{")?;
985 if !self.should_print_verbose() {
986 self.write_fmt(format_args!("closure"))write!(self, "closure")?;
987 self.pretty_print_closure_inner(did, args)?;
988 } else {
989 self.print_def_path(did, args)?;
990 self.write_fmt(format_args!(" closure_kind_ty="))write!(self, " closure_kind_ty=")?;
991 args.as_closure().kind_ty().print(self)?;
992 self.write_fmt(format_args!(" closure_sig_as_fn_ptr_ty="))write!(self, " closure_sig_as_fn_ptr_ty=")?;
993 args.as_closure().sig_as_fn_ptr_ty().print(self)?;
994 self.write_fmt(format_args!(" upvar_tys="))write!(self, " upvar_tys=")?;
995 args.as_closure().tupled_upvars_ty().print(self)?;
996 }
997 self.write_fmt(format_args!("}}"))write!(self, "}}")?;
998 }
999 ty::CoroutineClosure(did, args) => {
1000 self.write_fmt(format_args!("{{"))write!(self, "{{")?;
1001 if !self.should_print_verbose() {
1002 match self.tcx().coroutine_kind(self.tcx().coroutine_for_closure(did)).unwrap()
1003 {
1004 hir::CoroutineKind::Desugared(
1005 desugaring,
1006 hir::CoroutineSource::Closure,
1007 ) => self.write_fmt(format_args!("{0}closure", desugaring))write!(self, "{desugaring}closure")?,
1008 _ => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("coroutine from coroutine-closure should have CoroutineSource::Closure")));
}unreachable!(
1009 "coroutine from coroutine-closure should have CoroutineSource::Closure"
1010 ),
1011 };
1012 self.pretty_print_closure_inner(did, args)?;
1013 } else {
1014 self.print_def_path(did, args)?;
1015 self.write_fmt(format_args!(" closure_kind_ty="))write!(self, " closure_kind_ty=")?;
1016 args.as_coroutine_closure().kind_ty().print(self)?;
1017 self.write_fmt(format_args!(" signature_parts_ty="))write!(self, " signature_parts_ty=")?;
1018 args.as_coroutine_closure().signature_parts_ty().print(self)?;
1019 self.write_fmt(format_args!(" upvar_tys="))write!(self, " upvar_tys=")?;
1020 args.as_coroutine_closure().tupled_upvars_ty().print(self)?;
1021 self.write_fmt(format_args!(" coroutine_captures_by_ref_ty="))write!(self, " coroutine_captures_by_ref_ty=")?;
1022 args.as_coroutine_closure().coroutine_captures_by_ref_ty().print(self)?;
1023 }
1024 self.write_fmt(format_args!("}}"))write!(self, "}}")?;
1025 }
1026 ty::Array(ty, sz) => {
1027 self.write_fmt(format_args!("["))write!(self, "[")?;
1028 ty.print(self)?;
1029 self.write_fmt(format_args!("; "))write!(self, "; ")?;
1030 sz.print(self)?;
1031 self.write_fmt(format_args!("]"))write!(self, "]")?;
1032 }
1033 ty::Slice(ty) => {
1034 self.write_fmt(format_args!("["))write!(self, "[")?;
1035 ty.print(self)?;
1036 self.write_fmt(format_args!("]"))write!(self, "]")?;
1037 }
1038 }
1039
1040 Ok(())
1041 }
1042
1043 fn pretty_print_opaque_impl_type(
1044 &mut self,
1045 def_id: DefId,
1046 args: ty::GenericArgs<'tcx>,
1047 ) -> Result<(), PrintError> {
1048 let tcx = self.tcx();
1049
1050 let bounds = tcx.explicit_item_bounds(def_id);
1053
1054 let mut traits = FxIndexMap::default();
1055 let mut fn_traits = FxIndexMap::default();
1056 let mut lifetimes = SmallVec::<[ty::Region<'tcx>; 1]>::new();
1057
1058 let mut has_sized_bound = false;
1059 let mut has_negative_sized_bound = false;
1060 let mut has_meta_sized_bound = false;
1061
1062 for (predicate, _) in
1063 bounds.iter_instantiated_copied(tcx, args).map(Unnormalized::skip_norm_wip)
1064 {
1065 let bound_predicate = predicate.kind();
1066
1067 match bound_predicate.skip_binder() {
1068 ty::ClauseKind::Trait(pred) => {
1069 match tcx.as_lang_item(pred.def_id()) {
1072 Some(LangItem::Sized) => match pred.polarity {
1073 ty::ClausePolarity::Positive => {
1074 has_sized_bound = true;
1075 continue;
1076 }
1077 ty::ClausePolarity::Negative => has_negative_sized_bound = true,
1078 },
1079 Some(LangItem::MetaSized) => {
1080 has_meta_sized_bound = true;
1081 continue;
1082 }
1083 Some(LangItem::PointeeSized) => {
1084 ::rustc_span::macros::bug_impl(None,
format_args!("`PointeeSized` is removed during lowering"),
Location::caller());bug!("`PointeeSized` is removed during lowering");
1085 }
1086 _ => (),
1087 }
1088
1089 self.insert_trait_and_projection(
1090 bound_predicate.rebind(pred),
1091 None,
1092 &mut traits,
1093 &mut fn_traits,
1094 );
1095 }
1096 ty::ClauseKind::Projection(pred) => {
1097 let proj = bound_predicate.rebind(pred);
1098 let trait_ref = proj.map_bound(|proj| TraitClause {
1099 trait_ref: proj.projection_term.trait_ref(tcx),
1100 polarity: ty::ClausePolarity::Positive,
1101 });
1102
1103 self.insert_trait_and_projection(
1104 trait_ref,
1105 Some((proj.item_def_id(), proj.term())),
1106 &mut traits,
1107 &mut fn_traits,
1108 );
1109 }
1110 ty::ClauseKind::TypeOutlives(outlives) => {
1111 lifetimes.push(outlives.1);
1112 }
1113 _ => {}
1114 }
1115 }
1116
1117 self.write_fmt(format_args!("impl "))write!(self, "impl ")?;
1118
1119 let mut first = true;
1120 let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !has_sized_bound;
1122
1123 for ((bound_args_and_self_ty, is_async), entry) in fn_traits {
1124 self.write_fmt(format_args!("{0}", if first { "" } else { " + " }))write!(self, "{}", if first { "" } else { " + " })?;
1125 self.write_fmt(format_args!("{0}", if paren_needed { "(" } else { "" }))write!(self, "{}", if paren_needed { "(" } else { "" })?;
1126
1127 let trait_def_id = if is_async {
1128 tcx.async_fn_trait_kind_to_def_id(entry.kind).expect("expected AsyncFn lang items")
1129 } else {
1130 tcx.fn_trait_kind_to_def_id(entry.kind).expect("expected Fn lang items")
1131 };
1132
1133 if let Some(return_ty) = entry.return_ty {
1134 self.wrap_binder(
1135 &bound_args_and_self_ty,
1136 WrapBinderMode::ForAll,
1137 |(args, _), p| {
1138 p.write_fmt(format_args!("{0}", tcx.item_name(trait_def_id)))write!(p, "{}", tcx.item_name(trait_def_id))?;
1139 p.write_fmt(format_args!("("))write!(p, "(")?;
1140
1141 for (idx, ty) in args.iter().enumerate() {
1142 if idx > 0 {
1143 p.write_fmt(format_args!(", "))write!(p, ", ")?;
1144 }
1145 ty.print(p)?;
1146 }
1147
1148 p.write_fmt(format_args!(")"))write!(p, ")")?;
1149 if let Some(ty) = return_ty.skip_binder().as_type() {
1150 if !ty.is_unit() {
1151 p.write_fmt(format_args!(" -> "))write!(p, " -> ")?;
1152 return_ty.print(p)?;
1153 }
1154 }
1155 p.write_fmt(format_args!("{0}", if paren_needed { ")" } else { "" }))write!(p, "{}", if paren_needed { ")" } else { "" })?;
1156
1157 first = false;
1158 Ok(())
1159 },
1160 )?;
1161 } else {
1162 traits.insert(
1164 bound_args_and_self_ty.map_bound(|(args, self_ty)| ty::TraitClause {
1165 polarity: ty::ClausePolarity::Positive,
1166 trait_ref: ty::TraitRef::new(
1167 tcx,
1168 trait_def_id,
1169 [self_ty, Ty::new_tup(tcx, args)],
1170 ),
1171 }),
1172 FxIndexMap::default(),
1173 );
1174 }
1175 }
1176
1177 for (trait_pred, assoc_items) in traits {
1179 self.write_fmt(format_args!("{0}", if first { "" } else { " + " }))write!(self, "{}", if first { "" } else { " + " })?;
1180
1181 self.wrap_binder(&trait_pred, WrapBinderMode::ForAll, |trait_pred, p| {
1182 if trait_pred.polarity == ty::ClausePolarity::Negative {
1183 p.write_fmt(format_args!("!"))write!(p, "!")?;
1184 }
1185 trait_pred.trait_ref.print_only_trait_name().print(p)?;
1186
1187 let generics = tcx.generics_of(trait_pred.def_id());
1188 let own_args =
1189 generics.own_args_no_defaults(tcx, trait_pred.trait_ref.args.as_slice());
1190
1191 if !own_args.is_empty() || !assoc_items.is_empty() {
1192 let mut first = true;
1193
1194 for ty in own_args {
1195 if first {
1196 p.write_fmt(format_args!("<"))write!(p, "<")?;
1197 first = false;
1198 } else {
1199 p.write_fmt(format_args!(", "))write!(p, ", ")?;
1200 }
1201 ty.print(p)?;
1202 }
1203
1204 for (assoc_item_def_id, term) in assoc_items {
1205 if first {
1206 p.write_fmt(format_args!("<"))write!(p, "<")?;
1207 first = false;
1208 } else {
1209 p.write_fmt(format_args!(", "))write!(p, ", ")?;
1210 }
1211
1212 p.write_fmt(format_args!("{0} = ",
tcx.associated_item(assoc_item_def_id).name()))write!(p, "{} = ", tcx.associated_item(assoc_item_def_id).name())?;
1213
1214 match term.skip_binder().kind() {
1215 TermKind::Ty(ty) => ty.print(p)?,
1216 TermKind::Const(c) => c.print(p)?,
1217 };
1218 }
1219
1220 if !first {
1221 p.write_fmt(format_args!(">"))write!(p, ">")?;
1222 }
1223 }
1224
1225 first = false;
1226 Ok(())
1227 })?;
1228 }
1229
1230 let using_sized_hierarchy = self.tcx().features().sized_hierarchy();
1231 let add_sized = has_sized_bound && (first || has_negative_sized_bound);
1232 let add_maybe_sized =
1233 has_meta_sized_bound && !has_negative_sized_bound && !using_sized_hierarchy;
1234 let has_pointee_sized_bound =
1236 !has_sized_bound && !has_meta_sized_bound && !has_negative_sized_bound;
1237 if add_sized || add_maybe_sized {
1238 if !first {
1239 self.write_fmt(format_args!(" + "))write!(self, " + ")?;
1240 }
1241 if add_maybe_sized {
1242 self.write_fmt(format_args!("?"))write!(self, "?")?;
1243 }
1244 self.write_fmt(format_args!("Sized"))write!(self, "Sized")?;
1245 } else if has_meta_sized_bound && using_sized_hierarchy {
1246 if !first {
1247 self.write_fmt(format_args!(" + "))write!(self, " + ")?;
1248 }
1249 self.write_fmt(format_args!("MetaSized"))write!(self, "MetaSized")?;
1250 } else if has_pointee_sized_bound && using_sized_hierarchy {
1251 if !first {
1252 self.write_fmt(format_args!(" + "))write!(self, " + ")?;
1253 }
1254 self.write_fmt(format_args!("PointeeSized"))write!(self, "PointeeSized")?;
1255 }
1256
1257 if !with_forced_trimmed_paths() {
1258 for re in lifetimes {
1259 self.write_fmt(format_args!(" + "))write!(self, " + ")?;
1260 self.print_region(re)?;
1261 }
1262 }
1263
1264 Ok(())
1265 }
1266
1267 fn insert_trait_and_projection(
1270 &mut self,
1271 trait_pred: ty::PolyTraitClause<'tcx>,
1272 proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
1273 traits: &mut FxIndexMap<
1274 ty::PolyTraitClause<'tcx>,
1275 FxIndexMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,
1276 >,
1277 fn_traits: &mut FxIndexMap<
1278 (ty::Binder<'tcx, (&'tcx ty::List<Ty<'tcx>>, Ty<'tcx>)>, bool),
1279 OpaqueFnEntry<'tcx>,
1280 >,
1281 ) {
1282 let tcx = self.tcx();
1283 let trait_def_id = trait_pred.def_id();
1284
1285 let fn_trait_and_async = if let Some(kind) = tcx.fn_trait_kind_from_def_id(trait_def_id) {
1286 Some((kind, false))
1287 } else if let Some(kind) = tcx.async_fn_trait_kind_from_def_id(trait_def_id) {
1288 Some((kind, true))
1289 } else {
1290 None
1291 };
1292
1293 if trait_pred.polarity() == ty::ClausePolarity::Positive
1294 && let Some((kind, is_async)) = fn_trait_and_async
1295 && let ty::Tuple(types) = *trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
1296 {
1297 let entry = fn_traits
1298 .entry((trait_pred.rebind((types, trait_pred.skip_binder().self_ty())), is_async))
1299 .or_insert_with(|| OpaqueFnEntry { kind, return_ty: None });
1300 if kind.extends(entry.kind) {
1301 entry.kind = kind;
1302 }
1303 if let Some((proj_def_id, proj_ty)) = proj_ty
1304 && tcx.item_name(proj_def_id) == sym::Output
1305 {
1306 entry.return_ty = Some(proj_ty);
1307 }
1308 return;
1309 }
1310
1311 traits.entry(trait_pred).or_default().extend(proj_ty);
1313 }
1314
1315 fn pretty_print_inherent_projection(
1316 &mut self,
1317 alias_term: ty::AliasTerm<'tcx>,
1318 ) -> Result<(), PrintError> {
1319 let alias_def_id = alias_term.expect_inherent_def_id();
1320 let def_key = self.tcx().def_key(alias_def_id);
1321 self.print_path_with_generic_args(
1322 |p| {
1323 p.print_path_with_simple(
1324 |p| p.print_path_with_qualified(alias_term.self_ty(), None),
1325 &def_key.disambiguated_data,
1326 )
1327 },
1328 self.tcx().mk_args(&alias_term.args.as_slice()[1..]),
1329 )
1330 }
1331
1332 fn pretty_print_rpitit(
1333 &mut self,
1334 def_id: DefId,
1335 args: ty::GenericArgs<'tcx>,
1336 ) -> Result<(), PrintError> {
1337 let fn_args = if self.tcx().features().return_type_notation()
1338 && let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, .. }) =
1339 self.tcx().opt_rpitit_info(def_id)
1340 && let ty::Alias(_, alias_ty) =
1341 self.tcx().fn_sig(fn_def_id).skip_binder().output().skip_binder().kind()
1342 && let Some(projection_ty) = alias_ty.try_to_projection()
1343 && projection_ty.kind == def_id
1344 && let generics = self.tcx().generics_of(fn_def_id)
1345 && generics
1347 .own_params
1348 .iter()
1349 .all(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
ty::GenericParamDefKind::Lifetime => true,
_ => false,
}matches!(param.kind, ty::GenericParamDefKind::Lifetime))
1350 {
1351 let num_args = generics.count();
1352 Some((fn_def_id, self.tcx().mk_args(&args.as_slice()[..num_args])))
1353 } else {
1354 None
1355 };
1356
1357 match (fn_args, RTN_MODE.with(|c| c.get())) {
1358 (Some((fn_def_id, fn_args)), RtnMode::ForDiagnostic) => {
1359 self.pretty_print_opaque_impl_type(def_id, args)?;
1360 self.write_fmt(format_args!(" {{ "))write!(self, " {{ ")?;
1361 self.print_def_path(fn_def_id, fn_args)?;
1362 self.write_fmt(format_args!("(..) }}"))write!(self, "(..) }}")?;
1363 }
1364 (Some((fn_def_id, fn_args)), RtnMode::ForSuggestion) => {
1365 self.print_def_path(fn_def_id, fn_args)?;
1366 self.write_fmt(format_args!("(..)"))write!(self, "(..)")?;
1367 }
1368 _ => {
1369 self.pretty_print_opaque_impl_type(def_id, args)?;
1370 }
1371 }
1372
1373 Ok(())
1374 }
1375
1376 fn ty_infer_name(&self, _: ty::TyVid) -> Option<Symbol> {
1377 None
1378 }
1379
1380 fn const_infer_name(&self, _: ty::ConstVid) -> Option<Symbol> {
1381 None
1382 }
1383
1384 fn pretty_print_dyn_existential(
1385 &mut self,
1386 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1387 ) -> Result<(), PrintError> {
1388 let mut first = true;
1390
1391 if let Some(bound_principal) = predicates.principal() {
1392 self.wrap_binder(&bound_principal, WrapBinderMode::ForAll, |principal, p| {
1393 p.print_def_path(principal.def_id, ty::GenericArgs::empty())?;
1394
1395 let mut resugared = false;
1396
1397 let fn_trait_kind = p.tcx().fn_trait_kind_from_def_id(principal.def_id);
1399 if !p.should_print_verbose() && fn_trait_kind.is_some() {
1400 if let ty::Tuple(tys) = principal.args.type_at(0).kind() {
1401 let mut projections = predicates.projection_bounds();
1402 if let (Some(proj), None) = (projections.next(), projections.next()) {
1403 p.pretty_print_fn_sig(
1404 tys,
1405 false,
1406 None,
1408 proj.skip_binder().term.as_type().expect("Return type was a const"),
1409 )?;
1410 resugared = true;
1411 }
1412 }
1413 }
1414
1415 if !resugared {
1418 let principal_with_self =
1419 principal.with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self);
1420
1421 let args = p
1422 .tcx()
1423 .generics_of(principal_with_self.def_id)
1424 .own_args_no_defaults(p.tcx(), principal_with_self.args.as_slice());
1425
1426 let bound_principal_with_self = bound_principal
1427 .with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self);
1428
1429 let clause: ty::Clause<'tcx> = bound_principal_with_self.upcast(p.tcx());
1430 let super_projections: Vec<_> = elaborate::elaborate(p.tcx(), [clause])
1431 .filter_only_self()
1432 .filter_map(|clause| clause.as_projection_clause())
1433 .collect();
1434
1435 let mut projections: Vec<_> = predicates
1436 .projection_bounds()
1437 .filter(|&proj| {
1438 let proj_is_implied = super_projections.iter().any(|&super_proj| {
1440 let super_proj = super_proj.map_bound(|super_proj| {
1441 ty::ExistentialProjection::erase_self_ty(p.tcx(), super_proj)
1442 });
1443
1444 let proj = p.tcx().erase_and_anonymize_regions(proj);
1449 let super_proj = p.tcx().erase_and_anonymize_regions(super_proj);
1450
1451 proj == super_proj
1452 });
1453 !proj_is_implied
1454 })
1455 .map(|proj| {
1456 proj.skip_binder()
1459 })
1460 .collect();
1461
1462 projections
1463 .sort_by_cached_key(|proj| p.tcx().item_name(proj.def_id).to_string());
1464
1465 if !args.is_empty() || !projections.is_empty() {
1466 p.generic_delimiters(|p| {
1467 p.comma_sep(args.iter().copied())?;
1468 if !args.is_empty() && !projections.is_empty() {
1469 p.write_fmt(format_args!(", "))write!(p, ", ")?;
1470 }
1471 p.comma_sep(projections.iter().copied())
1472 })?;
1473 }
1474 }
1475 Ok(())
1476 })?;
1477
1478 first = false;
1479 }
1480
1481 let mut auto_traits: Vec<_> = predicates.auto_traits().collect();
1485
1486 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)));
1494
1495 for def_id in auto_traits {
1496 if !first {
1497 self.write_fmt(format_args!(" + "))write!(self, " + ")?;
1498 }
1499 first = false;
1500
1501 self.print_def_path(def_id, ty::GenericArgs::empty())?;
1502 }
1503
1504 Ok(())
1505 }
1506
1507 fn pretty_print_fn_sig(
1508 &mut self,
1509 inputs: &[Ty<'tcx>],
1510 c_variadic: bool,
1511 splatted: Option<u8>,
1512 output: Ty<'tcx>,
1513 ) -> Result<(), PrintError> {
1514 self.write_fmt(format_args!("("))write!(self, "(")?;
1515 let splatted_arg_index = splatted.map(usize::from);
1516 let mut input_iter = inputs.iter().copied();
1517 if let Some(index) = splatted_arg_index {
1518 self.comma_sep((&mut input_iter).take(index))?;
1519 if index > 0 {
1523 if self.comma_sep_has_space() {
1524 self.write_fmt(format_args!(", "))write!(self, ", ")?;
1525 } else {
1526 self.write_fmt(format_args!(","))write!(self, ",")?;
1527 }
1528 }
1529 self.write_fmt(format_args!("#[rustc_splat] "))write!(self, "#[rustc_splat] ")?;
1530 self.comma_sep(input_iter)?;
1531 } else {
1532 self.comma_sep(input_iter)?;
1533 }
1534 if c_variadic {
1535 if !inputs.is_empty() {
1536 self.write_fmt(format_args!(", "))write!(self, ", ")?;
1539 }
1540 self.write_fmt(format_args!("..."))write!(self, "...")?;
1541 }
1542 self.write_fmt(format_args!(")"))write!(self, ")")?;
1543 if !output.is_unit() {
1544 self.write_fmt(format_args!(" -> "))write!(self, " -> ")?;
1545 output.print(self)?;
1546 }
1547
1548 Ok(())
1549 }
1550
1551 fn pretty_print_const(
1552 &mut self,
1553 ct: ty::Const<'tcx>,
1554 print_ty: bool,
1555 ) -> Result<(), PrintError> {
1556 if self.should_print_verbose() {
1557 self.write_fmt(format_args!("{0:?}", ct))write!(self, "{ct:?}")?;
1558 return Ok(());
1559 }
1560
1561 match ct.kind() {
1562 ty::ConstKind::Alias(_, ty::AliasConst { kind, args, .. }) => {
1563 match kind {
1564 ty::AliasConstKind::Projection { def_id }
1565 | ty::AliasConstKind::InherentSelf { def_id }
1566 | ty::AliasConstKind::InherentImpl { def_id }
1567 | ty::AliasConstKind::Free { def_id } => {
1568 self.pretty_print_value_path(def_id, args)?;
1569 }
1570 ty::AliasConstKind::Anon { def_id } => {
1571 if def_id.is_local()
1572 && let span = self.tcx().def_span(def_id)
1573 && let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
1574 {
1575 self.write_fmt(format_args!("{0}", snip))write!(self, "{snip}")?;
1576 } else {
1577 self.write_fmt(format_args!("{0}::{1}", self.tcx().crate_name(def_id.krate),
self.tcx().def_path(def_id).to_string_no_crate_verbose()))write!(
1585 self,
1586 "{}::{}",
1587 self.tcx().crate_name(def_id.krate),
1588 self.tcx().def_path(def_id).to_string_no_crate_verbose()
1589 )?;
1590 }
1591 }
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.into_iter())?;
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 ::rustc_span::macros::bug_impl(None,
format_args!("expected to convert valtree {0:?} to raw bytes for type {1:?}",
cv.valtree, t), Location::caller())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 ::rustc_span::macros::bug_impl(None,
format_args!("expected to convert valtree to raw bytes for type {0:?}",
cv.ty), Location::caller())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::unreachable_default_msg()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, ", ")?;
1997 }
1998 self.write_fmt(format_args!("{0}: ", field_def.name))write!(self, "{}: ", field_def.name)?;
1999 field.print(self)?;
2000 first = false;
2001 }
2002 self.write_fmt(format_args!(" }}"))write!(self, " }}")?;
2003 }
2004 }
2005 }
2006 return Ok(());
2007 }
2008 (ty::ValTreeKind::Leaf(leaf), ty::Ref(_, inner_ty, _)) => {
2009 self.write_fmt(format_args!("&"))write!(self, "&")?;
2010 return self.pretty_print_const_scalar_int(*leaf, inner_ty, print_ty);
2011 }
2012 (ty::ValTreeKind::Leaf(leaf), _) => {
2013 return self.pretty_print_const_scalar_int(*leaf, cv.ty, print_ty);
2014 }
2015 (_, ty::FnDef(def_id, args)) => {
2016 self.pretty_print_value_path(def_id, args.no_bound_vars().unwrap())?;
2019 return Ok(());
2020 }
2021 _ => {}
2024 }
2025
2026 if cv.valtree.is_zst() {
2028 self.write_fmt(format_args!("<ZST>"))write!(self, "<ZST>")?;
2029 } else {
2030 self.write_fmt(format_args!("{0:?}", cv.valtree))write!(self, "{:?}", cv.valtree)?;
2031 }
2032 if print_ty {
2033 self.write_fmt(format_args!(": "))write!(self, ": ")?;
2034 cv.ty.print(self)?;
2035 }
2036 Ok(())
2037 }
2038
2039 fn pretty_print_closure_as_impl(
2040 &mut self,
2041 closure: ty::ClosureArgs<TyCtxt<'tcx>>,
2042 ) -> Result<(), PrintError> {
2043 let sig = closure.sig();
2044 let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn);
2045
2046 self.write_fmt(format_args!("impl "))write!(self, "impl ")?;
2047 self.wrap_binder(&sig, WrapBinderMode::ForAll, |sig, p| {
2048 p.write_fmt(format_args!("{0}(", kind))write!(p, "{kind}(")?;
2049 for (i, arg) in sig.inputs()[0].tuple_fields().iter().enumerate() {
2050 if i > 0 {
2051 p.write_fmt(format_args!(", "))write!(p, ", ")?;
2052 }
2053 arg.print(p)?;
2054 }
2055 p.write_fmt(format_args!(")"))write!(p, ")")?;
2056
2057 if !sig.output().is_unit() {
2058 p.write_fmt(format_args!(" -> "))write!(p, " -> ")?;
2059 sig.output().print(p)?;
2060 }
2061
2062 Ok(())
2063 })
2064 }
2065
2066 fn pretty_print_bound_constness(
2067 &mut self,
2068 constness: ty::BoundConstness,
2069 ) -> Result<(), PrintError> {
2070 match constness {
2071 ty::BoundConstness::Const => self.write_fmt(format_args!("const "))write!(self, "const ")?,
2072 ty::BoundConstness::Maybe => self.write_fmt(format_args!("[const] "))write!(self, "[const] ")?,
2073 }
2074 Ok(())
2075 }
2076
2077 fn should_print_verbose(&self) -> bool {
2078 self.tcx().sess.verbose_internals()
2079 }
2080}
2081
2082pub(crate) fn pretty_print_const<'tcx>(
2083 c: ty::Const<'tcx>,
2084 fmt: &mut fmt::Formatter<'_>,
2085 print_types: bool,
2086) -> fmt::Result {
2087 ty::tls::with(|tcx| {
2088 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
2089 p.print_alloc_ids = true;
2090 p.pretty_print_const(tcx.lift(c), print_types)?;
2091 fmt.write_str(&p.into_buffer())?;
2092 Ok(())
2093 })
2094}
2095
2096pub struct FmtPrinter<'a, 'tcx>(Box<FmtPrinterData<'a, 'tcx>>);
2098
2099pub struct FmtPrinterData<'a, 'tcx> {
2100 tcx: TyCtxt<'tcx>,
2101 fmt: String,
2102
2103 empty_path: bool,
2104 in_value: bool,
2105 pub print_alloc_ids: bool,
2106
2107 used_region_names: FxHashSet<Symbol>,
2109
2110 region_index: usize,
2111 binder_depth: usize,
2112 printed_type_count: usize,
2113 type_length_limit: Limit,
2114
2115 pub region_highlight_mode: RegionHighlightMode<'tcx>,
2116
2117 pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<Symbol> + 'a>>,
2118 pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid) -> Option<Symbol> + 'a>>,
2119}
2120
2121impl<'a, 'tcx> Deref for FmtPrinter<'a, 'tcx> {
2122 type Target = FmtPrinterData<'a, 'tcx>;
2123 fn deref(&self) -> &Self::Target {
2124 &self.0
2125 }
2126}
2127
2128impl DerefMut for FmtPrinter<'_, '_> {
2129 fn deref_mut(&mut self) -> &mut Self::Target {
2130 &mut self.0
2131 }
2132}
2133
2134impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
2135 pub fn new(tcx: TyCtxt<'tcx>, ns: Namespace) -> Self {
2136 let limit =
2137 if with_reduced_queries() { Limit::new(1048576) } else { tcx.type_length_limit() };
2138 Self::new_with_limit(tcx, ns, limit)
2139 }
2140
2141 pub fn print_string(
2142 tcx: TyCtxt<'tcx>,
2143 ns: Namespace,
2144 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2145 ) -> Result<String, PrintError> {
2146 let mut c = FmtPrinter::new(tcx, ns);
2147 f(&mut c)?;
2148 Ok(c.into_buffer())
2149 }
2150
2151 pub fn new_with_limit(tcx: TyCtxt<'tcx>, ns: Namespace, type_length_limit: Limit) -> Self {
2152 FmtPrinter(Box::new(FmtPrinterData {
2153 tcx,
2154 fmt: String::with_capacity(64),
2157 empty_path: false,
2158 in_value: ns == Namespace::ValueNS,
2159 print_alloc_ids: false,
2160 used_region_names: Default::default(),
2161 region_index: 0,
2162 binder_depth: 0,
2163 printed_type_count: 0,
2164 type_length_limit,
2165 region_highlight_mode: RegionHighlightMode::default(),
2166 ty_infer_name_resolver: None,
2167 const_infer_name_resolver: None,
2168 }))
2169 }
2170
2171 pub fn into_buffer(self) -> String {
2172 self.0.fmt
2173 }
2174}
2175
2176fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
2177 match tcx.def_key(def_id).disambiguated_data.data {
2178 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::OpaqueTy => {
2179 Namespace::TypeNS
2180 }
2181
2182 DefPathData::ValueNs(..)
2183 | DefPathData::AnonConst
2184 | DefPathData::Closure
2185 | DefPathData::Ctor => Namespace::ValueNS,
2186
2187 DefPathData::MacroNs(..) => Namespace::MacroNS,
2188
2189 _ => Namespace::TypeNS,
2190 }
2191}
2192
2193impl<'t> TyCtxt<'t> {
2194 pub fn def_path_str(self, def_id: impl IntoQueryKey<DefId>) -> String {
2197 let def_id = def_id.into_query_key();
2198 self.def_path_str_with_args(def_id, ty::GenericArgs::empty())
2199 }
2200
2201 pub fn def_path_str_with_args(
2203 self,
2204 def_id: impl IntoQueryKey<DefId>,
2205 args: ty::GenericArgs<'t>,
2206 ) -> String {
2207 let def_id = def_id.into_query_key();
2208 let ns = guess_def_namespace(self, def_id);
2209 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs:2209",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(2209u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("def_path_str: def_id={0:?}, ns={1:?}",
def_id, ns) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
2210
2211 FmtPrinter::print_string(self, ns, |p| p.print_def_path(def_id, args)).unwrap()
2212 }
2213
2214 pub fn value_path_str_with_args(
2216 self,
2217 def_id: impl IntoQueryKey<DefId>,
2218 args: ty::GenericArgs<'t>,
2219 ) -> String {
2220 let def_id = def_id.into_query_key();
2221 let ns = Namespace::ValueNS;
2222 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs:2222",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(2222u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("value_path_str: def_id={0:?}, ns={1:?}",
def_id, ns) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns);
2223
2224 FmtPrinter::print_string(self, ns, |p| p.print_def_path(def_id, args)).unwrap()
2225 }
2226}
2227
2228impl fmt::Write for FmtPrinter<'_, '_> {
2229 fn write_str(&mut self, s: &str) -> fmt::Result {
2230 self.fmt.push_str(s);
2231 Ok(())
2232 }
2233}
2234
2235impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
2236 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
2237 self.tcx
2238 }
2239
2240 fn reset_path(&mut self) -> Result<(), PrintError> {
2241 self.empty_path = true;
2242 Ok(())
2243 }
2244
2245 fn should_omit_parent_def_path(&self, parent_def_id: DefId) -> bool {
2246 RTN_MODE.with(|mode| mode.get()) == RtnMode::ForSuggestion
2247 && #[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!(
2248 self.tcx().def_key(parent_def_id).disambiguated_data.data,
2249 DefPathData::ValueNs(..) | DefPathData::Closure | DefPathData::AnonConst
2250 )
2251 }
2252
2253 fn print_def_path(
2254 &mut self,
2255 def_id: DefId,
2256 args: ty::GenericArgs<'tcx>,
2257 ) -> Result<(), PrintError> {
2258 if args.is_empty() {
2259 match self.try_print_trimmed_def_path(def_id)? {
2260 true => return Ok(()),
2261 false => {}
2262 }
2263
2264 match self.try_print_visible_def_path(def_id)? {
2265 true => return Ok(()),
2266 false => {}
2267 }
2268 }
2269
2270 let key = self.tcx.def_key(def_id);
2271 if let DefPathData::Impl = key.disambiguated_data.data {
2272 let use_types = !def_id.is_local() || {
2275 let force_no_types = with_forced_impl_filename_line();
2277 !force_no_types
2278 };
2279
2280 if !use_types {
2281 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
2285 let span = self.tcx.def_span(def_id);
2286
2287 self.print_def_path(parent_def_id, ty::GenericArgs::empty())?;
2288
2289 if !self.empty_path {
2292 self.write_fmt(format_args!("::"))write!(self, "::")?;
2293 }
2294 self.write_fmt(format_args!("<impl at {0}>",
self.tcx.sess.source_map().span_to_diagnostic_string(span)))write!(
2295 self,
2296 "<impl at {}>",
2297 self.tcx.sess.source_map().span_to_diagnostic_string(span)
2300 )?;
2301 self.empty_path = false;
2302
2303 return Ok(());
2304 }
2305 }
2306
2307 self.default_print_def_path(def_id, args)
2308 }
2309
2310 fn print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), PrintError> {
2311 self.pretty_print_region(region)
2312 }
2313
2314 fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
2315 let has_regions = self.region_highlight_mode.keep_regions
2316 && ty.has_type_flags(ty::TypeFlags::HAS_REGIONS);
2317 match ty.kind() {
2318 ty::Tuple(tys) if tys.len() == 0 => {
2319 self.pretty_print_type(ty)
2321 }
2322
2323 ty::Adt(def, args)
2324 if self.should_truncate()
2325 && args.consts().count() < 2
2326 && args.types().count() < 2
2327 && {
2328 if let Some(arg) = args.types().next() {
2333 if let ty::Adt(_, arg_args) = arg.kind() {
2334 if arg_args.terms().next().is_none() {
2335 true
2338 } else {
2339 false
2343 }
2344 } else {
2345 true
2348 }
2349 } else {
2350 true
2352 }
2353 }
2354 && self.tcx.item_name(def.did()).as_str().len() < 7 =>
2355 {
2356 { let _guard = ForceTrimmedGuard::new(); self.pretty_print_type(ty) }with_forced_trimmed_paths!(self.pretty_print_type(ty))
2359 }
2360
2361 ty::Alias(_, alias)
2362 if self.should_truncate()
2363 && let ty::AliasTyKind::Opaque { def_id } = alias.kind
2364 && self.region_highlight_mode.keep_regions
2365 && self
2366 .tcx
2367 .explicit_item_bounds(def_id)
2368 .iter_instantiated_copied(self.tcx, alias.args)
2369 .map(Unnormalized::skip_norm_wip)
2370 .any(|(value, _)| value.has_bound_vars()) =>
2371 {
2372 self.printed_type_count += 1;
2374 self.pretty_print_type(ty)
2375 }
2376
2377 ty::Adt(..)
2378 | ty::Foreign(_)
2379 | ty::Pat(..)
2380 | ty::RawPtr(..)
2381 | ty::Ref(..)
2382 | ty::FnDef(..)
2383 | ty::FnPtr(..)
2384 | ty::UnsafeBinder(..)
2385 | ty::Dynamic(..)
2386 | ty::CoroutineClosure(..)
2387 | ty::Coroutine(..)
2388 | ty::CoroutineWitness(..)
2389 | ty::Tuple(_)
2390 | ty::Alias(..)
2391 | ty::Bound(..)
2392 | ty::Placeholder(_)
2393 | ty::Error(_)
2394 if self.should_truncate() && !has_regions =>
2395 {
2396 self.write_fmt(format_args!("_"))write!(self, "_")?;
2399 Ok(())
2400 }
2401 ty::Ref(..) if self.should_truncate() && has_regions => self.pretty_print_type(ty),
2402 ty::Closure(..) => self.pretty_print_type(ty),
2403 _ => {
2404 self.printed_type_count += 1;
2405 self.pretty_print_type(ty)
2406 }
2407 }
2408 }
2409
2410 fn print_dyn_existential(
2411 &mut self,
2412 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2413 ) -> Result<(), PrintError> {
2414 self.pretty_print_dyn_existential(predicates)
2415 }
2416
2417 fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
2418 self.pretty_print_const(ct, false)
2419 }
2420
2421 fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
2422 self.empty_path = true;
2423 if cnum == LOCAL_CRATE && !with_resolve_crate_name() {
2424 if with_crate_prefix() {
2425 self.write_fmt(format_args!("{0}", kw::Crate))write!(self, "{}", kw::Crate)?;
2426 self.empty_path = false;
2427 }
2428 } else {
2429 self.write_fmt(format_args!("{0}", self.tcx.crate_name(cnum)))write!(self, "{}", self.tcx.crate_name(cnum))?;
2430 self.empty_path = false;
2431 }
2432 Ok(())
2433 }
2434
2435 fn print_path_with_qualified(
2436 &mut self,
2437 self_ty: Ty<'tcx>,
2438 trait_ref: Option<ty::TraitRef<'tcx>>,
2439 ) -> Result<(), PrintError> {
2440 self.pretty_print_path_with_qualified(self_ty, trait_ref)?;
2441 self.empty_path = false;
2442 Ok(())
2443 }
2444
2445 fn print_path_with_impl(
2446 &mut self,
2447 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2448 self_ty: Ty<'tcx>,
2449 trait_ref: Option<ty::TraitRef<'tcx>>,
2450 ) -> Result<(), PrintError> {
2451 self.pretty_print_path_with_impl(
2452 |p| {
2453 print_prefix(p)?;
2454 if !p.empty_path {
2455 p.write_fmt(format_args!("::"))write!(p, "::")?;
2456 }
2457
2458 Ok(())
2459 },
2460 self_ty,
2461 trait_ref,
2462 )?;
2463 self.empty_path = false;
2464 Ok(())
2465 }
2466
2467 fn print_path_with_simple(
2468 &mut self,
2469 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2470 disambiguated_data: &DisambiguatedDefPathData,
2471 ) -> Result<(), PrintError> {
2472 print_prefix(self)?;
2473
2474 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
2476 return Ok(());
2477 }
2478
2479 let name = disambiguated_data.data.name();
2480 if !self.empty_path {
2481 self.write_fmt(format_args!("::"))write!(self, "::")?;
2482 }
2483
2484 if let DefPathDataName::Named(name) = name {
2485 if Ident::with_dummy_span(name).is_raw_guess() {
2486 self.write_fmt(format_args!("r#"))write!(self, "r#")?;
2487 }
2488 }
2489
2490 let verbose = self.should_print_verbose();
2491 self.write_fmt(format_args!("{0}", disambiguated_data.as_sym(verbose)))write!(self, "{}", disambiguated_data.as_sym(verbose))?;
2492
2493 self.empty_path = false;
2494
2495 Ok(())
2496 }
2497
2498 fn print_path_with_generic_args(
2499 &mut self,
2500 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2501 args: ty::GenericArgs<'tcx>,
2502 ) -> Result<(), PrintError> {
2503 print_prefix(self)?;
2504
2505 if !args.is_empty() {
2506 if self.in_value {
2507 self.write_fmt(format_args!("::"))write!(self, "::")?;
2508 }
2509 self.generic_delimiters(|p| p.comma_sep(args.iter()))
2510 } else {
2511 Ok(())
2512 }
2513 }
2514}
2515
2516impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
2517 fn ty_infer_name(&self, id: ty::TyVid) -> Option<Symbol> {
2518 self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
2519 }
2520
2521 fn reset_type_limit(&mut self) {
2522 self.printed_type_count = 0;
2523 }
2524
2525 fn const_infer_name(&self, id: ty::ConstVid) -> Option<Symbol> {
2526 self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
2527 }
2528
2529 fn pretty_print_value_path(
2530 &mut self,
2531 def_id: DefId,
2532 args: ty::GenericArgs<'tcx>,
2533 ) -> Result<(), PrintError> {
2534 let was_in_value = std::mem::replace(&mut self.in_value, true);
2535 self.print_def_path(def_id, args)?;
2536 self.in_value = was_in_value;
2537
2538 Ok(())
2539 }
2540
2541 fn pretty_print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError>
2542 where
2543 T: Print<Self> + TypeFoldable<TyCtxt<'tcx>>,
2544 {
2545 self.wrap_binder(value, WrapBinderMode::ForAll, |new_value, this| new_value.print(this))
2546 }
2547
2548 fn wrap_binder<T, C: FnOnce(&T, &mut Self) -> Result<(), PrintError>>(
2549 &mut self,
2550 value: &ty::Binder<'tcx, T>,
2551 mode: WrapBinderMode,
2552 f: C,
2553 ) -> Result<(), PrintError>
2554 where
2555 T: TypeFoldable<TyCtxt<'tcx>>,
2556 {
2557 let old_region_index = self.region_index;
2558 let (new_value, _) = self.name_all_regions(value, mode)?;
2559 f(&new_value, self)?;
2560 self.region_index = old_region_index;
2561 self.binder_depth -= 1;
2562 Ok(())
2563 }
2564
2565 fn typed_value(
2566 &mut self,
2567 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2568 t: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2569 conversion: &str,
2570 ) -> Result<(), PrintError> {
2571 self.write_str("{")?;
2572 f(self)?;
2573 self.write_str(conversion)?;
2574 let was_in_value = std::mem::replace(&mut self.in_value, false);
2575 t(self)?;
2576 self.in_value = was_in_value;
2577 self.write_str("}")?;
2578 Ok(())
2579 }
2580
2581 fn generic_delimiters(
2582 &mut self,
2583 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2584 ) -> Result<(), PrintError> {
2585 self.write_fmt(format_args!("<"))write!(self, "<")?;
2586
2587 let was_in_value = std::mem::replace(&mut self.in_value, false);
2588 f(self)?;
2589 self.in_value = was_in_value;
2590
2591 self.write_fmt(format_args!(">"))write!(self, ">")?;
2592 Ok(())
2593 }
2594
2595 fn should_truncate(&mut self) -> bool {
2596 !self.type_length_limit.value_within_limit(self.printed_type_count)
2597 }
2598
2599 fn should_print_optional_region(&self, region: ty::Region<'tcx>) -> bool {
2600 let highlight = self.region_highlight_mode;
2601 if highlight.region_highlighted(region).is_some() {
2602 return true;
2603 }
2604
2605 if self.should_print_verbose() {
2606 return true;
2607 }
2608
2609 if with_forced_trimmed_paths() {
2610 return false;
2611 }
2612
2613 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2614
2615 match region.kind() {
2616 ty::ReEarlyParam(ref data) => data.is_named(),
2617
2618 ty::ReLateParam(ty::LateParamRegion { kind, .. }) => kind.is_named(self.tcx),
2619 ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2620 | ty::RePlaceholder(ty::Placeholder {
2621 bound: ty::BoundRegion { kind: br, .. }, ..
2622 }) => {
2623 if br.is_named(self.tcx) {
2624 return true;
2625 }
2626
2627 if let Some((region, _)) = highlight.highlight_bound_region {
2628 if br == region {
2629 return true;
2630 }
2631 }
2632
2633 false
2634 }
2635
2636 ty::ReVar(_) if identify_regions => true,
2637
2638 ty::ReVar(_) | ty::ReErased | ty::ReError(_) => false,
2639
2640 ty::ReStatic => true,
2641 }
2642 }
2643
2644 fn pretty_print_const_pointer<Prov: Provenance>(
2645 &mut self,
2646 p: Pointer<Prov>,
2647 ty: Ty<'tcx>,
2648 ) -> Result<(), PrintError> {
2649 let print = |this: &mut Self| {
2650 if this.print_alloc_ids {
2651 this.write_fmt(format_args!("{0:?}", p))write!(this, "{p:?}")?;
2652 } else {
2653 this.write_fmt(format_args!("&_"))write!(this, "&_")?;
2654 }
2655 Ok(())
2656 };
2657 self.typed_value(print, |this| this.print_type(ty), ": ")
2658 }
2659}
2660
2661impl<'tcx> FmtPrinter<'_, 'tcx> {
2663 pub fn pretty_print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), fmt::Error> {
2664 let highlight = self.region_highlight_mode;
2666 if let Some(n) = highlight.region_highlighted(region) {
2667 self.write_fmt(format_args!("\'{0}", n))write!(self, "'{n}")?;
2668 return Ok(());
2669 }
2670
2671 if self.should_print_verbose() {
2672 self.write_fmt(format_args!("{0:?}", region))write!(self, "{region:?}")?;
2673 return Ok(());
2674 }
2675
2676 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2677
2678 match region.kind() {
2683 ty::ReEarlyParam(data) => {
2684 self.write_fmt(format_args!("{0}", data.name))write!(self, "{}", data.name)?;
2685 return Ok(());
2686 }
2687 ty::ReLateParam(ty::LateParamRegion { kind, .. }) => {
2688 if let Some(name) = kind.get_name(self.tcx) {
2689 self.write_fmt(format_args!("{0}", name))write!(self, "{name}")?;
2690 return Ok(());
2691 }
2692 }
2693 ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2694 | ty::RePlaceholder(ty::Placeholder {
2695 bound: ty::BoundRegion { kind: br, .. }, ..
2696 }) => {
2697 if let Some(name) = br.get_name(self.tcx) {
2698 self.write_fmt(format_args!("{0}", name))write!(self, "{name}")?;
2699 return Ok(());
2700 }
2701
2702 if let Some((region, counter)) = highlight.highlight_bound_region {
2703 if br == region {
2704 self.write_fmt(format_args!("\'{0}", counter))write!(self, "'{counter}")?;
2705 return Ok(());
2706 }
2707 }
2708 }
2709 ty::ReVar(region_vid) if identify_regions => {
2710 self.write_fmt(format_args!("{0:?}", region_vid))write!(self, "{region_vid:?}")?;
2711 return Ok(());
2712 }
2713 ty::ReVar(_) => {}
2714 ty::ReErased => {}
2715 ty::ReError(_) => {}
2716 ty::ReStatic => {
2717 self.write_fmt(format_args!("\'static"))write!(self, "'static")?;
2718 return Ok(());
2719 }
2720 }
2721
2722 self.write_fmt(format_args!("\'_"))write!(self, "'_")?;
2723
2724 Ok(())
2725 }
2726}
2727
2728struct RegionFolder<'a, 'tcx> {
2730 tcx: TyCtxt<'tcx>,
2731 current_index: ty::DebruijnIndex,
2732 region_map: UnordMap<ty::BoundRegion<'tcx>, ty::Region<'tcx>>,
2735 name: &'a mut (dyn FnMut(ty::BoundRegion<'tcx>) -> ty::Region<'tcx> + 'a),
2736}
2737
2738impl<'a, 'tcx> ty::TypeFolder<TyCtxt<'tcx>> for RegionFolder<'a, 'tcx> {
2739 fn cx(&self) -> TyCtxt<'tcx> {
2740 self.tcx
2741 }
2742
2743 fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>(
2744 &mut self,
2745 t: ty::Binder<'tcx, T>,
2746 ) -> ty::Binder<'tcx, T> {
2747 self.current_index.shift_in(1);
2748 let t = t.super_fold_with(self);
2749 self.current_index.shift_out(1);
2750 t
2751 }
2752
2753 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2754 match *t.kind() {
2755 _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2756 return t.super_fold_with(self);
2757 }
2758 _ => {}
2759 }
2760 t
2761 }
2762
2763 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2764 let name = &mut self.name;
2765 let region = match r.kind() {
2766 ty::ReBound(ty::BoundVarIndexKind::Bound(db), br) if db == self.current_index => {
2772 *self.region_map.entry(br).or_insert_with(|| name(br))
2773 }
2774 ty::RePlaceholder(ty::PlaceholderRegion {
2775 bound: ty::BoundRegion { kind, .. },
2776 ..
2777 }) => {
2778 match kind {
2781 ty::BoundRegionKind::Anon | ty::BoundRegionKind::ClosureEnv => r,
2782 _ => {
2783 let br = ty::BoundRegion { var: ty::BoundVar::ZERO, kind };
2785 *self.region_map.entry(br).or_insert_with(|| name(br))
2786 }
2787 }
2788 }
2789 _ => return r,
2790 };
2791 if let ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn1), br) = region.kind() {
2792 {
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);
2793 ty::Region::new_bound(self.tcx, self.current_index, br)
2794 } else {
2795 region
2796 }
2797 }
2798}
2799
2800impl<'tcx> FmtPrinter<'_, 'tcx> {
2803 pub fn name_all_regions<T>(
2804 &mut self,
2805 value: &ty::Binder<'tcx, T>,
2806 mode: WrapBinderMode,
2807 ) -> Result<(T, UnordMap<ty::BoundRegion<'tcx>, ty::Region<'tcx>>), fmt::Error>
2808 where
2809 T: TypeFoldable<TyCtxt<'tcx>>,
2810 {
2811 fn name_by_region_index(
2812 index: usize,
2813 available_names: &mut Vec<Symbol>,
2814 num_available: usize,
2815 ) -> Symbol {
2816 if let Some(name) = available_names.pop() {
2817 name
2818 } else {
2819 Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'z{0}", index - num_available))
})format!("'z{}", index - num_available))
2820 }
2821 }
2822
2823 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs:2823",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(2823u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("name_all_regions")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("name_all_regions");
2824
2825 if self.binder_depth == 0 {
2831 self.prepare_region_info(value);
2832 }
2833
2834 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs:2834",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(2834u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("self.used_region_names: {0:?}",
self.used_region_names) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("self.used_region_names: {:?}", self.used_region_names);
2835
2836 let mut empty = true;
2837 let mut start_or_continue = |p: &mut Self, start: &str, cont: &str| {
2838 let w = if empty {
2839 empty = false;
2840 start
2841 } else {
2842 cont
2843 };
2844 let _ = p.write_fmt(format_args!("{0}", w))write!(p, "{w}");
2845 };
2846 let do_continue = |p: &mut Self, cont: Symbol| {
2847 let _ = p.write_fmt(format_args!("{0}", cont))write!(p, "{cont}");
2848 };
2849
2850 let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'{0}", s))
})format!("'{s}")));
2851
2852 let mut available_names = possible_names
2853 .filter(|name| !self.used_region_names.contains(name))
2854 .collect::<Vec<_>>();
2855 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs:2855",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(2855u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::print::pretty"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("available_names")
}> =
::tracing::__macro_support::FieldName::new("available_names");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&available_names)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?available_names);
2856 let num_available = available_names.len();
2857
2858 let mut region_index = self.region_index;
2859 let mut next_name = |this: &Self| {
2860 let mut name;
2861
2862 loop {
2863 name = name_by_region_index(region_index, &mut available_names, num_available);
2864 region_index += 1;
2865
2866 if !this.used_region_names.contains(&name) {
2867 break;
2868 }
2869 }
2870
2871 name
2872 };
2873
2874 let (new_value, map) = if self.should_print_verbose() {
2879 for var in value.bound_vars().iter() {
2880 start_or_continue(self, mode.start_str(), ", ");
2881 self.write_fmt(format_args!("{0:?}", var))write!(self, "{var:?}")?;
2882 }
2883 if value.bound_vars().is_empty() && mode == WrapBinderMode::Unsafe {
2885 start_or_continue(self, mode.start_str(), "");
2886 }
2887 start_or_continue(self, "", "> ");
2888 (value.clone().skip_binder(), UnordMap::default())
2889 } else {
2890 let tcx = self.tcx;
2891
2892 let trim_path = with_forced_trimmed_paths();
2893 let mut name = |br: ty::BoundRegion<'tcx>| {
2896 let (name, kind) = if let Some(name) = br.kind.get_name(tcx) {
2897 (name, br.kind)
2898 } else {
2899 let name = next_name(self);
2900 (name, ty::BoundRegionKind::NamedForPrinting(name))
2901 };
2902
2903 if !trim_path || mode == WrapBinderMode::Unsafe {
2905 start_or_continue(self, mode.start_str(), ", ");
2906 do_continue(self, name);
2907 }
2908 ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { var: br.var, kind })
2909 };
2910 let mut folder = RegionFolder {
2911 tcx,
2912 current_index: ty::INNERMOST,
2913 name: &mut name,
2914 region_map: UnordMap::default(),
2915 };
2916 let new_value = value.clone().skip_binder().fold_with(&mut folder);
2917 let region_map = folder.region_map;
2918
2919 if mode == WrapBinderMode::Unsafe && region_map.is_empty() {
2920 start_or_continue(self, mode.start_str(), "");
2921 }
2922 start_or_continue(self, "", "> ");
2923
2924 (new_value, region_map)
2925 };
2926
2927 self.binder_depth += 1;
2928 self.region_index = region_index;
2929 Ok((new_value, map))
2930 }
2931
2932 fn prepare_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2933 where
2934 T: TypeFoldable<TyCtxt<'tcx>>,
2935 {
2936 struct RegionNameCollector<'tcx> {
2937 tcx: TyCtxt<'tcx>,
2938 used_region_names: FxHashSet<Symbol>,
2939 type_collector: SsoHashSet<Ty<'tcx>>,
2940 }
2941
2942 impl<'tcx> RegionNameCollector<'tcx> {
2943 fn new(tcx: TyCtxt<'tcx>) -> Self {
2944 RegionNameCollector {
2945 tcx,
2946 used_region_names: Default::default(),
2947 type_collector: SsoHashSet::new(),
2948 }
2949 }
2950 }
2951
2952 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for RegionNameCollector<'tcx> {
2953 fn visit_region(&mut self, r: ty::Region<'tcx>) {
2954 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs:2954",
"rustc_middle::ty::print::pretty", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(2954u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("address: {0:p}",
r.0.0) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("address: {:p}", r.0.0);
2955
2956 if let Some(name) = r.get_name(self.tcx) {
2960 self.used_region_names.insert(name);
2961 }
2962 }
2963
2964 fn visit_ty(&mut self, ty: Ty<'tcx>) {
2967 let not_previously_inserted = self.type_collector.insert(ty);
2968 if not_previously_inserted {
2969 ty.super_visit_with(self)
2970 }
2971 }
2972 }
2973
2974 let mut collector = RegionNameCollector::new(self.tcx());
2975 value.visit_with(&mut collector);
2976 self.used_region_names = collector.used_region_names;
2977 self.region_index = 0;
2978 }
2979}
2980
2981impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<P> for ty::Binder<'tcx, T>
2982where
2983 T: Print<P> + TypeFoldable<TyCtxt<'tcx>>,
2984{
2985 fn print(&self, p: &mut P) -> Result<(), PrintError> {
2986 p.pretty_print_in_binder(self)
2987 }
2988}
2989
2990impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<P> for ty::OutlivesClause<'tcx, T>
2991where
2992 T: Print<P>,
2993{
2994 fn print(&self, p: &mut P) -> Result<(), PrintError> {
2995 self.0.print(p)?;
2996 p.write_fmt(format_args!(": "))write!(p, ": ")?;
2997 self.1.print(p)?;
2998 Ok(())
2999 }
3000}
3001
3002#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for
TraitRefPrintOnlyTraitPath<'tcx> {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for TraitRefPrintOnlyTraitPath<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for
TraitRefPrintOnlyTraitPath<'tcx> {
#[inline]
fn clone(&self) -> Self {
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)]
3006pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
3007
3008impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintOnlyTraitPath<'tcx> {
3009 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
3010 ty::tls::with(|tcx| {
3011 let trait_ref = tcx.short_string(tcx.lift(self), path);
3012 rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
3013 })
3014 }
3015}
3016
3017impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
3018 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3019 fmt::Display::fmt(self, f)
3020 }
3021}
3022
3023#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for
TraitRefPrintSugared<'tcx> {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for TraitRefPrintSugared<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for
TraitRefPrintSugared<'tcx> {
#[inline]
fn clone(&self) -> Self {
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)]
3026pub struct TraitRefPrintSugared<'tcx>(ty::TraitRef<'tcx>);
3027
3028impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintSugared<'tcx> {
3029 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
3030 ty::tls::with(|tcx| {
3031 let trait_ref = tcx.short_string(tcx.lift(self), path);
3032 rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
3033 })
3034 }
3035}
3036
3037impl<'tcx> fmt::Debug for TraitRefPrintSugared<'tcx> {
3038 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3039 fmt::Display::fmt(self, f)
3040 }
3041}
3042
3043#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for
TraitRefPrintOnlyTraitName<'tcx> {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for TraitRefPrintOnlyTraitName<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for
TraitRefPrintOnlyTraitName<'tcx> {
#[inline]
fn clone(&self) -> Self {
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)]
3047pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
3048
3049impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
3050 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3051 fmt::Display::fmt(self, f)
3052 }
3053}
3054
3055pub trait PrintTraitRefExt<'tcx> {
fn print_only_trait_path(self)
-> TraitRefPrintOnlyTraitPath<'tcx>;
fn print_trait_sugared(self)
-> TraitRefPrintSugared<'tcx>;
fn print_only_trait_name(self)
-> TraitRefPrintOnlyTraitName<'tcx>;
}
impl<'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>)]
3056impl<'tcx> ty::TraitRef<'tcx> {
3057 fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
3058 TraitRefPrintOnlyTraitPath(self)
3059 }
3060
3061 fn print_trait_sugared(self) -> TraitRefPrintSugared<'tcx> {
3062 TraitRefPrintSugared(self)
3063 }
3064
3065 fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
3066 TraitRefPrintOnlyTraitName(self)
3067 }
3068}
3069
3070pub trait PrintPolyTraitRefExt<'tcx> {
fn print_only_trait_path(self)
-> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>>;
fn print_trait_sugared(self)
-> ty::Binder<'tcx, TraitRefPrintSugared<'tcx>>;
}
impl<'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>)]
3071impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
3072 fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
3073 self.map_bound(|tr| tr.print_only_trait_path())
3074 }
3075
3076 fn print_trait_sugared(self) -> ty::Binder<'tcx, TraitRefPrintSugared<'tcx>> {
3077 self.map_bound(|tr| tr.print_trait_sugared())
3078 }
3079}
3080
3081#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for
TraitClausePrintModifiersAndPath<'tcx> {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for TraitClausePrintModifiersAndPath<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for
TraitClausePrintModifiersAndPath<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<ty::TraitClause<'tcx>>;
*self
}
}Clone, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for TraitClausePrintModifiersAndPath<'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 {
TraitClausePrintModifiersAndPath(__binding_0) => {
TraitClausePrintModifiersAndPath(::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 {
TraitClausePrintModifiersAndPath(__binding_0) => {
TraitClausePrintModifiersAndPath(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for TraitClausePrintModifiersAndPath<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
TraitClausePrintModifiersAndPath(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 TraitClausePrintModifiersAndPath<'tcx> {
type Lifted = TraitClausePrintModifiersAndPath<'__lifted>;
fn lift_to_interner(self,
__tcx: ::rustc_middle::ty::TyCtxt<'__lifted>)
-> TraitClausePrintModifiersAndPath<'__lifted> {
match self {
TraitClausePrintModifiersAndPath(__binding_0) => {
TraitClausePrintModifiersAndPath(__tcx.lift(__binding_0))
}
}
}
}
};Lift, #[automatically_derived]impl<'tcx> ::core::hash::Hash for
TraitClausePrintModifiersAndPath<'tcx> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash)]
3082pub struct TraitClausePrintModifiersAndPath<'tcx>(ty::TraitClause<'tcx>);
3083
3084impl<'tcx> fmt::Debug for TraitClausePrintModifiersAndPath<'tcx> {
3085 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3086 fmt::Display::fmt(self, f)
3087 }
3088}
3089
3090pub trait PrintTraitClauseExt<'tcx> {
fn print_modifiers_and_trait_path(self)
-> TraitClausePrintModifiersAndPath<'tcx>;
}
impl<'tcx> PrintTraitClauseExt<'tcx> for ty::TraitClause<'tcx> {
fn print_modifiers_and_trait_path(self)
-> TraitClausePrintModifiersAndPath<'tcx> {
TraitClausePrintModifiersAndPath(self)
}
}#[extension(pub trait PrintTraitClauseExt<'tcx>)]
3091impl<'tcx> ty::TraitClause<'tcx> {
3092 fn print_modifiers_and_trait_path(self) -> TraitClausePrintModifiersAndPath<'tcx> {
3093 TraitClausePrintModifiersAndPath(self)
3094 }
3095}
3096
3097#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for
TraitClausePrintWithBoundConstness<'tcx> {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for TraitClausePrintWithBoundConstness<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for
TraitClausePrintWithBoundConstness<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<ty::TraitClause<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Option<ty::BoundConstness>>;
*self
}
}Clone, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for TraitClausePrintWithBoundConstness<'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 {
TraitClausePrintWithBoundConstness(__binding_0, __binding_1)
=> {
TraitClausePrintWithBoundConstness(::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 {
TraitClausePrintWithBoundConstness(__binding_0, __binding_1)
=> {
TraitClausePrintWithBoundConstness(::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 TraitClausePrintWithBoundConstness<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
TraitClausePrintWithBoundConstness(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 TraitClausePrintWithBoundConstness<'tcx> {
type Lifted = TraitClausePrintWithBoundConstness<'__lifted>;
fn lift_to_interner(self,
__tcx: ::rustc_middle::ty::TyCtxt<'__lifted>)
-> TraitClausePrintWithBoundConstness<'__lifted> {
match self {
TraitClausePrintWithBoundConstness(__binding_0, __binding_1)
=> {
TraitClausePrintWithBoundConstness(__tcx.lift(__binding_0),
__tcx.lift(__binding_1))
}
}
}
}
};Lift, #[automatically_derived]impl<'tcx> ::core::hash::Hash for
TraitClausePrintWithBoundConstness<'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)]
3098pub struct TraitClausePrintWithBoundConstness<'tcx>(
3099 ty::TraitClause<'tcx>,
3100 Option<ty::BoundConstness>,
3101);
3102
3103impl<'tcx> fmt::Debug for TraitClausePrintWithBoundConstness<'tcx> {
3104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3105 fmt::Display::fmt(self, f)
3106 }
3107}
3108
3109pub trait PrintPolyTraitClauseExt<'tcx> {
fn print_modifiers_and_trait_path(self)
-> ty::Binder<'tcx, TraitClausePrintModifiersAndPath<'tcx>>;
fn print_with_bound_constness(self, constness: Option<ty::BoundConstness>)
-> ty::Binder<'tcx, TraitClausePrintWithBoundConstness<'tcx>>;
}
impl<'tcx> PrintPolyTraitClauseExt<'tcx> for ty::PolyTraitClause<'tcx> {
fn print_modifiers_and_trait_path(self)
-> ty::Binder<'tcx, TraitClausePrintModifiersAndPath<'tcx>> {
self.map_bound(TraitClausePrintModifiersAndPath)
}
fn print_with_bound_constness(self, constness: Option<ty::BoundConstness>)
-> ty::Binder<'tcx, TraitClausePrintWithBoundConstness<'tcx>> {
self.map_bound(|trait_pred|
TraitClausePrintWithBoundConstness(trait_pred, constness))
}
}#[extension(pub trait PrintPolyTraitClauseExt<'tcx>)]
3110impl<'tcx> ty::PolyTraitClause<'tcx> {
3111 fn print_modifiers_and_trait_path(
3112 self,
3113 ) -> ty::Binder<'tcx, TraitClausePrintModifiersAndPath<'tcx>> {
3114 self.map_bound(TraitClausePrintModifiersAndPath)
3115 }
3116
3117 fn print_with_bound_constness(
3118 self,
3119 constness: Option<ty::BoundConstness>,
3120 ) -> ty::Binder<'tcx, TraitClausePrintWithBoundConstness<'tcx>> {
3121 self.map_bound(|trait_pred| TraitClausePrintWithBoundConstness(trait_pred, constness))
3122 }
3123}
3124
3125#[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]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for PrintClosureAsImpl<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for
PrintClosureAsImpl<'tcx> {
#[inline]
fn clone(&self) -> Self {
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)]
3126pub struct PrintClosureAsImpl<'tcx> {
3127 pub closure: ty::ClosureArgs<TyCtxt<'tcx>>,
3128}
3129
3130macro_rules! forward_display_to_print {
3131 ($($ty:ty),+) => {
3132 $(
3133 #[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
3134 impl<'tcx> fmt::Display for $ty {
3135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3136 ty::tls::with(|tcx| {
3137 let mut p = FmtPrinter::new(tcx, Namespace::TypeNS);
3138 tcx.lift(*self)
3139 .print(&mut p)?;
3140 f.write_str(&p.into_buffer())?;
3141 Ok(())
3142 })
3143 }
3144 }
3145 )+
3146 };
3147}
3148
3149macro_rules! define_print {
3150 (($self:ident, $p:ident): $($ty:ty $print:block)+) => {
3151 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for $ty {
3152 fn print(&$self, $p: &mut P) -> Result<(), PrintError> {
3153 let _: () = $print;
3154 Ok(())
3155 }
3156 })+
3157 };
3158}
3159
3160macro_rules! define_print_and_forward_display {
3161 (($self:ident, $p:ident): $($ty:ty $print:block)+) => {
3162 define_print!(($self, $p): $($ty $print)*);
3163 forward_display_to_print!($($ty),+);
3164 };
3165}
3166
3167#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for Ty<'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(())
})
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for &'tcx ty::List<ty::PolyExistentialPredicate<'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! {
3168 Ty<'tcx>,
3169 &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>
3170}
3171
3172impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::FnSig<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
p.write_fmt(format_args!("{0}", self.safety().prefix_str()))?;
if self.abi() != ExternAbi::Rust {
p.write_fmt(format_args!("extern {0} ", self.abi()))?;
}
p.write_fmt(format_args!("fn"))?;
p.pretty_print_fn_sig(self.inputs(), self.c_variadic(),
self.splatted(), self.output())?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::TraitRef<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
p.write_fmt(format_args!("<{0} as {1}>", self.self_ty(),
self.print_only_trait_path()))?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::AliasTy<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
let alias_term: ty::AliasTerm<'tcx> = (*self).into();
alias_term.print(p)?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::AliasTerm<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
match self.kind {
ty::AliasTermKind::InherentTy { .. } |
ty::AliasTermKind::InherentConstSelf { .. } => {
p.pretty_print_inherent_projection(*self)?;
}
ty::AliasTermKind::ProjectionTy { def_id } => {
if !(p.should_print_verbose() || with_reduced_queries()) &&
p.tcx().is_impl_trait_in_trait(def_id) {
p.pretty_print_rpitit(def_id, self.args)?;
} else { p.print_def_path(def_id, self.args)?; }
}
ty::AliasTermKind::FreeTy { def_id } |
ty::AliasTermKind::FreeConst { def_id } |
ty::AliasTermKind::OpaqueTy { def_id } |
ty::AliasTermKind::AnonConst { def_id } |
ty::AliasTermKind::ProjectionConst { def_id } |
ty::AliasTermKind::InherentConstImpl { def_id } => {
p.print_def_path(def_id, self.args)?;
}
}
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::TraitClause<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
self.trait_ref.self_ty().print(p)?;
p.write_fmt(format_args!(": "))?;
if let ty::ClausePolarity::Negative = self.polarity {
p.write_fmt(format_args!("!"))?;
}
self.trait_ref.print_trait_sugared().print(p)?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::HostEffectClause<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
let constness =
match self.constness {
ty::BoundConstness::Const => { "const" }
ty::BoundConstness::Maybe => { "[const]" }
};
self.trait_ref.self_ty().print(p)?;
p.write_fmt(format_args!(": {0} ", constness))?;
self.trait_ref.print_trait_sugared().print(p)?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::TypeAndMut<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
p.write_fmt(format_args!("{0}", self.mutbl.prefix_str()))?;
self.ty.print(p)?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::ClauseKind<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
match *self {
ty::ClauseKind::Trait(ref data) => data.print(p)?,
ty::ClauseKind::RegionOutlives(clause) => clause.print(p)?,
ty::ClauseKind::TypeOutlives(clause) => clause.print(p)?,
ty::ClauseKind::Projection(predicate) =>
predicate.print(p)?,
ty::ClauseKind::HostEffect(clause) => clause.print(p)?,
ty::ClauseKind::ConstArgHasType(ct, ty) => {
p.write_fmt(format_args!("the constant `"))?;
ct.print(p)?;
p.write_fmt(format_args!("` has type `"))?;
ty.print(p)?;
p.write_fmt(format_args!("`"))?;
}
ty::ClauseKind::WellFormed(term) => {
term.print(p)?;
p.write_fmt(format_args!(" well-formed"))?;
}
ty::ClauseKind::ConstEvaluatable(ct) => {
p.write_fmt(format_args!("the constant `"))?;
ct.print(p)?;
p.write_fmt(format_args!("` can be evaluated"))?;
}
ty::ClauseKind::UnstableFeature(symbol) => {
p.write_fmt(format_args!("feature({0}) is enabled",
symbol))?;
}
}
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::PredicateKind<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
match *self {
ty::PredicateKind::Clause(data) => data.print(p)?,
ty::PredicateKind::Subtype(predicate) =>
predicate.print(p)?,
ty::PredicateKind::Coerce(predicate) => predicate.print(p)?,
ty::PredicateKind::DynCompatible(trait_def_id) => {
p.write_fmt(format_args!("the trait `"))?;
p.print_def_path(trait_def_id, ty::GenericArgs::empty())?;
p.write_fmt(format_args!("` is dyn-compatible"))?;
}
ty::PredicateKind::ConstEquate(c1, c2) => {
p.write_fmt(format_args!("the constant `"))?;
c1.print(p)?;
p.write_fmt(format_args!("` equals `"))?;
c2.print(p)?;
p.write_fmt(format_args!("`"))?;
}
ty::PredicateKind::Ambiguous =>
p.write_fmt(format_args!("ambiguous"))?,
ty::PredicateKind::NormalizesTo(data) => data.print(p)?,
}
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::ExistentialPredicate<'tcx>
{
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
match *self {
ty::ExistentialPredicate::Trait(x) => x.print(p)?,
ty::ExistentialPredicate::Projection(x) => x.print(p)?,
ty::ExistentialPredicate::AutoTrait(def_id) =>
p.print_def_path(def_id, ty::GenericArgs::empty())?,
}
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::ExistentialTraitRef<'tcx>
{
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
let trait_ref =
self.with_self_ty(p.tcx(),
p.tcx().types.trait_object_dummy_self);
trait_ref.print_only_trait_path().print(p)?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for
ty::ExistentialProjection<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
let name = p.tcx().associated_item(self.def_id).name();
let args =
&self.args.as_slice()[p.tcx().generics_of(self.def_id).parent_count
- 1..];
p.print_path_with_generic_args(|p|
p.write_fmt(format_args!("{0}", name)),
p.tcx().mk_args(args))?;
p.write_fmt(format_args!(" = "))?;
self.term.print(p)?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::ProjectionClause<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
self.projection_term.print(p)?;
p.write_fmt(format_args!(" == "))?;
p.reset_type_limit();
self.term.print(p)?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::SubtypePredicate<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
self.a.print(p)?;
p.write_fmt(format_args!(" <: "))?;
p.reset_type_limit();
self.b.print(p)?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::CoercePredicate<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
self.a.print(p)?;
p.write_fmt(format_args!(" -> "))?;
p.reset_type_limit();
self.b.print(p)?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::NormalizesTo<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
self.alias.print(p)?;
p.write_fmt(format_args!(" normalizes-to "))?;
p.reset_type_limit();
self.term.print(p)?;
};
Ok(())
}
}
impl<'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! {
3173 (self, p):
3174
3175 ty::FnSig<'tcx> {
3176 write!(p, "{}", self.safety().prefix_str())?;
3177
3178 if self.abi() != ExternAbi::Rust {
3179 write!(p, "extern {} ", self.abi())?;
3180 }
3181
3182 write!(p, "fn")?;
3183 p.pretty_print_fn_sig(self.inputs(), self.c_variadic(), self.splatted(), self.output())?;
3184 }
3185
3186 ty::TraitRef<'tcx> {
3187 write!(p, "<{} as {}>", self.self_ty(), self.print_only_trait_path())?;
3188 }
3189
3190 ty::AliasTy<'tcx> {
3191 let alias_term: ty::AliasTerm<'tcx> = (*self).into();
3192 alias_term.print(p)?;
3193 }
3194
3195 ty::AliasTerm<'tcx> {
3196 match self.kind {
3197 ty::AliasTermKind::InherentTy { .. } | ty::AliasTermKind::InherentConstSelf { .. } => {
3198 p.pretty_print_inherent_projection(*self)?;
3199 }
3200 ty::AliasTermKind::ProjectionTy { def_id } => {
3201 if !(p.should_print_verbose() || with_reduced_queries())
3202 && p.tcx().is_impl_trait_in_trait(def_id)
3203 {
3204 p.pretty_print_rpitit(def_id, self.args)?;
3205 } else {
3206 p.print_def_path(def_id, self.args)?;
3207 }
3208 }
3209 ty::AliasTermKind::FreeTy { def_id }
3210 | ty::AliasTermKind::FreeConst { def_id }
3211 | ty::AliasTermKind::OpaqueTy { def_id }
3212 | ty::AliasTermKind::AnonConst { def_id }
3213 | ty::AliasTermKind::ProjectionConst { def_id }
3214 | ty::AliasTermKind::InherentConstImpl { def_id } => {
3215 p.print_def_path(def_id, self.args)?;
3216 }
3217 }
3218 }
3219
3220 ty::TraitClause<'tcx> {
3221 self.trait_ref.self_ty().print(p)?;
3222 write!(p, ": ")?;
3223 if let ty::ClausePolarity::Negative = self.polarity {
3224 write!(p, "!")?;
3225 }
3226 self.trait_ref.print_trait_sugared().print(p)?;
3227 }
3228
3229 ty::HostEffectClause<'tcx> {
3230 let constness = match self.constness {
3231 ty::BoundConstness::Const => { "const" }
3232 ty::BoundConstness::Maybe => { "[const]" }
3233 };
3234 self.trait_ref.self_ty().print(p)?;
3235 write!(p, ": {constness} ")?;
3236 self.trait_ref.print_trait_sugared().print(p)?;
3237 }
3238
3239 ty::TypeAndMut<'tcx> {
3240 write!(p, "{}", self.mutbl.prefix_str())?;
3241 self.ty.print(p)?;
3242 }
3243
3244 ty::ClauseKind<'tcx> {
3245 match *self {
3246 ty::ClauseKind::Trait(ref data) => data.print(p)?,
3247 ty::ClauseKind::RegionOutlives(clause) => clause.print(p)?,
3248 ty::ClauseKind::TypeOutlives(clause) => clause.print(p)?,
3249 ty::ClauseKind::Projection(predicate) => predicate.print(p)?,
3250 ty::ClauseKind::HostEffect(clause) => clause.print(p)?,
3251 ty::ClauseKind::ConstArgHasType(ct, ty) => {
3252 write!(p, "the constant `")?;
3253 ct.print(p)?;
3254 write!(p, "` has type `")?;
3255 ty.print(p)?;
3256 write!(p, "`")?;
3257 },
3258 ty::ClauseKind::WellFormed(term) => {
3259 term.print(p)?;
3260 write!(p, " well-formed")?;
3261 }
3262 ty::ClauseKind::ConstEvaluatable(ct) => {
3263 write!(p, "the constant `")?;
3264 ct.print(p)?;
3265 write!(p, "` can be evaluated")?;
3266 }
3267 ty::ClauseKind::UnstableFeature(symbol) => {
3268 write!(p, "feature({symbol}) is enabled")?;
3269 }
3270 }
3271 }
3272
3273 ty::PredicateKind<'tcx> {
3274 match *self {
3275 ty::PredicateKind::Clause(data) => data.print(p)?,
3276 ty::PredicateKind::Subtype(predicate) => predicate.print(p)?,
3277 ty::PredicateKind::Coerce(predicate) => predicate.print(p)?,
3278 ty::PredicateKind::DynCompatible(trait_def_id) => {
3279 write!(p, "the trait `")?;
3280 p.print_def_path(trait_def_id, ty::GenericArgs::empty())?;
3281 write!(p, "` is dyn-compatible")?;
3282 }
3283 ty::PredicateKind::ConstEquate(c1, c2) => {
3284 write!(p, "the constant `")?;
3285 c1.print(p)?;
3286 write!(p, "` equals `")?;
3287 c2.print(p)?;
3288 write!(p, "`")?;
3289 }
3290 ty::PredicateKind::Ambiguous => write!(p, "ambiguous")?,
3291 ty::PredicateKind::NormalizesTo(data) => data.print(p)?,
3292 }
3293 }
3294
3295 ty::ExistentialPredicate<'tcx> {
3296 match *self {
3297 ty::ExistentialPredicate::Trait(x) => x.print(p)?,
3298 ty::ExistentialPredicate::Projection(x) => x.print(p)?,
3299 ty::ExistentialPredicate::AutoTrait(def_id) => p.print_def_path(def_id, ty::GenericArgs::empty())?,
3300 }
3301 }
3302
3303 ty::ExistentialTraitRef<'tcx> {
3304 let trait_ref = self.with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self);
3307 trait_ref.print_only_trait_path().print(p)?;
3308 }
3309
3310 ty::ExistentialProjection<'tcx> {
3311 let name = p.tcx().associated_item(self.def_id).name();
3312 let args = &self.args.as_slice()[p.tcx().generics_of(self.def_id).parent_count - 1..];
3315 p.print_path_with_generic_args(|p| write!(p, "{name}"), p.tcx().mk_args(args))?;
3316 write!(p, " = ")?;
3317 self.term.print(p)?;
3318 }
3319
3320 ty::ProjectionClause<'tcx> {
3321 self.projection_term.print(p)?;
3322 write!(p, " == ")?;
3323 p.reset_type_limit();
3324 self.term.print(p)?;
3325 }
3326
3327 ty::SubtypePredicate<'tcx> {
3328 self.a.print(p)?;
3329 write!(p, " <: ")?;
3330 p.reset_type_limit();
3331 self.b.print(p)?;
3332 }
3333
3334 ty::CoercePredicate<'tcx> {
3335 self.a.print(p)?;
3336 write!(p, " -> ")?;
3337 p.reset_type_limit();
3338 self.b.print(p)?;
3339 }
3340
3341 ty::NormalizesTo<'tcx> {
3342 self.alias.print(p)?;
3343 write!(p, " normalizes-to ")?;
3344 p.reset_type_limit();
3345 self.term.print(p)?;
3346 }
3347
3348 ty::PlaceholderType<'tcx> {
3349 match self.bound.kind {
3350 ty::BoundTyKind::Anon => write!(p, "{self:?}")?,
3351 ty::BoundTyKind::Param(def_id) => match p.should_print_verbose() {
3352 true => write!(p, "{self:?}")?,
3353 false => write!(p, "{}", p.tcx().item_name(def_id))?,
3354 },
3355 }
3356 }
3357}
3358
3359impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for &'tcx ty::List<Ty<'tcx>> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
p.write_fmt(format_args!("{{"))?;
p.comma_sep(self.iter())?;
p.write_fmt(format_args!("}}"))?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for
TraitRefPrintOnlyTraitPath<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () = { p.print_def_path(self.0.def_id, self.0.args)?; };
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for TraitRefPrintSugared<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
if !with_reduced_queries() &&
p.tcx().trait_def(self.0.def_id).paren_sugar &&
let Some(args_ty) =
self.0.args.get(1).and_then(|arg| arg.as_type()) &&
let ty::Tuple(args) = args_ty.kind() {
p.write_fmt(format_args!("{0}(",
p.tcx().item_name(self.0.def_id)))?;
for (i, arg) in args.iter().enumerate() {
if i > 0 { p.write_fmt(format_args!(", "))?; }
arg.print(p)?;
}
p.write_fmt(format_args!(")"))?;
} else { p.print_def_path(self.0.def_id, self.0.args)?; }
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for
TraitRefPrintOnlyTraitName<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{ p.print_def_path(self.0.def_id, ty::GenericArgs::empty())?; };
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for
TraitClausePrintModifiersAndPath<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
if let ty::ClausePolarity::Negative = self.0.polarity {
p.write_fmt(format_args!("!"))?;
}
self.0.trait_ref.print_trait_sugared().print(p)?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for
TraitClausePrintWithBoundConstness<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
self.0.trait_ref.self_ty().print(p)?;
p.write_fmt(format_args!(": "))?;
if let Some(constness) = self.1 {
p.pretty_print_bound_constness(constness)?;
}
if let ty::ClausePolarity::Negative = self.0.polarity {
p.write_fmt(format_args!("!"))?;
}
self.0.trait_ref.print_trait_sugared().print(p)?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for PrintClosureAsImpl<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () = { p.pretty_print_closure_as_impl(self.closure)?; };
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::ParamTy {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () = { p.write_fmt(format_args!("{0}", self.name))?; };
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::ParamConst {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () = { p.write_fmt(format_args!("{0}", self.name))?; };
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::Term<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
match self.kind() {
ty::TermKind::Ty(ty) => ty.print(p)?,
ty::TermKind::Const(c) => c.print(p)?,
}
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::Predicate<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () = { self.kind().print(p)?; };
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::Clause<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () = { self.kind().print(p)?; };
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for ty::UserTypeKind<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
match *self {
Self::Ty(ty) => {
p.write_fmt(format_args!("Ty("))?;
ty.print(p)?;
}
Self::TypeOf(def_id, ty::UserArgs { args, user_self_ty }) =>
{
p.write_fmt(format_args!("TypeOf("))?;
p.print_def_path(def_id, args)?;
if let Some(ty::UserSelfTy { impl_def_id, self_ty }) =
user_self_ty {
p.write_fmt(format_args!(" at <impl "))?;
let key = p.tcx().def_key(impl_def_id);
let parent_def_id =
DefId { index: key.parent.unwrap(), ..impl_def_id };
p.print_def_path(parent_def_id, ty::GenericArgs::empty())?;
p.write_fmt(format_args!("::<{0}> for ",
key.disambiguated_data.as_sym(false)))?;
self_ty.print(p)?;
p.write_fmt(format_args!(">"))?;
}
}
}
p.write_fmt(format_args!(")"))?;
};
Ok(())
}
}
impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for GenericArg<'tcx> {
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
match self.kind() {
GenericArgKind::Lifetime(lt) => lt.print(p)?,
GenericArgKind::Type(ty) => ty.print(p)?,
GenericArgKind::Const(ct) => ct.print(p)?,
}
};
Ok(())
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for &'tcx ty::List<Ty<'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(())
})
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for TraitRefPrintOnlyTraitPath<'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(())
})
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for TraitRefPrintSugared<'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(())
})
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for TraitRefPrintOnlyTraitName<'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(())
})
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for TraitClausePrintModifiersAndPath<'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(())
})
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for TraitClausePrintWithBoundConstness<'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(())
})
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for PrintClosureAsImpl<'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(())
})
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for ty::ParamTy {
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(())
})
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for ty::ParamConst {
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(())
})
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for ty::Term<'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(())
})
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for ty::Predicate<'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(())
})
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for ty::Clause<'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(())
})
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
impl<'tcx> fmt::Display for ty::UserTypeKind<'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(())
})
}
}
#[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
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! {
3360 (self, p):
3361
3362 &'tcx ty::List<Ty<'tcx>> {
3363 write!(p, "{{")?;
3364 p.comma_sep(self.iter())?;
3365 write!(p, "}}")?;
3366 }
3367
3368 TraitRefPrintOnlyTraitPath<'tcx> {
3369 p.print_def_path(self.0.def_id, self.0.args)?;
3370 }
3371
3372 TraitRefPrintSugared<'tcx> {
3373 if !with_reduced_queries()
3374 && p.tcx().trait_def(self.0.def_id).paren_sugar
3375 && let Some(args_ty) = self.0.args.get(1).and_then(|arg| arg.as_type())
3376 && let ty::Tuple(args) = args_ty.kind()
3377 {
3378 write!(p, "{}(", p.tcx().item_name(self.0.def_id))?;
3379 for (i, arg) in args.iter().enumerate() {
3380 if i > 0 {
3381 write!(p, ", ")?;
3382 }
3383 arg.print(p)?;
3384 }
3385 write!(p, ")")?;
3386 } else {
3387 p.print_def_path(self.0.def_id, self.0.args)?;
3388 }
3389 }
3390
3391 TraitRefPrintOnlyTraitName<'tcx> {
3392 p.print_def_path(self.0.def_id, ty::GenericArgs::empty())?;
3393 }
3394
3395 TraitClausePrintModifiersAndPath<'tcx> {
3396 if let ty::ClausePolarity::Negative = self.0.polarity {
3397 write!(p, "!")?;
3398 }
3399 self.0.trait_ref.print_trait_sugared().print(p)?;
3400 }
3401
3402 TraitClausePrintWithBoundConstness<'tcx> {
3403 self.0.trait_ref.self_ty().print(p)?;
3404 write!(p, ": ")?;
3405 if let Some(constness) = self.1 {
3406 p.pretty_print_bound_constness(constness)?;
3407 }
3408 if let ty::ClausePolarity::Negative = self.0.polarity {
3409 write!(p, "!")?;
3410 }
3411 self.0.trait_ref.print_trait_sugared().print(p)?;
3412 }
3413
3414 PrintClosureAsImpl<'tcx> {
3415 p.pretty_print_closure_as_impl(self.closure)?;
3416 }
3417
3418 ty::ParamTy {
3419 write!(p, "{}", self.name)?;
3420 }
3421
3422 ty::ParamConst {
3423 write!(p, "{}", self.name)?;
3424 }
3425
3426 ty::Term<'tcx> {
3427 match self.kind() {
3428 ty::TermKind::Ty(ty) => ty.print(p)?,
3429 ty::TermKind::Const(c) => c.print(p)?,
3430 }
3431 }
3432
3433 ty::Predicate<'tcx> {
3434 self.kind().print(p)?;
3435 }
3436
3437 ty::Clause<'tcx> {
3438 self.kind().print(p)?;
3439 }
3440
3441 ty::UserTypeKind<'tcx> {
3442 match *self {
3443 Self::Ty(ty) => {
3444 write!(p, "Ty(")?;
3445 ty.print(p)?;
3446 }
3447 Self::TypeOf(def_id, ty::UserArgs { args, user_self_ty }) => {
3448 write!(p, "TypeOf(")?;
3449 p.print_def_path(def_id, args)?;
3450 if let Some(ty::UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
3451 write!(p, " at <impl ")?;
3452 let key = p.tcx().def_key(impl_def_id);
3453 let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
3454 p.print_def_path(parent_def_id, ty::GenericArgs::empty())?;
3455 write!(p, "::<{}> for ", key.disambiguated_data.as_sym(false))?;
3456 self_ty.print(p)?;
3457 write!(p, ">")?;
3458 }
3459 }
3460 }
3461 write!(p, ")")?;
3462 }
3463
3464 GenericArg<'tcx> {
3465 match self.kind() {
3466 GenericArgKind::Lifetime(lt) => lt.print(p)?,
3467 GenericArgKind::Type(ty) => ty.print(p)?,
3468 GenericArgKind::Const(ct) => ct.print(p)?,
3469 }
3470 }
3471}
3472
3473fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
3474 for id in tcx.hir_free_items() {
3476 if tcx.def_kind(id.owner_id) == DefKind::Use {
3477 continue;
3478 }
3479
3480 let item = tcx.hir_item(id);
3481 let Some(ident) = item.kind.ident() else { continue };
3482
3483 let def_id = item.owner_id.to_def_id();
3484 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
3485 collect_fn(&ident, ns, def_id);
3486 }
3487
3488 let queue = &mut Vec::new();
3490 let mut seen_defs: DefIdSet = Default::default();
3491
3492 for &cnum in tcx.crates(()).iter() {
3493 match tcx.extern_crate(cnum) {
3495 None => continue,
3496 Some(extern_crate) => {
3497 if !extern_crate.is_direct() {
3498 continue;
3499 }
3500 }
3501 }
3502
3503 queue.push(cnum.as_def_id());
3504 }
3505
3506 while let Some(def) = queue.pop() {
3508 for child in tcx.module_children(def).iter() {
3509 if !child.vis.is_public() {
3510 continue;
3511 }
3512
3513 match child.res {
3514 def::Res::Def(DefKind::AssocTy, _) => {}
3515 def::Res::Def(DefKind::TyAlias, _) => {}
3516 def::Res::Def(defkind, def_id) => {
3517 if tcx.is_doc_hidden(def_id) {
3521 continue;
3522 }
3523
3524 if let Some(ns) = defkind.ns() {
3525 collect_fn(&child.ident, ns, def_id);
3526 }
3527
3528 if defkind.is_module_like() && seen_defs.insert(def_id) {
3529 queue.push(def_id);
3530 }
3531 }
3532 _ => {}
3533 }
3534 }
3535 }
3536}
3537
3538pub fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> DefIdMap<Symbol> {
3554 tcx.sess.record_trimmed_def_paths();
3561
3562 let unique_symbols_rev: &mut FxIndexMap<(Namespace, Symbol), Option<DefId>> =
3565 &mut FxIndexMap::default();
3566
3567 for symbol_set in tcx.resolutions(()).glob_map.values() {
3568 for symbol in symbol_set {
3569 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
3570 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
3571 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
3572 }
3573 }
3574
3575 for_each_def(tcx, |ident, ns, def_id| match unique_symbols_rev.entry((ns, ident.name)) {
3576 IndexEntry::Occupied(mut v) => match v.get() {
3577 None => {}
3578 Some(existing) => {
3579 if *existing != def_id {
3580 v.insert(None);
3581 }
3582 }
3583 },
3584 IndexEntry::Vacant(v) => {
3585 v.insert(Some(def_id));
3586 }
3587 });
3588
3589 let mut map: DefIdMap<Symbol> = Default::default();
3591 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain(..) {
3592 use std::collections::hash_map::Entry::{Occupied, Vacant};
3593
3594 if let Some(def_id) = opt_def_id {
3595 match map.entry(def_id) {
3596 Occupied(mut v) => {
3597 if *v.get() != symbol && v.get().as_str() > symbol.as_str() {
3606 v.insert(symbol);
3607 }
3608 }
3609 Vacant(v) => {
3610 v.insert(symbol);
3611 }
3612 }
3613 }
3614 }
3615
3616 map
3617}
3618
3619pub fn provide(providers: &mut Providers) {
3620 *providers = Providers { trimmed_def_paths, ..*providers };
3621}
3622
3623pub struct OpaqueFnEntry<'tcx> {
3624 kind: ty::ClosureKind,
3625 return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,
3626}