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