Skip to content

Commit b39c019

Browse files
committed
pattern testing: store constants as valtrees
1 parent ebe74a2 commit b39c019

File tree

10 files changed

+106
-120
lines changed

10 files changed

+106
-120
lines changed

compiler/rustc_middle/src/thir.rs

Lines changed: 28 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -935,17 +935,17 @@ impl<'tcx> PatRange<'tcx> {
935935
// Also, for performance, it's important to only do the second `try_to_bits` if necessary.
936936
let lo_is_min = match self.lo {
937937
PatRangeBoundary::NegInfinity => true,
938-
PatRangeBoundary::Finite(value) => {
939-
let lo = value.try_to_bits(size).unwrap() ^ bias;
938+
PatRangeBoundary::Finite(_ty, value) => {
939+
let lo = value.unwrap_leaf().to_bits(size) ^ bias;
940940
lo <= min
941941
}
942942
PatRangeBoundary::PosInfinity => false,
943943
};
944944
if lo_is_min {
945945
let hi_is_max = match self.hi {
946946
PatRangeBoundary::NegInfinity => false,
947-
PatRangeBoundary::Finite(value) => {
948-
let hi = value.try_to_bits(size).unwrap() ^ bias;
947+
PatRangeBoundary::Finite(_ty, value) => {
948+
let hi = value.unwrap_leaf().to_bits(size) ^ bias;
949949
hi > max || hi == max && self.end == RangeEnd::Included
950950
}
951951
PatRangeBoundary::PosInfinity => true,
@@ -958,22 +958,16 @@ impl<'tcx> PatRange<'tcx> {
958958
}
959959

960960
#[inline]
961-
pub fn contains(
962-
&self,
963-
value: mir::Const<'tcx>,
964-
tcx: TyCtxt<'tcx>,
965-
typing_env: ty::TypingEnv<'tcx>,
966-
) -> Option<bool> {
961+
pub fn contains(&self, value: ty::ValTree<'tcx>, tcx: TyCtxt<'tcx>) -> Option<bool> {
967962
use Ordering::*;
968-
debug_assert_eq!(self.ty, value.ty());
969963
let ty = self.ty;
970-
let value = PatRangeBoundary::Finite(value);
964+
let value = PatRangeBoundary::Finite(ty, value);
971965
// For performance, it's important to only do the second comparison if necessary.
972966
Some(
973-
match self.lo.compare_with(value, ty, tcx, typing_env)? {
967+
match self.lo.compare_with(value, ty, tcx)? {
974968
Less | Equal => true,
975969
Greater => false,
976-
} && match value.compare_with(self.hi, ty, tcx, typing_env)? {
970+
} && match value.compare_with(self.hi, ty, tcx)? {
977971
Less => true,
978972
Equal => self.end == RangeEnd::Included,
979973
Greater => false,
@@ -982,21 +976,16 @@ impl<'tcx> PatRange<'tcx> {
982976
}
983977

984978
#[inline]
985-
pub fn overlaps(
986-
&self,
987-
other: &Self,
988-
tcx: TyCtxt<'tcx>,
989-
typing_env: ty::TypingEnv<'tcx>,
990-
) -> Option<bool> {
979+
pub fn overlaps(&self, other: &Self, tcx: TyCtxt<'tcx>) -> Option<bool> {
991980
use Ordering::*;
992981
debug_assert_eq!(self.ty, other.ty);
993982
// For performance, it's important to only do the second comparison if necessary.
994983
Some(
995-
match other.lo.compare_with(self.hi, self.ty, tcx, typing_env)? {
984+
match other.lo.compare_with(self.hi, self.ty, tcx)? {
996985
Less => true,
997986
Equal => self.end == RangeEnd::Included,
998987
Greater => false,
999-
} && match self.lo.compare_with(other.hi, self.ty, tcx, typing_env)? {
988+
} && match self.lo.compare_with(other.hi, self.ty, tcx)? {
1000989
Less => true,
1001990
Equal => other.end == RangeEnd::Included,
1002991
Greater => false,
@@ -1007,10 +996,13 @@ impl<'tcx> PatRange<'tcx> {
1007996

1008997
impl<'tcx> fmt::Display for PatRange<'tcx> {
1009998
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1010-
if let PatRangeBoundary::Finite(value) = &self.lo {
999+
if let &PatRangeBoundary::Finite(ty, value) = &self.lo {
1000+
// `ty::Value` has a reasonable pretty-printing implementation.
1001+
let value = ty::Value { ty, valtree: value };
10111002
write!(f, "{value}")?;
10121003
}
1013-
if let PatRangeBoundary::Finite(value) = &self.hi {
1004+
if let &PatRangeBoundary::Finite(ty, value) = &self.hi {
1005+
let value = ty::Value { ty, valtree: value };
10141006
write!(f, "{}", self.end)?;
10151007
write!(f, "{value}")?;
10161008
} else {
@@ -1025,7 +1017,7 @@ impl<'tcx> fmt::Display for PatRange<'tcx> {
10251017
/// If present, the const must be of a numeric type.
10261018
#[derive(Copy, Clone, Debug, PartialEq, HashStable, TypeVisitable)]
10271019
pub enum PatRangeBoundary<'tcx> {
1028-
Finite(mir::Const<'tcx>),
1020+
Finite(Ty<'tcx>, ty::ValTree<'tcx>),
10291021
NegInfinity,
10301022
PosInfinity,
10311023
}
@@ -1036,20 +1028,15 @@ impl<'tcx> PatRangeBoundary<'tcx> {
10361028
matches!(self, Self::Finite(..))
10371029
}
10381030
#[inline]
1039-
pub fn as_finite(self) -> Option<mir::Const<'tcx>> {
1031+
pub fn as_finite(self) -> Option<ty::ValTree<'tcx>> {
10401032
match self {
1041-
Self::Finite(value) => Some(value),
1033+
Self::Finite(_ty, value) => Some(value),
10421034
Self::NegInfinity | Self::PosInfinity => None,
10431035
}
10441036
}
1045-
pub fn eval_bits(
1046-
self,
1047-
ty: Ty<'tcx>,
1048-
tcx: TyCtxt<'tcx>,
1049-
typing_env: ty::TypingEnv<'tcx>,
1050-
) -> u128 {
1037+
pub fn eval_bits(self, ty: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> u128 {
10511038
match self {
1052-
Self::Finite(value) => value.eval_bits(tcx, typing_env),
1039+
Self::Finite(_ty, value) => value.unwrap_leaf().to_bits_unchecked(),
10531040
Self::NegInfinity => {
10541041
// Unwrap is ok because the type is known to be numeric.
10551042
ty.numeric_min_and_max_as_bits(tcx).unwrap().0
@@ -1061,14 +1048,8 @@ impl<'tcx> PatRangeBoundary<'tcx> {
10611048
}
10621049
}
10631050

1064-
#[instrument(skip(tcx, typing_env), level = "debug", ret)]
1065-
pub fn compare_with(
1066-
self,
1067-
other: Self,
1068-
ty: Ty<'tcx>,
1069-
tcx: TyCtxt<'tcx>,
1070-
typing_env: ty::TypingEnv<'tcx>,
1071-
) -> Option<Ordering> {
1051+
#[instrument(skip(tcx), level = "debug", ret)]
1052+
pub fn compare_with(self, other: Self, ty: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Ordering> {
10721053
use PatRangeBoundary::*;
10731054
match (self, other) {
10741055
// When comparing with infinities, we must remember that `0u8..` and `0u8..=255`
@@ -1082,7 +1063,9 @@ impl<'tcx> PatRangeBoundary<'tcx> {
10821063
// we can do scalar comparisons. E.g. `unicode-normalization` has
10831064
// many ranges such as '\u{037A}'..='\u{037F}', and chars can be compared
10841065
// in this way.
1085-
(Finite(a), Finite(b)) if matches!(ty.kind(), ty::Int(_) | ty::Uint(_) | ty::Char) => {
1066+
(Finite(_, a), Finite(_, b))
1067+
if matches!(ty.kind(), ty::Int(_) | ty::Uint(_) | ty::Char) =>
1068+
{
10861069
if let (Some(a), Some(b)) = (a.try_to_scalar_int(), b.try_to_scalar_int()) {
10871070
let sz = ty.primitive_size(tcx);
10881071
let cmp = match ty.kind() {
@@ -1096,8 +1079,8 @@ impl<'tcx> PatRangeBoundary<'tcx> {
10961079
_ => {}
10971080
}
10981081

1099-
let a = self.eval_bits(ty, tcx, typing_env);
1100-
let b = other.eval_bits(ty, tcx, typing_env);
1082+
let a = self.eval_bits(ty, tcx);
1083+
let b = other.eval_bits(ty, tcx);
11011084

11021085
match ty.kind() {
11031086
ty::Float(ty::FloatTy::F16) => {

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@ use std::fmt;
22
use std::ops::Deref;
33

44
use rustc_data_structures::intern::Interned;
5+
use rustc_hir::def::Namespace;
56
use rustc_macros::{HashStable, Lift, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
67

78
use super::ScalarInt;
89
use crate::mir::interpret::{ErrorHandled, Scalar};
10+
use crate::ty::print::{FmtPrinter, PrettyPrinter};
911
use crate::ty::{self, Ty, TyCtxt};
1012

1113
/// This datastructure is used to represent the value of constants used in the type system.
@@ -203,3 +205,14 @@ impl<'tcx> rustc_type_ir::inherent::ValueConst<TyCtxt<'tcx>> for Value<'tcx> {
203205
self.valtree
204206
}
205207
}
208+
209+
impl<'tcx> fmt::Display for Value<'tcx> {
210+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211+
ty::tls::with(move |tcx| {
212+
let cv = tcx.lift(*self).unwrap();
213+
let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
214+
cx.pretty_print_const_valtree(cv, /*print_ty*/ true)?;
215+
f.write_str(&cx.into_buffer())
216+
})
217+
}
218+
}

compiler/rustc_middle/src/ty/structural_impls.rs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ use rustc_hir::def_id::LocalDefId;
1212
use rustc_span::source_map::Spanned;
1313
use rustc_type_ir::{ConstKind, TypeFolder, VisitorResult, try_visit};
1414

15-
use super::print::PrettyPrinter;
1615
use super::{GenericArg, GenericArgKind, Pattern, Region};
1716
use crate::mir::PlaceElem;
1817
use crate::ty::print::{FmtPrinter, Printer, with_no_trimmed_paths};
@@ -168,15 +167,11 @@ impl<'tcx> fmt::Debug for ty::Const<'tcx> {
168167
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169168
// If this is a value, we spend some effort to make it look nice.
170169
if let ConstKind::Value(cv) = self.kind() {
171-
return ty::tls::with(move |tcx| {
172-
let cv = tcx.lift(cv).unwrap();
173-
let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
174-
cx.pretty_print_const_valtree(cv, /*print_ty*/ true)?;
175-
f.write_str(&cx.into_buffer())
176-
});
170+
write!(f, "{}", cv)
171+
} else {
172+
// Fall back to something verbose.
173+
write!(f, "{:?}", self.kind())
177174
}
178-
// Fall back to something verbose.
179-
write!(f, "{:?}", self.kind())
180175
}
181176
}
182177

compiler/rustc_mir_build/src/builder/matches/match_pair.rs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,11 +136,7 @@ impl<'tcx> MatchPairTree<'tcx> {
136136
}
137137
}
138138

139-
PatKind::Constant { ty: value_ty, value } => {
140-
// FIXME: `TestCase::Constant` should probably represent that it is always a `ValTree`.
141-
let value = Const::Ty(value_ty, ty::Const::new_value(cx.tcx, value, value_ty));
142-
Some(TestCase::Constant { value })
143-
}
139+
PatKind::Constant { ty, value } => Some(TestCase::Constant { ty, value }),
144140

145141
PatKind::AscribeUserType {
146142
ascription: Ascription { ref annotation, variance },

compiler/rustc_mir_build/src/builder/matches/mod.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use rustc_data_structures::stack::ensure_sufficient_stack;
1616
use rustc_hir::{BindingMode, ByRef, LetStmt, LocalSource, Node};
1717
use rustc_middle::bug;
1818
use rustc_middle::middle::region;
19-
use rustc_middle::mir::{self, *};
19+
use rustc_middle::mir::*;
2020
use rustc_middle::thir::{self, *};
2121
use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, ValTree, ValTreeKind};
2222
use rustc_pattern_analysis::constructor::RangeEnd;
@@ -1260,7 +1260,7 @@ struct Ascription<'tcx> {
12601260
#[derive(Debug, Clone)]
12611261
enum TestCase<'tcx> {
12621262
Variant { adt_def: ty::AdtDef<'tcx>, variant_index: VariantIdx },
1263-
Constant { value: mir::Const<'tcx> },
1263+
Constant { ty: Ty<'tcx>, value: ty::ValTree<'tcx> },
12641264
Range(Arc<PatRange<'tcx>>),
12651265
Slice { len: usize, variable_length: bool },
12661266
Deref { temp: Place<'tcx>, mutability: Mutability },
@@ -1333,11 +1333,12 @@ enum TestKind<'tcx> {
13331333
/// Test for equality with value, possibly after an unsizing coercion to
13341334
/// `ty`,
13351335
Eq {
1336-
value: Const<'tcx>,
1336+
value: ty::ValTree<'tcx>,
1337+
value_ty: Ty<'tcx>,
13371338
// Integer types are handled by `SwitchInt`, and constants with ADT
13381339
// types and `&[T]` types are converted back into patterns, so this can
13391340
// only be `&str` or `f*`.
1340-
ty: Ty<'tcx>,
1341+
cast_ty: Ty<'tcx>,
13411342
},
13421343

13431344
/// Test whether the value falls within an inclusive or exclusive range.
@@ -1373,16 +1374,16 @@ enum TestBranch<'tcx> {
13731374
/// Success branch, used for tests with two possible outcomes.
13741375
Success,
13751376
/// Branch corresponding to this constant.
1376-
Constant(Const<'tcx>, u128),
1377+
Constant(ty::ValTree<'tcx>, u128),
13771378
/// Branch corresponding to this variant.
13781379
Variant(VariantIdx),
13791380
/// Failure branch for tests with two possible outcomes, and "otherwise" branch for other tests.
13801381
Failure,
13811382
}
13821383

13831384
impl<'tcx> TestBranch<'tcx> {
1384-
fn as_constant(&self) -> Option<&Const<'tcx>> {
1385-
if let Self::Constant(v, _) = self { Some(v) } else { None }
1385+
fn as_constant(&self) -> Option<ty::ValTree<'tcx>> {
1386+
if let Self::Constant(v, _) = self { Some(*v) } else { None }
13861387
}
13871388
}
13881389

0 commit comments

Comments
 (0)