nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
//! Explicit elapsed-instant, calendar-date, and clock-report clauses.
use super::endpoint;
use crate::plugins::{compositions::Compositions, integer_queries, model_coordinates, time};
use crate::{Context, Error, Outcome, re};
use chrono::{
    DateTime, Datelike, Duration, LocalResult, NaiveDate, NaiveTime, TimeZone, Timelike, Utc,
};
use chrono_tz::Tz;
use num_bigint::BigInt;
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};

fn invalid(name: &str) -> Error {
    Error(name.into())
}
fn date(input: &str) -> Result<NaiveDate, Error> {
    NaiveDate::parse_from_str(input, "%Y-%m-%d").map_err(|_| invalid("invalid_endpoint"))
}
fn count(input: &str) -> Result<i64, Error> {
    input.parse::<i64>().map_err(|_| invalid("integer_limit"))
}
fn zone(input: &str) -> Result<Tz, Error> {
    input
        .parse::<Tz>()
        .ok()
        .or_else(|| time::zone(input))
        .ok_or_else(|| invalid("invalid_endpoint"))
}
fn shifted(start: &str, seconds: i64, context: &Context) -> Result<DateTime<Utc>, Error> {
    endpoint::resolve(start, context)?
        .checked_add_signed(
            Duration::try_seconds(seconds).ok_or_else(|| invalid("invalid_duration"))?,
        )
        .ok_or_else(|| invalid("invalid_endpoint"))
}
fn instant(value: DateTime<Utc>, zone: Tz) -> Result<String, Error> {
    super::bounded(format!(
        "calendar_datetime_instant({}|{})",
        value.timestamp(),
        zone.name()
    ))
}
fn interval(start: &DateTime<Utc>, end: &DateTime<Utc>) -> Result<(), Error> {
    if end < start {
        Err(invalid("invalid_interval"))
    } else {
        Ok(())
    }
}

fn elapsed_role(
    input: &str,
    default_unit: &str,
    engine: &Compositions,
    context: &Context,
) -> Result<BigRational, Error> {
    let coordinate = match model_coordinates::read(input, "seconds", engine, context) {
        Ok(value) => value,
        Err(error) if error.0 == "incompatible_units" => {
            model_coordinates::read(input, "1", engine, context)?;
            model_coordinates::read(
                &format!("({input}) {default_unit}"),
                "seconds",
                engine,
                context,
            )?
        }
        Err(error) => return Err(error),
    };
    if coordinate.value.is_negative() {
        return Err(invalid("invalid_duration"));
    }
    Ok(coordinate.value)
}

struct ScheduleRequest<'a> {
    kind: &'a str,
    stated: &'a str,
    list: &'a str,
    clock: &'a str,
    pauses: SchedulePauses<'a>,
    final_goal: bool,
    elapsed_goal: Option<bool>,
}

enum SchedulePauses<'a> {
    Uniform(&'a str),
    Named(&'a str),
    Listed {
        durations: &'a str,
        indices: &'a str,
    },
    Between(&'a str),
    Only {
        amount: &'a str,
        before: &'a str,
        after: &'a str,
    },
}

fn boundary_number(input: &str) -> Result<i64, Error> {
    if input.chars().all(|ch| ch.is_ascii_digit()) {
        return super::count(input);
    }
    let ordinal = [
        "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth",
        "tenth",
    ];
    if let Some(index) = ordinal
        .iter()
        .position(|name| input.eq_ignore_ascii_case(name))
    {
        return Ok(index as i64 + 1);
    }
    let digits = input.trim_end_matches(|ch: char| ch.is_ascii_alphabetic());
    let suffix = &input[digits.len()..];
    if !matches!(suffix, "st" | "nd" | "rd" | "th") {
        return Err(invalid("invalid_interval"));
    }
    let number = super::count(digits)?;
    let expected = if (11..=13).contains(&(number % 100)) {
        "th"
    } else {
        match number % 10 {
            1 => "st",
            2 => "nd",
            3 => "rd",
            _ => "th",
        }
    };
    if suffix != expected {
        return Err(invalid("invalid_interval"));
    }
    Ok(number)
}

fn schedule_clock(input: &str) -> Result<NaiveTime, Error> {
    if re!(r"^\d{2}:\d{2}$").is_match(input) {
        NaiveTime::parse_from_str(input, "%H:%M").map_err(|_| invalid("invalid_endpoint"))
    } else if re!(r"(?i)^\d{1,2}:\d{2} (?:am|pm)$").is_match(input) {
        NaiveTime::parse_from_str(&input.to_ascii_uppercase(), "%I:%M %p")
            .map_err(|_| invalid("invalid_endpoint"))
    } else {
        Err(invalid("invalid_endpoint"))
    }
}

fn task_schedule(
    engine: &Compositions,
    context: &Context,
    request: ScheduleRequest<'_>,
) -> Result<String, Error> {
    let ScheduleRequest {
        kind,
        stated,
        list,
        clock,
        pauses,
        final_goal,
        elapsed_goal,
    } = request;
    let count = integer_queries::value(stated)?;
    let count = integer_queries::bounded(&count, 256)? as usize;
    if count == 0 {
        return Err(invalid("invalid_duration"));
    }
    let start = schedule_clock(clock)?;
    let parts = re!(r",\s*and\s+|,\s*")
        .split(list)
        .map(str::trim)
        .collect::<Vec<_>>();
    if parts.len() != count {
        return Err(invalid("invalid_duration"));
    }
    let default_unit = re!(r"(?i)\b(seconds?|minutes?|hours?)$")
        .captures(parts[count - 1])
        .map(|c| c[1].to_owned())
        .ok_or_else(|| invalid("invalid_duration"))?;
    let durations = parts
        .iter()
        .map(|part| elapsed_role(part, &default_unit, engine, context))
        .collect::<Result<Vec<_>, _>>()?;
    let mut boundaries = vec![BigRational::zero(); count.saturating_sub(1)];
    match pauses {
        SchedulePauses::Uniform(pause) => {
            let pause = elapsed_role(pause, "minutes", engine, context)?;
            boundaries.fill(pause);
        }
        SchedulePauses::Named(clauses) => {
            let items = re!(r"(?i),\s*(?:and\s+)?|\s+and\s+")
                .split(clauses)
                .collect::<Vec<_>>();
            if items.len() != boundaries.len() {
                return Err(invalid("invalid_interval"));
            }
            let mut seen = vec![false; boundaries.len()];
            for item in items {
                let c =
                    re!(r"(?i)^(.+?) after (?:the )?(?:[a-z-]+ )?([a-z]+|\d+(?:st|nd|rd|th)?)$")
                        .captures(item.trim())
                        .ok_or_else(|| invalid("invalid_interval"))?;
                let pause = elapsed_role(&c[1], "minutes", engine, context)?;
                let before = boundary_number(&c[2])?;
                if before < 1 || before as usize > boundaries.len() || seen[before as usize - 1] {
                    return Err(invalid("invalid_interval"));
                }
                boundaries[before as usize - 1] = pause;
                seen[before as usize - 1] = true;
            }
        }
        SchedulePauses::Listed { durations, indices } => {
            let values = re!(r"(?i),\s*and\s+|,\s*")
                .split(durations)
                .map(str::trim)
                .collect::<Vec<_>>();
            let indices = if let Some(c) =
                re!(r"(?i)^(\d+)\s+(?:through|to)\s+(\d+)$").captures(indices.trim())
            {
                let first = super::count(&c[1])?;
                let last = super::count(&c[2])?;
                if first < 1 || last < first || last > count as i64 || last - first > 256 {
                    return Err(invalid("invalid_interval"));
                }
                (first..=last).collect::<Vec<_>>()
            } else {
                re!(r"(?i),\s*and\s+|,\s*")
                    .split(indices)
                    .map(|part| super::count(part.trim()))
                    .collect::<Result<Vec<_>, _>>()?
            };
            if values.len() != boundaries.len() || indices.len() != values.len() {
                return Err(invalid("invalid_interval"));
            }
            let default_unit = re!(r"(?i)\b(seconds?|minutes?|hours?)$")
                .captures(values[values.len() - 1])
                .map(|c| c[1].to_owned())
                .ok_or_else(|| invalid("invalid_duration"))?;
            let mut seen = vec![false; boundaries.len()];
            for (amount, before) in values.into_iter().zip(indices) {
                let pause = elapsed_role(amount, &default_unit, engine, context)?;
                if before < 1 || before as usize > boundaries.len() || seen[before as usize - 1] {
                    return Err(invalid("invalid_interval"));
                }
                boundaries[before as usize - 1] = pause;
                seen[before as usize - 1] = true;
            }
        }
        SchedulePauses::Between(clauses) => {
            let items = re!(r"(?i),\s*(?:and\s+)?")
                .split(clauses)
                .collect::<Vec<_>>();
            if items.len() != boundaries.len() {
                return Err(invalid("invalid_interval"));
            }
            let mut seen = vec![false; boundaries.len()];
            for (index, item) in items.into_iter().enumerate() {
                let c = re!(r"(?i)^(.+?) between (batches )?(\d+) and (\d+)$")
                    .captures(item.trim())
                    .ok_or_else(|| invalid("invalid_interval"))?;
                if index == 0 && c.get(2).is_none() {
                    return Err(invalid("invalid_interval"));
                }
                let pause = elapsed_role(&c[1], "minutes", engine, context)?;
                let first = super::count(&c[3])?;
                let second = super::count(&c[4])?;
                if first < 1
                    || first as usize > boundaries.len()
                    || first.checked_add(1) != Some(second)
                    || seen[first as usize - 1]
                {
                    return Err(invalid("invalid_interval"));
                }
                boundaries[first as usize - 1] = pause;
                seen[first as usize - 1] = true;
            }
        }
        SchedulePauses::Only {
            amount,
            before,
            after,
        } => {
            let pause = elapsed_role(amount, "minutes", engine, context)?;
            let before = super::count(before)?;
            let after = super::count(after)?;
            if before < 1 || before.checked_add(1) != Some(after) || after > count as i64 {
                return Err(invalid("invalid_interval"));
            }
            boundaries[before as usize - 1] = pause;
        }
    }
    let mut cursor = BigRational::from_integer(start.num_seconds_from_midnight().into());
    let mut intervals = Vec::with_capacity(count);
    for (index, duration) in durations.into_iter().enumerate() {
        let beginning = cursor.clone();
        cursor = model_coordinates::bounded(cursor + duration)?;
        intervals.push(format!("{}~{}", scalar(&beginning), scalar(&cursor)));
        if index + 1 < count {
            cursor = model_coordinates::bounded(cursor + &boundaries[index])?;
        }
    }
    let pairs = if elapsed_goal.is_some() {
        let first = intervals
            .first()
            .and_then(|pair| pair.split_once('~'))
            .ok_or_else(|| invalid("invalid_expression"))?
            .0;
        format!("{first}~{}", scalar(&cursor))
    } else {
        intervals.join(";")
    };
    let carrier = format!(
        "calendar_task_schedule({kind}|{}|{})",
        match elapsed_goal {
            Some(true) => "elapsed_first",
            Some(false) => "finish_first",
            None if final_goal => "final",
            None => "pairs",
        },
        pairs
    );
    if carrier.len() > 4096 {
        return Err(invalid("expression_too_complex"));
    }
    Ok(carrier)
}

fn repeated_elapsed_schedule(
    engine: &Compositions,
    context: &Context,
    stated: &str,
    duration: &str,
    pauses: SchedulePauses<'_>,
    clock: &str,
    elapsed_first: bool,
) -> Result<String, Error> {
    let count = super::count(stated)?;
    if !(1..=256).contains(&count) {
        return Err(invalid("invalid_duration"));
    }
    let list = vec![duration.to_owned(); count as usize].join(", ");
    let numeric = count.to_string();
    task_schedule(
        engine,
        context,
        ScheduleRequest {
            kind: "task",
            stated: &numeric,
            list: &list,
            clock,
            pauses,
            final_goal: false,
            elapsed_goal: Some(elapsed_first),
        },
    )
}

fn scalar(value: &BigRational) -> String {
    format!("rational({},{})", value.numer(), value.denom())
}

fn clock_display(seconds: BigRational) -> Result<String, Error> {
    if seconds.is_negative() {
        return Err(invalid("invalid_expression"));
    }
    // Round the whole endpoint first so a second close to sixty carries into
    // its minute, hour, or day instead of producing an invalid clock field.
    let scale = BigInt::from(10_000_000_000u64);
    let rounded = (seconds * BigRational::from_integer(scale.clone())
        + BigRational::new(1.into(), 2.into()))
    .to_integer();
    let day_ticks = &scale * 86_400u32;
    let hour_ticks = &scale * 3_600u32;
    let minute_ticks = &scale * 60u32;
    let day = &rounded / &day_ticks;
    let day_u64 = day.to_u64().ok_or_else(|| invalid("integer_limit"))?;
    let within_day = rounded % day_ticks;
    let hour = &within_day / &hour_ticks;
    let within_hour = within_day % hour_ticks;
    let minute = &within_hour / &minute_ticks;
    let within_minute = within_hour % minute_ticks;
    let second = &within_minute / &scale;
    let fractional_ticks = within_minute % &scale;
    let (hour, minute) = (
        hour.to_u32().ok_or_else(|| invalid("integer_limit"))?,
        minute.to_u32().ok_or_else(|| invalid("integer_limit"))?,
    );
    let mut clock = format!("{hour:02}:{minute:02}");
    if !second.is_zero() || !fractional_ticks.is_zero() {
        let second = second.to_u32().ok_or_else(|| invalid("integer_limit"))?;
        clock.push_str(&format!(":{second:02}"));
        if !fractional_ticks.is_zero() {
            let digits = format!("{:0>10}", fractional_ticks)
                .trim_end_matches('0')
                .to_owned();
            clock.push_str(&format!(".{digits}"));
        }
    }
    if day_u64 > 0 {
        clock.push_str(&format!(
            " (+{day_u64} {})",
            if day_u64 == 1 { "day" } else { "days" }
        ));
    }
    Ok(clock)
}

pub(super) fn rewrite(engine: &Compositions, input: &str, context: &Context) -> Outcome {
    if let Some(c) = re!(r"(?i)^i perform (.+?) tasks, each lasting (.+?), with pauses of (.+?) after tasks (.+?) respectively\. find the full elapsed interval from starting task (.+?) through finishing task (.+?) and the clock time of the finish if i start at (.+)$").captures(input) {
        return Some((|| {
            let first = super::count(&c[5])?;
            let last = super::count(&c[6])?;
            let count = super::count(&c[1])?;
            if first != 1 || last != count { return Err(invalid("invalid_interval")); }
            repeated_elapsed_schedule(engine, context, &c[1], &c[2], SchedulePauses::Listed { durations: &c[3], indices: &c[4] }, &c[7], true)
        })());
    }
    if let Some(c) = re!(r"(?i)^(.+?) repeated inspections each take (.+?); the pauses after inspections (.+?) are respectively (.+?)\. starting at (.+?), what is the finish time, and what is the entire elapsed interval including every between-inspection pause$").captures(input) {
        return Some(repeated_elapsed_schedule(engine, context, &c[1], &c[2], SchedulePauses::Listed { durations: &c[4], indices: &c[3] }, &c[5], false));
    }
    if let Some(c) = re!(r"(?i)^i bake (.+?) trays for (.+?) each, waiting (.+?)\. starting at (.+?), report total elapsed time through the final tray and its finish time$").captures(input) {
        return Some(repeated_elapsed_schedule(engine, context, &c[1], &c[2], SchedulePauses::Named(&c[3]), &c[4], true));
    }
    if let Some(c) = re!(r"(?i)^complete (.+?) data-entry batches taking (.+?) each; breaks after batches (.+?) last (.+?)\. if the first batch begins at (.+?), find the full interval and completion clock time$").captures(input) {
        return Some(repeated_elapsed_schedule(engine, context, &c[1], &c[2], SchedulePauses::Listed { durations: &c[4], indices: &c[3] }, &c[5], true));
    }
    if let Some(c) = re!(r"(?i)^there are (.+?) machine cycles of (.+?) each and inter-cycle idle gaps after cycles (.+?) of (.+?)\. starting at (.+?), compute total start-to-final-finish duration and end time$").captures(input) {
        return Some(repeated_elapsed_schedule(engine, context, &c[1], &c[2], SchedulePauses::Listed { durations: &c[4], indices: &c[3] }, &c[5], true));
    }
    if let Some(c) = re!(r"(?i)^prepare (.+?) batches requiring (.+?) each, with (.+?)\. find the full elapsed time and finish time from a (.+?) start$").captures(input) {
        return Some(repeated_elapsed_schedule(engine, context, &c[1], &c[2], SchedulePauses::Between(&c[3]), &c[4], true));
    }
    if let Some(c) = re!(r"(?i)^read (.+?) chapters at (.+?) per chapter with pauses of (.+?)\. beginning at (.+?), when will reading finish and how much total time elapses$").captures(input) {
        return Some(repeated_elapsed_schedule(engine, context, &c[1], &c[2], SchedulePauses::Named(&c[3]), &c[4], false));
    }
    if let Some(c) = re!(r"(?i)^run (.+?) test jobs, each (.+?), pausing (.+?) after jobs (.+?)\. given a (.+?) start, calculate the finish time and complete interval$").captures(input) {
        return Some(repeated_elapsed_schedule(engine, context, &c[1], &c[2], SchedulePauses::Listed { durations: &c[3], indices: &c[4] }, &c[5], false));
    }
    if let Some(c) = re!(r"(?i)^(.+?) lessons last (.+?) apiece, with pauses after lessons (.+?) of (.+?)\. starting at (.+?), give the final finish time and elapsed duration including all pauses$").captures(input) {
        return Some(repeated_elapsed_schedule(engine, context, &c[1], &c[2], SchedulePauses::Listed { durations: &c[4], indices: &c[3] }, &c[5], false));
    }
    if let Some(c) = re!(r"(?i)^i label (.+?) boxes at (.+?) each, with unequal pauses of (.+?) after boxes (.+?)\. from a (.+?) start, calculate final completion time and total start-to-finish interval$").captures(input) {
        return Some(repeated_elapsed_schedule(engine, context, &c[1], &c[2], SchedulePauses::Listed { durations: &c[3], indices: &c[4] }, &c[5], false));
    }
    if let Some(c) = re!(r"(?i)^starting at (\d{2}:\d{2}|\d{1,2}:\d{2} (?:am|pm)), complete (.+?) work blocks of (.+?) each with pauses of (.+?)\. give each block's start and finish time and the final finish time$").captures(input) {
        return Some((|| {
            let count = super::count(&c[2])?;
            if !(1..=256).contains(&count) { return Err(invalid("invalid_duration")); }
            let list = vec![c[3].to_owned(); count as usize].join(", ");
            let stated = count.to_string();
            task_schedule(engine, context, ScheduleRequest {
                kind: "block", stated: &stated, list: &list, clock: &c[1],
                pauses: SchedulePauses::Named(&c[4]), final_goal: true, elapsed_goal: None,
            })
        })());
    }
    if let Some(c) = re!(r"(?i)^plan (.+?) consecutive tasks lasting (.+?), starting at (\d{2}:\d{2}) with a (.+?)-minute break between tasks\. give each task's start and finish time$").captures(input) {
        return Some(task_schedule(engine, context, ScheduleRequest {
            kind: "task", stated: &c[1], list: &c[2], clock: &c[3], pauses: SchedulePauses::Uniform(&c[4]), final_goal: false, elapsed_goal: None,
        }));
    }
    if let Some(c) = re!(r"(?i)^an event starts at (\d{2}:\d{2}) and has segments of (.+?) with (.+?)-minute breaks between segments\. give segment start/end clock times and final finish time$").captures(input) {
        let count = re!(r",\s*and\s+|,\s*").split(&c[2]).count().to_string();
        return Some(task_schedule(engine, context, ScheduleRequest {
            kind: "segment", stated: &count, list: &c[2], clock: &c[1], pauses: SchedulePauses::Uniform(&c[3]), final_goal: true, elapsed_goal: None,
        }));
    }
    if let Some(c) = re!(r"(?i)^a workday starts at (.+?) with tasks of (.+?) and a (.+?) lunch break between task (.+?) and task (.+?) only; show the task intervals and finish time$").captures(input) {
        let count = re!(r",\s*and\s+|,\s*").split(&c[2]).count().to_string();
        return Some(task_schedule(engine, context, ScheduleRequest {
            kind: "task", stated: &count, list: &c[2], clock: &c[1],
            pauses: SchedulePauses::Only { amount: &c[3], before: &c[4], after: &c[5] },
            final_goal: true, elapsed_goal: None,
        }));
    }
    if let Some(c) = re!(r"(?i)^starting at (\d{4}-\d{2}-\d{2} \d{2}:\d{2} UTC), what local date and time is it in (.+?) after (\d+) hours (\d+) minutes, using the IANA timezone rules for that date$").captures(input) {
        return Some((|| {
            let seconds = count(&c[3])?.checked_mul(3600)
                .and_then(|hours| count(&c[4]).ok()?.checked_mul(60).and_then(|minutes| hours.checked_add(minutes)))
                .ok_or_else(|| invalid("integer_limit"))?;
            instant(shifted(&c[1], seconds, context)?, zone(&c[2])?)
        })());
    }
    if let Some(c) = re!(r"(?i)^a train leaves (\d{4}-\d{2}-\d{2} \d{2}:\d{2}) in ([^;]+); using the first occurrence of that repeated local time, what local time and date is (\d+) elapsed minutes later$").captures(input) {
        return Some((|| {
            let zone = zone(&c[2])?;
            let start = format!("{} {} first occurrence", &c[1], zone.name());
            let minutes = count(&c[3])?;
            instant(shifted(&start, minutes.checked_mul(60).ok_or_else(|| invalid("integer_limit"))?, context)?, zone)
        })());
    }
    if let Some(c) = re!(r"(?i)^under a policy that counts every calendar date touched, how many dates does an interval from (\d{4}-\d{2}-\d{2} \d{2}:\d{2}) ([^ ]+) through (\d{4}-\d{2}-\d{2} \d{2}:\d{2}) ([^ ]+) touch$").captures(input) {
        return Some((|| {
            let a = zone(&c[2])?;
            let b = zone(&c[4])?;
            if a != b { return Err(invalid("invalid_endpoint")); }
            let start = endpoint::resolve(&format!("{} {}", &c[1], a.name()), context)?;
            let end = endpoint::resolve(&format!("{} {}", &c[3], b.name()), context)?;
            interval(&start, &end)?;
            let dates = (end.with_timezone(&a).date_naive() - start.with_timezone(&a).date_naive()).num_days() + 1;
            Ok(format!("calendar_datetime_dates({dates})"))
        })());
    }
    if let Some(c) = re!(r"(?i)^if a subscription starts at (\d{4}-\d{2}-\d{2} \d{2}:\d{2} UTC) and renews monthly on the last calendar day at (\d{2}:\d{2}) UTC, what is its renewal timestamp after (\d+) renewals$").captures(input) {
        return Some((|| {
            let start = endpoint::resolve(&c[1], context)?;
            let renewal_time = NaiveTime::parse_from_str(&c[2], "%H:%M").map_err(|_| invalid("invalid_endpoint"))?;
            let count = count(&c[3])?;
            if !(1..=1000).contains(&count) { return Err(invalid("integer_limit")); }
            let mut year = start.year();
            let mut month = start.month();
            let mut renewal = start;
            for _ in 0..count {
                if month == 12 { year = year.checked_add(1).ok_or_else(|| invalid("invalid_endpoint"))?; month = 1; }
                else { month += 1; }
                let first_next = if month == 12 {
                    NaiveDate::from_ymd_opt(year.checked_add(1).ok_or_else(|| invalid("invalid_endpoint"))?, 1, 1)
                } else { NaiveDate::from_ymd_opt(year, month + 1, 1) }
                .ok_or_else(|| invalid("invalid_endpoint"))?;
                let last = first_next.pred_opt().ok_or_else(|| invalid("invalid_endpoint"))?;
                renewal = Utc.from_utc_datetime(&last.and_time(renewal_time));
            }
            instant(renewal, Tz::UTC)
        })());
    }
    if let Some(c) = re!(r"(?i)^a meeting is (\d{4}-\d{2}-\d{2} \d{2}:\d{2}) ([^;]+); add (\d+) elapsed minutes and report the resulting local date and time under the timezone's actual daylight-saving rules$").captures(input) {
        return Some((|| {
            let zone = zone(&c[2])?;
            let minutes = count(&c[3])?;
            instant(shifted(&format!("{} {}", &c[1], zone.name()), minutes.checked_mul(60).ok_or_else(|| invalid("integer_limit"))?, context)?, zone)
        })());
    }
    if let Some(c) = re!(r"(?i)^how many minutes elapse from (\d{4}-\d{2}-\d{2} \d{2}:\d{2} UTC) to (\d{4}-\d{2}-\d{2} \d{2}:\d{2} UTC), and how many UTC calendar dates are touched, counting both endpoints' dates$").captures(input) {
        return Some((|| {
            let start = endpoint::resolve(&c[1], context)?;
            let end = endpoint::resolve(&c[2], context)?;
            interval(&start, &end)?;
            let minutes = (end - start).num_minutes();
            let dates = (end.date_naive() - start.date_naive()).num_days() + 1;
            Ok(format!("calendar_datetime_elapsed_dates({minutes}|{dates})"))
        })());
    }
    if let Some(c) = re!(r"(?i)^starting from (\d{4}-\d{2}-\d{2} \d{2}:\d{2}) ([^,]+), add (\d+) calendar days and then (\d+) elapsed hours; what is the final local timestamp under the timezone rules$").captures(input) {
        return Some((|| {
            let zone = zone(&c[2])?;
            let start = endpoint::resolve(&format!("{} {}", &c[1], zone.name()), context)?.with_timezone(&zone);
            let days = count(&c[3])?;
            let local_date = start.date_naive().checked_add_signed(Duration::try_days(days).ok_or_else(|| invalid("integer_limit"))?).ok_or_else(|| invalid("invalid_endpoint"))?;
            let local = local_date.and_time(start.time());
            let calendar_step = match zone.from_local_datetime(&local) {
                LocalResult::Single(point) => point.with_timezone(&Utc),
                LocalResult::Ambiguous(_, _) => return Err(invalid("ambiguous_endpoint")),
                LocalResult::None => return Err(invalid("nonexistent_endpoint")),
            };
            let seconds = count(&c[4])?.checked_mul(3600).ok_or_else(|| invalid("integer_limit"))?;
            instant(calendar_step.checked_add_signed(Duration::try_seconds(seconds).ok_or_else(|| invalid("integer_limit"))?).ok_or_else(|| invalid("invalid_endpoint"))?, zone)
        })());
    }
    if let Some(c) = re!(r"(?i)^a trip starts (\d{4}-\d{2}-\d{2} \d{2}:\d{2}) ([^;]+); add (\d+) elapsed minutes, choosing the actual instant represented by that valid local time, and report the local result$").captures(input) {
        return Some((|| {
            let zone = zone(&c[2])?;
            let seconds = count(&c[3])?.checked_mul(60).ok_or_else(|| invalid("integer_limit"))?;
            instant(shifted(&format!("{} {}", &c[1], zone.name()), seconds, context)?, zone)
        })());
    }
    if let Some(c) = re!(r"(?i)^from (\d{4}-\d{2}-\d{2}) through (\d{4}-\d{2}-\d{2}), count calendar dates inclusively and calculate the elapsed number of midnight-to-midnight days between the endpoints$").captures(input) {
        return Some((|| {
            let days = (date(&c[2])? - date(&c[1])?).num_days();
            if days < 0 { return Err(invalid("invalid_interval")); }
            Ok(format!("calendar_datetime_date_span({days})"))
        })());
    }
    if let Some(c) = re!(r"(?i)^a task starts at (\d{2}:\d{2}) and ends at (\d{2}:\d{2}) on the same day; calculate elapsed time in minutes and decimal hours$").captures(input) {
        return Some((|| {
            let start = NaiveTime::parse_from_str(&c[1], "%H:%M").map_err(|_| invalid("invalid_endpoint"))?;
            let end = NaiveTime::parse_from_str(&c[2], "%H:%M").map_err(|_| invalid("invalid_endpoint"))?;
            let minutes = (end.num_seconds_from_midnight() as i64 - start.num_seconds_from_midnight() as i64) / 60;
            if minutes < 0 { return Err(invalid("invalid_interval")); }
            Ok(format!("calendar_datetime_clock({minutes})"))
        })());
    }
    None
}

pub(super) fn evaluate(input: &str) -> Outcome {
    if let Some(inner) = input
        .strip_prefix("calendar_task_schedule(")
        .and_then(|s| s.strip_suffix(')'))
    {
        return Some((|| {
            if input.len() > 4096 {
                return Err(invalid("expression_too_complex"));
            }
            let mut fields = inner.split('|');
            let (Some(kind), Some(goal), Some(pairs), None) =
                (fields.next(), fields.next(), fields.next(), fields.next())
            else {
                return Err(invalid("invalid_expression"));
            };
            if !matches!(kind, "task" | "segment" | "block")
                || !matches!(goal, "pairs" | "final" | "elapsed_first" | "finish_first")
            {
                return Err(invalid("invalid_expression"));
            }
            let pairs = pairs.split(';').collect::<Vec<_>>();
            if !(1..=256).contains(&pairs.len()) {
                return Err(invalid("invalid_expression"));
            }
            let mut output = Vec::new();
            let mut previous = None;
            let mut final_time = None;
            let mut initial_time = None;
            for (index, pair) in pairs.iter().enumerate() {
                let (start, finish) = pair
                    .split_once('~')
                    .ok_or_else(|| invalid("invalid_expression"))?;
                let read = |value: &str| -> Result<BigRational, Error> {
                    let (n, d) = integer_queries::ratio_value(value)?;
                    if d == 0.into() {
                        return Err(invalid("invalid_expression"));
                    }
                    Ok(BigRational::new(n, d))
                };
                let (start, finish) = (read(start)?, read(finish)?);
                if finish < start || previous.as_ref().is_some_and(|value| &start < value) {
                    return Err(invalid("invalid_expression"));
                }
                if index == 0 {
                    initial_time = Some(start.clone());
                }
                output.push(format!(
                    "{kind} {} start: {}",
                    index + 1,
                    clock_display(start)?
                ));
                output.push(format!(
                    "{kind} {} {}: {}",
                    index + 1,
                    if kind == "segment" { "end" } else { "finish" },
                    clock_display(finish.clone())?
                ));
                previous = Some(finish.clone());
                final_time = Some(finish);
            }
            if matches!(goal, "elapsed_first" | "finish_first") {
                let start = initial_time.ok_or_else(|| invalid("invalid_expression"))?;
                let finish = final_time.ok_or_else(|| invalid("invalid_expression"))?;
                let minutes = model_coordinates::bounded((&finish - start) / BigInt::from(60))?;
                let display = if minutes.is_integer() {
                    integer_queries::decimal(&minutes.to_integer())
                } else {
                    let number = minutes
                        .to_f64()
                        .filter(|n| n.is_finite())
                        .ok_or_else(|| invalid("numeric_overflow"))?;
                    if number == 0.0 && !minutes.is_zero() {
                        return Err(invalid("numeric_underflow"));
                    }
                    crate::number(number)
                };
                let elapsed = format!("elapsed interval: {display} minutes");
                let clock = format!("finish time: {}", clock_display(finish)?);
                output = if goal == "elapsed_first" {
                    vec![elapsed, clock]
                } else {
                    vec![clock, elapsed]
                };
            } else if goal == "final" {
                output.push(format!(
                    "final finish: {}",
                    clock_display(final_time.ok_or_else(|| invalid("invalid_expression"))?)?
                ));
            }
            let result = output.join("; ");
            if result.len() > 4096 {
                return Err(invalid("expression_too_complex"));
            }
            Ok(result)
        })());
    }
    if let Some(c) = re!(r"^calendar_datetime_instant\((-?\d+)\|([^|]+)\)$").captures(input) {
        return Some((|| {
            let seconds = count(&c[1])?;
            let zone = zone(&c[2])?;
            let instant = DateTime::<Utc>::from_timestamp(seconds, 0)
                .ok_or_else(|| invalid("invalid_endpoint"))?;
            let local = instant.with_timezone(&zone);
            let hour = if local.hour().is_multiple_of(12) {
                12
            } else {
                local.hour() % 12
            };
            let meridiem = if local.hour() < 12 { "am" } else { "pm" };
            let seconds = if local.second() == 0 {
                String::new()
            } else {
                format!(":{:02}", local.second())
            };
            Ok(format!(
                "{} at {hour}:{:02}{seconds} {meridiem} {}",
                local.format("%-d %B %Y"),
                local.minute(),
                local.format("%Z")
            ))
        })());
    }
    if let Some(c) = re!(r"^calendar_datetime_dates\((\d+)\)$").captures(input) {
        return Some(Ok(format!("{} dates", &c[1])));
    }
    if let Some(c) = re!(r"^calendar_datetime_elapsed_dates\((\d+)\|(\d+)\)$").captures(input) {
        return Some(Ok(format!(
            "elapsed time: {} min; calendar dates: {} dates",
            &c[1], &c[2]
        )));
    }
    if let Some(c) = re!(r"^calendar_datetime_date_span\((\d+)\)$").captures(input) {
        return Some((|| {
            let days = count(&c[1])?;
            let dates = days
                .checked_add(1)
                .ok_or_else(|| invalid("integer_limit"))?;
            Ok(format!(
                "calendar dates: {dates} dates; elapsed time: {days} days"
            ))
        })());
    }
    if let Some(c) = re!(r"^calendar_datetime_clock\((\d+)\)$").captures(input) {
        return Some((|| {
            let minutes = count(&c[1])?;
            Ok(format!(
                "elapsed time: {minutes} min; decimal hours: {} h",
                crate::number(minutes as f64 / 60.0)
            ))
        })());
    }
    None
}