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
//! The rich-type instructions, `object_new`, `object_set`, `duration` and
//! `relative_date`, as the reference's instruction-set text states them.
//!
//! A duration is read as the map of its eight units that the instruction-set
//! text makes it: `object_set` writes into a map or a duration, which answers
//! the plain map of its units with the key written, and `relative_date`
//! takes a duration or a plain map, read as the duration its unit names
//! spell. A date and an instant are not maps to either. `duration` builds the one duration kind
//! the crate has, the same kind a context or a date subtraction gives, and
//! `relative_date` moves the current time by any duration exactly as `add`
//! and `subtract` move an instant (`arithmetic`), so a month is 30 days and
//! a year 365 wherever a duration is applied.

use super::Fault;
use super::arithmetic::shift_instant;
use crate::{DateTime, Duration, EvaluationError, Key, Value};

/// `object_set`: `target` with `key` set to `value`. A duration target is
/// the plain map of its eight units, so the answer is that map with the key
/// written. A target that is neither a map nor a duration fails with the
/// reason `invalid_stack_value`.
pub(super) fn object_set(mut target: Value, key: &str, value: Value) -> Result<Value, Fault> {
    if let Value::Duration(duration) = &target {
        target = Value::Map(duration.unit_map());
    }
    if let Value::Map(map) = &mut target {
        map.insert(Key::from(key), value);
        return Ok(target);
    }
    Err(invalid_stack_value(&format!(
        "object_set takes a map beneath the value, not a {}",
        super::type_name(&target)
    )))
}

fn invalid_stack_value(message: &str) -> Fault {
    EvaluationError::new("invalid_stack_value", message).into()
}

/// The unit a `duration` unit string names, by its name in the duration's
/// map; `None` for a string that names none.
fn unit_name(unit: &str) -> Option<&'static str> {
    Some(match unit {
        "y" | "year" | "years" => "years",
        "mo" | "month" | "months" => "months",
        "w" | "week" | "weeks" => "weeks",
        "d" | "day" | "days" => "days",
        "h" | "hour" | "hours" => "hours",
        "m" | "min" | "minute" | "minutes" => "minutes",
        "s" | "sec" | "second" | "seconds" => "seconds",
        "ms" | "millisecond" | "milliseconds" => "milliseconds",
        _ => return None,
    })
}

/// `duration`: the duration `pairs` builds, each `[amount, unit]` setting
/// its unit, a later pair overwriting an earlier one naming the same unit.
/// The first pair that is not an integer and a string fails with the reason
/// `invalid_duration_format`, and the first unit string that names no unit
/// with `invalid_duration_unit`, whichever comes first.
pub(super) fn duration(pairs: &[Value]) -> Result<Duration, Fault> {
    let mut duration = Duration::default();
    for pair in pairs {
        let (amount, unit) = match pair {
            Value::List(parts) => match parts.as_slice() {
                [Value::Integer(amount), Value::String(unit)] => (*amount, unit),
                _ => return Err(invalid_format()),
            },
            _ => return Err(invalid_format()),
        };
        let slot = unit_name(unit).and_then(|name| duration.unit_mut(name));
        match slot {
            Some(slot) => *slot = amount,
            None => {
                return Err(EvaluationError::new(
                    "invalid_duration_unit",
                    format!("duration has no unit {unit:?}"),
                )
                .into());
            }
        }
    }
    Ok(duration)
}

fn invalid_format() -> Fault {
    EvaluationError::new(
        "invalid_duration_format",
        "a duration unit pair is an integer and a unit string",
    )
    .into()
}

/// `relative_date`'s operands checked before the clock is read: the
/// duration on top of the stack and the sign `direction` gives it, `-1` for
/// `ago` and `last` and `1` for `future` and `next`. A plain map on top is
/// read as the duration its unit names spell, a unit it leaves out as 0 and
/// any other key passed over. A top that is neither, or a map holding a
/// unit that is not an integer, fails with the reason
/// `invalid_stack_value`, and any other direction with `invalid_direction`.
pub(super) fn relative(top: &Value, direction: &str) -> Result<(Duration, i128), Fault> {
    let duration = match top {
        Value::Duration(duration) => Some(*duration),
        Value::Map(map) => Duration::from_unit_map(map, &[]),
        _ => None,
    };
    let Some(duration) = duration else {
        return Err(invalid_stack_value(&format!(
            "relative_date takes a duration or a map of its units, not a {}",
            super::type_name(top)
        )));
    };
    let sign = match direction {
        "ago" | "last" => -1,
        "future" | "next" => 1,
        _ => {
            return Err(EvaluationError::new(
                "invalid_direction",
                format!("relative_date has no direction {direction:?}"),
            )
            .into());
        }
    };
    Ok((duration, sign))
}

/// `now` moved by `duration`, forward when `sign` is 1 and back when it is
/// -1, as `add` and `subtract` move an instant.
pub(super) fn shift(now: DateTime, duration: &Duration, sign: i128) -> Result<Value, Fault> {
    Ok(shift_instant(now, duration, sign)?)
}

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

    fn run_with(text: &str, options: &Options) -> Result<Value, Error> {
        evaluate(
            &Instructions::from_json(text).unwrap(),
            &Context::new(),
            options,
        )
    }

    fn run(text: &str) -> Result<Value, Error> {
        run_with(text, &Options::new())
    }

    fn reason(text: &str) -> String {
        match run(text) {
            Ok(value) => format!("answered {value:?}"),
            Err(error) => format!("{} {}", error.type_name(), error.reason()),
        }
    }

    fn noon() -> DateTime {
        DateTime::new(Date::new(2030, 1, 15).unwrap(), 12, 0, 0, 0).unwrap()
    }

    // Sabotage: with object_set inserting under the key "key" whatever its
    // operand, this test fails.
    #[test]
    fn object_new_and_object_set_build_a_map() {
        let built = run(
            r#"[["object_new"],["lit",1],["object_set","a"],["object_new"],["lit",2],["object_set","b"],["object_set","c"]]"#,
        )
        .unwrap();
        let inner: crate::Map = [("b", Value::from(2))].into_iter().collect();
        let outer: crate::Map = [("a", Value::from(1)), ("c", Value::Map(inner))]
            .into_iter()
            .collect();
        assert_eq!(built, Value::Map(outer));
        assert_eq!(
            run(r#"[["object_new"]]"#).unwrap(),
            Value::Map(crate::Map::new())
        );
        let overwritten =
            run(r#"[["object_new"],["lit",1],["object_set","a"],["lit",2],["object_set","a"]]"#)
                .unwrap();
        assert_eq!(
            overwritten,
            Value::Map([("a", Value::from(2))].into_iter().collect())
        );
    }

    // Sabotage: with object_set accepting a date target as an empty map, this
    // test fails.
    #[test]
    fn object_set_refuses_a_target_that_is_not_a_map() {
        for target in [
            "5",
            "null",
            "[1]",
            r#"{"$type":"undefined"}"#,
            r#"{"$type":"date","value":"2030-01-15"}"#,
            r#"{"$type":"datetime","value":"2030-01-15T12:00:00Z"}"#,
        ] {
            let text = format!(r#"[["lit",{target}],["lit",1],["object_set","a"]]"#);
            assert_eq!(
                reason(&text),
                "EvaluationError invalid_stack_value",
                "{text}"
            );
        }
        assert_eq!(
            reason(r#"[["lit",1],["object_set","a"]]"#),
            "EvaluationError insufficient_operands"
        );
        for text in [
            r#"[["object_new",1]]"#,
            r#"[["object_new"],["lit",1],["object_set"]]"#,
            r#"[["object_new"],["lit",1],["object_set",1]]"#,
            r#"[["object_new"],["lit",1],["object_set","a","b"]]"#,
        ] {
            assert_eq!(
                reason(text),
                "EvaluationError unknown_instruction",
                "{text}"
            );
        }
    }

    // Sabotage: with object_set leaving a duration target refused as
    // invalid_stack_value, this test fails.
    #[test]
    fn object_set_on_a_duration_answers_the_plain_map_of_its_units() {
        let units = |days: i64, extra: Option<(&str, Value)>| {
            let mut map: crate::Map = Duration {
                days,
                ..Duration::default()
            }
            .units()
            .into_iter()
            .map(|(name, _, amount)| (name, Value::Integer(amount)))
            .collect();
            if let Some((key, value)) = extra {
                map.insert(key, value);
            }
            Value::Map(map)
        };
        assert_eq!(
            run(r#"[["duration",[[3,"d"]]],["lit",1],["object_set","a"]]"#).unwrap(),
            units(3, Some(("a", Value::from(1))))
        );
        // A unit name is a key like any other: the written value replaces
        // the unit's, and the answer is still a plain map.
        assert_eq!(
            run(r#"[["duration",[[3,"d"]]],["lit",5],["object_set","days"]]"#).unwrap(),
            units(5, None)
        );
    }

    // Sabotage: with relative refusing every map as invalid_stack_value,
    // this test fails.
    #[test]
    fn relative_date_reads_a_plain_map_as_the_duration_its_unit_names_spell() {
        let options = Options::new().clock(|| Some(noon()));
        let at = |text: &str| run_with(text, &options);
        let instant = |text: &str| Value::DateTime(DateTime::parse(text).unwrap());
        // An absent unit is 0 and a key naming no unit is passed over.
        assert_eq!(
            at(r#"[["lit",{"days":3,"hours":1,"other":"x"}],["relative_date","ago"]]"#).unwrap(),
            instant("2030-01-12T11:00:00Z")
        );
        assert_eq!(
            at(r#"[["object_new"],["relative_date","next"]]"#).unwrap(),
            instant("2030-01-15T12:00:00Z")
        );
        // A unit that is not an integer is refused, as is any other value.
        for text in [
            r#"[["lit",{"days":"3"}],["relative_date","ago"]]"#,
            r#"[["lit",{"days":1.5}],["relative_date","ago"]]"#,
            r#"[["lit",{"$type":"date","value":"2030-01-15"}],["relative_date","ago"]]"#,
            r#"[["lit",3],["relative_date","ago"]]"#,
        ] {
            let error = at(text).unwrap_err();
            assert_eq!(
                (error.type_name(), error.reason()),
                ("EvaluationError", "invalid_stack_value"),
                "{text}"
            );
        }
    }

    // Sabotage: with "min" left out of unit_name's minutes arm, this test
    // fails.
    #[test]
    fn duration_reads_every_unit_spelling_and_lets_a_later_pair_win() {
        let spellings = [
            ("years", ["y", "year", "years"].as_slice()),
            ("months", &["mo", "month", "months"]),
            ("weeks", &["w", "week", "weeks"]),
            ("days", &["d", "day", "days"]),
            ("hours", &["h", "hour", "hours"]),
            ("minutes", &["m", "min", "minute", "minutes"]),
            ("seconds", &["s", "sec", "second", "seconds"]),
            ("milliseconds", &["ms", "millisecond", "milliseconds"]),
        ];
        for (name, units) in spellings {
            for unit in units {
                let text = format!(r#"[["duration",[[-4,"{unit}"]]],["access","{name}"]]"#);
                assert_eq!(run(&text).unwrap(), Value::from(-4), "{unit}");
            }
        }
        assert_eq!(
            run(r#"[["duration",[[1,"h"],[2,"hours"],[5,"d"]]]]"#).unwrap(),
            Value::Duration(Duration {
                hours: 2,
                days: 5,
                ..Duration::default()
            })
        );
        assert_eq!(
            run(r#"[["duration",[]]]"#).unwrap(),
            Value::Duration(Duration::default())
        );
    }

    // Sabotage: with duration skipping a pair that is not a list instead of
    // refusing it, this test fails.
    #[test]
    fn duration_refuses_a_malformed_pair_or_an_unknown_unit_in_order() {
        for pairs in [
            r#"[["bad"]]"#,
            r#"[[1]]"#,
            r#"[[1,"d",2]]"#,
            r#"[[1.5,"d"]]"#,
            r#"[["d",1]]"#,
            r#"[5]"#,
            r#"[[1,"d"],"x",[1,"xyz"]]"#,
        ] {
            let text = format!(r#"[["duration",{pairs}]]"#);
            assert_eq!(
                reason(&text),
                "EvaluationError invalid_duration_format",
                "{text}"
            );
        }
        for pairs in [r#"[[3,"xyz"]]"#, r#"[[3,"D"]]"#, r#"[[1,"d"],[3,""],"x"]"#] {
            let text = format!(r#"[["duration",{pairs}]]"#);
            assert_eq!(
                reason(&text),
                "EvaluationError invalid_duration_unit",
                "{text}"
            );
        }
        for text in [
            r#"[["duration"]]"#,
            r#"[["duration",5]]"#,
            r#"[["duration",{}]]"#,
        ] {
            assert_eq!(
                reason(text),
                "EvaluationError unknown_instruction",
                "{text}"
            );
        }
    }

    // Sabotage: with relative_date's sign for "last" made 1, this test
    // fails.
    #[test]
    fn relative_date_moves_the_clock_time_by_any_duration() {
        let options = Options::new().clock(|| Some(noon()));
        let at = |text: &str| run_with(text, &options).unwrap();
        let instant = |text: &str| Value::DateTime(DateTime::parse(text).unwrap());
        assert_eq!(
            at(r#"[["duration",[[3,"d"]]],["relative_date","ago"]]"#),
            instant("2030-01-12T12:00:00Z")
        );
        assert_eq!(
            at(r#"[["duration",[[1,"mo"]]],["relative_date","last"]]"#),
            instant("2029-12-16T12:00:00Z")
        );
        assert_eq!(
            at(r#"[["duration",[[2,"h"],[500,"ms"]]],["relative_date","future"]]"#),
            instant("2030-01-15T14:00:00.500000Z")
        );
        assert_eq!(
            at(r#"[["duration",[[1,"y"]]],["relative_date","next"]]"#),
            instant("2031-01-15T12:00:00Z")
        );
        // A duration from the context, or from subtracting two dates, is
        // the same kind as one the instruction builds.
        let mut context = Context::new();
        context.insert(
            "span",
            Value::Duration(Duration {
                weeks: 1,
                ..Duration::default()
            }),
        );
        let program = Instructions::from_json(
            r#"[["load","span"],["relative_date","ago"],["lit",{"$type":"date","value":"2030-01-02"}],["lit",{"$type":"date","value":"2030-01-01"}],["subtract"],["relative_date","next"],["compare","LT"]]"#,
        )
        .unwrap();
        assert_eq!(
            evaluate(&program, &context, &options).unwrap(),
            Value::from(true)
        );
    }

    // Sabotage: with relative_date reading the clock before the duration
    // check, this test fails.
    #[test]
    fn relative_date_refuses_before_it_reads_the_clock() {
        let reads = AtomicU32::new(0);
        let options = Options::new().clock(|| {
            reads.fetch_add(1, Ordering::SeqCst);
            Some(noon())
        });
        let refused = |text: &str| {
            let error = run_with(text, &options).unwrap_err();
            format!("{} {}", error.type_name(), error.reason())
        };
        assert_eq!(
            refused(r#"[["relative_date","ago"]]"#),
            "EvaluationError insufficient_operands"
        );
        assert_eq!(
            refused(r#"[["lit",{"days":"1"}],["relative_date","ago"]]"#),
            "EvaluationError invalid_stack_value"
        );
        assert_eq!(
            refused(r#"[["lit",3],["relative_date","ago"]]"#),
            "EvaluationError invalid_stack_value"
        );
        assert_eq!(
            refused(r#"[["duration",[[1,"d"]]],["relative_date","sideways"]]"#),
            "EvaluationError invalid_direction"
        );
        for text in [
            r#"[["duration",[[1,"d"]]],["relative_date"]]"#,
            r#"[["duration",[[1,"d"]]],["relative_date",1]]"#,
        ] {
            assert_eq!(
                refused(text),
                "EvaluationError unknown_instruction",
                "{text}"
            );
        }
        assert_eq!(reads.load(Ordering::SeqCst), 0);
    }

    // Sabotage: with Machine::now reading the clock on every call (the
    // cache never filled), this test fails.
    #[test]
    fn a_run_reads_the_clock_at_most_once_and_only_when_it_reads_the_time() {
        let reads = AtomicU32::new(0);
        let ticking = Options::new().clock(|| {
            let read = reads.fetch_add(1, Ordering::SeqCst) + 1;
            DateTime::from_unix(i64::from(read) * 3600, 0)
        });
        // Two reads of the time in one run see the same instant.
        assert_eq!(
            run_with(
                r#"[["duration",[]],["relative_date","ago"],["duration",[]],["relative_date","next"],["compare","STRICT_EQ"]]"#,
                &ticking
            )
            .unwrap(),
            Value::from(true)
        );
        assert_eq!(reads.load(Ordering::SeqCst), 1);
        // A run that never reads the time never reads the clock.
        run_with(
            r#"[["duration",[[1,"d"]]],["lit",1],["compare","EQ"]]"#,
            &ticking,
        )
        .unwrap();
        assert_eq!(reads.load(Ordering::SeqCst), 1);
        // Each run reads it afresh.
        run_with(r#"[["duration",[]],["relative_date","ago"]]"#, &ticking).unwrap();
        assert_eq!(reads.load(Ordering::SeqCst), 2);
    }

    // Sabotage: with Machine::now answering the epoch when the clock gives
    // none, this test fails.
    #[test]
    fn a_clock_with_no_time_fails_the_run_with_one_refusal() {
        let options = Options::new().clock(|| None);
        for direction in ["ago", "last", "future", "next"] {
            let text = format!(r#"[["duration",[[1,"d"]]],["relative_date","{direction}"]]"#);
            let error = run_with(&text, &options).unwrap_err();
            assert_eq!(
                (error.type_name(), error.reason()),
                ("EvaluationError", "clock_failed")
            );
        }
        // Without a clock the run reads the system clock.
        let before = Options::new().now().unwrap();
        let read = run(r#"[["duration",[]],["relative_date","next"]]"#).unwrap();
        let after = Options::new().now().unwrap();
        let Value::DateTime(read) = read else {
            panic!("relative_date answered {read:?}");
        };
        assert!(before <= read && read <= after);
    }

    // Sabotage: with shift answering now unmoved, this test fails.
    #[test]
    fn relative_date_past_the_years_held_is_date_out_of_range() {
        let options = Options::new().clock(|| Some(noon()));
        let error = run_with(
            r#"[["duration",[[9223372036854775807,"y"]]],["relative_date","next"]]"#,
            &options,
        )
        .unwrap_err();
        assert_eq!(error.reason(), "date_out_of_range");
    }
}