Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 19 additions & 25 deletions compiler/rustc_borrowck/src/type_check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -995,39 +995,33 @@ 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()),
Locations::Single(location),
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,
);
}
}
}
Expand Down
87 changes: 0 additions & 87 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Span> {
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_hir_analysis/src/check/region.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
39 changes: 2 additions & 37 deletions compiler/rustc_hir_typeck/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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);
Expand All @@ -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);
}
Expand Down
6 changes: 5 additions & 1 deletion compiler/rustc_middle/src/mir/syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
38 changes: 28 additions & 10 deletions compiler/rustc_mir_build/src/builder/expr/as_constant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ConstOperand<'tcx>> {
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 {
Expand All @@ -47,54 +55,64 @@ pub(crate) fn as_constant_inner<'tcx>(
push_cuta: impl FnMut(&Box<CanonicalUserType<'tcx>>) -> Option<UserTypeAnnotationIndex>,
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<CanonicalUserType<'tcx>>) -> Option<UserTypeAnnotationIndex>,
tcx: TyCtxt<'tcx>,
) -> Option<ConstOperand<'tcx>> {
let Expr { ty, temp_scope_id: _, span, ref kind } = *expr;

match *kind {
ExprKind::Literal { lit, neg } => {
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,
}
}

Expand Down
Loading
Loading