1use std::cell::Cell;2use std::fmt::{self, Write as _};3use std::iter;4use std::ops::{Deref, DerefMut};56use rustc_abi::{ExternAbi, Size};7use rustc_apfloat::Float;8use rustc_apfloat::ieee::{Double, Half, Quad, Single};9use rustc_data_structures::fx::{FxIndexMap, IndexEntry};10use rustc_data_structures::unord::UnordMap;11use rustc_hir as hir;12use rustc_hir::LangItem;13use rustc_hir::def::{self, CtorKind, DefKind, Namespace};14use rustc_hir::def_id::{DefIdMap, DefIdSet, LOCAL_CRATE, ModDefId};15use rustc_hir::definitions::{DefKey, DefPathDataName};16use rustc_hir::limit::Limit;17use rustc_macros::{Lift, extension};18use rustc_session::cstore::{ExternCrate, ExternCrateSource};19use rustc_span::{Ident, RemapPathScopeComponents, Symbol, kw, sym};20use rustc_type_ir::{FieldInfo, Unnormalized, Upcast as _, elaborate};21use smallvec::SmallVec;2223// `pretty` is a separate module only for organization.24use super::*;25use crate::mir::interpret::{AllocRange, GlobalAlloc, Pointer, Provenance, Scalar};26use crate::query::{IntoQueryKey, Providers};27use crate::ty::{28 ConstInt, Expr, GenericArgKind, ParamConst, ScalarInt, Term, TermKind, TraitPredicate,29 TypeFoldable, TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt,30};3132thread_local! {33 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = const { Cell::new(false) };34 static SHOULD_PREFIX_WITH_CRATE_NAME: Cell<bool> = const { Cell::new(false) };35 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = const { Cell::new(false) };36 static NO_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };37 static FORCE_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };38 static REDUCED_QUERIES: Cell<bool> = const { Cell::new(false) };39 static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) };40 static NO_VISIBLE_PATH_IF_DOC_HIDDEN: Cell<bool> = const { Cell::new(false) };41 static RTN_MODE: Cell<RtnMode> = const { Cell::new(RtnMode::ForDiagnostic) };42}4344/// Rendering style for RTN types.45#[derive(Copy, Clone, PartialEq, Eq, Debug)]46pub enum RtnMode {47 /// Print the RTN type as an impl trait with its path, i.e.e `impl Sized { T::method(..) }`.48 ForDiagnostic,49 /// Print the RTN type as an impl trait, i.e. `impl Sized`.50 ForSignature,51 /// Print the RTN type as a value path, i.e. `T::method(..): ...`.52 ForSuggestion,53}5455macro_rules! define_helper {56 ($($(#[$a:meta])* fn $name:ident($helper:ident, $tl:ident);)+) => {57 $(58 #[must_use]59 pub struct $helper(bool);6061 impl $helper {62 pub fn new() -> $helper {63 $helper($tl.replace(true))64 }65 }6667 $(#[$a])*68 pub macro $name($e:expr) {69 {70 let _guard = $helper::new();71 $e72 }73 }7475 impl Drop for $helper {76 fn drop(&mut self) {77 $tl.set(self.0)78 }79 }8081 pub fn $name() -> bool {82 $tl.get()83 }84 )+85 }86}8788define_helper!(89 /// Avoids running select queries during any prints that occur90 /// during the closure. This may alter the appearance of some91 /// types (e.g. forcing verbose printing for opaque types).92 /// This method is used during some queries (e.g. `explicit_item_bounds`93 /// for opaque types), to ensure that any debug printing that94 /// occurs during the query computation does not end up recursively95 /// calling the same query.96 fn with_reduced_queries(ReducedQueriesGuard, REDUCED_QUERIES);97 /// Force us to name impls with just the filename/line number. We98 /// normally try to use types. But at some points, notably while printing99 /// cycle errors, this can result in extra or suboptimal error output,100 /// so this variable disables that check.101 fn with_forced_impl_filename_line(ForcedImplGuard, FORCE_IMPL_FILENAME_LINE);102 /// Adds the crate name prefix to paths where appropriate.103 /// Unlike `with_crate_prefix`, this unconditionally uses `tcx.crate_name` instead of sometimes104 /// using `crate::` for local items.105 ///106 /// Overrides `with_crate_prefix`.107108 // This function is used by `rustc_public` and downstream rustc-driver in109 // Ferrocene. Please check with them before removing it.110 fn with_resolve_crate_name(CrateNamePrefixGuard, SHOULD_PREFIX_WITH_CRATE_NAME);111 /// Adds the `crate::` prefix to paths where appropriate.112 ///113 /// Ignored if `with_resolve_crate_name` is active.114 fn with_crate_prefix(CratePrefixGuard, SHOULD_PREFIX_WITH_CRATE);115 /// Prevent path trimming if it is turned on. Path trimming affects `Display` impl116 /// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,117 /// if no other `Vec` is found.118 fn with_no_trimmed_paths(NoTrimmedGuard, NO_TRIMMED_PATH);119 fn with_forced_trimmed_paths(ForceTrimmedGuard, FORCE_TRIMMED_PATH);120 /// Prevent selection of visible paths. `Display` impl of DefId will prefer121 /// visible (public) reexports of types as paths.122 fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH);123 /// Prevent selection of visible paths if the paths are through a doc hidden path.124 fn with_no_visible_paths_if_doc_hidden(NoVisibleIfDocHiddenGuard, NO_VISIBLE_PATH_IF_DOC_HIDDEN);125);126127#[must_use]128pub struct RtnModeHelper(RtnMode);129130impl RtnModeHelper {131 pub fn with(mode: RtnMode) -> RtnModeHelper {132 RtnModeHelper(RTN_MODE.with(|c| c.replace(mode)))133 }134}135136impl Drop for RtnModeHelper {137 fn drop(&mut self) {138 RTN_MODE.with(|c| c.set(self.0))139 }140}141142/// Print types for the purposes of a suggestion.143///144/// Specifically, this will render RPITITs as `T::method(..)` which is suitable for145/// things like where-clauses.146pub macro with_types_for_suggestion($e:expr) {{147 let _guard = $crate::ty::print::pretty::RtnModeHelper::with(RtnMode::ForSuggestion);148 $e149}}150151/// Print types for the purposes of a signature suggestion.152///153/// Specifically, this will render RPITITs as `impl Trait` rather than `T::method(..)`.154pub macro with_types_for_signature($e:expr) {{155 let _guard = $crate::ty::print::pretty::RtnModeHelper::with(RtnMode::ForSignature);156 $e157}}158159/// Avoids running any queries during prints.160pub macro with_no_queries($e:expr) {{161 $crate::ty::print::with_reduced_queries!($crate::ty::print::with_forced_impl_filename_line!(162 $crate::ty::print::with_no_trimmed_paths!($crate::ty::print::with_no_visible_paths!($e))163 ))164}}165166#[derive(Copy, Clone, Debug, PartialEq, Eq)]167pub enum WrapBinderMode {168 ForAll,169 Unsafe,170}171impl WrapBinderMode {172 pub fn start_str(self) -> &'static str {173 match self {174 WrapBinderMode::ForAll => "for<",175 WrapBinderMode::Unsafe => "unsafe<",176 }177 }178}179180/// The "region highlights" are used to control region printing during181/// specific error messages. When a "region highlight" is enabled, it182/// gives an alternate way to print specific regions. For now, we183/// always print those regions using a number, so something like "`'0`".184///185/// Regions not selected by the region highlight mode are presently186/// unaffected.187#[derive(Copy, Clone, Default)]188pub struct RegionHighlightMode<'tcx> {189 /// If enabled, when we see the selected region, use "`'N`"190 /// instead of the ordinary behavior.191 highlight_regions: [Option<(ty::Region<'tcx>, usize)>; 3],192193 /// If enabled, when printing a "free region" that originated from194 /// the given `ty::BoundRegionKind`, print it as "`'1`". Free regions that would ordinarily195 /// have names print as normal.196 ///197 /// This is used when you have a signature like `fn foo(x: &u32,198 /// y: &'a u32)` and we want to give a name to the region of the199 /// reference `x`.200 highlight_bound_region: Option<(ty::BoundRegionKind<'tcx>, usize)>,201}202203impl<'tcx> RegionHighlightMode<'tcx> {204 /// If `region` and `number` are both `Some`, invokes205 /// `highlighting_region`.206 pub fn maybe_highlighting_region(207 &mut self,208 region: Option<ty::Region<'tcx>>,209 number: Option<usize>,210 ) {211 if let Some(k) = region212 && let Some(n) = number213 {214 self.highlighting_region(k, n);215 }216 }217218 /// Highlights the region inference variable `vid` as `'N`.219 pub fn highlighting_region(&mut self, region: ty::Region<'tcx>, number: usize) {220 let num_slots = self.highlight_regions.len();221 let first_avail_slot =222 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {223 bug!("can only highlight {} placeholders at a time", num_slots,)224 });225 *first_avail_slot = Some((region, number));226 }227228 /// Convenience wrapper for `highlighting_region`.229 pub fn highlighting_region_vid(230 &mut self,231 tcx: TyCtxt<'tcx>,232 vid: ty::RegionVid,233 number: usize,234 ) {235 self.highlighting_region(ty::Region::new_var(tcx, vid), number)236 }237238 /// Returns `Some(n)` with the number to use for the given region, if any.239 fn region_highlighted(&self, region: ty::Region<'tcx>) -> Option<usize> {240 self.highlight_regions.iter().find_map(|h| match h {241 Some((r, n)) if *r == region => Some(*n),242 _ => None,243 })244 }245246 /// Highlight the given bound region.247 /// We can only highlight one bound region at a time. See248 /// the field `highlight_bound_region` for more detailed notes.249 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind<'tcx>, number: usize) {250 assert!(self.highlight_bound_region.is_none());251 self.highlight_bound_region = Some((br, number));252 }253}254255/// Trait for printers that pretty-print using `fmt::Write` to the printer.256pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {257 /// Like `print_def_path` but for value paths.258 fn pretty_print_value_path(259 &mut self,260 def_id: DefId,261 args: &'tcx [GenericArg<'tcx>],262 ) -> Result<(), PrintError> {263 self.print_def_path(def_id, args)264 }265266 fn pretty_print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError>267 where268 T: Print<Self> + TypeFoldable<TyCtxt<'tcx>>,269 {270 value.as_ref().skip_binder().print(self)271 }272273 fn wrap_binder<T, F: FnOnce(&T, &mut Self) -> Result<(), fmt::Error>>(274 &mut self,275 value: &ty::Binder<'tcx, T>,276 _mode: WrapBinderMode,277 f: F,278 ) -> Result<(), PrintError>279 where280 T: TypeFoldable<TyCtxt<'tcx>>,281 {282 f(value.as_ref().skip_binder(), self)283 }284285 /// Prints comma-separated elements.286 fn comma_sep<T>(&mut self, mut elems: impl Iterator<Item = T>) -> Result<(), PrintError>287 where288 T: Print<Self>,289 {290 if let Some(first) = elems.next() {291 first.print(self)?;292 for elem in elems {293 self.write_str(", ")?;294 elem.print(self)?;295 }296 }297 Ok(())298 }299300 /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument301 fn typed_value(302 &mut self,303 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,304 t: impl FnOnce(&mut Self) -> Result<(), PrintError>,305 conversion: &str,306 ) -> Result<(), PrintError> {307 self.write_str("{")?;308 f(self)?;309 self.write_str(conversion)?;310 t(self)?;311 self.write_str("}")?;312 Ok(())313 }314315 /// Prints `(...)` around what `f` prints.316 fn parenthesized(317 &mut self,318 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,319 ) -> Result<(), PrintError> {320 self.write_str("(")?;321 f(self)?;322 self.write_str(")")?;323 Ok(())324 }325326 /// Prints `(...)` around what `f` prints if `parenthesized` is true, otherwise just prints `f`.327 fn maybe_parenthesized(328 &mut self,329 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,330 parenthesized: bool,331 ) -> Result<(), PrintError> {332 if parenthesized {333 self.parenthesized(f)?;334 } else {335 f(self)?;336 }337 Ok(())338 }339340 /// Prints `<...>` around what `f` prints.341 fn generic_delimiters(342 &mut self,343 f: impl FnOnce(&mut Self) -> Result<(), PrintError>,344 ) -> Result<(), PrintError>;345346 fn should_truncate(&mut self) -> bool {347 false348 }349350 /// Returns `true` if the region should be printed in optional positions,351 /// e.g., `&'a T` or `dyn Tr + 'b`. (Regions like the one in `Cow<'static, T>`352 /// will always be printed.)353 fn should_print_optional_region(&self, region: ty::Region<'tcx>) -> bool;354355 fn reset_type_limit(&mut self) {}356357 // Defaults (should not be overridden):358359 /// If possible, this returns a global path resolving to `def_id` that is visible360 /// from at least one local module, and returns `true`. If the crate defining `def_id` is361 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.362 fn try_print_visible_def_path(&mut self, def_id: DefId) -> Result<bool, PrintError> {363 if with_no_visible_paths() {364 return Ok(false);365 }366367 let mut callers = Vec::new();368 self.try_print_visible_def_path_recur(def_id, &mut callers)369 }370371 // Given a `DefId`, produce a short name. For types and traits, it prints *only* its name,372 // For associated items on traits it prints out the trait's name and the associated item's name.373 // For enum variants, if they have an unique name, then we only print the name, otherwise we374 // print the enum name and the variant name. Otherwise, we do not print anything and let the375 // caller use the `print_def_path` fallback.376 fn force_print_trimmed_def_path(&mut self, def_id: DefId) -> Result<bool, PrintError> {377 let key = self.tcx().def_key(def_id);378 let visible_parent_map = self.tcx().visible_parent_map(());379 let kind = self.tcx().def_kind(def_id);380381 let get_local_name = |this: &Self, name, def_id, key: DefKey| {382 if let Some(visible_parent) = visible_parent_map.get(&def_id)383 && let actual_parent = this.tcx().opt_parent(def_id)384 && let DefPathData::TypeNs(_) = key.disambiguated_data.data385 && Some(*visible_parent) != actual_parent386 {387 this.tcx()388 // FIXME(typed_def_id): Further propagate ModDefId389 .module_children(ModDefId::new_unchecked(*visible_parent))390 .iter()391 .filter(|child| child.res.opt_def_id() == Some(def_id))392 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)393 .map(|child| child.ident.name)394 .unwrap_or(name)395 } else {396 name397 }398 };399 if let DefKind::Variant = kind400 && let Some(symbol) = self.tcx().trimmed_def_paths(()).get(&def_id)401 {402 // If `Assoc` is unique, we don't want to talk about `Trait::Assoc`.403 self.write_str(get_local_name(self, *symbol, def_id, key).as_str())?;404 return Ok(true);405 }406 if let Some(symbol) = key.get_opt_name() {407 if let DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy = kind408 && let Some(parent) = self.tcx().opt_parent(def_id)409 && let parent_key = self.tcx().def_key(parent)410 && let Some(symbol) = parent_key.get_opt_name()411 {412 // Trait413 self.write_str(get_local_name(self, symbol, parent, parent_key).as_str())?;414 self.write_str("::")?;415 } else if let DefKind::Variant = kind416 && let Some(parent) = self.tcx().opt_parent(def_id)417 && let parent_key = self.tcx().def_key(parent)418 && let Some(symbol) = parent_key.get_opt_name()419 {420 // Enum421422 // For associated items and variants, we want the "full" path, namely, include423 // the parent type in the path. For example, `Iterator::Item`.424 self.write_str(get_local_name(self, symbol, parent, parent_key).as_str())?;425 self.write_str("::")?;426 } else if let DefKind::Struct427 | DefKind::Union428 | DefKind::Enum429 | DefKind::Trait430 | DefKind::TyAlias431 | DefKind::Fn432 | DefKind::Const { .. }433 | DefKind::Static { .. } = kind434 {435 } else {436 // If not covered above, like for example items out of `impl` blocks, fallback.437 return Ok(false);438 }439 self.write_str(get_local_name(self, symbol, def_id, key).as_str())?;440 return Ok(true);441 }442 Ok(false)443 }444445 /// Try to see if this path can be trimmed to a unique symbol name.446 fn try_print_trimmed_def_path(&mut self, def_id: DefId) -> Result<bool, PrintError> {447 if with_forced_trimmed_paths() && self.force_print_trimmed_def_path(def_id)? {448 return Ok(true);449 }450 if self.tcx().sess.opts.unstable_opts.trim_diagnostic_paths451 && self.tcx().sess.opts.trimmed_def_paths452 && !with_no_trimmed_paths()453 && !with_crate_prefix()454 && let Some(symbol) = self.tcx().trimmed_def_paths(()).get(&def_id)455 {456 write!(self, "{}", Ident::with_dummy_span(*symbol))?;457 Ok(true)458 } else {459 Ok(false)460 }461 }462463 /// Does the work of `try_print_visible_def_path`, building the464 /// full definition path recursively before attempting to465 /// post-process it into the valid and visible version that466 /// accounts for re-exports.467 ///468 /// This method should only be called by itself or469 /// `try_print_visible_def_path`.470 ///471 /// `callers` is a chain of visible_parent's leading to `def_id`,472 /// to support cycle detection during recursion.473 ///474 /// This method returns false if we can't print the visible path, so475 /// `print_def_path` can fall back on the item's real definition path.476 fn try_print_visible_def_path_recur(477 &mut self,478 def_id: DefId,479 callers: &mut Vec<DefId>,480 ) -> Result<bool, PrintError> {481 debug!("try_print_visible_def_path: def_id={:?}", def_id);482483 // If `def_id` is a direct or injected extern crate, return the484 // path to the crate followed by the path to the item within the crate.485 if let Some(cnum) = def_id.as_crate_root() {486 if cnum == LOCAL_CRATE {487 self.print_crate_name(cnum)?;488 return Ok(true);489 }490491 // In local mode, when we encounter a crate other than492 // LOCAL_CRATE, execution proceeds in one of two ways:493 //494 // 1. For a direct dependency, where user added an495 // `extern crate` manually, we put the `extern496 // crate` as the parent. So you wind up with497 // something relative to the current crate.498 // 2. For an extern inferred from a path or an indirect crate,499 // where there is no explicit `extern crate`, we just prepend500 // the crate name.501 match self.tcx().extern_crate(cnum) {502 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {503 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {504 // NOTE(eddyb) the only reason `span` might be dummy,505 // that we're aware of, is that it's the `std`/`core`506 // `extern crate` injected by default.507 // FIXME(eddyb) find something better to key this on,508 // or avoid ending up with `ExternCrateSource::Extern`,509 // for the injected `std`/`core`.510 if span.is_dummy() {511 self.print_crate_name(cnum)?;512 return Ok(true);513 }514515 // Disable `try_print_trimmed_def_path` behavior within516 // the `print_def_path` call, to avoid infinite recursion517 // in cases where the `extern crate foo` has non-trivial518 // parents, e.g. it's nested in `impl foo::Trait for Bar`519 // (see also issues #55779 and #87932).520 with_no_visible_paths!(self.print_def_path(def_id, &[])?);521522 return Ok(true);523 }524 (ExternCrateSource::Path, LOCAL_CRATE) => {525 self.print_crate_name(cnum)?;526 return Ok(true);527 }528 _ => {}529 },530 None => {531 self.print_crate_name(cnum)?;532 return Ok(true);533 }534 }535 }536537 if def_id.is_local() {538 return Ok(false);539 }540541 let visible_parent_map = self.tcx().visible_parent_map(());542543 let mut cur_def_key = self.tcx().def_key(def_id);544 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);545546 // For a constructor, we want the name of its parent rather than <unnamed>.547 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {548 let parent = DefId {549 krate: def_id.krate,550 index: cur_def_key551 .parent552 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),553 };554555 cur_def_key = self.tcx().def_key(parent);556 }557558 let Some(visible_parent) = visible_parent_map.get(&def_id).cloned() else {559 return Ok(false);560 };561562 if self.tcx().is_doc_hidden(visible_parent) && with_no_visible_paths_if_doc_hidden() {563 return Ok(false);564 }565566 let actual_parent = self.tcx().opt_parent(def_id);567 debug!(568 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",569 visible_parent, actual_parent,570 );571572 let mut data = cur_def_key.disambiguated_data.data;573 debug!(574 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",575 data, visible_parent, actual_parent,576 );577578 match data {579 // In order to output a path that could actually be imported (valid and visible),580 // we need to handle re-exports correctly.581 //582 // For example, take `std::os::unix::process::CommandExt`, this trait is actually583 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).584 //585 // `std::os::unix` reexports the contents of `std::sys::unix::ext`. `std::sys` is586 // private so the "true" path to `CommandExt` isn't accessible.587 //588 // In this case, the `visible_parent_map` will look something like this:589 //590 // (child) -> (parent)591 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`592 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`593 // `std::sys::unix::ext` -> `std::os`594 //595 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact596 // `std::os`.597 //598 // When printing the path to `CommandExt` and looking at the `cur_def_key` that599 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go600 // to the parent - resulting in a mangled path like601 // `std::os::ext::process::CommandExt`.602 //603 // Instead, we must detect that there was a re-export and instead print `unix`604 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To605 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with606 // the visible parent (`std::os`). If these do not match, then we iterate over607 // the children of the visible parent (as was done when computing608 // `visible_parent_map`), looking for the specific child we currently have and then609 // have access to the re-exported name.610 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {611 // Item might be re-exported several times, but filter for the one612 // that's public and whose identifier isn't `_`.613 let reexport = self614 .tcx()615 // FIXME(typed_def_id): Further propagate ModDefId616 .module_children(ModDefId::new_unchecked(visible_parent))617 .iter()618 .filter(|child| child.res.opt_def_id() == Some(def_id))619 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)620 .map(|child| child.ident.name);621622 if let Some(new_name) = reexport {623 *name = new_name;624 } else {625 // There is no name that is public and isn't `_`, so bail.626 return Ok(false);627 }628 }629 // Re-exported `extern crate` (#43189).630 DefPathData::CrateRoot => {631 data = DefPathData::TypeNs(self.tcx().crate_name(def_id.krate));632 }633 _ => {}634 }635 debug!("try_print_visible_def_path: data={:?}", data);636637 if callers.contains(&visible_parent) {638 return Ok(false);639 }640 callers.push(visible_parent);641 // HACK(eddyb) this bypasses `print_path_with_simple`'s prefix printing to avoid642 // knowing ahead of time whether the entire path will succeed or not.643 // To support printers that do not implement `PrettyPrinter`, a `Vec` or644 // linked list on the stack would need to be built, before any printing.645 match self.try_print_visible_def_path_recur(visible_parent, callers)? {646 false => return Ok(false),647 true => {}648 }649 callers.pop();650 self.print_path_with_simple(651 |_| Ok(()),652 &DisambiguatedDefPathData { data, disambiguator: 0 },653 )?;654 Ok(true)655 }656657 fn pretty_print_path_with_qualified(658 &mut self,659 self_ty: Ty<'tcx>,660 trait_ref: Option<ty::TraitRef<'tcx>>,661 ) -> Result<(), PrintError> {662 if trait_ref.is_none() {663 // Inherent impls. Try to print `Foo::bar` for an inherent664 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is665 // anything other than a simple path.666 match self_ty.kind() {667 ty::Adt(..)668 | ty::Foreign(_)669 | ty::Bool670 | ty::Char671 | ty::Str672 | ty::Int(_)673 | ty::Uint(_)674 | ty::Float(_) => {675 return self_ty.print(self);676 }677678 _ => {}679 }680 }681682 self.generic_delimiters(|p| {683 self_ty.print(p)?;684 if let Some(trait_ref) = trait_ref {685 write!(p, " as ")?;686 trait_ref.print_only_trait_path().print(p)?;687 }688 Ok(())689 })690 }691692 fn pretty_print_path_with_impl(693 &mut self,694 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,695 self_ty: Ty<'tcx>,696 trait_ref: Option<ty::TraitRef<'tcx>>,697 ) -> Result<(), PrintError> {698 print_prefix(self)?;699700 self.generic_delimiters(|p| {701 write!(p, "impl ")?;702 if let Some(trait_ref) = trait_ref {703 trait_ref.print_only_trait_path().print(p)?;704 write!(p, " for ")?;705 }706 self_ty.print(p)?;707708 Ok(())709 })710 }711712 fn pretty_print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {713 match *ty.kind() {714 ty::Bool => write!(self, "bool")?,715 ty::Char => write!(self, "char")?,716 ty::Int(t) => write!(self, "{}", t.name_str())?,717 ty::Uint(t) => write!(self, "{}", t.name_str())?,718 ty::Float(t) => write!(self, "{}", t.name_str())?,719 ty::Pat(ty, pat) => {720 write!(self, "(")?;721 ty.print(self)?;722 write!(self, ") is {pat:?}")?;723 }724 ty::RawPtr(ty, mutbl) => {725 write!(self, "*{} ", mutbl.ptr_str())?;726 ty.print(self)?;727 }728 ty::Ref(r, ty, mutbl) => {729 write!(self, "&")?;730 if self.should_print_optional_region(r) {731 r.print(self)?;732 write!(self, " ")?;733 }734 ty::TypeAndMut { ty, mutbl }.print(self)?;735 }736 ty::Never => write!(self, "!")?,737 ty::Tuple(tys) => {738 write!(self, "(")?;739 self.comma_sep(tys.iter())?;740 if tys.len() == 1 {741 write!(self, ",")?;742 }743 write!(self, ")")?;744 }745 ty::FnDef(def_id, args) => {746 if with_reduced_queries() {747 self.print_def_path(def_id, args)?;748 } else {749 let mut sig =750 self.tcx().fn_sig(def_id).instantiate(self.tcx(), args).skip_norm_wip();751 if self.tcx().codegen_fn_attrs(def_id).safe_target_features {752 write!(self, "#[target_features] ")?;753 sig = sig.map_bound(|mut sig| {754 sig.fn_sig_kind = sig.fn_sig_kind.set_safety(hir::Safety::Safe);755 sig756 });757 }758 sig.print(self)?;759 write!(self, " {{")?;760 self.pretty_print_value_path(def_id, args)?;761 write!(self, "}}")?;762 }763 }764 ty::FnPtr(ref sig_tys, hdr) => sig_tys.with(hdr).print(self)?,765 ty::UnsafeBinder(ref bound_ty) => {766 self.wrap_binder(bound_ty, WrapBinderMode::Unsafe, |ty, p| {767 p.pretty_print_type(*ty)768 })?;769 }770 ty::Infer(infer_ty) => {771 if self.should_print_verbose() {772 write!(self, "{:?}", ty.kind())?;773 return Ok(());774 }775776 if let ty::TyVar(ty_vid) = infer_ty {777 if let Some(name) = self.ty_infer_name(ty_vid) {778 write!(self, "{name}")?;779 } else {780 write!(self, "{infer_ty}")?;781 }782 } else {783 write!(self, "{infer_ty}")?;784 }785 }786 ty::Error(_) => write!(self, "{{type error}}")?,787 ty::Param(ref param_ty) => param_ty.print(self)?,788 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {789 ty::BoundTyKind::Anon => {790 rustc_type_ir::debug_bound_var(self, debruijn, bound_ty.var)?791 }792 ty::BoundTyKind::Param(def_id) => match self.should_print_verbose() {793 true => write!(self, "{:?}", ty.kind())?,794 false => write!(self, "{}", self.tcx().item_name(def_id))?,795 },796 },797 ty::Adt(def, args)798 if let Some(FieldInfo { base, variant, name, .. }) =799 def.field_representing_type_info(self.tcx(), args) =>800 {801 if let Some(variant) = variant {802 write!(self, "field_of!({base}, {variant}.{name})")?;803 } else {804 write!(self, "field_of!({base}, {name})")?;805 }806 }807 ty::Adt(def, args) => self.print_def_path(def.did(), args)?,808 ty::Dynamic(data, r) => {809 let print_r = self.should_print_optional_region(r);810 if print_r {811 write!(self, "(")?;812 }813 write!(self, "dyn ")?;814 data.print(self)?;815 if print_r {816 write!(self, " + ")?;817 r.print(self)?;818 write!(self, ")")?;819 }820 }821 ty::Foreign(def_id) => self.print_def_path(def_id, &[])?,822 ty::Alias(823 ref data @ ty::AliasTy {824 kind: ty::Projection { .. } | ty::Inherent { .. } | ty::Free { .. },825 ..826 },827 ) => data.print(self)?,828 ty::Placeholder(placeholder) => placeholder.print(self)?,829 ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {830 // We use verbose printing in 'NO_QUERIES' mode, to831 // avoid needing to call `predicates_of`. This should832 // only affect certain debug messages (e.g. messages printed833 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),834 // and should have no effect on any compiler output.835 // [Unless `-Zverbose-internals` is used, e.g. in the output of836 // `tests/ui/nll/ty-outlives/impl-trait-captures.rs`, for837 // example.]838 if self.should_print_verbose() {839 // FIXME(eddyb) print this with `print_def_path`.840 write!(self, "Opaque({:?}, {})", def_id, args.print_as_list())?;841 return Ok(());842 }843844 let parent = self.tcx().parent(def_id);845 match self.tcx().def_kind(parent) {846 DefKind::TyAlias | DefKind::AssocTy => {847 // NOTE: I know we should check for NO_QUERIES here, but it's alright.848 // `type_of` on a type alias or assoc type should never cause a cycle.849 if let ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id: d }, .. }) = *self850 .tcx()851 .type_of(parent)852 .instantiate_identity()853 .skip_norm_wip()854 .kind()855 {856 if d == def_id {857 // If the type alias directly starts with the `impl` of the858 // opaque type we're printing, then skip the `::{opaque#1}`.859 self.print_def_path(parent, args)?;860 return Ok(());861 }862 }863 // Complex opaque type, e.g. `type Foo = (i32, impl Debug);`864 self.print_def_path(def_id, args)?;865 return Ok(());866 }867 _ => {868 if with_reduced_queries() {869 self.print_def_path(def_id, &[])?;870 return Ok(());871 } else {872 return self.pretty_print_opaque_impl_type(def_id, args);873 }874 }875 }876 }877 ty::Str => write!(self, "str")?,878 ty::Coroutine(did, args) => {879 write!(self, "{{")?;880 let coroutine_kind = self.tcx().coroutine_kind(did).unwrap();881 let should_print_movability = self.should_print_verbose()882 || matches!(coroutine_kind, hir::CoroutineKind::Coroutine(_));883884 if should_print_movability {885 match coroutine_kind.movability() {886 hir::Movability::Movable => {}887 hir::Movability::Static => write!(self, "static ")?,888 }889 }890891 if !self.should_print_verbose() {892 write!(self, "{coroutine_kind}")?;893 if coroutine_kind.is_fn_like() {894 // If we are printing an `async fn` coroutine type, then give the path895 // of the fn, instead of its span, because that will in most cases be896 // more helpful for the reader than just a source location.897 //898 // This will look like:899 // {async fn body of some_fn()}900 let did_of_the_fn_item = self.tcx().parent(did);901 write!(self, " of ")?;902 self.print_def_path(did_of_the_fn_item, args)?;903 write!(self, "()")?;904 } else if let Some(local_did) = did.as_local() {905 let span = self.tcx().def_span(local_did);906 write!(907 self,908 "@{}",909 // This may end up in stderr diagnostics but it may also be emitted910 // into MIR. Hence we use the remapped path if available911 self.tcx().sess.source_map().span_to_diagnostic_string(span)912 )?;913 } else {914 write!(self, "@")?;915 self.print_def_path(did, args)?;916 }917 } else {918 self.print_def_path(did, args)?;919 write!(self, " upvar_tys=")?;920 args.as_coroutine().tupled_upvars_ty().print(self)?;921 write!(self, " resume_ty=")?;922 args.as_coroutine().resume_ty().print(self)?;923 write!(self, " yield_ty=")?;924 args.as_coroutine().yield_ty().print(self)?;925 write!(self, " return_ty=")?;926 args.as_coroutine().return_ty().print(self)?;927 }928929 write!(self, "}}")?930 }931 ty::CoroutineWitness(did, args) => {932 write!(self, "{{")?;933 if !self.tcx().sess.verbose_internals() {934 write!(self, "coroutine witness")?;935 if let Some(did) = did.as_local() {936 let span = self.tcx().def_span(did);937 write!(938 self,939 "@{}",940 // This may end up in stderr diagnostics but it may also be emitted941 // into MIR. Hence we use the remapped path if available942 self.tcx().sess.source_map().span_to_diagnostic_string(span)943 )?;944 } else {945 write!(self, "@")?;946 self.print_def_path(did, args)?;947 }948 } else {949 self.print_def_path(did, args)?;950 }951952 write!(self, "}}")?953 }954 ty::Closure(did, args) => {955 write!(self, "{{")?;956 if !self.should_print_verbose() {957 write!(self, "closure")?;958 if self.should_truncate() {959 write!(self, "@...}}")?;960 return Ok(());961 } else {962 if let Some(did) = did.as_local() {963 if self.tcx().sess.opts.unstable_opts.span_free_formats {964 write!(self, "@")?;965 self.print_def_path(did.to_def_id(), args)?;966 } else {967 let span = self.tcx().def_span(did);968 let loc = if with_forced_trimmed_paths() {969 self.tcx().sess.source_map().span_to_short_string(970 span,971 RemapPathScopeComponents::DIAGNOSTICS,972 )973 } else {974 self.tcx().sess.source_map().span_to_diagnostic_string(span)975 };976 write!(977 self,978 "@{}",979 // This may end up in stderr diagnostics but it may also be980 // emitted into MIR. Hence we use the remapped path if981 // available982 loc983 )?;984 }985 } else {986 write!(self, "@")?;987 self.print_def_path(did, args)?;988 }989 }990 } else {991 self.print_def_path(did, args)?;992 write!(self, " closure_kind_ty=")?;993 args.as_closure().kind_ty().print(self)?;994 write!(self, " closure_sig_as_fn_ptr_ty=")?;995 args.as_closure().sig_as_fn_ptr_ty().print(self)?;996 write!(self, " upvar_tys=")?;997 args.as_closure().tupled_upvars_ty().print(self)?;998 }999 write!(self, "}}")?;1000 }1001 ty::CoroutineClosure(did, args) => {1002 write!(self, "{{")?;1003 if !self.should_print_verbose() {1004 match self.tcx().coroutine_kind(self.tcx().coroutine_for_closure(did)).unwrap()1005 {1006 hir::CoroutineKind::Desugared(1007 hir::CoroutineDesugaring::Async,1008 hir::CoroutineSource::Closure,1009 ) => write!(self, "async closure")?,1010 hir::CoroutineKind::Desugared(1011 hir::CoroutineDesugaring::AsyncGen,1012 hir::CoroutineSource::Closure,1013 ) => write!(self, "async gen closure")?,1014 hir::CoroutineKind::Desugared(1015 hir::CoroutineDesugaring::Gen,1016 hir::CoroutineSource::Closure,1017 ) => write!(self, "gen closure")?,1018 _ => unreachable!(1019 "coroutine from coroutine-closure should have CoroutineSource::Closure"1020 ),1021 }1022 if let Some(did) = did.as_local() {1023 if self.tcx().sess.opts.unstable_opts.span_free_formats {1024 write!(self, "@")?;1025 self.print_def_path(did.to_def_id(), args)?;1026 } else {1027 let span = self.tcx().def_span(did);1028 // This may end up in stderr diagnostics but it may also be emitted1029 // into MIR. Hence we use the remapped path if available1030 let loc = if with_forced_trimmed_paths() {1031 self.tcx().sess.source_map().span_to_short_string(1032 span,1033 RemapPathScopeComponents::DIAGNOSTICS,1034 )1035 } else {1036 self.tcx().sess.source_map().span_to_diagnostic_string(span)1037 };1038 write!(self, "@{loc}")?;1039 }1040 } else {1041 write!(self, "@")?;1042 self.print_def_path(did, args)?;1043 }1044 } else {1045 self.print_def_path(did, args)?;1046 write!(self, " closure_kind_ty=")?;1047 args.as_coroutine_closure().kind_ty().print(self)?;1048 write!(self, " signature_parts_ty=")?;1049 args.as_coroutine_closure().signature_parts_ty().print(self)?;1050 write!(self, " upvar_tys=")?;1051 args.as_coroutine_closure().tupled_upvars_ty().print(self)?;1052 write!(self, " coroutine_captures_by_ref_ty=")?;1053 args.as_coroutine_closure().coroutine_captures_by_ref_ty().print(self)?;1054 }1055 write!(self, "}}")?;1056 }1057 ty::Array(ty, sz) => {1058 write!(self, "[")?;1059 ty.print(self)?;1060 write!(self, "; ")?;1061 sz.print(self)?;1062 write!(self, "]")?;1063 }1064 ty::Slice(ty) => {1065 write!(self, "[")?;1066 ty.print(self)?;1067 write!(self, "]")?;1068 }1069 }10701071 Ok(())1072 }10731074 fn pretty_print_opaque_impl_type(1075 &mut self,1076 def_id: DefId,1077 args: ty::GenericArgsRef<'tcx>,1078 ) -> Result<(), PrintError> {1079 let tcx = self.tcx();10801081 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,1082 // by looking up the projections associated with the def_id.1083 let bounds = tcx.explicit_item_bounds(def_id);10841085 let mut traits = FxIndexMap::default();1086 let mut fn_traits = FxIndexMap::default();1087 let mut lifetimes = SmallVec::<[ty::Region<'tcx>; 1]>::new();10881089 let mut has_sized_bound = false;1090 let mut has_negative_sized_bound = false;1091 let mut has_meta_sized_bound = false;10921093 for (predicate, _) in1094 bounds.iter_instantiated_copied(tcx, args).map(Unnormalized::skip_norm_wip)1095 {1096 let bound_predicate = predicate.kind();10971098 match bound_predicate.skip_binder() {1099 ty::ClauseKind::Trait(pred) => {1100 // With `feature(sized_hierarchy)`, don't print `?Sized` as an alias for1101 // `MetaSized`, and skip sizedness bounds to be added at the end.1102 match tcx.as_lang_item(pred.def_id()) {1103 Some(LangItem::Sized) => match pred.polarity {1104 ty::PredicatePolarity::Positive => {1105 has_sized_bound = true;1106 continue;1107 }1108 ty::PredicatePolarity::Negative => has_negative_sized_bound = true,1109 },1110 Some(LangItem::MetaSized) => {1111 has_meta_sized_bound = true;1112 continue;1113 }1114 Some(LangItem::PointeeSized) => {1115 bug!("`PointeeSized` is removed during lowering");1116 }1117 _ => (),1118 }11191120 self.insert_trait_and_projection(1121 bound_predicate.rebind(pred),1122 None,1123 &mut traits,1124 &mut fn_traits,1125 );1126 }1127 ty::ClauseKind::Projection(pred) => {1128 let proj = bound_predicate.rebind(pred);1129 let trait_ref = proj.map_bound(|proj| TraitPredicate {1130 trait_ref: proj.projection_term.trait_ref(tcx),1131 polarity: ty::PredicatePolarity::Positive,1132 });11331134 self.insert_trait_and_projection(1135 trait_ref,1136 Some((proj.item_def_id(), proj.term())),1137 &mut traits,1138 &mut fn_traits,1139 );1140 }1141 ty::ClauseKind::TypeOutlives(outlives) => {1142 lifetimes.push(outlives.1);1143 }1144 _ => {}1145 }1146 }11471148 write!(self, "impl ")?;11491150 let mut first = true;1151 // Insert parenthesis around (Fn(A, B) -> C) if the opaque ty has more than one other trait1152 let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !has_sized_bound;11531154 for ((bound_args_and_self_ty, is_async), entry) in fn_traits {1155 write!(self, "{}", if first { "" } else { " + " })?;1156 write!(self, "{}", if paren_needed { "(" } else { "" })?;11571158 let trait_def_id = if is_async {1159 tcx.async_fn_trait_kind_to_def_id(entry.kind).expect("expected AsyncFn lang items")1160 } else {1161 tcx.fn_trait_kind_to_def_id(entry.kind).expect("expected Fn lang items")1162 };11631164 if let Some(return_ty) = entry.return_ty {1165 self.wrap_binder(1166 &bound_args_and_self_ty,1167 WrapBinderMode::ForAll,1168 |(args, _), p| {1169 write!(p, "{}", tcx.item_name(trait_def_id))?;1170 write!(p, "(")?;11711172 for (idx, ty) in args.iter().enumerate() {1173 if idx > 0 {1174 write!(p, ", ")?;1175 }1176 ty.print(p)?;1177 }11781179 write!(p, ")")?;1180 if let Some(ty) = return_ty.skip_binder().as_type() {1181 if !ty.is_unit() {1182 write!(p, " -> ")?;1183 return_ty.print(p)?;1184 }1185 }1186 write!(p, "{}", if paren_needed { ")" } else { "" })?;11871188 first = false;1189 Ok(())1190 },1191 )?;1192 } else {1193 // Otherwise, render this like a regular trait.1194 traits.insert(1195 bound_args_and_self_ty.map_bound(|(args, self_ty)| ty::TraitPredicate {1196 polarity: ty::PredicatePolarity::Positive,1197 trait_ref: ty::TraitRef::new(1198 tcx,1199 trait_def_id,1200 [self_ty, Ty::new_tup(tcx, args)],1201 ),1202 }),1203 FxIndexMap::default(),1204 );1205 }1206 }12071208 // Print the rest of the trait types (that aren't Fn* family of traits)1209 for (trait_pred, assoc_items) in traits {1210 write!(self, "{}", if first { "" } else { " + " })?;12111212 self.wrap_binder(&trait_pred, WrapBinderMode::ForAll, |trait_pred, p| {1213 if trait_pred.polarity == ty::PredicatePolarity::Negative {1214 write!(p, "!")?;1215 }1216 trait_pred.trait_ref.print_only_trait_name().print(p)?;12171218 let generics = tcx.generics_of(trait_pred.def_id());1219 let own_args = generics.own_args_no_defaults(tcx, trait_pred.trait_ref.args);12201221 if !own_args.is_empty() || !assoc_items.is_empty() {1222 let mut first = true;12231224 for ty in own_args {1225 if first {1226 write!(p, "<")?;1227 first = false;1228 } else {1229 write!(p, ", ")?;1230 }1231 ty.print(p)?;1232 }12331234 for (assoc_item_def_id, term) in assoc_items {1235 if first {1236 write!(p, "<")?;1237 first = false;1238 } else {1239 write!(p, ", ")?;1240 }12411242 write!(p, "{} = ", tcx.associated_item(assoc_item_def_id).name())?;12431244 match term.skip_binder().kind() {1245 TermKind::Ty(ty) => ty.print(p)?,1246 TermKind::Const(c) => c.print(p)?,1247 };1248 }12491250 if !first {1251 write!(p, ">")?;1252 }1253 }12541255 first = false;1256 Ok(())1257 })?;1258 }12591260 let using_sized_hierarchy = self.tcx().features().sized_hierarchy();1261 let add_sized = has_sized_bound && (first || has_negative_sized_bound);1262 let add_maybe_sized =1263 has_meta_sized_bound && !has_negative_sized_bound && !using_sized_hierarchy;1264 // Set `has_pointee_sized_bound` if there were no `Sized` or `MetaSized` bounds.1265 let has_pointee_sized_bound =1266 !has_sized_bound && !has_meta_sized_bound && !has_negative_sized_bound;1267 if add_sized || add_maybe_sized {1268 if !first {1269 write!(self, " + ")?;1270 }1271 if add_maybe_sized {1272 write!(self, "?")?;1273 }1274 write!(self, "Sized")?;1275 } else if has_meta_sized_bound && using_sized_hierarchy {1276 if !first {1277 write!(self, " + ")?;1278 }1279 write!(self, "MetaSized")?;1280 } else if has_pointee_sized_bound && using_sized_hierarchy {1281 if !first {1282 write!(self, " + ")?;1283 }1284 write!(self, "PointeeSized")?;1285 }12861287 if !with_forced_trimmed_paths() {1288 for re in lifetimes {1289 write!(self, " + ")?;1290 self.print_region(re)?;1291 }1292 }12931294 Ok(())1295 }12961297 /// Insert the trait ref and optionally a projection type associated with it into either the1298 /// traits map or fn_traits map, depending on if the trait is in the Fn* family of traits.1299 fn insert_trait_and_projection(1300 &mut self,1301 trait_pred: ty::PolyTraitPredicate<'tcx>,1302 proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,1303 traits: &mut FxIndexMap<1304 ty::PolyTraitPredicate<'tcx>,1305 FxIndexMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,1306 >,1307 fn_traits: &mut FxIndexMap<1308 (ty::Binder<'tcx, (&'tcx ty::List<Ty<'tcx>>, Ty<'tcx>)>, bool),1309 OpaqueFnEntry<'tcx>,1310 >,1311 ) {1312 let tcx = self.tcx();1313 let trait_def_id = trait_pred.def_id();13141315 let fn_trait_and_async = if let Some(kind) = tcx.fn_trait_kind_from_def_id(trait_def_id) {1316 Some((kind, false))1317 } else if let Some(kind) = tcx.async_fn_trait_kind_from_def_id(trait_def_id) {1318 Some((kind, true))1319 } else {1320 None1321 };13221323 if trait_pred.polarity() == ty::PredicatePolarity::Positive1324 && let Some((kind, is_async)) = fn_trait_and_async1325 && let ty::Tuple(types) = *trait_pred.skip_binder().trait_ref.args.type_at(1).kind()1326 {1327 let entry = fn_traits1328 .entry((trait_pred.rebind((types, trait_pred.skip_binder().self_ty())), is_async))1329 .or_insert_with(|| OpaqueFnEntry { kind, return_ty: None });1330 if kind.extends(entry.kind) {1331 entry.kind = kind;1332 }1333 if let Some((proj_def_id, proj_ty)) = proj_ty1334 && tcx.item_name(proj_def_id) == sym::Output1335 {1336 entry.return_ty = Some(proj_ty);1337 }1338 return;1339 }13401341 // Otherwise, just group our traits and projection types.1342 traits.entry(trait_pred).or_default().extend(proj_ty);1343 }13441345 fn pretty_print_inherent_projection(1346 &mut self,1347 alias_term: ty::AliasTerm<'tcx>,1348 ) -> Result<(), PrintError> {1349 let alias_def_id = alias_term.expect_inherent_def_id();1350 let def_key = self.tcx().def_key(alias_def_id);1351 self.print_path_with_generic_args(1352 |p| {1353 p.print_path_with_simple(1354 |p| p.print_path_with_qualified(alias_term.self_ty(), None),1355 &def_key.disambiguated_data,1356 )1357 },1358 &alias_term.args[1..],1359 )1360 }13611362 fn pretty_print_rpitit(1363 &mut self,1364 def_id: DefId,1365 args: ty::GenericArgsRef<'tcx>,1366 ) -> Result<(), PrintError> {1367 let fn_args = if self.tcx().features().return_type_notation()1368 && let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, .. }) =1369 self.tcx().opt_rpitit_info(def_id)1370 && let ty::Alias(alias_ty) =1371 self.tcx().fn_sig(fn_def_id).skip_binder().output().skip_binder().kind()1372 && alias_ty.kind.def_id() == def_id1373 && let generics = self.tcx().generics_of(fn_def_id)1374 // FIXME(return_type_notation): We only support lifetime params for now.1375 && generics.own_params.iter().all(|param| matches!(param.kind, ty::GenericParamDefKind::Lifetime))1376 {1377 let num_args = generics.count();1378 Some((fn_def_id, &args[..num_args]))1379 } else {1380 None1381 };13821383 match (fn_args, RTN_MODE.with(|c| c.get())) {1384 (Some((fn_def_id, fn_args)), RtnMode::ForDiagnostic) => {1385 self.pretty_print_opaque_impl_type(def_id, args)?;1386 write!(self, " {{ ")?;1387 self.print_def_path(fn_def_id, fn_args)?;1388 write!(self, "(..) }}")?;1389 }1390 (Some((fn_def_id, fn_args)), RtnMode::ForSuggestion) => {1391 self.print_def_path(fn_def_id, fn_args)?;1392 write!(self, "(..)")?;1393 }1394 _ => {1395 self.pretty_print_opaque_impl_type(def_id, args)?;1396 }1397 }13981399 Ok(())1400 }14011402 fn ty_infer_name(&self, _: ty::TyVid) -> Option<Symbol> {1403 None1404 }14051406 fn const_infer_name(&self, _: ty::ConstVid) -> Option<Symbol> {1407 None1408 }14091410 fn pretty_print_dyn_existential(1411 &mut self,1412 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,1413 ) -> Result<(), PrintError> {1414 // Generate the main trait ref, including associated types.1415 let mut first = true;14161417 if let Some(bound_principal) = predicates.principal() {1418 self.wrap_binder(&bound_principal, WrapBinderMode::ForAll, |principal, p| {1419 p.print_def_path(principal.def_id, &[])?;14201421 let mut resugared = false;14221423 // Special-case `Fn(...) -> ...` and re-sugar it.1424 let fn_trait_kind = p.tcx().fn_trait_kind_from_def_id(principal.def_id);1425 if !p.should_print_verbose() && fn_trait_kind.is_some() {1426 if let ty::Tuple(tys) = principal.args.type_at(0).kind() {1427 let mut projections = predicates.projection_bounds();1428 if let (Some(proj), None) = (projections.next(), projections.next()) {1429 p.pretty_print_fn_sig(1430 tys,1431 false,1432 proj.skip_binder().term.as_type().expect("Return type was a const"),1433 )?;1434 resugared = true;1435 }1436 }1437 }14381439 // HACK(eddyb) this duplicates `FmtPrinter`'s `print_path_with_generic_args`,1440 // in order to place the projections inside the `<...>`.1441 if !resugared {1442 let principal_with_self =1443 principal.with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self);14441445 let args = p1446 .tcx()1447 .generics_of(principal_with_self.def_id)1448 .own_args_no_defaults(p.tcx(), principal_with_self.args);14491450 let bound_principal_with_self = bound_principal1451 .with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self);14521453 let clause: ty::Clause<'tcx> = bound_principal_with_self.upcast(p.tcx());1454 let super_projections: Vec<_> = elaborate::elaborate(p.tcx(), [clause])1455 .filter_only_self()1456 .filter_map(|clause| clause.as_projection_clause())1457 .collect();14581459 let mut projections: Vec<_> = predicates1460 .projection_bounds()1461 .filter(|&proj| {1462 // Filter out projections that are implied by the super predicates.1463 let proj_is_implied = super_projections.iter().any(|&super_proj| {1464 let super_proj = super_proj.map_bound(|super_proj| {1465 ty::ExistentialProjection::erase_self_ty(p.tcx(), super_proj)1466 });14671468 // This function is sometimes called on types with erased and1469 // anonymized regions, but the super projections can still1470 // contain named regions. So we erase and anonymize everything1471 // here to compare the types modulo regions below.1472 let proj = p.tcx().erase_and_anonymize_regions(proj);1473 let super_proj = p.tcx().erase_and_anonymize_regions(super_proj);14741475 proj == super_proj1476 });1477 !proj_is_implied1478 })1479 .map(|proj| {1480 // Skip the binder, because we don't want to print the binder in1481 // front of the associated item.1482 proj.skip_binder()1483 })1484 .collect();14851486 projections1487 .sort_by_cached_key(|proj| p.tcx().item_name(proj.def_id).to_string());14881489 if !args.is_empty() || !projections.is_empty() {1490 p.generic_delimiters(|p| {1491 p.comma_sep(args.iter().copied())?;1492 if !args.is_empty() && !projections.is_empty() {1493 write!(p, ", ")?;1494 }1495 p.comma_sep(projections.iter().copied())1496 })?;1497 }1498 }1499 Ok(())1500 })?;15011502 first = false;1503 }15041505 // Builtin bounds.1506 // FIXME(eddyb) avoid printing twice (needed to ensure1507 // that the auto traits are sorted *and* printed via p).1508 let mut auto_traits: Vec<_> = predicates.auto_traits().collect();15091510 // The auto traits come ordered by `DefPathHash`. While1511 // `DefPathHash` is *stable* in the sense that it depends on1512 // neither the host nor the phase of the moon, it depends1513 // "pseudorandomly" on the compiler version and the target.1514 //1515 // To avoid causing instabilities in compiletest1516 // output, sort the auto-traits alphabetically.1517 auto_traits.sort_by_cached_key(|did| with_no_trimmed_paths!(self.tcx().def_path_str(*did)));15181519 for def_id in auto_traits {1520 if !first {1521 write!(self, " + ")?;1522 }1523 first = false;15241525 self.print_def_path(def_id, &[])?;1526 }15271528 Ok(())1529 }15301531 fn pretty_print_fn_sig(1532 &mut self,1533 inputs: &[Ty<'tcx>],1534 c_variadic: bool,1535 output: Ty<'tcx>,1536 ) -> Result<(), PrintError> {1537 write!(self, "(")?;1538 self.comma_sep(inputs.iter().copied())?;1539 if c_variadic {1540 if !inputs.is_empty() {1541 write!(self, ", ")?;1542 }1543 write!(self, "...")?;1544 }1545 write!(self, ")")?;1546 if !output.is_unit() {1547 write!(self, " -> ")?;1548 output.print(self)?;1549 }15501551 Ok(())1552 }15531554 fn pretty_print_const(1555 &mut self,1556 ct: ty::Const<'tcx>,1557 print_ty: bool,1558 ) -> Result<(), PrintError> {1559 if self.should_print_verbose() {1560 write!(self, "{ct:?}")?;1561 return Ok(());1562 }15631564 match ct.kind() {1565 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { kind, args, .. }) => {1566 match kind {1567 ty::UnevaluatedConstKind::Projection { def_id }1568 | ty::UnevaluatedConstKind::Inherent { def_id }1569 | ty::UnevaluatedConstKind::Free { def_id } => {1570 self.pretty_print_value_path(def_id, args)?;1571 }1572 ty::UnevaluatedConstKind::Anon { def_id } => {1573 if def_id.is_local()1574 && let span = self.tcx().def_span(def_id)1575 && let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)1576 {1577 write!(self, "{snip}")?;1578 } else {1579 // Do not call `pretty_print_value_path` as if a parent of this anon1580 // const is an impl it will attempt to print out the impl trait ref1581 // i.e. `<T as Trait>::{constant#0}`. This would cause printing to1582 // enter an infinite recursion if the anon const is in the self type1583 // i.e. `impl<T: Default> Default for [T; 32 - 1 - 1 - 1] {` where we1584 // would try to print `<[T; /* print constant#0 again */] as //1585 // Default>::{constant#0}`.1586 write!(1587 self,1588 "{}::{}",1589 self.tcx().crate_name(def_id.krate),1590 self.tcx().def_path(def_id).to_string_no_crate_verbose()1591 )?;1592 }1593 }1594 }1595 }1596 ty::ConstKind::Infer(infer_ct) => match infer_ct {1597 ty::InferConst::Var(ct_vid) if let Some(name) = self.const_infer_name(ct_vid) => {1598 write!(self, "{name}")?;1599 }1600 _ => write!(self, "_")?,1601 },1602 ty::ConstKind::Param(ParamConst { name, .. }) => write!(self, "{name}")?,1603 ty::ConstKind::Value(cv) => {1604 return self.pretty_print_const_valtree(cv, print_ty);1605 }16061607 ty::ConstKind::Bound(debruijn, bound_var) => {1608 rustc_type_ir::debug_bound_var(self, debruijn, bound_var)?1609 }1610 ty::ConstKind::Placeholder(placeholder) => write!(self, "{placeholder:?}")?,1611 // FIXME(generic_const_exprs):1612 // write out some legible representation of an abstract const?1613 ty::ConstKind::Expr(expr) => self.pretty_print_const_expr(expr, print_ty)?,1614 ty::ConstKind::Error(_) => write!(self, "{{const error}}")?,1615 };1616 Ok(())1617 }16181619 fn pretty_print_const_expr(1620 &mut self,1621 expr: Expr<'tcx>,1622 print_ty: bool,1623 ) -> Result<(), PrintError> {1624 match expr.kind {1625 ty::ExprKind::Binop(op) => {1626 let (_, _, c1, c2) = expr.binop_args();16271628 let precedence = |binop: crate::mir::BinOp| binop.to_hir_binop().precedence();1629 let op_precedence = precedence(op);1630 let formatted_op = op.to_hir_binop().as_str();1631 let (lhs_parenthesized, rhs_parenthesized) = match (c1.kind(), c2.kind()) {1632 (1633 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),1634 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),1635 ) => (precedence(lhs_op) < op_precedence, precedence(rhs_op) < op_precedence),1636 (1637 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),1638 ty::ConstKind::Expr(_),1639 ) => (precedence(lhs_op) < op_precedence, true),1640 (1641 ty::ConstKind::Expr(_),1642 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),1643 ) => (true, precedence(rhs_op) < op_precedence),1644 (ty::ConstKind::Expr(_), ty::ConstKind::Expr(_)) => (true, true),1645 (1646 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(lhs_op), .. }),1647 _,1648 ) => (precedence(lhs_op) < op_precedence, false),1649 (1650 _,1651 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::Binop(rhs_op), .. }),1652 ) => (false, precedence(rhs_op) < op_precedence),1653 (ty::ConstKind::Expr(_), _) => (true, false),1654 (_, ty::ConstKind::Expr(_)) => (false, true),1655 _ => (false, false),1656 };16571658 self.maybe_parenthesized(1659 |this| this.pretty_print_const(c1, print_ty),1660 lhs_parenthesized,1661 )?;1662 write!(self, " {formatted_op} ")?;1663 self.maybe_parenthesized(1664 |this| this.pretty_print_const(c2, print_ty),1665 rhs_parenthesized,1666 )?;1667 }1668 ty::ExprKind::UnOp(op) => {1669 let (_, ct) = expr.unop_args();16701671 use crate::mir::UnOp;1672 let formatted_op = match op {1673 UnOp::Not => "!",1674 UnOp::Neg => "-",1675 UnOp::PtrMetadata => "PtrMetadata",1676 };1677 let parenthesized = match ct.kind() {1678 _ if op == UnOp::PtrMetadata => true,1679 ty::ConstKind::Expr(ty::Expr { kind: ty::ExprKind::UnOp(c_op), .. }) => {1680 c_op != op1681 }1682 ty::ConstKind::Expr(_) => true,1683 _ => false,1684 };1685 write!(self, "{formatted_op}")?;1686 self.maybe_parenthesized(1687 |this| this.pretty_print_const(ct, print_ty),1688 parenthesized,1689 )?1690 }1691 ty::ExprKind::FunctionCall => {1692 let (_, fn_def, fn_args) = expr.call_args();16931694 write!(self, "(")?;1695 self.pretty_print_const(fn_def, print_ty)?;1696 write!(self, ")(")?;1697 self.comma_sep(fn_args)?;1698 write!(self, ")")?;1699 }1700 ty::ExprKind::Cast(kind) => {1701 let (_, value, to_ty) = expr.cast_args();17021703 use ty::abstract_const::CastKind;1704 if kind == CastKind::As || (kind == CastKind::Use && self.should_print_verbose()) {1705 let parenthesized = match value.kind() {1706 ty::ConstKind::Expr(ty::Expr {1707 kind: ty::ExprKind::Cast { .. }, ..1708 }) => false,1709 ty::ConstKind::Expr(_) => true,1710 _ => false,1711 };1712 self.maybe_parenthesized(1713 |this| {1714 this.typed_value(1715 |this| this.pretty_print_const(value, print_ty),1716 |this| this.pretty_print_type(to_ty),1717 " as ",1718 )1719 },1720 parenthesized,1721 )?;1722 } else {1723 self.pretty_print_const(value, print_ty)?1724 }1725 }1726 }1727 Ok(())1728 }17291730 fn pretty_print_const_scalar(1731 &mut self,1732 scalar: Scalar,1733 ty: Ty<'tcx>,1734 ) -> Result<(), PrintError> {1735 match scalar {1736 Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty),1737 Scalar::Int(int) => {1738 self.pretty_print_const_scalar_int(int, ty, /* print_ty */ true)1739 }1740 }1741 }17421743 fn pretty_print_const_scalar_ptr(1744 &mut self,1745 ptr: Pointer,1746 ty: Ty<'tcx>,1747 ) -> Result<(), PrintError> {1748 let (prov, offset) = ptr.prov_and_relative_offset();1749 match ty.kind() {1750 // Byte strings (&[u8; N])1751 ty::Ref(_, inner, _) => {1752 if let ty::Array(elem, ct_len) = inner.kind()1753 && let ty::Uint(ty::UintTy::U8) = elem.kind()1754 && let Some(len) = ct_len.try_to_target_usize(self.tcx())1755 {1756 match self.tcx().try_get_global_alloc(prov.alloc_id()) {1757 Some(GlobalAlloc::Memory(alloc)) => {1758 let range = AllocRange { start: offset, size: Size::from_bytes(len) };1759 if let Ok(byte_str) =1760 alloc.inner().get_bytes_strip_provenance(&self.tcx(), range)1761 {1762 self.pretty_print_byte_str(byte_str)?;1763 } else {1764 write!(self, "<too short allocation>")?;1765 }1766 }1767 // FIXME: for statics, vtables, and functions, we could in principle print more detail.1768 Some(GlobalAlloc::Static(def_id)) => {1769 write!(self, "<static({def_id:?})>")?;1770 }1771 Some(GlobalAlloc::Function { .. }) => write!(self, "<function>")?,1772 Some(GlobalAlloc::VTable(..)) => write!(self, "<vtable>")?,1773 Some(GlobalAlloc::TypeId { .. }) => write!(self, "<typeid>")?,1774 None => write!(self, "<dangling pointer>")?,1775 }1776 return Ok(());1777 }1778 }1779 ty::FnPtr(..) => {1780 // FIXME: We should probably have a helper method to share code with the "Byte strings"1781 // printing above (which also has to handle pointers to all sorts of things).1782 if let Some(GlobalAlloc::Function { instance, .. }) =1783 self.tcx().try_get_global_alloc(prov.alloc_id())1784 {1785 self.typed_value(1786 |this| this.pretty_print_value_path(instance.def_id(), instance.args),1787 |this| this.print_type(ty),1788 " as ",1789 )?;1790 return Ok(());1791 }1792 }1793 _ => {}1794 }1795 // Any pointer values not covered by a branch above1796 self.pretty_print_const_pointer(ptr, ty)?;1797 Ok(())1798 }17991800 fn pretty_print_const_scalar_int(1801 &mut self,1802 int: ScalarInt,1803 ty: Ty<'tcx>,1804 print_ty: bool,1805 ) -> Result<(), PrintError> {1806 match ty.kind() {1807 // Bool1808 ty::Bool if int == ScalarInt::FALSE => write!(self, "false")?,1809 ty::Bool if int == ScalarInt::TRUE => write!(self, "true")?,1810 // Float1811 ty::Float(fty) => match fty {1812 ty::FloatTy::F16 => {1813 let val = Half::try_from(int).unwrap();1814 write!(self, "{}{}f16", val, if val.is_finite() { "" } else { "_" })?;1815 }1816 ty::FloatTy::F32 => {1817 let val = Single::try_from(int).unwrap();1818 write!(self, "{}{}f32", val, if val.is_finite() { "" } else { "_" })?;1819 }1820 ty::FloatTy::F64 => {1821 let val = Double::try_from(int).unwrap();1822 write!(self, "{}{}f64", val, if val.is_finite() { "" } else { "_" })?;1823 }1824 ty::FloatTy::F128 => {1825 let val = Quad::try_from(int).unwrap();1826 write!(self, "{}{}f128", val, if val.is_finite() { "" } else { "_" })?;1827 }1828 },1829 // Int1830 ty::Uint(_) | ty::Int(_) => {1831 let int =1832 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());1833 if print_ty { write!(self, "{int:#?}")? } else { write!(self, "{int:?}")? }1834 }1835 // Char1836 ty::Char if char::try_from(int).is_ok() => {1837 write!(self, "{:?}", char::try_from(int).unwrap())?;1838 }1839 // Pointer types1840 ty::Ref(..) | ty::RawPtr(_, _) | ty::FnPtr(..) => {1841 let data = int.to_bits(self.tcx().data_layout.pointer_size());1842 self.typed_value(1843 |this| {1844 write!(this, "0x{data:x}")?;1845 Ok(())1846 },1847 |this| this.print_type(ty),1848 " as ",1849 )?;1850 }1851 ty::Pat(base_ty, pat) if self.tcx().validate_scalar_in_layout(int, ty) => {1852 self.pretty_print_const_scalar_int(int, *base_ty, print_ty)?;1853 write!(self, " is {pat:?}")?;1854 }1855 // Nontrivial types with scalar bit representation1856 _ => {1857 let print = |this: &mut Self| {1858 if int.size() == Size::ZERO {1859 write!(this, "transmute(())")?;1860 } else {1861 write!(this, "transmute(0x{int:x})")?;1862 }1863 Ok(())1864 };1865 if print_ty {1866 self.typed_value(print, |this| this.print_type(ty), ": ")?1867 } else {1868 print(self)?1869 };1870 }1871 }1872 Ok(())1873 }18741875 /// This is overridden for MIR printing because we only want to hide alloc ids from users, not1876 /// from MIR where it is actually useful.1877 fn pretty_print_const_pointer<Prov: Provenance>(1878 &mut self,1879 _: Pointer<Prov>,1880 ty: Ty<'tcx>,1881 ) -> Result<(), PrintError> {1882 self.typed_value(1883 |this| {1884 this.write_str("&_")?;1885 Ok(())1886 },1887 |this| this.print_type(ty),1888 ": ",1889 )1890 }18911892 fn pretty_print_byte_str(&mut self, byte_str: &'tcx [u8]) -> Result<(), PrintError> {1893 write!(self, "b\"{}\"", byte_str.escape_ascii())?;1894 Ok(())1895 }18961897 fn pretty_print_const_valtree(1898 &mut self,1899 cv: ty::Value<'tcx>,1900 print_ty: bool,1901 ) -> Result<(), PrintError> {1902 if with_reduced_queries() || self.should_print_verbose() {1903 write!(self, "ValTree({:?}: ", cv.valtree)?;1904 cv.ty.print(self)?;1905 write!(self, ")")?;1906 return Ok(());1907 }19081909 let u8_type = self.tcx().types.u8;1910 match (*cv.valtree, *cv.ty.kind()) {1911 (ty::ValTreeKind::Branch(_), ty::Ref(_, inner_ty, _)) => match inner_ty.kind() {1912 ty::Slice(t) if *t == u8_type => {1913 let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {1914 bug!(1915 "expected to convert valtree {:?} to raw bytes for type {:?}",1916 cv.valtree,1917 t1918 )1919 });1920 return self.pretty_print_byte_str(bytes);1921 }1922 ty::Str => {1923 let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| {1924 bug!("expected to convert valtree to raw bytes for type {:?}", cv.ty)1925 });1926 write!(self, "{:?}", String::from_utf8_lossy(bytes))?;1927 return Ok(());1928 }1929 _ => {1930 let cv = ty::Value { valtree: cv.valtree, ty: inner_ty };1931 write!(self, "&")?;1932 self.pretty_print_const_valtree(cv, print_ty)?;1933 return Ok(());1934 }1935 },1936 // If it is a branch with an array, and this array can be printed as raw bytes, then dump its bytes1937 (ty::ValTreeKind::Branch(_), ty::Array(t, _))1938 if t == u8_type1939 && let Some(bytes) = cv.try_to_raw_bytes(self.tcx()) =>1940 {1941 write!(self, "*")?;1942 self.pretty_print_byte_str(bytes)?;1943 return Ok(());1944 }1945 // Otherwise, print the array separated by commas (or if it's a tuple)1946 (ty::ValTreeKind::Branch(fields), ty::Array(..) | ty::Tuple(..)) => {1947 let fields_iter = fields.iter();19481949 match *cv.ty.kind() {1950 ty::Array(..) => {1951 write!(self, "[")?;1952 self.comma_sep(fields_iter)?;1953 write!(self, "]")?;1954 }1955 ty::Tuple(..) => {1956 write!(self, "(")?;1957 self.comma_sep(fields_iter)?;1958 if fields.len() == 1 {1959 write!(self, ",")?;1960 }1961 write!(self, ")")?;1962 }1963 _ => unreachable!(),1964 }1965 return Ok(());1966 }1967 (ty::ValTreeKind::Branch(_), ty::Adt(def, args)) => {1968 let contents = cv.destructure_adt_const();1969 let fields = contents.fields.iter().copied();19701971 if def.variants().is_empty() {1972 self.typed_value(1973 |this| {1974 write!(this, "unreachable()")?;1975 Ok(())1976 },1977 |this| this.print_type(cv.ty),1978 ": ",1979 )?;1980 } else {1981 let variant_idx = contents.variant;1982 let variant_def = &def.variant(variant_idx);1983 self.pretty_print_value_path(variant_def.def_id, args)?;1984 match variant_def.ctor_kind() {1985 Some(CtorKind::Const) => {}1986 Some(CtorKind::Fn) => {1987 write!(self, "(")?;1988 self.comma_sep(fields)?;1989 write!(self, ")")?;1990 }1991 None => {1992 write!(self, " {{ ")?;1993 let mut first = true;1994 for (field_def, field) in iter::zip(&variant_def.fields, fields) {1995 if !first {1996 write!(self, ", ")?;1997 }1998 write!(self, "{}: ", field_def.name)?;1999 field.print(self)?;2000 first = false;
Findings
✓ No findings reported for this file.