predicator-rs 0.1.0

The Rust port of the predicator condition language: compiles a condition to a small instruction set and evaluates it on a stack machine, checked against the reference conformance corpus.
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! The `cast` instruction, as the reference's instruction-set text states
//! its conversion matrix, with the reference's code answering where the
//! text is silent.
//!
//! Two rules make every cell: undefined casts to undefined, and a value
//! that cannot become one of the target type casts to undefined too, never
//! to an error. Null casts to undefined for every target, by the second
//! rule.
//!
//! | from \ to | integer | float | string | boolean | date | datetime | duration |
//! |---|---|---|---|---|---|---|---|
//! | integer | = | widen | text | - | - | - | - |
//! | float | truncate | = | text | - | - | - | - |
//! | string | read | read | = | read | read | read | read |
//! | boolean | - | - | text | = | - | - | - |
//! | date | - | - | text | - | = | midnight UTC | - |
//! | datetime | - | - | text | - | its date | = | - |
//! | duration | - | - | text | - | - | - | = |
//!
//! `=` passes the value through and `-` is undefined; a list, a map, null
//! and undefined are `-` for every target, with one exception: a units map
//! (a map carrying `years`, `months`, `weeks`, `days`, `hours`, `minutes`
//! and `seconds` under their string names, every unit it holds an
//! integer, `milliseconds` included when it holds one) is a duration to a
//! cast. It passes through `duration` unchanged, still a map, and
//! `string` writes it in the duration-literal grammar. A string is read whole or not at
//! all, with no trimming: an integer as `-?[0-9]+`, a float as
//! `-?[0-9]+(\.[0-9]+)?`, a boolean as exactly `true` or `false`, a date as
//! `YYYY-MM-DD`, an instant as the text the tagged codec reads (a date, a
//! time, an offset; [`DateTime::parse`]) with a `T` before the time, as the
//! reference's text names an ISO 8601 datetime ([`is_iso_datetime`]), and a
//! duration as the duration-literal grammar ([`Duration::parse`]). A float
//! is written as the reference writes one (`json::float_text`), an instant
//! in UTC with the fraction left out when it is zero and six digits when it
//! is not.
//!
//! Where the answer is a value this crate cannot hold, or one the reference
//! raises on, the cast fails the run; [`refusal`] is the one place each
//! such refusal is made.

use crate::civil::DurationText;
use crate::{Date, DateTime, Duration, EvaluationError, Value};

/// The seven type names a cast converts to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Target {
    Integer,
    Float,
    String,
    Boolean,
    Date,
    DateTime,
    Duration,
}

impl Target {
    /// The target `name` names, or `None` when it names none.
    pub(super) fn named(name: &str) -> Option<Target> {
        Some(match name {
            "integer" => Target::Integer,
            "float" => Target::Float,
            "string" => Target::String,
            "boolean" => Target::Boolean,
            "date" => Target::Date,
            "datetime" => Target::DateTime,
            "duration" => Target::Duration,
            _ => return None,
        })
    }
}

/// Why a cast fails the run rather than answer a value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Refused {
    /// The integer the cast answers is outside `i64`; the reference's
    /// integers have no bound.
    IntegerOverflow,
    /// The string names a number too large for a finite float; the
    /// reference raises.
    NonFinite,
    /// The instant is outside the years 0 to 9999 an instant's text
    /// carries; the reference raises past 9999.
    OutOfRange,
}

/// The refusal of a cast to `target`: the one function that turns a cast
/// the reference raises on, or answers with a value this crate cannot hold,
/// into an error.
///
/// | cast | reason |
/// |---|---|
/// | a string or a float to an integer outside `i64` | `integer_overflow` |
/// | a string to a duration with a unit outside `i64` | `integer_overflow` |
/// | a string to a float too large for a finite float | `non_finite_number` |
/// | an instant outside the years 0 to 9999 to a string | `date_out_of_range` |
fn refusal(refused: Refused, target: Target) -> EvaluationError {
    let target = format!("{target:?}").to_lowercase();
    match refused {
        Refused::IntegerOverflow => EvaluationError::new(
            "integer_overflow",
            format!("the cast to {target} answers an integer outside the 64-bit range"),
        ),
        Refused::NonFinite => EvaluationError::new(
            "non_finite_number",
            format!("the cast to {target} answers a number too large for a finite float"),
        ),
        Refused::OutOfRange => EvaluationError::new(
            "date_out_of_range",
            format!("the cast to {target} takes an instant outside the years 0 to 9999"),
        ),
    }
}

/// `cast`: `value` converted to `target`, undefined when it cannot be one,
/// or the refusal of a cast this crate cannot answer.
pub(super) fn cast(value: Value, target: Target) -> Result<Value, EvaluationError> {
    convert(value, target).map_err(|refused| refusal(refused, target))
}

fn convert(value: Value, target: Target) -> Result<Value, Refused> {
    Ok(match (value, target) {
        (value @ Value::Integer(_), Target::Integer)
        | (value @ Value::Float(_), Target::Float)
        | (value @ Value::String(_), Target::String)
        | (value @ Value::Bool(_), Target::Boolean)
        | (value @ Value::Date(_), Target::Date)
        | (value @ Value::DateTime(_), Target::DateTime)
        | (value @ Value::Duration(_), Target::Duration) => value,
        // Widened to the nearest float, ties to even: exact up to 2^53.
        (Value::Integer(number), Target::Float) => Value::Float(number as f64),
        (Value::Float(number), Target::Integer) => Value::Integer(truncate(number)?),
        (Value::Integer(number), Target::String) => Value::String(number.to_string()),
        (Value::Float(number), Target::String) => Value::String(crate::json::float_text(number)),
        (Value::Bool(flag), Target::String) => Value::String(flag.to_string()),
        (Value::Date(date), Target::String) => Value::String(date.to_string()),
        (Value::DateTime(instant), Target::String) => Value::String(instant_text(instant)?),
        (Value::Duration(duration), Target::String) => Value::String(duration.to_string()),
        (Value::Date(date), Target::DateTime) => midnight(date),
        (Value::DateTime(instant), Target::Date) => Value::Date(instant.date()),
        (Value::String(ref text), target) => read(text, target)?,
        (value @ Value::Map(_), Target::Duration) if matches!(&value, Value::Map(map) if units_map(map).is_some()) => {
            value
        }
        (Value::Map(ref map), Target::String) => match units_map(map) {
            Some(duration) => Value::String(duration.to_string()),
            None => Value::Undefined,
        },
        _ => Value::Undefined,
    })
}

/// The units a map carries to be read by a cast as a duration: the seven
/// the reference's duration always holds.
const DURATION_KEYS: [&str; 7] = [
    "years", "months", "weeks", "days", "hours", "minutes", "seconds",
];

/// The duration a units map names: a map carrying each of
/// [`DURATION_KEYS`] under its string name, every unit it holds
/// (`milliseconds` included, which may be left out) an integer.
fn units_map(map: &crate::Map) -> Option<Duration> {
    Duration::from_unit_map(map, &DURATION_KEYS)
}

/// A string read as `target`, whole or not at all.
fn read(text: &str, target: Target) -> Result<Value, Refused> {
    Ok(match target {
        Target::Integer if is_decimal(text, false) => text
            .parse::<i64>()
            .map(Value::Integer)
            .map_err(|_| Refused::IntegerOverflow)?,
        Target::Float if is_decimal(text, true) => {
            let number = text.parse::<f64>().map_err(|_| Refused::NonFinite)?;
            if !number.is_finite() {
                return Err(Refused::NonFinite);
            }
            Value::Float(number)
        }
        Target::Boolean => match text {
            "true" => Value::Bool(true),
            "false" => Value::Bool(false),
            _ => Value::Undefined,
        },
        Target::Date => Date::parse(text).map_or(Value::Undefined, Value::Date),
        Target::DateTime if is_iso_datetime(text) => {
            DateTime::parse(text).map_or(Value::Undefined, Value::DateTime)
        }
        Target::Duration => match Duration::parse(text) {
            Ok(duration) => Value::Duration(duration),
            Err(DurationText::Malformed) => Value::Undefined,
            Err(DurationText::Overflow) => return Err(Refused::IntegerOverflow),
        },
        Target::Integer | Target::Float | Target::String | Target::DateTime => Value::Undefined,
    })
}

/// Whether `text` is `-?[0-9]+`, and with `fraction` also
/// `-?[0-9]+\.[0-9]+`.
fn is_decimal(text: &str, fraction: bool) -> bool {
    let unsigned = text.strip_prefix('-').unwrap_or(text);
    let (whole, part) = match unsigned.split_once('.') {
        Some((whole, part)) if fraction => (whole, part),
        Some(_) => return false,
        None => (unsigned, "0"),
    };
    let digits = |run: &str| !run.is_empty() && run.bytes().all(|byte| byte.is_ascii_digit());
    digits(whole) && digits(part)
}

/// Whether `text` separates its date from its time with a `T`, as an ISO
/// 8601 datetime does. The tagged codec's reader, which a cast shares, also
/// takes a space there, as the reference's code does; a cast follows the
/// reference's text and does not.
fn is_iso_datetime(text: &str) -> bool {
    text.as_bytes().get(10) == Some(&b'T')
}

/// A float truncated toward zero, when the integer fits in `i64`.
fn truncate(number: f64) -> Result<i64, Refused> {
    /// 2^63, the first float past `i64`.
    const LIMIT: f64 = 9_223_372_036_854_775_808.0;
    let whole = number.trunc();
    if (-LIMIT..LIMIT).contains(&whole) {
        // In range and whole, so the conversion is exact.
        Ok(whole as i64)
    } else {
        Err(Refused::IntegerOverflow)
    }
}

/// `date` at midnight UTC, or undefined when its year is outside the 0 to
/// 9999 an instant holds.
fn midnight(date: Date) -> Value {
    if !(0..=9999).contains(&date.year()) {
        return Value::Undefined;
    }
    DateTime::new(date, 0, 0, 0, 0).map_or(Value::Undefined, Value::DateTime)
}

/// An instant's text, when its year is within 0 to 9999.
fn instant_text(instant: DateTime) -> Result<String, Refused> {
    if (0..=9999).contains(&instant.date().year()) {
        Ok(instant.to_string())
    } else {
        Err(Refused::OutOfRange)
    }
}

#[cfg(test)]
mod tests {
    use crate::{Context, Date, DateTime, Duration, Error, Instructions, Options, Value, evaluate};

    /// `x::target`, `x` bound to `value`.
    fn cast(value: Value, target: &str) -> Result<Value, Error> {
        let mut context = Context::new();
        context.insert("x", value);
        evaluate(
            &Instructions::from_json(&format!(r#"[["load","x"],["cast","{target}"]]"#)).unwrap(),
            &context,
            &Options::new(),
        )
    }

    fn answer(value: Value, target: &str) -> Value {
        cast(value, target).unwrap()
    }

    fn reason(value: Value, target: &str) -> String {
        match cast(value, target) {
            Ok(value) => format!("no error: {value:?}"),
            Err(error) => error.reason().to_owned(),
        }
    }

    fn text(value: &str) -> Value {
        Value::from(value)
    }

    // Sabotage: with null cast to a string answering "null", this test
    // fails.
    #[test]
    fn a_value_with_no_conversion_casts_to_undefined() {
        let mut map = crate::Map::new();
        map.insert("a", Value::from(1));
        for target in [
            "integer", "float", "string", "boolean", "date", "datetime", "duration",
        ] {
            for value in [
                Value::Null,
                Value::Undefined,
                Value::from(vec![Value::from(1)]),
                Value::Map(map.clone()),
            ] {
                assert_eq!(answer(value.clone(), target), Value::Undefined, "{value:?}");
            }
        }
        assert_eq!(answer(Value::from(true), "float"), Value::Undefined);
        assert_eq!(answer(Value::from(1.0), "boolean"), Value::Undefined);
        assert_eq!(
            answer(Value::Duration(Duration::default()), "date"),
            Value::Undefined
        );
    }

    // Sabotage: with a float cast to an integer by rounding, this test
    // fails.
    #[test]
    fn numbers_widen_truncate_and_refuse_past_the_integer_range() {
        assert_eq!(
            answer(Value::from(9_007_199_254_740_993), "float"),
            Value::from(9_007_199_254_740_992.0)
        );
        assert_eq!(answer(Value::from(-2.7), "integer"), Value::from(-2));
        assert_eq!(answer(Value::from(2.7), "integer"), Value::from(2));
        assert_eq!(
            answer(Value::from(-9_223_372_036_854_775_808.0), "integer"),
            Value::from(i64::MIN)
        );
        assert_eq!(
            reason(Value::from(9_223_372_036_854_775_808.0), "integer"),
            "integer_overflow"
        );
        assert_eq!(reason(Value::from(-1e19), "integer"), "integer_overflow");
    }

    // Sabotage: with a float written by Rust's own Display, this test fails.
    #[test]
    fn a_float_is_written_as_the_reference_writes_one() {
        assert_eq!(answer(Value::from(1e16), "string"), text("1.0e16"));
        assert_eq!(answer(Value::from(42.0), "string"), text("42.0"));
        assert_eq!(answer(Value::from(0.0001), "string"), text("0.0001"));
        assert_eq!(answer(Value::from(-0.0), "string"), text("-0.0"));
        assert_eq!(answer(Value::from(-7), "string"), text("-7"));
    }

    // Sabotage: with the integer read through str::parse alone (which
    // takes a leading plus), this test fails.
    #[test]
    fn a_string_is_read_whole_as_a_number() {
        assert_eq!(answer(text("+5"), "integer"), Value::Undefined);
        assert_eq!(answer(text("-0"), "integer"), Value::from(0));
        assert_eq!(answer(text("00012"), "integer"), Value::from(12));
        assert_eq!(answer(text("-"), "integer"), Value::Undefined);
        assert_eq!(answer(text("1.5"), "integer"), Value::Undefined);
        assert_eq!(
            answer(text("\u{FF14}\u{FF12}"), "integer"),
            Value::Undefined
        );
        assert_eq!(
            reason(text("9223372036854775808"), "integer"),
            "integer_overflow"
        );
        assert_eq!(
            answer(text("-9223372036854775808"), "integer"),
            Value::from(i64::MIN)
        );
        assert_eq!(answer(text("1."), "float"), Value::Undefined);
        assert_eq!(answer(text(".5"), "float"), Value::Undefined);
        assert_eq!(answer(text("1.2.3"), "float"), Value::Undefined);
        assert_eq!(answer(text("inf"), "float"), Value::Undefined);
        assert_eq!(answer(text("-0"), "float"), Value::from(-0.0));
        let huge = format!("1{}.0", "0".repeat(400));
        assert_eq!(reason(text(&huge), "float"), "non_finite_number");
        let tiny = format!("0.{}1", "0".repeat(400));
        assert_eq!(answer(text(&tiny), "float"), Value::from(0.0));
    }

    // Sabotage: with midnight taking a date of any year, this test fails.
    #[test]
    fn dates_and_instants_bridge_inside_the_years_an_instant_holds() {
        let far = Date::new(10_000, 1, 1).unwrap();
        let early = Date::new(-1, 12, 31).unwrap();
        assert_eq!(answer(Value::Date(far), "datetime"), Value::Undefined);
        assert_eq!(answer(Value::Date(early), "datetime"), Value::Undefined);
        assert_eq!(answer(Value::Date(far), "string"), text("10000-01-01"));
        assert_eq!(answer(Value::Date(early), "string"), text("-0001-12-31"));
        let past = DateTime::new(far, 0, 0, 0, 0).unwrap();
        let before = DateTime::new(early, 23, 59, 59, 999_999).unwrap();
        assert_eq!(reason(Value::DateTime(past), "string"), "date_out_of_range");
        assert_eq!(
            reason(Value::DateTime(before), "string"),
            "date_out_of_range"
        );
        assert_eq!(answer(Value::DateTime(past), "date"), Value::Date(far));
        let last = DateTime::new(Date::new(9999, 12, 31).unwrap(), 23, 59, 59, 999_999).unwrap();
        assert_eq!(
            answer(Value::DateTime(last), "string"),
            text("9999-12-31T23:59:59.999999Z")
        );
    }

    // Sabotage: with is_iso_datetime also taking a space at byte 10, this
    // test fails.
    #[test]
    fn a_string_is_read_as_a_date_or_an_instant_in_the_reference_forms() {
        let instant = |value: &str| match answer(text(value), "datetime") {
            Value::DateTime(instant) => instant.to_string(),
            other => format!("{other:?}"),
        };
        assert_eq!(instant("2026-08-09T10:00:00+05"), "2026-08-09T05:00:00Z");
        assert_eq!(instant("2026-08-09T10:00:00+0530"), "2026-08-09T04:30:00Z");
        assert_eq!(
            instant("2026-08-09T10:00:00,5Z"),
            "2026-08-09T10:00:00.500000Z"
        );
        assert_eq!(
            instant("2026-08-09T10:00:00.1234567Z"),
            "2026-08-09T10:00:00.123456Z"
        );
        for refused in [
            "2026-08-09T10:00:00",
            "2026-08-09T10:00:00-00:00",
            "2026-08-09t10:00:00Z",
            "2026-08-09T10:00Z",
            "2026-08-09T24:00:00Z",
            "20260809T100000Z",
            "-0005-08-09T10:00:00Z",
            "+2026-08-09T10:00:00Z",
            "2026-08-09 10:00:00Z",
        ] {
            assert_eq!(instant(refused), "Undefined", "{refused}");
        }
        assert_eq!(
            answer(text("2024-02-29"), "date"),
            Value::Date(Date::new(2024, 2, 29).unwrap())
        );
        for refused in [
            "2026-02-29",
            "-0005-01-01",
            "+2026-08-09",
            "10000-01-01",
            "20260809",
            "2026-8-9",
        ] {
            assert_eq!(answer(text(refused), "date"), Value::Undefined, "{refused}");
        }
    }

    // Sabotage: with a duration unit past i64 read as undefined, this test
    // fails.
    #[test]
    fn a_string_is_read_as_a_duration_or_refused_past_the_integer_range() {
        assert_eq!(
            answer(text("1d2h"), "duration"),
            Value::Duration(Duration {
                days: 1,
                hours: 2,
                ..Duration::default()
            })
        );
        assert_eq!(
            reason(text("9223372036854775808s"), "duration"),
            "integer_overflow"
        );
        assert_eq!(
            reason(text("9223372036854775807s1s"), "duration"),
            "integer_overflow"
        );
        assert_eq!(answer(text("1d 2h"), "duration"), Value::Undefined);
        assert_eq!(
            answer(
                Value::Duration(Duration {
                    days: 3,
                    ..Duration::default()
                }),
                "string"
            ),
            text("3d")
        );
    }

    // Sabotage: with units_map requiring no key (any map read as a
    // duration), this test fails.
    #[test]
    fn a_units_map_casts_as_a_duration() {
        let units = |extra: &[(&str, Value)]| {
            let mut map: crate::Map = [
                "years", "months", "weeks", "days", "hours", "minutes", "seconds",
            ]
            .into_iter()
            .map(|name| (name, Value::from(0)))
            .collect();
            map.insert("days", Value::from(3));
            for (key, value) in extra {
                map.insert(*key, value.clone());
            }
            Value::Map(map)
        };
        // It passes through ::duration unchanged, still a map.
        assert_eq!(answer(units(&[]), "duration"), units(&[]));
        assert_eq!(answer(units(&[]), "string"), text("3d"));
        assert_eq!(
            answer(
                units(&[("milliseconds", Value::from(500)), ("other", text("x"))]),
                "string"
            ),
            text("3d500ms")
        );
        // A unit left out, or one that is not an integer, is not a units map.
        let mut short = crate::Map::new();
        short.insert("days", Value::from(3));
        for value in [
            Value::Map(short),
            units(&[("days", Value::from(1.5))]),
            units(&[("milliseconds", text("5"))]),
        ] {
            assert_eq!(
                answer(value.clone(), "duration"),
                Value::Undefined,
                "{value:?}"
            );
            assert_eq!(
                answer(value.clone(), "string"),
                Value::Undefined,
                "{value:?}"
            );
        }
    }

    // Sabotage: with an unknown type name read as a cast to integer, this
    // test fails.
    #[test]
    fn cast_takes_one_of_the_seven_type_names_and_one_value() {
        let run = |text: &str| {
            evaluate(
                &Instructions::from_json(text).unwrap(),
                &Context::new(),
                &Options::new(),
            )
            .unwrap_err()
            .reason()
            .to_owned()
        };
        for operands in [r#""widget""#, "5", r#""Integer""#, r#""integer","float""#] {
            assert_eq!(
                run(&format!(r#"[["lit",1],["cast",{operands}]]"#)),
                "unknown_instruction",
                "{operands}"
            );
        }
        assert_eq!(run(r#"[["lit",1],["cast"]]"#), "unknown_instruction");
        assert_eq!(run(r#"[["cast","string"]]"#), "insufficient_operands");
    }
}