cel 0.14.5

A parser and interpreter for the Common Expression Language (CEL)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use crate::common::traits::Negator;
use crate::common::traits::{self, Comparer};
use crate::common::types::{CelDouble, CelString, CelUInt, Kind, Type};
use crate::common::value::{Downcast, Val};
use crate::ExecutionError;
use std::borrow::Cow;
use std::cmp::Ordering;
use std::ops::{Deref, Neg};

#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct Int(i64);

impl Int {
    pub fn into_inner(self) -> i64 {
        self.0
    }

    pub fn inner(&self) -> &i64 {
        &self.0
    }
}

impl Deref for Int {
    type Target = i64;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Val for Int {
    fn get_type(&self) -> &Type {
        &super::INT_TYPE
    }

    fn as_adder(&self) -> Option<&dyn traits::Adder> {
        Some(self)
    }

    fn as_comparer(&self) -> Option<&dyn traits::Comparer> {
        Some(self)
    }

    fn as_divider(&self) -> Option<&dyn traits::Divider> {
        Some(self)
    }

    fn as_modder(&self) -> Option<&dyn traits::Modder> {
        Some(self)
    }

    fn as_multiplier(&self) -> Option<&dyn traits::Multiplier> {
        Some(self)
    }

    fn as_negator(&self) -> Option<&dyn Negator> {
        Some(self)
    }

    fn as_subtractor(&self) -> Option<&dyn traits::Subtractor> {
        Some(self)
    }

    fn as_zeroer(&self) -> Option<&dyn traits::Zeroer> {
        Some(self)
    }

    fn equals(&self, other: &dyn Val) -> bool {
        self.compare(other)
            .map(|r| r == Ordering::Equal)
            .unwrap_or(false)
    }

    fn clone_as_boxed(&self) -> Box<dyn Val> {
        Box::new(Int(self.0))
    }
}

impl traits::Adder for Int {
    fn add<'a>(&'a self, other: &dyn Val) -> Result<Cow<'a, dyn Val>, ExecutionError> {
        if let Some(i) = other.downcast_ref::<Int>() {
            let t: Self = self
                .0
                .checked_add(i.0)
                .ok_or_else(|| ExecutionError::Overflow("add", self.0.into(), i.0.into()))?
                .into();
            let b: Box<dyn Val> = Box::new(t);
            Ok(Cow::Owned(b))
        } else {
            Err(ExecutionError::NoSuchOverload)
        }
    }
}

impl traits::Comparer for Int {
    fn compare(&self, rhs: &dyn Val) -> Result<Ordering, ExecutionError> {
        if let Some(i) = rhs.downcast_ref::<Self>() {
            Ok(self.0.cmp(&i.0))
        } else if let Some(u) = rhs.downcast_ref::<CelUInt>() {
            Ok((*self.inner())
                .try_into()
                .map(|a: u64| a.cmp(u.inner()))
                // If the i64 doesn't fit into a u64 it must be less than 0.
                .unwrap_or(Ordering::Less))
        } else if let Some(d) = rhs.downcast_ref::<CelDouble>() {
            Ok((*self.inner() as f64)
                .partial_cmp(d.inner())
                .ok_or(ExecutionError::NoSuchOverload)?)
        } else {
            Err(ExecutionError::NoSuchOverload)
        }
    }
}

impl traits::Divider for Int {
    fn div<'a>(&self, rhs: &'a dyn Val) -> Result<Cow<'a, dyn Val>, ExecutionError> {
        if let Some(i) = rhs.downcast_ref::<Int>() {
            if i.0 == 0 {
                return Err(ExecutionError::DivisionByZero(self.0.into()));
            }
            let t: Self = (self
                .0
                .checked_div(i.0)
                .ok_or_else(|| ExecutionError::Overflow("div", self.0.into(), i.0.into()))?)
            .into();
            let b: Box<dyn Val> = Box::new(t);
            Ok(Cow::Owned(b))
        } else {
            Err(ExecutionError::NoSuchOverload)
        }
    }
}

impl traits::Modder for Int {
    fn modulo<'a>(&self, rhs: &'a dyn Val) -> Result<Cow<'a, dyn Val>, ExecutionError> {
        if let Some(i) = rhs.downcast_ref::<Int>() {
            if i.0 == 0 {
                return Err(ExecutionError::RemainderByZero(self.0.into()));
            }
            let t: Self = (self
                .0
                .checked_rem(i.0)
                .ok_or_else(|| ExecutionError::Overflow("rem", self.0.into(), i.0.into()))?)
            .into();
            let b: Box<dyn Val> = Box::new(t);
            Ok(Cow::Owned(b))
        } else {
            Err(ExecutionError::NoSuchOverload)
        }
    }
}

impl traits::Multiplier for Int {
    fn mul<'a>(&self, rhs: &'a dyn Val) -> Result<Cow<'a, dyn Val>, ExecutionError> {
        if let Some(i) = rhs.downcast_ref::<Int>() {
            let t: Self = (self
                .0
                .checked_mul(i.0)
                .ok_or_else(|| ExecutionError::Overflow("mul", self.0.into(), i.0.into()))?)
            .into();
            let b: Box<dyn Val> = Box::new(t);
            Ok(Cow::Owned(b))
        } else {
            Err(ExecutionError::NoSuchOverload)
        }
    }
}

impl Negator for Int {
    fn negate(&self) -> Result<Box<dyn Val>, ExecutionError> {
        Ok(Box::new(Self::from(self.0.neg())))
    }
}

impl traits::Subtractor for Int {
    fn sub<'a>(&'a self, rhs: &dyn Val) -> Result<Cow<'a, dyn Val>, ExecutionError> {
        if let Some(i) = rhs.downcast_ref::<Int>() {
            Ok(Cow::<dyn Val>::Owned(Box::new(Self::from(
                self.0
                    .checked_sub(i.0)
                    .ok_or_else(|| ExecutionError::Overflow("sub", self.0.into(), i.0.into()))?,
            ))))
        } else {
            Err(ExecutionError::NoSuchOverload)
        }
    }
}

impl traits::Zeroer for Int {
    fn is_zero_value(&self) -> bool {
        self.0 == 0
    }
}

impl From<Int> for i64 {
    fn from(value: Int) -> Self {
        value.0
    }
}

impl From<i64> for Int {
    fn from(value: i64) -> Self {
        Self(value)
    }
}

impl TryFrom<Box<dyn Val>> for i64 {
    type Error = Box<dyn Val>;

    fn try_from(value: Box<dyn Val>) -> Result<Self, Self::Error> {
        if let Some(i) = value.downcast_ref::<Int>() {
            return Ok(i.0);
        }
        Err(value)
    }
}

impl<'a> TryFrom<&'a dyn Val> for &'a i64 {
    type Error = &'a dyn Val;

    fn try_from(value: &'a dyn Val) -> Result<Self, Self::Error> {
        if let Some(i) = value.downcast_ref::<Int>() {
            return Ok(&i.0);
        }
        Err(value)
    }
}

fn int<'a>(args: Vec<Cow<'a, dyn Val>>) -> Result<Cow<'a, dyn Val>, ExecutionError> {
    let mut args = args;
    let arg = args.remove(0).into_owned();
    let ret: Result<Box<Int>, Box<dyn Val>> = match arg.get_type().kind() {
        Kind::Int => arg.downcast::<Int>(),
        Kind::UInt => match arg.downcast::<CelUInt>() {
            Err(arg) => Err(arg),
            Ok(arg) => match i64::try_from(*arg.inner()) {
                Ok(value) => Ok(Box::new(Int::from(value))),
                Err(_) => {
                    return Err(ExecutionError::FunctionError {
                        function: "int".to_owned(),
                        message: "integer overflow".to_owned(),
                    });
                }
            },
        },
        Kind::Double => match arg.downcast::<CelDouble>() {
            Err(arg) => Err(arg),
            Ok(arg) => {
                let value = *arg.inner();
                // Double to int conversions are limited to (minInt, maxInt) non-inclusive.
                // 'i64::MAX as f64' rounds up to 2^63, and the largest double below that
                // is 2^63 - 2^10, so the check also keeps 'value as i64' from saturating.
                // 'i64::MIN as f64' is exactly -(2^63), so the exclusive lower bound
                // rejects a double that i64 could actually hold. NaN, -infinity and
                // infinity will also be rejected.
                if !(value > (i64::MIN as f64) && value < (i64::MAX as f64)) {
                    return Err(ExecutionError::FunctionError {
                        function: "int".to_owned(),
                        message: "integer overflow".to_owned(),
                    });
                }

                Ok(Box::new(Int::from(value as i64)))
            }
        },
        Kind::String => match arg.downcast::<CelString>() {
            Err(arg) => Err(arg),
            Ok(arg) => match arg.inner().parse::<i64>() {
                Ok(arg) => Ok(Box::new(Int::from(arg))),
                Err(e) => {
                    return Err(ExecutionError::FunctionError {
                        function: "int".to_owned(),
                        message: format!("string parse error: {e}"),
                    })
                }
            },
        },
        _ => Err(arg),
    };

    match ret {
        Ok(ret) => Ok(Cow::<dyn Val>::Owned(ret)),
        Err(arg) => Err(ExecutionError::FunctionError {
            function: "int".to_owned(),
            message: format!("cannot convert {arg:?} to int"),
        }),
    }
}

pub(crate) fn stdlib(env: &mut crate::Env) {
    env.add_overload("int", "int64_to_int64", vec![super::INT_TYPE], int)
        .expect("Must be unique id");
    env.add_overload("int", "uint64_to_int64", vec![super::UINT_TYPE], int)
        .expect("Must be unique id");
    env.add_overload("int", "double_to_int64", vec![super::DOUBLE_TYPE], int)
        .expect("Must be unique id");
    env.add_overload("int", "string_to_int64", vec![super::STRING_TYPE], int)
        .expect("Must be unique id");
}

#[cfg(test)]
mod tests {
    use crate::common::traits::Comparer;
    use crate::common::types::{CelDouble, CelInt, CelString, CelUInt};
    use crate::common::value::Val;
    use crate::{Context, Program};
    use std::cmp::Ordering::{Equal, Greater, Less};

    #[test]
    fn test_compare() {
        let one = CelInt::from(1);
        let two = CelInt::from(2);
        assert_eq!(one.compare(&two), Ok(Less));
        assert_eq!(two.compare(&one), Ok(Greater));
        assert_eq!(two.compare(&two), Ok(Equal));
    }

    #[test]
    fn test_equals() {
        let int = CelInt::from(42);
        let neg = CelInt::from(-42);
        assert!(int.equals(&int));
        assert!(int.equals(&CelUInt::from(42u64)));
        assert!(!neg.equals(&CelUInt::from(42u64)));
        assert!(int.equals(&CelDouble::from(42.0)));
        assert!(neg.equals(&CelDouble::from(-42.0)));
        assert!(!int.equals(&CelDouble::from(f64::NAN)));
        assert!(!neg.equals(&CelDouble::from(f64::NAN)));
        assert!(!int.equals(&CelString::from("42")));
    }

    #[test]
    fn test_conversion_boundaries() {
        let context = Context::default();

        // int(double) -> int
        // Accepted doubles are those in (-2^63, 2^63) exclusive. The upper bound
        // is 2^63 rather than i64::MAX because f64 cannot hold i64::MAX.
        // The largest double below 2^63 is:
        // 2^63 - 2^10 == 9223372036854774784
        let program = Program::compile("int(9223372036854774784.0)").unwrap();
        let value = program.execute(&context).unwrap();
        assert_eq!(value, 9223372036854774784i64.into());

        // int(double) -> int
        // The smallest double above -2^63 is:
        // -(2^63) + 2^10 == -9223372036854774784
        let program = Program::compile("int(-9223372036854774784.0)").unwrap();
        let value = program.execute(&context).unwrap();
        assert_eq!(value, (-9223372036854774784i64).into());

        // int(uint) -> int
        // i64::MAX == (2^63 - 1) is the largest uint that still fits in an int
        let program = Program::compile("int(9223372036854775807u)").unwrap();
        let value = program.execute(&context).unwrap();
        assert_eq!(value, 9223372036854775807i64.into());
    }

    #[test]
    fn test_conversion_errors() {
        let context = Context::default();

        // int(double) -> int
        // -2^63 is exactly representable as f64 and equals i64::MIN, but the
        // lower bound is exclusive, so it should not convert:
        // -(2^63) == -9223372036854775808
        let program = Program::compile("int(-9223372036854775808.0)").unwrap();
        let result = program.execute(&context);
        assert!(
            result.is_err(),
            "int(-9223372036854775808.0) should return error, got {result:?}"
        );

        // int(double) -> int
        // i64::MAX == 2^63 - 1 == 9223372036854775807 cannot be held by f64,
        // so this literal rounds up to 2^63, which is outside the accepted range.
        let program = Program::compile("int(9223372036854775807.0)").unwrap();
        let result = program.execute(&context);
        assert!(
            result.is_err(),
            "int(9223372036854775807.0) should return error, got {result:?}"
        );

        // int(double) -> int
        let program = Program::compile("int(double('NaN'))").unwrap();
        let result = program.execute(&context);
        assert!(
            result.is_err(),
            "int(double('NaN')) should return error, got {result:?}"
        );

        // int(double) -> int
        let program = Program::compile("int(double('infinity'))").unwrap();
        let result = program.execute(&context);
        assert!(
            result.is_err(),
            "int(double('infinity')) should return error, got {result:?}"
        );

        // int(double) -> int
        let program = Program::compile("int(double('-infinity'))").unwrap();
        let result = program.execute(&context);
        assert!(
            result.is_err(),
            "int(double('-infinity')) should return error, got {result:?}"
        );

        // int(uint) -> int
        // One above the largest uint that fits in an int:
        // (i64::MAX + 1) == 2^63 == 9223372036854775808
        let program = Program::compile("int(9223372036854775808u)").unwrap();
        let result = program.execute(&context);
        assert!(
            result.is_err(),
            "int(9223372036854775808u) should return error, got {result:?}"
        );
    }
}