Skip to content

Commit 5b906d5

Browse files
Get rid of const eval_* and try_eval_* helpers
1 parent a3f76a2 commit 5b906d5

File tree

24 files changed

+90
-109
lines changed

24 files changed

+90
-109
lines changed

compiler/rustc_borrowck/src/type_check/mod.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1128,7 +1128,6 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
11281128
}
11291129
let projected_ty = curr_projected_ty.projection_ty_core(
11301130
tcx,
1131-
self.param_env,
11321131
proj,
11331132
|this, field, ()| {
11341133
let ty = this.field_ty(tcx, field);
@@ -1919,7 +1918,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
19191918
// than 1.
19201919
// If the length is larger than 1, the repeat expression will need to copy the
19211920
// element, so we require the `Copy` trait.
1922-
if len.try_eval_target_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1921+
if len.try_to_target_usize(tcx).is_none_or(|len| len > 1) {
19231922
match operand {
19241923
Operand::Copy(..) | Operand::Constant(..) => {
19251924
// These are always okay: direct use of a const, or a value that can evidently be copied.

compiler/rustc_codegen_llvm/src/intrinsic.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1172,8 +1172,10 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
11721172
ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
11731173
ty::Array(elem, len)
11741174
if matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
1175-
&& len.try_eval_target_usize(bx.tcx, ty::ParamEnv::reveal_all())
1176-
== Some(expected_bytes) =>
1175+
&& len
1176+
.try_to_target_usize(bx.tcx)
1177+
.expect("expected monomorphic const in codegen")
1178+
== expected_bytes =>
11771179
{
11781180
let place = PlaceRef::alloca(bx, args[0].layout);
11791181
args[0].val.store(bx, place);
@@ -1462,8 +1464,10 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
14621464
}
14631465
ty::Array(elem, len)
14641466
if matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
1465-
&& len.try_eval_target_usize(bx.tcx, ty::ParamEnv::reveal_all())
1466-
== Some(expected_bytes) =>
1467+
&& len
1468+
.try_to_target_usize(bx.tcx)
1469+
.expect("expected monomorphic const in codegen")
1470+
== expected_bytes =>
14671471
{
14681472
// Zero-extend iN to the array length:
14691473
let ze = bx.zext(i_, bx.type_ix(expected_bytes * 8));

compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -690,16 +690,20 @@ fn push_const_param<'tcx>(tcx: TyCtxt<'tcx>, ct: ty::Const<'tcx>, output: &mut S
690690
ty::Int(ity) => {
691691
// FIXME: directly extract the bits from a valtree instead of evaluating an
692692
// already evaluated `Const` in order to get the bits.
693-
let bits = ct.eval_bits(tcx, ty::ParamEnv::reveal_all());
693+
let bits = ct
694+
.try_to_bits(tcx, ty::ParamEnv::reveal_all())
695+
.expect("expected monomorphic const in codegen");
694696
let val = Integer::from_int_ty(&tcx, *ity).size().sign_extend(bits) as i128;
695697
write!(output, "{val}")
696698
}
697699
ty::Uint(_) => {
698-
let val = ct.eval_bits(tcx, ty::ParamEnv::reveal_all());
700+
let val = ct
701+
.try_to_bits(tcx, ty::ParamEnv::reveal_all())
702+
.expect("expected monomorphic const in codegen");
699703
write!(output, "{val}")
700704
}
701705
ty::Bool => {
702-
let val = ct.try_eval_bool(tcx, ty::ParamEnv::reveal_all()).unwrap();
706+
let val = ct.try_to_bool().expect("expected monomorphic const in codegen");
703707
write!(output, "{val}")
704708
}
705709
_ => {

compiler/rustc_const_eval/src/const_eval/mod.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,13 @@ pub(crate) fn try_destructure_mir_constant_for_user_output<'tcx>(
5555

5656
// We go to `usize` as we cannot allocate anything bigger anyway.
5757
let (field_count, variant, down) = match ty.kind() {
58-
ty::Array(_, len) => (len.eval_target_usize(tcx.tcx, param_env) as usize, None, op),
58+
ty::Array(_, len) => (
59+
len.try_to_target_usize(tcx.tcx)
60+
.expect("expected monomorphic constant when printing MIR const")
61+
as usize,
62+
None,
63+
op,
64+
),
5965
ty::Adt(def, _) if def.variants().is_empty() => {
6066
return None;
6167
}

compiler/rustc_const_eval/src/interpret/cast.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,9 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
394394
let ptr = self.read_pointer(src)?;
395395
let val = Immediate::new_slice(
396396
ptr,
397-
length.eval_target_usize(*self.tcx, self.param_env),
397+
length
398+
.try_to_target_usize(*self.tcx)
399+
.expect("expected monomorphic const in const eval"),
398400
self,
399401
);
400402
self.write_immediate(val, dest)

compiler/rustc_hir_analysis/src/check/check.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1086,7 +1086,8 @@ fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
10861086
return;
10871087
}
10881088

1089-
if let Some(len) = len_const.try_eval_target_usize(tcx, tcx.param_env(def.did())) {
1089+
// TODO:
1090+
if let Some(len) = len_const.try_to_target_usize(tcx) {
10901091
if len == 0 {
10911092
struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
10921093
return;

compiler/rustc_hir_analysis/src/check/intrinsicck.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,8 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
7777
let (size, ty) = match elem_ty.kind() {
7878
ty::Array(ty, len) => {
7979
if let Some(len) =
80-
len.try_eval_target_usize(self.tcx, self.tcx.param_env(adt.did()))
80+
// TODO:
81+
len.try_to_target_usize(self.tcx)
8182
{
8283
(len, *ty)
8384
} else {

compiler/rustc_lint/src/builtin.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2601,7 +2601,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue {
26012601
ty.tuple_fields().iter().find_map(|field| ty_find_init_error(cx, field, init))
26022602
}
26032603
Array(ty, len) => {
2604-
if matches!(len.try_eval_target_usize(cx.tcx, cx.param_env), Some(v) if v > 0) {
2604+
if matches!(len.try_to_target_usize(cx.tcx), Some(v) if v > 0) {
26052605
// Array length known at array non-empty -- recurse.
26062606
ty_find_init_error(cx, *ty, init)
26072607
} else {

compiler/rustc_lint/src/unused.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
346346
None
347347
}
348348
}
349-
ty::Array(ty, len) => match len.try_eval_target_usize(cx.tcx, cx.param_env) {
349+
ty::Array(ty, len) => match len.try_to_target_usize(cx.tcx) {
350350
// If the array is empty we don't lint, to avoid false positives
351351
Some(0) | None => None,
352352
// If the array is definitely non-empty, we can do `#[must_use]` checking.

compiler/rustc_middle/src/mir/tcx.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ impl<'tcx> PlaceTy<'tcx> {
5555
/// `PlaceElem`, where we can just use the `Ty` that is already
5656
/// stored inline on field projection elems.
5757
pub fn projection_ty(self, tcx: TyCtxt<'tcx>, elem: PlaceElem<'tcx>) -> PlaceTy<'tcx> {
58-
self.projection_ty_core(tcx, ty::ParamEnv::empty(), &elem, |_, _, ty| ty, |_, ty| ty)
58+
self.projection_ty_core(tcx, &elem, |_, _, ty| ty, |_, ty| ty)
5959
}
6060

6161
/// `place_ty.projection_ty_core(tcx, elem, |...| { ... })`
@@ -66,7 +66,6 @@ impl<'tcx> PlaceTy<'tcx> {
6666
pub fn projection_ty_core<V, T>(
6767
self,
6868
tcx: TyCtxt<'tcx>,
69-
param_env: ty::ParamEnv<'tcx>,
7069
elem: &ProjectionElem<V, T>,
7170
mut handle_field: impl FnMut(&Self, FieldIdx, T) -> Ty<'tcx>,
7271
mut handle_opaque_cast_and_subtype: impl FnMut(&Self, T) -> Ty<'tcx>,
@@ -93,7 +92,9 @@ impl<'tcx> PlaceTy<'tcx> {
9392
ty::Slice(..) => self.ty,
9493
ty::Array(inner, _) if !from_end => Ty::new_array(tcx, *inner, to - from),
9594
ty::Array(inner, size) if from_end => {
96-
let size = size.eval_target_usize(tcx, param_env);
95+
let size = size
96+
.try_to_target_usize(tcx)
97+
.expect("expected subslice projection on fixed-size array");
9798
let len = size - from - to;
9899
Ty::new_array(tcx, *inner, len)
99100
}

compiler/rustc_middle/src/ty/consts.rs

Lines changed: 21 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -431,100 +431,47 @@ impl<'tcx> Const<'tcx> {
431431
}
432432
}
433433

434-
#[inline]
435-
pub fn try_eval_scalar(
436-
self,
437-
tcx: TyCtxt<'tcx>,
438-
param_env: ty::ParamEnv<'tcx>,
439-
) -> Option<(Ty<'tcx>, Scalar)> {
440-
let (ty, val) = self.eval(tcx, param_env, DUMMY_SP).ok()?;
441-
let val = val.try_to_scalar()?;
442-
Some((ty, val))
443-
}
444-
445-
#[inline]
446-
/// Attempts to evaluate the given constant to bits. Can fail to evaluate in the presence of
447-
/// generics (or erroneous code) or if the value can't be represented as bits (e.g. because it
448-
/// contains const generic parameters or pointers).
449-
pub fn try_eval_scalar_int(
450-
self,
451-
tcx: TyCtxt<'tcx>,
452-
param_env: ParamEnv<'tcx>,
453-
) -> Option<(Ty<'tcx>, ScalarInt)> {
454-
let (ty, scalar) = self.try_eval_scalar(tcx, param_env)?;
455-
let val = scalar.try_to_scalar_int().ok()?;
456-
Some((ty, val))
457-
}
458-
459-
#[inline]
460-
/// Attempts to evaluate the given constant to bits. Can fail to evaluate in the presence of
461-
/// generics (or erroneous code) or if the value can't be represented as bits (e.g. because it
462-
/// contains const generic parameters or pointers).
463-
pub fn try_eval_bits(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<u128> {
464-
let (ty, scalar) = self.try_eval_scalar_int(tcx, param_env)?;
465-
let size = tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
466-
// if `ty` does not depend on generic parameters, use an empty param_env
467-
Some(scalar.to_bits(size))
468-
}
469-
470-
#[inline]
471-
/// Panics if the value cannot be evaluated or doesn't contain a valid integer of the given type.
472-
pub fn eval_bits(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> u128 {
473-
self.try_eval_bits(tcx, param_env)
474-
.unwrap_or_else(|| bug!("failed to evalate {:#?} to bits", self))
475-
}
476-
477-
#[inline]
478-
pub fn try_eval_target_usize(
479-
self,
480-
tcx: TyCtxt<'tcx>,
481-
param_env: ParamEnv<'tcx>,
482-
) -> Option<u64> {
483-
let (_, scalar) = self.try_eval_scalar_int(tcx, param_env)?;
484-
Some(scalar.to_target_usize(tcx))
485-
}
486-
487-
#[inline]
488-
pub fn try_eval_bool(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<bool> {
489-
let (_, scalar) = self.try_eval_scalar_int(tcx, param_env)?;
490-
scalar.try_into().ok()
491-
}
492-
493-
#[inline]
494-
/// Panics if the value cannot be evaluated or doesn't contain a valid `usize`.
495-
pub fn eval_target_usize(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> u64 {
496-
self.try_eval_target_usize(tcx, param_env)
497-
.unwrap_or_else(|| bug!("expected usize, got {:#?}", self))
498-
}
499-
500434
/// Panics if self.kind != ty::ConstKind::Value
501-
pub fn to_valtree(self) -> ty::ValTree<'tcx> {
435+
pub fn to_valtree(self) -> (ty::ValTree<'tcx>, Ty<'tcx>) {
502436
match self.kind() {
503-
ty::ConstKind::Value(_, valtree) => valtree,
437+
ty::ConstKind::Value(ty, valtree) => (valtree, ty),
504438
_ => bug!("expected ConstKind::Value, got {:?}", self.kind()),
505439
}
506440
}
507441

508442
/// Attempts to convert to a `ValTree`
509-
pub fn try_to_valtree(self) -> Option<ty::ValTree<'tcx>> {
443+
pub fn try_to_valtree(self) -> Option<(ty::ValTree<'tcx>, Ty<'tcx>)> {
510444
match self.kind() {
511-
ty::ConstKind::Value(_, valtree) => Some(valtree),
445+
ty::ConstKind::Value(ty, valtree) => Some((valtree, ty)),
512446
_ => None,
513447
}
514448
}
515449

516450
#[inline]
517-
pub fn try_to_scalar(self) -> Option<Scalar> {
518-
self.try_to_valtree()?.try_to_scalar()
451+
pub fn try_to_scalar(self) -> Option<(Scalar, Ty<'tcx>)> {
452+
let (valtree, ty) = self.try_to_valtree()?;
453+
Some((valtree.try_to_scalar()?, ty))
519454
}
520455

521456
pub fn try_to_bool(self) -> Option<bool> {
522-
self.try_to_scalar()?.to_bool().ok()
457+
self.try_to_scalar()?.0.to_bool().ok()
523458
}
524459

525460
#[inline]
526461
pub fn try_to_target_usize(self, tcx: TyCtxt<'tcx>) -> Option<u64> {
527-
self.try_to_valtree()?.try_to_target_usize(tcx)
462+
self.try_to_valtree()?.0.try_to_target_usize(tcx)
463+
}
464+
465+
#[inline]
466+
/// Attempts to evaluate the given constant to bits. Can fail to evaluate in the presence of
467+
/// generics (or erroneous code) or if the value can't be represented as bits (e.g. because it
468+
/// contains const generic parameters or pointers).
469+
pub fn try_to_bits(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<u128> {
470+
let (scalar, ty) = self.try_to_scalar()?;
471+
let scalar = scalar.try_to_scalar_int().ok()?;
472+
let size = tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
473+
// if `ty` does not depend on generic parameters, use an empty param_env
474+
Some(scalar.to_bits(size))
528475
}
529476

530477
pub fn is_ct_infer(self) -> bool {

compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ impl<'tcx> InhabitedPredicate<'tcx> {
8585
match self {
8686
Self::False => Ok(false),
8787
Self::True => Ok(true),
88-
Self::ConstIsZero(const_) => match const_.try_eval_target_usize(tcx, param_env) {
88+
Self::ConstIsZero(const_) => match const_.try_to_target_usize(tcx) {
8989
None | Some(0) => Ok(true),
9090
Some(1..) => Ok(false),
9191
},

compiler/rustc_middle/src/ty/layout.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ impl<'tcx> SizeSkeleton<'tcx> {
387387
}
388388
}
389389
ty::Array(inner, len) if tcx.features().transmute_generic_consts => {
390-
let len_eval = len.try_eval_target_usize(tcx, param_env);
390+
let len_eval = len.try_to_target_usize(tcx);
391391
if len_eval == Some(0) {
392392
return Ok(SizeSkeleton::Known(Size::from_bytes(0), None));
393393
}

compiler/rustc_middle/src/ty/sty.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1105,7 +1105,12 @@ impl<'tcx> Ty<'tcx> {
11051105
// The way we evaluate the `N` in `[T; N]` here only works since we use
11061106
// `simd_size_and_type` post-monomorphization. It will probably start to ICE
11071107
// if we use it in generic code. See the `simd-array-trait` ui test.
1108-
(f0_len.eval_target_usize(tcx, ParamEnv::empty()), *f0_elem_ty)
1108+
(
1109+
f0_len
1110+
.try_to_target_usize(tcx)
1111+
.expect("expected SIMD field to have definite array size"),
1112+
*f0_elem_ty,
1113+
)
11091114
}
11101115

11111116
#[inline]

compiler/rustc_mir_dataflow/src/elaborate_drops.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -863,7 +863,7 @@ where
863863
ty::Adt(def, args) => self.open_drop_for_adt(*def, args),
864864
ty::Dynamic(..) => self.complete_drop(self.succ, self.unwind),
865865
ty::Array(ety, size) => {
866-
let size = size.try_eval_target_usize(self.tcx(), self.elaborator.param_env());
866+
let size = size.try_to_target_usize(self.tcx());
867867
self.open_drop_for_array(*ety, size)
868868
}
869869
ty::Slice(ety) => self.drop_loop_pair(*ety),

compiler/rustc_mir_dataflow/src/move_paths/builder.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ struct MoveDataBuilder<'a, 'tcx, F> {
1818
body: &'a Body<'tcx>,
1919
loc: Location,
2020
tcx: TyCtxt<'tcx>,
21+
// TODO:
22+
#[allow(unused)]
2123
param_env: ty::ParamEnv<'tcx>,
2224
data: MoveData<'tcx>,
2325
filter: F,
@@ -549,7 +551,9 @@ impl<'a, 'tcx, F: Fn(Ty<'tcx>) -> bool> MoveDataBuilder<'a, 'tcx, F> {
549551
};
550552
let base_ty = base_place.ty(self.body, self.tcx).ty;
551553
let len: u64 = match base_ty.kind() {
552-
ty::Array(_, size) => size.eval_target_usize(self.tcx, self.param_env),
554+
ty::Array(_, size) => size
555+
.try_to_target_usize(self.tcx)
556+
.expect("expected subslice projection on fixed-size array"),
553557
_ => bug!("from_end: false slice pattern of non-array type"),
554558
};
555559
for offset in from..to {

compiler/rustc_mir_transform/src/coroutine.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1957,7 +1957,8 @@ fn check_must_not_suspend_ty<'tcx>(
19571957
let descr_pre = &format!("{}array{} of ", data.descr_pre, plural_suffix);
19581958
check_must_not_suspend_ty(tcx, ty, hir_id, param_env, SuspendCheckData {
19591959
descr_pre,
1960-
plural_len: len.try_eval_target_usize(tcx, param_env).unwrap_or(0) as usize + 1,
1960+
// FIXME(must_not_suspend): This is wrong. We should handle printing unevaluated consts.
1961+
plural_len: len.try_to_target_usize(tcx).unwrap_or(0) as usize + 1,
19611962
..data
19621963
})
19631964
}

compiler/rustc_mir_transform/src/known_panics_lint.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -605,7 +605,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
605605
Value::Immediate(src) => src.len(&self.ecx).ok()?,
606606
Value::Aggregate { fields, .. } => fields.len() as u64,
607607
Value::Uninit => match place.ty(self.local_decls(), self.tcx).ty.kind() {
608-
ty::Array(_, n) => n.try_eval_target_usize(self.tcx, self.param_env)?,
608+
ty::Array(_, n) => n.try_to_target_usize(self.tcx)?,
609609
_ => return None,
610610
},
611611
};

compiler/rustc_mir_transform/src/promote_consts.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,7 @@ impl<'tcx> Validator<'_, 'tcx> {
329329
// Determine the type of the thing we are indexing.
330330
&& let ty::Array(_, len) = place_base.ty(self.body, self.tcx).ty.kind()
331331
// It's an array; determine its length.
332-
&& let Some(len) = len.try_eval_target_usize(self.tcx, self.param_env)
332+
&& let Some(len) = len.try_to_target_usize(self.tcx)
333333
// If the index is in-bounds, go ahead.
334334
&& idx < len
335335
{
@@ -407,7 +407,7 @@ impl<'tcx> Validator<'_, 'tcx> {
407407
// mutably without consequences. However, only &mut []
408408
// is allowed right now.
409409
if let ty::Array(_, len) = ty.kind() {
410-
match len.try_eval_target_usize(self.tcx, self.param_env) {
410+
match len.try_to_target_usize(self.tcx) {
411411
Some(0) => {}
412412
_ => return Err(Unpromotable),
413413
}

0 commit comments

Comments
 (0)