1
Fork 0

Auto merge of #97019 - b-naber:transition-to-valtrees-pt1, r=oli-obk

Transition to valtrees pt1

Compartmentalising https://github.com/rust-lang/rust/pull/96591 as much as possible.

r? `@oli-obk`
This commit is contained in:
bors 2022-05-18 20:12:07 +00:00
commit cd282d7f75
27 changed files with 541 additions and 245 deletions

View file

@ -1,16 +1,12 @@
//! See docs in build/expr/mod.rs
use crate::build::Builder;
use crate::thir::constant::parse_float;
use rustc_ast as ast;
use crate::build::{lit_to_mir_constant, Builder};
use rustc_hir::def_id::DefId;
use rustc_middle::mir::interpret::Allocation;
use rustc_middle::mir::interpret::{ConstValue, LitToConstError, LitToConstInput, Scalar};
use rustc_middle::mir::*;
use rustc_middle::thir::*;
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt};
use rustc_target::abi::Size;
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Compile `expr`, yielding a compile-time constant. Assumes that
@ -88,54 +84,3 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
}
}
}
#[instrument(skip(tcx, lit_input))]
fn lit_to_mir_constant<'tcx>(
tcx: TyCtxt<'tcx>,
lit_input: LitToConstInput<'tcx>,
) -> Result<ConstantKind<'tcx>, LitToConstError> {
let LitToConstInput { lit, ty, neg } = lit_input;
let trunc = |n| {
let param_ty = ty::ParamEnv::reveal_all().and(ty);
let width = tcx.layout_of(param_ty).map_err(|_| LitToConstError::Reported)?.size;
trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
let result = width.truncate(n);
trace!("trunc result: {}", result);
Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
};
let value = match (lit, &ty.kind()) {
(ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
let s = s.as_str();
let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
let allocation = tcx.intern_const_alloc(allocation);
ConstValue::Slice { data: allocation, start: 0, end: s.len() }
}
(ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
if matches!(inner_ty.kind(), ty::Slice(_)) =>
{
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
let allocation = tcx.intern_const_alloc(allocation);
ConstValue::Slice { data: allocation, start: 0, end: data.len() }
}
(ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
let id = tcx.allocate_bytes(data);
ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
}
(ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
}
(ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
}
(ast::LitKind::Float(n, _), ty::Float(fty)) => {
parse_float(*n, *fty, neg).ok_or(LitToConstError::Reported)?
}
(ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(*b)),
(ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(*c)),
(ast::LitKind::Err(_), _) => return Err(LitToConstError::Reported),
_ => return Err(LitToConstError::TypeError),
};
Ok(ConstantKind::Val(value, ty))
}

View file

@ -966,13 +966,13 @@ enum TestKind<'tcx> {
///
/// For `bool` we always generate two edges, one for `true` and one for
/// `false`.
options: FxIndexMap<ty::Const<'tcx>, u128>,
options: FxIndexMap<ConstantKind<'tcx>, u128>,
},
/// Test for equality with value, possibly after an unsizing coercion to
/// `ty`,
Eq {
value: ty::Const<'tcx>,
value: ConstantKind<'tcx>,
// Integer types are handled by `SwitchInt`, and constants with ADT
// types are converted back into patterns, so this can only be `&str`,
// `&[T]`, `f32` or `f64`.

View file

@ -228,9 +228,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
_ => (None, 0),
};
if let Some((min, max, sz)) = range {
if let (Some(lo), Some(hi)) =
(lo.val().try_to_bits(sz), hi.val().try_to_bits(sz))
{
if let (Some(lo), Some(hi)) = (lo.try_to_bits(sz), hi.try_to_bits(sz)) {
// We want to compare ranges numerically, but the order of the bitwise
// representation of signed integers does not match their numeric order.
// Thus, to correct the ordering, we need to shift the range of signed

View file

@ -86,7 +86,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
test_place: &PlaceBuilder<'tcx>,
candidate: &Candidate<'pat, 'tcx>,
switch_ty: Ty<'tcx>,
options: &mut FxIndexMap<ty::Const<'tcx>, u128>,
options: &mut FxIndexMap<ConstantKind<'tcx>, u128>,
) -> bool {
let Some(match_pair) = candidate.match_pairs.iter().find(|mp| mp.place == *test_place) else {
return false;
@ -366,7 +366,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
block: BasicBlock,
make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>,
source_info: SourceInfo,
value: ty::Const<'tcx>,
value: ConstantKind<'tcx>,
place: Place<'tcx>,
mut ty: Ty<'tcx>,
) {
@ -760,7 +760,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
span_bug!(match_pair.pattern.span, "simplifyable pattern found: {:?}", match_pair.pattern)
}
fn const_range_contains(&self, range: PatRange<'tcx>, value: ty::Const<'tcx>) -> Option<bool> {
fn const_range_contains(
&self,
range: PatRange<'tcx>,
value: ConstantKind<'tcx>,
) -> Option<bool> {
use std::cmp::Ordering::*;
let tcx = self.tcx;
@ -777,7 +781,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
fn values_not_contained_in_range(
&self,
range: PatRange<'tcx>,
options: &FxIndexMap<ty::Const<'tcx>, u128>,
options: &FxIndexMap<ConstantKind<'tcx>, u128>,
) -> Option<bool> {
for &val in options.keys() {
if self.const_range_contains(range, val)? {

View file

@ -3,7 +3,6 @@
use crate::build::Builder;
use rustc_middle::mir;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
use rustc_span::{Span, DUMMY_SP};
@ -26,11 +25,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Convenience function for creating a literal operand, one
/// without any user type annotation.
crate fn literal_operand(
&mut self,
span: Span,
literal: mir::ConstantKind<'tcx>,
) -> Operand<'tcx> {
crate fn literal_operand(&mut self, span: Span, literal: ConstantKind<'tcx>) -> Operand<'tcx> {
let constant = Box::new(Constant { span, user_ty: None, literal });
Operand::Constant(constant)
}

View file

@ -1,7 +1,9 @@
use crate::build;
use crate::build::expr::as_place::PlaceBuilder;
use crate::build::scope::DropKind;
use crate::thir::constant::parse_float;
use crate::thir::pattern::pat_from_hir;
use rustc_ast as ast;
use rustc_errors::ErrorGuaranteed;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId};
@ -11,12 +13,15 @@ use rustc_index::vec::{Idx, IndexVec};
use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
use rustc_middle::hir::place::PlaceBase as HirPlaceBase;
use rustc_middle::middle::region;
use rustc_middle::mir::interpret::Allocation;
use rustc_middle::mir::interpret::{ConstValue, LitToConstError, LitToConstInput, Scalar};
use rustc_middle::mir::*;
use rustc_middle::thir::{BindingMode, Expr, ExprId, LintLevel, PatKind, Thir};
use rustc_middle::ty::subst::Subst;
use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeckResults};
use rustc_span::symbol::sym;
use rustc_span::Span;
use rustc_target::abi::Size;
use rustc_target::spec::abi::Abi;
use super::lints;
@ -260,6 +265,57 @@ fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_
})
}
#[instrument(skip(tcx, lit_input))]
pub(crate) fn lit_to_mir_constant<'tcx>(
tcx: TyCtxt<'tcx>,
lit_input: LitToConstInput<'tcx>,
) -> Result<ConstantKind<'tcx>, LitToConstError> {
let LitToConstInput { lit, ty, neg } = lit_input;
let trunc = |n| {
let param_ty = ty::ParamEnv::reveal_all().and(ty);
let width = tcx.layout_of(param_ty).map_err(|_| LitToConstError::Reported)?.size;
trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
let result = width.truncate(n);
trace!("trunc result: {}", result);
Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
};
let value = match (lit, &ty.kind()) {
(ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
let s = s.as_str();
let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
let allocation = tcx.intern_const_alloc(allocation);
ConstValue::Slice { data: allocation, start: 0, end: s.len() }
}
(ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
if matches!(inner_ty.kind(), ty::Slice(_)) =>
{
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
let allocation = tcx.intern_const_alloc(allocation);
ConstValue::Slice { data: allocation, start: 0, end: data.len() }
}
(ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
let id = tcx.allocate_bytes(data);
ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
}
(ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
}
(ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
}
(ast::LitKind::Float(n, _), ty::Float(fty)) => {
parse_float(*n, *fty, neg).ok_or(LitToConstError::Reported)?
}
(ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(*b)),
(ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(*c)),
(ast::LitKind::Err(_), _) => return Err(LitToConstError::Reported),
_ => return Err(LitToConstError::TypeError),
};
Ok(ConstantKind::Val(value, ty))
}
///////////////////////////////////////////////////////////////////////////
// BuildMir -- walks a crate, looking for fn items and methods to build MIR from

View file

@ -27,6 +27,7 @@ use rustc_middle::ty::query::Providers;
pub fn provide(providers: &mut Providers) {
providers.check_match = thir::pattern::check_match;
providers.lit_to_const = thir::constant::lit_to_const;
providers.lit_to_mir_constant = build::lit_to_mir_constant;
providers.mir_built = build::mir_built;
providers.thir_check_unsafety = check_unsafety::thir_check_unsafety;
providers.thir_check_unsafety_for_const_arg = check_unsafety::thir_check_unsafety_for_const_arg;

View file

@ -5,6 +5,7 @@
use crate::thir::pattern::pat_from_hir;
use crate::thir::util::UserAnnotatedTyHelpers;
use rustc_ast as ast;
use rustc_data_structures::steal::Steal;
use rustc_errors::ErrorGuaranteed;
use rustc_hir as hir;
@ -12,8 +13,10 @@ use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::HirId;
use rustc_hir::Node;
use rustc_middle::middle::region;
use rustc_middle::mir::interpret::{LitToConstError, LitToConstInput};
use rustc_middle::mir::ConstantKind;
use rustc_middle::thir::*;
use rustc_middle::ty::{self, TyCtxt};
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::Span;
crate fn thir_body<'tcx>(
@ -75,6 +78,24 @@ impl<'tcx> Cx<'tcx> {
}
}
#[instrument(skip(self), level = "debug")]
crate fn const_eval_literal(
&mut self,
lit: &'tcx ast::LitKind,
ty: Ty<'tcx>,
sp: Span,
neg: bool,
) -> ConstantKind<'tcx> {
match self.tcx.at(sp).lit_to_mir_constant(LitToConstInput { lit, ty, neg }) {
Ok(c) => c,
Err(LitToConstError::Reported) => {
// create a dummy value and continue compiling
ConstantKind::Ty(self.tcx.const_error(ty))
}
Err(LitToConstError::TypeError) => bug!("const_eval_literal: had type error"),
}
}
crate fn pattern_from_hir(&mut self, p: &hir::Pat<'_>) -> Pat<'tcx> {
let p = match self.tcx.hir().get(p.hir_id) {
Node::Pat(p) | Node::Binding(p) => p,

View file

@ -1,7 +1,7 @@
use rustc_hir as hir;
use rustc_index::vec::Idx;
use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
use rustc_middle::mir::Field;
use rustc_middle::mir::{self, Field};
use rustc_middle::thir::{FieldPat, Pat, PatKind};
use rustc_middle::ty::print::with_no_trimmed_paths;
use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
@ -22,7 +22,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
#[instrument(level = "debug", skip(self))]
pub(super) fn const_to_pat(
&self,
cv: ty::Const<'tcx>,
cv: mir::ConstantKind<'tcx>,
id: hir::HirId,
span: Span,
mir_structural_match_violation: bool,
@ -152,7 +152,11 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
ty.is_structural_eq_shallow(self.infcx.tcx)
}
fn to_pat(&mut self, cv: ty::Const<'tcx>, mir_structural_match_violation: bool) -> Pat<'tcx> {
fn to_pat(
&mut self,
cv: mir::ConstantKind<'tcx>,
mir_structural_match_violation: bool,
) -> Pat<'tcx> {
trace!(self.treat_byte_string_as_slice);
// This method is just a wrapper handling a validity check; the heavy lifting is
// performed by the recursive `recur` method, which is not meant to be
@ -246,7 +250,7 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
fn field_pats(
&self,
vals: impl Iterator<Item = ty::Const<'tcx>>,
vals: impl Iterator<Item = mir::ConstantKind<'tcx>>,
) -> Result<Vec<FieldPat<'tcx>>, FallbackToConstRef> {
vals.enumerate()
.map(|(idx, val)| {
@ -257,9 +261,10 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
}
// Recursive helper for `to_pat`; invoke that (instead of calling this directly).
#[instrument(skip(self), level = "debug")]
fn recur(
&self,
cv: ty::Const<'tcx>,
cv: mir::ConstantKind<'tcx>,
mir_structural_match_violation: bool,
) -> Result<Pat<'tcx>, FallbackToConstRef> {
let id = self.id;
@ -365,7 +370,7 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
PatKind::Wild
}
ty::Adt(adt_def, substs) if adt_def.is_enum() => {
let destructured = tcx.destructure_const(param_env.and(cv));
let destructured = tcx.destructure_mir_constant(param_env, cv);
PatKind::Variant {
adt_def: *adt_def,
substs,
@ -376,12 +381,12 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
}
}
ty::Tuple(_) | ty::Adt(_, _) => {
let destructured = tcx.destructure_const(param_env.and(cv));
let destructured = tcx.destructure_mir_constant(param_env, cv);
PatKind::Leaf { subpatterns: self.field_pats(destructured.fields.iter().copied())? }
}
ty::Array(..) => PatKind::Array {
prefix: tcx
.destructure_const(param_env.and(cv))
.destructure_mir_constant(param_env, cv)
.fields
.iter()
.map(|val| self.recur(*val, false))
@ -412,12 +417,12 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
// arrays.
ty::Array(..) if !self.treat_byte_string_as_slice => {
let old = self.behind_reference.replace(true);
let array = tcx.deref_const(self.param_env.and(cv));
let array = tcx.deref_mir_constant(self.param_env.and(cv));
let val = PatKind::Deref {
subpattern: Pat {
kind: Box::new(PatKind::Array {
prefix: tcx
.destructure_const(param_env.and(array))
.destructure_mir_constant(param_env, array)
.fields
.iter()
.map(|val| self.recur(*val, false))
@ -438,12 +443,12 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
// pattern.
ty::Slice(elem_ty) => {
let old = self.behind_reference.replace(true);
let array = tcx.deref_const(self.param_env.and(cv));
let array = tcx.deref_mir_constant(self.param_env.and(cv));
let val = PatKind::Deref {
subpattern: Pat {
kind: Box::new(PatKind::Slice {
prefix: tcx
.destructure_const(param_env.and(array))
.destructure_mir_constant(param_env, array)
.fields
.iter()
.map(|val| self.recur(*val, false))
@ -512,7 +517,7 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
// we fall back to a const pattern. If we do not do this, we may end up with
// a !structural-match constant that is not of reference type, which makes it
// very hard to invoke `PartialEq::eq` on it as a fallback.
let val = match self.recur(tcx.deref_const(self.param_env.and(cv)), false) {
let val = match self.recur(tcx.deref_mir_constant(self.param_env.and(cv)), false) {
Ok(subpattern) => PatKind::Deref { subpattern },
Err(_) => PatKind::Constant { value: cv },
};

View file

@ -52,7 +52,7 @@ use rustc_data_structures::captures::Captures;
use rustc_index::vec::Idx;
use rustc_hir::{HirId, RangeEnd};
use rustc_middle::mir::Field;
use rustc_middle::mir::{self, Field};
use rustc_middle::thir::{FieldPat, Pat, PatKind, PatRange};
use rustc_middle::ty::layout::IntegerExt;
use rustc_middle::ty::{self, Ty, TyCtxt, VariantDef};
@ -133,23 +133,35 @@ impl IntRange {
}
#[inline]
fn from_const<'tcx>(
fn from_constant<'tcx>(
tcx: TyCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
value: ty::Const<'tcx>,
value: mir::ConstantKind<'tcx>,
) -> Option<IntRange> {
let ty = value.ty();
if let Some((target_size, bias)) = Self::integral_size_and_signed_bias(tcx, ty) {
let val = (|| {
if let ty::ConstKind::Value(ConstValue::Scalar(scalar)) = value.val() {
// For this specific pattern we can skip a lot of effort and go
// straight to the result, after doing a bit of checking. (We
// could remove this branch and just fall through, which
// is more general but much slower.)
if let Ok(bits) = scalar.to_bits_or_ptr_internal(target_size).unwrap() {
return Some(bits);
match value {
mir::ConstantKind::Val(ConstValue::Scalar(scalar), _) => {
// For this specific pattern we can skip a lot of effort and go
// straight to the result, after doing a bit of checking. (We
// could remove this branch and just fall through, which
// is more general but much slower.)
if let Ok(Ok(bits)) = scalar.to_bits_or_ptr_internal(target_size) {
return Some(bits);
} else {
return None;
}
}
mir::ConstantKind::Ty(c) => match c.val() {
ty::ConstKind::Value(_) => bug!(
"encountered ConstValue in mir::ConstantKind::Ty, whereas this is expected to be in ConstantKind::Val"
),
_ => {}
},
_ => {}
}
// This is a more general form of the previous case.
value.try_eval_bits(tcx, param_env, ty)
})()?;
@ -234,8 +246,8 @@ impl IntRange {
let (lo, hi) = (lo ^ bias, hi ^ bias);
let env = ty::ParamEnv::empty().and(ty);
let lo_const = ty::Const::from_bits(tcx, lo, env);
let hi_const = ty::Const::from_bits(tcx, hi, env);
let lo_const = mir::ConstantKind::from_bits(tcx, lo, env);
let hi_const = mir::ConstantKind::from_bits(tcx, hi, env);
let kind = if lo == hi {
PatKind::Constant { value: lo_const }
@ -635,9 +647,9 @@ pub(super) enum Constructor<'tcx> {
/// Ranges of integer literal values (`2`, `2..=5` or `2..5`).
IntRange(IntRange),
/// Ranges of floating-point literal values (`2.0..=5.2`).
FloatRange(ty::Const<'tcx>, ty::Const<'tcx>, RangeEnd),
FloatRange(mir::ConstantKind<'tcx>, mir::ConstantKind<'tcx>, RangeEnd),
/// String literals. Strings are not quite the same as `&[u8]` so we treat them separately.
Str(ty::Const<'tcx>),
Str(mir::ConstantKind<'tcx>),
/// Array and slice patterns.
Slice(Slice),
/// Constants that must not be matched structurally. They are treated as black
@ -1376,7 +1388,7 @@ impl<'p, 'tcx> DeconstructedPat<'p, 'tcx> {
}
}
PatKind::Constant { value } => {
if let Some(int_range) = IntRange::from_const(cx.tcx, cx.param_env, *value) {
if let Some(int_range) = IntRange::from_constant(cx.tcx, cx.param_env, *value) {
ctor = IntRange(int_range);
fields = Fields::empty();
} else {

View file

@ -17,7 +17,7 @@ use rustc_hir::RangeEnd;
use rustc_index::vec::Idx;
use rustc_middle::mir::interpret::{get_slice_bytes, ConstValue};
use rustc_middle::mir::interpret::{ErrorHandled, LitToConstError, LitToConstInput};
use rustc_middle::mir::UserTypeProjection;
use rustc_middle::mir::{self, UserTypeProjection};
use rustc_middle::mir::{BorrowKind, Field, Mutability};
use rustc_middle::thir::{Ascription, BindingMode, FieldPat, Pat, PatKind, PatRange, PatTyProj};
use rustc_middle::ty::subst::{GenericArg, SubstsRef};
@ -121,8 +121,8 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
fn lower_pattern_range(
&mut self,
ty: Ty<'tcx>,
lo: ty::Const<'tcx>,
hi: ty::Const<'tcx>,
lo: mir::ConstantKind<'tcx>,
hi: mir::ConstantKind<'tcx>,
end: RangeEnd,
span: Span,
) -> PatKind<'tcx> {
@ -177,16 +177,18 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
ty: Ty<'tcx>,
lo: Option<&PatKind<'tcx>>,
hi: Option<&PatKind<'tcx>>,
) -> Option<(ty::Const<'tcx>, ty::Const<'tcx>)> {
) -> Option<(mir::ConstantKind<'tcx>, mir::ConstantKind<'tcx>)> {
match (lo, hi) {
(Some(PatKind::Constant { value: lo }), Some(PatKind::Constant { value: hi })) => {
Some((*lo, *hi))
}
(Some(PatKind::Constant { value: lo }), None) => {
Some((*lo, ty.numeric_max_val(self.tcx)?))
let hi = ty.numeric_max_val(self.tcx)?;
Some((*lo, hi.into()))
}
(None, Some(PatKind::Constant { value: hi })) => {
Some((ty.numeric_min_val(self.tcx)?, *hi))
let lo = ty.numeric_min_val(self.tcx)?;
Some((lo.into(), *hi))
}
_ => None,
}
@ -446,6 +448,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
/// Takes a HIR Path. If the path is a constant, evaluates it and feeds
/// it to `const_to_pat`. Any other path (like enum variants without fields)
/// is converted to the corresponding pattern via `lower_variant_or_leaf`.
#[instrument(skip(self), level = "debug")]
fn lower_path(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, span: Span) -> Pat<'tcx> {
let ty = self.typeck_results.node_type(id);
let res = self.typeck_results.qpath_res(qpath, id);
@ -487,8 +490,8 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
debug!("mir_structural_match_violation({:?}) -> {}", qpath, mir_structural_match_violation);
match self.tcx.const_eval_instance(param_env_reveal_all, instance, Some(span)) {
Ok(value) => {
let const_ = ty::Const::from_value(self.tcx, value, ty);
Ok(literal) => {
let const_ = mir::ConstantKind::Val(literal, ty);
let pattern = self.const_to_pat(const_, id, span, mir_structural_match_violation);
if !is_associated_const {
@ -537,25 +540,30 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
span: Span,
) -> PatKind<'tcx> {
let anon_const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id);
let value = ty::Const::from_inline_const(self.tcx, anon_const_def_id);
let value = mir::ConstantKind::from_inline_const(self.tcx, anon_const_def_id);
// Evaluate early like we do in `lower_path`.
let value = value.eval(self.tcx, self.param_env);
match value.val() {
ConstKind::Param(_) => {
self.errors.push(PatternError::ConstParamInPattern(span));
return PatKind::Wild;
match value {
mir::ConstantKind::Ty(c) => {
match c.val() {
ConstKind::Param(_) => {
self.errors.push(PatternError::ConstParamInPattern(span));
return PatKind::Wild;
}
ConstKind::Unevaluated(_) => {
// If we land here it means the const can't be evaluated because it's `TooGeneric`.
self.tcx
.sess
.span_err(span, "constant pattern depends on a generic parameter");
return PatKind::Wild;
}
_ => bug!("Expected either ConstKind::Param or ConstKind::Unevaluated"),
}
}
ConstKind::Unevaluated(_) => {
// If we land here it means the const can't be evaluated because it's `TooGeneric`.
self.tcx.sess.span_err(span, "constant pattern depends on a generic parameter");
return PatKind::Wild;
}
_ => (),
mir::ConstantKind::Val(_, _) => *self.const_to_pat(value, id, span, false).kind,
}
*self.const_to_pat(value, id, span, false).kind
}
/// Converts literals, paths and negation of literals to patterns.
@ -582,7 +590,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
let lit_input =
LitToConstInput { lit: &lit.node, ty: self.typeck_results.expr_ty(expr), neg };
match self.tcx.at(expr.span).lit_to_const(lit_input) {
match self.tcx.at(expr.span).lit_to_mir_constant(lit_input) {
Ok(constant) => *self.const_to_pat(constant, expr.hir_id, lit.span, false).kind,
Err(LitToConstError::Reported) => PatKind::Wild,
Err(LitToConstError::TypeError) => bug!("lower_lit: had type error"),
@ -740,8 +748,8 @@ impl<'tcx> PatternFoldable<'tcx> for PatKind<'tcx> {
#[instrument(skip(tcx), level = "debug")]
crate fn compare_const_vals<'tcx>(
tcx: TyCtxt<'tcx>,
a: ty::Const<'tcx>,
b: ty::Const<'tcx>,
a: mir::ConstantKind<'tcx>,
b: mir::ConstantKind<'tcx>,
param_env: ty::ParamEnv<'tcx>,
ty: Ty<'tcx>,
) -> Option<Ordering> {
@ -754,9 +762,7 @@ crate fn compare_const_vals<'tcx>(
return fallback();
}
// Early return for equal constants (so e.g. references to ZSTs can be compared, even if they
// are just integer addresses).
if a.val() == b.val() {
if a == b {
return from_bool(true);
}
@ -788,9 +794,9 @@ crate fn compare_const_vals<'tcx>(
}
if let ty::Str = ty.kind() && let (
ty::ConstKind::Value(a_val @ ConstValue::Slice { .. }),
ty::ConstKind::Value(b_val @ ConstValue::Slice { .. }),
) = (a.val(), b.val())
Some(a_val @ ConstValue::Slice { .. }),
Some(b_val @ ConstValue::Slice { .. }),
) = (a.try_val(), b.try_val())
{
let a_bytes = get_slice_bytes(&tcx, a_val);
let b_bytes = get_slice_bytes(&tcx, b_val);