dtrexp 1.0.0

Date-Time Range & Recurrence Expression โ€” a compact coverage-expression language (DTRExp draft 2.8)
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
//! Static validation: hard domain/stride errors (returned as [`ParseError`]),
//! plus the ยง9.1 satisfiability warnings (the required minimum).

use crate::ast::*;
use crate::civil::{days_in_month, days_in_quarter, days_in_year, weeks_in_iso_year};
use crate::error::{ParseError, Warning};
use crate::eval::atom_match;

#[derive(Clone, Copy)]
enum Scope {
    Month,
    Quarter,
    Year,
}

fn scope_of(expr: &Expr) -> Scope {
    let has = |d: Desig| expr.selectors.iter().any(|s| s.desig == d);
    if has(Desig::Month) {
        Scope::Month
    } else if has(Desig::Quarter) {
        Scope::Quarter
    } else if has(Desig::Year) {
        Scope::Year
    } else {
        Scope::Month
    }
}

/// (is_zero_based, min_value, max_value, domain_size).
fn domain_info(desig: Desig, scope: Scope) -> (bool, i64, i64, i64) {
    match desig {
        Desig::Quarter => (false, 1, 4, 4),
        Desig::Month => (false, 1, 12, 12),
        Desig::Week => (false, 1, 53, 53),
        Desig::Weekday => (false, 1, 7, 7),
        Desig::Hour => (true, 0, 23, 24),
        Desig::Minute => (true, 0, 59, 60),
        Desig::Second => (true, 0, 59, 60),
        Desig::Day => match scope {
            Scope::Month => (false, 1, 31, 31),
            Scope::Quarter => (false, 1, 92, 92),
            Scope::Year => (false, 1, 366, 366),
        },
        Desig::Year => (false, 1, i64::MAX, i64::MAX),
    }
}

/// Run hard validation (errors) and collect warnings for one branch.
pub fn check(expr: &Expr) -> Result<Vec<Warning>, ParseError> {
    let scope = scope_of(expr);
    for sel in &expr.selectors {
        if sel.desig == Desig::Year {
            check_year(sel)?;
        } else {
            check_selector(sel, scope)?;
        }
    }
    Ok(warnings(expr, scope))
}

fn check_year(sel: &Selector) -> Result<(), ParseError> {
    if let Some((wd, _)) = sel.ordinal {
        // Ordinals are E-only; this is unreachable via the parser, but be safe.
        return Err(ParseError::new(
            sel.pos,
            format!("ordinal not valid here ({wd})"),
        ));
    }
    for atom in &sel.atoms {
        match *atom {
            Atom::All => {}
            Atom::Single(v) => year_value(sel.pos, v)?,
            Atom::Range { start, end, wrap } => {
                if wrap {
                    return Err(ParseError::new(
                        sel.pos,
                        "Y range cannot wrap โ€” no edge to wrap around",
                    ));
                }
                if let Endpoint::Value(v) = start {
                    year_value(sel.pos, v)?;
                }
                if let Endpoint::Value(v) = end {
                    year_value(sel.pos, v)?;
                }
            }
            Atom::Stride {
                start,
                end,
                interval,
                duration,
            } => {
                year_value(sel.pos, start)?;
                if let Endpoint::Value(v) = end {
                    year_value(sel.pos, v)?;
                }
                if interval < 2 {
                    return Err(ParseError::new(sel.pos, "stride interval must be >= 2"));
                }
                if duration < 1 || duration >= interval {
                    return Err(ParseError::new(
                        sel.pos,
                        "stride duration must be in 1..interval",
                    ));
                }
            }
        }
    }
    Ok(())
}

fn year_value(pos: usize, v: i64) -> Result<(), ParseError> {
    if v < 0 {
        Err(ParseError::new(
            pos,
            "negative value on Y โ€” no edge to count back from",
        ))
    } else if !(1..=9999).contains(&v) {
        // Y takes 4-digit ISO years (spec ยง2): 1-9999.
        Err(ParseError::new(pos, "year out of domain (1-9999)"))
    } else {
        Ok(())
    }
}

fn check_selector(sel: &Selector, scope: Scope) -> Result<(), ParseError> {
    let (zero_based, _minv, maxv, size) = domain_info(sel.desig, scope);
    if let Some((wd, _)) = sel.ordinal {
        if !(1..=7).contains(&wd) {
            return Err(ParseError::new(sel.pos, "weekday out of domain (1-7)"));
        }
        return Ok(());
    }
    let check_val = |v: i64| -> Result<(), ParseError> {
        if v >= 0 {
            if !zero_based && v == 0 {
                return Err(ParseError::new(sel.pos, "zero value"));
            }
            if v > maxv {
                return Err(ParseError::new(sel.pos, "value out of domain"));
            }
        } else if v < -size {
            return Err(ParseError::new(
                sel.pos,
                "negative value out of domain (symmetric parse-time check)",
            ));
        }
        Ok(())
    };
    for atom in &sel.atoms {
        match *atom {
            Atom::All => {}
            Atom::Single(v) => check_val(v)?,
            Atom::Range { start, end, .. } => {
                if let Endpoint::Value(v) = start {
                    check_val(v)?;
                }
                if let Endpoint::Value(v) = end {
                    check_val(v)?;
                }
            }
            Atom::Stride {
                start,
                end,
                interval,
                duration,
            } => {
                check_val(start)?;
                if let Endpoint::Value(v) = end {
                    check_val(v)?;
                }
                if interval < 2 {
                    return Err(ParseError::new(sel.pos, "stride interval must be >= 2"));
                }
                if interval > size {
                    return Err(ParseError::new(
                        sel.pos,
                        "stride interval exceeds parent domain โ€” use a cadence",
                    ));
                }
                if duration < 1 || duration >= interval {
                    return Err(ParseError::new(
                        sel.pos,
                        "stride duration must be in 1..interval",
                    ));
                }
            }
        }
    }
    Ok(())
}

// ---- satisfiability warnings --------------------------------------------

/// Which values in [minv, maxv] a (non-Year) selector matches.
fn matched_values(sel: &Selector, minv: i64, maxv: i64) -> Vec<i64> {
    (minv..=maxv)
        .filter(|&v| {
            let hit = sel.atoms.iter().any(|a| atom_match(a, minv, maxv, v));
            if sel.exclude {
                !hit
            } else {
                hit
            }
        })
        .collect()
}

/// The Y selector's values as a closed, enumerable set (โ‰ค1000-year span), else
/// `None` for open/unbounded/non-enumerable spans.
fn enumerate_years(expr: &Expr) -> Option<Vec<i64>> {
    let sel = expr.selectors.iter().find(|s| s.desig == Desig::Year)?;
    if sel.exclude {
        return None;
    }
    let mut years = Vec::new();
    for atom in &sel.atoms {
        match *atom {
            Atom::Single(v) if v > 0 => years.push(v),
            Atom::Range {
                start: Endpoint::Value(a),
                end: Endpoint::Value(b),
                wrap: false,
            } if a > 0 && b >= a => {
                if b - a > 1000 {
                    return None;
                }
                years.extend(a..=b);
            }
            _ => return None, // Star, All, stride, negative โ†’ open/unknown
        }
    }
    // Every push-arm above contributes โ‰ฅ1 value and the others bail with `None`,
    // so a completed loop leaves `years` non-empty.
    let (lo, hi) = (*years.iter().min().unwrap(), *years.iter().max().unwrap());
    if hi - lo > 1000 {
        return None;
    }
    Some(years)
}

fn warnings(expr: &Expr, scope: Scope) -> Vec<Warning> {
    let mut ws = Vec::new();
    let month_set = expr
        .selectors
        .iter()
        .find(|s| s.desig == Desig::Month)
        .map(|s| matched_values(s, 1, 12));
    let quarter_set = expr
        .selectors
        .iter()
        .find(|s| s.desig == Desig::Quarter)
        .map(|s| matched_values(s, 1, 4));

    for sel in &expr.selectors {
        match sel.desig {
            Desig::Year => {}
            Desig::Weekday if sel.ordinal.is_some() => {}
            Desig::Day => {
                if let Some(w) = day_unsat(
                    sel,
                    expr,
                    scope,
                    month_set.as_deref(),
                    quarter_set.as_deref(),
                ) {
                    ws.push(w);
                }
            }
            Desig::Week => {
                if let Some(w) = week_unsat(sel, expr) {
                    ws.push(w);
                }
            }
            _ => {
                if let Some(w) = fixed_unsat(sel) {
                    ws.push(w);
                }
            }
        }
    }

    // M โˆฉ Q disjointness.
    if let (Some(ms), Some(qs)) = (&month_set, &quarter_set) {
        let disjoint = !ms.is_empty()
            && !qs.is_empty()
            && !ms.iter().any(|&m| qs.contains(&((m - 1) / 3 + 1)));
        if disjoint {
            // A non-empty `month_set` means a Month selector is present.
            let pos = expr
                .selectors
                .iter()
                .find(|s| s.desig == Desig::Month)
                .map(|s| s.pos)
                .unwrap();
            ws.push(Warning::new(
                pos,
                "unsatisfiable โ€” M and Q select disjoint months",
            ));
        }
    }

    ws
}

/// Fixed-domain selectors (Q/M/E/H/m/s): empty match set โ‡’ unsatisfiable.
fn fixed_unsat(sel: &Selector) -> Option<Warning> {
    let (_, minv, maxv, _) = domain_info(sel.desig, Scope::Month);
    if matched_values(sel, minv, maxv).is_empty() {
        Some(Warning::new(
            sel.pos,
            "unsatisfiable โ€” selector matches nothing in its domain",
        ))
    } else {
        None
    }
}

/// Day selector: unsatisfiable iff empty against every possible domain size.
fn day_unsat(
    sel: &Selector,
    expr: &Expr,
    scope: Scope,
    month_set: Option<&[i64]>,
    quarter_set: Option<&[i64]>,
) -> Option<Warning> {
    let years = if expr.has_week {
        None // W present โ‡’ Y is the week-year; day-of-year is cross-selector โ†’ quiet.
    } else {
        enumerate_years(expr)
    };
    let sizes = day_domain_sizes(scope, month_set, quarter_set, years.as_deref());
    let satisfiable = sizes.iter().any(|&z| !matched_values(sel, 1, z).is_empty());
    if satisfiable {
        None
    } else {
        Some(Warning::new(
            sel.pos,
            "unsatisfiable โ€” day never exists in the covered instances",
        ))
    }
}

fn day_domain_sizes(
    scope: Scope,
    month_set: Option<&[i64]>,
    quarter_set: Option<&[i64]>,
    years: Option<&[i64]>,
) -> Vec<i64> {
    let mut sizes = Vec::new();
    match scope {
        Scope::Month => {
            let months: Vec<i64> = month_set
                .map(|m| m.to_vec())
                .unwrap_or_else(|| (1..=12).collect());
            for m in months {
                match years {
                    Some(ys) => {
                        for &y in ys {
                            sizes.push(days_in_month(y, m));
                        }
                    }
                    None => {
                        sizes.push(days_in_month(2001, m)); // common year
                        sizes.push(days_in_month(2000, m)); // leap year
                    }
                }
            }
        }
        Scope::Quarter => {
            // A quarter scope is only chosen when a Q selector is present.
            let quarters: Vec<i64> = quarter_set
                .map(|q| q.to_vec())
                .expect("quarter scope implies a Q selector");
            for q in quarters {
                match years {
                    Some(ys) => {
                        for &y in ys {
                            sizes.push(days_in_quarter(y, q));
                        }
                    }
                    None => {
                        sizes.push(days_in_quarter(2001, q));
                        sizes.push(days_in_quarter(2000, q));
                    }
                }
            }
        }
        Scope::Year => match years {
            Some(ys) => {
                for &y in ys {
                    sizes.push(days_in_year(y));
                }
            }
            None => {
                sizes.push(365);
                sizes.push(366);
            }
        },
    }
    sizes
}

/// Week selector: unsatisfiable iff empty against every possible week count.
fn week_unsat(sel: &Selector, expr: &Expr) -> Option<Warning> {
    // When W is present, Y (if any) is the ISO week-year.
    let week_counts: Vec<i64> = match enumerate_years(expr) {
        Some(ys) => ys.iter().map(|&y| weeks_in_iso_year(y)).collect(),
        None => vec![52, 53],
    };
    let satisfiable = week_counts
        .iter()
        .any(|&z| !matched_values(sel, 1, z).is_empty());
    if satisfiable {
        None
    } else {
        Some(Warning::new(
            sel.pos,
            "unsatisfiable โ€” week never exists in the covered week-years",
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn year_selector(ordinal: Option<(i64, i64)>) -> Expr {
        let mut expr = Expr::default();
        expr.selectors.push(Selector {
            desig: Desig::Year,
            atoms: vec![Atom::Single(2020)],
            exclude: false,
            ordinal,
            pos: 0,
        });
        expr
    }

    #[test]
    fn year_domain_is_one_based_and_unbounded() {
        // The Year row of the domain table: 1-based, no finite upper edge.
        assert_eq!(
            domain_info(Desig::Year, Scope::Month),
            (false, 1, i64::MAX, i64::MAX)
        );
    }

    #[test]
    fn year_accepts_a_plain_value() {
        // Guards the surrounding check: a normal Year selector validates.
        assert!(check(&year_selector(None)).is_ok());
    }

    #[test]
    fn year_rejects_an_ordinal() {
        // Ordinals are E-only; the parser never builds this, but `check_year`
        // defends the invariant if an ordinal ever reaches a Year selector.
        let err = check(&year_selector(Some((3, 2)))).unwrap_err();
        assert!(err.message.contains("ordinal not valid here"));
    }
}