1use std::fmt::Display;
7use std::marker::PhantomData;
8
9use num_traits::{
10 AsPrimitive, CheckedAdd, CheckedDiv, CheckedMul, CheckedNeg, CheckedRem, CheckedShl,
11 CheckedShr, CheckedSub, PrimInt,
12};
13
14use crate::ast::{BinaryOp, PrimitiveType};
15use crate::ty::value::ConstValue;
16
17#[must_use]
20pub fn width(p: PrimitiveType) -> Option<&'static dyn Width> {
21 use PrimitiveType as P;
22 Some(match p {
23 P::Int8 => &In::<i8>(PhantomData),
24 P::Int16 => &In::<i16>(PhantomData),
25 P::Int32 => &In::<i32>(PhantomData),
26 P::Int | P::Int64 => &In::<i64>(PhantomData),
27 P::UInt8 | P::Byte => &In::<u8>(PhantomData),
28 P::UInt16 => &In::<u16>(PhantomData),
29 P::UInt32 => &In::<u32>(PhantomData),
30 P::UInt | P::UInt64 | P::Address => &In::<u64>(PhantomData),
31 P::Bool => return None,
32 })
33}
34
35pub trait Width {
38 fn signed(&self, v: i64) -> Option<ConstValue>;
41 fn unsigned(&self, v: u64) -> Option<ConstValue>;
44 fn holds(&self, v: ConstValue) -> bool;
46 fn bounds(&self) -> (String, String);
48 fn range(&self) -> (i128, i128);
50 fn binary(&self, op: BinaryOp, a: ConstValue, b: ConstValue) -> Option<ConstValue>;
54 fn compare(&self, op: BinaryOp, a: ConstValue, b: ConstValue) -> Option<bool>;
56 fn neg(&self, a: ConstValue) -> Option<ConstValue>;
58 fn not(&self, a: ConstValue) -> Option<ConstValue>;
60 fn cast(&self, v: ConstValue) -> Option<ConstValue>;
63}
64
65struct In<T>(PhantomData<T>);
67
68trait Scalar:
71 PrimInt
72 + CheckedAdd
73 + CheckedSub
74 + CheckedMul
75 + CheckedDiv
76 + CheckedRem
77 + CheckedShl
78 + CheckedShr
79 + CheckedNeg
80 + TryFrom<i64>
81 + TryFrom<u64>
82 + TryFrom<ConstValue>
83 + Into<ConstValue>
84 + Display
85{
86 fn cast_from(v: ConstValue) -> Option<Self>;
88}
89
90impl<T> Scalar for T
91where
92 T: PrimInt
93 + CheckedAdd
94 + CheckedSub
95 + CheckedMul
96 + CheckedDiv
97 + CheckedRem
98 + CheckedShl
99 + CheckedShr
100 + CheckedNeg
101 + TryFrom<i64>
102 + TryFrom<u64>
103 + TryFrom<ConstValue>
104 + Into<ConstValue>
105 + Display
106 + 'static,
107 i8: AsPrimitive<T>,
108 i16: AsPrimitive<T>,
109 i32: AsPrimitive<T>,
110 i64: AsPrimitive<T>,
111 u8: AsPrimitive<T>,
112 u16: AsPrimitive<T>,
113 u32: AsPrimitive<T>,
114 u64: AsPrimitive<T>,
115{
116 fn cast_from(v: ConstValue) -> Option<Self> {
117 Some(match v {
118 ConstValue::Int8(x) => x.as_(),
119 ConstValue::Int16(x) => x.as_(),
120 ConstValue::Int32(x) => x.as_(),
121 ConstValue::Int64(x) => x.as_(),
122 ConstValue::UInt8(x) => x.as_(),
123 ConstValue::UInt16(x) => x.as_(),
124 ConstValue::UInt32(x) => x.as_(),
125 ConstValue::UInt64(x) => x.as_(),
126 ConstValue::Bool(_) => return None,
127 })
128 }
129}
130
131impl<T: Scalar> Width for In<T> {
132 fn signed(&self, v: i64) -> Option<ConstValue> {
133 T::try_from(v).ok().map(Into::into)
134 }
135
136 fn unsigned(&self, v: u64) -> Option<ConstValue> {
137 T::try_from(v).ok().map(Into::into)
138 }
139
140 fn holds(&self, v: ConstValue) -> bool {
141 T::try_from(v).is_ok()
142 }
143
144 fn bounds(&self) -> (String, String) {
145 (T::min_value().to_string(), T::max_value().to_string())
146 }
147
148 fn range(&self) -> (i128, i128) {
149 let int = |v: T| v.into().integer().unwrap_or_default();
150 (int(T::min_value()), int(T::max_value()))
151 }
152
153 fn binary(&self, op: BinaryOp, a: ConstValue, b: ConstValue) -> Option<ConstValue> {
154 use BinaryOp as B;
155 let a = T::try_from(a).ok()?;
156 let b = T::try_from(b).ok()?;
157 let v = match op {
158 B::Add => a.checked_add(&b)?,
159 B::Sub => a.checked_sub(&b)?,
160 B::Mul => a.checked_mul(&b)?,
161 B::Div => a.checked_div(&b)?,
162 B::Mod => a.checked_rem(&b)?,
163 B::BitAnd => a & b,
164 B::BitOr => a | b,
165 B::BitXor => a ^ b,
166 B::Shl => a.checked_shl(b.to_u32()?)?,
167 B::Shr => a.checked_shr(b.to_u32()?)?,
168 B::Eq | B::Ne | B::Lt | B::Le | B::Gt | B::Ge | B::And | B::Or => return None,
169 };
170 Some(v.into())
171 }
172
173 fn compare(&self, op: BinaryOp, a: ConstValue, b: ConstValue) -> Option<bool> {
174 use BinaryOp as B;
175 let a = T::try_from(a).ok()?;
176 let b = T::try_from(b).ok()?;
177 Some(match op {
178 B::Eq => a == b,
179 B::Ne => a != b,
180 B::Lt => a < b,
181 B::Le => a <= b,
182 B::Gt => a > b,
183 B::Ge => a >= b,
184 _ => return None,
185 })
186 }
187
188 fn neg(&self, a: ConstValue) -> Option<ConstValue> {
189 T::try_from(a).ok()?.checked_neg().map(Into::into)
190 }
191
192 fn not(&self, a: ConstValue) -> Option<ConstValue> {
193 Some((!T::try_from(a).ok()?).into())
194 }
195
196 fn cast(&self, v: ConstValue) -> Option<ConstValue> {
197 T::cast_from(v).map(Into::into)
198 }
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204
205 #[test]
206 fn a_literal_enters_a_width_or_does_not() {
207 let w = width(PrimitiveType::UInt8).unwrap();
208 assert_eq!(w.signed(255), Some(ConstValue::UInt8(255)));
209 assert_eq!(w.signed(256), None);
210 assert_eq!(w.signed(-1), None);
211 assert_eq!(w.bounds(), ("0".to_owned(), "255".to_owned()));
212 let w = width(PrimitiveType::Int8).unwrap();
213 assert_eq!(w.signed(-128), Some(ConstValue::Int8(-128)));
214 assert_eq!(w.signed(128), None);
215 let w = width(PrimitiveType::UInt).unwrap();
216 assert_eq!(w.unsigned(u64::MAX), Some(ConstValue::UInt64(u64::MAX)));
217 assert!(width(PrimitiveType::Bool).is_none());
218 }
219
220 #[test]
221 fn an_operation_is_rusts_checked_one_in_the_width() {
222 let w = width(PrimitiveType::UInt8).unwrap();
223 let (a, b) = (ConstValue::UInt8(200), ConstValue::UInt8(100));
224 assert_eq!(w.binary(BinaryOp::Add, a, b), None);
225 assert_eq!(w.binary(BinaryOp::Sub, a, b), Some(ConstValue::UInt8(100)));
226 assert_eq!(w.binary(BinaryOp::Div, a, ConstValue::UInt8(0)), None);
227 assert_eq!(
228 w.binary(BinaryOp::Shl, ConstValue::UInt8(1), ConstValue::UInt8(9)),
229 None
230 );
231 assert_eq!(w.compare(BinaryOp::Lt, b, a), Some(true));
232 assert_eq!(w.binary(BinaryOp::Add, a, ConstValue::Int64(1)), None);
234 assert!(!w.holds(ConstValue::Int64(1)));
235 let w = width(PrimitiveType::Int8).unwrap();
236 assert_eq!(w.neg(ConstValue::Int8(-128)), None);
237 assert_eq!(w.not(ConstValue::Int8(0)), Some(ConstValue::Int8(-1)));
238 }
239
240 #[test]
242 fn a_cast_is_rusts_as() {
243 let u8w = width(PrimitiveType::UInt8).unwrap();
244 assert_eq!(
245 u8w.cast(ConstValue::UInt16(300)),
246 Some(ConstValue::UInt8(44))
247 );
248 assert_eq!(u8w.cast(ConstValue::Int8(-1)), Some(ConstValue::UInt8(255)));
249 let i8w = width(PrimitiveType::Int8).unwrap();
250 assert_eq!(
251 i8w.cast(ConstValue::UInt8(200)),
252 Some(ConstValue::Int8(-56))
253 );
254 let uw = width(PrimitiveType::UInt).unwrap();
255 assert_eq!(
256 uw.cast(ConstValue::Int64(-1)),
257 Some(ConstValue::UInt64(u64::MAX))
258 );
259 assert_eq!(uw.cast(ConstValue::UInt32(7)), Some(ConstValue::UInt64(7)));
260 assert_eq!(uw.cast(ConstValue::Bool(true)), None);
261 }
262}