1
Fork 0

do use ty::Const in patterns and abstract consts

This commit is contained in:
b-naber 2022-03-09 13:56:12 +01:00
parent b38077ea0b
commit ac60db231c
15 changed files with 105 additions and 127 deletions

View file

@ -661,7 +661,7 @@ pub enum PatKind<'tcx> {
/// * Opaque constants, that must not be matched structurally. So anything that does not derive /// * Opaque constants, that must not be matched structurally. So anything that does not derive
/// `PartialEq` and `Eq`. /// `PartialEq` and `Eq`.
Constant { Constant {
value: mir::ConstantKind<'tcx>, value: ty::Const<'tcx>,
}, },
Range(PatRange<'tcx>), Range(PatRange<'tcx>),
@ -691,8 +691,8 @@ pub enum PatKind<'tcx> {
#[derive(Copy, Clone, Debug, PartialEq, HashStable)] #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
pub struct PatRange<'tcx> { pub struct PatRange<'tcx> {
pub lo: mir::ConstantKind<'tcx>, pub lo: ty::Const<'tcx>,
pub hi: mir::ConstantKind<'tcx>, pub hi: ty::Const<'tcx>,
pub end: RangeEnd, pub end: RangeEnd,
} }
@ -736,7 +736,11 @@ impl<'tcx> fmt::Display for Pat<'tcx> {
Some(adt_def.variant(variant_index)) Some(adt_def.variant(variant_index))
} }
_ => self.ty.ty_adt_def().and_then(|adt| { _ => self.ty.ty_adt_def().and_then(|adt| {
if !adt.is_enum() { Some(adt.non_enum_variant()) } else { None } if !adt.is_enum() {
Some(adt.non_enum_variant())
} else {
None
}
}), }),
}; };

View file

@ -22,7 +22,7 @@ pub enum CastKind {
/// A node of an `AbstractConst`. /// A node of an `AbstractConst`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)] #[derive(Debug, Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
pub enum Node<'tcx> { pub enum Node<'tcx> {
Leaf(mir::ConstantKind<'tcx>), Leaf(ty::Const<'tcx>),
Binop(mir::BinOp, NodeId, NodeId), Binop(mir::BinOp, NodeId, NodeId),
UnaryOp(mir::UnOp, NodeId), UnaryOp(mir::UnOp, NodeId),
FunctionCall(NodeId, &'tcx [NodeId]), FunctionCall(NodeId, &'tcx [NodeId]),

View file

@ -94,13 +94,8 @@ pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Exp
visitor.visit_expr(&visitor.thir()[value]) visitor.visit_expr(&visitor.thir()[value])
} }
} }
<<<<<<< HEAD
ConstBlock { did: _, substs: _ } => {} ConstBlock { did: _, substs: _ } => {}
Repeat { value, count: _ } => { Repeat { value, count: _ } => {
=======
ConstBlock { value } => visitor.visit_constant(value),
Repeat { value, count } => {
>>>>>>> 6064f16d846 (change thir to use mir::ConstantKind instead of ty::Const)
visitor.visit_expr(&visitor.thir()[value]); visitor.visit_expr(&visitor.thir()[value]);
} }
Array { ref fields } | Tuple { ref fields } => { Array { ref fields } | Tuple { ref fields } => {

View file

@ -76,7 +76,11 @@ static_assert_size!(ConstKind<'_>, 40);
impl<'tcx> ConstKind<'tcx> { impl<'tcx> ConstKind<'tcx> {
#[inline] #[inline]
pub fn try_to_value(self) -> Option<ConstValue<'tcx>> { pub fn try_to_value(self) -> Option<ConstValue<'tcx>> {
if let ConstKind::Value(val) = self { Some(val) } else { None } if let ConstKind::Value(val) = self {
Some(val)
} else {
None
}
} }
#[inline] #[inline]
@ -126,6 +130,7 @@ impl<'tcx> ConstKind<'tcx> {
#[inline] #[inline]
/// Tries to evaluate the constant if it is `Unevaluated`. If that isn't possible or necessary /// Tries to evaluate the constant if it is `Unevaluated`. If that isn't possible or necessary
/// return `None`. /// return `None`.
// FIXME(@lcnr): Completely rework the evaluation/normalization system for `ty::Const` once valtrees are merged.
pub fn try_eval( pub fn try_eval(
self, self,
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,

View file

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

View file

@ -228,7 +228,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
_ => (None, 0), _ => (None, 0),
}; };
if let Some((min, max, sz)) = range { if let Some((min, max, sz)) = range {
if let (Some(lo), Some(hi)) = (lo.try_to_bits(sz), hi.try_to_bits(sz)) { if let (Some(lo), Some(hi)) =
(lo.val().try_to_bits(sz), hi.val().try_to_bits(sz))
{
// We want to compare ranges numerically, but the order of the bitwise // We want to compare ranges numerically, but the order of the bitwise
// representation of signed integers does not match their numeric order. // representation of signed integers does not match their numeric order.
// Thus, to correct the ordering, we need to shift the range of signed // 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>, test_place: &PlaceBuilder<'tcx>,
candidate: &Candidate<'pat, 'tcx>, candidate: &Candidate<'pat, 'tcx>,
switch_ty: Ty<'tcx>, switch_ty: Ty<'tcx>,
options: &mut FxIndexMap<ConstantKind<'tcx>, u128>, options: &mut FxIndexMap<ty::Const<'tcx>, u128>,
) -> bool { ) -> bool {
let Some(match_pair) = candidate.match_pairs.iter().find(|mp| mp.place == *test_place) else { let Some(match_pair) = candidate.match_pairs.iter().find(|mp| mp.place == *test_place) else {
return false; return false;
@ -264,7 +264,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
); );
} else if let [success, fail] = *make_target_blocks(self) { } else if let [success, fail] = *make_target_blocks(self) {
assert_eq!(value.ty(), ty); assert_eq!(value.ty(), ty);
let expect = self.literal_operand(test.span, value); let expect = self.literal_operand(test.span, value.into());
let val = Operand::Copy(place); let val = Operand::Copy(place);
self.compare(block, success, fail, source_info, BinOp::Eq, expect, val); self.compare(block, success, fail, source_info, BinOp::Eq, expect, val);
} else { } else {
@ -277,8 +277,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
let target_blocks = make_target_blocks(self); let target_blocks = make_target_blocks(self);
// Test `val` by computing `lo <= val && val <= hi`, using primitive comparisons. // Test `val` by computing `lo <= val && val <= hi`, using primitive comparisons.
let lo = self.literal_operand(test.span, lo); let lo = self.literal_operand(test.span, lo.into());
let hi = self.literal_operand(test.span, hi); let hi = self.literal_operand(test.span, hi.into());
let val = Operand::Copy(place); let val = Operand::Copy(place);
let [success, fail] = *target_blocks else { let [success, fail] = *target_blocks else {
@ -366,11 +366,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
block: BasicBlock, block: BasicBlock,
make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>, make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>,
source_info: SourceInfo, source_info: SourceInfo,
value: ConstantKind<'tcx>, value: ty::Const<'tcx>,
place: Place<'tcx>, place: Place<'tcx>,
mut ty: Ty<'tcx>, mut ty: Ty<'tcx>,
) { ) {
let mut expect = self.literal_operand(source_info.span, value); let mut expect = self.literal_operand(source_info.span, value.into());
let mut val = Operand::Copy(place); let mut val = Operand::Copy(place);
// If we're using `b"..."` as a pattern, we need to insert an // If we're using `b"..."` as a pattern, we need to insert an
@ -760,11 +760,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
span_bug!(match_pair.pattern.span, "simplifyable pattern found: {:?}", match_pair.pattern) span_bug!(match_pair.pattern.span, "simplifyable pattern found: {:?}", match_pair.pattern)
} }
fn const_range_contains( fn const_range_contains(&self, range: PatRange<'tcx>, value: ty::Const<'tcx>) -> Option<bool> {
&self,
range: PatRange<'tcx>,
value: ConstantKind<'tcx>,
) -> Option<bool> {
use std::cmp::Ordering::*; use std::cmp::Ordering::*;
let tcx = self.tcx; let tcx = self.tcx;
@ -781,7 +777,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
fn values_not_contained_in_range( fn values_not_contained_in_range(
&self, &self,
range: PatRange<'tcx>, range: PatRange<'tcx>,
options: &FxIndexMap<ConstantKind<'tcx>, u128>, options: &FxIndexMap<ty::Const<'tcx>, u128>,
) -> Option<bool> { ) -> Option<bool> {
for &val in options.keys() { for &val in options.keys() {
if self.const_range_contains(range, val)? { if self.const_range_contains(range, val)? {

View file

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

View file

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

View file

@ -52,7 +52,7 @@ use rustc_data_structures::captures::Captures;
use rustc_index::vec::Idx; use rustc_index::vec::Idx;
use rustc_hir::{HirId, RangeEnd}; use rustc_hir::{HirId, RangeEnd};
use rustc_middle::mir::{self, Field}; use rustc_middle::mir::Field;
use rustc_middle::thir::{FieldPat, Pat, PatKind, PatRange}; use rustc_middle::thir::{FieldPat, Pat, PatKind, PatRange};
use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::layout::IntegerExt;
use rustc_middle::ty::{self, Ty, TyCtxt, VariantDef}; use rustc_middle::ty::{self, Ty, TyCtxt, VariantDef};
@ -136,30 +136,20 @@ impl IntRange {
fn from_const<'tcx>( fn from_const<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>, param_env: ty::ParamEnv<'tcx>,
value: mir::ConstantKind<'tcx>, value: ty::Const<'tcx>,
) -> Option<IntRange> { ) -> Option<IntRange> {
let ty = value.ty(); let ty = value.ty();
if let Some((target_size, bias)) = Self::integral_size_and_signed_bias(tcx, ty) { if let Some((target_size, bias)) = Self::integral_size_and_signed_bias(tcx, ty) {
let val = (|| { let val = (|| {
match value { if let ty::ConstKind::Value(ConstValue::Scalar(scalar)) = value.val() {
mir::ConstantKind::Val(ConstValue::Scalar(scalar), _) => { // For this specific pattern we can skip a lot of effort and go
// For this specific pattern we can skip a lot of effort and go // straight to the result, after doing a bit of checking. (We
// straight to the result, after doing a bit of checking. (We // could remove this branch and just fall through, which
// could remove this branch and just fall through, which // is more general but much slower.)
// is more general but much slower.) if let Ok(bits) = scalar.to_bits_or_ptr_internal(target_size) {
if let Ok(bits) = scalar.to_bits_or_ptr_internal(target_size) { return Some(bits);
return Some(bits);
}
} }
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. // This is a more general form of the previous case.
value.try_eval_bits(tcx, param_env, ty) value.try_eval_bits(tcx, param_env, ty)
})()?; })()?;
@ -244,8 +234,8 @@ impl IntRange {
let (lo, hi) = (lo ^ bias, hi ^ bias); let (lo, hi) = (lo ^ bias, hi ^ bias);
let env = ty::ParamEnv::empty().and(ty); let env = ty::ParamEnv::empty().and(ty);
let lo_const = mir::ConstantKind::from_bits(tcx, lo, env); let lo_const = ty::Const::from_bits(tcx, lo, env);
let hi_const = mir::ConstantKind::from_bits(tcx, hi, env); let hi_const = ty::Const::from_bits(tcx, hi, env);
let kind = if lo == hi { let kind = if lo == hi {
PatKind::Constant { value: lo_const } PatKind::Constant { value: lo_const }
@ -640,9 +630,9 @@ pub(super) enum Constructor<'tcx> {
/// Ranges of integer literal values (`2`, `2..=5` or `2..5`). /// Ranges of integer literal values (`2`, `2..=5` or `2..5`).
IntRange(IntRange), IntRange(IntRange),
/// Ranges of floating-point literal values (`2.0..=5.2`). /// Ranges of floating-point literal values (`2.0..=5.2`).
FloatRange(mir::ConstantKind<'tcx>, mir::ConstantKind<'tcx>, RangeEnd), FloatRange(ty::Const<'tcx>, ty::Const<'tcx>, RangeEnd),
/// String literals. Strings are not quite the same as `&[u8]` so we treat them separately. /// String literals. Strings are not quite the same as `&[u8]` so we treat them separately.
Str(mir::ConstantKind<'tcx>), Str(ty::Const<'tcx>),
/// Array and slice patterns. /// Array and slice patterns.
Slice(Slice), Slice(Slice),
/// Constants that must not be matched structurally. They are treated as black /// Constants that must not be matched structurally. They are treated as black
@ -839,7 +829,8 @@ impl<'tcx> Constructor<'tcx> {
} }
} }
(Str(self_val), Str(other_val)) => { (Str(self_val), Str(other_val)) => {
// FIXME: there's probably a more direct way of comparing for equality // FIXME Once valtrees are available we can directly use the bytes
// in the `Str` variant of the valtree for the comparison here.
match compare_const_vals( match compare_const_vals(
pcx.cx.tcx, pcx.cx.tcx,
*self_val, *self_val,

View file

@ -17,7 +17,7 @@ use rustc_hir::RangeEnd;
use rustc_index::vec::Idx; use rustc_index::vec::Idx;
use rustc_middle::mir::interpret::{get_slice_bytes, ConstValue}; use rustc_middle::mir::interpret::{get_slice_bytes, ConstValue};
use rustc_middle::mir::interpret::{ErrorHandled, LitToConstError, LitToConstInput}; use rustc_middle::mir::interpret::{ErrorHandled, LitToConstError, LitToConstInput};
use rustc_middle::mir::{self, UserTypeProjection}; use rustc_middle::mir::UserTypeProjection;
use rustc_middle::mir::{BorrowKind, Field, Mutability}; use rustc_middle::mir::{BorrowKind, Field, Mutability};
use rustc_middle::thir::{Ascription, BindingMode, FieldPat, Pat, PatKind, PatRange, PatTyProj}; use rustc_middle::thir::{Ascription, BindingMode, FieldPat, Pat, PatKind, PatRange, PatTyProj};
use rustc_middle::ty::subst::{GenericArg, SubstsRef}; use rustc_middle::ty::subst::{GenericArg, SubstsRef};
@ -121,8 +121,8 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
fn lower_pattern_range( fn lower_pattern_range(
&mut self, &mut self,
ty: Ty<'tcx>, ty: Ty<'tcx>,
lo: mir::ConstantKind<'tcx>, lo: ty::Const<'tcx>,
hi: mir::ConstantKind<'tcx>, hi: ty::Const<'tcx>,
end: RangeEnd, end: RangeEnd,
span: Span, span: Span,
) -> PatKind<'tcx> { ) -> PatKind<'tcx> {
@ -177,24 +177,18 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
ty: Ty<'tcx>, ty: Ty<'tcx>,
lo: Option<&PatKind<'tcx>>, lo: Option<&PatKind<'tcx>>,
hi: Option<&PatKind<'tcx>>, hi: Option<&PatKind<'tcx>>,
) -> Option<(mir::ConstantKind<'tcx>, mir::ConstantKind<'tcx>)> { ) -> Option<(ty::Const<'tcx>, ty::Const<'tcx>)> {
match (lo, hi) { match (lo, hi) {
(Some(PatKind::Constant { value: lo }), Some(PatKind::Constant { value: hi })) => { (Some(PatKind::Constant { value: lo }), Some(PatKind::Constant { value: hi })) => {
Some((*lo, *hi)) Some((*lo, *hi))
} }
(Some(PatKind::Constant { value: lo }), None) => { (Some(PatKind::Constant { value: lo }), None) => {
let hi = ty.numeric_max_val(self.tcx)?; let hi = ty.numeric_max_val(self.tcx)?;
Some(( Some((*lo, ty::Const::from_bits(self.tcx, hi, ty::ParamEnv::empty().and(ty))))
*lo,
mir::ConstantKind::from_bits(self.tcx, hi, ty::ParamEnv::empty().and(ty)),
))
} }
(None, Some(PatKind::Constant { value: hi })) => { (None, Some(PatKind::Constant { value: hi })) => {
let lo = ty.numeric_min_val(self.tcx)?; let lo = ty.numeric_min_val(self.tcx)?;
Some(( Some((ty::Const::from_bits(self.tcx, lo, ty::ParamEnv::empty().and(ty)), *hi))
mir::ConstantKind::from_bits(self.tcx, lo, ty::ParamEnv::empty().and(ty)),
*hi,
))
} }
_ => None, _ => None,
} }
@ -496,7 +490,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
match self.tcx.const_eval_instance(param_env_reveal_all, instance, Some(span)) { match self.tcx.const_eval_instance(param_env_reveal_all, instance, Some(span)) {
Ok(value) => { Ok(value) => {
let const_ = mir::ConstantKind::Val(value, ty); let const_ = ty::Const::from_value(self.tcx, value, ty);
let pattern = self.const_to_pat(const_, id, span, mir_structural_match_violation); let pattern = self.const_to_pat(const_, id, span, mir_structural_match_violation);
if !is_associated_const { if !is_associated_const {
@ -545,30 +539,25 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
span: Span, span: Span,
) -> PatKind<'tcx> { ) -> PatKind<'tcx> {
let anon_const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id); let anon_const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id);
let value = mir::ConstantKind::from_inline_const(self.tcx, anon_const_def_id); let value = ty::Const::from_inline_const(self.tcx, anon_const_def_id);
// Evaluate early like we do in `lower_path`. // Evaluate early like we do in `lower_path`.
let value = value.eval(self.tcx, self.param_env); let value = value.eval(self.tcx, self.param_env);
match value { match value.val() {
mir::ConstantKind::Ty(c) => { ConstKind::Param(_) => {
match c.val() { self.errors.push(PatternError::ConstParamInPattern(span));
ConstKind::Param(_) => { return PatKind::Wild;
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"),
}
} }
mir::ConstantKind::Val(_, _) => *self.const_to_pat(value, id, span, false).kind, 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;
}
_ => (),
} }
*self.const_to_pat(value, id, span, false).kind
} }
/// Converts literals, paths and negation of literals to patterns. /// Converts literals, paths and negation of literals to patterns.
@ -595,7 +584,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
let lit_input = let lit_input =
LitToConstInput { lit: &lit.node, ty: self.typeck_results.expr_ty(expr), neg }; LitToConstInput { lit: &lit.node, ty: self.typeck_results.expr_ty(expr), neg };
match self.tcx.at(expr.span).lit_to_mir_constant(lit_input) { match self.tcx.at(expr.span).lit_to_const(lit_input) {
Ok(constant) => *self.const_to_pat(constant, expr.hir_id, lit.span, false).kind, Ok(constant) => *self.const_to_pat(constant, expr.hir_id, lit.span, false).kind,
Err(LitToConstError::Reported) => PatKind::Wild, Err(LitToConstError::Reported) => PatKind::Wild,
Err(LitToConstError::TypeError) => bug!("lower_lit: had type error"), Err(LitToConstError::TypeError) => bug!("lower_lit: had type error"),
@ -750,11 +739,12 @@ impl<'tcx> PatternFoldable<'tcx> for PatKind<'tcx> {
} }
} }
// FIXME: Get rid of this function once valtrees land
#[instrument(skip(tcx), level = "debug")] #[instrument(skip(tcx), level = "debug")]
crate fn compare_const_vals<'tcx>( crate fn compare_const_vals<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
a: mir::ConstantKind<'tcx>, a: ty::Const<'tcx>,
b: mir::ConstantKind<'tcx>, b: ty::Const<'tcx>,
param_env: ty::ParamEnv<'tcx>, param_env: ty::ParamEnv<'tcx>,
ty: Ty<'tcx>, ty: Ty<'tcx>,
) -> Option<Ordering> { ) -> Option<Ordering> {

View file

@ -765,10 +765,7 @@ fn lint_non_exhaustive_omitted_patterns<'p, 'tcx>(
/// `is_under_guard` is used to inform if the pattern has a guard. If it /// `is_under_guard` is used to inform if the pattern has a guard. If it
/// has one it must not be inserted into the matrix. This shouldn't be /// has one it must not be inserted into the matrix. This shouldn't be
/// relied on for soundness. /// relied on for soundness.
#[instrument( #[instrument(level = "debug", skip(cx, matrix, hir_id))]
level = "debug",
skip(cx, matrix, witness_preference, hir_id, is_under_guard, is_top_level)
)]
fn is_useful<'p, 'tcx>( fn is_useful<'p, 'tcx>(
cx: &MatchCheckCtxt<'p, 'tcx>, cx: &MatchCheckCtxt<'p, 'tcx>,
matrix: &Matrix<'p, 'tcx>, matrix: &Matrix<'p, 'tcx>,
@ -800,6 +797,7 @@ fn is_useful<'p, 'tcx>(
let ty = v.head().ty(); let ty = v.head().ty();
let is_non_exhaustive = cx.is_foreign_non_exhaustive_enum(ty); let is_non_exhaustive = cx.is_foreign_non_exhaustive_enum(ty);
debug!("v.head: {:?}, v.span: {:?}", v.head(), v.head().span());
let pcx = PatCtxt { cx, ty, span: v.head().span(), is_top_level, is_non_exhaustive }; let pcx = PatCtxt { cx, ty, span: v.head().span(), is_top_level, is_non_exhaustive };
// If the first pattern is an or-pattern, expand it. // If the first pattern is an or-pattern, expand it.
@ -809,9 +807,11 @@ fn is_useful<'p, 'tcx>(
// We try each or-pattern branch in turn. // We try each or-pattern branch in turn.
let mut matrix = matrix.clone(); let mut matrix = matrix.clone();
for v in v.expand_or_pat() { for v in v.expand_or_pat() {
debug!(?v);
let usefulness = ensure_sufficient_stack(|| { let usefulness = ensure_sufficient_stack(|| {
is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false) is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false)
}); });
debug!(?usefulness);
ret.extend(usefulness); ret.extend(usefulness);
// If pattern has a guard don't add it to the matrix. // If pattern has a guard don't add it to the matrix.
if !is_under_guard { if !is_under_guard {
@ -822,6 +822,7 @@ fn is_useful<'p, 'tcx>(
} }
} else { } else {
let v_ctor = v.head().ctor(); let v_ctor = v.head().ctor();
debug!(?v_ctor);
if let Constructor::IntRange(ctor_range) = &v_ctor { if let Constructor::IntRange(ctor_range) = &v_ctor {
// Lint on likely incorrect range patterns (#63987) // Lint on likely incorrect range patterns (#63987)
ctor_range.lint_overlapping_range_endpoints( ctor_range.lint_overlapping_range_endpoints(
@ -895,7 +896,7 @@ fn is_useful<'p, 'tcx>(
} }
/// The arm of a match expression. /// The arm of a match expression.
#[derive(Clone, Copy)] #[derive(Clone, Copy, Debug)]
crate struct MatchArm<'p, 'tcx> { crate struct MatchArm<'p, 'tcx> {
/// The pattern must have been lowered through `check_match::MatchVisitor::lower_pattern`. /// The pattern must have been lowered through `check_match::MatchVisitor::lower_pattern`.
crate pat: &'p DeconstructedPat<'p, 'tcx>, crate pat: &'p DeconstructedPat<'p, 'tcx>,
@ -928,6 +929,7 @@ crate struct UsefulnessReport<'p, 'tcx> {
/// ///
/// Note: the input patterns must have been lowered through /// Note: the input patterns must have been lowered through
/// `check_match::MatchVisitor::lower_pattern`. /// `check_match::MatchVisitor::lower_pattern`.
#[instrument(skip(cx, arms), level = "debug")]
crate fn compute_match_usefulness<'p, 'tcx>( crate fn compute_match_usefulness<'p, 'tcx>(
cx: &MatchCheckCtxt<'p, 'tcx>, cx: &MatchCheckCtxt<'p, 'tcx>,
arms: &[MatchArm<'p, 'tcx>], arms: &[MatchArm<'p, 'tcx>],
@ -939,6 +941,7 @@ crate fn compute_match_usefulness<'p, 'tcx>(
.iter() .iter()
.copied() .copied()
.map(|arm| { .map(|arm| {
debug!(?arm);
let v = PatStack::from_pattern(arm.pat); let v = PatStack::from_pattern(arm.pat);
is_useful(cx, &matrix, &v, RealArm, arm.hir_id, arm.has_guard, true); is_useful(cx, &matrix, &v, RealArm, arm.hir_id, arm.has_guard, true);
if !arm.has_guard { if !arm.has_guard {

View file

@ -19,7 +19,6 @@ use rustc_hir::{AssocItemKind, HirIdSet, Node, PatKind};
use rustc_middle::bug; use rustc_middle::bug;
use rustc_middle::hir::nested_filter; use rustc_middle::hir::nested_filter;
use rustc_middle::middle::privacy::{AccessLevel, AccessLevels}; use rustc_middle::middle::privacy::{AccessLevel, AccessLevels};
use rustc_middle::mir::ConstantKind;
use rustc_middle::span_bug; use rustc_middle::span_bug;
use rustc_middle::thir::abstract_const::Node as ACNode; use rustc_middle::thir::abstract_const::Node as ACNode;
use rustc_middle::ty::fold::TypeVisitor; use rustc_middle::ty::fold::TypeVisitor;
@ -157,10 +156,7 @@ where
ct: AbstractConst<'tcx>, ct: AbstractConst<'tcx>,
) -> ControlFlow<V::BreakTy> { ) -> ControlFlow<V::BreakTy> {
const_evaluatable::walk_abstract_const(tcx, ct, |node| match node.root(tcx) { const_evaluatable::walk_abstract_const(tcx, ct, |node| match node.root(tcx) {
ACNode::Leaf(leaf) => match leaf { ACNode::Leaf(leaf) => self.visit_const(leaf),
ConstantKind::Ty(c) => self.visit_const(c),
ConstantKind::Val(_, ty) => self.visit_ty(ty),
},
ACNode::Cast(_, _, ty) => self.visit_ty(ty), ACNode::Cast(_, _, ty) => self.visit_ty(ty),
ACNode::Binop(..) | ACNode::UnaryOp(..) | ACNode::FunctionCall(_, _) => { ACNode::Binop(..) | ACNode::UnaryOp(..) | ACNode::FunctionCall(_, _) => {
ControlFlow::CONTINUE ControlFlow::CONTINUE
@ -288,7 +284,7 @@ where
fn visit_const(&mut self, c: Const<'tcx>) -> ControlFlow<Self::BreakTy> { fn visit_const(&mut self, c: Const<'tcx>) -> ControlFlow<Self::BreakTy> {
self.visit_ty(c.ty())?; self.visit_ty(c.ty())?;
let tcx = self.def_id_visitor.tcx(); let tcx = self.def_id_visitor.tcx();
if let Ok(Some(ct)) = AbstractConst::from_constant(tcx, ConstantKind::Ty(c)) { if let Ok(Some(ct)) = AbstractConst::from_const(tcx, c) {
self.visit_abstract_const_expr(tcx, ct)?; self.visit_abstract_const_expr(tcx, ct)?;
} }
ControlFlow::CONTINUE ControlFlow::CONTINUE

View file

@ -37,14 +37,9 @@ pub fn is_const_evaluatable<'cx, 'tcx>(
param_env: ty::ParamEnv<'tcx>, param_env: ty::ParamEnv<'tcx>,
span: Span, span: Span,
) -> Result<(), NotConstEvaluatable> { ) -> Result<(), NotConstEvaluatable> {
<<<<<<< HEAD
let tcx = infcx.tcx; let tcx = infcx.tcx;
if tcx.features().generic_const_exprs { if tcx.features().generic_const_exprs {
=======
if infcx.tcx.features().generic_const_exprs {
let tcx = infcx.tcx;
>>>>>>> 6064f16d846 (change thir to use mir::ConstantKind instead of ty::Const)
match AbstractConst::new(tcx, uv)? { match AbstractConst::new(tcx, uv)? {
// We are looking at a generic abstract constant. // We are looking at a generic abstract constant.
Some(ct) => { Some(ct) => {
@ -249,7 +244,7 @@ impl<'tcx> AbstractConst<'tcx> {
Ok(inner.map(|inner| AbstractConst { inner, substs: uv.substs })) Ok(inner.map(|inner| AbstractConst { inner, substs: uv.substs }))
} }
pub fn from_constant( pub fn from_const(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
ct: ty::Const<'tcx>, ct: ty::Const<'tcx>,
) -> Result<Option<AbstractConst<'tcx>>, ErrorGuaranteed> { ) -> Result<Option<AbstractConst<'tcx>>, ErrorGuaranteed> {
@ -382,6 +377,10 @@ impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
} }
} }
fn visit_const(&mut self, ct: ty::Const<'tcx>) {
self.is_poly |= ct.has_param_types_or_consts();
}
fn visit_constant(&mut self, ct: mir::ConstantKind<'tcx>) { fn visit_constant(&mut self, ct: mir::ConstantKind<'tcx>) {
self.is_poly |= ct.has_param_types_or_consts(); self.is_poly |= ct.has_param_types_or_consts();
} }
@ -423,10 +422,10 @@ impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
self.recurse_build(self.body_id)?; self.recurse_build(self.body_id)?;
for n in self.nodes.iter() { for n in self.nodes.iter() {
if let Node::Leaf(mir::ConstantKind::Ty(ty::Const(Interned( if let Node::Leaf(ty::Const(Interned(
ty::ConstS { val: ty::ConstKind::Unevaluated(ct), ty: _ }, ty::ConstS { val: ty::ConstKind::Unevaluated(ct), ty: _ },
_, _,
)))) = n ))) = n
{ {
// `AbstractConst`s should not contain any promoteds as they require references which // `AbstractConst`s should not contain any promoteds as they require references which
// are not allowed. // are not allowed.
@ -863,4 +862,4 @@ impl<'tcx> ConstUnifyCtxt<'tcx> {
false false
>>>>>>> 6064f16d846 (change thir to use mir::ConstantKind instead of ty::Const) >>>>>>> 6064f16d846 (change thir to use mir::ConstantKind instead of ty::Const)
*/ */

View file

@ -17,7 +17,6 @@ use crate::traits::{self, Obligation, ObligationCause};
use rustc_errors::FatalError; use rustc_errors::FatalError;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_middle::mir::ConstantKind;
use rustc_middle::ty::subst::{GenericArg, InternalSubsts, Subst}; use rustc_middle::ty::subst::{GenericArg, InternalSubsts, Subst};
use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeVisitor}; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeVisitor};
use rustc_middle::ty::{Predicate, ToPredicate}; use rustc_middle::ty::{Predicate, ToPredicate};
@ -837,10 +836,7 @@ fn contains_illegal_self_type_reference<'tcx, T: TypeFoldable<'tcx>>(
if let Ok(Some(ct)) = AbstractConst::new(self.tcx, uv.shrink()) { if let Ok(Some(ct)) = AbstractConst::new(self.tcx, uv.shrink()) {
const_evaluatable::walk_abstract_const(self.tcx, ct, |node| { const_evaluatable::walk_abstract_const(self.tcx, ct, |node| {
match node.root(self.tcx) { match node.root(self.tcx) {
Node::Leaf(leaf) => match leaf { Node::Leaf(leaf) => self.visit_const(leaf),
ConstantKind::Ty(c) => self.visit_const(c),
ConstantKind::Val(_, ty) => self.visit_ty(ty),
},
Node::Cast(_, _, ty) => self.visit_ty(ty), Node::Cast(_, _, ty) => self.visit_ty(ty),
Node::Binop(..) | Node::UnaryOp(..) | Node::FunctionCall(_, _) => { Node::Binop(..) | Node::UnaryOp(..) | Node::FunctionCall(_, _) => {
ControlFlow::CONTINUE ControlFlow::CONTINUE