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