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/522d96a5707c154b15960db186c03b84a52b4efb/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/522d96a5707c154b15960db186c03b84a52b4efb/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/522d96a5707c154b15960db186c03b84a52b4efb/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/522d96a5707c154b15960db186c03b84a52b4efb/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/522d96a5707c154b15960db186c03b84a52b4efb/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/522d96a5707c154b15960db186c03b84a52b4efb/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/522d96a5707c154b15960db186c03b84a52b4efb/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/522d96a5707c154b15960db186c03b84a52b4efb/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/522d96a5707c154b15960db186c03b84a52b4efb/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/522d96a5707c154b15960db186c03b84a52b4efb/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 match fields.kind() {
1043 ty::Tuple(fields) => {
1044 let mut first = true;
1045 if !fields.is_empty() {
1046 self.write_fmt(format_args!(" "))write!(self, " ")?;
1047 }
1048 for field in fields.iter() {
1049 if first {
1050 first = false;
1051 } else {
1052 self.write_fmt(format_args!(", "))write!(self, ", ")?;
1053 }
1054
1055 match field.kind() {
1056 ty::Adt(def_, args_)
1057 if let Some(FieldInfo { variant, name, .. }) =
1058 def_.field_representing_type_info(self.tcx(), *args_) =>
1059 {
1060 if true {
if !variant.is_none() {
::core::panicking::panic("assertion failed: variant.is_none()")
};
};debug_assert!(variant.is_none());
1062 self.write_fmt(format_args!("{0}", name))write!(self, "{name}")?;
1063 }
1064 _ => self.print_type(field)?,
1065 }
1066 }
1067 if !fields.is_empty() {
1068 self.write_fmt(format_args!(" "))write!(self, " ")?;
1069 }
1070 }
1071
1072 _ => self.print_type(fields)?,
1073 }
1074 self.write_fmt(format_args!("}})"))write!(self, "}})")?;
1075 }
1076 }
1077
1078 Ok(())
1079 }
1080
1081 fn pretty_print_opaque_impl_type(
1082 &mut self,
1083 def_id: DefId,
1084 args: ty::GenericArgs<'tcx>,
1085 ) -> Result<(), PrintError> {
1086 let tcx = self.tcx();
1087
1088 let bounds = tcx.explicit_item_bounds(def_id);
1091
1092 let mut traits = FxIndexMap::default();
1093 let mut fn_traits = FxIndexMap::default();
1094 let mut lifetimes = SmallVec::<[ty::Region<'tcx>; 1]>::new();
1095
1096 let mut has_sized_bound = false;
1097 let mut has_negative_sized_bound = false;
1098 let mut has_meta_sized_bound = false;
1099
1100 for (predicate, _) in
1101 bounds.iter_instantiated_copied(tcx, args).map(Unnormalized::skip_norm_wip)
1102 {
1103 let bound_predicate = predicate.kind();
1104
1105 match bound_predicate.skip_binder() {
1106 ty::ClauseKind::Trait(pred) => {
1107 match tcx.as_lang_item(pred.def_id()) {
1110 Some(LangItem::Sized) => match pred.polarity {
1111 ty::ClausePolarity::Positive => {
1112 has_sized_bound = true;
1113 continue;
1114 }
1115 ty::ClausePolarity::Negative => has_negative_sized_bound = true,
1116 },
1117 Some(LangItem::MetaSized) => {
1118 has_meta_sized_bound = true;
1119 continue;
1120 }
1121 Some(LangItem::PointeeSized) => {
1122 ::rustc_span::macros::bug_impl(None,
format_args!("`PointeeSized` is removed during lowering"),
Location::caller());bug!("`PointeeSized` is removed during lowering");
1123 }
1124 _ => (),
1125 }
1126
1127 self.insert_trait_and_projection(
1128 bound_predicate.rebind(pred),
1129 None,
1130 &mut traits,
1131 &mut fn_traits,
1132 );
1133 }
1134 ty::ClauseKind::Projection(pred) => {
1135 let proj = bound_predicate.rebind(pred);
1136 let trait_ref = proj.map_bound(|proj| TraitClause {
1137 trait_ref: proj.projection_term.trait_ref(tcx),
1138 polarity: ty::ClausePolarity::Positive,
1139 });
1140
1141 self.insert_trait_and_projection(
1142 trait_ref,
1143 Some((proj.item_def_id(), proj.term())),
1144 &mut traits,
1145 &mut fn_traits,
1146 );
1147 }
1148 ty::ClauseKind::TypeOutlives(outlives) => {
1149 lifetimes.push(outlives.1);
1150 }
1151 _ => {}
1152 }
1153 }
1154
1155 self.write_fmt(format_args!("impl "))write!(self, "impl ")?;
1156
1157 let mut first = true;
1158 let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !has_sized_bound;
1160
1161 for ((bound_args_and_self_ty, is_async), entry) in fn_traits {
1162 self.write_fmt(format_args!("{0}", if first { "" } else { " + " }))write!(self, "{}", if first { "" } else { " + " })?;
1163 self.write_fmt(format_args!("{0}", if paren_needed { "(" } else { "" }))write!(self, "{}", if paren_needed { "(" } else { "" })?;
1164
1165 let trait_def_id = if is_async {
1166 tcx.async_fn_trait_kind_to_def_id(entry.kind).expect("expected AsyncFn lang items")
1167 } else {
1168 tcx.fn_trait_kind_to_def_id(entry.kind).expect("expected Fn lang items")
1169 };
1170
1171 if let Some(return_ty) = entry.return_ty {
1172 self.wrap_binder(
1173 &bound_args_and_self_ty,
1174 WrapBinderMode::ForAll,
1175 |(args, _), p| {
1176 p.write_fmt(format_args!("{0}", tcx.item_name(trait_def_id)))write!(p, "{}", tcx.item_name(trait_def_id))?;
1177 p.write_fmt(format_args!("("))write!(p, "(")?;
1178
1179 for (idx, ty) in args.iter().enumerate() {
1180 if idx > 0 {
1181 p.write_fmt(format_args!(", "))write!(p, ", ")?;
1182 }
1183 ty.print(p)?;
1184 }
1185
1186 p.write_fmt(format_args!(")"))write!(p, ")")?;
1187 if let Some(ty) = return_ty.skip_binder().as_type() {
1188 if !ty.is_unit() {
1189 p.write_fmt(format_args!(" -> "))write!(p, " -> ")?;
1190 return_ty.print(p)?;
1191 }
1192 }
1193 p.write_fmt(format_args!("{0}", if paren_needed { ")" } else { "" }))write!(p, "{}", if paren_needed { ")" } else { "" })?;
1194
1195 first = false;
1196 Ok(())
1197 },
1198 )?;
1199 } else {
1200 traits.insert(
1202 bound_args_and_self_ty.map_bound(|(args, self_ty)| ty::TraitClause {
1203 polarity: ty::ClausePolarity::Positive,
1204 trait_ref: ty::TraitRef::new(
1205 tcx,
1206 trait_def_id,
1207 [self_ty, Ty::new_tup(tcx, args)],
1208 ),
1209 }),
1210 FxIndexMap::default(),
1211 );
1212 }
1213 }
1214
1215 for (trait_pred, assoc_items) in traits {
1217 self.write_fmt(format_args!("{0}", if first { "" } else { " + " }))write!(self, "{}", if first { "" } else { " + " })?;
1218
1219 self.wrap_binder(&trait_pred, WrapBinderMode::ForAll, |trait_pred, p| {
1220 if trait_pred.polarity == ty::ClausePolarity::Negative {
1221 p.write_fmt(format_args!("!"))write!(p, "!")?;
1222 }
1223 trait_pred.trait_ref.print_only_trait_name().print(p)?;
1224
1225 let generics = tcx.generics_of(trait_pred.def_id());
1226 let own_args =
1227 generics.own_args_no_defaults(tcx, trait_pred.trait_ref.args.as_slice());
1228
1229 if !own_args.is_empty() || !assoc_items.is_empty() {
1230 let mut first = true;
1231
1232 for ty in own_args {
1233 if first {
1234 p.write_fmt(format_args!("<"))write!(p, "<")?;
1235 first = false;
1236 } else {
1237 p.write_fmt(format_args!(", "))write!(p, ", ")?;
1238 }
1239 ty.print(p)?;
1240 }
1241
1242 for (assoc_item_def_id, term) in assoc_items {
1243 if first {
1244 p.write_fmt(format_args!("<"))write!(p, "<")?;
1245 first = false;
1246 } else {
1247 p.write_fmt(format_args!(", "))write!(p, ", ")?;
1248 }
1249
1250 p.write_fmt(format_args!("{0} = ",
tcx.associated_item(assoc_item_def_id).name()))write!(p, "{} = ", tcx.associated_item(assoc_item_def_id).name())?;
1251
1252 match term.skip_binder().kind() {
1253 TermKind::Ty(ty) => ty.print(p)?,
1254 TermKind::Const(c) => c.print(p)?,
1255 };
1256 }
1257
1258 if !first {
1259 p.write_fmt(format_args!(">"))write!(p, ">")?;
1260 }
1261 }
1262
1263 first = false;
1264 Ok(())
1265 })?;
1266 }
1267
1268 let using_sized_hierarchy = self.tcx().features().sized_hierarchy();
1269 let add_sized = has_sized_bound && (first || has_negative_sized_bound);
1270 let add_maybe_sized =
1271 has_meta_sized_bound && !has_negative_sized_bound && !using_sized_hierarchy;
1272 let has_pointee_sized_bound =
1274 !has_sized_bound && !has_meta_sized_bound && !has_negative_sized_bound;
1275 if add_sized || add_maybe_sized {
1276 if !first {
1277 self.write_fmt(format_args!(" + "))write!(self, " + ")?;
1278 }
1279 if add_maybe_sized {
1280 self.write_fmt(format_args!("?"))write!(self, "?")?;
1281 }
1282 self.write_fmt(format_args!("Sized"))write!(self, "Sized")?;
1283 } else if has_meta_sized_bound && using_sized_hierarchy {
1284 if !first {
1285 self.write_fmt(format_args!(" + "))write!(self, " + ")?;
1286 }
1287 self.write_fmt(format_args!("MetaSized"))write!(self, "MetaSized")?;
1288 } else if has_pointee_sized_bound && using_sized_hierarchy {
1289 if !first {
1290 self.write_fmt(format_args!(" + "))write!(self, " + ")?;
1291 }
1292 self.write_fmt(format_args!("PointeeSized"))write!(self, "PointeeSized")?;
1293 }
1294
1295 if !with_forced_trimmed_paths() {
1296 for re in lifetimes {
1297 self.write_fmt(format_args!(" + "))write!(self, " + ")?;
1298 self.print_region(re)?;
1299 }
1300 }
1301
1302 Ok(())
1303 }
1304
1305 fn insert_trait_and_projection(
1308 &mut self,
1309 trait_pred: ty::PolyTraitClause<'tcx>,
1310 proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
1311 traits: &mut FxIndexMap<
1312 ty::PolyTraitClause<'tcx>,
1313 FxIndexMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,
1314 >,
1315 fn_traits: &mut FxIndexMap<
1316 (ty::Binder<'tcx, (&'tcx ty::List<Ty<'tcx>>, Ty<'tcx>)>, bool),
1317 OpaqueFnEntry<'tcx>,
1318 >,
1319 ) {
1320 let tcx = self.tcx();
1321 let trait_def_id = trait_pred.def_id();
1322
1323 let fn_trait_and_async = if let Some(kind) = tcx.fn_trait_kind_from_def_id(trait_def_id) {
1324 Some((kind, false))
1325 } else if let Some(kind) = tcx.async_fn_trait_kind_from_def_id(trait_def_id) {
1326 Some((kind, true))
1327 } else {
1328 None
1329 };
1330
1331 if trait_pred.polarity() == ty::ClausePolarity::Positive
1332 && let Some((kind, is_async)) = fn_trait_and_async
1333 && let ty::Tuple(types) = *trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
1334 {
1335 let entry = fn_traits
1336 .entry((trait_pred.rebind((types, trait_pred.skip_binder().self_ty())), is_async))
1337 .or_insert_with(|| OpaqueFnEntry { kind, return_ty: None });
1338 if kind.extends(entry.kind) {
1339 entry.kind = kind;
1340 }
1341 if let Some((proj_def_id, proj_ty)) = proj_ty
1342 && tcx.item_name(proj_def_id) == sym::Output
1343 {
1344 entry.return_ty = Some(proj_ty);
1345 }
1346 return;
1347 }
1348
1349 traits.entry(trait_pred).or_default().extend(proj_ty);
1351 }
1352
1353 fn pretty_print_inherent_projection(
1354 &mut self,
1355 alias_term: ty::AliasTerm<'tcx>,
1356 ) -> Result<(), PrintError> {
1357 let alias_def_id = alias_term.expect_inherent_def_id();
1358 let def_key = self.tcx().def_key(alias_def_id);
1359 self.print_path_with_generic_args(
1360 |p| {
1361 p.print_path_with_simple(
1362 |p| p.print_path_with_qualified(alias_term.self_ty(), None),
1363 &def_key.disambiguated_data,
1364 )
1365 },
1366 self.tcx().mk_args(&alias_term.args.as_slice()[1..]),
1367 )
1368 }
1369
1370 fn pretty_print_rpitit(
1371 &mut self,
1372 def_id: DefId,
1373 args: ty::GenericArgs<'tcx>,
1374 ) -> Result<(), PrintError> {
1375 let fn_args = if self.tcx().features().return_type_notation()
1376 && let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, .. }) =
1377 self.tcx().opt_rpitit_info(def_id)
1378 && let ty::Alias(_, alias_ty) =
1379 self.tcx().fn_sig(fn_def_id).skip_binder().output().skip_binder().kind()
1380 && let Some(projection_ty) = alias_ty.try_to_projection()
1381 && projection_ty.kind == def_id
1382 && let generics = self.tcx().generics_of(fn_def_id)
1383 && generics
1385 .own_params
1386 .iter()
1387 .all(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
ty::GenericParamDefKind::Lifetime => true,
_ => false,
}matches!(param.kind, ty::GenericParamDefKind::Lifetime))
1388 {
1389 let num_args = generics.count();
1390 Some((fn_def_id, self.tcx().mk_args(&args.as_slice()[..num_args])))
1391 } else {
1392 None
1393 };
1394
1395 match (fn_args, RTN_MODE.with(|c| c.get())) {
1396 (Some((fn_def_id, fn_args)), RtnMode::ForDiagnostic) => {
1397 self.pretty_print_opaque_impl_type(def_id, args)?;
1398 self.write_fmt(format_args!(" {{ "))write!(self, " {{ ")?;
1399 self.print_def_path(fn_def_id, fn_args)?;
1400 self.write_fmt(format_args!("(..) }}"))write!(self, "(..) }}")?;
1401 }
1402 (Some((fn_def_id, fn_args)), RtnMode::ForSuggestion) => {
1403 self.print_def_path(fn_def_id, fn_args)?;
1404 self.write_fmt(format_args!("(..)"))write!(self, "(..)")?;
1405 }
1406 _ => {
1407 self.pretty_print_opaque_impl_type(def_id, args)?;
1408 }
1409 }
1410
1411 Ok(())
1412 }
1413
1414 fn ty_infer_name(&self, _: ty::TyVid) -> Option<Symbol> {
1415 None
1416 }
1417
1418 fn const_infer_name(&self, _: ty::ConstVid) -> Option<Symbol> {
1419 None
1420 }
1421
1422 fn pretty_print_dyn_existential(
1423 &mut self,
1424 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1425 ) -> Result<(), PrintError> {
1426 let mut first = true;
1428
1429 if let Some(bound_principal) = predicates.principal() {
1430 self.wrap_binder(&bound_principal, WrapBinderMode::ForAll, |principal, p| {
1431 p.print_def_path(principal.def_id, ty::GenericArgs::empty())?;
1432
1433 let mut resugared = false;
1434
1435 let fn_trait_kind = p.tcx().fn_trait_kind_from_def_id(principal.def_id);
1437 if !p.should_print_verbose() && fn_trait_kind.is_some() {
1438 if let ty::Tuple(tys) = principal.args.type_at(0).kind() {
1439 let mut projections = predicates.projection_bounds();
1440 if let (Some(proj), None) = (projections.next(), projections.next()) {
1441 p.pretty_print_fn_sig(
1442 tys,
1443 false,
1444 None,
1446 proj.skip_binder().term.as_type().expect("Return type was a const"),
1447 )?;
1448 resugared = true;
1449 }
1450 }
1451 }
1452
1453 if !resugared {
1456 let principal_with_self =
1457 principal.with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self);
1458
1459 let args = p
1460 .tcx()
1461 .generics_of(principal_with_self.def_id)
1462 .own_args_no_defaults(p.tcx(), principal_with_self.args.as_slice());
1463
1464 let bound_principal_with_self = bound_principal
1465 .with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self);
1466
1467 let clause: ty::Clause<'tcx> = bound_principal_with_self.upcast(p.tcx());
1468 let super_projections: Vec<_> = elaborate::elaborate(p.tcx(), [clause])
1469 .filter_only_self()
1470 .filter_map(|clause| clause.as_projection_clause())
1471 .collect();
1472
1473 let mut projections: Vec<_> = predicates
1474 .projection_bounds()
1475 .filter(|&proj| {
1476 let proj_is_implied = super_projections.iter().any(|&super_proj| {
1478 let super_proj = super_proj.map_bound(|super_proj| {
1479 ty::ExistentialProjection::erase_self_ty(p.tcx(), super_proj)
1480 });
1481
1482 let proj = p.tcx().erase_and_anonymize_regions(proj);
1487 let super_proj = p.tcx().erase_and_anonymize_regions(super_proj);
1488
1489 proj == super_proj
1490 });
1491 !proj_is_implied
1492 })
1493 .map(|proj| {
1494 proj.skip_binder()
1497 })
1498 .collect();
1499
1500 projections
1501 .sort_by_cached_key(|proj| p.tcx().item_name(proj.def_id).to_string());
1502
1503 if !args.is_empty() || !projections.is_empty() {
1504 p.generic_delimiters(|p| {
1505 p.comma_sep(args.iter().copied())?;
1506 if !args.is_empty() && !projections.is_empty() {
1507 p.write_fmt(format_args!(", "))write!(p, ", ")?;
1508 }
1509 p.comma_sep(projections.iter().copied())
1510 })?;
1511 }
1512 }
1513 Ok(())
1514 })?;
1515
1516 first = false;
1517 }
1518
1519 let mut auto_traits: Vec<_> = predicates.auto_traits().collect();
1523
1524 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)));
1532
1533 for def_id in auto_traits {
1534 if !first {
1535 self.write_fmt(format_args!(" + "))write!(self, " + ")?;
1536 }
1537 first = false;
1538
1539 self.print_def_path(def_id, ty::GenericArgs::empty())?;
1540 }
1541
1542 Ok(())
1543 }
1544
1545 fn pretty_print_fn_sig(
1546 &mut self,
1547 inputs: &[Ty<'tcx>],
1548 c_variadic: bool,
1549 splatted: Option<u8>,
1550 output: Ty<'tcx>,
1551 ) -> Result<(), PrintError> {
1552 self.write_fmt(format_args!("("))write!(self, "(")?;
1553 let splatted_arg_index = splatted.map(usize::from);
1554 let mut input_iter = inputs.iter().copied();
1555 if let Some(index) = splatted_arg_index {
1556 self.comma_sep((&mut input_iter).take(index))?;
1557 if index > 0 {
1561 if self.comma_sep_has_space() {
1562 self.write_fmt(format_args!(", "))write!(self, ", ")?;
1563 } else {
1564 self.write_fmt(format_args!(","))write!(self, ",")?;
1565 }
1566 }
1567 self.write_fmt(format_args!("#[rustc_splat] "))write!(self, "#[rustc_splat] ")?;
1568 self.comma_sep(input_iter)?;
1569 } else {
1570 self.comma_sep(input_iter)?;
1571 }
1572 if c_variadic {
1573 if !inputs.is_empty() {
1574 self.write_fmt(format_args!(", "))write!(self, ", ")?;
1577 }
1578 self.write_fmt(format_args!("..."))write!(self, "...")?;
1579 }
1580 self.write_fmt(format_args!(")"))write!(self, ")")?;
1581 if !output.is_unit() {
1582 self.write_fmt(format_args!(" -> "))write!(self, " -> ")?;
1583 output.print(self)?;
1584 }
1585
1586 Ok(())
1587 }
1588
1589 fn pretty_print_const(
1590 &mut self,
1591 ct: ty::Const<'tcx>,
1592 print_ty: bool,
1593 ) -> Result<(), PrintError> {
1594 if self.should_print_verbose() {
1595 self.write_fmt(format_args!("{0:?}", ct))write!(self, "{ct:?}")?;
1596 return Ok(());
1597 }
1598
1599 match ct.kind() {
1600 ty::ConstKind::Alias(_, ty::AliasConst { kind, args, .. }) => {
1601 match kind {
1602 ty::AliasConstKind::Projection { def_id }
1603 | ty::AliasConstKind::InherentSelf { def_id }
1604 | ty::AliasConstKind::InherentImpl { def_id }
1605 | ty::AliasConstKind::Free { def_id } => {
1606 self.pretty_print_value_path(def_id, args)?;
1607 }
1608 ty::AliasConstKind::Anon { def_id } => {
1609 if def_id.is_local()
1610 && let span = self.tcx().def_span(def_id)
1611 && let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
1612 {
1613 self.write_fmt(format_args!("{0}", snip))write!(self, "{snip}")?;
1614 } else {
1615 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!(
1623 self,
1624 "{}::{}",
1625 self.tcx().crate_name(def_id.krate),
1626 self.tcx().def_path(def_id).to_string_no_crate_verbose()
1627 )?;
1628 }
1629 }
1630 }
1631 }
1632 ty::ConstKind::Infer(infer_ct) => match infer_ct {
1633 ty::InferConst::Var(ct_vid) if let Some(name) = self.const_infer_name(ct_vid) => {
1634 self.write_fmt(format_args!("{0}", name))write!(self, "{name}")?;
1635 }
1636 _ => self.write_fmt(format_args!("_"))write!(self, "_")?,
1637 },
1638 ty::ConstKind::Param(ParamConst { name, .. }) => self.write_fmt(format_args!("{0}", name))write!(self, "{name}")?,
1639 ty::ConstKind::Value(cv) => {
1640 return self.pretty_print_const_valtree(cv, print_ty);
1641 }
1642
1643 ty::ConstKind::Bound(debruijn, bound_var) => {
1644 rustc_type_ir::debug_bound_var(self, debruijn, bound_var)?
1645 }
1646 ty::ConstKind::Placeholder(placeholder) => self.write_fmt(format_args!("{0:?}", placeholder))write!(self, "{placeholder:?}")?,
1647 ty::ConstKind::Expr(expr) => self.pretty_print_const_expr(expr, print_ty)?,
1650 ty::ConstKind::Error(_) => self.write_fmt(format_args!("{{const error}}"))write!(self, "{{const error}}")?,
1651 };
1652 Ok(())
1653 }
1654
1655 fn pretty_print_const_expr(
1656 &mut self,
1657 expr: Expr<'tcx>,
1658 print_ty: bool,
1659 ) -> Result<(), PrintError> {
1660 match expr.kind {
1661 ty::ExprKind::Binop(op) => {
1662 let (_, _, c1, c2) = expr.binop_args();
1663
1664 let precedence = |binop: crate::mir::BinOp| binop.to_hir_binop().precedence();
1665 let op_precedence = precedence(op);
1666 let formatted_op = op.to_hir_binop().as_str();
1667 let (lhs_parenthesized, rhs_parenthesized) = match (c1.kind(), c2.kind()) {
1668 (
1669 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),
1670 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),
1671 ) => (precedence(lhs_op) < op_precedence, precedence(rhs_op) < op_precedence),
1672 (
1673 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),
1674 ty::ConstKind::Expr(_),
1675 ) => (precedence(lhs_op) < op_precedence, true),
1676 (
1677 ty::ConstKind::Expr(_),
1678 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),
1679 ) => (true, precedence(rhs_op) < op_precedence),
1680 (ty::ConstKind::Expr(_), ty::ConstKind::Expr(_)) => (true, true),
1681 (
1682 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),
1683 _,
1684 ) => (precedence(lhs_op) < op_precedence, false),
1685 (
1686 _,
1687 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),
1688 ) => (false, precedence(rhs_op) < op_precedence),
1689 (ty::ConstKind::Expr(_), _) => (true, false),
1690 (_, ty::ConstKind::Expr(_)) => (false, true),
1691 _ => (false, false),
1692 };
1693
1694 self.maybe_parenthesized(
1695 |this| this.pretty_print_const(c1, print_ty),
1696 lhs_parenthesized,
1697 )?;
1698 self.write_fmt(format_args!(" {0} ", formatted_op))write!(self, " {formatted_op} ")?;
1699 self.maybe_parenthesized(
1700 |this| this.pretty_print_const(c2, print_ty),
1701 rhs_parenthesized,
1702 )?;
1703 }
1704 ty::ExprKind::UnOp(op) => {
1705 let (_, ct) = expr.unop_args();
1706
1707 use crate::mir::UnOp;
1708 let formatted_op = match op {
1709 UnOp::Not => "!",
1710 UnOp::Neg => "-",
1711 UnOp::PtrMetadata => "PtrMetadata",
1712 };
1713 let parenthesized = match ct.kind() {
1714 _ if op == UnOp::PtrMetadata => true,
1715 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::UnOp(c_op), .. }) => {
1716 c_op != op
1717 }
1718 ty::ConstKind::Expr(_) => true,
1719 _ => false,
1720 };
1721 self.write_fmt(format_args!("{0}", formatted_op))write!(self, "{formatted_op}")?;
1722 self.maybe_parenthesized(
1723 |this| this.pretty_print_const(ct, print_ty),
1724 parenthesized,
1725 )?
1726 }
1727 ty::ExprKind::FunctionCall => {
1728 let (_, fn_def, fn_args) = expr.call_args();
1729
1730 self.write_fmt(format_args!("("))write!(self, "(")?;
1731 self.pretty_print_const(fn_def, print_ty)?;
1732 self.write_fmt(format_args!(")("))write!(self, ")(")?;
1733 self.comma_sep(fn_args.into_iter())?;
1734 self.write_fmt(format_args!(")"))write!(self, ")")?;
1735 }
1736 ty::ExprKind::Cast(kind) => {
1737 let (_, value, to_ty) = expr.cast_args();
1738
1739 use ty::abstract_const::CastKind;
1740 if kind == CastKind::As || (kind == CastKind::Use && self.should_print_verbose()) {
1741 let parenthesized = match value.kind() {
1742 ty::ConstKind::Expr(ty::Expr {
1743 kind: ty::ExprKind::Cast { .. }, ..
1744 }) => false,
1745 ty::ConstKind::Expr(_) => true,
1746 _ => false,
1747 };
1748 self.maybe_parenthesized(
1749 |this| {
1750 this.typed_value(
1751 |this| this.pretty_print_const(value, print_ty),
1752 |this| this.pretty_print_type(to_ty),
1753 " as ",
1754 )
1755 },
1756 parenthesized,
1757 )?;
1758 } else {
1759 self.pretty_print_const(value, print_ty)?
1760 }
1761 }
1762 }
1763 Ok(())
1764 }
1765
1766 fn pretty_print_const_scalar(
1767 &mut self,
1768 scalar: Scalar,
1769 ty: Ty<'tcx>,
1770 ) -> Result<(), PrintError> {
1771 match scalar {
1772 Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty),
1773 Scalar::Int(int) => {
1774 self.pretty_print_const_scalar_int(int, ty, true)
1775 }
1776 }
1777 }
1778
1779 fn pretty_print_const_scalar_ptr(
1780 &mut self,
1781 ptr: Pointer,
1782 ty: Ty<'tcx>,
1783 ) -> Result<(), PrintError> {
1784 let (prov, offset) = ptr.prov_and_relative_offset();
1785 match ty.kind() {
1786 ty::Ref(_, inner, _) => {
1788 if let ty::Array(elem, ct_len) = inner.kind()
1789 && let ty::Uint(ty::UintTy::U8) = elem.kind()
1790 && let Some(len) = ct_len.try_to_target_usize(self.tcx())
1791 {
1792 match self.tcx().try_get_global_alloc(prov.alloc_id()) {
1793 Some(GlobalAlloc::Memory(alloc)) => {
1794 let range = AllocRange { start: offset, size: Size::from_bytes(len) };
1795 if let Ok(byte_str) =
1796 alloc.inner().get_bytes_strip_provenance(&self.tcx(), range)
1797 {
1798 self.pretty_print_byte_str(byte_str)?;
1799 } else {
1800 self.write_fmt(format_args!("<too short allocation>"))write!(self, "<too short allocation>")?;
1801 }
1802 }
1803 Some(GlobalAlloc::Static(def_id)) => {
1805 self.write_fmt(format_args!("<static({0:?})>", def_id))write!(self, "<static({def_id:?})>")?;
1806 }
1807 Some(GlobalAlloc::Function { .. }) => self.write_fmt(format_args!("<function>"))write!(self, "<function>")?,
1808 Some(GlobalAlloc::VTable(..)) => self.write_fmt(format_args!("<vtable>"))write!(self, "<vtable>")?,
1809 Some(GlobalAlloc::TypeId { .. }) => self.write_fmt(format_args!("<typeid>"))write!(self, "<typeid>")?,
1810 None => self.write_fmt(format_args!("<dangling pointer>"))write!(self, "<dangling pointer>")?,
1811 }
1812 return Ok(());
1813 }
1814 }
1815 ty::FnPtr(..) => {
1816 if let Some(GlobalAlloc::Function { instance, .. }) =
1819 self.tcx().try_get_global_alloc(prov.alloc_id())
1820 {
1821 self.typed_value(
1822 |this| this.pretty_print_value_path(instance.def_id(), instance.args),
1823 |this| this.print_type(ty),
1824 " as ",
1825 )?;
1826 return Ok(());
1827 }
1828 }
1829 _ => {}
1830 }
1831 self.pretty_print_const_pointer(ptr, ty)?;
1833 Ok(())
1834 }
1835
1836 fn pretty_print_const_scalar_int(
1837 &mut self,
1838 int: ScalarInt,
1839 ty: Ty<'tcx>,
1840 print_ty: bool,
1841 ) -> Result<(), PrintError> {
1842 match ty.kind() {
1843 ty::Bool if int == ScalarInt::FALSE => self.write_fmt(format_args!("false"))write!(self, "false")?,
1845 ty::Bool if int == ScalarInt::TRUE => self.write_fmt(format_args!("true"))write!(self, "true")?,
1846 ty::Float(fty) => match fty {
1848 ty::FloatTy::F16 => {
1849 let val = Half::try_from(int).unwrap();
1850 self.write_fmt(format_args!("{0}{1}f16", val,
if val.is_finite() { "" } else { "_" }))write!(self, "{}{}f16", val, if val.is_finite() { "" } else { "_" })?;
1851 }
1852 ty::FloatTy::F32 => {
1853 let val = Single::try_from(int).unwrap();
1854 self.write_fmt(format_args!("{0}{1}f32", val,
if val.is_finite() { "" } else { "_" }))write!(self, "{}{}f32", val, if val.is_finite() { "" } else { "_" })?;
1855 }
1856 ty::FloatTy::F64 => {
1857 let val = Double::try_from(int).unwrap();
1858 self.write_fmt(format_args!("{0}{1}f64", val,
if val.is_finite() { "" } else { "_" }))write!(self, "{}{}f64", val, if val.is_finite() { "" } else { "_" })?;
1859 }
1860 ty::FloatTy::F128 => {
1861 let val = Quad::try_from(int).unwrap();
1862 self.write_fmt(format_args!("{0}{1}f128", val,
if val.is_finite() { "" } else { "_" }))write!(self, "{}{}f128", val, if val.is_finite() { "" } else { "_" })?;
1863 }
1864 },
1865 ty::Uint(_) | ty::Int(_) => {
1867 let int =
1868 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());
1869 if print_ty { self.write_fmt(format_args!("{0:#?}", int))write!(self, "{int:#?}")? } else { self.write_fmt(format_args!("{0:?}", int))write!(self, "{int:?}")? }
1870 }
1871 ty::Char if char::try_from(int).is_ok() => {
1873 self.write_fmt(format_args!("{0:?}", char::try_from(int).unwrap()))write!(self, "{:?}", char::try_from(int).unwrap())?;
1874 }
1875 ty::Ref(..) | ty::RawPtr(_, _) | ty::FnPtr(..) => {
1877 let data = int.to_bits(self.tcx().data_layout.pointer_size());
1878 self.typed_value(
1879 |this| {
1880 this.write_fmt(format_args!("0x{0:x}", data))write!(this, "0x{data:x}")?;
1881 Ok(())
1882 },
1883 |this| this.print_type(ty),
1884 " as ",
1885 )?;
1886 }
1887 ty::Pat(base_ty, pat) if self.tcx().validate_scalar_in_layout(int, ty) => {
1888 self.pretty_print_const_scalar_int(int, *base_ty, print_ty)?;
1889 self.write_fmt(format_args!(" is {0:?}", pat))write!(self, " is {pat:?}")?;
1890 }
1891 _ => {
1893 let print = |this: &mut Self| {
1894 if int.size() == Size::ZERO {
1895 this.write_fmt(format_args!("transmute(())"))write!(this, "transmute(())")?;
1896 } else {
1897 this.write_fmt(format_args!("transmute(0x{0:x})", int))write!(this, "transmute(0x{int:x})")?;
1898 }
1899 Ok(())
1900 };
1901 if print_ty {
1902 self.typed_value(print, |this| this.print_type(ty), ": ")?
1903 } else {
1904 print(self)?
1905 };
1906 }
1907 }
1908 Ok(())
1909 }
1910
1911 fn pretty_print_const_pointer<Prov: Provenance>(
1914 &mut self,
1915 _: Pointer<Prov>,
1916 ty: Ty<'tcx>,
1917 ) -> Result<(), PrintError> {
1918 self.typed_value(
1919 |this| {
1920 this.write_str("&_")?;
1921 Ok(())
1922 },
1923 |this| this.print_type(ty),
1924 ": ",
1925 )
1926 }
1927
1928 fn pretty_print_byte_str(&mut self, byte_str: &'tcx [u8]) -> Result<(), PrintError> {
1929 self.write_fmt(format_args!("b\"{0}\"", byte_str.escape_ascii()))write!(self, "b\"{}\"", byte_str.escape_ascii())?;
1930 Ok(())
1931 }
1932
1933 fn pretty_print_const_valtree(
1934 &mut self,
1935 cv: ty::Value<'tcx>,
1936 print_ty: bool,
1937 ) -> Result<(), PrintError> {
1938 if with_reduced_queries() || self.should_print_verbose() {
1939 self.write_fmt(format_args!("ValTree({0:?}: ", cv.valtree))write!(self, "ValTree({:?}: ", cv.valtree)?;
1940 cv.ty.print(self)?;
1941 self.write_fmt(format_args!(")"))write!(self, ")")?;
1942 return Ok(());
1943 }
1944
1945 let u8_type = self.tcx().types.u8;
1946 match (*cv.valtree, *cv.ty.kind()) {
1947 (ty::ValTreeKind::Branch(_), ty::Ref(_, inner_ty, _)) => match inner_ty.kind() {
1948 ty::Slice(t) if *t == u8_type => {
1949 let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {
1950 ::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!(
1951 "expected to convert valtree {:?} to raw bytes for type {:?}",
1952 cv.valtree,
1953 t
1954 )
1955 });
1956 return self.pretty_print_byte_str(bytes);
1957 }
1958 ty::Str => {
1959 let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {
1960 ::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)
1961 });
1962 self.write_fmt(format_args!("{0:?}", String::from_utf8_lossy(bytes)))write!(self, "{:?}", String::from_utf8_lossy(bytes))?;
1963 return Ok(());
1964 }
1965 _ => {
1966 let cv = ty::Value { valtree: cv.valtree, ty: inner_ty };
1967 self.write_fmt(format_args!("&"))write!(self, "&")?;
1968 self.pretty_print_const_valtree(cv, print_ty)?;
1969 return Ok(());
1970 }
1971 },
1972 (ty::ValTreeKind::Branch(_), ty::Array(t, _))
1974 if t == u8_type
1975 && let Some(bytes) = cv.try_to_raw_bytes(self.tcx()) =>
1976 {
1977 self.write_fmt(format_args!("*"))write!(self, "*")?;
1978 self.pretty_print_byte_str(bytes)?;
1979 return Ok(());
1980 }
1981 (ty::ValTreeKind::Branch(fields), ty::Array(..) | ty::Tuple(..)) => {
1983 let fields_iter = fields.iter();
1984
1985 match *cv.ty.kind() {
1986 ty::Array(..) => {
1987 self.write_fmt(format_args!("["))write!(self, "[")?;
1988 self.comma_sep(fields_iter)?;
1989 self.write_fmt(format_args!("]"))write!(self, "]")?;
1990 }
1991 ty::Tuple(..) => {
1992 self.write_fmt(format_args!("("))write!(self, "(")?;
1993 self.comma_sep(fields_iter)?;
1994 if fields.len() == 1 {
1995 self.write_fmt(format_args!(","))write!(self, ",")?;
1996 }
1997 self.write_fmt(format_args!(")"))write!(self, ")")?;
1998 }
1999 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
2000 }
2001 return Ok(());
2002 }
2003 (ty::ValTreeKind::Branch(_), ty::Adt(def, args)) => {
2004 let contents = cv.destructure_adt_const();
2005 let fields = contents.fields.iter().copied();
2006
2007 if def.variants().is_empty() {
2008 self.typed_value(
2009 |this| {
2010 this.write_fmt(format_args!("unreachable()"))write!(this, "unreachable()")?;
2011 Ok(())
2012 },
2013 |this| this.print_type(cv.ty),
2014 ": ",
2015 )?;
2016 } else {
2017 let variant_idx = contents.variant;
2018 let variant_def = &def.variant(variant_idx);
2019 self.pretty_print_value_path(variant_def.def_id, args)?;
2020 match variant_def.ctor_kind() {
2021 Some(CtorKind::Const) => {}
2022 Some(CtorKind::Fn) => {
2023 self.write_fmt(format_args!("("))write!(self, "(")?;
2024 self.comma_sep(fields)?;
2025 self.write_fmt(format_args!(")"))write!(self, ")")?;
2026 }
2027 None => {
2028 self.write_fmt(format_args!(" {{ "))write!(self, " {{ ")?;
2029 let mut first = true;
2030 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
2031 if !first {
2032 self.write_fmt(format_args!(", "))write!(self, ", ")?;
2035 }
2036 self.write_fmt(format_args!("{0}: ", field_def.name))write!(self, "{}: ", field_def.name)?;
2037 field.print(self)?;
2038 first = false;
2039 }
2040 self.write_fmt(format_args!(" }}"))write!(self, " }}")?;
2041 }
2042 }
2043 }
2044 return Ok(());
2045 }
2046 (ty::ValTreeKind::Leaf(leaf), ty::Ref(_, inner_ty, _)) => {
2047 self.write_fmt(format_args!("&"))write!(self, "&")?;
2048 return self.pretty_print_const_scalar_int(*leaf, inner_ty, print_ty);
2049 }
2050 (ty::ValTreeKind::Leaf(leaf), _) => {
2051 return self.pretty_print_const_scalar_int(*leaf, cv.ty, print_ty);
2052 }
2053 (_, ty::FnDef(def_id, args)) => {
2054 self.pretty_print_value_path(def_id, args.no_bound_vars().unwrap())?;
2057 return Ok(());
2058 }
2059 _ => {}
2062 }
2063
2064 if cv.valtree.is_zst() {
2066 self.write_fmt(format_args!("<ZST>"))write!(self, "<ZST>")?;
2067 } else {
2068 self.write_fmt(format_args!("{0:?}", cv.valtree))write!(self, "{:?}", cv.valtree)?;
2069 }
2070 if print_ty {
2071 self.write_fmt(format_args!(": "))write!(self, ": ")?;
2072 cv.ty.print(self)?;
2073 }
2074 Ok(())
2075 }
2076
2077 fn pretty_print_closure_as_impl(
2078 &mut self,
2079 closure: ty::ClosureArgs<TyCtxt<'tcx>>,
2080 ) -> Result<(), PrintError> {
2081 let sig = closure.sig();
2082 let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn);
2083
2084 self.write_fmt(format_args!("impl "))write!(self, "impl ")?;
2085 self.wrap_binder(&sig, WrapBinderMode::ForAll, |sig, p| {
2086 p.write_fmt(format_args!("{0}(", kind))write!(p, "{kind}(")?;
2087 for (i, arg) in sig.inputs()[0].tuple_fields().iter().enumerate() {
2088 if i > 0 {
2089 p.write_fmt(format_args!(", "))write!(p, ", ")?;
2090 }
2091 arg.print(p)?;
2092 }
2093 p.write_fmt(format_args!(")"))write!(p, ")")?;
2094
2095 if !sig.output().is_unit() {
2096 p.write_fmt(format_args!(" -> "))write!(p, " -> ")?;
2097 sig.output().print(p)?;
2098 }
2099
2100 Ok(())
2101 })
2102 }
2103
2104 fn pretty_print_bound_constness(
2105 &mut self,
2106 constness: ty::BoundConstness,
2107 ) -> Result<(), PrintError> {
2108 match constness {
2109 ty::BoundConstness::Const => self.write_fmt(format_args!("const "))write!(self, "const ")?,
2110 ty::BoundConstness::Maybe => self.write_fmt(format_args!("[const] "))write!(self, "[const] ")?,
2111 }
2112 Ok(())
2113 }
2114
2115 fn should_print_verbose(&self) -> bool {
2116 self.tcx().sess.verbose_internals()
2117 }
2118}
2119
2120pub(crate) fn pretty_print_const<'tcx>(
2121 c: ty::Const<'tcx>,
2122 fmt: &mut fmt::Formatter<'_>,
2123 print_types: bool,
2124) -> fmt::Result {
2125 ty::tls::with(|tcx| {
2126 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
2127 p.print_alloc_ids = true;
2128 p.pretty_print_const(tcx.lift(c), print_types)?;
2129 fmt.write_str(&p.into_buffer())?;
2130 Ok(())
2131 })
2132}
2133
2134pub struct FmtPrinter<'a, 'tcx>(Box<FmtPrinterData<'a, 'tcx>>);
2136
2137pub struct FmtPrinterData<'a, 'tcx> {
2138 tcx: TyCtxt<'tcx>,
2139 fmt: String,
2140
2141 empty_path: bool,
2142 in_value: bool,
2143 pub print_alloc_ids: bool,
2144
2145 used_region_names: FxHashSet<Symbol>,
2147
2148 region_index: usize,
2149 binder_depth: usize,
2150 printed_type_count: usize,
2151 type_length_limit: Limit,
2152
2153 pub region_highlight_mode: RegionHighlightMode<'tcx>,
2154
2155 pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<Symbol> + 'a>>,
2156 pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid) -> Option<Symbol> + 'a>>,
2157}
2158
2159impl<'a, 'tcx> Deref for FmtPrinter<'a, 'tcx> {
2160 type Target = FmtPrinterData<'a, 'tcx>;
2161 fn deref(&self) -> &Self::Target {
2162 &self.0
2163 }
2164}
2165
2166impl DerefMut for FmtPrinter<'_, '_> {
2167 fn deref_mut(&mut self) -> &mut Self::Target {
2168 &mut self.0
2169 }
2170}
2171
2172impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
2173 pub fn new(tcx: TyCtxt<'tcx>, ns: Namespace) -> Self {
2174 let limit =
2175 if with_reduced_queries() { Limit::new(1048576) } else { tcx.type_length_limit() };
2176 Self::new_with_limit(tcx, ns, limit)
2177 }
2178
2179 pub fn print_string(
2180 tcx: TyCtxt<'tcx>,
2181 ns: Namespace,
2182 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2183 ) -> Result<String, PrintError> {
2184 let mut c = FmtPrinter::new(tcx, ns);
2185 f(&mut c)?;
2186 Ok(c.into_buffer())
2187 }
2188
2189 pub fn new_with_limit(tcx: TyCtxt<'tcx>, ns: Namespace, type_length_limit: Limit) -> Self {
2190 FmtPrinter(Box::new(FmtPrinterData {
2191 tcx,
2192 fmt: String::with_capacity(64),
2195 empty_path: false,
2196 in_value: ns == Namespace::ValueNS,
2197 print_alloc_ids: false,
2198 used_region_names: Default::default(),
2199 region_index: 0,
2200 binder_depth: 0,
2201 printed_type_count: 0,
2202 type_length_limit,
2203 region_highlight_mode: RegionHighlightMode::default(),
2204 ty_infer_name_resolver: None,
2205 const_infer_name_resolver: None,
2206 }))
2207 }
2208
2209 pub fn into_buffer(self) -> String {
2210 self.0.fmt
2211 }
2212}
2213
2214fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
2215 match tcx.def_key(def_id).disambiguated_data.data {
2216 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::OpaqueTy => {
2217 Namespace::TypeNS
2218 }
2219
2220 DefPathData::ValueNs(..)
2221 | DefPathData::AnonConst
2222 | DefPathData::Closure
2223 | DefPathData::Ctor => Namespace::ValueNS,
2224
2225 DefPathData::MacroNs(..) => Namespace::MacroNS,
2226
2227 _ => Namespace::TypeNS,
2228 }
2229}
2230
2231impl<'t> TyCtxt<'t> {
2232 pub fn def_path_str(self, def_id: impl IntoQueryKey<DefId>) -> String {
2235 let def_id = def_id.into_query_key();
2236 self.def_path_str_with_args(def_id, ty::GenericArgs::empty())
2237 }
2238
2239 pub fn def_path_str_with_args(
2241 self,
2242 def_id: impl IntoQueryKey<DefId>,
2243 args: ty::GenericArgs<'t>,
2244 ) -> String {
2245 let def_id = def_id.into_query_key();
2246 let ns = guess_def_namespace(self, def_id);
2247 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/print/pretty.rs:2247",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(2247u32),
::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);
2248
2249 FmtPrinter::print_string(self, ns, |p| p.print_def_path(def_id, args)).unwrap()
2250 }
2251
2252 pub fn value_path_str_with_args(
2254 self,
2255 def_id: impl IntoQueryKey<DefId>,
2256 args: ty::GenericArgs<'t>,
2257 ) -> String {
2258 let def_id = def_id.into_query_key();
2259 let ns = Namespace::ValueNS;
2260 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/print/pretty.rs:2260",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(2260u32),
::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);
2261
2262 FmtPrinter::print_string(self, ns, |p| p.print_def_path(def_id, args)).unwrap()
2263 }
2264}
2265
2266impl fmt::Write for FmtPrinter<'_, '_> {
2267 fn write_str(&mut self, s: &str) -> fmt::Result {
2268 self.fmt.push_str(s);
2269 Ok(())
2270 }
2271}
2272
2273impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
2274 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
2275 self.tcx
2276 }
2277
2278 fn reset_path(&mut self) -> Result<(), PrintError> {
2279 self.empty_path = true;
2280 Ok(())
2281 }
2282
2283 fn should_omit_parent_def_path(&self, parent_def_id: DefId) -> bool {
2284 RTN_MODE.with(|mode| mode.get()) == RtnMode::ForSuggestion
2285 && #[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!(
2286 self.tcx().def_key(parent_def_id).disambiguated_data.data,
2287 DefPathData::ValueNs(..) | DefPathData::Closure | DefPathData::AnonConst
2288 )
2289 }
2290
2291 fn print_def_path(
2292 &mut self,
2293 def_id: DefId,
2294 args: ty::GenericArgs<'tcx>,
2295 ) -> Result<(), PrintError> {
2296 if args.is_empty() {
2297 match self.try_print_trimmed_def_path(def_id)? {
2298 true => return Ok(()),
2299 false => {}
2300 }
2301
2302 match self.try_print_visible_def_path(def_id)? {
2303 true => return Ok(()),
2304 false => {}
2305 }
2306 }
2307
2308 let key = self.tcx.def_key(def_id);
2309 if let DefPathData::Impl = key.disambiguated_data.data {
2310 let use_types = !def_id.is_local() || {
2313 let force_no_types = with_forced_impl_filename_line();
2315 !force_no_types
2316 };
2317
2318 if !use_types {
2319 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
2323 let span = self.tcx.def_span(def_id);
2324
2325 self.print_def_path(parent_def_id, ty::GenericArgs::empty())?;
2326
2327 if !self.empty_path {
2330 self.write_fmt(format_args!("::"))write!(self, "::")?;
2331 }
2332 self.write_fmt(format_args!("<impl at {0}>",
self.tcx.sess.source_map().span_to_diagnostic_string(span)))write!(
2333 self,
2334 "<impl at {}>",
2335 self.tcx.sess.source_map().span_to_diagnostic_string(span)
2338 )?;
2339 self.empty_path = false;
2340
2341 return Ok(());
2342 }
2343 }
2344
2345 self.default_print_def_path(def_id, args)
2346 }
2347
2348 fn print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), PrintError> {
2349 self.pretty_print_region(region)
2350 }
2351
2352 fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
2353 let has_regions = self.region_highlight_mode.keep_regions
2354 && ty.has_type_flags(ty::TypeFlags::HAS_REGIONS);
2355 match ty.kind() {
2356 ty::Tuple(tys) if tys.len() == 0 => {
2357 self.pretty_print_type(ty)
2359 }
2360
2361 ty::Adt(def, args)
2362 if self.should_truncate()
2363 && args.consts().count() < 2
2364 && args.types().count() < 2
2365 && {
2366 if let Some(arg) = args.types().next() {
2371 if let ty::Adt(_, arg_args) = arg.kind() {
2372 if arg_args.terms().next().is_none() {
2373 true
2376 } else {
2377 false
2381 }
2382 } else {
2383 true
2386 }
2387 } else {
2388 true
2390 }
2391 }
2392 && self.tcx.item_name(def.did()).as_str().len() < 7 =>
2393 {
2394 { let _guard = ForceTrimmedGuard::new(); self.pretty_print_type(ty) }with_forced_trimmed_paths!(self.pretty_print_type(ty))
2397 }
2398
2399 ty::Alias(_, alias)
2400 if self.should_truncate()
2401 && let ty::AliasTyKind::Opaque { def_id } = alias.kind
2402 && self.region_highlight_mode.keep_regions
2403 && self
2404 .tcx
2405 .explicit_item_bounds(def_id)
2406 .iter_instantiated_copied(self.tcx, alias.args)
2407 .map(Unnormalized::skip_norm_wip)
2408 .any(|(value, _)| value.has_bound_vars()) =>
2409 {
2410 self.printed_type_count += 1;
2412 self.pretty_print_type(ty)
2413 }
2414
2415 ty::Adt(..)
2416 | ty::Foreign(_)
2417 | ty::Pat(..)
2418 | ty::RawPtr(..)
2419 | ty::Ref(..)
2420 | ty::FnDef(..)
2421 | ty::FnPtr(..)
2422 | ty::UnsafeBinder(..)
2423 | ty::Dynamic(..)
2424 | ty::CoroutineClosure(..)
2425 | ty::Coroutine(..)
2426 | ty::CoroutineWitness(..)
2427 | ty::Tuple(_)
2428 | ty::Alias(..)
2429 | ty::Bound(..)
2430 | ty::Placeholder(_)
2431 | ty::Error(_)
2432 if self.should_truncate() && !has_regions =>
2433 {
2434 self.write_fmt(format_args!("_"))write!(self, "_")?;
2437 Ok(())
2438 }
2439 ty::Ref(..) if self.should_truncate() && has_regions => self.pretty_print_type(ty),
2440 ty::Closure(..) => self.pretty_print_type(ty),
2441 _ => {
2442 self.printed_type_count += 1;
2443 self.pretty_print_type(ty)
2444 }
2445 }
2446 }
2447
2448 fn print_dyn_existential(
2449 &mut self,
2450 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2451 ) -> Result<(), PrintError> {
2452 self.pretty_print_dyn_existential(predicates)
2453 }
2454
2455 fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError> {
2456 self.pretty_print_const(ct, false)
2457 }
2458
2459 fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
2460 self.empty_path = true;
2461 if cnum == LOCAL_CRATE {
2462 if with_resolve_crate_name() {
2463 self.write_fmt(format_args!("{0}", self.tcx.crate_name(cnum)))write!(self, "{}", self.tcx.crate_name(cnum))?;
2465 self.empty_path = false;
2466 } else if with_crate_prefix() {
2467 self.write_fmt(format_args!("{0}", kw::Crate))write!(self, "{}", kw::Crate)?;
2468 self.empty_path = false;
2469 }
2470 } else {
2471 self.write_fmt(format_args!("{0}", self.tcx.crate_name_with_rename(cnum)))write!(self, "{}", self.tcx.crate_name_with_rename(cnum))?;
2472 self.empty_path = false;
2473 }
2474 Ok(())
2475 }
2476
2477 fn print_path_with_qualified(
2478 &mut self,
2479 self_ty: Ty<'tcx>,
2480 trait_ref: Option<ty::TraitRef<'tcx>>,
2481 ) -> Result<(), PrintError> {
2482 self.pretty_print_path_with_qualified(self_ty, trait_ref)?;
2483 self.empty_path = false;
2484 Ok(())
2485 }
2486
2487 fn print_path_with_impl(
2488 &mut self,
2489 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2490 self_ty: Ty<'tcx>,
2491 trait_ref: Option<ty::TraitRef<'tcx>>,
2492 ) -> Result<(), PrintError> {
2493 self.pretty_print_path_with_impl(
2494 |p| {
2495 print_prefix(p)?;
2496 if !p.empty_path {
2497 p.write_fmt(format_args!("::"))write!(p, "::")?;
2498 }
2499
2500 Ok(())
2501 },
2502 self_ty,
2503 trait_ref,
2504 )?;
2505 self.empty_path = false;
2506 Ok(())
2507 }
2508
2509 fn print_path_with_simple(
2510 &mut self,
2511 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2512 disambiguated_data: &DisambiguatedDefPathData,
2513 ) -> Result<(), PrintError> {
2514 print_prefix(self)?;
2515
2516 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
2518 return Ok(());
2519 }
2520
2521 let name = disambiguated_data.data.name();
2522 if !self.empty_path {
2523 self.write_fmt(format_args!("::"))write!(self, "::")?;
2524 }
2525
2526 if let DefPathDataName::Named(name) = name {
2527 if Ident::with_dummy_span(name).is_raw_guess() {
2528 self.write_fmt(format_args!("r#"))write!(self, "r#")?;
2529 }
2530 }
2531
2532 let verbose = self.should_print_verbose();
2533 self.write_fmt(format_args!("{0}", disambiguated_data.as_sym(verbose)))write!(self, "{}", disambiguated_data.as_sym(verbose))?;
2534
2535 self.empty_path = false;
2536
2537 Ok(())
2538 }
2539
2540 fn print_path_with_generic_args(
2541 &mut self,
2542 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2543 args: ty::GenericArgs<'tcx>,
2544 ) -> Result<(), PrintError> {
2545 print_prefix(self)?;
2546
2547 if !args.is_empty() {
2548 if self.in_value {
2549 self.write_fmt(format_args!("::"))write!(self, "::")?;
2550 }
2551 self.generic_delimiters(|p| p.comma_sep(args.iter()))
2552 } else {
2553 Ok(())
2554 }
2555 }
2556}
2557
2558impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
2559 fn ty_infer_name(&self, id: ty::TyVid) -> Option<Symbol> {
2560 self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
2561 }
2562
2563 fn reset_type_limit(&mut self) {
2564 self.printed_type_count = 0;
2565 }
2566
2567 fn const_infer_name(&self, id: ty::ConstVid) -> Option<Symbol> {
2568 self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
2569 }
2570
2571 fn pretty_print_value_path(
2572 &mut self,
2573 def_id: DefId,
2574 args: ty::GenericArgs<'tcx>,
2575 ) -> Result<(), PrintError> {
2576 let was_in_value = std::mem::replace(&mut self.in_value, true);
2577 self.print_def_path(def_id, args)?;
2578 self.in_value = was_in_value;
2579
2580 Ok(())
2581 }
2582
2583 fn pretty_print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError>
2584 where
2585 T: Print<Self> + TypeFoldable<TyCtxt<'tcx>>,
2586 {
2587 self.wrap_binder(value, WrapBinderMode::ForAll, |new_value, this| new_value.print(this))
2588 }
2589
2590 fn wrap_binder<T, C: FnOnce(&T, &mut Self) -> Result<(), PrintError>>(
2591 &mut self,
2592 value: &ty::Binder<'tcx, T>,
2593 mode: WrapBinderMode,
2594 f: C,
2595 ) -> Result<(), PrintError>
2596 where
2597 T: TypeFoldable<TyCtxt<'tcx>>,
2598 {
2599 let old_region_index = self.region_index;
2600 let (new_value, _) = self.name_all_regions(value, mode)?;
2601 f(&new_value, self)?;
2602 self.region_index = old_region_index;
2603 self.binder_depth -= 1;
2604 Ok(())
2605 }
2606
2607 fn typed_value(
2608 &mut self,
2609 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2610 t: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2611 conversion: &str,
2612 ) -> Result<(), PrintError> {
2613 self.write_str("{")?;
2614 f(self)?;
2615 self.write_str(conversion)?;
2616 let was_in_value = std::mem::replace(&mut self.in_value, false);
2617 t(self)?;
2618 self.in_value = was_in_value;
2619 self.write_str("}")?;
2620 Ok(())
2621 }
2622
2623 fn generic_delimiters(
2624 &mut self,
2625 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
2626 ) -> Result<(), PrintError> {
2627 self.write_fmt(format_args!("<"))write!(self, "<")?;
2628
2629 let was_in_value = std::mem::replace(&mut self.in_value, false);
2630 f(self)?;
2631 self.in_value = was_in_value;
2632
2633 self.write_fmt(format_args!(">"))write!(self, ">")?;
2634 Ok(())
2635 }
2636
2637 fn should_truncate(&mut self) -> bool {
2638 !self.type_length_limit.value_within_limit(self.printed_type_count)
2639 }
2640
2641 fn should_print_optional_region(&self, region: ty::Region<'tcx>) -> bool {
2642 let highlight = self.region_highlight_mode;
2643 if highlight.region_highlighted(region).is_some() {
2644 return true;
2645 }
2646
2647 if self.should_print_verbose() {
2648 return true;
2649 }
2650
2651 if with_forced_trimmed_paths() {
2652 return false;
2653 }
2654
2655 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2656
2657 match region.kind() {
2658 ty::ReEarlyParam(ref data) => data.is_named(),
2659
2660 ty::ReLateParam(ty::LateParamRegion { kind, .. }) => kind.is_named(self.tcx),
2661 ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2662 | ty::RePlaceholder(ty::Placeholder {
2663 bound: ty::BoundRegion { kind: br, .. }, ..
2664 }) => {
2665 if br.is_named(self.tcx) {
2666 return true;
2667 }
2668
2669 if let Some((region, _)) = highlight.highlight_bound_region {
2670 if br == region {
2671 return true;
2672 }
2673 }
2674
2675 false
2676 }
2677
2678 ty::ReVar(_) if identify_regions => true,
2679
2680 ty::ReVar(_) | ty::ReErased | ty::ReError(_) => false,
2681
2682 ty::ReStatic => true,
2683 }
2684 }
2685
2686 fn pretty_print_const_pointer<Prov: Provenance>(
2687 &mut self,
2688 p: Pointer<Prov>,
2689 ty: Ty<'tcx>,
2690 ) -> Result<(), PrintError> {
2691 let print = |this: &mut Self| {
2692 if this.print_alloc_ids {
2693 this.write_fmt(format_args!("{0:?}", p))write!(this, "{p:?}")?;
2694 } else {
2695 this.write_fmt(format_args!("&_"))write!(this, "&_")?;
2696 }
2697 Ok(())
2698 };
2699 self.typed_value(print, |this| this.print_type(ty), ": ")
2700 }
2701}
2702
2703impl<'tcx> FmtPrinter<'_, 'tcx> {
2705 pub fn pretty_print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), fmt::Error> {
2706 let highlight = self.region_highlight_mode;
2708 if let Some(n) = highlight.region_highlighted(region) {
2709 self.write_fmt(format_args!("\'{0}", n))write!(self, "'{n}")?;
2710 return Ok(());
2711 }
2712
2713 if self.should_print_verbose() {
2714 self.write_fmt(format_args!("{0:?}", region))write!(self, "{region:?}")?;
2715 return Ok(());
2716 }
2717
2718 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2719
2720 match region.kind() {
2725 ty::ReEarlyParam(data) => {
2726 self.write_fmt(format_args!("{0}", data.name))write!(self, "{}", data.name)?;
2727 return Ok(());
2728 }
2729 ty::ReLateParam(ty::LateParamRegion { kind, .. }) => {
2730 if let Some(name) = kind.get_name(self.tcx) {
2731 self.write_fmt(format_args!("{0}", name))write!(self, "{name}")?;
2732 return Ok(());
2733 }
2734 }
2735 ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2736 | ty::RePlaceholder(ty::Placeholder {
2737 bound: ty::BoundRegion { kind: br, .. }, ..
2738 }) => {
2739 if let Some(name) = br.get_name(self.tcx) {
2740 self.write_fmt(format_args!("{0}", name))write!(self, "{name}")?;
2741 return Ok(());
2742 }
2743
2744 if let Some((region, counter)) = highlight.highlight_bound_region {
2745 if br == region {
2746 self.write_fmt(format_args!("\'{0}", counter))write!(self, "'{counter}")?;
2747 return Ok(());
2748 }
2749 }
2750 }
2751 ty::ReVar(region_vid) if identify_regions => {
2752 self.write_fmt(format_args!("{0:?}", region_vid))write!(self, "{region_vid:?}")?;
2753 return Ok(());
2754 }
2755 ty::ReVar(_) => {}
2756 ty::ReErased => {}
2757 ty::ReError(_) => {}
2758 ty::ReStatic => {
2759 self.write_fmt(format_args!("\'static"))write!(self, "'static")?;
2760 return Ok(());
2761 }
2762 }
2763
2764 self.write_fmt(format_args!("\'_"))write!(self, "'_")?;
2765
2766 Ok(())
2767 }
2768}
2769
2770struct RegionFolder<'a, 'tcx> {
2772 tcx: TyCtxt<'tcx>,
2773 current_index: ty::DebruijnIndex,
2774 region_map: UnordMap<ty::BoundRegion<'tcx>, ty::Region<'tcx>>,
2777 name: &'a mut (dyn FnMut(ty::BoundRegion<'tcx>) -> ty::Region<'tcx> + 'a),
2778}
2779
2780impl<'a, 'tcx> ty::TypeFolder<TyCtxt<'tcx>> for RegionFolder<'a, 'tcx> {
2781 fn cx(&self) -> TyCtxt<'tcx> {
2782 self.tcx
2783 }
2784
2785 fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>(
2786 &mut self,
2787 t: ty::Binder<'tcx, T>,
2788 ) -> ty::Binder<'tcx, T> {
2789 self.current_index.shift_in(1);
2790 let t = t.super_fold_with(self);
2791 self.current_index.shift_out(1);
2792 t
2793 }
2794
2795 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2796 match *t.kind() {
2797 _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2798 return t.super_fold_with(self);
2799 }
2800 _ => {}
2801 }
2802 t
2803 }
2804
2805 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2806 let name = &mut self.name;
2807 let region = match r.kind() {
2808 ty::ReBound(ty::BoundVarIndexKind::Bound(db), br) if db == self.current_index => {
2814 *self.region_map.entry(br).or_insert_with(|| name(br))
2815 }
2816 ty::RePlaceholder(ty::PlaceholderRegion {
2817 bound: ty::BoundRegion { kind, .. },
2818 ..
2819 }) => {
2820 match kind {
2823 ty::BoundRegionKind::Anon | ty::BoundRegionKind::ClosureEnv => r,
2824 _ => {
2825 let br = ty::BoundRegion { var: ty::BoundVar::ZERO, kind };
2827 *self.region_map.entry(br).or_insert_with(|| name(br))
2828 }
2829 }
2830 }
2831 _ => return r,
2832 };
2833 if let ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn1), br) = region.kind() {
2834 {
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);
2835 ty::Region::new_bound(self.tcx, self.current_index, br)
2836 } else {
2837 region
2838 }
2839 }
2840}
2841
2842impl<'tcx> FmtPrinter<'_, 'tcx> {
2845 pub fn name_all_regions<T>(
2846 &mut self,
2847 value: &ty::Binder<'tcx, T>,
2848 mode: WrapBinderMode,
2849 ) -> Result<(T, UnordMap<ty::BoundRegion<'tcx>, ty::Region<'tcx>>), fmt::Error>
2850 where
2851 T: TypeFoldable<TyCtxt<'tcx>>,
2852 {
2853 fn name_by_region_index(
2854 index: usize,
2855 available_names: &mut Vec<Symbol>,
2856 num_available: usize,
2857 ) -> Symbol {
2858 if let Some(name) = available_names.pop() {
2859 name
2860 } else {
2861 Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'z{0}", index - num_available))
})format!("'z{}", index - num_available))
2862 }
2863 }
2864
2865 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/print/pretty.rs:2865",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(2865u32),
::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");
2866
2867 if self.binder_depth == 0 {
2873 self.prepare_region_info(value);
2874 }
2875
2876 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/print/pretty.rs:2876",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(2876u32),
::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);
2877
2878 let mut empty = true;
2879 let mut start_or_continue = |p: &mut Self, start: &str, cont: &str| {
2880 let w = if empty {
2881 empty = false;
2882 start
2883 } else {
2884 cont
2885 };
2886 let _ = p.write_fmt(format_args!("{0}", w))write!(p, "{w}");
2887 };
2888 let do_continue = |p: &mut Self, cont: Symbol| {
2889 let _ = p.write_fmt(format_args!("{0}", cont))write!(p, "{cont}");
2890 };
2891
2892 let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'{0}", s))
})format!("'{s}")));
2893
2894 let mut available_names = possible_names
2895 .filter(|name| !self.used_region_names.contains(name))
2896 .collect::<Vec<_>>();
2897 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/print/pretty.rs:2897",
"rustc_middle::ty::print::pretty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(2897u32),
::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);
2898 let num_available = available_names.len();
2899
2900 let mut region_index = self.region_index;
2901 let mut next_name = |this: &Self| {
2902 let mut name;
2903
2904 loop {
2905 name = name_by_region_index(region_index, &mut available_names, num_available);
2906 region_index += 1;
2907
2908 if !this.used_region_names.contains(&name) {
2909 break;
2910 }
2911 }
2912
2913 name
2914 };
2915
2916 let (new_value, map) = if self.should_print_verbose() {
2921 for var in value.bound_vars().iter() {
2922 start_or_continue(self, mode.start_str(), ", ");
2923 self.write_fmt(format_args!("{0:?}", var))write!(self, "{var:?}")?;
2924 }
2925 if value.bound_vars().is_empty() && mode == WrapBinderMode::Unsafe {
2927 start_or_continue(self, mode.start_str(), "");
2928 }
2929 start_or_continue(self, "", "> ");
2930 (value.clone().skip_binder(), UnordMap::default())
2931 } else {
2932 let tcx = self.tcx;
2933
2934 let trim_path = with_forced_trimmed_paths();
2935 let mut name = |br: ty::BoundRegion<'tcx>| {
2938 let (name, kind) = if let Some(name) = br.kind.get_name(tcx) {
2939 (name, br.kind)
2940 } else {
2941 let name = next_name(self);
2942 (name, ty::BoundRegionKind::NamedForPrinting(name))
2943 };
2944
2945 if !trim_path || mode == WrapBinderMode::Unsafe {
2947 start_or_continue(self, mode.start_str(), ", ");
2948 do_continue(self, name);
2949 }
2950 ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { var: br.var, kind })
2951 };
2952 let mut folder = RegionFolder {
2953 tcx,
2954 current_index: ty::INNERMOST,
2955 name: &mut name,
2956 region_map: UnordMap::default(),
2957 };
2958 let new_value = value.clone().skip_binder().fold_with(&mut folder);
2959 let region_map = folder.region_map;
2960
2961 if mode == WrapBinderMode::Unsafe && region_map.is_empty() {
2962 start_or_continue(self, mode.start_str(), "");
2963 }
2964 start_or_continue(self, "", "> ");
2965
2966 (new_value, region_map)
2967 };
2968
2969 self.binder_depth += 1;
2970 self.region_index = region_index;
2971 Ok((new_value, map))
2972 }
2973
2974 fn prepare_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2975 where
2976 T: TypeFoldable<TyCtxt<'tcx>>,
2977 {
2978 struct RegionNameCollector<'tcx> {
2979 tcx: TyCtxt<'tcx>,
2980 used_region_names: FxHashSet<Symbol>,
2981 type_collector: SsoHashSet<Ty<'tcx>>,
2982 }
2983
2984 impl<'tcx> RegionNameCollector<'tcx> {
2985 fn new(tcx: TyCtxt<'tcx>) -> Self {
2986 RegionNameCollector {
2987 tcx,
2988 used_region_names: Default::default(),
2989 type_collector: SsoHashSet::new(),
2990 }
2991 }
2992 }
2993
2994 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for RegionNameCollector<'tcx> {
2995 fn visit_region(&mut self, r: ty::Region<'tcx>) {
2996 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/print/pretty.rs:2996",
"rustc_middle::ty::print::pretty", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/522d96a5707c154b15960db186c03b84a52b4efb/compiler/rustc_middle/src/ty/print/pretty.rs"),
::tracing_core::__macro_support::Option::Some(2996u32),
::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);
2997
2998 if let Some(name) = r.get_name(self.tcx) {
3002 self.used_region_names.insert(name);
3003 }
3004 }
3005
3006 fn visit_ty(&mut self, ty: Ty<'tcx>) {
3009 let not_previously_inserted = self.type_collector.insert(ty);
3010 if not_previously_inserted {
3011 ty.super_visit_with(self)
3012 }
3013 }
3014 }
3015
3016 let mut collector = RegionNameCollector::new(self.tcx());
3017 value.visit_with(&mut collector);
3018 self.used_region_names = collector.used_region_names;
3019 self.region_index = 0;
3020 }
3021}
3022
3023impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<P> for ty::Binder<'tcx, T>
3024where
3025 T: Print<P> + TypeFoldable<TyCtxt<'tcx>>,
3026{
3027 fn print(&self, p: &mut P) -> Result<(), PrintError> {
3028 p.pretty_print_in_binder(self)
3029 }
3030}
3031
3032impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<P> for ty::OutlivesClause<'tcx, T>
3033where
3034 T: Print<P>,
3035{
3036 fn print(&self, p: &mut P) -> Result<(), PrintError> {
3037 self.0.print(p)?;
3038 p.write_fmt(format_args!(": "))write!(p, ": ")?;
3039 self.1.print(p)?;
3040 Ok(())
3041 }
3042}
3043
3044#[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)]
3048pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
3049
3050impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintOnlyTraitPath<'tcx> {
3051 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
3052 ty::tls::with(|tcx| {
3053 let trait_ref = tcx.short_string(tcx.lift(self), path);
3054 rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
3055 })
3056 }
3057}
3058
3059impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
3060 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3061 fmt::Display::fmt(self, f)
3062 }
3063}
3064
3065#[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)]
3068pub struct TraitRefPrintSugared<'tcx>(ty::TraitRef<'tcx>);
3069
3070impl<'tcx> rustc_errors::IntoDiagArg for TraitRefPrintSugared<'tcx> {
3071 fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
3072 ty::tls::with(|tcx| {
3073 let trait_ref = tcx.short_string(tcx.lift(self), path);
3074 rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(trait_ref))
3075 })
3076 }
3077}
3078
3079impl<'tcx> fmt::Debug for TraitRefPrintSugared<'tcx> {
3080 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3081 fmt::Display::fmt(self, f)
3082 }
3083}
3084
3085#[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)]
3089pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
3090
3091impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
3092 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3093 fmt::Display::fmt(self, f)
3094 }
3095}
3096
3097pub 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>)]
3098impl<'tcx> ty::TraitRef<'tcx> {
3099 fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
3100 TraitRefPrintOnlyTraitPath(self)
3101 }
3102
3103 fn print_trait_sugared(self) -> TraitRefPrintSugared<'tcx> {
3104 TraitRefPrintSugared(self)
3105 }
3106
3107 fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
3108 TraitRefPrintOnlyTraitName(self)
3109 }
3110}
3111
3112pub 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>)]
3113impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
3114 fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
3115 self.map_bound(|tr| tr.print_only_trait_path())
3116 }
3117
3118 fn print_trait_sugared(self) -> ty::Binder<'tcx, TraitRefPrintSugared<'tcx>> {
3119 self.map_bound(|tr| tr.print_trait_sugared())
3120 }
3121}
3122
3123#[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)]
3124pub struct TraitClausePrintModifiersAndPath<'tcx>(ty::TraitClause<'tcx>);
3125
3126impl<'tcx> fmt::Debug for TraitClausePrintModifiersAndPath<'tcx> {
3127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3128 fmt::Display::fmt(self, f)
3129 }
3130}
3131
3132pub 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>)]
3133impl<'tcx> ty::TraitClause<'tcx> {
3134 fn print_modifiers_and_trait_path(self) -> TraitClausePrintModifiersAndPath<'tcx> {
3135 TraitClausePrintModifiersAndPath(self)
3136 }
3137}
3138
3139#[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)]
3140pub struct TraitClausePrintWithBoundConstness<'tcx>(
3141 ty::TraitClause<'tcx>,
3142 Option<ty::BoundConstness>,
3143);
3144
3145impl<'tcx> fmt::Debug for TraitClausePrintWithBoundConstness<'tcx> {
3146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3147 fmt::Display::fmt(self, f)
3148 }
3149}
3150
3151pub 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>)]
3152impl<'tcx> ty::PolyTraitClause<'tcx> {
3153 fn print_modifiers_and_trait_path(
3154 self,
3155 ) -> ty::Binder<'tcx, TraitClausePrintModifiersAndPath<'tcx>> {
3156 self.map_bound(TraitClausePrintModifiersAndPath)
3157 }
3158
3159 fn print_with_bound_constness(
3160 self,
3161 constness: Option<ty::BoundConstness>,
3162 ) -> ty::Binder<'tcx, TraitClausePrintWithBoundConstness<'tcx>> {
3163 self.map_bound(|trait_pred| TraitClausePrintWithBoundConstness(trait_pred, constness))
3164 }
3165}
3166
3167macro_rules! forward_display_to_print {
3168 ($($ty:ty),+) => {
3169 $(
3170 #[allow(unused_lifetimes, reason = "not all `$ty` have a 'tcx")]
3171 impl<'tcx> fmt::Display for $ty {
3172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3173 ty::tls::with(|tcx| {
3174 let mut p = FmtPrinter::new(tcx, Namespace::TypeNS);
3175 tcx.lift(*self)
3176 .print(&mut p)?;
3177 f.write_str(&p.into_buffer())?;
3178 Ok(())
3179 })
3180 }
3181 }
3182 )+
3183 };
3184}
3185
3186macro_rules! define_print {
3187 (($self:ident, $p:ident): $($ty:ty $print:block)+) => {
3188 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<P> for $ty {
3189 fn print(&$self, $p: &mut P) -> Result<(), PrintError> {
3190 let _: () = $print;
3191 Ok(())
3192 }
3193 })+
3194 };
3195}
3196
3197macro_rules! define_print_and_forward_display {
3198 (($self:ident, $p:ident): $($ty:ty $print:block)+) => {
3199 define_print!(($self, $p): $($ty $print)*);
3200 forward_display_to_print!($($ty),+);
3201 };
3202}
3203
3204#[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! {
3205 Ty<'tcx>,
3206 &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>
3207}
3208
3209impl<'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))?;
}
ty::ClauseKind::CompressedTrait(_) =>
::core::panicking::unreachable_default_msg(),
}
};
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::SelectAssocCandidate(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::SelectAssocCandidate<'tcx>
{
fn print(&self, p: &mut P) -> Result<(), PrintError> {
let _: () =
{
self.alias.print(p)?;
p.write_fmt(format_args!(" select-assoc-candidate "))?;
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! {
3210 (self, p):
3211
3212 ty::FnSig<'tcx> {
3213 write!(p, "{}", self.safety().prefix_str())?;
3214
3215 if self.abi() != ExternAbi::Rust {
3216 write!(p, "extern {} ", self.abi())?;
3217 }
3218
3219 write!(p, "fn")?;
3220 p.pretty_print_fn_sig(self.inputs(), self.c_variadic(), self.splatted(), self.output())?;
3221 }
3222
3223 ty::TraitRef<'tcx> {
3224 write!(p, "<{} as {}>", self.self_ty(), self.print_only_trait_path())?;
3225 }
3226
3227 ty::AliasTy<'tcx> {
3228 let alias_term: ty::AliasTerm<'tcx> = (*self).into();
3229 alias_term.print(p)?;
3230 }
3231
3232 ty::AliasTerm<'tcx> {
3233 match self.kind {
3234 ty::AliasTermKind::InherentTy { .. } | ty::AliasTermKind::InherentConstSelf { .. } => {
3235 p.pretty_print_inherent_projection(*self)?;
3236 }
3237 ty::AliasTermKind::ProjectionTy { def_id } => {
3238 if !(p.should_print_verbose() || with_reduced_queries())
3239 && p.tcx().is_impl_trait_in_trait(def_id)
3240 {
3241 p.pretty_print_rpitit(def_id, self.args)?;
3242 } else {
3243 p.print_def_path(def_id, self.args)?;
3244 }
3245 }
3246 ty::AliasTermKind::FreeTy { def_id }
3247 | ty::AliasTermKind::FreeConst { def_id }
3248 | ty::AliasTermKind::OpaqueTy { def_id }
3249 | ty::AliasTermKind::AnonConst { def_id }
3250 | ty::AliasTermKind::ProjectionConst { def_id }
3251 | ty::AliasTermKind::InherentConstImpl { def_id } => {
3252 p.print_def_path(def_id, self.args)?;
3253 }
3254 }
3255 }
3256
3257 ty::TraitClause<'tcx> {
3258 self.trait_ref.self_ty().print(p)?;
3259 write!(p, ": ")?;
3260 if let ty::ClausePolarity::Negative = self.polarity {
3261 write!(p, "!")?;
3262 }
3263 self.trait_ref.print_trait_sugared().print(p)?;
3264 }
3265
3266 ty::HostEffectClause<'tcx> {
3267 let constness = match self.constness {
3268 ty::BoundConstness::Const => { "const" }
3269 ty::BoundConstness::Maybe => { "[const]" }
3270 };
3271 self.trait_ref.self_ty().print(p)?;
3272 write!(p, ": {constness} ")?;
3273 self.trait_ref.print_trait_sugared().print(p)?;
3274 }
3275
3276 ty::TypeAndMut<'tcx> {
3277 write!(p, "{}", self.mutbl.prefix_str())?;
3278 self.ty.print(p)?;
3279 }
3280
3281 ty::ClauseKind<'tcx> {
3282 match *self {
3283 ty::ClauseKind::Trait(ref data) => data.print(p)?,
3284 ty::ClauseKind::RegionOutlives(clause) => clause.print(p)?,
3285 ty::ClauseKind::TypeOutlives(clause) => clause.print(p)?,
3286 ty::ClauseKind::Projection(predicate) => predicate.print(p)?,
3287 ty::ClauseKind::HostEffect(clause) => clause.print(p)?,
3288 ty::ClauseKind::ConstArgHasType(ct, ty) => {
3289 write!(p, "the constant `")?;
3290 ct.print(p)?;
3291 write!(p, "` has type `")?;
3292 ty.print(p)?;
3293 write!(p, "`")?;
3294 },
3295 ty::ClauseKind::WellFormed(term) => {
3296 term.print(p)?;
3297 write!(p, " well-formed")?;
3298 }
3299 ty::ClauseKind::ConstEvaluatable(ct) => {
3300 write!(p, "the constant `")?;
3301 ct.print(p)?;
3302 write!(p, "` can be evaluated")?;
3303 }
3304 ty::ClauseKind::UnstableFeature(symbol) => {
3305 write!(p, "feature({symbol}) is enabled")?;
3306 }
3307 ty::ClauseKind::CompressedTrait(_) => unreachable!(),
3308 }
3309 }
3310
3311 ty::PredicateKind<'tcx> {
3312 match *self {
3313 ty::PredicateKind::Clause(data) => data.print(p)?,
3314 ty::PredicateKind::Subtype(predicate) => predicate.print(p)?,
3315 ty::PredicateKind::Coerce(predicate) => predicate.print(p)?,
3316 ty::PredicateKind::DynCompatible(trait_def_id) => {
3317 write!(p, "the trait `")?;
3318 p.print_def_path(trait_def_id, ty::GenericArgs::empty())?;
3319 write!(p, "` is dyn-compatible")?;
3320 }
3321 ty::PredicateKind::ConstEquate(c1, c2) => {
3322 write!(p, "the constant `")?;
3323 c1.print(p)?;
3324 write!(p, "` equals `")?;
3325 c2.print(p)?;
3326 write!(p, "`")?;
3327 }
3328 ty::PredicateKind::Ambiguous => write!(p, "ambiguous")?,
3329 ty::PredicateKind::SelectAssocCandidate(data) => data.print(p)?,
3330 }
3331 }
3332
3333 ty::ExistentialPredicate<'tcx> {
3334 match *self {
3335 ty::ExistentialPredicate::Trait(x) => x.print(p)?,
3336 ty::ExistentialPredicate::Projection(x) => x.print(p)?,
3337 ty::ExistentialPredicate::AutoTrait(def_id) => p.print_def_path(def_id, ty::GenericArgs::empty())?,
3338 }
3339 }
3340
3341 ty::ExistentialTraitRef<'tcx> {
3342 let trait_ref = self.with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self);
3345 trait_ref.print_only_trait_path().print(p)?;
3346 }
3347
3348 ty::ExistentialProjection<'tcx> {
3349 let name = p.tcx().associated_item(self.def_id).name();
3350 let args = &self.args.as_slice()[p.tcx().generics_of(self.def_id).parent_count - 1..];
3353 p.print_path_with_generic_args(|p| write!(p, "{name}"), p.tcx().mk_args(args))?;
3354 write!(p, " = ")?;
3355 self.term.print(p)?;
3356 }
3357
3358 ty::ProjectionClause<'tcx> {
3359 self.projection_term.print(p)?;
3360 write!(p, " == ")?;
3361 p.reset_type_limit();
3362 self.term.print(p)?;
3363 }
3364
3365 ty::SubtypePredicate<'tcx> {
3366 self.a.print(p)?;
3367 write!(p, " <: ")?;
3368 p.reset_type_limit();
3369 self.b.print(p)?;
3370 }
3371
3372 ty::CoercePredicate<'tcx> {
3373 self.a.print(p)?;
3374 write!(p, " -> ")?;
3375 p.reset_type_limit();
3376 self.b.print(p)?;
3377 }
3378
3379 ty::SelectAssocCandidate<'tcx> {
3380 self.alias.print(p)?;
3381 write!(p, " select-assoc-candidate ")?;
3382 p.reset_type_limit();
3383 self.term.print(p)?;
3384 }
3385
3386 ty::PlaceholderType<'tcx> {
3387 match self.bound.kind {
3388 ty::BoundTyKind::Anon => write!(p, "{self:?}")?,
3389 ty::BoundTyKind::Param(def_id) => match p.should_print_verbose() {
3390 true => write!(p, "{self:?}")?,
3391 false => write!(p, "{}", p.tcx().item_name(def_id))?,
3392 },
3393 }
3394 }
3395}
3396
3397impl<'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! {
3398 (self, p):
3399
3400 &'tcx ty::List<Ty<'tcx>> {
3401 write!(p, "{{")?;
3402 p.comma_sep(self.iter())?;
3403 write!(p, "}}")?;
3404 }
3405
3406 TraitRefPrintOnlyTraitPath<'tcx> {
3407 p.print_def_path(self.0.def_id, self.0.args)?;
3408 }
3409
3410 TraitRefPrintSugared<'tcx> {
3411 if !with_reduced_queries()
3412 && p.tcx().trait_def(self.0.def_id).paren_sugar
3413 && let Some(args_ty) = self.0.args.get(1).and_then(|arg| arg.as_type())
3414 && let ty::Tuple(args) = args_ty.kind()
3415 {
3416 write!(p, "{}(", p.tcx().item_name(self.0.def_id))?;
3417 for (i, arg) in args.iter().enumerate() {
3418 if i > 0 {
3419 write!(p, ", ")?;
3420 }
3421 arg.print(p)?;
3422 }
3423 write!(p, ")")?;
3424 } else {
3425 p.print_def_path(self.0.def_id, self.0.args)?;
3426 }
3427 }
3428
3429 TraitRefPrintOnlyTraitName<'tcx> {
3430 p.print_def_path(self.0.def_id, ty::GenericArgs::empty())?;
3431 }
3432
3433 TraitClausePrintModifiersAndPath<'tcx> {
3434 if let ty::ClausePolarity::Negative = self.0.polarity {
3435 write!(p, "!")?;
3436 }
3437 self.0.trait_ref.print_trait_sugared().print(p)?;
3438 }
3439
3440 TraitClausePrintWithBoundConstness<'tcx> {
3441 self.0.trait_ref.self_ty().print(p)?;
3442 write!(p, ": ")?;
3443 if let Some(constness) = self.1 {
3444 p.pretty_print_bound_constness(constness)?;
3445 }
3446 if let ty::ClausePolarity::Negative = self.0.polarity {
3447 write!(p, "!")?;
3448 }
3449 self.0.trait_ref.print_trait_sugared().print(p)?;
3450 }
3451
3452 ty::ParamTy {
3453 write!(p, "{}", self.name)?;
3454 }
3455
3456 ty::ParamConst {
3457 write!(p, "{}", self.name)?;
3458 }
3459
3460 ty::Term<'tcx> {
3461 match self.kind() {
3462 ty::TermKind::Ty(ty) => ty.print(p)?,
3463 ty::TermKind::Const(c) => c.print(p)?,
3464 }
3465 }
3466
3467 ty::Predicate<'tcx> {
3468 self.kind().print(p)?;
3469 }
3470
3471 ty::Clause<'tcx> {
3472 self.kind().print(p)?;
3473 }
3474
3475 ty::UserTypeKind<'tcx> {
3476 match *self {
3477 Self::Ty(ty) => {
3478 write!(p, "Ty(")?;
3479 ty.print(p)?;
3480 }
3481 Self::TypeOf(def_id, ty::UserArgs { args, user_self_ty }) => {
3482 write!(p, "TypeOf(")?;
3483 p.print_def_path(def_id, args)?;
3484 if let Some(ty::UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
3485 write!(p, " at <impl ")?;
3486 let key = p.tcx().def_key(impl_def_id);
3487 let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
3488 p.print_def_path(parent_def_id, ty::GenericArgs::empty())?;
3489 write!(p, "::<{}> for ", key.disambiguated_data.as_sym(false))?;
3490 self_ty.print(p)?;
3491 write!(p, ">")?;
3492 }
3493 }
3494 }
3495 write!(p, ")")?;
3496 }
3497
3498 GenericArg<'tcx> {
3499 match self.kind() {
3500 GenericArgKind::Lifetime(lt) => lt.print(p)?,
3501 GenericArgKind::Type(ty) => ty.print(p)?,
3502 GenericArgKind::Const(ct) => ct.print(p)?,
3503 }
3504 }
3505}
3506
3507fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
3508 for id in tcx.hir_free_items() {
3510 if tcx.def_kind(id.owner_id) == DefKind::Use {
3511 continue;
3512 }
3513
3514 let item = tcx.hir_item(id);
3515 let Some(ident) = item.kind.ident() else { continue };
3516
3517 let def_id = item.owner_id.to_def_id();
3518 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
3519 collect_fn(&ident, ns, def_id);
3520 }
3521
3522 let queue = &mut Vec::new();
3524 let mut seen_defs: DefIdSet = Default::default();
3525
3526 for &cnum in tcx.crates(()).iter() {
3527 match tcx.extern_crate(cnum) {
3529 None => continue,
3530 Some(extern_crate) => {
3531 if !extern_crate.is_direct() {
3532 continue;
3533 }
3534 }
3535 }
3536
3537 queue.push(cnum.as_def_id());
3538 }
3539
3540 while let Some(def) = queue.pop() {
3542 for child in tcx.module_children(def).iter() {
3543 if !child.vis.is_public() {
3544 continue;
3545 }
3546
3547 match child.res {
3548 def::Res::Def(DefKind::AssocTy, _) => {}
3549 def::Res::Def(DefKind::TyAlias, _) => {}
3550 def::Res::Def(defkind, def_id) => {
3551 if tcx.is_doc_hidden(def_id) {
3555 continue;
3556 }
3557
3558 if let Some(ns) = defkind.ns() {
3559 collect_fn(&child.ident, ns, def_id);
3560 }
3561
3562 if defkind.is_module_like() && seen_defs.insert(def_id) {
3563 queue.push(def_id);
3564 }
3565 }
3566 _ => {}
3567 }
3568 }
3569 }
3570}
3571
3572pub fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> DefIdMap<Symbol> {
3588 tcx.sess.record_trimmed_def_paths();
3595
3596 let unique_symbols_rev: &mut FxIndexMap<(Namespace, Symbol), Option<DefId>> =
3599 &mut FxIndexMap::default();
3600
3601 for symbol_set in tcx.resolutions(()).glob_map.values() {
3602 for symbol in symbol_set {
3603 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
3604 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
3605 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
3606 }
3607 }
3608
3609 for_each_def(tcx, |ident, ns, def_id| match unique_symbols_rev.entry((ns, ident.name)) {
3610 IndexEntry::Occupied(mut v) => match v.get() {
3611 None => {}
3612 Some(existing) => {
3613 if *existing != def_id {
3614 v.insert(None);
3615 }
3616 }
3617 },
3618 IndexEntry::Vacant(v) => {
3619 v.insert(Some(def_id));
3620 }
3621 });
3622
3623 let mut map: DefIdMap<Symbol> = Default::default();
3625 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain(..) {
3626 use std::collections::hash_map::Entry::{Occupied, Vacant};
3627
3628 if let Some(def_id) = opt_def_id {
3629 match map.entry(def_id) {
3630 Occupied(mut v) => {
3631 if *v.get() != symbol && v.get().as_str() > symbol.as_str() {
3640 v.insert(symbol);
3641 }
3642 }
3643 Vacant(v) => {
3644 v.insert(symbol);
3645 }
3646 }
3647 }
3648 }
3649
3650 map
3651}
3652
3653pub fn provide(providers: &mut Providers) {
3654 *providers = Providers { trimmed_def_paths, ..*providers };
3655}
3656
3657pub struct OpaqueFnEntry<'tcx> {
3658 kind: ty::ClosureKind,
3659 return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,
3660}