diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index 97b0c0f12fc10..2f598333efd75 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -995,7 +995,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { match rvalue { Rvalue::Aggregate(ak, ops) => self.check_aggregate_rvalue(rvalue, ak, ops, location), - Rvalue::Repeat(operand, len) => { + Rvalue::Repeat(operand, _) => { let array_ty = rvalue.ty(self.body.local_decls(), tcx); self.prove_clause( ty::ClauseKind::WellFormed(array_ty.into()), @@ -1003,31 +1003,25 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ConstraintCategory::Boring, ); - // If the length cannot be evaluated we must assume that the length can be larger - // than 1. - // If the length is larger than 1, the repeat expression will need to copy the - // element, so we require the `Copy` trait. - if len.try_to_target_usize(tcx).is_none_or(|len| len > 1) { - match operand { - Operand::Copy(..) | Operand::Constant(..) | Operand::RuntimeChecks(_) => { - // These are always okay: direct use of a const, or a value that can - // evidently be copied. - } - Operand::Move(place) => { - // Make sure that repeated elements implement `Copy`. - let ty = place.ty(self.body, tcx).ty; - let trait_ref = ty::TraitRef::new( - tcx, - tcx.require_lang_item(LangItem::Copy, span), - [ty], - ); + match operand { + Operand::Copy(..) | Operand::Constant(..) | Operand::RuntimeChecks(_) => { + // These are always okay: direct use of a const, or a value that can + // evidently be copied. + } + Operand::Move(place) => { + // Make sure that repeated elements implement `Copy`. + let ty = place.ty(self.body, tcx).ty; + let trait_ref = ty::TraitRef::new( + tcx, + tcx.require_lang_item(LangItem::Copy, span), + [ty], + ); - self.prove_trait_ref( - trait_ref, - Locations::Single(location), - ConstraintCategory::CopyBound, - ); - } + self.prove_trait_ref( + trait_ref, + Locations::Single(location), + ConstraintCategory::CopyBound, + ); } } } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 779b049063b8f..b9065542ca7b3 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2350,93 +2350,6 @@ impl Expr<'_> { } } - /// Returns true if mir building would consider this expression a constant for the purposes of - /// lowering `[CONST; 0]` as `[]`. - pub fn is_constant_for_zero_repeat(&self) -> bool { - // NB: This needs to be kept in sync with `rustc_mir_build::builder::expr::category::Category::of` - - match self.kind { - ExprKind::ConstBlock(_) | ExprKind::Lit(_) => true, - ExprKind::Cast(inner, _) | ExprKind::Type(inner, _) => { - inner.is_constant_for_zero_repeat() - } - - ExprKind::Path(qpath) => { - match qpath { - QPath::Resolved(_, Path { res: Res::Def(def_kind, _), .. }) => match def_kind { - DefKind::Const | DefKind::ConstParam | DefKind::AssocConst => true, - - DefKind::Mod - | DefKind::Struct - | DefKind::Union - | DefKind::Enum - | DefKind::Variant - | DefKind::Trait - | DefKind::TyAlias - | DefKind::ForeignTy - | DefKind::TraitAlias - | DefKind::AssocTy - | DefKind::TyParam - | DefKind::Fn - | DefKind::Static { .. } - | DefKind::Ctor(..) - | DefKind::AssocFn - | DefKind::Macro(_) - | DefKind::ExternCrate - | DefKind::Use - | DefKind::ForeignMod - | DefKind::AnonConst - | DefKind::OpaqueTy - | DefKind::Field - | DefKind::LifetimeParam - | DefKind::GlobalAsm - | DefKind::Impl { .. } - | DefKind::Closure - | DefKind::SyntheticCoroutineBody - | DefKind::TestBinderConstraints => false, - }, - - // A path that resolved to something other than a definition cannot be a const - QPath::Resolved(..) => false, - - // A type relative expression can only be a const - QPath::TypeRelative(..) => true, - } - } - - ExprKind::Array(_) - | ExprKind::Call(..) - | ExprKind::MethodCall(..) - | ExprKind::Use(..) - | ExprKind::Tup(_) - | ExprKind::Binary(..) - | ExprKind::Unary(..) - | ExprKind::DropTemps(_) - | ExprKind::Let(_) - | ExprKind::If(..) - | ExprKind::Loop(..) - | ExprKind::Match(..) - | ExprKind::Closure(_) - | ExprKind::Block(..) - | ExprKind::Assign(..) - | ExprKind::AssignOp(..) - | ExprKind::Field(..) - | ExprKind::Index(..) - | ExprKind::AddrOf(..) - | ExprKind::Break(..) - | ExprKind::Continue(_) - | ExprKind::Ret(_) - | ExprKind::Become(_) - | ExprKind::InlineAsm(_) - | ExprKind::OffsetOf(..) - | ExprKind::Struct(..) - | ExprKind::Repeat(..) - | ExprKind::Yield(..) - | ExprKind::UnsafeBinderCast(..) - | ExprKind::Err(_) => false, - } - } - /// If this is a desugared range expression, /// returns the span of the range without desugaring context. pub fn range_span(&self) -> Option { diff --git a/compiler/rustc_hir_analysis/src/check/region.rs b/compiler/rustc_hir_analysis/src/check/region.rs index 96acfd2f97177..4c325fad36dcc 100644 --- a/compiler/rustc_hir_analysis/src/check/region.rs +++ b/compiler/rustc_hir_analysis/src/check/region.rs @@ -633,6 +633,9 @@ fn resolve_local<'tcx>( record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id); } } + hir::ExprKind::Repeat(subexpr, _) => { + record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id); + } hir::ExprKind::Cast(subexpr, _) => { record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id) } diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 7356f8f94615b..def4f1f969c90 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -28,10 +28,10 @@ use rustc_infer::traits::WellFormedLoc; use rustc_infer::traits::query::NoSolution; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase}; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::{self, AdtKind, ConstKind, GenericArgs, Ty, TypeVisitableExt, Unnormalized}; +use rustc_middle::ty::{self, AdtKind, GenericArgs, Ty, TypeVisitableExt, Unnormalized}; use rustc_session::diagnostics::feature_err; use rustc_span::hygiene::DesugaringKind; -use rustc_span::{Ident, Span, Spanned, Symbol, bug, kw, span_bug, sym}; +use rustc_span::{Ident, Span, Spanned, Symbol, kw, span_bug, sym}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{self, ObligationCauseCode, ObligationCtxt}; use tracing::{debug, instrument, trace}; @@ -1703,8 +1703,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => None, }; - let old_diverges = self.diverges.get(); - let (element_ty, t) = match uty { Some(uty) => { self.check_expr_coercible_to_type(element, uty, None); @@ -1717,39 +1715,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } }; - // FIXME: remove this workaround for an unsoundness (#165323) once it's no longer needed. - // - // MIR building lowers `[CONST; 0]` to `[]`, making `CONST` not evaluated. - // - // This is a problem, because it means if `CONST` is `const { panic!() }`, the side effect - // of panic / failing compilation never happens. In such cases we need to ignore divergence - // from the `CONST`, as otherwise we can end up executing code that was assumed unreachable. - let count_is_zero = match count.kind() { - // This is the exact check that mir building does - ConstKind::Value(v) => v.try_to_target_usize(tcx) == Some(0), - - // An infer const can get inferred to 0. - // - // We could check the expectation here to do ad-hoc inference, but that feels quite - // error prone and annoying. - ConstKind::Infer(_) => true, - - // While const generic params can be substituted with 0, mir building specifically - // checks for value 0 before monomorphization, so they (alongside aliases, etc) cannot - // trigger the bug. - ConstKind::Param(_) - | ConstKind::Placeholder(_) - | ConstKind::Alias(..) - | ConstKind::Error(_) - | ConstKind::Expr(_) => false, - - ConstKind::Bound(..) => bug!(), - }; - - if count_is_zero && element.is_constant_for_zero_repeat() { - self.diverges.set(old_diverges); - } - if let Err(guar) = element_ty.error_reported() { return Ty::new_error(tcx, guar); } diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index 7db6a7390d539..67463ac66065f 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -1370,7 +1370,11 @@ pub enum Rvalue<'tcx> { /// Creates an array where each element is the value of the operand. /// - /// Corresponds to source code like `[x; 32]`. + /// Corresponds to source code like `[x; 32]` or `[x; N]`. + /// + /// Note: `[x; 0]` and `[x; 1]` don't compile down to this; + /// instead, they become [`Self::Aggregate`] + /// (preceded by [`StatementKind::PlaceMention`] for the former). Repeat(Operand<'tcx>, ty::Const<'tcx>), /// Creates a reference of the indicated kind to the place. diff --git a/compiler/rustc_mir_build/src/builder/expr/as_constant.rs b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs index 4622870fee4d5..8702ad1c24933 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_constant.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs @@ -20,14 +20,22 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// Compile `expr`, yielding a compile-time constant. Assumes that /// `expr` is a valid compile-time constant! pub(crate) fn as_constant(&mut self, expr: &Expr<'tcx>) -> ConstOperand<'tcx> { + self.try_as_constant(expr).unwrap_or_else(|| { + span_bug!(expr.span, "expression is not a valid constant {:?}", expr.kind) + }) + } + + /// Compile `expr`, yielding a compile-time constant. + /// Returns `None` if `expr` is not a valid compile-time constant. + pub(crate) fn try_as_constant(&mut self, expr: &Expr<'tcx>) -> Option> { let this = self; // See "LET_THIS_SELF". let tcx = this.tcx; let Expr { ty, temp_scope_id: _, span, ref kind } = *expr; match kind { ExprKind::Scope { region_scope: _, hir_id: _, value } => { - this.as_constant(&this.thir[*value]) + this.try_as_constant(&this.thir[*value]) } - _ => as_constant_inner( + _ => try_as_constant_inner( expr, |user_ty| { Some(this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation { @@ -47,6 +55,16 @@ pub(crate) fn as_constant_inner<'tcx>( push_cuta: impl FnMut(&Box>) -> Option, tcx: TyCtxt<'tcx>, ) -> ConstOperand<'tcx> { + try_as_constant_inner(expr, push_cuta, tcx).unwrap_or_else(|| { + span_bug!(expr.span, "expression is not a valid constant {:?}", expr.kind) + }) +} + +fn try_as_constant_inner<'tcx>( + expr: &Expr<'tcx>, + push_cuta: impl FnMut(&Box>) -> Option, + tcx: TyCtxt<'tcx>, +) -> Option> { let Expr { ty, temp_scope_id: _, span, ref kind } = *expr; match *kind { @@ -54,47 +72,47 @@ pub(crate) fn as_constant_inner<'tcx>( let const_ = lit_to_mir_constant(tcx, LitToConstInput { lit: lit.node, ty: Some(ty), neg }); - ConstOperand { span, user_ty: None, const_ } + Some(ConstOperand { span, user_ty: None, const_ }) } ExprKind::NonHirLiteral { lit, ref user_ty } => { let user_ty = user_ty.as_ref().and_then(push_cuta); let const_ = Const::Val(ConstValue::Scalar(Scalar::Int(lit)), ty); - ConstOperand { span, user_ty, const_ } + Some(ConstOperand { span, user_ty, const_ }) } ExprKind::ZstLiteral { ref user_ty } => { let user_ty = user_ty.as_ref().and_then(push_cuta); let const_ = Const::Val(ConstValue::ZeroSized, ty); - ConstOperand { span, user_ty, const_ } + Some(ConstOperand { span, user_ty, const_ }) } ExprKind::NamedConst { def_id, args, ref user_ty } => { let user_ty = user_ty.as_ref().and_then(push_cuta); let uneval = mir::UnevaluatedConst::new(def_id, args); let const_ = Const::Unevaluated(uneval, ty); - ConstOperand { user_ty, span, const_ } + Some(ConstOperand { user_ty, span, const_ }) } ExprKind::ConstParam { param, def_id: _ } => { let const_param = ty::Const::new_param(tcx, param); let const_ = Const::Ty(expr.ty, const_param); - ConstOperand { user_ty: None, span, const_ } + Some(ConstOperand { user_ty: None, span, const_ }) } ExprKind::ConstBlock { did: def_id, args } => { let uneval = mir::UnevaluatedConst::new(def_id, args); let const_ = Const::Unevaluated(uneval, ty); - ConstOperand { user_ty: None, span, const_ } + Some(ConstOperand { user_ty: None, span, const_ }) } ExprKind::StaticRef { alloc_id, ty, .. } => { let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx)); let const_ = Const::Val(const_val, ty); - ConstOperand { span, user_ty: None, const_ } + Some(ConstOperand { span, user_ty: None, const_ }) } - _ => span_bug!(span, "expression is not a valid constant {:?}", kind), + _ => None, } } diff --git a/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs index 9e8293f5a35b2..9e027043f9f58 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs @@ -6,11 +6,10 @@ use rustc_middle::middle::region::{self, TempLifetime}; use rustc_middle::mir::interpret::Scalar; use rustc_middle::mir::*; use rustc_middle::thir::*; -use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::cast::{CastTy, mir_cast_kind}; use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::{self, Ty, UpvarArgs}; -use rustc_span::{DUMMY_SP, Span, Spanned, bug}; +use rustc_span::{Span, Spanned, bug}; use tracing::debug; use crate::builder::expr::as_place::PlaceBase; @@ -57,19 +56,139 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { }) } ExprKind::Repeat { value, count } => { - if Some(0) == count.try_to_target_usize(this.tcx) { - this.build_zero_repeat(block, value, scope, source_info) - } else { - let value_operand = unpack!( - block = this.as_operand( + let value_expr = &this.thir[value]; + let elem_ty = value_expr.ty; + let value_operand = unpack!( + block = + this.as_operand(block, scope, value, LocalInfo::Boring, NeedsTemporary::No) + ); + match count.try_to_target_usize(this.tcx) { + Some(0) => { + let needs_drop = value_expr.ty.needs_drop(this.tcx, this.typing_env()); + + let place_to_drop = match value_operand { + Operand::Move(place) if needs_drop => { + this.record_operands_moved(&[Spanned { + node: value_operand, + span: expr_span, + }]); + Some(place) + } + Operand::Constant(const_operand) => { + let const_temp = this.temp(elem_ty, expr_span); + + // Do this even if not `needs_drop` + // to ensure the const is mentioned in MIR + this.cfg.push_assign_constant( + block, + source_info, + const_temp, + *const_operand, + ); + if needs_drop { Some(const_temp) } else { None } + } + Operand::Move(_) | Operand::Copy(_) | Operand::RuntimeChecks(_) => None, + }; + + if let Some(to_drop) = place_to_drop { + let success = this.cfg.start_new_block(); + this.cfg.terminate( + block, + source_info, + TerminatorKind::Drop { + place: to_drop, + target: success, + unwind: UnwindAction::Continue, + replace: false, + drop: None, + }, + ); + this.diverge_from(block); + block = success; + } + + block.and(Rvalue::Aggregate( + Box::new(AggregateKind::Array(elem_ty)), + IndexVec::new(), + )) + } + + Some(1) => { + let fields = IndexVec::from_elem_n(value_operand, 1); + block + .and(Rvalue::Aggregate(Box::new(AggregateKind::Array(elem_ty)), fields)) + } + + None if value_expr.ty.needs_drop(this.tcx, this.typing_env()) + && let Operand::Constant(ref constant) = value_operand => + { + // conditionally drop the constant if `count` is 0 + + let is_zero_temp = this.temp(this.tcx.types.bool, expr_span); + + let conditional_drop_block = this.cfg.start_new_block(); + let post_conditional_drop_block = this.cfg.start_new_block(); + + // check if `count` is 0 + this.cfg.push_assign( block, - scope, - value, - LocalInfo::Boring, - NeedsTemporary::No - ) - ); - block.and(Rvalue::Repeat(value_operand, count)) + source_info, + is_zero_temp, + Rvalue::BinaryOp( + BinOp::Eq, + Box::new(( + Operand::Constant(Box::new(ConstOperand { + span: expr_span, + user_ty: None, + const_: Const::Ty(this.tcx.types.usize, count), + })), + Operand::Constant(Box::new(ConstOperand { + span: expr_span, + user_ty: None, + const_: Const::from_usize(this.tcx, 0), + })), + )), + ), + ); + + // drop the const if it is + let const_temp = this.temp(elem_ty, expr_span); + this.cfg.push_assign_constant( + conditional_drop_block, + source_info, + const_temp, + (**constant).clone(), + ); + + this.cfg.terminate( + conditional_drop_block, + source_info, + TerminatorKind::Drop { + place: const_temp, + target: post_conditional_drop_block, + unwind: UnwindAction::Continue, + replace: false, + drop: None, + }, + ); + this.diverge_from(conditional_drop_block); + + this.cfg.terminate( + block, + source_info, + TerminatorKind::if_( + Operand::Move(is_zero_temp), + conditional_drop_block, + post_conditional_drop_block, + ), + ); + + block = post_conditional_drop_block; + + block.and(Rvalue::Repeat(value_operand, count)) + } + + _ => block.and(Rvalue::Repeat(value_operand, count)), } } ExprKind::Binary { op, lhs, rhs } => { @@ -584,65 +703,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { block.and(rvalue) } - /// Recursively inspect a THIR expression and probe through unsizing - /// operations that can be const-folded today. - fn check_constness(&self, mut kind: &'a ExprKind<'tcx>) -> bool { - loop { - debug!(?kind, "check_constness"); - match kind { - &ExprKind::ValueTypeAscription { source: eid, user_ty: _, user_ty_span: _ } - | &ExprKind::ValueExpr { source: eid } - | &ExprKind::PointerCoercion { - cast: PointerCoercion::Unsize, - source: eid, - is_from_as_cast: _, - } - | &ExprKind::Scope { region_scope: _, hir_id: _, value: eid } => { - kind = &self.thir[eid].kind - } - _ => return matches!(Category::of(&kind), Some(Category::Constant)), - } - } - } - - fn build_zero_repeat( - &mut self, - mut block: BasicBlock, - value: ExprId, - scope: TempLifetime, - outer_source_info: SourceInfo, - ) -> BlockAnd> { - let this = self; // See "LET_THIS_SELF". - let value_expr = &this.thir[value]; - let elem_ty = value_expr.ty; - if this.check_constness(&value_expr.kind) { - // Repeating a const does nothing - } else { - // For a non-const, we may need to generate an appropriate `Drop` - let value_operand = unpack!( - block = this.as_operand(block, scope, value, LocalInfo::Boring, NeedsTemporary::No) - ); - if let Operand::Move(to_drop) = value_operand { - let success = this.cfg.start_new_block(); - this.cfg.terminate( - block, - outer_source_info, - TerminatorKind::Drop { - place: to_drop, - target: success, - unwind: UnwindAction::Continue, - replace: false, - drop: None, - }, - ); - this.diverge_from(block); - block = success; - } - this.record_operands_moved(&[Spanned { node: value_operand, span: DUMMY_SP }]); - } - block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(elem_ty)), IndexVec::new())) - } - fn limit_capture_mutability( &mut self, upvar_span: Span, diff --git a/tests/mir-opt/coroutine/async_fn.hello_world-{closure#0}.StateTransform.diff b/tests/mir-opt/coroutine/async_fn.hello_world-{closure#0}.StateTransform.diff index 5707f3dcd4439..d105006730cde 100644 --- a/tests/mir-opt/coroutine/async_fn.hello_world-{closure#0}.StateTransform.diff +++ b/tests/mir-opt/coroutine/async_fn.hello_world-{closure#0}.StateTransform.diff @@ -83,7 +83,7 @@ bb0: { - StorageLive(_3); -- _3 = [const 0_u8; 1]; +- _3 = [const 0_u8]; - StorageLive(_4); - StorageLive(_5); - StorageLive(_6); @@ -103,10 +103,10 @@ StorageDead(_6); - _4 = &(*_5); - StorageLive(_8); -- _8 = [const 0_u8; 1]; +- _8 = [const 0_u8]; + (((*_35) as variant#3).1: &[u8]) = &(*_5); + nop; -+ (((*_35) as variant#3).2: [u8; 1]) = [const 0_u8; 1]; ++ (((*_35) as variant#3).2: [u8; 1]) = [const 0_u8]; StorageLive(_9); StorageLive(_10); StorageLive(_11); @@ -441,7 +441,7 @@ + + bb32: { + nop; -+ (((*_35) as variant#3).0: [u8; 1]) = [const 0_u8; 1]; ++ (((*_35) as variant#3).0: [u8; 1]) = [const 0_u8]; + nop; + StorageLive(_5); + StorageLive(_6); diff --git a/tests/mir-opt/instsimplify/simplify_repeat.repeat_once_to_aggregate.InstSimplify-after-simplifycfg.diff b/tests/mir-opt/instsimplify/simplify_repeat.repeat_once_to_aggregate.InstSimplify-after-simplifycfg.diff index 6c1b9abc5d7c7..5b6da03573a04 100644 --- a/tests/mir-opt/instsimplify/simplify_repeat.repeat_once_to_aggregate.InstSimplify-after-simplifycfg.diff +++ b/tests/mir-opt/instsimplify/simplify_repeat.repeat_once_to_aggregate.InstSimplify-after-simplifycfg.diff @@ -15,13 +15,11 @@ StorageLive(_2); StorageLive(_3); _3 = copy _1; -- _2 = [move _3; 1]; -+ _2 = [move _3]; + _2 = [move _3]; StorageDead(_3); StorageLive(_4); _4 = copy _1; -- _0 = [move _4; 1]; -+ _0 = [move _4]; + _0 = [move _4]; StorageDead(_4); StorageDead(_2); return; diff --git a/tests/ui/coercion/no_local_for_coerced_const-issue-143671.rs b/tests/ui/coercion/no_local_for_coerced_const-issue-143671.rs index 38479d9070b8d..416433a448f6b 100644 --- a/tests/ui/coercion/no_local_for_coerced_const-issue-143671.rs +++ b/tests/ui/coercion/no_local_for_coerced_const-issue-143671.rs @@ -1,5 +1,3 @@ -//@ run-pass - #![feature(unsize)] #![feature(coerce_unsized)] @@ -35,6 +33,7 @@ fn main() { fn coercion_on_weak_in_const() { const X: Weak = Weak::new(); const Y: [Weak; 0] = [X; 0]; + //~^ ERROR destructor of `std::rc::Weak` cannot be evaluated at compile-time let _ = Y; } diff --git a/tests/ui/coercion/no_local_for_coerced_const-issue-143671.stderr b/tests/ui/coercion/no_local_for_coerced_const-issue-143671.stderr new file mode 100644 index 0000000000000..a62ce2144f969 --- /dev/null +++ b/tests/ui/coercion/no_local_for_coerced_const-issue-143671.stderr @@ -0,0 +1,12 @@ +error[E0493]: destructor of `std::rc::Weak` cannot be evaluated at compile-time + --> $DIR/no_local_for_coerced_const-issue-143671.rs:35:37 + | +LL | const Y: [Weak; 0] = [X; 0]; + | -^---- + | || + | |the destructor for this type cannot be evaluated in constants + | value is dropped here + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0493`. diff --git a/tests/ui/consts/const-blocks/const-repeat.rs b/tests/ui/consts/const-blocks/const-repeat.rs index 89dfbc3cbad29..7a60ee18651e2 100644 --- a/tests/ui/consts/const-blocks/const-repeat.rs +++ b/tests/ui/consts/const-blocks/const-repeat.rs @@ -1,5 +1,7 @@ //@ run-pass +use std::sync::atomic::{AtomicUsize, Ordering}; + // Repeating a *constant* of non-Copy type (not just a constant expression) is already stable. const EMPTY: Vec = Vec::new(); @@ -8,20 +10,24 @@ pub fn bar() -> [Vec; 2] { [EMPTY; 2] } -struct Bomb; +static NUM_DROPS: AtomicUsize = AtomicUsize::new(0); + +struct NoisyDrop; -impl Drop for Bomb { +impl Drop for NoisyDrop { fn drop(&mut self) { - panic!("BOOM!"); + NUM_DROPS.fetch_add(1, Ordering::Relaxed); } } -const BOOM: Bomb = Bomb; +const NOISY: NoisyDrop = NoisyDrop; fn main() { let _x = bar(); - // Make sure the destructor does not get called for empty arrays. `[CONST; N]` should - // instantiate (and then later drop) the const exactly `N` times. - let _x = [BOOM; 0]; + // Make sure the destructor gets called even for empty arrays. + // `[CONST; N]` should instantiate the const. + let _x = [NOISY; 0]; + + assert_eq!(NUM_DROPS.load(Ordering::Relaxed), 1); } diff --git a/tests/ui/consts/promote-not.stderr b/tests/ui/consts/promote-not.stderr index ebe2a963a74b1..e433e7b0181f1 100644 --- a/tests/ui/consts/promote-not.stderr +++ b/tests/ui/consts/promote-not.stderr @@ -272,10 +272,12 @@ error[E0716]: temporary value dropped while borrowed --> $DIR/promote-not.rs:90:31 | LL | let _val: &'static _ = &[&TEST_DROP; 1]; - | ---------- ^^^^^^^^^ - temporary value is freed at the end of this statement - | | | - | | creates a temporary value which is freed while still in use + | ---------- ^^^^^^^^^ creates a temporary value which is freed while still in use + | | | type annotation requires that borrow lasts for `'static` +... +LL | } + | - temporary value is freed at the end of this statement error[E0716]: temporary value dropped while borrowed --> $DIR/promote-not.rs:99:26 diff --git a/tests/ui/drop/repeat-drop.rs b/tests/ui/drop/repeat-drop.rs index 1b10e6e553b80..922723a85c9f7 100644 --- a/tests/ui/drop/repeat-drop.rs +++ b/tests/ui/drop/repeat-drop.rs @@ -2,7 +2,6 @@ //@ needs-unwind #![allow(dropping_references, dropping_copy_types)] - // FIXME(static_mut_refs): use raw pointers instead of references #![allow(static_mut_refs)] @@ -58,9 +57,16 @@ const DROP_CHECKER: DropChecker = DropChecker(1); fn const_zero() { unsafe { CHECK = 0 }; let v: [DropChecker; 0] = [DROP_CHECKER; 0]; - check_drops!(0); + check_drops!(1); std::mem::drop(v); - check_drops!(0); + check_drops!(1); + + // test lifetime extension + unsafe { CHECK = 0 }; + let v: ([DropChecker; 0], ()) = ([DROP_CHECKER; 0], check_drops!(1)); + check_drops!(1); + std::mem::drop(v); + check_drops!(1); } fn const_one() { @@ -74,9 +80,16 @@ fn const_one() { fn const_generic_zero() { unsafe { CHECK = 0 }; let v: [DropChecker; N] = [DROP_CHECKER; N]; - check_drops!(0); + check_drops!(1); std::mem::drop(v); - check_drops!(0); + check_drops!(1); + + // test lifetime extension + unsafe { CHECK = 0 }; + let v: ([DropChecker; N], ()) = ([DROP_CHECKER; N], check_drops!(1)); + check_drops!(1); + std::mem::drop(v); + check_drops!(1); } fn const_generic_one() { @@ -104,7 +117,7 @@ fn on_unwind() { std::panic::catch_unwind(|| { let panic = DropPanic; let _local = DropChecker(2); - let _v = (DropChecker(1), [panic; 0]); + let _v = (DropChecker(1), [{ panic }; 0]); std::process::abort(); }) .unwrap_err(); diff --git a/tests/ui/repeat-expr/extending.rs b/tests/ui/repeat-expr/extending.rs new file mode 100644 index 0000000000000..88326647d2093 --- /dev/null +++ b/tests/ui/repeat-expr/extending.rs @@ -0,0 +1,14 @@ +//@ run-pass +//! Test that array repeat expressions are extending + +#![allow(path_statements)] + +fn temp() {} + +fn main() { + let _extended = [&temp(); 1]; + _extended; + + let _extended = [&temp(); 17]; + _extended; +} diff --git a/tests/ui/repeat-expr/zero_diverging_consts.rs b/tests/ui/repeat-expr/zero_diverging_consts.rs index 91881a3b94d67..0838c7913dd20 100644 --- a/tests/ui/repeat-expr/zero_diverging_consts.rs +++ b/tests/ui/repeat-expr/zero_diverging_consts.rs @@ -1,10 +1,12 @@ +//@ build-fail + // Check that repeating a diverging constant 0 times doesn't lead to unsoundness. // // Issue: fn ex_nihilo() -> u32 { - //~^ error: mismatched types [const { panic!() } as !; 0]; + //~^ ERROR evaluation panicked: explicit panic } fn main() { diff --git a/tests/ui/repeat-expr/zero_diverging_consts.stderr b/tests/ui/repeat-expr/zero_diverging_consts.stderr index 27e48e5d656b2..21aa2d752c3a7 100644 --- a/tests/ui/repeat-expr/zero_diverging_consts.stderr +++ b/tests/ui/repeat-expr/zero_diverging_consts.stderr @@ -1,11 +1,24 @@ -error[E0308]: mismatched types - --> $DIR/zero_diverging_consts.rs:5:19 +error[E0080]: evaluation panicked: explicit panic + --> $DIR/zero_diverging_consts.rs:8:14 | LL | fn ex_nihilo() -> u32 { - | --------- ^^^ expected `u32`, found `()` - | | - | implicitly returns `()` as its body has no tail or `return` expression +LL | [const { panic!() } as !; 0]; + | ^^^^^^^^ evaluation of `ex_nihilo::{constant#0}` failed here + +note: erroneous constant encountered + --> $DIR/zero_diverging_consts.rs:8:6 + | +LL | [const { panic!() } as !; 0]; + | ^^^^^^^^^^^^^^^^^^ + +note: erroneous constant encountered + --> $DIR/zero_diverging_consts.rs:8:6 + | +LL | [const { panic!() } as !; 0]; + | ^^^^^^^^^^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: aborting due to 1 previous error -For more information about this error, try `rustc --explain E0308`. +For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/repeat-expr/zero_diverging_consts_runnable.rs b/tests/ui/repeat-expr/zero_diverging_consts_runnable.rs deleted file mode 100644 index 9fa26608b58a0..0000000000000 --- a/tests/ui/repeat-expr/zero_diverging_consts_runnable.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Check that repeating a diverging constant 0 times doesn't lead to unsoundness. -// -// Issue: -// -//@ run-fail -//@ check-run-results -//@ exec-env:RUST_BACKTRACE=0 - -fn get(v: &[u32], i: usize) -> u32 { - if i >= v.len() { - let _: [!; 0] = [const { panic!() }; 0]; - } - v[i] -} - -fn main() { - let v = vec![1, 2, 3]; - let i = std::hint::black_box(4); // 4, hidden from the optimizer - println!("v[{i}] = {}", get(&v, i)); -} diff --git a/tests/ui/repeat-expr/zero_diverging_consts_runnable.run.stderr b/tests/ui/repeat-expr/zero_diverging_consts_runnable.run.stderr deleted file mode 100644 index b2de85342f2c6..0000000000000 --- a/tests/ui/repeat-expr/zero_diverging_consts_runnable.run.stderr +++ /dev/null @@ -1,4 +0,0 @@ - -thread 'main' ($TID) panicked at $DIR/zero_diverging_consts_runnable.rs:13:5: -index out of bounds: the len is 3 but the index is 4 -note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace diff --git a/tests/ui/repeat-expr/zero_diverging_type_relative_consts.rs b/tests/ui/repeat-expr/zero_diverging_type_relative_consts.rs index 0b23e291cfacf..1bbc689184f17 100644 --- a/tests/ui/repeat-expr/zero_diverging_type_relative_consts.rs +++ b/tests/ui/repeat-expr/zero_diverging_type_relative_consts.rs @@ -1,3 +1,5 @@ +//@ build-fail + // Check that repeating a diverging constant 0 times doesn't lead to unsoundness. // // Issue: @@ -9,10 +11,10 @@ trait T { struct Panic; impl T for Panic { const V: ! = panic!(); + //~^ ERROR evaluation panicked: explicit panic } fn ex_nihilo() -> u32 { - //~^ error: mismatched types [Panic::V; 0]; } diff --git a/tests/ui/repeat-expr/zero_diverging_type_relative_consts.stderr b/tests/ui/repeat-expr/zero_diverging_type_relative_consts.stderr index 0311068803300..ebd5cf9f8a546 100644 --- a/tests/ui/repeat-expr/zero_diverging_type_relative_consts.stderr +++ b/tests/ui/repeat-expr/zero_diverging_type_relative_consts.stderr @@ -1,11 +1,24 @@ -error[E0308]: mismatched types - --> $DIR/zero_diverging_type_relative_consts.rs:14:19 +error[E0080]: evaluation panicked: explicit panic + --> $DIR/zero_diverging_type_relative_consts.rs:13:18 | -LL | fn ex_nihilo() -> u32 { - | --------- ^^^ expected `u32`, found `()` - | | - | implicitly returns `()` as its body has no tail or `return` expression +LL | impl T for Panic { +LL | const V: ! = panic!(); + | ^^^^^^^^ evaluation of `::V` failed here + +note: erroneous constant encountered + --> $DIR/zero_diverging_type_relative_consts.rs:18:6 + | +LL | [Panic::V; 0]; + | ^^^^^^^^ + +note: erroneous constant encountered + --> $DIR/zero_diverging_type_relative_consts.rs:18:6 + | +LL | [Panic::V; 0]; + | ^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: aborting due to 1 previous error -For more information about this error, try `rustc --explain E0308`. +For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/repeat-expr/zero_infer_diverging_consts.rs b/tests/ui/repeat-expr/zero_infer_diverging_consts.rs index 4e174fbf2a7b4..e911fec980ad3 100644 --- a/tests/ui/repeat-expr/zero_infer_diverging_consts.rs +++ b/tests/ui/repeat-expr/zero_infer_diverging_consts.rs @@ -1,16 +1,18 @@ +//@ build-fail + // Check that repeating a diverging constant 0 times (inferred via `_`) // doesn't lead to unsoundness. // // Issue: fn ex_nihilo() -> u32 { - //~^ error: mismatched types let _: [_; 0] = [const { panic!() } as !; _]; + //~^ ERROR evaluation panicked: explicit panic } fn ex_nihilo2() -> u32 { - //~^ error: mismatched types let a = [const { panic!() } as !; _]; + //~^ ERROR evaluation panicked: explicit panic let _: [_; 0] = a; } diff --git a/tests/ui/repeat-expr/zero_infer_diverging_consts.stderr b/tests/ui/repeat-expr/zero_infer_diverging_consts.stderr index db55732073786..743350072f1ee 100644 --- a/tests/ui/repeat-expr/zero_infer_diverging_consts.stderr +++ b/tests/ui/repeat-expr/zero_infer_diverging_consts.stderr @@ -1,19 +1,45 @@ -error[E0308]: mismatched types - --> $DIR/zero_infer_diverging_consts.rs:6:19 +error[E0080]: evaluation panicked: explicit panic + --> $DIR/zero_infer_diverging_consts.rs:9:30 | LL | fn ex_nihilo() -> u32 { - | --------- ^^^ expected `u32`, found `()` - | | - | implicitly returns `()` as its body has no tail or `return` expression +LL | let _: [_; 0] = [const { panic!() } as !; _]; + | ^^^^^^^^ evaluation of `ex_nihilo::{constant#1}` failed here -error[E0308]: mismatched types - --> $DIR/zero_infer_diverging_consts.rs:11:20 +note: erroneous constant encountered + --> $DIR/zero_infer_diverging_consts.rs:9:22 + | +LL | let _: [_; 0] = [const { panic!() } as !; _]; + | ^^^^^^^^^^^^^^^^^^ + +note: erroneous constant encountered + --> $DIR/zero_infer_diverging_consts.rs:9:22 + | +LL | let _: [_; 0] = [const { panic!() } as !; _]; + | ^^^^^^^^^^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error[E0080]: evaluation panicked: explicit panic + --> $DIR/zero_infer_diverging_consts.rs:14:22 | LL | fn ex_nihilo2() -> u32 { - | ---------- ^^^ expected `u32`, found `()` - | | - | implicitly returns `()` as its body has no tail or `return` expression +LL | let a = [const { panic!() } as !; _]; + | ^^^^^^^^ evaluation of `ex_nihilo2::{constant#0}` failed here + +note: erroneous constant encountered + --> $DIR/zero_infer_diverging_consts.rs:14:14 + | +LL | let a = [const { panic!() } as !; _]; + | ^^^^^^^^^^^^^^^^^^ + +note: erroneous constant encountered + --> $DIR/zero_infer_diverging_consts.rs:14:14 + | +LL | let a = [const { panic!() } as !; _]; + | ^^^^^^^^^^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0308`. +For more information about this error, try `rustc --explain E0080`.