Skip to content

Commit 13cfa7a

Browse files
Auto merge of #144591 - RalfJung:pattern-valtrees, r=<try>
Patterns: represent constants as valtrees
2 parents cb6785f + 9f3f015 commit 13cfa7a

File tree

12 files changed

+139
-170
lines changed

12 files changed

+139
-170
lines changed

compiler/rustc_middle/src/mir/consts.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,11 @@ impl<'tcx> Const<'tcx> {
448448
Self::Val(val, ty)
449449
}
450450

451+
#[inline]
452+
pub fn from_ty_value(tcx: TyCtxt<'tcx>, val: ty::Value<'tcx>) -> Self {
453+
Self::Ty(val.ty, ty::Const::new_value(tcx, val.valtree, val.ty))
454+
}
455+
451456
pub fn from_bits(
452457
tcx: TyCtxt<'tcx>,
453458
bits: u128,

compiler/rustc_middle/src/thir.rs

Lines changed: 20 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -832,15 +832,15 @@ pub enum PatKind<'tcx> {
832832
},
833833

834834
/// One of the following:
835-
/// * `&str` (represented as a valtree), which will be handled as a string pattern and thus
835+
/// * `&str`, which will be handled as a string pattern and thus
836836
/// exhaustiveness checking will detect if you use the same string twice in different
837837
/// patterns.
838-
/// * integer, bool, char or float (represented as a valtree), which will be handled by
838+
/// * integer, bool, char or float, which will be handled by
839839
/// exhaustiveness to cover exactly its own value, similar to `&str`, but these values are
840840
/// much simpler.
841841
/// * `String`, if `string_deref_patterns` is enabled.
842842
Constant {
843-
value: mir::Const<'tcx>,
843+
value: ty::Value<'tcx>,
844844
},
845845

846846
/// Pattern obtained by converting a constant (inline or named) to its pattern
@@ -933,7 +933,7 @@ impl<'tcx> PatRange<'tcx> {
933933
let lo_is_min = match self.lo {
934934
PatRangeBoundary::NegInfinity => true,
935935
PatRangeBoundary::Finite(value) => {
936-
let lo = value.try_to_bits(size).unwrap() ^ bias;
936+
let lo = value.try_to_scalar_int().unwrap().to_bits(size) ^ bias;
937937
lo <= min
938938
}
939939
PatRangeBoundary::PosInfinity => false,
@@ -942,7 +942,7 @@ impl<'tcx> PatRange<'tcx> {
942942
let hi_is_max = match self.hi {
943943
PatRangeBoundary::NegInfinity => false,
944944
PatRangeBoundary::Finite(value) => {
945-
let hi = value.try_to_bits(size).unwrap() ^ bias;
945+
let hi = value.try_to_scalar_int().unwrap().to_bits(size) ^ bias;
946946
hi > max || hi == max && self.end == RangeEnd::Included
947947
}
948948
PatRangeBoundary::PosInfinity => true,
@@ -955,22 +955,17 @@ impl<'tcx> PatRange<'tcx> {
955955
}
956956

957957
#[inline]
958-
pub fn contains(
959-
&self,
960-
value: mir::Const<'tcx>,
961-
tcx: TyCtxt<'tcx>,
962-
typing_env: ty::TypingEnv<'tcx>,
963-
) -> Option<bool> {
958+
pub fn contains(&self, value: ty::Value<'tcx>, tcx: TyCtxt<'tcx>) -> Option<bool> {
964959
use Ordering::*;
965-
debug_assert_eq!(self.ty, value.ty());
960+
debug_assert_eq!(self.ty, value.ty);
966961
let ty = self.ty;
967962
let value = PatRangeBoundary::Finite(value);
968963
// For performance, it's important to only do the second comparison if necessary.
969964
Some(
970-
match self.lo.compare_with(value, ty, tcx, typing_env)? {
965+
match self.lo.compare_with(value, ty, tcx)? {
971966
Less | Equal => true,
972967
Greater => false,
973-
} && match value.compare_with(self.hi, ty, tcx, typing_env)? {
968+
} && match value.compare_with(self.hi, ty, tcx)? {
974969
Less => true,
975970
Equal => self.end == RangeEnd::Included,
976971
Greater => false,
@@ -979,21 +974,16 @@ impl<'tcx> PatRange<'tcx> {
979974
}
980975

981976
#[inline]
982-
pub fn overlaps(
983-
&self,
984-
other: &Self,
985-
tcx: TyCtxt<'tcx>,
986-
typing_env: ty::TypingEnv<'tcx>,
987-
) -> Option<bool> {
977+
pub fn overlaps(&self, other: &Self, tcx: TyCtxt<'tcx>) -> Option<bool> {
988978
use Ordering::*;
989979
debug_assert_eq!(self.ty, other.ty);
990980
// For performance, it's important to only do the second comparison if necessary.
991981
Some(
992-
match other.lo.compare_with(self.hi, self.ty, tcx, typing_env)? {
982+
match other.lo.compare_with(self.hi, self.ty, tcx)? {
993983
Less => true,
994984
Equal => self.end == RangeEnd::Included,
995985
Greater => false,
996-
} && match self.lo.compare_with(other.hi, self.ty, tcx, typing_env)? {
986+
} && match self.lo.compare_with(other.hi, self.ty, tcx)? {
997987
Less => true,
998988
Equal => other.end == RangeEnd::Included,
999989
Greater => false,
@@ -1022,7 +1012,7 @@ impl<'tcx> fmt::Display for PatRange<'tcx> {
10221012
/// If present, the const must be of a numeric type.
10231013
#[derive(Copy, Clone, Debug, PartialEq, HashStable, TypeVisitable)]
10241014
pub enum PatRangeBoundary<'tcx> {
1025-
Finite(mir::Const<'tcx>),
1015+
Finite(ty::Value<'tcx>),
10261016
NegInfinity,
10271017
PosInfinity,
10281018
}
@@ -1033,20 +1023,15 @@ impl<'tcx> PatRangeBoundary<'tcx> {
10331023
matches!(self, Self::Finite(..))
10341024
}
10351025
#[inline]
1036-
pub fn as_finite(self) -> Option<mir::Const<'tcx>> {
1026+
pub fn as_finite(self) -> Option<ty::Value<'tcx>> {
10371027
match self {
10381028
Self::Finite(value) => Some(value),
10391029
Self::NegInfinity | Self::PosInfinity => None,
10401030
}
10411031
}
1042-
pub fn eval_bits(
1043-
self,
1044-
ty: Ty<'tcx>,
1045-
tcx: TyCtxt<'tcx>,
1046-
typing_env: ty::TypingEnv<'tcx>,
1047-
) -> u128 {
1032+
pub fn eval_bits(self, ty: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> u128 {
10481033
match self {
1049-
Self::Finite(value) => value.eval_bits(tcx, typing_env),
1034+
Self::Finite(value) => value.try_to_scalar_int().unwrap().to_bits_unchecked(),
10501035
Self::NegInfinity => {
10511036
// Unwrap is ok because the type is known to be numeric.
10521037
ty.numeric_min_and_max_as_bits(tcx).unwrap().0
@@ -1058,14 +1043,8 @@ impl<'tcx> PatRangeBoundary<'tcx> {
10581043
}
10591044
}
10601045

1061-
#[instrument(skip(tcx, typing_env), level = "debug", ret)]
1062-
pub fn compare_with(
1063-
self,
1064-
other: Self,
1065-
ty: Ty<'tcx>,
1066-
tcx: TyCtxt<'tcx>,
1067-
typing_env: ty::TypingEnv<'tcx>,
1068-
) -> Option<Ordering> {
1046+
#[instrument(skip(tcx), level = "debug", ret)]
1047+
pub fn compare_with(self, other: Self, ty: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Ordering> {
10691048
use PatRangeBoundary::*;
10701049
match (self, other) {
10711050
// When comparing with infinities, we must remember that `0u8..` and `0u8..=255`
@@ -1093,8 +1072,8 @@ impl<'tcx> PatRangeBoundary<'tcx> {
10931072
_ => {}
10941073
}
10951074

1096-
let a = self.eval_bits(ty, tcx, typing_env);
1097-
let b = other.eval_bits(ty, tcx, typing_env);
1075+
let a = self.eval_bits(ty, tcx);
1076+
let b = other.eval_bits(ty, tcx);
10981077

10991078
match ty.kind() {
11001079
ty::Float(ty::FloatTy::F16) => {

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

Lines changed: 23 additions & 4 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.
@@ -133,6 +135,8 @@ pub type ConstToValTreeResult<'tcx> = Result<Result<ValTree<'tcx>, Ty<'tcx>>, Er
133135
/// A type-level constant value.
134136
///
135137
/// Represents a typed, fully evaluated constant.
138+
/// Note that this is used by pattern elaboration to represent values which cannot occur in types,
139+
/// such as raw pointers and floats.
136140
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
137141
#[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable, TypeVisitable, Lift)]
138142
pub struct Value<'tcx> {
@@ -147,15 +151,19 @@ impl<'tcx> Value<'tcx> {
147151
/// or an aggregate).
148152
#[inline]
149153
pub fn try_to_bits(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> Option<u128> {
150-
let (ty::Bool | ty::Char | ty::Uint(_) | ty::Int(_) | ty::Float(_)) = self.ty.kind() else {
151-
return None;
152-
};
153-
let scalar = self.valtree.try_to_scalar_int()?;
154+
let scalar = self.try_to_scalar_int()?;
154155
let input = typing_env.with_post_analysis_normalized(tcx).as_query_input(self.ty);
155156
let size = tcx.layout_of(input).ok()?.size;
156157
Some(scalar.to_bits(size))
157158
}
158159

160+
pub fn try_to_scalar_int(self) -> Option<ScalarInt> {
161+
let (ty::Bool | ty::Char | ty::Uint(_) | ty::Int(_) | ty::Float(_)) = self.ty.kind() else {
162+
return None;
163+
};
164+
self.valtree.try_to_scalar_int()
165+
}
166+
159167
pub fn try_to_bool(self) -> Option<bool> {
160168
if !self.ty.is_bool() {
161169
return None;
@@ -203,3 +211,14 @@ impl<'tcx> rustc_type_ir::inherent::ValueConst<TyCtxt<'tcx>> for Value<'tcx> {
203211
self.valtree
204212
}
205213
}
214+
215+
impl<'tcx> fmt::Display for Value<'tcx> {
216+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217+
ty::tls::with(move |tcx| {
218+
let cv = tcx.lift(*self).unwrap();
219+
let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
220+
cx.pretty_print_const_valtree(cv, /*print_ty*/ true)?;
221+
f.write_str(&cx.into_buffer())
222+
})
223+
}
224+
}

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/custom/parse/instruction.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ impl<'a, 'tcx> ParseCtxt<'a, 'tcx> {
160160
});
161161
}
162162
};
163-
values.push(value.eval_bits(self.tcx, self.typing_env));
163+
values.push(value.try_to_scalar_int().unwrap().to_bits_unchecked());
164164
targets.push(self.parse_block(arm.body)?);
165165
}
166166

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

Lines changed: 8 additions & 8 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 { value: ty::Value<'tcx> },
12641264
Range(Arc<PatRange<'tcx>>),
12651265
Slice { len: usize, variable_length: bool },
12661266
Deref { temp: Place<'tcx>, mutability: Mutability },
@@ -1333,11 +1333,11 @@ 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::Value<'tcx>,
13371337
// Integer types are handled by `SwitchInt`, and constants with ADT
13381338
// types and `&[T]` types are converted back into patterns, so this can
1339-
// only be `&str`, `f32` or `f64`.
1340-
ty: Ty<'tcx>,
1339+
// only be `&str` or `f*`.
1340+
cast_ty: Ty<'tcx>,
13411341
},
13421342

13431343
/// Test whether the value falls within an inclusive or exclusive range.
@@ -1373,16 +1373,16 @@ enum TestBranch<'tcx> {
13731373
/// Success branch, used for tests with two possible outcomes.
13741374
Success,
13751375
/// Branch corresponding to this constant.
1376-
Constant(Const<'tcx>, u128),
1376+
Constant(ty::Value<'tcx>, u128),
13771377
/// Branch corresponding to this variant.
13781378
Variant(VariantIdx),
13791379
/// Failure branch for tests with two possible outcomes, and "otherwise" branch for other tests.
13801380
Failure,
13811381
}
13821382

13831383
impl<'tcx> TestBranch<'tcx> {
1384-
fn as_constant(&self) -> Option<&Const<'tcx>> {
1385-
if let Self::Constant(v, _) = self { Some(v) } else { None }
1384+
fn as_constant(&self) -> Option<ty::Value<'tcx>> {
1385+
if let Self::Constant(v, _) = self { Some(*v) } else { None }
13861386
}
13871387
}
13881388

0 commit comments

Comments
 (0)