|
| 1 | +use crate::{data_units::BitUnits, target::Target}; |
| 2 | +use derive_more::IsVariant; |
| 3 | +use std::cmp::Ordering; |
| 4 | + |
| 5 | +#[derive(Copy, Clone, Debug)] |
| 6 | +pub enum IntegerRank { |
| 7 | + Bool, |
| 8 | + Char, |
| 9 | + Short, |
| 10 | + Int, |
| 11 | + Long, |
| 12 | + LongLong, |
| 13 | + FixedInt(BitUnits), |
| 14 | +} |
| 15 | + |
| 16 | +impl IntegerRank { |
| 17 | + pub fn compare_for_target(left: Self, right: Self, target: &Target) -> Ordering { |
| 18 | + let left_precision = left.precision(target); |
| 19 | + let right_precision = right.precision(target); |
| 20 | + left_precision.cmp(&right_precision) |
| 21 | + } |
| 22 | + |
| 23 | + pub fn precision(&self, target: &Target) -> IntegerPrecision { |
| 24 | + match self { |
| 25 | + IntegerRank::Bool => IntegerPrecision::boolean(), |
| 26 | + IntegerRank::Char => IntegerPrecision::flexible(target.char_layout().width.to_bits()), |
| 27 | + IntegerRank::Short => IntegerPrecision::flexible(target.short_layout().width.to_bits()), |
| 28 | + IntegerRank::Int => IntegerPrecision::flexible(target.int_layout().width.to_bits()), |
| 29 | + IntegerRank::Long => IntegerPrecision::flexible(target.long_layout().width.to_bits()), |
| 30 | + IntegerRank::LongLong => { |
| 31 | + IntegerPrecision::flexible(target.longlong_layout().width.to_bits()) |
| 32 | + } |
| 33 | + IntegerRank::FixedInt(bits) => IntegerPrecision::fixed(*bits), |
| 34 | + } |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, IsVariant)] |
| 39 | +pub enum IntegerPrecision { |
| 40 | + Boolean, |
| 41 | + Normal { bits: BitUnits, flexible: bool }, |
| 42 | +} |
| 43 | + |
| 44 | +impl IntegerPrecision { |
| 45 | + pub fn boolean() -> Self { |
| 46 | + Self::Boolean |
| 47 | + } |
| 48 | + pub fn flexible(bits: BitUnits) -> Self { |
| 49 | + Self::Normal { |
| 50 | + bits, |
| 51 | + flexible: true, |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + pub fn fixed(bits: BitUnits) -> Self { |
| 56 | + Self::Normal { |
| 57 | + bits, |
| 58 | + flexible: false, |
| 59 | + } |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +impl Ord for IntegerPrecision { |
| 64 | + fn cmp(&self, other: &Self) -> Ordering { |
| 65 | + match self { |
| 66 | + IntegerPrecision::Boolean => other |
| 67 | + .is_normal() |
| 68 | + .then_some(Ordering::Less) |
| 69 | + .unwrap_or(Ordering::Equal), |
| 70 | + IntegerPrecision::Normal { bits, flexible } => { |
| 71 | + let IntegerPrecision::Normal { |
| 72 | + bits: other_bits, |
| 73 | + flexible: other_flexible, |
| 74 | + } = other |
| 75 | + else { |
| 76 | + return Ordering::Greater; |
| 77 | + }; |
| 78 | + |
| 79 | + bits.cmp(other_bits) |
| 80 | + .then_with(|| flexible.cmp(other_flexible)) |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | +} |
0 commit comments