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