diff options
Diffstat (limited to 'compiler/rustc_middle/src')
55 files changed, 416 insertions, 502 deletions
diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index 2dc5b896993..4e242c684e3 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -380,7 +380,7 @@ impl<'tcx> DepNodeParams<TyCtxt<'tcx>> for HirId { let local_id = local_id .as_u64() .try_into() - .unwrap_or_else(|_| panic!("local id should be u32, found {:?}", local_id)); + .unwrap_or_else(|_| panic!("local id should be u32, found {local_id:?}")); Some(HirId { owner: OwnerId { def_id }, local_id: ItemLocalId::from_u32(local_id) }) } else { None diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index 0ddbe7d1c29..3ad9b0d79e7 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -35,7 +35,7 @@ impl rustc_query_system::dep_graph::DepKind for DepKind { if let Some(def_id) = node.extract_def_id(tcx) { write!(f, "{}", tcx.def_path_debug_str(def_id))?; } else if let Some(ref s) = tcx.dep_graph.dep_node_debug_str(*node) { - write!(f, "{}", s)?; + write!(f, "{s}")?; } else { write!(f, "{}", node.hash)?; } diff --git a/compiler/rustc_middle/src/error.rs b/compiler/rustc_middle/src/error.rs index 57b2de84b47..b346cd45391 100644 --- a/compiler/rustc_middle/src/error.rs +++ b/compiler/rustc_middle/src/error.rs @@ -132,6 +132,9 @@ pub enum LayoutError<'tcx> { #[diag(middle_cycle)] Cycle, + + #[diag(middle_layout_references_error)] + ReferencesError, } #[derive(Diagnostic)] diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 1fd68dc5cb2..0256e09e4b5 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -24,7 +24,7 @@ pub fn associated_body(node: Node<'_>) -> Option<(LocalDefId, BodyId)> { match node { Node::Item(Item { owner_id, - kind: ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body), + kind: ItemKind::Const(_, _, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body), .. }) | Node::TraitItem(TraitItem { @@ -534,7 +534,7 @@ impl<'hir> Map<'hir> { (m, span, hir_id) } Some(OwnerNode::Crate(item)) => (item, item.spans.inner_span, hir_id), - node => panic!("not a module: {:?}", node), + node => panic!("not a module: {node:?}"), } } diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index 6ce1ad8f43e..9ecc7580f5c 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -218,14 +218,12 @@ pub fn explain_lint_level_source( let hyphen_case_lint_name = name.replace('_', "-"); if lint_flag_val.as_str() == name { err.note_once(format!( - "requested on the command line with `{} {}`", - flag, hyphen_case_lint_name + "requested on the command line with `{flag} {hyphen_case_lint_name}`" )); } else { let hyphen_case_flag_val = lint_flag_val.as_str().replace('_', "-"); err.note_once(format!( - "`{} {}` implied by `{} {}`", - flag, hyphen_case_lint_name, flag, hyphen_case_flag_val + "`{flag} {hyphen_case_lint_name}` implied by `{flag} {hyphen_case_flag_val}`" )); } } @@ -237,8 +235,7 @@ pub fn explain_lint_level_source( if lint_attr_name.as_str() != name { let level_str = level.as_str(); err.note_once(format!( - "`#[{}({})]` implied by `#[{}({})]`", - level_str, name, level_str, lint_attr_name + "`#[{level_str}({name})]` implied by `#[{level_str}({lint_attr_name})]`" )); } } @@ -416,12 +413,11 @@ pub fn struct_lint_level( FutureIncompatibilityReason::EditionError(edition) => { let current_edition = sess.edition(); format!( - "this is accepted in the current edition (Rust {}) but is a hard error in Rust {}!", - current_edition, edition + "this is accepted in the current edition (Rust {current_edition}) but is a hard error in Rust {edition}!" ) } FutureIncompatibilityReason::EditionSemanticsChange(edition) => { - format!("this changes meaning in Rust {}", edition) + format!("this changes meaning in Rust {edition}") } FutureIncompatibilityReason::Custom(reason) => reason.to_owned(), }; diff --git a/compiler/rustc_middle/src/macros.rs b/compiler/rustc_middle/src/macros.rs index cd1c6c330bc..fca16d8e509 100644 --- a/compiler/rustc_middle/src/macros.rs +++ b/compiler/rustc_middle/src/macros.rs @@ -43,7 +43,7 @@ macro_rules! span_bug { #[macro_export] macro_rules! CloneLiftImpls { - ($($ty:ty,)+) => { + ($($ty:ty),+ $(,)?) => { $( impl<'tcx> $crate::ty::Lift<'tcx> for $ty { type Lifted = Self; @@ -59,7 +59,7 @@ macro_rules! CloneLiftImpls { /// allocated data** (i.e., don't need to be folded). #[macro_export] macro_rules! TrivialTypeTraversalImpls { - ($($ty:ty,)+) => { + ($($ty:ty),+ $(,)?) => { $( impl<'tcx> $crate::ty::fold::TypeFoldable<$crate::ty::TyCtxt<'tcx>> for $ty { fn try_fold_with<F: $crate::ty::fold::FallibleTypeFolder<$crate::ty::TyCtxt<'tcx>>>( diff --git a/compiler/rustc_middle/src/middle/privacy.rs b/compiler/rustc_middle/src/middle/privacy.rs index 5baeb1ee0cf..1913421f54c 100644 --- a/compiler/rustc_middle/src/middle/privacy.rs +++ b/compiler/rustc_middle/src/middle/privacy.rs @@ -178,7 +178,12 @@ impl EffectiveVisibilities { // All effective visibilities except `reachable_through_impl_trait` are limited to // nominal visibility. For some items nominal visibility doesn't make sense so we // don't check this condition for them. - if !matches!(tcx.def_kind(def_id), DefKind::Impl { .. }) { + let is_impl = matches!(tcx.def_kind(def_id), DefKind::Impl { .. }); + let is_associated_item_in_trait_impl = tcx + .impl_of_method(def_id.to_def_id()) + .and_then(|impl_id| tcx.trait_id_of_impl(impl_id)) + .is_some(); + if !is_impl && !is_associated_item_in_trait_impl { let nominal_vis = tcx.visibility(def_id); if !nominal_vis.is_at_least(ev.reachable, tcx) { span_bug!( @@ -186,7 +191,7 @@ impl EffectiveVisibilities { "{:?}: reachable {:?} > nominal {:?}", def_id, ev.reachable, - nominal_vis + nominal_vis, ); } } diff --git a/compiler/rustc_middle/src/middle/stability.rs b/compiler/rustc_middle/src/middle/stability.rs index 60844c17e47..908ab8b613e 100644 --- a/compiler/rustc_middle/src/middle/stability.rs +++ b/compiler/rustc_middle/src/middle/stability.rs @@ -107,7 +107,7 @@ pub fn report_unstable( soft_handler: impl FnOnce(&'static Lint, Span, String), ) { let msg = match reason { - Some(r) => format!("use of unstable library feature '{}': {}", feature, r), + Some(r) => format!("use of unstable library feature '{feature}': {r}"), None => format!("use of unstable library feature '{}'", &feature), }; @@ -170,7 +170,7 @@ pub fn deprecation_suggestion( if let Some(suggestion) = suggestion { diag.span_suggestion_verbose( span, - format!("replace the use of the deprecated {}", kind), + format!("replace the use of the deprecated {kind}"), suggestion, Applicability::MachineApplicable, ); @@ -189,12 +189,12 @@ fn deprecation_message( path: &str, ) -> String { let message = if is_in_effect { - format!("use of deprecated {} `{}`", kind, path) + format!("use of deprecated {kind} `{path}`") } else { let since = since.as_ref().map(Symbol::as_str); if since == Some("TBD") { - format!("use of {} `{}` that will be deprecated in a future Rust version", kind, path) + format!("use of {kind} `{path}` that will be deprecated in a future Rust version") } else { format!( "use of {} `{}` that will be deprecated in future version {}", @@ -206,7 +206,7 @@ fn deprecation_message( }; match note { - Some(reason) => format!("{}: {}", message, reason), + Some(reason) => format!("{message}: {reason}"), None => message, } } @@ -312,7 +312,7 @@ fn suggestion_for_allocator_api( return Some(( inner_types, "consider wrapping the inner types in tuple".to_string(), - format!("({})", snippet), + format!("({snippet})"), Applicability::MaybeIncorrect, )); } @@ -599,7 +599,7 @@ impl<'tcx> TyCtxt<'tcx> { |span, def_id| { // The API could be uncallable for other reasons, for example when a private module // was referenced. - self.sess.delay_span_bug(span, format!("encountered unmarked API: {:?}", def_id)); + self.sess.delay_span_bug(span, format!("encountered unmarked API: {def_id:?}")); }, ) } diff --git a/compiler/rustc_middle/src/mir/basic_blocks.rs b/compiler/rustc_middle/src/mir/basic_blocks.rs index 7722e7b47cf..0ad17e819c7 100644 --- a/compiler/rustc_middle/src/mir/basic_blocks.rs +++ b/compiler/rustc_middle/src/mir/basic_blocks.rs @@ -178,9 +178,7 @@ impl<'tcx> graph::WithPredecessors for BasicBlocks<'tcx> { } } -TrivialTypeTraversalAndLiftImpls! { - Cache, -} +TrivialTypeTraversalAndLiftImpls! { Cache } impl<S: Encoder> Encodable<S> for Cache { #[inline] diff --git a/compiler/rustc_middle/src/mir/generic_graph.rs b/compiler/rustc_middle/src/mir/generic_graph.rs index d1f3561c02c..d1753427e74 100644 --- a/compiler/rustc_middle/src/mir/generic_graph.rs +++ b/compiler/rustc_middle/src/mir/generic_graph.rs @@ -7,7 +7,7 @@ use rustc_middle::ty::TyCtxt; pub fn mir_fn_to_generic_graph<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'_>) -> Graph { let def_id = body.source.def_id(); let def_name = graphviz_safe_def_name(def_id); - let graph_name = format!("Mir_{}", def_name); + let graph_name = format!("Mir_{def_name}"); let dark_mode = tcx.sess.opts.unstable_opts.graphviz_dark_mode; // Nodes @@ -48,7 +48,7 @@ fn bb_to_graph_node(block: BasicBlock, body: &Body<'_>, dark_mode: bool) -> Node }; let style = NodeStyle { title_bg: Some(bgcolor.to_owned()), ..Default::default() }; - let mut stmts: Vec<String> = data.statements.iter().map(|x| format!("{:?}", x)).collect(); + let mut stmts: Vec<String> = data.statements.iter().map(|x| format!("{x:?}")).collect(); // add the terminator to the stmts, gsgdt can print it out separately let mut terminator_head = String::new(); diff --git a/compiler/rustc_middle/src/mir/generic_graphviz.rs b/compiler/rustc_middle/src/mir/generic_graphviz.rs index ccae7e159b1..299b50525cb 100644 --- a/compiler/rustc_middle/src/mir/generic_graphviz.rs +++ b/compiler/rustc_middle/src/mir/generic_graphviz.rs @@ -70,8 +70,8 @@ impl< writeln!(w, r#" graph [{}];"#, graph_attrs.join(" "))?; let content_attrs_str = content_attrs.join(" "); - writeln!(w, r#" node [{}];"#, content_attrs_str)?; - writeln!(w, r#" edge [{}];"#, content_attrs_str)?; + writeln!(w, r#" node [{content_attrs_str}];"#)?; + writeln!(w, r#" edge [{content_attrs_str}];"#)?; // Graph label if let Some(graph_label) = &self.graph_label { @@ -112,7 +112,7 @@ impl< // (format!("{:?}", node), color) // }; let color = if dark_mode { "dimgray" } else { "gray" }; - let (blk, bgcolor) = (format!("{:?}", node), color); + let (blk, bgcolor) = (format!("{node:?}"), color); write!( w, r#"<tr><td bgcolor="{bgcolor}" {attrs} colspan="{colspan}">{blk}</td></tr>"#, @@ -151,7 +151,7 @@ impl< } else { "".to_owned() }; - writeln!(w, r#" {} -> {} [label=<{}>];"#, src, trg, escaped_edge_label)?; + writeln!(w, r#" {src} -> {trg} [label=<{escaped_edge_label}>];"#)?; } Ok(()) } @@ -163,7 +163,7 @@ impl< W: Write, { let escaped_label = dot::escape_html(label); - writeln!(w, r#" label=<<br/><br/>{}<br align="left"/><br/><br/><br/>>;"#, escaped_label) + writeln!(w, r#" label=<<br/><br/>{escaped_label}<br align="left"/><br/><br/><br/>>;"#) } fn node(&self, node: G::Node) -> String { diff --git a/compiler/rustc_middle/src/mir/graphviz.rs b/compiler/rustc_middle/src/mir/graphviz.rs index 2de73db3a3c..5c7de864430 100644 --- a/compiler/rustc_middle/src/mir/graphviz.rs +++ b/compiler/rustc_middle/src/mir/graphviz.rs @@ -127,5 +127,5 @@ fn write_graph_label<'tcx, W: std::fmt::Write>( } fn escape<T: Debug>(t: &T) -> String { - dot::escape_html(&format!("{:?}", t)) + dot::escape_html(&format!("{t:?}")) } diff --git a/compiler/rustc_middle/src/mir/interpret/allocation.rs b/compiler/rustc_middle/src/mir/interpret/allocation.rs index b8030d9db13..c1cb2f2e497 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation.rs @@ -571,7 +571,7 @@ impl<Prov: Provenance, Extra, Bytes: AllocBytes> Allocation<Prov, Extra, Bytes> assert!(self.mutability == Mutability::Mut); // `to_bits_or_ptr_internal` is the right method because we just want to store this data - // as-is into memory. + // as-is into memory. This also double-checks that `val.size()` matches `range.size`. let (bytes, provenance) = match val.to_bits_or_ptr_internal(range.size)? { Right(ptr) => { let (provenance, offset) = ptr.into_parts(); diff --git a/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs b/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs index d4dd56a42c1..2c6bb908f39 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs @@ -542,11 +542,7 @@ impl InitMaskMaterialized { debug_assert_eq!( result, find_bit_slow(self, start, end, is_init), - "optimized implementation of find_bit is wrong for start={:?} end={:?} is_init={} init_mask={:#?}", - start, - end, - is_init, - self + "optimized implementation of find_bit is wrong for start={start:?} end={end:?} is_init={is_init} init_mask={self:#?}" ); result diff --git a/compiler/rustc_middle/src/mir/interpret/error.rs b/compiler/rustc_middle/src/mir/interpret/error.rs index 372452ea29a..d44dfa2172a 100644 --- a/compiler/rustc_middle/src/mir/interpret/error.rs +++ b/compiler/rustc_middle/src/mir/interpret/error.rs @@ -12,7 +12,8 @@ use rustc_errors::{ use rustc_macros::HashStable; use rustc_session::CtfeBacktrace; use rustc_span::def_id::DefId; -use rustc_target::abi::{call, Align, Size, WrappingRange}; +use rustc_target::abi::{call, Align, Size, VariantIdx, WrappingRange}; + use std::borrow::Cow; use std::{any::Any, backtrace::Backtrace, fmt}; @@ -66,9 +67,7 @@ impl Into<ErrorGuaranteed> for ReportedErrorInfo { } } -TrivialTypeTraversalAndLiftImpls! { - ErrorHandled, -} +TrivialTypeTraversalAndLiftImpls! { ErrorHandled } pub type EvalToAllocationRawResult<'tcx> = Result<ConstAlloc<'tcx>, ErrorHandled>; pub type EvalToConstValueResult<'tcx> = Result<ConstValue<'tcx>, ErrorHandled>; @@ -156,7 +155,7 @@ impl<'tcx> InterpErrorInfo<'tcx> { } fn print_backtrace(backtrace: &Backtrace) { - eprintln!("\n\nAn error occurred in miri:\n{}", backtrace); + eprintln!("\n\nAn error occurred in miri:\n{backtrace}"); } impl From<ErrorGuaranteed> for InterpErrorInfo<'_> { @@ -191,9 +190,8 @@ pub enum InvalidProgramInfo<'tcx> { FnAbiAdjustForForeignAbi(call::AdjustForForeignAbiError), /// SizeOf of unsized type was requested. SizeOfUnsizedType(Ty<'tcx>), - /// An unsized local was accessed without having been initialized. - /// This is not meaningful as we can't even have backing memory for such locals. - UninitUnsizedLocal, + /// We are runnning into a nonsense situation due to ConstProp violating our invariants. + ConstPropNonsense, } /// Details of why a pointer had to be in-bounds. @@ -324,7 +322,9 @@ pub enum UndefinedBehaviorInfo<'a> { /// Data size is not equal to target size. ScalarSizeMismatch(ScalarSizeMismatch), /// A discriminant of an uninhabited enum variant is written. - UninhabitedEnumVariantWritten, + UninhabitedEnumVariantWritten(VariantIdx), + /// An uninhabited enum variant is projected. + UninhabitedEnumVariantRead(VariantIdx), /// Validation error. Validation(ValidationErrorInfo<'a>), // FIXME(fee1-dead) these should all be actual variants of the enum instead of dynamically @@ -394,6 +394,7 @@ pub enum ValidationErrorKind<'tcx> { UnsafeCell, UninhabitedVal { ty: Ty<'tcx> }, InvalidEnumTag { value: String }, + UninhabitedEnumTag, UninitEnumTag, UninitStr, Uninit { expected: ExpectedKind }, diff --git a/compiler/rustc_middle/src/mir/interpret/mod.rs b/compiler/rustc_middle/src/mir/interpret/mod.rs index 69c15e9cc06..8b5a8d17301 100644 --- a/compiler/rustc_middle/src/mir/interpret/mod.rs +++ b/compiler/rustc_middle/src/mir/interpret/mod.rs @@ -176,7 +176,7 @@ impl<'tcx> GlobalId<'tcx> { pub fn display(self, tcx: TyCtxt<'tcx>) -> String { let instance_name = with_no_trimmed_paths!(tcx.def_path_str(self.instance.def.def_id())); if let Some(promoted) = self.promoted { - format!("{}::{:?}", instance_name, promoted) + format!("{instance_name}::{promoted:?}") } else { instance_name } diff --git a/compiler/rustc_middle/src/mir/interpret/queries.rs b/compiler/rustc_middle/src/mir/interpret/queries.rs index c9db0e7c11d..fc659ce18a4 100644 --- a/compiler/rustc_middle/src/mir/interpret/queries.rs +++ b/compiler/rustc_middle/src/mir/interpret/queries.rs @@ -139,7 +139,6 @@ impl<'tcx> TyCtxt<'tcx> { cid: GlobalId<'tcx>, span: Option<Span>, ) -> EvalToConstValueResult<'tcx> { - let param_env = param_env.with_const(); // Const-eval shouldn't depend on lifetimes at all, so we can erase them, which should // improve caching of queries. let inputs = self.erase_regions(param_env.and(cid)); @@ -158,8 +157,6 @@ impl<'tcx> TyCtxt<'tcx> { cid: GlobalId<'tcx>, span: Option<Span>, ) -> EvalToValTreeResult<'tcx> { - let param_env = param_env.with_const(); - debug!(?param_env); // Const-eval shouldn't depend on lifetimes at all, so we can erase them, which should // improve caching of queries. let inputs = self.erase_regions(param_env.and(cid)); @@ -204,7 +201,6 @@ impl<'tcx> TyCtxtAt<'tcx> { gid: GlobalId<'tcx>, param_env: ty::ParamEnv<'tcx>, ) -> Result<mir::ConstAllocation<'tcx>, ErrorHandled> { - let param_env = param_env.with_const(); trace!("eval_to_allocation: Need to compute {:?}", gid); let raw_const = self.eval_to_allocation_raw(param_env.and(gid))?; Ok(self.global_alloc(raw_const.alloc_id).unwrap_memory()) @@ -224,8 +220,7 @@ impl<'tcx> TyCtxtEnsure<'tcx> { let args = GenericArgs::identity_for_item(self.tcx, def_id); let instance = ty::Instance::new(def_id, args); let cid = GlobalId { instance, promoted: None }; - let param_env = - self.tcx.param_env(def_id).with_reveal_all_normalized(self.tcx).with_const(); + let param_env = self.tcx.param_env(def_id).with_reveal_all_normalized(self.tcx); // Const-eval shouldn't depend on lifetimes at all, so we can erase them, which should // improve caching of queries. let inputs = self.tcx.erase_regions(param_env.and(cid)); @@ -238,7 +233,7 @@ impl<'tcx> TyCtxtEnsure<'tcx> { assert!(self.tcx.is_static(def_id)); let instance = ty::Instance::mono(self.tcx, def_id); let gid = GlobalId { instance, promoted: None }; - let param_env = ty::ParamEnv::reveal_all().with_const(); + let param_env = ty::ParamEnv::reveal_all(); trace!("eval_to_allocation: Need to compute {:?}", gid); self.eval_to_allocation_raw(param_env.and(gid)) } diff --git a/compiler/rustc_middle/src/mir/interpret/value.rs b/compiler/rustc_middle/src/mir/interpret/value.rs index 0416411dfe1..20861d5ffa4 100644 --- a/compiler/rustc_middle/src/mir/interpret/value.rs +++ b/compiler/rustc_middle/src/mir/interpret/value.rs @@ -135,8 +135,8 @@ static_assert_size!(Scalar, 24); impl<Prov: Provenance> fmt::Debug for Scalar<Prov> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Scalar::Ptr(ptr, _size) => write!(f, "{:?}", ptr), - Scalar::Int(int) => write!(f, "{:?}", int), + Scalar::Ptr(ptr, _size) => write!(f, "{ptr:?}"), + Scalar::Int(int) => write!(f, "{int:?}"), } } } @@ -144,8 +144,8 @@ impl<Prov: Provenance> fmt::Debug for Scalar<Prov> { impl<Prov: Provenance> fmt::Display for Scalar<Prov> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Scalar::Ptr(ptr, _size) => write!(f, "pointer to {:?}", ptr), - Scalar::Int(int) => write!(f, "{}", int), + Scalar::Ptr(ptr, _size) => write!(f, "pointer to {ptr:?}"), + Scalar::Int(int) => write!(f, "{int}"), } } } @@ -153,8 +153,8 @@ impl<Prov: Provenance> fmt::Display for Scalar<Prov> { impl<Prov: Provenance> fmt::LowerHex for Scalar<Prov> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Scalar::Ptr(ptr, _size) => write!(f, "pointer to {:?}", ptr), - Scalar::Int(int) => write!(f, "{:#x}", int), + Scalar::Ptr(ptr, _size) => write!(f, "pointer to {ptr:?}"), + Scalar::Int(int) => write!(f, "{int:#x}"), } } } @@ -320,6 +320,14 @@ impl<Prov> Scalar<Prov> { } }) } + + #[inline] + pub fn size(self) -> Size { + match self { + Scalar::Int(int) => int.size(), + Scalar::Ptr(_ptr, sz) => Size::from_bytes(sz), + } + } } impl<'tcx, Prov: Provenance> Scalar<Prov> { diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 97f53a59fd6..c1f87d79b83 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -619,7 +619,7 @@ impl<D: TyDecoder, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> { let val = T::decode(d); ClearCrossCrate::Set(val) } - tag => panic!("Invalid tag for ClearCrossCrate: {:?}", tag), + tag => panic!("Invalid tag for ClearCrossCrate: {tag:?}"), } } } @@ -706,9 +706,7 @@ pub enum BindingForm<'tcx> { RefForGuard, } -TrivialTypeTraversalAndLiftImpls! { - BindingForm<'tcx>, -} +TrivialTypeTraversalAndLiftImpls! { BindingForm<'tcx> } mod binding_form_impl { use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; @@ -1048,12 +1046,12 @@ pub enum VarDebugInfoContents<'tcx> { impl<'tcx> Debug for VarDebugInfoContents<'tcx> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { match self { - VarDebugInfoContents::Const(c) => write!(fmt, "{}", c), - VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p), + VarDebugInfoContents::Const(c) => write!(fmt, "{c}"), + VarDebugInfoContents::Place(p) => write!(fmt, "{p:?}"), VarDebugInfoContents::Composite { ty, fragments } => { - write!(fmt, "{:?}{{ ", ty)?; + write!(fmt, "{ty:?}{{ ")?; for f in fragments.iter() { - write!(fmt, "{:?}, ", f)?; + write!(fmt, "{f:?}, ")?; } write!(fmt, "}}") } @@ -1317,55 +1315,47 @@ impl<O> AssertKind<O> { match self { BoundsCheck { ref len, ref index } => write!( f, - "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}", - len, index + "\"index out of bounds: the length is {{}} but the index is {{}}\", {len:?}, {index:?}" ), OverflowNeg(op) => { - write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op) + write!(f, "\"attempt to negate `{{}}`, which would overflow\", {op:?}") } - DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op), + DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {op:?}"), RemainderByZero(op) => write!( f, - "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}", - op + "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {op:?}" ), Overflow(BinOp::Add, l, r) => write!( f, - "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute `{{}} + {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Sub, l, r) => write!( f, - "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute `{{}} - {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Mul, l, r) => write!( f, - "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute `{{}} * {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Div, l, r) => write!( f, - "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute `{{}} / {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Rem, l, r) => write!( f, - "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Shr, _, r) => { - write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {:?}", r) + write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {r:?}") } Overflow(BinOp::Shl, _, r) => { - write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {:?}", r) + write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {r:?}") } MisalignedPointerDereference { required, found } => { write!( f, - "\"misaligned pointer dereference: address must be a multiple of {{}} but is {{}}\", {:?}, {:?}", - required, found + "\"misaligned pointer dereference: address must be a multiple of {{}} but is {{}}\", {required:?}, {found:?}" ) } _ => write!(f, "\"{}\"", self.description()), @@ -1461,9 +1451,9 @@ impl Debug for Statement<'_> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { use self::StatementKind::*; match self.kind { - Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv), + Assign(box (ref place, ref rv)) => write!(fmt, "{place:?} = {rv:?}"), FakeRead(box (ref cause, ref place)) => { - write!(fmt, "FakeRead({:?}, {:?})", cause, place) + write!(fmt, "FakeRead({cause:?}, {place:?})") } Retag(ref kind, ref place) => write!( fmt, @@ -1476,20 +1466,20 @@ impl Debug for Statement<'_> { }, place, ), - StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place), - StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place), + StorageLive(ref place) => write!(fmt, "StorageLive({place:?})"), + StorageDead(ref place) => write!(fmt, "StorageDead({place:?})"), SetDiscriminant { ref place, variant_index } => { - write!(fmt, "discriminant({:?}) = {:?}", place, variant_index) + write!(fmt, "discriminant({place:?}) = {variant_index:?}") } - Deinit(ref place) => write!(fmt, "Deinit({:?})", place), + Deinit(ref place) => write!(fmt, "Deinit({place:?})"), PlaceMention(ref place) => { - write!(fmt, "PlaceMention({:?})", place) + write!(fmt, "PlaceMention({place:?})") } AscribeUserType(box (ref place, ref c_ty), ref variance) => { - write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty) + write!(fmt, "AscribeUserType({place:?}, {variance:?}, {c_ty:?})") } Coverage(box self::Coverage { ref kind, code_region: Some(ref rgn) }) => { - write!(fmt, "Coverage::{:?} for {:?}", kind, rgn) + write!(fmt, "Coverage::{kind:?} for {rgn:?}") } Coverage(box ref coverage) => write!(fmt, "Coverage::{:?}", coverage.kind), Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"), @@ -1769,13 +1759,13 @@ impl Debug for Place<'_> { for elem in self.projection.iter() { match elem { ProjectionElem::OpaqueCast(ty) => { - write!(fmt, " as {})", ty)?; + write!(fmt, " as {ty})")?; } ProjectionElem::Downcast(Some(name), _index) => { - write!(fmt, " as {})", name)?; + write!(fmt, " as {name})")?; } ProjectionElem::Downcast(None, index) => { - write!(fmt, " as variant#{:?})", index)?; + write!(fmt, " as variant#{index:?})")?; } ProjectionElem::Deref => { write!(fmt, ")")?; @@ -1784,25 +1774,25 @@ impl Debug for Place<'_> { write!(fmt, ".{:?}: {:?})", field.index(), ty)?; } ProjectionElem::Index(ref index) => { - write!(fmt, "[{:?}]", index)?; + write!(fmt, "[{index:?}]")?; } ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => { - write!(fmt, "[{:?} of {:?}]", offset, min_length)?; + write!(fmt, "[{offset:?} of {min_length:?}]")?; } ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => { - write!(fmt, "[-{:?} of {:?}]", offset, min_length)?; + write!(fmt, "[-{offset:?} of {min_length:?}]")?; } ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => { - write!(fmt, "[{:?}:]", from)?; + write!(fmt, "[{from:?}:]")?; } ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => { - write!(fmt, "[:-{:?}]", to)?; + write!(fmt, "[:-{to:?}]")?; } ProjectionElem::Subslice { from, to, from_end: true } => { - write!(fmt, "[{:?}:-{:?}]", from, to)?; + write!(fmt, "[{from:?}:-{to:?}]")?; } ProjectionElem::Subslice { from, to, from_end: false } => { - write!(fmt, "[{:?}..{:?}]", from, to)?; + write!(fmt, "[{from:?}..{to:?}]")?; } } } @@ -1896,9 +1886,9 @@ impl<'tcx> Debug for Operand<'tcx> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { use self::Operand::*; match *self { - Constant(ref a) => write!(fmt, "{:?}", a), - Copy(ref place) => write!(fmt, "{:?}", place), - Move(ref place) => write!(fmt, "move {:?}", place), + Constant(ref a) => write!(fmt, "{a:?}"), + Copy(ref place) => write!(fmt, "{place:?}"), + Move(ref place) => write!(fmt, "move {place:?}"), } } } @@ -1937,11 +1927,11 @@ impl<'tcx> Operand<'tcx> { let param_env_and_ty = ty::ParamEnv::empty().and(ty); let type_size = tcx .layout_of(param_env_and_ty) - .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e)) + .unwrap_or_else(|e| panic!("could not compute layout for {ty:?}: {e:?}")) .size; let scalar_size = match val { Scalar::Int(int) => int.size(), - _ => panic!("Invalid scalar type {:?}", val), + _ => panic!("Invalid scalar type {val:?}"), }; scalar_size == type_size }); @@ -2057,26 +2047,26 @@ impl<'tcx> Debug for Rvalue<'tcx> { use self::Rvalue::*; match *self { - Use(ref place) => write!(fmt, "{:?}", place), + Use(ref place) => write!(fmt, "{place:?}"), Repeat(ref a, b) => { - write!(fmt, "[{:?}; ", a)?; + write!(fmt, "[{a:?}; ")?; pretty_print_const(b, fmt, false)?; write!(fmt, "]") } - Len(ref a) => write!(fmt, "Len({:?})", a), + Len(ref a) => write!(fmt, "Len({a:?})"), Cast(ref kind, ref place, ref ty) => { - write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind) + write!(fmt, "{place:?} as {ty:?} ({kind:?})") } - BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{:?}({:?}, {:?})", op, a, b), + BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{op:?}({a:?}, {b:?})"), CheckedBinaryOp(ref op, box (ref a, ref b)) => { - write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b) + write!(fmt, "Checked{op:?}({a:?}, {b:?})") } - UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a), - Discriminant(ref place) => write!(fmt, "discriminant({:?})", place), + UnaryOp(ref op, ref a) => write!(fmt, "{op:?}({a:?})"), + Discriminant(ref place) => write!(fmt, "discriminant({place:?})"), NullaryOp(ref op, ref t) => match op { - NullOp::SizeOf => write!(fmt, "SizeOf({:?})", t), - NullOp::AlignOf => write!(fmt, "AlignOf({:?})", t), - NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({:?}, {:?})", t, fields), + NullOp::SizeOf => write!(fmt, "SizeOf({t:?})"), + NullOp::AlignOf => write!(fmt, "AlignOf({t:?})"), + NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({t:?}, {fields:?})"), }, ThreadLocalRef(did) => ty::tls::with(|tcx| { let muta = tcx.static_mutability(did).unwrap().prefix_str(); @@ -2103,10 +2093,10 @@ impl<'tcx> Debug for Rvalue<'tcx> { // Do not even print 'static String::new() }; - write!(fmt, "&{}{}{:?}", region, kind_str, place) + write!(fmt, "&{region}{kind_str}{place:?}") } - CopyForDeref(ref place) => write!(fmt, "deref_copy {:#?}", place), + CopyForDeref(ref place) => write!(fmt, "deref_copy {place:#?}"), AddressOf(mutability, ref place) => { let kind_str = match mutability { @@ -2114,7 +2104,7 @@ impl<'tcx> Debug for Rvalue<'tcx> { Mutability::Not => "const", }; - write!(fmt, "&raw {} {:?}", kind_str, place) + write!(fmt, "&raw {kind_str} {place:?}") } Aggregate(ref kind, ref places) => { @@ -2127,7 +2117,7 @@ impl<'tcx> Debug for Rvalue<'tcx> { }; match **kind { - AggregateKind::Array(_) => write!(fmt, "{:?}", places), + AggregateKind::Array(_) => write!(fmt, "{places:?}"), AggregateKind::Tuple => { if places.is_empty() { @@ -2213,7 +2203,7 @@ impl<'tcx> Debug for Rvalue<'tcx> { } ShallowInitBox(ref place, ref ty) => { - write!(fmt, "ShallowInitBox({:?}, {:?})", place, ty) + write!(fmt, "ShallowInitBox({place:?}, {ty:?})") } } } @@ -2757,7 +2747,7 @@ rustc_index::newtype_index! { impl<'tcx> Debug for Constant<'tcx> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { - write!(fmt, "{}", self) + write!(fmt, "{self}") } } @@ -2833,7 +2823,7 @@ fn pretty_print_const_value<'tcx>( let ty = tcx.lift(ty).unwrap(); if tcx.sess.verbose() { - fmt.write_str(&format!("ConstValue({:?}: {})", ct, ty))?; + fmt.write_str(&format!("ConstValue({ct:?}: {ty})"))?; return Ok(()); } @@ -2903,7 +2893,7 @@ fn pretty_print_const_value<'tcx>( fmt.write_str(")")?; } ty::Adt(def, _) if def.variants().is_empty() => { - fmt.write_str(&format!("{{unreachable(): {}}}", ty))?; + fmt.write_str(&format!("{{unreachable(): {ty}}}"))?; } ty::Adt(def, args) => { let variant_idx = contents diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index f4133dfbc95..ddb6cc15bc1 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -223,7 +223,7 @@ impl<'tcx> MonoItem<'tcx> { impl<'tcx> fmt::Display for MonoItem<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - MonoItem::Fn(instance) => write!(f, "fn {}", instance), + MonoItem::Fn(instance) => write!(f, "fn {instance}"), MonoItem::Static(def_id) => { write!(f, "static {}", Instance::new(def_id, GenericArgs::empty())) } @@ -534,17 +534,17 @@ impl<'tcx> CodegenUnitNameBuilder<'tcx> { format!("{}.{:08x}{}", tcx.crate_name(cnum), stable_crate_id, local_crate_id) }); - write!(cgu_name, "{}", crate_prefix).unwrap(); + write!(cgu_name, "{crate_prefix}").unwrap(); // Add the components for component in components { - write!(cgu_name, "-{}", component).unwrap(); + write!(cgu_name, "-{component}").unwrap(); } if let Some(special_suffix) = special_suffix { // We add a dot in here so it cannot clash with anything in a regular // Rust identifier - write!(cgu_name, ".{}", special_suffix).unwrap(); + write!(cgu_name, ".{special_suffix}").unwrap(); } Symbol::intern(&cgu_name) diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 8cbab31451b..27e39137092 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -124,14 +124,14 @@ fn dump_matched_mir_node<'tcx, F>( let def_path = ty::print::with_forced_impl_filename_line!(tcx.def_path_str(body.source.def_id())); // ignore-tidy-odd-backticks the literal below is fine - write!(file, "// MIR for `{}", def_path)?; + write!(file, "// MIR for `{def_path}")?; match body.source.promoted { None => write!(file, "`")?, - Some(promoted) => write!(file, "::{:?}`", promoted)?, + Some(promoted) => write!(file, "::{promoted:?}`")?, } - writeln!(file, " {} {}", disambiguator, pass_name)?; + writeln!(file, " {disambiguator} {pass_name}")?; if let Some(ref layout) = body.generator_layout() { - writeln!(file, "/* generator_layout = {:#?} */", layout)?; + writeln!(file, "/* generator_layout = {layout:#?} */")?; } writeln!(file)?; extra_data(PassWhere::BeforeCFG, &mut file)?; @@ -169,7 +169,7 @@ fn dump_file_basename<'tcx>( ) -> String { let source = body.source; let promotion_id = match source.promoted { - Some(id) => format!("-{:?}", id), + Some(id) => format!("-{id:?}"), None => String::new(), }; @@ -203,8 +203,7 @@ fn dump_file_basename<'tcx>( }; format!( - "{}.{}{}{}{}.{}.{}", - crate_name, item_name, shim_disambiguator, promotion_id, pass_num, pass_name, disambiguator, + "{crate_name}.{item_name}{shim_disambiguator}{promotion_id}{pass_num}.{pass_name}.{disambiguator}", ) } @@ -215,7 +214,7 @@ fn dump_path(tcx: TyCtxt<'_>, basename: &str, extension: &str) -> PathBuf { let mut file_path = PathBuf::new(); file_path.push(Path::new(&tcx.sess.opts.unstable_opts.dump_mir_dir)); - let file_name = format!("{}.{}", basename, extension,); + let file_name = format!("{basename}.{extension}",); file_path.push(&file_name); @@ -233,12 +232,12 @@ fn create_dump_file_with_basename( fs::create_dir_all(parent).map_err(|e| { io::Error::new( e.kind(), - format!("IO error creating MIR dump directory: {:?}; {}", parent, e), + format!("IO error creating MIR dump directory: {parent:?}; {e}"), ) })?; } Ok(io::BufWriter::new(fs::File::create(&file_path).map_err(|e| { - io::Error::new(e.kind(), format!("IO error creating MIR dump file: {:?}; {}", file_path, e)) + io::Error::new(e.kind(), format!("IO error creating MIR dump file: {file_path:?}; {e}")) })?)) } @@ -346,28 +345,24 @@ where // Basic block label at the top. let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" }; - writeln!(w, "{}{:?}{}: {{", INDENT, block, cleanup_text)?; + writeln!(w, "{INDENT}{block:?}{cleanup_text}: {{")?; // List of statements in the middle. let mut current_location = Location { block, statement_index: 0 }; for statement in &data.statements { extra_data(PassWhere::BeforeLocation(current_location), w)?; - let indented_body = format!("{0}{0}{1:?};", INDENT, statement); + let indented_body = format!("{INDENT}{INDENT}{statement:?};"); if tcx.sess.opts.unstable_opts.mir_include_spans { writeln!( w, "{:A$} // {}{}", indented_body, - if tcx.sess.verbose() { - format!("{:?}: ", current_location) - } else { - String::new() - }, + if tcx.sess.verbose() { format!("{current_location:?}: ") } else { String::new() }, comment(tcx, statement.source_info), A = ALIGN, )?; } else { - writeln!(w, "{}", indented_body)?; + writeln!(w, "{indented_body}")?; } write_extra(tcx, w, |visitor| { @@ -387,12 +382,12 @@ where w, "{:A$} // {}{}", indented_terminator, - if tcx.sess.verbose() { format!("{:?}: ", current_location) } else { String::new() }, + if tcx.sess.verbose() { format!("{current_location:?}: ") } else { String::new() }, comment(tcx, data.terminator().source_info), A = ALIGN, )?; } else { - writeln!(w, "{}", indented_terminator)?; + writeln!(w, "{indented_terminator}")?; } write_extra(tcx, w, |visitor| { @@ -402,7 +397,7 @@ where extra_data(PassWhere::AfterLocation(current_location), w)?; extra_data(PassWhere::AfterTerminator(block), w)?; - writeln!(w, "{}}}", INDENT) + writeln!(w, "{INDENT}}}") } /// After we print the main statement, we sometimes dump extra @@ -457,25 +452,25 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> { self.tcx.sess.source_map().span_to_embeddable_string(*span) )); if let Some(user_ty) = user_ty { - self.push(&format!("+ user_ty: {:?}", user_ty)); + self.push(&format!("+ user_ty: {user_ty:?}")); } // FIXME: this is a poor version of `pretty_print_const_value`. let fmt_val = |val: &ConstValue<'tcx>| match val { ConstValue::ZeroSized => "<ZST>".to_string(), - ConstValue::Scalar(s) => format!("Scalar({:?})", s), + ConstValue::Scalar(s) => format!("Scalar({s:?})"), ConstValue::Slice { .. } => "Slice(..)".to_string(), ConstValue::ByRef { .. } => "ByRef(..)".to_string(), }; let fmt_valtree = |valtree: &ty::ValTree<'tcx>| match valtree { - ty::ValTree::Leaf(leaf) => format!("ValTree::Leaf({:?})", leaf), + ty::ValTree::Leaf(leaf) => format!("ValTree::Leaf({leaf:?})"), ty::ValTree::Branch(_) => "ValTree::Branch(..)".to_string(), }; let val = match literal { ConstantKind::Ty(ct) => match ct.kind() { - ty::ConstKind::Param(p) => format!("Param({})", p), + ty::ConstKind::Param(p) => format!("Param({p})"), ty::ConstKind::Unevaluated(uv) => { format!("Unevaluated({}, {:?})", self.tcx.def_path_str(uv.def), uv.args,) } @@ -514,20 +509,20 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> { match **kind { AggregateKind::Closure(def_id, args) => { self.push("closure"); - self.push(&format!("+ def_id: {:?}", def_id)); - self.push(&format!("+ args: {:#?}", args)); + self.push(&format!("+ def_id: {def_id:?}")); + self.push(&format!("+ args: {args:#?}")); } AggregateKind::Generator(def_id, args, movability) => { self.push("generator"); - self.push(&format!("+ def_id: {:?}", def_id)); - self.push(&format!("+ args: {:#?}", args)); - self.push(&format!("+ movability: {:?}", movability)); + self.push(&format!("+ def_id: {def_id:?}")); + self.push(&format!("+ args: {args:#?}")); + self.push(&format!("+ movability: {movability:?}")); } AggregateKind::Adt(_, _, _, Some(user_ty), _) => { self.push("adt"); - self.push(&format!("+ user_ty: {:?}", user_ty)); + self.push(&format!("+ user_ty: {user_ty:?}")); } _ => {} @@ -578,7 +573,7 @@ fn write_scope_tree( comment(tcx, var_debug_info.source_info), )?; } else { - writeln!(w, "{}", indented_debug_info)?; + writeln!(w, "{indented_debug_info}")?; } } @@ -600,7 +595,7 @@ fn write_scope_tree( format!("{0:1$}let {2}{3:?}: {4:?}", INDENT, indent, mut_str, local, local_decl.ty); if let Some(user_ty) = &local_decl.user_ty { for user_ty in user_ty.projections() { - write!(indented_decl, " as {:?}", user_ty).unwrap(); + write!(indented_decl, " as {user_ty:?}").unwrap(); } } indented_decl.push(';'); @@ -617,7 +612,7 @@ fn write_scope_tree( comment(tcx, local_decl.source_info), )?; } else { - writeln!(w, "{}", indented_decl,)?; + writeln!(w, "{indented_decl}",)?; } } @@ -654,10 +649,10 @@ fn write_scope_tree( tcx.sess.source_map().span_to_embeddable_string(span), )?; } else { - writeln!(w, "{}", indented_header)?; + writeln!(w, "{indented_header}")?; } } else { - writeln!(w, "{}", indented_header)?; + writeln!(w, "{indented_header}")?; } write_scope_tree(tcx, body, scope_tree, w, child, depth + 1)?; @@ -844,7 +839,7 @@ fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fm for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) { write!(w, " ")?; } - writeln!(w, " │ {}", ascii) + writeln!(w, " │ {ascii}") } /// Number of bytes to print per allocation hex dump line. @@ -880,7 +875,7 @@ pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( if num_lines > 0 { write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?; } else { - write!(w, "{}", prefix)?; + write!(w, "{prefix}")?; } let mut i = Size::ZERO; @@ -913,10 +908,10 @@ pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( let offset = Size::from_bytes(offset); let provenance_width = |bytes| bytes * 3; let ptr = Pointer::new(prov, offset); - let mut target = format!("{:?}", ptr); + let mut target = format!("{ptr:?}"); if target.len() > provenance_width(ptr_size.bytes_usize() - 1) { // This is too long, try to save some space. - target = format!("{:#?}", ptr); + target = format!("{ptr:#?}"); } if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE { // This branch handles the situation where a provenance starts in the current line @@ -935,10 +930,10 @@ pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?; ascii.clear(); - write!(w, "{0:─^1$}╼", target, overflow_width)?; + write!(w, "{target:─^overflow_width$}╼")?; } else { oversized_ptr(&mut target, remainder_width); - write!(w, "╾{0:─^1$}", target, remainder_width)?; + write!(w, "╾{target:─^remainder_width$}")?; line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?; write!(w, "{0:─^1$}╼", "", overflow_width)?; @@ -955,7 +950,7 @@ pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( let provenance_width = provenance_width(ptr_size.bytes_usize() - 1); oversized_ptr(&mut target, provenance_width); ascii.push('╾'); - write!(w, "╾{0:─^1$}╼", target, provenance_width)?; + write!(w, "╾{target:─^provenance_width$}╼")?; for _ in 0..ptr_size.bytes() - 2 { ascii.push('─'); } @@ -972,7 +967,7 @@ pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( // Format is similar to "oversized" above. let j = i.bytes_usize(); let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0]; - write!(w, "╾{:02x}{:#?} (1 ptr byte)╼", c, prov)?; + write!(w, "╾{c:02x}{prov:#?} (1 ptr byte)╼")?; i += Size::from_bytes(1); } else if alloc .init_mask() @@ -984,7 +979,7 @@ pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( // Checked definedness (and thus range) and provenance. This access also doesn't // influence interpreter execution but is only for debugging. let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0]; - write!(w, "{:02x}", c)?; + write!(w, "{c:02x}")?; if c.is_ascii_control() || c >= 0x80 { ascii.push('.'); } else { @@ -1018,7 +1013,7 @@ fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn Write) -> io::Res _ => tcx.is_closure(def_id), }; match (kind, body.source.promoted) { - (_, Some(i)) => write!(w, "{:?} in ", i)?, + (_, Some(i)) => write!(w, "{i:?} in ")?, (DefKind::Const | DefKind::AssocConst, _) => write!(w, "const ")?, (DefKind::Static(hir::Mutability::Not), _) => write!(w, "static ")?, (DefKind::Static(hir::Mutability::Mut), _) => write!(w, "static mut ")?, @@ -1051,7 +1046,7 @@ fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn Write) -> io::Res if let Some(yield_ty) = body.yield_ty() { writeln!(w)?; - writeln!(w, "yields {}", yield_ty)?; + writeln!(w, "yields {yield_ty}")?; } write!(w, " ")?; diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index e8cb9860ee5..71bec49af93 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -198,7 +198,7 @@ impl Debug for GeneratorLayout<'_> { if fmt.alternate() { write!(fmt, "{:9}({:?})", variant_name, self.0) } else { - write!(fmt, "{}", variant_name) + write!(fmt, "{variant_name}") } } } diff --git a/compiler/rustc_middle/src/mir/spanview.rs b/compiler/rustc_middle/src/mir/spanview.rs index 730c551576a..20a9e6889e4 100644 --- a/compiler/rustc_middle/src/mir/spanview.rs +++ b/compiler/rustc_middle/src/mir/spanview.rs @@ -159,10 +159,10 @@ where indent_to_initial_start_col, source_map.span_to_snippet(spanview_span).expect("function should have printable source") ); - writeln!(w, "{}", HEADER)?; - writeln!(w, "<title>{}</title>", title)?; - writeln!(w, "{}", STYLE_SECTION)?; - writeln!(w, "{}", START_BODY)?; + writeln!(w, "{HEADER}")?; + writeln!(w, "<title>{title}</title>")?; + writeln!(w, "{STYLE_SECTION}")?; + writeln!(w, "{START_BODY}")?; write!( w, r#"<div class="code" style="counter-reset: line {}"><span class="line">{}"#, @@ -226,7 +226,7 @@ where write_coverage_gap(tcx, from_pos, end_pos, w)?; } writeln!(w, r#"</span></div>"#)?; - writeln!(w, "{}", FOOTER)?; + writeln!(w, "{FOOTER}")?; Ok(()) } @@ -561,17 +561,16 @@ where } for (i, line) in html_snippet.lines().enumerate() { if i > 0 { - write!(w, "{}", NEW_LINE_SPAN)?; + write!(w, "{NEW_LINE_SPAN}")?; } write!( w, - r#"<span class="code{}" style="--layer: {}"{}>{}</span>"#, - maybe_alt_class, layer, maybe_title_attr, line + r#"<span class="code{maybe_alt_class}" style="--layer: {layer}"{maybe_title_attr}>{line}</span>"# )?; } // Check for and translate trailing newlines, because `str::lines()` ignores them if html_snippet.ends_with('\n') { - write!(w, "{}", NEW_LINE_SPAN)?; + write!(w, "{NEW_LINE_SPAN}")?; } if layer == 1 { write!(w, "</span>")?; diff --git a/compiler/rustc_middle/src/mir/terminator.rs b/compiler/rustc_middle/src/mir/terminator.rs index 1b9c1438f40..6de84351595 100644 --- a/compiler/rustc_middle/src/mir/terminator.rs +++ b/compiler/rustc_middle/src/mir/terminator.rs @@ -280,7 +280,7 @@ impl<'tcx> Debug for TerminatorKind<'tcx> { match (successor_count, unwind) { (0, None) => Ok(()), - (0, Some(unwind)) => write!(fmt, " -> {}", unwind), + (0, Some(unwind)) => write!(fmt, " -> {unwind}"), (1, None) => write!(fmt, " -> {:?}", self.successors().next().unwrap()), _ => { write!(fmt, " -> [")?; @@ -307,22 +307,22 @@ impl<'tcx> TerminatorKind<'tcx> { use self::TerminatorKind::*; match self { Goto { .. } => write!(fmt, "goto"), - SwitchInt { discr, .. } => write!(fmt, "switchInt({:?})", discr), + SwitchInt { discr, .. } => write!(fmt, "switchInt({discr:?})"), Return => write!(fmt, "return"), GeneratorDrop => write!(fmt, "generator_drop"), Resume => write!(fmt, "resume"), Terminate => write!(fmt, "abort"), - Yield { value, resume_arg, .. } => write!(fmt, "{:?} = yield({:?})", resume_arg, value), + Yield { value, resume_arg, .. } => write!(fmt, "{resume_arg:?} = yield({value:?})"), Unreachable => write!(fmt, "unreachable"), - Drop { place, .. } => write!(fmt, "drop({:?})", place), + Drop { place, .. } => write!(fmt, "drop({place:?})"), Call { func, args, destination, .. } => { - write!(fmt, "{:?} = ", destination)?; - write!(fmt, "{:?}(", func)?; + write!(fmt, "{destination:?} = ")?; + write!(fmt, "{func:?}(")?; for (index, arg) in args.iter().enumerate() { if index > 0 { write!(fmt, ", ")?; } - write!(fmt, "{:?}", arg)?; + write!(fmt, "{arg:?}")?; } write!(fmt, ")") } @@ -331,7 +331,7 @@ impl<'tcx> TerminatorKind<'tcx> { if !expected { write!(fmt, "!")?; } - write!(fmt, "{:?}, ", cond)?; + write!(fmt, "{cond:?}, ")?; msg.fmt_assert_args(fmt)?; write!(fmt, ")") } @@ -344,7 +344,7 @@ impl<'tcx> TerminatorKind<'tcx> { let print_late = |&late| if late { "late" } else { "" }; match op { InlineAsmOperand::In { reg, value } => { - write!(fmt, "in({}) {:?}", reg, value)?; + write!(fmt, "in({reg}) {value:?}")?; } InlineAsmOperand::Out { reg, late, place: Some(place) } => { write!(fmt, "{}out({}) {:?}", print_late(late), reg, place)?; @@ -371,17 +371,17 @@ impl<'tcx> TerminatorKind<'tcx> { write!(fmt, "in{}out({}) {:?} => _", print_late(late), reg, in_value)?; } InlineAsmOperand::Const { value } => { - write!(fmt, "const {:?}", value)?; + write!(fmt, "const {value:?}")?; } InlineAsmOperand::SymFn { value } => { - write!(fmt, "sym_fn {:?}", value)?; + write!(fmt, "sym_fn {value:?}")?; } InlineAsmOperand::SymStatic { def_id } => { - write!(fmt, "sym_static {:?}", def_id)?; + write!(fmt, "sym_static {def_id:?}")?; } } } - write!(fmt, ", options({:?}))", options) + write!(fmt, ", options({options:?}))") } } } diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index b36f0df78f1..63df2830e0a 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -885,6 +885,13 @@ rustc_queries! { desc { |tcx| "computing the implied bounds of `{}`", tcx.def_path_str(key) } } + /// We need to store the assumed_wf_types for an RPITIT so that impls of foreign + /// traits with return-position impl trait in traits can inherit the right wf types. + query assumed_wf_types_for_rpitit(key: DefId) -> &'tcx [(Ty<'tcx>, Span)] { + desc { |tcx| "computing the implied bounds of `{}`", tcx.def_path_str(key) } + separate_provide_extern + } + /// Computes the signature of the function. query fn_sig(key: DefId) -> ty::EarlyBinder<ty::PolyFnSig<'tcx>> { desc { |tcx| "computing function signature of `{}`", tcx.def_path_str(key) } @@ -1277,7 +1284,7 @@ rustc_queries! { query vtable_allocation(key: (Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>)) -> mir::interpret::AllocId { desc { |tcx| "vtable const allocation for <{} as {}>", key.0, - key.1.map(|trait_ref| format!("{}", trait_ref)).unwrap_or("_".to_owned()) + key.1.map(|trait_ref| format!("{trait_ref}")).unwrap_or("_".to_owned()) } } @@ -2064,9 +2071,9 @@ rustc_queries! { } } - query is_impossible_method(key: (DefId, DefId)) -> bool { + query is_impossible_associated_item(key: (DefId, DefId)) -> bool { desc { |tcx| - "checking if `{}` is impossible to call within `{}`", + "checking if `{}` is impossible to reference within `{}`", tcx.def_path_str(key.1), tcx.def_path_str(key.0), } diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index e070b054720..8e2e71fd879 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -659,7 +659,7 @@ impl<'tcx> Pat<'tcx> { impl<'tcx> IntoDiagnosticArg for Pat<'tcx> { fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { - format!("{}", self).into_diagnostic_arg() + format!("{self}").into_diagnostic_arg() } } @@ -789,7 +789,7 @@ impl<'tcx> fmt::Display for Pat<'tcx> { match self.kind { PatKind::Wild => write!(f, "_"), - PatKind::AscribeUserType { ref subpattern, .. } => write!(f, "{}: _", subpattern), + PatKind::AscribeUserType { ref subpattern, .. } => write!(f, "{subpattern}: _"), PatKind::Binding { mutability, name, mode, ref subpattern, .. } => { let is_mut = match mode { BindingMode::ByValue => mutability == Mutability::Mut, @@ -801,9 +801,9 @@ impl<'tcx> fmt::Display for Pat<'tcx> { if is_mut { write!(f, "mut ")?; } - write!(f, "{}", name)?; + write!(f, "{name}")?; if let Some(ref subpattern) = *subpattern { - write!(f, " @ {}", subpattern)?; + write!(f, " @ {subpattern}")?; } Ok(()) } @@ -833,7 +833,7 @@ impl<'tcx> fmt::Display for Pat<'tcx> { }; if let Some((variant, name)) = &variant_and_name { - write!(f, "{}", name)?; + write!(f, "{name}")?; // Only for Adt we can have `S {...}`, // which we handle separately here. @@ -893,13 +893,13 @@ impl<'tcx> fmt::Display for Pat<'tcx> { } _ => bug!("{} is a bad Deref pattern type", self.ty), } - write!(f, "{}", subpattern) + write!(f, "{subpattern}") } - PatKind::Constant { value } => write!(f, "{}", value), + PatKind::Constant { value } => write!(f, "{value}"), PatKind::Range(box PatRange { lo, hi, end }) => { - write!(f, "{}", lo)?; - write!(f, "{}", end)?; - write!(f, "{}", hi) + write!(f, "{lo}")?; + write!(f, "{end}")?; + write!(f, "{hi}") } PatKind::Slice { ref prefix, ref slice, ref suffix } | PatKind::Array { ref prefix, ref slice, ref suffix } => { @@ -911,7 +911,7 @@ impl<'tcx> fmt::Display for Pat<'tcx> { write!(f, "{}", start_or_comma())?; match slice.kind { PatKind::Wild => {} - _ => write!(f, "{}", slice)?, + _ => write!(f, "{slice}")?, } write!(f, "..")?; } diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index b7ffed57a0b..85116555fc0 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -649,43 +649,31 @@ pub enum ImplSource<'tcx, N> { /// for some type parameter. The `Vec<N>` represents the /// obligations incurred from normalizing the where-clause (if /// any). - Param(Vec<N>, ty::BoundConstness), + Param(ty::BoundConstness, Vec<N>), - /// Virtual calls through an object. - Object(ImplSourceObjectData<N>), - - /// Successful resolution for a builtin trait. - Builtin(Vec<N>), - - /// ImplSource for trait upcasting coercion - TraitUpcasting(ImplSourceTraitUpcastingData<N>), + /// Successful resolution for a builtin impl. + Builtin(BuiltinImplSource, Vec<N>), } impl<'tcx, N> ImplSource<'tcx, N> { pub fn nested_obligations(self) -> Vec<N> { match self { ImplSource::UserDefined(i) => i.nested, - ImplSource::Param(n, _) | ImplSource::Builtin(n) => n, - ImplSource::Object(d) => d.nested, - ImplSource::TraitUpcasting(d) => d.nested, + ImplSource::Param(_, n) | ImplSource::Builtin(_, n) => n, } } pub fn borrow_nested_obligations(&self) -> &[N] { match self { ImplSource::UserDefined(i) => &i.nested, - ImplSource::Param(n, _) | ImplSource::Builtin(n) => &n, - ImplSource::Object(d) => &d.nested, - ImplSource::TraitUpcasting(d) => &d.nested, + ImplSource::Param(_, n) | ImplSource::Builtin(_, n) => &n, } } pub fn borrow_nested_obligations_mut(&mut self) -> &mut [N] { match self { ImplSource::UserDefined(i) => &mut i.nested, - ImplSource::Param(n, _) | ImplSource::Builtin(n) => n, - ImplSource::Object(d) => &mut d.nested, - ImplSource::TraitUpcasting(d) => &mut d.nested, + ImplSource::Param(_, n) | ImplSource::Builtin(_, n) => n, } } @@ -699,17 +687,9 @@ impl<'tcx, N> ImplSource<'tcx, N> { args: i.args, nested: i.nested.into_iter().map(f).collect(), }), - ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct), - ImplSource::Builtin(n) => ImplSource::Builtin(n.into_iter().map(f).collect()), - ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData { - vtable_base: o.vtable_base, - nested: o.nested.into_iter().map(f).collect(), - }), - ImplSource::TraitUpcasting(d) => { - ImplSource::TraitUpcasting(ImplSourceTraitUpcastingData { - vtable_vptr_slot: d.vtable_vptr_slot, - nested: d.nested.into_iter().map(f).collect(), - }) + ImplSource::Param(ct, n) => ImplSource::Param(ct, n.into_iter().map(f).collect()), + ImplSource::Builtin(source, n) => { + ImplSource::Builtin(source, n.into_iter().map(f).collect()) } } } @@ -733,29 +713,31 @@ pub struct ImplSourceUserDefinedData<'tcx, N> { pub nested: Vec<N>, } -#[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)] -#[derive(TypeFoldable, TypeVisitable)] -pub struct ImplSourceTraitUpcastingData<N> { +#[derive(Copy, Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Debug)] +pub enum BuiltinImplSource { + /// Some builtin impl we don't need to differentiate. This should be used + /// unless more specific information is necessary. + Misc, + /// A builtin impl for trait objects. + /// + /// The vtable is formed by concatenating together the method lists of + /// the base object trait and all supertraits, pointers to supertrait vtable will + /// be provided when necessary; this is the start of `upcast_trait_ref`'s methods + /// in that vtable. + Object { vtable_base: usize }, /// The vtable is formed by concatenating together the method lists of /// the base object trait and all supertraits, pointers to supertrait vtable will /// be provided when necessary; this is the position of `upcast_trait_ref`'s vtable /// within that vtable. - pub vtable_vptr_slot: Option<usize>, - - pub nested: Vec<N>, + TraitUpcasting { vtable_vptr_slot: Option<usize> }, + /// Unsizing a tuple like `(A, B, ..., X)` to `(A, B, ..., Y)` if `X` unsizes to `Y`. + /// + /// This needs to be a separate variant as it is still unstable and we need to emit + /// a feature error when using it on stable. + TupleUnsizing, } -#[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, Lift)] -#[derive(TypeFoldable, TypeVisitable)] -pub struct ImplSourceObjectData<N> { - /// The vtable is formed by concatenating together the method lists of - /// the base object trait and all supertraits, pointers to supertrait vtable will - /// be provided when necessary; this is the start of `upcast_trait_ref`'s methods - /// in that vtable. - pub vtable_base: usize, - - pub nested: Vec<N>, -} +TrivialTypeTraversalAndLiftImpls! { BuiltinImplSource } #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)] pub enum ObjectSafetyViolation { @@ -795,49 +777,48 @@ impl ObjectSafetyViolation { "where clause cannot reference non-lifetime `for<...>` variables".into() } ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => { - format!("associated function `{}` has no `self` parameter", name).into() + format!("associated function `{name}` has no `self` parameter").into() } ObjectSafetyViolation::Method( name, MethodViolationCode::ReferencesSelfInput(_), DUMMY_SP, - ) => format!("method `{}` references the `Self` type in its parameters", name).into(), + ) => format!("method `{name}` references the `Self` type in its parameters").into(), ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => { - format!("method `{}` references the `Self` type in this parameter", name).into() + format!("method `{name}` references the `Self` type in this parameter").into() } ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => { - format!("method `{}` references the `Self` type in its return type", name).into() + format!("method `{name}` references the `Self` type in its return type").into() } ObjectSafetyViolation::Method( name, MethodViolationCode::ReferencesImplTraitInTrait(_), _, - ) => format!("method `{}` references an `impl Trait` type in its return type", name) - .into(), + ) => { + format!("method `{name}` references an `impl Trait` type in its return type").into() + } ObjectSafetyViolation::Method(name, MethodViolationCode::AsyncFn, _) => { - format!("method `{}` is `async`", name).into() + format!("method `{name}` is `async`").into() } ObjectSafetyViolation::Method( name, MethodViolationCode::WhereClauseReferencesSelf, _, - ) => { - format!("method `{}` references the `Self` type in its `where` clause", name).into() - } + ) => format!("method `{name}` references the `Self` type in its `where` clause").into(), ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => { - format!("method `{}` has generic type parameters", name).into() + format!("method `{name}` has generic type parameters").into() } ObjectSafetyViolation::Method( name, MethodViolationCode::UndispatchableReceiver(_), _, - ) => format!("method `{}`'s `self` parameter cannot be dispatched on", name).into(), + ) => format!("method `{name}`'s `self` parameter cannot be dispatched on").into(), ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => { - format!("it contains associated `const` `{}`", name).into() + format!("it contains associated `const` `{name}`").into() } ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(), ObjectSafetyViolation::GAT(name, _) => { - format!("it contains the generic associated type `{}`", name).into() + format!("it contains the generic associated type `{name}`").into() } } } @@ -855,8 +836,7 @@ impl ObjectSafetyViolation { err.span_suggestion( add_self_sugg.1, format!( - "consider turning `{}` into a method by giving it a `&self` argument", - name + "consider turning `{name}` into a method by giving it a `&self` argument" ), add_self_sugg.0.to_string(), Applicability::MaybeIncorrect, @@ -864,9 +844,8 @@ impl ObjectSafetyViolation { err.span_suggestion( make_sized_sugg.1, format!( - "alternatively, consider constraining `{}` so it does not apply to \ - trait objects", - name + "alternatively, consider constraining `{name}` so it does not apply to \ + trait objects" ), make_sized_sugg.0.to_string(), Applicability::MaybeIncorrect, @@ -879,7 +858,7 @@ impl ObjectSafetyViolation { ) => { err.span_suggestion( *span, - format!("consider changing method `{}`'s `self` parameter to be `&self`", name), + format!("consider changing method `{name}`'s `self` parameter to be `&self`"), "&Self", Applicability::MachineApplicable, ); @@ -887,7 +866,7 @@ impl ObjectSafetyViolation { ObjectSafetyViolation::AssocConst(name, _) | ObjectSafetyViolation::GAT(name, _) | ObjectSafetyViolation::Method(name, ..) => { - err.help(format!("consider moving `{}` to another trait", name)); + err.help(format!("consider moving `{name}` to another trait")); } } } diff --git a/compiler/rustc_middle/src/traits/select.rs b/compiler/rustc_middle/src/traits/select.rs index f2dda003b99..a90d58f5fc1 100644 --- a/compiler/rustc_middle/src/traits/select.rs +++ b/compiler/rustc_middle/src/traits/select.rs @@ -304,9 +304,7 @@ impl From<ErrorGuaranteed> for OverflowError { } } -TrivialTypeTraversalAndLiftImpls! { - OverflowError, -} +TrivialTypeTraversalAndLiftImpls! { OverflowError } impl<'tcx> From<OverflowError> for SelectionError<'tcx> { fn from(overflow_error: OverflowError) -> SelectionError<'tcx> { diff --git a/compiler/rustc_middle/src/traits/solve.rs b/compiler/rustc_middle/src/traits/solve.rs index 73b332fd8ec..b21a00e4122 100644 --- a/compiler/rustc_middle/src/traits/solve.rs +++ b/compiler/rustc_middle/src/traits/solve.rs @@ -57,6 +57,7 @@ pub enum Certainty { impl Certainty { pub const AMBIGUOUS: Certainty = Certainty::Maybe(MaybeCause::Ambiguity); + pub const OVERFLOW: Certainty = Certainty::Maybe(MaybeCause::Overflow); /// Use this function to merge the certainty of multiple nested subgoals. /// @@ -66,7 +67,7 @@ impl Certainty { /// success, we merge these two responses. This results in ambiguity. /// /// If we unify ambiguity with overflow, we return overflow. This doesn't matter - /// inside of the solver as we distinguish ambiguity from overflow. It does + /// inside of the solver as we do not distinguish ambiguity from overflow. It does /// however matter for diagnostics. If `T: Foo` resulted in overflow and `T: Bar` /// in ambiguity without changing the inference state, we still want to tell the /// user that `T: Baz` results in overflow. diff --git a/compiler/rustc_middle/src/traits/solve/inspect.rs b/compiler/rustc_middle/src/traits/solve/inspect.rs index 8698cf86022..e793f481995 100644 --- a/compiler/rustc_middle/src/traits/solve/inspect.rs +++ b/compiler/rustc_middle/src/traits/solve/inspect.rs @@ -73,8 +73,12 @@ pub struct GoalCandidate<'tcx> { pub enum CandidateKind<'tcx> { /// Probe entered when normalizing the self ty during candidate assembly NormalizedSelfTyAssembly, + DynUpcastingAssembly, /// A normal candidate for proving a goal - Candidate { name: String, result: QueryResult<'tcx> }, + Candidate { + name: String, + result: QueryResult<'tcx>, + }, } impl Debug for GoalCandidate<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { diff --git a/compiler/rustc_middle/src/traits/solve/inspect/format.rs b/compiler/rustc_middle/src/traits/solve/inspect/format.rs index f19f1189e44..f1e567e9bf8 100644 --- a/compiler/rustc_middle/src/traits/solve/inspect/format.rs +++ b/compiler/rustc_middle/src/traits/solve/inspect/format.rs @@ -15,11 +15,11 @@ struct Indentor<'a, 'b> { impl Write for Indentor<'_, '_> { fn write_str(&mut self, s: &str) -> std::fmt::Result { - for line in s.split_inclusive("\n") { + for line in s.split_inclusive('\n') { if self.on_newline { self.f.write_str(" ")?; } - self.on_newline = line.ends_with("\n"); + self.on_newline = line.ends_with('\n'); self.f.write_str(line)?; } @@ -68,7 +68,7 @@ impl<'a, 'b> ProofTreeFormatter<'a, 'b> { writeln!(self.f, "NESTED GOALS ADDED TO CALLER: [")?; self.nested(|this| { for goal in goal.returned_goals.iter() { - writeln!(this.f, "ADDED GOAL: {:?},", goal)?; + writeln!(this.f, "ADDED GOAL: {goal:?},")?; } Ok(()) })?; @@ -100,8 +100,11 @@ impl<'a, 'b> ProofTreeFormatter<'a, 'b> { CandidateKind::NormalizedSelfTyAssembly => { writeln!(self.f, "NORMALIZING SELF TY FOR ASSEMBLY:") } + CandidateKind::DynUpcastingAssembly => { + writeln!(self.f, "ASSEMBLING CANDIDATES FOR DYN UPCASTING:") + } CandidateKind::Candidate { name, result } => { - writeln!(self.f, "CANDIDATE {}: {:?}", name, result) + writeln!(self.f, "CANDIDATE {name}: {result:?}") } }?; diff --git a/compiler/rustc_middle/src/traits/specialization_graph.rs b/compiler/rustc_middle/src/traits/specialization_graph.rs index 18a57b6181a..e48b46d12c4 100644 --- a/compiler/rustc_middle/src/traits/specialization_graph.rs +++ b/compiler/rustc_middle/src/traits/specialization_graph.rs @@ -43,7 +43,7 @@ impl Graph { /// The parent of a given impl, which is the `DefId` of the trait when the /// impl is a "specialization root". pub fn parent(&self, child: DefId) -> DefId { - *self.parent.get(&child).unwrap_or_else(|| panic!("Failed to get parent for {:?}", child)) + *self.parent.get(&child).unwrap_or_else(|| panic!("Failed to get parent for {child:?}")) } } diff --git a/compiler/rustc_middle/src/traits/structural_impls.rs b/compiler/rustc_middle/src/traits/structural_impls.rs index e2cd118500b..d7dc429f53b 100644 --- a/compiler/rustc_middle/src/traits/structural_impls.rs +++ b/compiler/rustc_middle/src/traits/structural_impls.rs @@ -6,18 +6,16 @@ use std::fmt; impl<'tcx, N: fmt::Debug> fmt::Debug for traits::ImplSource<'tcx, N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - super::ImplSource::UserDefined(ref v) => write!(f, "{:?}", v), + match self { + super::ImplSource::UserDefined(v) => write!(f, "{v:?}"), - super::ImplSource::Builtin(ref d) => write!(f, "{:?}", d), - - super::ImplSource::Object(ref d) => write!(f, "{:?}", d), - - super::ImplSource::Param(ref n, ct) => { - write!(f, "ImplSourceParamData({:?}, {:?})", n, ct) + super::ImplSource::Builtin(source, d) => { + write!(f, "Builtin({source:?}, {d:?})") } - super::ImplSource::TraitUpcasting(ref d) => write!(f, "{:?}", d), + super::ImplSource::Param(ct, n) => { + write!(f, "ImplSourceParamData({n:?}, {ct:?})") + } } } } @@ -31,23 +29,3 @@ impl<'tcx, N: fmt::Debug> fmt::Debug for traits::ImplSourceUserDefinedData<'tcx, ) } } - -impl<N: fmt::Debug> fmt::Debug for traits::ImplSourceTraitUpcastingData<N> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "ImplSourceTraitUpcastingData(vtable_vptr_slot={:?}, nested={:?})", - self.vtable_vptr_slot, self.nested - ) - } -} - -impl<N: fmt::Debug> fmt::Debug for traits::ImplSourceObjectData<N> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "ImplSourceObjectData(vtable_base={}, nested={:?})", - self.vtable_base, self.nested - ) - } -} diff --git a/compiler/rustc_middle/src/ty/abstract_const.rs b/compiler/rustc_middle/src/ty/abstract_const.rs index 0364a620810..cdd8351499b 100644 --- a/compiler/rustc_middle/src/ty/abstract_const.rs +++ b/compiler/rustc_middle/src/ty/abstract_const.rs @@ -27,9 +27,7 @@ impl From<ErrorGuaranteed> for NotConstEvaluatable { } } -TrivialTypeTraversalAndLiftImpls! { - NotConstEvaluatable, -} +TrivialTypeTraversalAndLiftImpls! { NotConstEvaluatable } pub type BoundAbstractConst<'tcx> = Result<Option<EarlyBinder<ty::Const<'tcx>>>, ErrorGuaranteed>; diff --git a/compiler/rustc_middle/src/ty/binding.rs b/compiler/rustc_middle/src/ty/binding.rs index a5b05a4f9b5..2fec8ac9095 100644 --- a/compiler/rustc_middle/src/ty/binding.rs +++ b/compiler/rustc_middle/src/ty/binding.rs @@ -6,7 +6,7 @@ pub enum BindingMode { BindByValue(Mutability), } -TrivialTypeTraversalAndLiftImpls! { BindingMode, } +TrivialTypeTraversalAndLiftImpls! { BindingMode } impl BindingMode { pub fn convert(BindingAnnotation(by_ref, mutbl): BindingAnnotation) -> BindingMode { diff --git a/compiler/rustc_middle/src/ty/closure.rs b/compiler/rustc_middle/src/ty/closure.rs index 91eefa2c125..42f22604975 100644 --- a/compiler/rustc_middle/src/ty/closure.rs +++ b/compiler/rustc_middle/src/ty/closure.rs @@ -348,7 +348,7 @@ pub fn place_to_string_for_capture<'tcx>(tcx: TyCtxt<'tcx>, place: &HirPlace<'tc for (i, proj) in place.projections.iter().enumerate() { match proj.kind { HirProjectionKind::Deref => { - curr_string = format!("*{}", curr_string); + curr_string = format!("*{curr_string}"); } HirProjectionKind::Field(idx, variant) => match place.ty_before_projection(i).kind() { ty::Adt(def, ..) => { diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index b4f4f9bef8e..7c05deae90a 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -168,7 +168,6 @@ impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::ParamEnv<'tcx> { fn encode(&self, e: &mut E) { self.caller_bounds().encode(e); self.reveal().encode(e); - self.constness().encode(e); } } @@ -306,8 +305,7 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::ParamEnv<'tcx> { fn decode(d: &mut D) -> Self { let caller_bounds = Decodable::decode(d); let reveal = Decodable::decode(d); - let constness = Decodable::decode(d); - ty::ParamEnv::new(caller_bounds, reveal, constness) + ty::ParamEnv::new(caller_bounds, reveal) } } diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index 4ef70107f19..cce10417e1b 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -212,7 +212,7 @@ impl<'tcx> Const<'tcx> { Err(e) => { tcx.sess.delay_span_bug( expr.span, - format!("Const::from_anon_const: couldn't lit_to_const {:?}", e), + format!("Const::from_anon_const: couldn't lit_to_const {e:?}"), ); } } @@ -267,7 +267,7 @@ impl<'tcx> Const<'tcx> { pub fn from_bits(tcx: TyCtxt<'tcx>, bits: u128, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> Self { let size = tcx .layout_of(ty) - .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e)) + .unwrap_or_else(|e| panic!("could not compute layout for {ty:?}: {e:?}")) .size; ty::Const::new_value( tcx, diff --git a/compiler/rustc_middle/src/ty/consts/int.rs b/compiler/rustc_middle/src/ty/consts/int.rs index 624195cfb28..b16163edf14 100644 --- a/compiler/rustc_middle/src/ty/consts/int.rs +++ b/compiler/rustc_middle/src/ty/consts/int.rs @@ -463,7 +463,7 @@ impl TryFrom<ScalarInt> for Double { impl fmt::Debug for ScalarInt { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Dispatch to LowerHex below. - write!(f, "0x{:x}", self) + write!(f, "0x{self:x}") } } diff --git a/compiler/rustc_middle/src/ty/consts/kind.rs b/compiler/rustc_middle/src/ty/consts/kind.rs index 6c76075c214..db4a15fbee5 100644 --- a/compiler/rustc_middle/src/ty/consts/kind.rs +++ b/compiler/rustc_middle/src/ty/consts/kind.rs @@ -17,7 +17,7 @@ pub struct UnevaluatedConst<'tcx> { impl rustc_errors::IntoDiagnosticArg for UnevaluatedConst<'_> { fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> { - format!("{:?}", self).into_diagnostic_arg() + format!("{self:?}").into_diagnostic_arg() } } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 1a23fa80210..aa1f8e48b1b 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -569,6 +569,7 @@ pub struct GlobalCtxt<'tcx> { /// Caches the results of goal evaluation in the new solver. pub new_solver_evaluation_cache: solve::EvaluationCache<'tcx>, + pub new_solver_coherence_evaluation_cache: solve::EvaluationCache<'tcx>, /// Data layout specification for the current target. pub data_layout: TargetDataLayout, @@ -680,10 +681,12 @@ impl<'tcx> TyCtxt<'tcx> { value.lift_to_tcx(self) } - /// Creates a type context and call the closure with a `TyCtxt` reference - /// to the context. The closure enforces that the type context and any interned - /// value (types, args, etc.) can only be used while `ty::tls` has a valid - /// reference to the context, to allow formatting values that need it. + /// Creates a type context. To use the context call `fn enter` which + /// provides a `TyCtxt`. + /// + /// By only providing the `TyCtxt` inside of the closure we enforce that the type + /// context and any interned alue (types, args, etc.) can only be used while `ty::tls` + /// has a valid reference to the context, to allow formatting values that need it. pub fn create_global_ctxt( s: &'tcx Session, lint_store: Lrc<dyn Any + sync::DynSend + sync::DynSync>, @@ -721,6 +724,7 @@ impl<'tcx> TyCtxt<'tcx> { selection_cache: Default::default(), evaluation_cache: Default::default(), new_solver_evaluation_cache: Default::default(), + new_solver_coherence_evaluation_cache: Default::default(), data_layout, alloc_map: Lock::new(interpret::AllocMap::new()), } diff --git a/compiler/rustc_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index 905e855896e..8570f83dcc6 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -126,7 +126,7 @@ pub fn suggest_arbitrary_trait_bound<'tcx>( if constraint.ends_with('>') { constraint = format!("{}, {} = {}>", &constraint[..constraint.len() - 1], name, term); } else { - constraint.push_str(&format!("<{} = {}>", name, term)); + constraint.push_str(&format!("<{name} = {term}>")); } } @@ -274,9 +274,9 @@ pub fn suggest_constraining_type_params<'a>( if span_to_replace.is_some() { constraint.clone() } else if bound_list_non_empty { - format!(" + {}", constraint) + format!(" + {constraint}") } else { - format!(" {}", constraint) + format!(" {constraint}") }, SuggestChangingConstraintsMessage::RestrictBoundFurther, )) @@ -337,7 +337,7 @@ pub fn suggest_constraining_type_params<'a>( generics.tail_span_for_predicate_suggestion(), constraints .iter() - .map(|&(constraint, _)| format!(", {}: {}", param_name, constraint)) + .map(|&(constraint, _)| format!(", {param_name}: {constraint}")) .collect::<String>(), SuggestChangingConstraintsMessage::RestrictTypeFurther { ty: param_name }, )); @@ -358,7 +358,7 @@ pub fn suggest_constraining_type_params<'a>( // default (`<T=Foo>`), so we suggest adding `where T: Bar`. suggestions.push(( generics.tail_span_for_predicate_suggestion(), - format!(" where {}: {}", param_name, constraint), + format!(" where {param_name}: {constraint}"), SuggestChangingConstraintsMessage::RestrictTypeFurther { ty: param_name }, )); continue; @@ -371,7 +371,7 @@ pub fn suggest_constraining_type_params<'a>( if let Some(colon_span) = param.colon_span { suggestions.push(( colon_span.shrink_to_hi(), - format!(" {}", constraint), + format!(" {constraint}"), SuggestChangingConstraintsMessage::RestrictType { ty: param_name }, )); continue; @@ -383,7 +383,7 @@ pub fn suggest_constraining_type_params<'a>( // - help: consider restricting this type parameter with `T: Foo` suggestions.push(( param.span.shrink_to_hi(), - format!(": {}", constraint), + format!(": {constraint}"), SuggestChangingConstraintsMessage::RestrictType { ty: param_name }, )); } @@ -401,10 +401,10 @@ pub fn suggest_constraining_type_params<'a>( Cow::from("consider further restricting this bound") } SuggestChangingConstraintsMessage::RestrictType { ty } => { - Cow::from(format!("consider restricting type parameter `{}`", ty)) + Cow::from(format!("consider restricting type parameter `{ty}`")) } SuggestChangingConstraintsMessage::RestrictTypeFurther { ty } => { - Cow::from(format!("consider further restricting type parameter `{}`", ty)) + Cow::from(format!("consider further restricting type parameter `{ty}`")) } SuggestChangingConstraintsMessage::RemoveMaybeUnsized => { Cow::from("consider removing the `?Sized` bound to make the type parameter `Sized`") diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index c794c3faded..bf6f082c21c 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -90,9 +90,9 @@ impl<'tcx> TypeError<'tcx> { // A naive approach to making sure that we're not reporting silly errors such as: // (expected closure, found closure). if expected == found { - format!("expected {}, found a different {}", expected, found) + format!("expected {expected}, found a different {found}") } else { - format!("expected {}, found {}", expected, found) + format!("expected {expected}, found {found}") } } @@ -131,7 +131,7 @@ impl<'tcx> TypeError<'tcx> { ) .into(), ArgCount => "incorrect number of function parameters".into(), - FieldMisMatch(adt, field) => format!("field type mismatch: {}.{}", adt, field).into(), + FieldMisMatch(adt, field) => format!("field type mismatch: {adt}.{field}").into(), RegionsDoesNotOutlive(..) => "lifetime mismatch".into(), // Actually naming the region here is a bit confusing because context is lacking RegionsInsufficientlyPolymorphic(..) => { @@ -164,7 +164,7 @@ impl<'tcx> TypeError<'tcx> { ty::IntVarValue::IntType(ty) => ty.name_str(), ty::IntVarValue::UintType(ty) => ty.name_str(), }; - format!("expected `{}`, found `{}`", expected, found).into() + format!("expected `{expected}`, found `{found}`").into() } FloatMismatch(ref values) => format!( "expected `{}`, found `{}`", @@ -339,12 +339,17 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn short_ty_string(self, ty: Ty<'tcx>) -> (String, Option<PathBuf>) { - let width = self.sess.diagnostic_width(); - let length_limit = width.saturating_sub(30); let regular = FmtPrinter::new(self, hir::def::Namespace::TypeNS) .pretty_print_type(ty) .expect("could not write to `String`") .into_buffer(); + + if !self.sess.opts.unstable_opts.write_long_types_to_disk { + return (regular, None); + } + + let width = self.sess.diagnostic_width(); + let length_limit = width.saturating_sub(30); if regular.len() <= width { return (regular, None); } diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index 48e88daa890..8913bf76d34 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -308,13 +308,13 @@ fn fmt_instance( InstanceDef::ReifyShim(_) => write!(f, " - shim(reify)"), InstanceDef::ThreadLocalShim(_) => write!(f, " - shim(tls)"), InstanceDef::Intrinsic(_) => write!(f, " - intrinsic"), - InstanceDef::Virtual(_, num) => write!(f, " - virtual#{}", num), - InstanceDef::FnPtrShim(_, ty) => write!(f, " - shim({})", ty), + InstanceDef::Virtual(_, num) => write!(f, " - virtual#{num}"), + InstanceDef::FnPtrShim(_, ty) => write!(f, " - shim({ty})"), InstanceDef::ClosureOnceShim { .. } => write!(f, " - shim"), InstanceDef::DropGlue(_, None) => write!(f, " - shim(None)"), - InstanceDef::DropGlue(_, Some(ty)) => write!(f, " - shim(Some({}))", ty), - InstanceDef::CloneShim(_, ty) => write!(f, " - shim({})", ty), - InstanceDef::FnPtrAddrShim(_, ty) => write!(f, " - shim({})", ty), + InstanceDef::DropGlue(_, Some(ty)) => write!(f, " - shim(Some({ty}))"), + InstanceDef::CloneShim(_, ty) => write!(f, " - shim({ty})"), + InstanceDef::FnPtrAddrShim(_, ty) => write!(f, " - shim({ty})"), } } @@ -336,9 +336,7 @@ impl<'tcx> Instance<'tcx> { pub fn new(def_id: DefId, args: GenericArgsRef<'tcx>) -> Instance<'tcx> { assert!( !args.has_escaping_bound_vars(), - "args of instance {:?} not normalized for codegen: {:?}", - def_id, - args + "args of instance {def_id:?} not normalized for codegen: {args:?}" ); Instance { def: InstanceDef::Item(def_id), args } } @@ -425,7 +423,7 @@ impl<'tcx> Instance<'tcx> { ) -> Option<Instance<'tcx>> { debug!("resolve(def_id={:?}, args={:?})", def_id, args); // Use either `resolve_closure` or `resolve_for_vtable` - assert!(!tcx.is_closure(def_id), "Called `resolve_for_fn_ptr` on closure: {:?}", def_id); + assert!(!tcx.is_closure(def_id), "Called `resolve_for_fn_ptr` on closure: {def_id:?}"); Instance::resolve(tcx, param_env, def_id, args).ok().flatten().map(|mut resolved| { match resolved.def { InstanceDef::Item(def) if resolved.def.requires_caller_location(tcx) => { diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 62805d1e8b5..0f7bed0845c 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -10,7 +10,7 @@ use rustc_hir::def_id::DefId; use rustc_index::IndexVec; use rustc_session::config::OptLevel; use rustc_span::symbol::{sym, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; use rustc_target::abi::call::FnAbi; use rustc_target::abi::*; use rustc_target::spec::{abi::Abi as SpecAbi, HasTargetSpec, PanicStrategy, Target}; @@ -212,6 +212,7 @@ pub enum LayoutError<'tcx> { Unknown(Ty<'tcx>), SizeOverflow(Ty<'tcx>), NormalizationFailure(Ty<'tcx>, NormalizationError<'tcx>), + ReferencesError(ErrorGuaranteed), Cycle, } @@ -224,6 +225,7 @@ impl<'tcx> LayoutError<'tcx> { SizeOverflow(_) => middle_values_too_big, NormalizationFailure(_, _) => middle_cannot_be_normalized, Cycle => middle_cycle, + ReferencesError(_) => middle_layout_references_error, } } @@ -237,6 +239,7 @@ impl<'tcx> LayoutError<'tcx> { E::NormalizationFailure { ty, failure_ty: e.get_type_for_failure() } } Cycle => E::Cycle, + ReferencesError(_) => E::ReferencesError, } } } @@ -246,9 +249,9 @@ impl<'tcx> LayoutError<'tcx> { impl<'tcx> fmt::Display for LayoutError<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - LayoutError::Unknown(ty) => write!(f, "the type `{}` has an unknown layout", ty), + LayoutError::Unknown(ty) => write!(f, "the type `{ty}` has an unknown layout"), LayoutError::SizeOverflow(ty) => { - write!(f, "values of the type `{}` are too big for the current architecture", ty) + write!(f, "values of the type `{ty}` are too big for the current architecture") } LayoutError::NormalizationFailure(t, e) => write!( f, @@ -257,6 +260,7 @@ impl<'tcx> fmt::Display for LayoutError<'tcx> { e.get_type_for_failure() ), LayoutError::Cycle => write!(f, "a cycle occurred during layout computation"), + LayoutError::ReferencesError(_) => write!(f, "the type has an unknown layout"), } } } @@ -323,7 +327,8 @@ impl<'tcx> SizeSkeleton<'tcx> { Err( e @ LayoutError::Cycle | e @ LayoutError::SizeOverflow(_) - | e @ LayoutError::NormalizationFailure(..), + | e @ LayoutError::NormalizationFailure(..) + | e @ LayoutError::ReferencesError(_), ) => return Err(e), }; @@ -741,9 +746,9 @@ where let fields = match this.ty.kind() { ty::Adt(def, _) if def.variants().is_empty() => - bug!("for_variant called on zero-variant enum"), + bug!("for_variant called on zero-variant enum {}", this.ty), ty::Adt(def, _) => def.variant(variant_index).fields.len(), - _ => bug!(), + _ => bug!("`ty_and_layout_for_variant` on unexpected type {}", this.ty), }; tcx.mk_layout(LayoutS { variants: Variants::Single { index: variant_index }, diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 0411890ab51..2b4c834f766 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -867,20 +867,6 @@ pub struct TraitPredicate<'tcx> { pub type PolyTraitPredicate<'tcx> = ty::Binder<'tcx, TraitPredicate<'tcx>>; impl<'tcx> TraitPredicate<'tcx> { - pub fn remap_constness(&mut self, param_env: &mut ParamEnv<'tcx>) { - *param_env = param_env.with_constness(self.constness.and(param_env.constness())) - } - - /// Remap the constness of this predicate before emitting it for diagnostics. - pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) { - // this is different to `remap_constness` that callees want to print this predicate - // in case of selection errors. `T: ~const Drop` bounds cannot end up here when the - // param_env is not const because it is always satisfied in non-const contexts. - if let hir::Constness::NotConst = param_env.constness() { - self.constness = ty::BoundConstness::NotConst; - } - } - pub fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self { Self { trait_ref: self.trait_ref.with_self_ty(tcx, self_ty), ..self } } @@ -922,14 +908,6 @@ impl<'tcx> PolyTraitPredicate<'tcx> { self.map_bound(|trait_ref| trait_ref.self_ty()) } - /// Remap the constness of this predicate before emitting it for diagnostics. - pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) { - *self = self.map_bound(|mut p| { - p.remap_constness_diag(param_env); - p - }); - } - #[inline] pub fn is_const_if_const(self) -> bool { self.skip_binder().is_const_if_const() @@ -980,9 +958,9 @@ pub struct Term<'tcx> { impl Debug for Term<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let data = if let Some(ty) = self.ty() { - format!("Term::Ty({:?})", ty) + format!("Term::Ty({ty:?})") } else if let Some(ct) = self.ct() { - format!("Term::Ct({:?})", ct) + format!("Term::Ct({ct:?})") } else { unreachable!() }; @@ -1381,12 +1359,24 @@ impl<'tcx> ToPredicate<'tcx, Clause<'tcx>> for PolyTraitPredicate<'tcx> { } } +impl<'tcx> ToPredicate<'tcx> for OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>> { + fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { + ty::Binder::dummy(PredicateKind::Clause(ClauseKind::RegionOutlives(self))).to_predicate(tcx) + } +} + impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { self.map_bound(|p| PredicateKind::Clause(ClauseKind::RegionOutlives(p))).to_predicate(tcx) } } +impl<'tcx> ToPredicate<'tcx> for OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> { + fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { + ty::Binder::dummy(PredicateKind::Clause(ClauseKind::TypeOutlives(self))).to_predicate(tcx) + } +} + impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { self.map_bound(|p| PredicateKind::Clause(ClauseKind::TypeOutlives(p))).to_predicate(tcx) @@ -1700,15 +1690,12 @@ pub struct ParamEnv<'tcx> { #[derive(Copy, Clone)] struct ParamTag { reveal: traits::Reveal, - constness: hir::Constness, } impl_tag! { impl Tag for ParamTag; - ParamTag { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst }, - ParamTag { reveal: traits::Reveal::All, constness: hir::Constness::NotConst }, - ParamTag { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const }, - ParamTag { reveal: traits::Reveal::All, constness: hir::Constness::Const }, + ParamTag { reveal: traits::Reveal::UserFacing }, + ParamTag { reveal: traits::Reveal::All }, } impl<'tcx> fmt::Debug for ParamEnv<'tcx> { @@ -1716,7 +1703,6 @@ impl<'tcx> fmt::Debug for ParamEnv<'tcx> { f.debug_struct("ParamEnv") .field("caller_bounds", &self.caller_bounds()) .field("reveal", &self.reveal()) - .field("constness", &self.constness()) .finish() } } @@ -1725,7 +1711,6 @@ impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> { fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { self.caller_bounds().hash_stable(hcx, hasher); self.reveal().hash_stable(hcx, hasher); - self.constness().hash_stable(hcx, hasher); } } @@ -1737,7 +1722,6 @@ impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for ParamEnv<'tcx> { Ok(ParamEnv::new( self.caller_bounds().try_fold_with(folder)?, self.reveal().try_fold_with(folder)?, - self.constness(), )) } } @@ -1756,7 +1740,7 @@ impl<'tcx> ParamEnv<'tcx> { /// type-checking. #[inline] pub fn empty() -> Self { - Self::new(List::empty(), Reveal::UserFacing, hir::Constness::NotConst) + Self::new(List::empty(), Reveal::UserFacing) } #[inline] @@ -1769,16 +1753,6 @@ impl<'tcx> ParamEnv<'tcx> { self.packed.tag().reveal } - #[inline] - pub fn constness(self) -> hir::Constness { - self.packed.tag().constness - } - - #[inline] - pub fn is_const(self) -> bool { - self.packed.tag().constness == hir::Constness::Const - } - /// Construct a trait environment with no where-clauses in scope /// where the values of all `impl Trait` and other hidden types /// are revealed. This is suitable for monomorphized, post-typeck @@ -1788,17 +1762,13 @@ impl<'tcx> ParamEnv<'tcx> { /// or invoke `param_env.with_reveal_all()`. #[inline] pub fn reveal_all() -> Self { - Self::new(List::empty(), Reveal::All, hir::Constness::NotConst) + Self::new(List::empty(), Reveal::All) } /// Construct a trait environment with the given set of predicates. #[inline] - pub fn new( - caller_bounds: &'tcx List<Clause<'tcx>>, - reveal: Reveal, - constness: hir::Constness, - ) -> Self { - ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, ParamTag { reveal, constness }) } + pub fn new(caller_bounds: &'tcx List<Clause<'tcx>>, reveal: Reveal) -> Self { + ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, ParamTag { reveal }) } } pub fn with_user_facing(mut self) -> Self { @@ -1806,29 +1776,6 @@ impl<'tcx> ParamEnv<'tcx> { self } - #[inline] - pub fn with_constness(mut self, constness: hir::Constness) -> Self { - self.packed.set_tag(ParamTag { constness, ..self.packed.tag() }); - self - } - - #[inline] - pub fn with_const(mut self) -> Self { - self.packed.set_tag(ParamTag { constness: hir::Constness::Const, ..self.packed.tag() }); - self - } - - #[inline] - pub fn without_const(mut self) -> Self { - self.packed.set_tag(ParamTag { constness: hir::Constness::NotConst, ..self.packed.tag() }); - self - } - - #[inline] - pub fn remap_constness_with(&mut self, mut constness: ty::BoundConstness) { - *self = self.with_constness(constness.and(self.constness())) - } - /// Returns a new parameter environment with the same clauses, but /// which "reveals" the true results of projections in all cases /// (even for associated types that are specializable). This is @@ -1843,17 +1790,13 @@ impl<'tcx> ParamEnv<'tcx> { return self; } - ParamEnv::new( - tcx.reveal_opaque_types_in_bounds(self.caller_bounds()), - Reveal::All, - self.constness(), - ) + ParamEnv::new(tcx.reveal_opaque_types_in_bounds(self.caller_bounds()), Reveal::All) } /// Returns this same environment but with no caller bounds. #[inline] pub fn without_caller_bounds(self) -> Self { - Self::new(List::empty(), self.reveal(), self.constness()) + Self::new(List::empty(), self.reveal()) } /// Creates a suitable environment in which to perform trait @@ -2682,19 +2625,6 @@ impl<'tcx> TyCtxt<'tcx> { matches!(self.trait_of_item(def_id), Some(trait_id) if self.has_attr(trait_id, sym::const_trait)) } - pub fn impl_trait_in_trait_parent_fn(self, mut def_id: DefId) -> DefId { - match self.opt_rpitit_info(def_id) { - Some(ImplTraitInTraitData::Trait { fn_def_id, .. }) - | Some(ImplTraitInTraitData::Impl { fn_def_id, .. }) => fn_def_id, - None => { - while let def_kind = self.def_kind(def_id) && def_kind != DefKind::AssocFn { - def_id = self.parent(def_id); - } - def_id - } - } - } - /// Returns the `DefId` of the item within which the `impl Trait` is declared. /// For type-alias-impl-trait this is the `type` alias. /// For impl-trait-in-assoc-type this is the assoc type. diff --git a/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs b/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs index 3c2c4483c73..2415d50b278 100644 --- a/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs +++ b/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs @@ -20,8 +20,8 @@ pub enum NormalizationError<'tcx> { impl<'tcx> NormalizationError<'tcx> { pub fn get_type_for_failure(&self) -> String { match self { - NormalizationError::Type(t) => format!("{}", t), - NormalizationError::Const(c) => format!("{}", c), + NormalizationError::Type(t) => format!("{t}"), + NormalizationError::Const(c) => format!("{c}"), } } } diff --git a/compiler/rustc_middle/src/ty/opaque_types.rs b/compiler/rustc_middle/src/ty/opaque_types.rs index 7ae8be2dab3..0ff5ac90304 100644 --- a/compiler/rustc_middle/src/ty/opaque_types.rs +++ b/compiler/rustc_middle/src/ty/opaque_types.rs @@ -124,7 +124,7 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReverseMapper<'tcx> { match self.map.get(&r.into()).map(|k| k.unpack()) { Some(GenericArgKind::Lifetime(r1)) => r1, - Some(u) => panic!("region mapped to unexpected kind: {:?}", u), + Some(u) => panic!("region mapped to unexpected kind: {u:?}"), None if self.do_not_error => self.tcx.lifetimes.re_static, None => { let e = self @@ -134,9 +134,8 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReverseMapper<'tcx> { .span_label( self.span, format!( - "lifetime `{}` is part of concrete type but not used in \ - parameter list of the `impl Trait` type alias", - r + "lifetime `{r}` is part of concrete type but not used in \ + parameter list of the `impl Trait` type alias" ), ) .emit(); @@ -169,7 +168,7 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReverseMapper<'tcx> { // Found it in the substitution list; replace with the parameter from the // opaque type. Some(GenericArgKind::Type(t1)) => t1, - Some(u) => panic!("type mapped to unexpected kind: {:?}", u), + Some(u) => panic!("type mapped to unexpected kind: {u:?}"), None => { debug!(?param, ?self.map); if !self.ignore_errors { @@ -178,9 +177,8 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReverseMapper<'tcx> { .struct_span_err( self.span, format!( - "type parameter `{}` is part of concrete type but not \ - used in parameter list for the `impl Trait` type alias", - ty + "type parameter `{ty}` is part of concrete type but not \ + used in parameter list for the `impl Trait` type alias" ), ) .emit(); @@ -205,7 +203,7 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReverseMapper<'tcx> { // Found it in the substitution list, replace with the parameter from the // opaque type. Some(GenericArgKind::Const(c1)) => c1, - Some(u) => panic!("const mapped to unexpected kind: {:?}", u), + Some(u) => panic!("const mapped to unexpected kind: {u:?}"), None => { let guar = self .tcx diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index e5633223464..f146f8aa8b4 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -17,6 +17,7 @@ use rustc_hir::LangItem; use rustc_session::config::TrimmedDefPaths; use rustc_session::cstore::{ExternCrate, ExternCrateSource}; use rustc_session::Limit; +use rustc_span::sym; use rustc_span::symbol::{kw, Ident, Symbol}; use rustc_span::FileNameDisplayPreference; use rustc_target::abi::Size; @@ -1497,7 +1498,7 @@ pub trait PrettyPrinter<'tcx>: let data = int.assert_bits(self.tcx().data_layout.pointer_size); self = self.typed_value( |mut this| { - write!(this, "0x{:x}", data)?; + write!(this, "0x{data:x}")?; Ok(this) }, |this| this.print_type(ty), @@ -1510,7 +1511,7 @@ pub trait PrettyPrinter<'tcx>: if int.size() == Size::ZERO { write!(this, "transmute(())")?; } else { - write!(this, "transmute(0x{:x})", int)?; + write!(this, "transmute(0x{int:x})")?; } Ok(this) }; @@ -2017,11 +2018,37 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { ) -> Result<Self::Path, Self::Error> { self = print_prefix(self)?; - if args.first().is_some() { + let tcx = self.tcx; + + let args = args.iter().copied(); + + let args: Vec<_> = if !tcx.sess.verbose() { + // skip host param as those are printed as `~const` + args.filter(|arg| match arg.unpack() { + // FIXME(effects) there should be a better way than just matching the name + GenericArgKind::Const(c) + if tcx.features().effects + && matches!( + c.kind(), + ty::ConstKind::Param(ty::ParamConst { name: sym::host, .. }) + ) => + { + false + } + _ => true, + }) + .collect() + } else { + // If -Zverbose is passed, we should print the host parameter instead + // of eating it. + args.collect() + }; + + if !args.is_empty() { if self.in_value { write!(self, "::")?; } - self.generic_delimiters(|cx| cx.comma_sep(args.iter().cloned())) + self.generic_delimiters(|cx| cx.comma_sep(args.into_iter())) } else { Ok(self) } @@ -2348,10 +2375,10 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { } else { cont }; - let _ = write!(cx, "{}", w); + let _ = write!(cx, "{w}"); }; let do_continue = |cx: &mut Self, cont: Symbol| { - let _ = write!(cx, "{}", cont); + let _ = write!(cx, "{cont}"); }; define_scoped_cx!(self); @@ -2387,7 +2414,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { let (new_value, map) = if self.should_print_verbose() { for var in value.bound_vars().iter() { start_or_continue(&mut self, "for<", ", "); - write!(self, "{:?}", var)?; + write!(self, "{var:?}")?; } start_or_continue(&mut self, "", "> "); (value.clone().skip_binder(), BTreeMap::default()) diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 9d380a58d9f..2a6044cad37 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -73,9 +73,9 @@ impl fmt::Debug for ty::BoundRegionKind { ty::BrAnon(span) => write!(f, "BrAnon({span:?})"), ty::BrNamed(did, name) => { if did.is_crate_root() { - write!(f, "BrNamed({})", name) + write!(f, "BrNamed({name})") } else { - write!(f, "BrNamed({:?}, {})", did, name) + write!(f, "BrNamed({did:?}, {name})") } } ty::BrEnv => write!(f, "BrEnv"), @@ -205,7 +205,7 @@ impl<'tcx> fmt::Debug for ty::ClauseKind<'tcx> { ty::ClauseKind::RegionOutlives(ref pair) => pair.fmt(f), ty::ClauseKind::TypeOutlives(ref pair) => pair.fmt(f), ty::ClauseKind::Projection(ref pair) => pair.fmt(f), - ty::ClauseKind::WellFormed(ref data) => write!(f, "WellFormed({:?})", data), + ty::ClauseKind::WellFormed(ref data) => write!(f, "WellFormed({data:?})"), ty::ClauseKind::ConstEvaluatable(ct) => { write!(f, "ConstEvaluatable({ct:?})") } @@ -220,12 +220,12 @@ impl<'tcx> fmt::Debug for ty::PredicateKind<'tcx> { ty::PredicateKind::Subtype(ref pair) => pair.fmt(f), ty::PredicateKind::Coerce(ref pair) => pair.fmt(f), ty::PredicateKind::ObjectSafe(trait_def_id) => { - write!(f, "ObjectSafe({:?})", trait_def_id) + write!(f, "ObjectSafe({trait_def_id:?})") } ty::PredicateKind::ClosureKind(closure_def_id, closure_args, kind) => { - write!(f, "ClosureKind({:?}, {:?}, {:?})", closure_def_id, closure_args, kind) + write!(f, "ClosureKind({closure_def_id:?}, {closure_args:?}, {kind:?})") } - ty::PredicateKind::ConstEquate(c1, c2) => write!(f, "ConstEquate({:?}, {:?})", c1, c2), + ty::PredicateKind::ConstEquate(c1, c2) => write!(f, "ConstEquate({c1:?}, {c2:?})"), ty::PredicateKind::Ambiguous => write!(f, "Ambiguous"), ty::PredicateKind::AliasRelate(t1, t2, dir) => { write!(f, "AliasRelate({t1:?}, {dir:?}, {t2:?})") @@ -602,7 +602,7 @@ impl<'a, 'tcx> Lift<'tcx> for ty::ParamEnv<'a> { type Lifted = ty::ParamEnv<'tcx>; fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> { tcx.lift(self.caller_bounds()) - .map(|caller_bounds| ty::ParamEnv::new(caller_bounds, self.reveal(), self.constness())) + .map(|caller_bounds| ty::ParamEnv::new(caller_bounds, self.reveal())) } } diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index f9c1ca9a8b1..3e023ccdead 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -2670,11 +2670,6 @@ impl<'tcx> Ty<'tcx> { variant_index: VariantIdx, ) -> Option<Discr<'tcx>> { match self.kind() { - TyKind::Adt(adt, _) if adt.variants().is_empty() => { - // This can actually happen during CTFE, see - // https://github.com/rust-lang/rust/issues/89765. - None - } TyKind::Adt(adt, _) if adt.is_enum() => { Some(adt.discriminant_for_variant(tcx, variant_index)) } diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 553b76cad4e..90ecc8aa857 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -57,7 +57,7 @@ impl<'tcx> fmt::Display for Discr<'tcx> { let x = self.val; // sign extend the raw representation to be an i128 let x = size.sign_extend(x) as i128; - write!(fmt, "{}", x) + write!(fmt, "{x}") } _ => write!(fmt, "{}", self.val), } diff --git a/compiler/rustc_middle/src/ty/vtable.rs b/compiler/rustc_middle/src/ty/vtable.rs index 443791d0af4..97402caa001 100644 --- a/compiler/rustc_middle/src/ty/vtable.rs +++ b/compiler/rustc_middle/src/ty/vtable.rs @@ -29,8 +29,8 @@ impl<'tcx> fmt::Debug for VtblEntry<'tcx> { VtblEntry::MetadataSize => write!(f, "MetadataSize"), VtblEntry::MetadataAlign => write!(f, "MetadataAlign"), VtblEntry::Vacant => write!(f, "Vacant"), - VtblEntry::Method(instance) => write!(f, "Method({})", instance), - VtblEntry::TraitVPtr(trait_ref) => write!(f, "TraitVPtr({})", trait_ref), + VtblEntry::Method(instance) => write!(f, "Method({instance})"), + VtblEntry::TraitVPtr(trait_ref) => write!(f, "TraitVPtr({trait_ref})"), } } } diff --git a/compiler/rustc_middle/src/util/bug.rs b/compiler/rustc_middle/src/util/bug.rs index 43ee0343f5a..634ed5ec54b 100644 --- a/compiler/rustc_middle/src/util/bug.rs +++ b/compiler/rustc_middle/src/util/bug.rs @@ -29,7 +29,7 @@ fn opt_span_bug_fmt<S: Into<MultiSpan>>( location: &Location<'_>, ) -> ! { tls::with_opt(move |tcx| { - let msg = format!("{}: {}", location, args); + let msg = format!("{location}: {args}"); match (tcx, span) { (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, msg), (Some(tcx), None) => tcx.sess.diagnostic().bug(msg), diff --git a/compiler/rustc_middle/src/util/common.rs b/compiler/rustc_middle/src/util/common.rs index 08977049db0..df101a2f6e4 100644 --- a/compiler/rustc_middle/src/util/common.rs +++ b/compiler/rustc_middle/src/util/common.rs @@ -17,7 +17,7 @@ pub fn to_readable_str(mut val: usize) -> String { groups.push(group.to_string()); break; } else { - groups.push(format!("{:03}", group)); + groups.push(format!("{group:03}")); } } |
