Skip to content

Commit 0078e54

Browse files
committed
rebase and use ty::Const in patterns again
1 parent ac60db2 commit 0078e54

File tree

13 files changed

+73
-144
lines changed

13 files changed

+73
-144
lines changed

compiler/rustc_const_eval/src/const_eval/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -184,13 +184,13 @@ pub(crate) fn destructure_mir_constant<'tcx>(
184184
// We go to `usize` as we cannot allocate anything bigger anyway.
185185
let (field_count, variant, down) = match val.ty().kind() {
186186
ty::Array(_, len) => (usize::try_from(len.eval_usize(tcx, param_env)).unwrap(), None, op),
187-
ty::Adt(def, _) if def.variants.is_empty() => {
187+
ty::Adt(def, _) if def.variants().is_empty() => {
188188
return mir::DestructuredMirConstant { variant: None, fields: &[] };
189189
}
190190
ty::Adt(def, _) => {
191191
let variant = ecx.read_discriminant(&op).unwrap().1;
192192
let down = ecx.operand_downcast(&op, variant).unwrap();
193-
(def.variants[variant].fields.len(), Some(variant), down)
193+
(def.variants()[variant].fields.len(), Some(variant), down)
194194
}
195195
ty::Tuple(substs) => (substs.len(), None, op),
196196
_ => bug!("cannot destructure constant {:?}", val),
@@ -253,7 +253,7 @@ pub(crate) fn deref_mir_constant<'tcx>(
253253
let mplace = ecx.deref_operand(&op).unwrap();
254254
if let Some(alloc_id) = mplace.ptr.provenance {
255255
assert_eq!(
256-
tcx.get_global_alloc(alloc_id).unwrap().unwrap_memory().mutability,
256+
tcx.get_global_alloc(alloc_id).unwrap().unwrap_memory().0.0.mutability,
257257
Mutability::Not,
258258
"deref_const cannot be used with mutable allocations as \
259259
that could allow pattern matching to observe mutable statics",

compiler/rustc_middle/src/mir/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2711,7 +2711,7 @@ impl<'tcx> ConstantKind<'tcx> {
27112711
if let Some(val) = c.val().try_eval(tcx, param_env) {
27122712
match val {
27132713
Ok(val) => Self::Val(val, c.ty()),
2714-
Err(ErrorReported) => Self::Ty(tcx.const_error(self.ty())),
2714+
Err(_) => Self::Ty(tcx.const_error(self.ty())),
27152715
}
27162716
} else {
27172717
self

compiler/rustc_middle/src/thir.rs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ pub enum StmtKind<'tcx> {
193193

194194
// `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
195195
#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
196-
rustc_data_structures::static_assert_size!(Expr<'_>, 144);
196+
rustc_data_structures::static_assert_size!(Expr<'_>, 104);
197197

198198
/// A THIR expression.
199199
#[derive(Debug, HashStable)]
@@ -736,11 +736,7 @@ impl<'tcx> fmt::Display for Pat<'tcx> {
736736
Some(adt_def.variant(variant_index))
737737
}
738738
_ => self.ty.ty_adt_def().and_then(|adt| {
739-
if !adt.is_enum() {
740-
Some(adt.non_enum_variant())
741-
} else {
742-
None
743-
}
739+
if !adt.is_enum() { Some(adt.non_enum_variant()) } else { None }
744740
}),
745741
};
746742

compiler/rustc_middle/src/thir/visit.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ use super::{
22
Arm, Block, Expr, ExprKind, Guard, InlineAsmOperand, Pat, PatKind, Stmt, StmtKind, Thir,
33
};
44
use crate::mir::ConstantKind;
5-
use crate::ty::Const;
65

76
pub trait Visitor<'a, 'tcx: 'a>: Sized {
87
fn thir(&self) -> &'a Thir<'tcx>;

compiler/rustc_middle/src/ty/consts/kind.rs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,11 +76,7 @@ static_assert_size!(ConstKind<'_>, 40);
7676
impl<'tcx> ConstKind<'tcx> {
7777
#[inline]
7878
pub fn try_to_value(self) -> Option<ConstValue<'tcx>> {
79-
if let ConstKind::Value(val) = self {
80-
Some(val)
81-
} else {
82-
None
83-
}
79+
if let ConstKind::Value(val) = self { Some(val) } else { None }
8480
}
8581

8682
#[inline]
Lines changed: 3 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,12 @@
11
//! See docs in build/expr/mod.rs
22
33
use crate::build::Builder;
4-
use crate::thir::constant::parse_float;
5-
use rustc_ast::ast;
64
use rustc_hir::def_id::DefId;
7-
use rustc_middle::mir::interpret::{
8-
Allocation, ConstValue, LitToConstError, LitToConstInput, Scalar,
9-
};
5+
use rustc_middle::mir::interpret::{ConstValue, LitToConstError, LitToConstInput, Scalar};
106
use rustc_middle::mir::*;
117
use rustc_middle::thir::*;
128
use rustc_middle::ty::subst::SubstsRef;
139
use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt};
14-
use rustc_target::abi::Size;
1510

1611
impl<'a, 'tcx> Builder<'a, 'tcx> {
1712
/// Compile `expr`, yielding a compile-time constant. Assumes that
@@ -32,11 +27,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
3227
}
3328
ExprKind::Literal { lit, neg } => {
3429
let literal =
35-
match lit_to_constant(tcx, LitToConstInput { lit: &lit.node, ty, neg }) {
30+
match tcx.lit_to_mir_constant(LitToConstInput { lit: &lit.node, ty, neg }) {
3631
Ok(c) => c,
3732
Err(LitToConstError::Reported) => ConstantKind::Ty(tcx.const_error(ty)),
3833
Err(LitToConstError::TypeError) => {
39-
bug!("encountered type error in `lit_to_constant")
34+
bug!("encountered type error in `lit_to_mir_constant")
4035
}
4136
};
4237

@@ -85,60 +80,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
8580

8681
Constant { span, user_ty: None, literal }
8782
}
88-
ExprKind::ConstBlock { value } => {
89-
Constant { span: span, user_ty: None, literal: value }
90-
}
9183
_ => span_bug!(span, "expression is not a valid constant {:?}", kind),
9284
}
9385
}
9486
}
95-
96-
crate fn lit_to_constant<'tcx>(
97-
tcx: TyCtxt<'tcx>,
98-
lit_input: LitToConstInput<'tcx>,
99-
) -> Result<ConstantKind<'tcx>, LitToConstError> {
100-
let LitToConstInput { lit, ty, neg } = lit_input;
101-
let trunc = |n| {
102-
let param_ty = ty::ParamEnv::reveal_all().and(ty);
103-
let width = tcx.layout_of(param_ty).map_err(|_| LitToConstError::Reported)?.size;
104-
trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
105-
let result = width.truncate(n);
106-
trace!("trunc result: {}", result);
107-
Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
108-
};
109-
110-
let value = match (lit, &ty.kind()) {
111-
(ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
112-
let s = s.as_str();
113-
let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
114-
let allocation = tcx.intern_const_alloc(allocation);
115-
ConstValue::Slice { data: allocation, start: 0, end: s.len() }
116-
}
117-
(ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
118-
if matches!(inner_ty.kind(), ty::Slice(_)) =>
119-
{
120-
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
121-
let allocation = tcx.intern_const_alloc(allocation);
122-
ConstValue::Slice { data: allocation, start: 0, end: data.len() }
123-
}
124-
(ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
125-
let id = tcx.allocate_bytes(data);
126-
ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
127-
}
128-
(ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
129-
ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
130-
}
131-
(ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
132-
trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
133-
}
134-
(ast::LitKind::Float(n, _), ty::Float(fty)) => {
135-
parse_float(*n, *fty, neg).ok_or(LitToConstError::Reported)?
136-
}
137-
(ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(*b)),
138-
(ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(*c)),
139-
(ast::LitKind::Err(_), _) => return Err(LitToConstError::Reported),
140-
_ => return Err(LitToConstError::TypeError),
141-
};
142-
143-
Ok(ConstantKind::Val(value, ty))
144-
}

compiler/rustc_mir_build/src/thir/constant.rs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,56 @@ crate fn lit_to_const<'tcx>(
5959
Ok(ty::Const::from_value(tcx, lit, ty))
6060
}
6161

62+
crate fn lit_to_mir_constant<'tcx>(
63+
tcx: TyCtxt<'tcx>,
64+
lit_input: LitToConstInput<'tcx>,
65+
) -> Result<ConstantKind<'tcx>, LitToConstError> {
66+
let LitToConstInput { lit, ty, neg } = lit_input;
67+
let trunc = |n| {
68+
let param_ty = ty::ParamEnv::reveal_all().and(ty);
69+
let width = tcx.layout_of(param_ty).map_err(|_| LitToConstError::Reported)?.size;
70+
trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
71+
let result = width.truncate(n);
72+
trace!("trunc result: {}", result);
73+
Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
74+
};
75+
76+
let value = match (lit, &ty.kind()) {
77+
(ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
78+
let s = s.as_str();
79+
let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
80+
let allocation = tcx.intern_const_alloc(allocation);
81+
ConstValue::Slice { data: allocation, start: 0, end: s.len() }
82+
}
83+
(ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
84+
if matches!(inner_ty.kind(), ty::Slice(_)) =>
85+
{
86+
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
87+
let allocation = tcx.intern_const_alloc(allocation);
88+
ConstValue::Slice { data: allocation, start: 0, end: data.len() }
89+
}
90+
(ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
91+
let id = tcx.allocate_bytes(data);
92+
ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
93+
}
94+
(ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
95+
ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
96+
}
97+
(ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
98+
trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
99+
}
100+
(ast::LitKind::Float(n, _), ty::Float(fty)) => {
101+
parse_float(*n, *fty, neg).ok_or(LitToConstError::Reported)?
102+
}
103+
(ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(*b)),
104+
(ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(*c)),
105+
(ast::LitKind::Err(_), _) => return Err(LitToConstError::Reported),
106+
_ => return Err(LitToConstError::TypeError),
107+
};
108+
109+
Ok(ConstantKind::Val(value, ty))
110+
}
111+
62112
// FIXME move this to rustc_mir_build::build
63113
pub(crate) fn parse_float<'tcx>(
64114
num: Symbol,

compiler/rustc_mir_build/src/thir/cx/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use crate::thir::pattern::pat_from_hir;
66
use crate::thir::util::UserAnnotatedTyHelpers;
77

8+
use rustc_ast::ast;
89
use rustc_data_structures::steal::Steal;
910
use rustc_errors::ErrorGuaranteed;
1011
use rustc_hir as hir;
@@ -15,7 +16,7 @@ use rustc_middle::middle::region;
1516
use rustc_middle::mir::interpret::{LitToConstError, LitToConstInput};
1617
use rustc_middle::mir::ConstantKind;
1718
use rustc_middle::thir::*;
18-
use rustc_middle::ty::{self, TyCtxt};
19+
use rustc_middle::ty::{self, Ty, TyCtxt};
1920
use rustc_span::Span;
2021

2122
crate fn thir_body<'tcx>(

compiler/rustc_trait_selection/src/traits/const_evaluatable.rs

Lines changed: 0 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -377,10 +377,6 @@ impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
377377
}
378378
}
379379

380-
fn visit_const(&mut self, ct: ty::Const<'tcx>) {
381-
self.is_poly |= ct.has_param_types_or_consts();
382-
}
383-
384380
fn visit_constant(&mut self, ct: mir::ConstantKind<'tcx>) {
385381
self.is_poly |= ct.has_param_types_or_consts();
386382
}
@@ -815,51 +811,3 @@ impl<'tcx> ConstUnifyCtxt<'tcx> {
815811
}
816812
}
817813
}
818-
819-
/* Think I need these changes
820-
=======
821-
match (a_ct, b_ct) {
822-
(mir::ConstantKind::Ty(a_ct), mir::ConstantKind::Ty(b_ct)) => {
823-
match (a_ct.val(), b_ct.val()) {
824-
// We can just unify errors with everything to reduce the amount of
825-
// emitted errors here.
826-
(ty::ConstKind::Error(_), _) | (_, ty::ConstKind::Error(_)) => true,
827-
(ty::ConstKind::Param(a_param), ty::ConstKind::Param(b_param)) => {
828-
a_param == b_param
829-
}
830-
(ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => {
831-
a_val == b_val
832-
}
833-
834-
// If we have `fn a<const N: usize>() -> [u8; N + 1]` and `fn b<const M: usize>() -> [u8; 1 + M]`
835-
// we do not want to use `assert_eq!(a(), b())` to infer that `N` and `M` have to be `1`. This
836-
// means that we only allow inference variables if they are equal.
837-
(ty::ConstKind::Infer(a_val), ty::ConstKind::Infer(b_val)) => {
838-
a_val == b_val
839-
}
840-
// We expand generic anonymous constants at the start of this function, so this
841-
// branch should only be taking when dealing with associated constants, at
842-
// which point directly comparing them seems like the desired behavior.
843-
//
844-
// FIXME(generic_const_exprs): This isn't actually the case.
845-
// We also take this branch for concrete anonymous constants and
846-
// expand generic anonymous constants with concrete substs.
847-
(ty::ConstKind::Unevaluated(a_uv), ty::ConstKind::Unevaluated(b_uv)) => {
848-
a_uv == b_uv
849-
}
850-
// FIXME(generic_const_exprs): We may want to either actually try
851-
// to evaluate `a_ct` and `b_ct` if they are are fully concrete or something like
852-
// this, for now we just return false here.
853-
_ => false,
854-
}
855-
}
856-
(mir::ConstantKind::Val(a_val, a_ty), mir::ConstantKind::Val(b_val, b_ty)) => {
857-
a_val == b_val && a_ty == b_ty
858-
}
859-
_ => {
860-
// FIXME Can it happen that we need to compare ConstantKind::Ty(ConstKind::Value)
861-
// with a ConstantKind::Val and vice versa?
862-
false
863-
>>>>>>> 6064f16d846 (change thir to use mir::ConstantKind instead of ty::Const)
864-
865-
*/

compiler/rustc_trait_selection/src/traits/fulfill.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -407,7 +407,7 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> {
407407
let pred =
408408
ty::Binder::dummy(infcx.replace_bound_vars_with_placeholders(binder));
409409
ProcessResult::Changed(mk_pending(vec![
410-
obligation.with(pred.to_predicate(self.selcx.tcx()))
410+
obligation.with(pred.to_predicate(self.selcx.tcx())),
411411
]))
412412
}
413413
ty::PredicateKind::TypeWellFormedFromEnv(..) => {

src/tools/clippy/clippy_lints/src/matches/overlapping_arms.rs

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use clippy_utils::consts::{constant, constant_full_int, miri_to_const, FullInt};
1+
use clippy_utils::consts::{constant, constant_full_int, FullInt};
22
use clippy_utils::diagnostics::span_lint_and_note;
33
use core::cmp::Ordering;
44
use rustc_hir::{Arm, Expr, PatKind, RangeEnd};
@@ -32,18 +32,15 @@ fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>)
3232
.filter_map(|arm| {
3333
if let Arm { pat, guard: None, .. } = *arm {
3434
if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
35-
let lhs_const = match lhs {
36-
Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
37-
None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
35+
let lhs_val = match lhs {
36+
Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0.int_value(cx, ty)?,
37+
None => FullInt::U(ty.numeric_min_val(cx.tcx)?),
3838
};
39-
let rhs_const = match rhs {
40-
Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
41-
None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
39+
let rhs_val = match rhs {
40+
Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0.int_value(cx, ty)?,
41+
None => FullInt::U(ty.numeric_max_val(cx.tcx)?),
4242
};
4343

44-
let lhs_val = lhs_const.int_value(cx, ty)?;
45-
let rhs_val = rhs_const.int_value(cx, ty)?;
46-
4744
let rhs_bound = match range_end {
4845
RangeEnd::Included => EndBound::Included(rhs_val),
4946
RangeEnd::Excluded => EndBound::Excluded(rhs_val),

src/tools/clippy/clippy_lints/src/neg_multiply.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ impl<'tcx> LateLintPass<'tcx> for NegMultiply {
5353
fn check_mul(cx: &LateContext<'_>, span: Span, lit: &Expr<'_>, exp: &Expr<'_>) {
5454
if_chain! {
5555
if let ExprKind::Lit(ref l) = lit.kind;
56-
if consts::lit_to_constant(&l.node, cx.typeck_results().expr_ty_opt(lit)) == Constant::Int(1);
56+
if consts::lit_to_mir_constant(&l.node, cx.typeck_results().expr_ty_opt(lit)) == Constant::Int(1);
5757
if cx.typeck_results().expr_ty(exp).is_integral();
5858

5959
then {

src/tools/clippy/clippy_utils/src/consts.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ impl Constant {
179179
}
180180

181181
/// Parses a `LitKind` to a `Constant`.
182-
pub fn lit_to_constant(lit: &LitKind, ty: Option<Ty<'_>>) -> Constant {
182+
pub fn lit_to_mir_constant(lit: &LitKind, ty: Option<Ty<'_>>) -> Constant {
183183
match *lit {
184184
LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
185185
LitKind::Byte(b) => Constant::Int(u128::from(b)),
@@ -301,7 +301,7 @@ impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> {
301301
if is_direct_expn_of(e.span, "cfg").is_some() {
302302
None
303303
} else {
304-
Some(lit_to_constant(&lit.node, self.typeck_results.expr_ty_opt(e)))
304+
Some(lit_to_mir_constant(&lit.node, self.typeck_results.expr_ty_opt(e)))
305305
}
306306
},
307307
ExprKind::Array(vec) => self.multi(vec).map(Constant::Vec),

0 commit comments

Comments
 (0)