interpretthis 0.4.1

Sandboxed Python AST interpreter for untrusted and LLM-generated code
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
// Copyright 2026 Thomas Santerre and Moderately AI Inc.
//
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Emulation of Python's `datetime` module — date / datetime / time /
//! timedelta / timezone (Track D).
//!
//! Storage maps to chrono types: `NaiveDate` for `date`,
//! `NaiveDateTime` for `datetime` (with an optional fixed UTC offset),
//! `NaiveTime` for `time`, raw microseconds for `timedelta`, raw
//! seconds for `timezone`. Arithmetic between date / datetime and
//! timedelta lands here. Aware vs naive `datetime` mixing raises
//! TypeError per CPython.

use chrono::{Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime, Timelike};

use crate::{
    error::{EvalError, EvalResult, InterpreterError},
    eval::modules::{arg_str, value_error},
    value::Value,
};

/// Translate a Python `strftime` format to the equivalent chrono format. The
/// load-bearing difference is `%f`: Python zero-pads microseconds to 6 digits,
/// while chrono's `%f` is 9-digit nanoseconds — chrono's `%6f` matches Python.
fn py_strftime_fmt(fmt: &str) -> String {
    let mut out = String::with_capacity(fmt.len());
    let mut chars = fmt.chars();
    while let Some(c) = chars.next() {
        if c == '%' {
            match chars.next() {
                Some('f') => out.push_str("%6f"),
                Some(other) => {
                    out.push('%');
                    out.push(other);
                }
                None => out.push('%'),
            }
        } else {
            out.push(c);
        }
    }
    out
}

/// Whether `datetime` provides a **module-level** callable named `name`.
/// Classmethods on constructors (e.g. `datetime.strptime`) are not listed
/// here — they resolve through [`type_classmethod`].
pub fn has_function(name: &str) -> bool {
    matches!(name, "date" | "datetime" | "time" | "timedelta" | "timezone")
}

/// Classmethods on datetime module constructors (`datetime.datetime.strptime`).
/// Returns the internal `call` function name when `type_name.method` is valid.
#[must_use]
pub fn type_classmethod(type_name: &str, method: &str) -> Option<&'static str> {
    match (type_name, method) {
        ("datetime", "strptime") => Some("strptime"),
        ("date", "fromisoformat") => Some("date.fromisoformat"),
        ("datetime", "fromisoformat") => Some("datetime.fromisoformat"),
        ("date", "fromordinal") => Some("date.fromordinal"),
        ("datetime", "fromordinal") => Some("datetime.fromordinal"),
        ("time", "fromisoformat") => Some("time.fromisoformat"),
        _ => None,
    }
}

/// Class-level *constant* attributes on datetime types (as opposed to
/// [`type_classmethod`], which resolves callables). `timezone.utc` is the fixed
/// UTC timezone — `timezone(timedelta(0))`.
#[must_use]
pub fn type_attribute(type_name: &str, attr: &str) -> Option<Value> {
    match (type_name, attr) {
        ("timezone", "utc") => Some(Value::TimeZone(0)),
        // date/datetime/time bounds and resolution (CPython class constants).
        ("date", "max") => Some(Value::Date(NaiveDate::from_ymd_opt(9999, 12, 31)?)),
        ("date", "min") => Some(Value::Date(NaiveDate::from_ymd_opt(1, 1, 1)?)),
        ("date", "resolution") => Some(Value::TimeDelta(86_400_000_000)),
        ("datetime", "max") => Some(Value::DateTime {
            dt: NaiveDate::from_ymd_opt(9999, 12, 31)?.and_hms_micro_opt(23, 59, 59, 999_999)?,
            tz_offset_secs: None,
        }),
        ("datetime", "min") => Some(Value::DateTime {
            dt: NaiveDate::from_ymd_opt(1, 1, 1)?.and_hms_opt(0, 0, 0)?,
            tz_offset_secs: None,
        }),
        ("datetime", "resolution") | ("time", "resolution") => Some(Value::TimeDelta(1)),
        ("time", "max") => Some(Value::Time(NaiveTime::from_hms_micro_opt(23, 59, 59, 999_999)?)),
        ("time", "min") => Some(Value::Time(NaiveTime::from_hms_opt(0, 0, 0)?)),
        _ => None,
    }
}

/// Build a `NaiveDate` with CPython's exact validation order +
/// wording: year first (`year N is out of range`), then month
/// (`month must be in 1..12`), then day (`day is out of range for
/// month`). chrono's `from_ymd_opt` returns `None` for any
/// invalidity without saying which — so we pre-validate each
/// component to attach the right CPython message.
fn construct_naive_date(year: i32, month: u32, day: u32) -> Result<NaiveDate, EvalError> {
    if !(1..=9999).contains(&year) {
        return Err(value_error(format!("year {year} is out of range")));
    }
    if !(1..=12).contains(&month) {
        return Err(value_error("month must be in 1..12"));
    }
    NaiveDate::from_ymd_opt(year, month, day)
        .ok_or_else(|| value_error("day is out of range for month"))
}

/// Invoke a `datetime` constructor. Positional and keyword arguments are bound
/// through `bind_method_params`, so both `datetime(2020, 1, 1, hour=9)` and the
/// fully-positional form work and unknown/duplicate keywords raise TypeError.
pub fn call(func: &str, args: &[Value], kwargs: &indexmap::IndexMap<String, Value>) -> EvalResult {
    use crate::eval::functions::bind_method_params;
    match func {
        "date" => {
            let b = bind_method_params(func, args, kwargs, &["year", "month", "day"])?;
            let year = comp_i32(b[0].as_ref(), func, "year")?;
            let month = comp_u32(b[1].as_ref(), func, "month")?;
            let day = comp_u32(b[2].as_ref(), func, "day")?;
            let date = construct_naive_date(year, month, day)?;
            Ok(Value::Date(date))
        }
        "datetime" => {
            // datetime(year, month, day, hour=0, minute=0, second=0,
            //          microsecond=0, tzinfo=None, *, fold=0). Tzinfo is a
            // Value::TimeZone or None; fold is accepted but not modelled.
            let b = bind_method_params(
                func,
                args,
                kwargs,
                &[
                    "year",
                    "month",
                    "day",
                    "hour",
                    "minute",
                    "second",
                    "microsecond",
                    "tzinfo",
                    "fold",
                ],
            )?;
            let year = comp_i32(b[0].as_ref(), func, "year")?;
            let month = comp_u32(b[1].as_ref(), func, "month")?;
            let day = comp_u32(b[2].as_ref(), func, "day")?;
            let hour = comp_opt_u32(b[3].as_ref(), func)?.unwrap_or(0);
            let minute = comp_opt_u32(b[4].as_ref(), func)?.unwrap_or(0);
            let second = comp_opt_u32(b[5].as_ref(), func)?.unwrap_or(0);
            let microsecond = comp_opt_u32(b[6].as_ref(), func)?.unwrap_or(0);
            let date = construct_naive_date(year, month, day)?;
            let time = NaiveTime::from_hms_micro_opt(hour, minute, second, microsecond)
                .ok_or_else(|| value_error("time component out of range"))?;
            let dt = NaiveDateTime::new(date, time);
            let tz_offset_secs = match b[7].as_ref() {
                None | Some(Value::None) => None,
                Some(Value::TimeZone(secs)) => Some(*secs),
                Some(other) => {
                    return Err(InterpreterError::TypeError(format!(
                        "datetime() tzinfo must be a datetime.timezone (got '{}')",
                        other.type_name()
                    ))
                    .into());
                }
            };
            Ok(Value::DateTime { dt, tz_offset_secs })
        }
        "time" => {
            // time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None,
            //      *, fold=0). Our time is naive; tzinfo/fold are accepted for
            // signature parity but not modelled.
            let b = bind_method_params(
                func,
                args,
                kwargs,
                &["hour", "minute", "second", "microsecond", "tzinfo", "fold"],
            )?;
            let hour = comp_opt_u32(b[0].as_ref(), func)?.unwrap_or(0);
            let minute = comp_opt_u32(b[1].as_ref(), func)?.unwrap_or(0);
            let second = comp_opt_u32(b[2].as_ref(), func)?.unwrap_or(0);
            let microsecond = comp_opt_u32(b[3].as_ref(), func)?.unwrap_or(0);
            let t = NaiveTime::from_hms_micro_opt(hour, minute, second, microsecond)
                .ok_or_else(|| value_error("time component out of range"))?;
            Ok(Value::Time(t))
        }
        "timedelta" => {
            let b = bind_method_params(
                func,
                args,
                kwargs,
                &["days", "seconds", "microseconds", "milliseconds", "minutes", "hours", "weeks"],
            )?;
            let days = comp_opt_i64(b[0].as_ref())?.unwrap_or(0);
            let seconds = comp_opt_i64(b[1].as_ref())?.unwrap_or(0);
            let microseconds = comp_opt_i64(b[2].as_ref())?.unwrap_or(0);
            let milliseconds = comp_opt_i64(b[3].as_ref())?.unwrap_or(0);
            let minutes = comp_opt_i64(b[4].as_ref())?.unwrap_or(0);
            let hours = comp_opt_i64(b[5].as_ref())?.unwrap_or(0);
            let weeks = comp_opt_i64(b[6].as_ref())?.unwrap_or(0);
            // Compose into microseconds carefully — every component
            // converts via i64 multiplication, saturating-checked at
            // each step so 1e18-microsecond inputs surface as an
            // OverflowError rather than wrap silently.
            let micros = days
                .checked_mul(86_400_000_000)
                .and_then(|d| weeks.checked_mul(7 * 86_400_000_000).and_then(|w| d.checked_add(w)))
                .and_then(|x| hours.checked_mul(3_600_000_000).and_then(|h| x.checked_add(h)))
                .and_then(|x| minutes.checked_mul(60_000_000).and_then(|m| x.checked_add(m)))
                .and_then(|x| seconds.checked_mul(1_000_000).and_then(|s| x.checked_add(s)))
                .and_then(|x| milliseconds.checked_mul(1_000).and_then(|ms| x.checked_add(ms)))
                .and_then(|x| x.checked_add(microseconds))
                .ok_or_else(|| value_error("timedelta overflow"))?;
            Ok(Value::TimeDelta(micros))
        }
        "timezone" => {
            // timezone(offset, name=None) where offset is a timedelta.
            let b = bind_method_params(func, args, kwargs, &["offset", "name"])?;
            let offset = b[0]
                .as_ref()
                .ok_or_else(|| value_error("timezone() missing required argument 'offset'"))?;
            let secs = match offset {
                Value::TimeDelta(micros) => {
                    let secs_i64 = micros / 1_000_000;
                    i32::try_from(secs_i64)
                        .map_err(|_| value_error("timezone offset out of range"))?
                }
                _ => {
                    return Err(InterpreterError::TypeError(format!(
                        "timezone() argument 1 must be a timedelta (got '{}')",
                        offset.type_name()
                    ))
                    .into());
                }
            };
            Ok(Value::TimeZone(secs))
        }
        // Invoked only via type_classmethod resolution (not module_member).
        "strptime" => {
            let s = arg_str("strptime", args, 0)?;
            let fmt = arg_str("strptime", args, 1)?;
            parse_strptime(s, fmt)
        }
        "date.fromisoformat" => {
            let s = arg_str("fromisoformat", args, 0)?;
            NaiveDate::parse_from_str(s, "%Y-%m-%d").map(Value::Date).map_err(|_| {
                EvalError::from(InterpreterError::ValueError(format!(
                    "Invalid isoformat string: '{s}'"
                )))
            })
        }
        "datetime.fromisoformat" => {
            let s = arg_str("fromisoformat", args, 0)?;
            // Accept the common "T"/" "-separated forms, with or without seconds.
            let parsed = NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S")
                .or_else(|_| NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S"))
                .or_else(|_| NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M"))
                .or_else(|_| {
                    NaiveDate::parse_from_str(s, "%Y-%m-%d")
                        .map(|d| d.and_hms_opt(0, 0, 0).unwrap_or_default())
                });
            parsed.map(|dt| Value::DateTime { dt, tz_offset_secs: None }).map_err(|_| {
                EvalError::from(InterpreterError::ValueError(format!(
                    "Invalid isoformat string: '{s}'"
                )))
            })
        }
        "time.fromisoformat" => {
            let s = arg_str("fromisoformat", args, 0)?;
            let invalid = || {
                EvalError::from(InterpreterError::ValueError(format!(
                    "Invalid isoformat string: '{s}'"
                )))
            };
            // Accept the ISO forms `HH:MM:SS.ffffff`, `HH:MM:SS`, and `HH:MM`;
            // the bare-hour `HH` form has no separator for chrono to anchor on,
            // so parse it directly. Naive only — a trailing timezone offset is
            // not modelled.
            let t = NaiveTime::parse_from_str(s, "%H:%M:%S%.f")
                .or_else(|_| NaiveTime::parse_from_str(s, "%H:%M:%S"))
                .or_else(|_| NaiveTime::parse_from_str(s, "%H:%M"))
                .ok()
                .or_else(|| s.parse::<u32>().ok().and_then(|h| NaiveTime::from_hms_opt(h, 0, 0)))
                .ok_or_else(invalid)?;
            Ok(Value::Time(t))
        }
        // `date.fromordinal(n)` / `datetime.fromordinal(n)`: proleptic Gregorian
        // ordinal where day 1 is 0001-01-01 — exactly chrono's
        // `num_days_from_ce`. `datetime.fromordinal` sets the time to midnight.
        "date.fromordinal" | "datetime.fromordinal" => {
            let n = args
                .first()
                .and_then(crate::value::value_as_i64)
                .and_then(|n| i32::try_from(n).ok())
                .ok_or_else(|| {
                    EvalError::from(InterpreterError::TypeError(
                        "fromordinal() argument must be an integer".into(),
                    ))
                })?;
            let date = NaiveDate::from_num_days_from_ce_opt(n).ok_or_else(|| {
                EvalError::from(InterpreterError::ValueError("ordinal out of range".into()))
            })?;
            if func == "date.fromordinal" {
                Ok(Value::Date(date))
            } else {
                Ok(Value::DateTime {
                    dt: date.and_hms_opt(0, 0, 0).unwrap_or_default(),
                    tz_offset_secs: None,
                })
            }
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "module 'datetime' has no attribute '{func}'"
        ))
        .into()),
    }
}

/// `datetime.strptime(date_string, format)` — always returns a naive
/// `datetime` (CPython shape). Uses chrono's format parser; unsupported
/// directives surface as ValueError rather than locale-dependent output.
fn parse_strptime(s: &str, fmt: &str) -> EvalResult {
    if let Ok(dt) = NaiveDateTime::parse_from_str(s, fmt) {
        return Ok(Value::DateTime { dt, tz_offset_secs: None });
    }
    // Date-only formats: CPython still returns datetime at 00:00:00.
    if let Ok(date) = NaiveDate::parse_from_str(s, fmt) {
        let Some(time) = NaiveTime::from_hms_opt(0, 0, 0) else {
            return Err(value_error("internal: failed to build midnight time"));
        };
        return Ok(Value::DateTime { dt: NaiveDateTime::new(date, time), tz_offset_secs: None });
    }
    // Time-only formats: CPython uses date 1900-01-01.
    if let Ok(time) = NaiveTime::parse_from_str(s, fmt) {
        let Some(date) = NaiveDate::from_ymd_opt(1900, 1, 1) else {
            return Err(value_error("internal: failed to build 1900-01-01"));
        };
        return Ok(Value::DateTime { dt: NaiveDateTime::new(date, time), tz_offset_secs: None });
    }
    Err(value_error(format!("time data '{s}' does not match format '{fmt}'")))
}

/// Read an attribute of a `date` value (`.year`, `.month`, `.day`).
pub fn date_attribute(date: NaiveDate, attr: &str) -> EvalResult {
    match attr {
        "year" => Ok(Value::Int(i64::from(date.year()))),
        "month" => Ok(Value::Int(i64::from(date.month()))),
        "day" => Ok(Value::Int(i64::from(date.day()))),
        _ => Err(InterpreterError::AttributeError(format!(
            "'date' object has no attribute '{attr}'"
        ))
        .into()),
    }
}

/// Read an attribute of a `datetime` value.
pub fn datetime_attribute(
    dt: NaiveDateTime,
    tz_offset_secs: Option<i32>,
    attr: &str,
) -> EvalResult {
    match attr {
        "year" => Ok(Value::Int(i64::from(dt.year()))),
        "month" => Ok(Value::Int(i64::from(dt.month()))),
        "day" => Ok(Value::Int(i64::from(dt.day()))),
        "hour" => Ok(Value::Int(i64::from(dt.hour()))),
        "minute" => Ok(Value::Int(i64::from(dt.minute()))),
        "second" => Ok(Value::Int(i64::from(dt.second()))),
        "microsecond" => Ok(Value::Int(i64::from(dt.nanosecond() / 1_000))),
        "tzinfo" => Ok(tz_offset_secs.map_or(Value::None, Value::TimeZone)),
        _ => Err(InterpreterError::AttributeError(format!(
            "'datetime' object has no attribute '{attr}'"
        ))
        .into()),
    }
}

/// Read an attribute of a `time` value.
pub fn time_attribute(t: NaiveTime, attr: &str) -> EvalResult {
    match attr {
        "hour" => Ok(Value::Int(i64::from(t.hour()))),
        "minute" => Ok(Value::Int(i64::from(t.minute()))),
        "second" => Ok(Value::Int(i64::from(t.second()))),
        "microsecond" => Ok(Value::Int(i64::from(t.nanosecond() / 1_000))),
        _ => Err(InterpreterError::AttributeError(format!(
            "'time' object has no attribute '{attr}'"
        ))
        .into()),
    }
}

/// Read an attribute of a `timedelta` value.
pub fn timedelta_attribute(micros: i64, attr: &str) -> EvalResult {
    // CPython's timedelta normalises so seconds and microseconds are
    // non-negative; we match by using Euclidean division.
    let secs_total = micros.div_euclid(1_000_000);
    let us = micros.rem_euclid(1_000_000);
    let days = secs_total.div_euclid(86_400);
    let secs = secs_total.rem_euclid(86_400);
    match attr {
        "days" => Ok(Value::Int(days)),
        "seconds" => Ok(Value::Int(secs)),
        "microseconds" => Ok(Value::Int(us)),
        _ => Err(InterpreterError::AttributeError(format!(
            "'timedelta' object has no attribute '{attr}'"
        ))
        .into()),
    }
}

/// Dispatch a method on a `date` value.
/// Build a `time.struct_time` Instance (the class is seeded in
/// `InterpreterState::new`). `tm_isdst` is -1 for date/datetime (unknown).
fn build_struct_time(
    year: i32,
    month: u32,
    day: u32,
    hour: u32,
    minute: u32,
    second: u32,
    wday: u32,
    yday: u32,
) -> Value {
    let mut fields = std::collections::BTreeMap::new();
    fields.insert("tm_year".to_string(), Value::Int(i64::from(year)));
    fields.insert("tm_mon".to_string(), Value::Int(i64::from(month)));
    fields.insert("tm_mday".to_string(), Value::Int(i64::from(day)));
    fields.insert("tm_hour".to_string(), Value::Int(i64::from(hour)));
    fields.insert("tm_min".to_string(), Value::Int(i64::from(minute)));
    fields.insert("tm_sec".to_string(), Value::Int(i64::from(second)));
    fields.insert("tm_wday".to_string(), Value::Int(i64::from(wday)));
    fields.insert("tm_yday".to_string(), Value::Int(i64::from(yday)));
    fields.insert("tm_isdst".to_string(), Value::Int(-1));
    Value::Instance(crate::value::InstanceValue {
        class_name: "time.struct_time".to_string(),
        fields: crate::value::shared_fields(fields),
    })
}

/// Build a `datetime.IsoCalendarDate` Instance (ISO year, week, weekday 1-7).
fn build_isocalendar(date: NaiveDate) -> Value {
    let iso = date.iso_week();
    let mut fields = std::collections::BTreeMap::new();
    fields.insert("year".to_string(), Value::Int(i64::from(iso.year())));
    fields.insert("week".to_string(), Value::Int(i64::from(iso.week())));
    fields
        .insert("weekday".to_string(), Value::Int(i64::from(date.weekday().number_from_monday())));
    Value::Instance(crate::value::InstanceValue {
        class_name: "datetime.IsoCalendarDate".to_string(),
        fields: crate::value::shared_fields(fields),
    })
}

pub fn dispatch_date_method(
    date: NaiveDate,
    method: &str,
    args: &[Value],
    kwargs: &indexmap::IndexMap<String, Value>,
) -> EvalResult {
    // `replace` accepts year/month/day keyword args; the others are argument-less.
    if method != "replace" {
        crate::eval::functions::reject_kwargs(method, kwargs)?;
    }
    match method {
        "isoformat" => Ok(Value::String(date.format("%Y-%m-%d").to_string().into())),
        // C `asctime`-style, time fields zeroed: "Fri Mar 15 00:00:00 2024"
        // (day is space-padded via `%e`).
        "ctime" => Ok(Value::String(date.format("%a %b %e 00:00:00 %Y").to_string().into())),
        // Python: Monday == 0 … Sunday == 6.
        "weekday" => Ok(Value::Int(i64::from(date.weekday().num_days_from_monday()))),
        // Python: Monday == 1 … Sunday == 7.
        "isoweekday" => Ok(Value::Int(i64::from(date.weekday().number_from_monday()))),
        // Proleptic Gregorian ordinal — day 1 is 0001-01-01, matching CPython.
        "toordinal" => Ok(Value::Int(i64::from(date.num_days_from_ce()))),
        // `datetime.IsoCalendarDate(year, week, weekday)`.
        "isocalendar" => Ok(build_isocalendar(date)),
        // `time.struct_time` with the time fields zeroed (a plain date).
        "timetuple" => Ok(build_struct_time(
            date.year(),
            date.month(),
            date.day(),
            0,
            0,
            0,
            date.weekday().num_days_from_monday(),
            date.ordinal(),
        )),
        "strftime" => {
            let fmt = py_strftime_fmt(arg_str("strftime", args, 0)?);
            Ok(Value::String(date.format(&fmt).to_string().into()))
        }
        "replace" => {
            let b = crate::eval::functions::bind_method_params(
                method,
                args,
                kwargs,
                &["year", "month", "day"],
            )?;
            let year = comp_opt_i32(b[0].as_ref())?.unwrap_or_else(|| date.year());
            let month = comp_opt_u32(b[1].as_ref(), method)?.unwrap_or_else(|| date.month());
            let day = comp_opt_u32(b[2].as_ref(), method)?.unwrap_or_else(|| date.day());
            let replaced = construct_naive_date(year, month, day)?;
            Ok(Value::Date(replaced))
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "'date' object has no attribute '{method}'"
        ))
        .into()),
    }
}

/// Dispatch a method on a `datetime` value.
pub fn dispatch_datetime_method(
    dt: NaiveDateTime,
    tz_offset_secs: Option<i32>,
    method: &str,
    args: &[Value],
    kwargs: &indexmap::IndexMap<String, Value>,
) -> EvalResult {
    // `replace` accepts keyword components; the others are argument-less.
    if method != "replace" {
        crate::eval::functions::reject_kwargs(method, kwargs)?;
    }
    match method {
        "replace" => {
            let b = crate::eval::functions::bind_method_params(
                method,
                args,
                kwargs,
                &[
                    "year",
                    "month",
                    "day",
                    "hour",
                    "minute",
                    "second",
                    "microsecond",
                    "tzinfo",
                    "fold",
                ],
            )?;
            let year = comp_opt_i32(b[0].as_ref())?.unwrap_or_else(|| dt.year());
            let month = comp_opt_u32(b[1].as_ref(), method)?.unwrap_or_else(|| dt.month());
            let day = comp_opt_u32(b[2].as_ref(), method)?.unwrap_or_else(|| dt.day());
            let hour = comp_opt_u32(b[3].as_ref(), method)?.unwrap_or_else(|| dt.hour());
            let minute = comp_opt_u32(b[4].as_ref(), method)?.unwrap_or_else(|| dt.minute());
            let second = comp_opt_u32(b[5].as_ref(), method)?.unwrap_or_else(|| dt.second());
            let microsecond =
                comp_opt_u32(b[6].as_ref(), method)?.unwrap_or_else(|| dt.nanosecond() / 1_000);
            let tz = match b[7].as_ref() {
                None => tz_offset_secs,
                Some(Value::None) => None,
                Some(Value::TimeZone(secs)) => Some(*secs),
                Some(other) => {
                    return Err(InterpreterError::TypeError(format!(
                        "replace() tzinfo must be a datetime.timezone (got '{}')",
                        other.type_name()
                    ))
                    .into());
                }
            };
            let date = construct_naive_date(year, month, day)?;
            let time = NaiveTime::from_hms_micro_opt(hour, minute, second, microsecond)
                .ok_or_else(|| value_error("time component out of range"))?;
            Ok(Value::DateTime { dt: NaiveDateTime::new(date, time), tz_offset_secs: tz })
        }
        // C `asctime`-style: "Fri Mar 15 14:30:45 2024" (day space-padded).
        "ctime" => Ok(Value::String(dt.format("%a %b %e %H:%M:%S %Y").to_string().into())),
        "isoformat" => {
            // CPython: `2026-01-15T14:30:00` for naive; with tz adds
            // `+HH:MM`. We don't model microseconds in the default
            // isoformat (CPython only shows them when nonzero).
            let mut s = dt.format("%Y-%m-%dT%H:%M:%S").to_string();
            let us = dt.nanosecond() / 1_000;
            if us != 0 {
                s = format!("{s}.{us:06}");
            }
            if let Some(secs) = tz_offset_secs {
                let sign = if secs < 0 { '-' } else { '+' };
                let abs = secs.unsigned_abs();
                let h = abs / 3600;
                let m = (abs % 3600) / 60;
                s = format!("{s}{sign}{h:02}:{m:02}");
            }
            Ok(Value::String(s.into()))
        }
        "date" => Ok(Value::Date(dt.date())),
        "time" => Ok(Value::Time(dt.time())),
        "weekday" => Ok(Value::Int(i64::from(dt.weekday().num_days_from_monday()))),
        "isoweekday" => Ok(Value::Int(i64::from(dt.weekday().number_from_monday()))),
        "isocalendar" => Ok(build_isocalendar(dt.date())),
        // `time.struct_time` including the wall-clock time fields.
        "timetuple" => Ok(build_struct_time(
            dt.year(),
            dt.month(),
            dt.day(),
            dt.hour(),
            dt.minute(),
            dt.second(),
            dt.weekday().num_days_from_monday(),
            dt.ordinal(),
        )),
        "strftime" => {
            let fmt = py_strftime_fmt(arg_str("strftime", args, 0)?);
            Ok(Value::String(dt.format(&fmt).to_string().into()))
        }
        "timestamp" => {
            // CPython treats naive datetime as local time for
            // timestamp(); we treat naive as UTC for determinism (no
            // local-timezone access in the sandbox). Aware datetimes
            // subtract the offset.
            #[expect(
                clippy::cast_precision_loss,
                reason = "matches CPython's timestamp() return shape: f64 seconds since epoch. Loss matters only past 2^53 seconds (~285M years post-epoch)."
            )]
            let mut ts = dt.and_utc().timestamp_millis() as f64 / 1000.0;
            if let Some(secs) = tz_offset_secs {
                ts -= f64::from(secs);
            }
            Ok(Value::Float(ts))
        }
        // `utcoffset()` returns the fixed offset as a timedelta for an aware
        // datetime, None for a naive one. Our timezones are fixed offsets, so
        // `dst()` is always None (no daylight-saving transitions modelled).
        "utcoffset" => Ok(tz_offset_secs
            .map_or(Value::None, |secs| Value::TimeDelta(i64::from(secs) * 1_000_000))),
        "dst" => Ok(Value::None),
        "tzname" => Ok(tz_offset_secs
            .map_or(Value::None, |secs| Value::String(format_fixed_tzname(secs).into()))),
        _ => Err(InterpreterError::AttributeError(format!(
            "'datetime' object has no attribute '{method}'"
        ))
        .into()),
    }
}

/// CPython's `tzname()` for a fixed offset: `UTC`, or `UTC±HH:MM` (further
/// `:SS` only when the offset has a sub-minute part).
fn format_fixed_tzname(offset_secs: i32) -> String {
    if offset_secs == 0 {
        return "UTC".to_string();
    }
    let sign = if offset_secs < 0 { '-' } else { '+' };
    let secs = offset_secs.unsigned_abs();
    let (h, m, s) = (secs / 3600, (secs % 3600) / 60, secs % 60);
    if s == 0 {
        format!("UTC{sign}{h:02}:{m:02}")
    } else {
        format!("UTC{sign}{h:02}:{m:02}:{s:02}")
    }
}

/// Dispatch a method on a `time` value.
pub fn dispatch_time_method(
    t: NaiveTime,
    method: &str,
    args: &[Value],
    kwargs: &indexmap::IndexMap<String, Value>,
) -> EvalResult {
    crate::eval::functions::reject_kwargs(method, kwargs)?;
    match method {
        "isoformat" => {
            let mut s = t.format("%H:%M:%S").to_string();
            let us = t.nanosecond() / 1_000;
            if us != 0 {
                s = format!("{s}.{us:06}");
            }
            Ok(Value::String(s.into()))
        }
        "strftime" => {
            let fmt = py_strftime_fmt(arg_str("strftime", args, 0)?);
            Ok(Value::String(t.format(&fmt).to_string().into()))
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "'time' object has no attribute '{method}'"
        ))
        .into()),
    }
}

/// Dispatch a method on a `timedelta` value.
pub fn dispatch_timedelta_method(
    micros: i64,
    method: &str,
    _args: &[Value],
    kwargs: &indexmap::IndexMap<String, Value>,
) -> EvalResult {
    crate::eval::functions::reject_kwargs(method, kwargs)?;
    match method {
        "total_seconds" => {
            #[expect(
                clippy::cast_precision_loss,
                reason = "matches CPython's total_seconds() return shape: f64 seconds. Loss matters only past 2^53 microseconds (~285 years)."
            )]
            let secs = micros as f64 / 1_000_000.0;
            Ok(Value::Float(secs))
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "'timedelta' object has no attribute '{method}'"
        ))
        .into()),
    }
}

/// Arithmetic between Date / DateTime / TimeDelta. Returns `None` when
/// the operands don't form a supported pair so the dispatcher can try
/// the reflected slot or raise TypeError.
pub fn try_arith(op: &str, lhs: &Value, rhs: &Value) -> Option<EvalResult> {
    match (op, lhs, rhs) {
        // date + timedelta -> date. A date has no time, so only the timedelta's
        // whole-day count matters — and that is `timedelta.days`, the *floored*
        // day count (div_euclid), not truncation toward zero. `timedelta(hours=-1)`
        // has .days == -1, so it moves the date back a day.
        ("+", Value::Date(d), Value::TimeDelta(us))
        | ("+", Value::TimeDelta(us), Value::Date(d)) => {
            let days = i32::try_from(us.div_euclid(86_400_000_000)).ok()?;
            let result = d.checked_add_signed(Duration::days(i64::from(days)))?;
            Some(Ok(Value::Date(result)))
        }
        // date - timedelta -> date (subtract the floored whole-day count).
        ("-", Value::Date(d), Value::TimeDelta(us)) => {
            let days = i32::try_from(us.div_euclid(86_400_000_000)).ok()?;
            let result = d.checked_sub_signed(Duration::days(i64::from(days)))?;
            Some(Ok(Value::Date(result)))
        }
        // date - date -> timedelta (days)
        ("-", Value::Date(a), Value::Date(b)) => {
            let delta = a.signed_duration_since(*b);
            Some(Ok(Value::TimeDelta(delta.num_microseconds()?)))
        }
        // datetime + timedelta -> datetime
        ("+", Value::DateTime { dt, tz_offset_secs }, Value::TimeDelta(us))
        | ("+", Value::TimeDelta(us), Value::DateTime { dt, tz_offset_secs }) => {
            let result = dt.checked_add_signed(Duration::microseconds(*us))?;
            Some(Ok(Value::DateTime { dt: result, tz_offset_secs: *tz_offset_secs }))
        }
        ("-", Value::DateTime { dt, tz_offset_secs }, Value::TimeDelta(us)) => {
            let result = dt.checked_sub_signed(Duration::microseconds(*us))?;
            Some(Ok(Value::DateTime { dt: result, tz_offset_secs: *tz_offset_secs }))
        }
        // datetime - datetime -> timedelta. CPython raises TypeError on
        // mixed aware/naive subtraction.
        (
            "-",
            Value::DateTime { dt: a, tz_offset_secs: tz_a },
            Value::DateTime { dt: b, tz_offset_secs: tz_b },
        ) => {
            if tz_a.is_some() != tz_b.is_some() {
                return Some(Err(InterpreterError::TypeError(
                    "can't subtract offset-naive and offset-aware datetimes".into(),
                )
                .into()));
            }
            let delta = a.signed_duration_since(*b);
            Some(Ok(Value::TimeDelta(delta.num_microseconds()?)))
        }
        // timedelta + timedelta
        ("+", Value::TimeDelta(a), Value::TimeDelta(b)) => {
            Some(Ok(Value::TimeDelta(a.checked_add(*b)?)))
        }
        ("-", Value::TimeDelta(a), Value::TimeDelta(b)) => {
            Some(Ok(Value::TimeDelta(a.checked_sub(*b)?)))
        }
        // timedelta * int -> timedelta (and reflected)
        ("*", Value::TimeDelta(a), Value::Int(n)) | ("*", Value::Int(n), Value::TimeDelta(a)) => {
            Some(Ok(Value::TimeDelta(a.checked_mul(*n)?)))
        }
        // timedelta * float -> timedelta (and reflected). CPython scales by the
        // float's *exact* rational value and rounds to the nearest microsecond
        // (ties to even), so `timedelta(hours=1) * 2.5 == 2:30:00`.
        ("*", Value::TimeDelta(a), Value::Float(f))
        | ("*", Value::Float(f), Value::TimeDelta(a)) => {
            td_scale_float(*a, *f, false).map(|us| Ok(Value::TimeDelta(us)))
        }
        // timedelta / float -> timedelta (divide by the exact rational value).
        ("/", Value::TimeDelta(a), Value::Float(f)) if *f != 0.0 => {
            td_scale_float(*a, *f, true).map(|us| Ok(Value::TimeDelta(us)))
        }
        // timedelta // int -> timedelta (integer microseconds)
        ("//", Value::TimeDelta(a), Value::Int(n)) if *n != 0 => Some(Ok(Value::TimeDelta(a / n))),
        // timedelta / timedelta -> float ratio (`timedelta(days=1) / timedelta(hours=1)` == 24.0).
        #[expect(
            clippy::cast_precision_loss,
            reason = "CPython's timedelta.__truediv__ returns the float ratio, lossy for durations \
                      beyond 2^53 microseconds just as CPython is"
        )]
        ("/", Value::TimeDelta(a), Value::TimeDelta(b)) if *b != 0 => {
            Some(Ok(Value::Float(*a as f64 / *b as f64)))
        }
        // timedelta // timedelta -> int floor ratio.
        ("//", Value::TimeDelta(a), Value::TimeDelta(b)) if *b != 0 => {
            Some(Ok(Value::Int(td_floordiv(*a, *b))))
        }
        // timedelta % timedelta -> timedelta remainder (Python floor semantics).
        ("%", Value::TimeDelta(a), Value::TimeDelta(b)) if *b != 0 => {
            Some(Ok(Value::TimeDelta(a - td_floordiv(*a, *b) * b)))
        }
        // timedelta / int -> timedelta, rounding to the nearest microsecond
        // (ties to even, matching CPython's `_divide_and_round`).
        ("/", Value::TimeDelta(a), Value::Int(n)) if *n != 0 => {
            Some(Ok(Value::TimeDelta(td_divide_and_round(*a, *n))))
        }
        _ => None,
    }
}

/// Python floor division on microsecond counts (rounds toward negative
/// infinity, unlike Rust's truncating `/`).
const fn td_floordiv(a: i64, b: i64) -> i64 {
    let q = a / b;
    let r = a % b;
    if (r != 0) && ((r < 0) != (b < 0)) { q - 1 } else { q }
}

/// CPython's `datetime._divide_and_round`: `a / b` rounded to the nearest
/// integer, ties broken toward the even neighbour.
const fn td_divide_and_round(a: i64, b: i64) -> i64 {
    let mut q = td_floordiv(a, b);
    // Remainder with the sign of `b` (Python's `divmod`), so `2*r` vs `b`
    // compares magnitudes correctly for either sign of the divisor.
    let r = a - q * b;
    let r2 = r * 2;
    let greater_than_half = if b > 0 { r2 > b } else { r2 < b };
    if greater_than_half || (r2 == b && q % 2 != 0) {
        q += 1;
    }
    q
}

/// Scale a microsecond count by a float using CPython's exact-rational
/// arithmetic: `td * f` (divide=false) or `td / f` (divide=true), rounded to
/// the nearest microsecond with ties to even. Returns `None` for a non-finite
/// float or a result outside `i64` (CPython raises `OverflowError` there).
fn td_scale_float(a: i64, f: f64, divide: bool) -> Option<i64> {
    use num_bigint::BigInt;
    use num_rational::BigRational;
    use num_traits::ToPrimitive as _;
    if !f.is_finite() {
        return None;
    }
    let frac = BigRational::from_float(f)?;
    let a_big = BigInt::from(a);
    // For `a * (num/den)` → round(a*num / den); for `a / (num/den)` →
    // round(a*den / num).
    let (numerator, denominator) = if divide {
        (&a_big * frac.denom(), frac.numer().clone())
    } else {
        (&a_big * frac.numer(), frac.denom().clone())
    };
    big_divide_and_round(&numerator, &denominator).to_i64()
}

/// BigInt port of [`td_divide_and_round`]: `a / b` rounded to the nearest
/// integer, ties to even.
fn big_divide_and_round(a: &num_bigint::BigInt, b: &num_bigint::BigInt) -> num_bigint::BigInt {
    use num_bigint::BigInt;
    use num_integer::Integer as _;
    use num_traits::{Signed as _, Zero as _};
    // Floor division (rounds toward negative infinity), matching Python divmod.
    let (mut q, r) = a.div_rem(b);
    let floored_r = if !r.is_zero() && (r.is_negative() != b.is_negative()) {
        q -= 1;
        &r + b
    } else {
        r
    };
    let r2 = &floored_r * BigInt::from(2);
    let greater_than_half = if b.is_positive() { r2 > *b } else { r2 < *b };
    if greater_than_half || (r2 == *b && q.is_odd()) {
        q += 1;
    }
    q
}

fn int_arg(value: &Value, func: &str, index: usize) -> Result<i64, EvalError> {
    match value {
        Value::Int(i) => Ok(*i),
        Value::Bool(b) => Ok(i64::from(*b)),
        _ => Err(InterpreterError::TypeError(format!(
            "{func}() expected an integer at position {index}"
        ))
        .into()),
    }
}

/// Required `i32` component from a bound slot (year), CPython range wording.
fn comp_i32(v: Option<&Value>, func: &str, name: &str) -> Result<i32, EvalError> {
    let value = v.ok_or_else(|| {
        EvalError::from(InterpreterError::TypeError(format!(
            "{func}() missing required argument '{name}'"
        )))
    })?;
    i32::try_from(int_arg(value, func, 0)?).map_err(|_| value_error("year out of range"))
}

/// Required `u32` component from a bound slot (month/day).
fn comp_u32(v: Option<&Value>, func: &str, name: &str) -> Result<u32, EvalError> {
    let value = v.ok_or_else(|| {
        EvalError::from(InterpreterError::TypeError(format!(
            "{func}() missing required argument '{name}'"
        )))
    })?;
    u32::try_from(int_arg(value, func, 0)?).map_err(|_| value_error("value out of range"))
}

/// Optional `u32` component from a bound slot; `None`/absent → `None`.
fn comp_opt_u32(v: Option<&Value>, func: &str) -> Result<Option<u32>, EvalError> {
    match v {
        None | Some(Value::None) => Ok(None),
        Some(value) => Ok(Some(
            u32::try_from(int_arg(value, func, 0)?)
                .map_err(|_| value_error("value out of range"))?,
        )),
    }
}

/// Optional `i64` component from a bound slot (timedelta parts).
fn comp_opt_i64(v: Option<&Value>) -> Result<Option<i64>, EvalError> {
    match v {
        None | Some(Value::None) => Ok(None),
        Some(value) => int_arg(value, "timedelta", 0).map(Some),
    }
}

/// Optional `i32` component from a bound slot (replace year).
fn comp_opt_i32(v: Option<&Value>) -> Result<Option<i32>, EvalError> {
    match v {
        None | Some(Value::None) => Ok(None),
        Some(value) => Ok(Some(
            i32::try_from(int_arg(value, "replace", 0)?)
                .map_err(|_| value_error("year out of range"))?,
        )),
    }
}

/// `datetime` module registration.
pub struct DatetimeModule;

#[async_trait::async_trait]
impl crate::eval::modules::Module for DatetimeModule {
    fn name(&self) -> &'static str {
        "datetime"
    }
    fn has_function(&self, name: &str) -> bool {
        has_function(name)
    }
    async fn call(
        &self,
        _state: &mut crate::state::InterpreterState,
        func: &str,
        args: &[Value],
        kwargs: &indexmap::IndexMap<String, Value>,
        _tools: &crate::tools::Tools,
    ) -> EvalResult {
        call(func, args, kwargs)
    }
}