Skip to content

Commit 479d493

Browse files
committed
Abstract over PatRange boundary value
1 parent b50a21a commit 479d493

File tree

7 files changed

+298
-214
lines changed

7 files changed

+298
-214
lines changed

compiler/rustc_middle/src/thir.rs

Lines changed: 213 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,19 @@ use rustc_hir::RangeEnd;
1616
use rustc_index::newtype_index;
1717
use rustc_index::IndexVec;
1818
use rustc_middle::middle::region;
19-
use rustc_middle::mir::interpret::AllocId;
19+
use rustc_middle::mir::interpret::{AllocId, Scalar};
2020
use rustc_middle::mir::{self, BinOp, BorrowKind, FakeReadCause, Mutability, UnOp};
2121
use rustc_middle::ty::adjustment::PointerCoercion;
22+
use rustc_middle::ty::layout::IntegerExt;
2223
use rustc_middle::ty::{
2324
self, AdtDef, CanonicalUserType, CanonicalUserTypeAnnotation, FnSig, GenericArgsRef, List, Ty,
24-
UpvarArgs,
25+
TyCtxt, UpvarArgs,
2526
};
2627
use rustc_span::def_id::LocalDefId;
2728
use rustc_span::{sym, ErrorGuaranteed, Span, Symbol, DUMMY_SP};
28-
use rustc_target::abi::{FieldIdx, VariantIdx};
29+
use rustc_target::abi::{FieldIdx, Integer, Size, VariantIdx};
2930
use rustc_target::asm::InlineAsmRegOrRegClass;
31+
use std::cmp::Ordering;
3032
use std::fmt;
3133
use std::ops::Index;
3234

@@ -793,12 +795,217 @@ pub enum PatKind<'tcx> {
793795
Error(ErrorGuaranteed),
794796
}
795797

798+
/// A range pattern.
799+
/// The boundaries must be of the same type and that type must be numeric.
796800
#[derive(Clone, Debug, PartialEq, HashStable, TypeVisitable)]
797801
pub struct PatRange<'tcx> {
798-
pub lo: mir::Const<'tcx>,
799-
pub hi: mir::Const<'tcx>,
802+
pub lo: PatRangeBoundary<'tcx>,
803+
pub hi: PatRangeBoundary<'tcx>,
800804
#[type_visitable(ignore)]
801805
pub end: RangeEnd,
806+
pub ty: Ty<'tcx>,
807+
}
808+
809+
impl<'tcx> PatRange<'tcx> {
810+
/// Whether this range covers the full extent of possible values (best-effort, we ignore floats).
811+
#[inline]
812+
pub fn is_full_range(&self, tcx: TyCtxt<'tcx>) -> Option<bool> {
813+
let (min, max, size, bias) = match *self.ty.kind() {
814+
ty::Char => (0, std::char::MAX as u128, Size::from_bits(32), 0),
815+
ty::Int(ity) => {
816+
let size = Integer::from_int_ty(&tcx, ity).size();
817+
let max = size.truncate(u128::MAX);
818+
let bias = 1u128 << (size.bits() - 1);
819+
(0, max, size, bias)
820+
}
821+
ty::Uint(uty) => {
822+
let size = Integer::from_uint_ty(&tcx, uty).size();
823+
let max = size.unsigned_int_max();
824+
(0, max, size, 0)
825+
}
826+
_ => return None,
827+
};
828+
829+
// We want to compare ranges numerically, but the order of the bitwise representation of
830+
// signed integers does not match their numeric order. Thus, to correct the ordering, we
831+
// need to shift the range of signed integers to correct the comparison. This is achieved by
832+
// XORing with a bias (see pattern/deconstruct_pat.rs for another pertinent example of this
833+
// pattern).
834+
//
835+
// Also, for performance, it's important to only do the second `try_to_bits` if necessary.
836+
let lo_is_min = match self.lo {
837+
PatRangeBoundary::Finite(value) => {
838+
let lo = value.try_to_bits(size).unwrap() ^ bias;
839+
lo <= min
840+
}
841+
};
842+
if lo_is_min {
843+
let hi_is_max = match self.hi {
844+
PatRangeBoundary::Finite(value) => {
845+
let hi = value.try_to_bits(size).unwrap() ^ bias;
846+
hi > max || hi == max && self.end == RangeEnd::Included
847+
}
848+
};
849+
if hi_is_max {
850+
return Some(true);
851+
}
852+
}
853+
Some(false)
854+
}
855+
856+
#[inline]
857+
pub fn contains(
858+
&self,
859+
value: mir::Const<'tcx>,
860+
tcx: TyCtxt<'tcx>,
861+
param_env: ty::ParamEnv<'tcx>,
862+
) -> Option<bool> {
863+
use Ordering::*;
864+
debug_assert_eq!(self.ty, value.ty());
865+
let ty = self.ty;
866+
let value = PatRangeBoundary::Finite(value);
867+
// For performance, it's important to only do the second comparison if necessary.
868+
Some(
869+
match self.lo.compare_with(value, ty, tcx, param_env)? {
870+
Less | Equal => true,
871+
Greater => false,
872+
} && match value.compare_with(self.hi, ty, tcx, param_env)? {
873+
Less => true,
874+
Equal => self.end == RangeEnd::Included,
875+
Greater => false,
876+
},
877+
)
878+
}
879+
880+
#[inline]
881+
pub fn overlaps(
882+
&self,
883+
other: &Self,
884+
tcx: TyCtxt<'tcx>,
885+
param_env: ty::ParamEnv<'tcx>,
886+
) -> Option<bool> {
887+
use Ordering::*;
888+
debug_assert_eq!(self.ty, other.ty);
889+
// For performance, it's important to only do the second comparison if necessary.
890+
Some(
891+
match other.lo.compare_with(self.hi, self.ty, tcx, param_env)? {
892+
Less => true,
893+
Equal => self.end == RangeEnd::Included,
894+
Greater => false,
895+
} && match self.lo.compare_with(other.hi, self.ty, tcx, param_env)? {
896+
Less => true,
897+
Equal => other.end == RangeEnd::Included,
898+
Greater => false,
899+
},
900+
)
901+
}
902+
}
903+
904+
impl<'tcx> fmt::Display for PatRange<'tcx> {
905+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
906+
let PatRangeBoundary::Finite(value) = &self.lo;
907+
write!(f, "{value}")?;
908+
write!(f, "{}", self.end)?;
909+
let PatRangeBoundary::Finite(value) = &self.hi;
910+
write!(f, "{value}")?;
911+
Ok(())
912+
}
913+
}
914+
915+
/// A (possibly open) boundary of a range pattern.
916+
/// If present, the const must be of a numeric type.
917+
#[derive(Copy, Clone, Debug, PartialEq, HashStable, TypeVisitable)]
918+
pub enum PatRangeBoundary<'tcx> {
919+
Finite(mir::Const<'tcx>),
920+
}
921+
922+
impl<'tcx> PatRangeBoundary<'tcx> {
923+
#[inline]
924+
pub fn lower_bound(ty: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
925+
// Unwrap is ok because the type is known to be numeric.
926+
let c = ty.numeric_min_val(tcx).unwrap();
927+
let value = mir::Const::from_ty_const(c, tcx);
928+
Self::Finite(value)
929+
}
930+
#[inline]
931+
pub fn upper_bound(ty: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
932+
// Unwrap is ok because the type is known to be numeric.
933+
let c = ty.numeric_max_val(tcx).unwrap();
934+
let value = mir::Const::from_ty_const(c, tcx);
935+
Self::Finite(value)
936+
}
937+
938+
#[inline]
939+
pub fn to_const(self, _ty: Ty<'tcx>, _tcx: TyCtxt<'tcx>) -> mir::Const<'tcx> {
940+
match self {
941+
Self::Finite(value) => value,
942+
}
943+
}
944+
pub fn eval_bits(
945+
self,
946+
_ty: Ty<'tcx>,
947+
tcx: TyCtxt<'tcx>,
948+
param_env: ty::ParamEnv<'tcx>,
949+
) -> u128 {
950+
match self {
951+
Self::Finite(value) => value.eval_bits(tcx, param_env),
952+
}
953+
}
954+
955+
#[instrument(skip(tcx, param_env), level = "debug", ret)]
956+
pub fn compare_with(
957+
self,
958+
other: Self,
959+
ty: Ty<'tcx>,
960+
tcx: TyCtxt<'tcx>,
961+
param_env: ty::ParamEnv<'tcx>,
962+
) -> Option<Ordering> {
963+
use PatRangeBoundary::*;
964+
match (self, other) {
965+
// This code is hot when compiling matches with many ranges. So we
966+
// special-case extraction of evaluated scalars for speed, for types where
967+
// raw data comparisons are appropriate. E.g. `unicode-normalization` has
968+
// many ranges such as '\u{037A}'..='\u{037F}', and chars can be compared
969+
// in this way.
970+
(Finite(mir::Const::Ty(a)), Finite(mir::Const::Ty(b)))
971+
if matches!(ty.kind(), ty::Uint(_) | ty::Char) =>
972+
{
973+
return Some(a.kind().cmp(&b.kind()));
974+
}
975+
(
976+
Finite(mir::Const::Val(mir::ConstValue::Scalar(Scalar::Int(a)), _)),
977+
Finite(mir::Const::Val(mir::ConstValue::Scalar(Scalar::Int(b)), _)),
978+
) if matches!(ty.kind(), ty::Uint(_) | ty::Char) => return Some(a.cmp(&b)),
979+
_ => {}
980+
}
981+
982+
let a = self.eval_bits(ty, tcx, param_env);
983+
let b = other.eval_bits(ty, tcx, param_env);
984+
985+
match ty.kind() {
986+
ty::Float(ty::FloatTy::F32) => {
987+
use rustc_apfloat::Float;
988+
let a = rustc_apfloat::ieee::Single::from_bits(a);
989+
let b = rustc_apfloat::ieee::Single::from_bits(b);
990+
a.partial_cmp(&b)
991+
}
992+
ty::Float(ty::FloatTy::F64) => {
993+
use rustc_apfloat::Float;
994+
let a = rustc_apfloat::ieee::Double::from_bits(a);
995+
let b = rustc_apfloat::ieee::Double::from_bits(b);
996+
a.partial_cmp(&b)
997+
}
998+
ty::Int(ity) => {
999+
use rustc_middle::ty::layout::IntegerExt;
1000+
let size = rustc_target::abi::Integer::from_int_ty(&tcx, *ity).size();
1001+
let a = size.sign_extend(a) as i128;
1002+
let b = size.sign_extend(b) as i128;
1003+
Some(a.cmp(&b))
1004+
}
1005+
ty::Uint(_) | ty::Char => Some(a.cmp(&b)),
1006+
_ => bug!(),
1007+
}
1008+
}
8021009
}
8031010

8041011
impl<'tcx> fmt::Display for Pat<'tcx> {
@@ -924,11 +1131,7 @@ impl<'tcx> fmt::Display for Pat<'tcx> {
9241131
write!(f, "{subpattern}")
9251132
}
9261133
PatKind::Constant { value } => write!(f, "{value}"),
927-
PatKind::Range(box PatRange { lo, hi, end }) => {
928-
write!(f, "{lo}")?;
929-
write!(f, "{end}")?;
930-
write!(f, "{hi}")
931-
}
1134+
PatKind::Range(ref range) => write!(f, "{range}"),
9321135
PatKind::Slice { ref prefix, ref slice, ref suffix }
9331136
| PatKind::Array { ref prefix, ref slice, ref suffix } => {
9341137
write!(f, "[")?;

compiler/rustc_middle/src/ty/util.rs

Lines changed: 43 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use rustc_index::bit_set::GrowableBitSet;
1919
use rustc_macros::HashStable;
2020
use rustc_session::Limit;
2121
use rustc_span::sym;
22-
use rustc_target::abi::{Integer, IntegerType, Size};
22+
use rustc_target::abi::{Integer, IntegerType, Primitive, Size};
2323
use rustc_target::spec::abi::Abi;
2424
use smallvec::SmallVec;
2525
use std::{fmt, iter};
@@ -917,54 +917,62 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for OpaqueTypeExpander<'tcx> {
917917
}
918918

919919
impl<'tcx> Ty<'tcx> {
920+
/// Returns the `Size` for primitive types (bool, uint, int, char, float).
921+
pub fn primitive_size(self, tcx: TyCtxt<'tcx>) -> Size {
922+
match *self.kind() {
923+
ty::Bool => Size::from_bytes(1),
924+
ty::Char => Size::from_bytes(4),
925+
ty::Int(ity) => Integer::from_int_ty(&tcx, ity).size(),
926+
ty::Uint(uty) => Integer::from_uint_ty(&tcx, uty).size(),
927+
ty::Float(ty::FloatTy::F32) => Primitive::F32.size(&tcx),
928+
ty::Float(ty::FloatTy::F64) => Primitive::F64.size(&tcx),
929+
_ => bug!("non primitive type"),
930+
}
931+
}
932+
920933
pub fn int_size_and_signed(self, tcx: TyCtxt<'tcx>) -> (Size, bool) {
921-
let (int, signed) = match *self.kind() {
922-
ty::Int(ity) => (Integer::from_int_ty(&tcx, ity), true),
923-
ty::Uint(uty) => (Integer::from_uint_ty(&tcx, uty), false),
934+
match *self.kind() {
935+
ty::Int(ity) => (Integer::from_int_ty(&tcx, ity).size(), true),
936+
ty::Uint(uty) => (Integer::from_uint_ty(&tcx, uty).size(), false),
924937
_ => bug!("non integer discriminant"),
925-
};
926-
(int.size(), signed)
938+
}
927939
}
928940

929-
/// Returns the maximum value for the given numeric type (including `char`s)
930-
/// or returns `None` if the type is not numeric.
931-
pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<ty::Const<'tcx>> {
932-
let val = match self.kind() {
941+
/// Returns the minimum and maximum values for the given numeric type (including `char`s) or
942+
/// returns `None` if the type is not numeric.
943+
pub fn numeric_min_and_max_as_bits(self, tcx: TyCtxt<'tcx>) -> Option<(u128, u128)> {
944+
use rustc_apfloat::ieee::{Double, Single};
945+
Some(match self.kind() {
933946
ty::Int(_) | ty::Uint(_) => {
934947
let (size, signed) = self.int_size_and_signed(tcx);
935-
let val =
948+
let min = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
949+
let max =
936950
if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
937-
Some(val)
951+
(min, max)
938952
}
939-
ty::Char => Some(std::char::MAX as u128),
940-
ty::Float(fty) => Some(match fty {
941-
ty::FloatTy::F32 => rustc_apfloat::ieee::Single::INFINITY.to_bits(),
942-
ty::FloatTy::F64 => rustc_apfloat::ieee::Double::INFINITY.to_bits(),
943-
}),
944-
_ => None,
945-
};
953+
ty::Char => (0, std::char::MAX as u128),
954+
ty::Float(ty::FloatTy::F32) => {
955+
((-Single::INFINITY).to_bits(), Single::INFINITY.to_bits())
956+
}
957+
ty::Float(ty::FloatTy::F64) => {
958+
((-Double::INFINITY).to_bits(), Double::INFINITY.to_bits())
959+
}
960+
_ => return None,
961+
})
962+
}
946963

947-
val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
964+
/// Returns the maximum value for the given numeric type (including `char`s)
965+
/// or returns `None` if the type is not numeric.
966+
pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<ty::Const<'tcx>> {
967+
self.numeric_min_and_max_as_bits(tcx)
968+
.map(|(_, max)| ty::Const::from_bits(tcx, max, ty::ParamEnv::empty().and(self)))
948969
}
949970

950971
/// Returns the minimum value for the given numeric type (including `char`s)
951972
/// or returns `None` if the type is not numeric.
952973
pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<ty::Const<'tcx>> {
953-
let val = match self.kind() {
954-
ty::Int(_) | ty::Uint(_) => {
955-
let (size, signed) = self.int_size_and_signed(tcx);
956-
let val = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
957-
Some(val)
958-
}
959-
ty::Char => Some(0),
960-
ty::Float(fty) => Some(match fty {
961-
ty::FloatTy::F32 => (-::rustc_apfloat::ieee::Single::INFINITY).to_bits(),
962-
ty::FloatTy::F64 => (-::rustc_apfloat::ieee::Double::INFINITY).to_bits(),
963-
}),
964-
_ => None,
965-
};
966-
967-
val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
974+
self.numeric_min_and_max_as_bits(tcx)
975+
.map(|(min, _)| ty::Const::from_bits(tcx, min, ty::ParamEnv::empty().and(self)))
968976
}
969977

970978
/// Checks whether values of this type `T` are *moved* or *copied*

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1023,7 +1023,7 @@ enum TestKind<'tcx> {
10231023
ty: Ty<'tcx>,
10241024
},
10251025

1026-
/// Test whether the value falls within an inclusive or exclusive range
1026+
/// Test whether the value falls within an inclusive or exclusive range.
10271027
Range(Box<PatRange<'tcx>>),
10281028

10291029
/// Test that the length of the slice is equal to `len`.

0 commit comments

Comments
 (0)