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
// Copyright 2026 Thomas Santerre and Moderately AI Inc.
//
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Emulation of Python's `decimal` module.
//!
//! Exposes the `Decimal` class as a constructor that wraps a
//! `bigdecimal::BigDecimal`. Arithmetic is wired through the regular
//! dispatch path (Track A3 will move the actual arms there); this
//! module is the entry surface.
//!
//! Divergences from CPython documented in CONFORMANCE.md:
//!   - `getcontext()` / `setcontext()` expose a Context with mutable `prec` (default 28).
//!     Division rounds to active prec; other arithmetic stays exact.
//!   - Full Context traps/rounding modes are not modelled.
//!   - `Decimal + float` raises `TypeError`, matching CPython. `Decimal(float)` also raises
//!     `TypeError` — deliberate divergence from CPython (which accepts `Decimal(0.1)` and stores
//!     the expanded binary value); see CONFORMANCE.md#decimal-float-rejection.

use std::str::FromStr as _;

use bigdecimal::BigDecimal;

use crate::{
    error::{EvalError, EvalResult, InterpreterError},
    value::{DecimalKind, Value},
};

/// `abs(Decimal)` — infinity becomes `+Infinity`, NaN stays NaN, else `|d|`.
#[must_use]
pub fn abs_decimal(d: &BigDecimal, kind: DecimalKind) -> Value {
    match kind {
        DecimalKind::Nan => Value::Decimal(Box::new(BigDecimal::from(0)), DecimalKind::Nan),
        DecimalKind::PosInf | DecimalKind::NegInf => {
            Value::Decimal(Box::new(BigDecimal::from(0)), DecimalKind::PosInf)
        }
        _ => Value::Decimal(Box::new(d.abs()), DecimalKind::Normal),
    }
}

/// `-Decimal` — flips an infinity's sign, keeps NaN, else negates `d`.
#[must_use]
pub fn neg_decimal(d: &BigDecimal, kind: DecimalKind) -> Value {
    match kind {
        DecimalKind::Nan => Value::Decimal(Box::new(BigDecimal::from(0)), DecimalKind::Nan),
        DecimalKind::PosInf => Value::Decimal(Box::new(BigDecimal::from(0)), DecimalKind::NegInf),
        DecimalKind::NegInf => Value::Decimal(Box::new(BigDecimal::from(0)), DecimalKind::PosInf),
        _ => Value::Decimal(Box::new(-(d.clone())), DecimalKind::Normal),
    }
}

/// `copy_abs` sign for a special value: any infinity → `+Infinity`, NaN → NaN.
const fn abs_kind(kind: DecimalKind) -> DecimalKind {
    match kind {
        DecimalKind::PosInf | DecimalKind::NegInf => DecimalKind::PosInf,
        other => other,
    }
}

/// `copy_negate` sign for a special value: flip an infinity, keep NaN.
const fn neg_kind(kind: DecimalKind) -> DecimalKind {
    match kind {
        DecimalKind::PosInf => DecimalKind::NegInf,
        DecimalKind::NegInf => DecimalKind::PosInf,
        other => other,
    }
}

/// `as_tuple()` for a special value: CPython uses a string exponent (`'F'` for
/// infinity, `'n'` for NaN) with `digits=(0,)` for infinity and `()` for NaN.
fn special_as_tuple(kind: DecimalKind) -> EvalResult {
    let (sign, digits, exp): (i64, Vec<Value>, &str) = match kind {
        DecimalKind::PosInf => (0, vec![Value::Int(0)], "F"),
        DecimalKind::NegInf => (1, vec![Value::Int(0)], "F"),
        _ => (0, Vec::new(), "n"),
    };
    let mut fields = std::collections::BTreeMap::new();
    fields.insert("sign".to_string(), Value::Int(sign));
    fields.insert("digits".to_string(), Value::Tuple(digits));
    fields.insert("exponent".to_string(), Value::String(exp.into()));
    Ok(Value::Instance(crate::value::InstanceValue {
        class_name: "DecimalTuple".to_string(),
        fields: crate::value::shared_fields(fields),
    }))
}

/// Dispatch a method call on a `Decimal` receiver.
pub(crate) fn dispatch_decimal_method(
    d: &BigDecimal,
    kind: DecimalKind,
    method: &str,
    args: &[Value],
    kwargs: &indexmap::IndexMap<String, Value>,
) -> EvalResult {
    use num_traits::{Signed as _, Zero as _};
    // Special-value predicates and identities are answered from the kind, before
    // touching the placeholder BigDecimal.
    match method {
        "is_nan" => return Ok(Value::Bool(kind.is_nan())),
        "is_qnan" => return Ok(Value::Bool(kind == DecimalKind::Nan)),
        "is_snan" => return Ok(Value::Bool(false)),
        "is_infinite" => return Ok(Value::Bool(kind.is_infinite())),
        "is_finite" => return Ok(Value::Bool(!kind.is_special())),
        "is_signed" => {
            return Ok(Value::Bool(
                matches!(kind, DecimalKind::NegInf | DecimalKind::NegZero) || d.is_negative(),
            ));
        }
        _ => {}
    }
    // For any other method on a special value, propagate NaN / raise like
    // CPython rather than compute on the zero placeholder (a rare path).
    if kind.is_special() {
        return Ok(match method {
            "copy_abs" => Value::Decimal(Box::new(BigDecimal::from(0)), abs_kind(kind)),
            "copy_negate" => Value::Decimal(Box::new(BigDecimal::from(0)), neg_kind(kind)),
            "as_tuple" => return special_as_tuple(kind),
            _ if kind.is_nan() => Value::Decimal(Box::new(BigDecimal::from(0)), DecimalKind::Nan),
            // Infinity through most numeric methods is InvalidOperation in
            // CPython; mirror that rather than a wrong finite value.
            _ => {
                return Err(EvalError::Exception(crate::value::ExceptionValue::new(
                    "InvalidOperation",
                    format!("{method}() of a non-finite Decimal"),
                )));
            }
        });
    }
    match method {
        // `quantize(exp, rounding=…)` rounds to the exponent (decimal scale)
        // of `exp`. The rounding mode defaults to the context's
        // ROUND_HALF_EVEN (banker's) and may be overridden positionally or by
        // keyword with a `decimal.ROUND_*` string constant.
        "quantize" => {
            let Some(Value::Decimal(exp, _)) = args.first() else {
                return Err(InterpreterError::TypeError(
                    "quantize() requires a Decimal argument".into(),
                )
                .into());
            };
            let rounding = match args.get(1).or_else(|| kwargs.get("rounding")) {
                Some(Value::String(s)) => rounding_mode(s)?,
                Some(Value::None) | None => bigdecimal::RoundingMode::HalfEven,
                Some(other) => {
                    return Err(InterpreterError::TypeError(format!(
                        "quantize() rounding must be a decimal.ROUND_* constant, not '{}'",
                        other.type_name()
                    ))
                    .into());
                }
            };
            let scale = exp.fractional_digit_count();
            Ok(Value::Decimal(Box::new(d.with_scale_round(scale, rounding)), DecimalKind::Normal))
        }
        "copy_abs" => Ok(Value::Decimal(Box::new(d.abs()), DecimalKind::Normal)),
        "copy_negate" => Ok(Value::Decimal(Box::new(-d.clone()), DecimalKind::Normal)),
        "copy_sign" => {
            let Some(Value::Decimal(other, other_kind)) = args.first() else {
                return Err(InterpreterError::TypeError(
                    "copy_sign() requires a Decimal argument".into(),
                )
                .into());
            };
            // The sign source includes `-0`/`-Inf`, whose BigDecimal payload is a
            // signless zero — the kind carries the sign.
            let other_neg = other.is_negative()
                || matches!(other_kind, DecimalKind::NegZero | DecimalKind::NegInf);
            let magnitude = d.abs();
            Ok(Value::Decimal(
                Box::new(if other_neg { -magnitude } else { magnitude }),
                DecimalKind::Normal,
            ))
        }
        "is_zero" => Ok(Value::Bool(d.is_zero())),
        // is_nan/is_infinite/is_qnan/is_snan/is_finite/is_signed are answered
        // from the kind at the top of this function.
        "normalize" => Ok(Value::Decimal(Box::new(d.normalized()), DecimalKind::Normal)),
        // Rounded to the default context precision (28 significant digits),
        // matching CPython — bigdecimal's raw sqrt keeps ~100 digits.
        "sqrt" => {
            let r = d.sqrt().ok_or_else(|| {
                EvalError::Exception(crate::value::ExceptionValue::new(
                    "InvalidOperation",
                    "sqrt of negative Decimal",
                ))
            })?;
            // A perfect square takes the ideal exponent (operand exponent // 2)
            // rather than padding to the context's 28 significant digits, so
            // `Decimal('9').sqrt()` is `3` and `Decimal('9.00').sqrt()` is `3.0`
            // (scale = ceil(operand_scale / 2)). Inexact roots keep 28 digits.
            let exact = ((&r * &r) - d).is_zero();
            let result = if exact {
                r.with_scale((d.fractional_digit_count() + 1) / 2)
            } else {
                r.with_prec(28)
            };
            Ok(Value::Decimal(Box::new(result), DecimalKind::Normal))
        }
        // Transcendentals at the default context precision (28 significant
        // digits). `exp` is bigdecimal's; `ln`/`log10` use Newton's method on
        // `exp`. Accurate to 28 digits but — like `math.erf` — not guaranteed
        // bit-identical to CPython's correctly-rounded result in the final ULP.
        // exp(0) is exactly 1 (CPython returns the bare `1`, not `1.000…`).
        "exp" if d.is_zero() => {
            Ok(Value::Decimal(Box::new(BigDecimal::from(1)), DecimalKind::Normal))
        }
        "exp" => Ok(Value::Decimal(Box::new(d.exp().with_prec(28)), DecimalKind::Normal)),
        "ln" => {
            // ln(1) is exactly 0 (CPython returns the bare `0`, not a padded
            // 28-digit form). Every other value gives an irrational result.
            if power_of_ten_exponent(d) == Some(0) {
                Ok(Value::Decimal(Box::new(BigDecimal::from(0)), DecimalKind::Normal))
            } else {
                decimal_ln_prec(d, 45)
                    .map(|r| Value::Decimal(Box::new(r.with_prec(28)), DecimalKind::Normal))
                    .ok_or_else(|| non_positive_log_error("ln"))
            }
        }
        "log10" => {
            // log10 of an exact power of ten is the exact integer exponent
            // (CPython: `Decimal(1000).log10()` is `3`, not `3.000…`).
            if let Some(k) = power_of_ten_exponent(d) {
                Ok(Value::Decimal(Box::new(BigDecimal::from(k)), DecimalKind::Normal))
            } else {
                let ten = BigDecimal::from(10);
                match (decimal_ln_prec(d, 48), decimal_ln_prec(&ten, 48)) {
                    (Some(ln_d), Some(ln_ten)) => Ok(Value::Decimal(
                        Box::new((ln_d / ln_ten).with_prec(28)),
                        DecimalKind::Normal,
                    )),
                    _ => Err(non_positive_log_error("log10")),
                }
            }
        }
        // `compare(other)` yields Decimal(-1 / 0 / 1) (not a bare int).
        "compare" => {
            let Some(Value::Decimal(other, _)) = args.first() else {
                return Err(InterpreterError::TypeError(
                    "compare() requires a Decimal argument".into(),
                )
                .into());
            };
            let sign = match d.cmp(other) {
                std::cmp::Ordering::Less => -1,
                std::cmp::Ordering::Equal => 0,
                std::cmp::Ordering::Greater => 1,
            };
            Ok(Value::Decimal(Box::new(BigDecimal::from(sign)), DecimalKind::Normal))
        }
        // `compare_total(other)` is the IEEE total ordering: unlike `compare`,
        // equal numeric values with different exponents are ordered (`1.5` >
        // `1.50` because its exponent is larger). Yields Decimal(-1 / 0 / 1).
        "compare_total" => {
            let Some(Value::Decimal(other, other_kind)) = args.first() else {
                return Err(InterpreterError::TypeError(
                    "compare_total() requires a Decimal argument".into(),
                )
                .into());
            };
            let sign = compare_total_sign(d, kind, other, *other_kind);
            Ok(Value::Decimal(Box::new(BigDecimal::from(sign)), DecimalKind::Normal))
        }
        // `fma(other, third)` = self*other + third with a single final rounding.
        // BigDecimal is exact, so the fused product and sum carry no intermediate
        // rounding — exactly the guarantee `fma` makes.
        "fma" => {
            let (Some(Value::Decimal(other, _)), Some(Value::Decimal(third, _))) =
                (args.first(), args.get(1))
            else {
                return Err(InterpreterError::TypeError(
                    "fma() requires two Decimal arguments".into(),
                )
                .into());
            };
            let result = d.clone() * (**other).clone() + (**third).clone();
            Ok(Value::Decimal(Box::new(result), DecimalKind::Normal))
        }
        // `remainder_near(other)` = self - other*n, where n is the integer
        // nearest self/other (ties to even); the result has the smallest
        // possible magnitude (and may be negative).
        "remainder_near" => {
            let Some(Value::Decimal(other, _)) = args.first() else {
                return Err(InterpreterError::TypeError(
                    "remainder_near() requires a Decimal argument".into(),
                )
                .into());
            };
            if other.is_zero() {
                return Err(InterpreterError::ValueError(
                    "remainder_near() division by zero".into(),
                )
                .into());
            }
            let n = (d.clone() / (**other).clone())
                .with_scale_round(0, bigdecimal::RoundingMode::HalfEven);
            let result = d.clone() - (**other).clone() * n;
            Ok(Value::Decimal(Box::new(result), DecimalKind::Normal))
        }
        // `adjusted()` is the adjusted exponent: exponent + (significant digits
        // - 1). Returns a plain int (zero coefficient reports 0).
        "adjusted" => {
            let (mantissa, scale) = d.as_bigint_and_exponent();
            if mantissa.is_zero() {
                return Ok(Value::Int(0));
            }
            let digits = i64::try_from(mantissa.abs().to_string().len()).unwrap_or(i64::MAX);
            Ok(Value::Int(digits - 1 - scale))
        }
        // `scaleb(n)` shifts the decimal exponent by `n` (multiply by 10**n)
        // while preserving the coefficient, so the E-notation is retained.
        "scaleb" => {
            let n = match args.first() {
                Some(Value::Int(i)) => *i,
                Some(Value::Decimal(dec, _)) => {
                    use num_traits::ToPrimitive as _;
                    dec.to_i64().unwrap_or(0)
                }
                _ => {
                    return Err(InterpreterError::TypeError(
                        "scaleb() requires an integer or Decimal argument".into(),
                    )
                    .into());
                }
            };
            let (mantissa, scale) = d.as_bigint_and_exponent();
            Ok(Value::Decimal(Box::new(BigDecimal::new(mantissa, scale - n)), DecimalKind::Normal))
        }
        "to_integral_value" | "to_integral" => {
            // Optional `rounding=ROUND_*`; defaults to the context (HalfEven).
            let rounding = match args.first().or_else(|| kwargs.get("rounding")) {
                Some(Value::String(s)) => rounding_mode(s)?,
                _ => bigdecimal::RoundingMode::HalfEven,
            };
            Ok(Value::Decimal(Box::new(d.with_scale_round(0, rounding)), DecimalKind::Normal))
        }
        "as_integer_ratio" => {
            let (mantissa, scale) = d.as_bigint_and_exponent();
            let (num, den) = if scale >= 0 {
                (mantissa, num_bigint::BigInt::from(10).pow(u32::try_from(scale).unwrap_or(0)))
            } else {
                (
                    mantissa * num_bigint::BigInt::from(10).pow(u32::try_from(-scale).unwrap_or(0)),
                    num_bigint::BigInt::from(1),
                )
            };
            // CPython returns a plain `(numerator, denominator)` int tuple in
            // lowest terms, not a Fraction. `BigRational::new` reduces for us.
            let ratio = num_rational::BigRational::new(num, den);
            Ok(Value::Tuple(vec![
                crate::value::int_from_bigint(ratio.numer().clone()),
                crate::value::int_from_bigint(ratio.denom().clone()),
            ]))
        }
        // `as_tuple()` -> DecimalTuple(sign, digits, exponent): value ==
        // (-1)^sign * digits * 10^exponent, with trailing zeros preserved
        // (`Decimal('1.00')` -> digits (1, 0, 0), exponent -2). Signless zero
        // reports sign 0 — the `-0.0` case cannot be recovered from the bare
        // BigDecimal here, matching `is_signed`/`copy_sign`.
        "as_tuple" => {
            let (mantissa, scale) = d.as_bigint_and_exponent();
            let sign = i64::from(mantissa.is_negative());
            let digits: Vec<Value> = mantissa
                .abs()
                .to_string()
                .bytes()
                .map(|b| Value::Int(i64::from(b - b'0')))
                .collect();
            let mut fields = std::collections::BTreeMap::new();
            fields.insert("sign".to_string(), Value::Int(sign));
            fields.insert("digits".to_string(), Value::Tuple(digits));
            fields.insert("exponent".to_string(), Value::Int(-scale));
            Ok(Value::Instance(crate::value::InstanceValue {
                class_name: "DecimalTuple".to_string(),
                fields: crate::value::shared_fields(fields),
            }))
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "'Decimal' object has no attribute '{method}'"
        ))
        .into()),
    }
}

/// `InvalidOperation` for `ln`/`log10` of a value that is not strictly
/// positive, matching CPython's error class.
/// IEEE 754 total ordering of two Decimals (the `compare_total` result as
/// -1/0/1). `self` is always finite here (special kinds return earlier); a
/// special `other` is ranked: finite sorts below +Inf/NaN and above -Inf. For
/// two finite operands the numeric order decides, and equal numeric values are
/// broken by exponent (larger exponent is greater when positive, smaller when
/// negative), so `1.5` > `1.50`.
fn compare_total_sign(
    a: &BigDecimal,
    a_kind: DecimalKind,
    b: &BigDecimal,
    b_kind: DecimalKind,
) -> i64 {
    use num_traits::Signed as _;
    match b_kind {
        DecimalKind::Nan | DecimalKind::PosInf => -1,
        DecimalKind::NegInf => 1,
        DecimalKind::Normal | DecimalKind::NegZero => {
            let a_neg = a.is_negative() || matches!(a_kind, DecimalKind::NegZero);
            let b_neg = b.is_negative() || matches!(b_kind, DecimalKind::NegZero);
            if a_neg != b_neg {
                return if a_neg { -1 } else { 1 };
            }
            match a.cmp(b) {
                std::cmp::Ordering::Less => -1,
                std::cmp::Ordering::Greater => 1,
                std::cmp::Ordering::Equal => {
                    let a_exp = -a.as_bigint_and_exponent().1;
                    let b_exp = -b.as_bigint_and_exponent().1;
                    let base = match a_exp.cmp(&b_exp) {
                        std::cmp::Ordering::Less => -1,
                        std::cmp::Ordering::Greater => 1,
                        std::cmp::Ordering::Equal => 0,
                    };
                    if a_neg { -base } else { base }
                }
            }
        }
    }
}

fn non_positive_log_error(op: &str) -> EvalError {
    EvalError::Exception(crate::value::ExceptionValue::new(
        "InvalidOperation",
        format!("{op} of a non-positive value"),
    ))
}

/// If `d` is an exact power of ten (`10**k`), return `k`; else `None`. Used to
/// short-circuit `log10` (and `ln(1)`) to an exact integer result, matching
/// CPython's special-casing.
fn power_of_ten_exponent(d: &BigDecimal) -> Option<i64> {
    let (mantissa, scale) = d.normalized().into_bigint_and_exponent();
    (mantissa == num_bigint::BigInt::from(1)).then_some(-scale)
}

/// Natural logarithm of a positive `BigDecimal`, computed to `guard`
/// significant digits by Newton's method on `exp`
/// (`y ← y + d/exp(y) − 1`, which solves `exp(y) = d`). Quadratically
/// convergent from an `f64` seed. Returns `None` for a non-positive input.
/// The result carries `guard` digits so callers can round to the context
/// precision (or divide, for `log10`) without compounding rounding error.
fn decimal_ln_prec(d: &BigDecimal, guard: u64) -> Option<BigDecimal> {
    use num_traits::{FromPrimitive as _, Signed as _, ToPrimitive as _};
    if !d.is_positive() {
        return None;
    }
    let one = BigDecimal::from(1);
    let mut y = BigDecimal::from_f64(d.to_f64()?.ln())?;
    // Newton converges quadratically; from ~15 f64 digits, a handful of
    // iterations reaches `guard`. Cap the loop as a safety bound.
    for _ in 0..40 {
        let ey = y.exp().with_prec(guard);
        let ratio = (d / &ey).with_prec(guard);
        let correction = (ratio - &one).with_prec(guard);
        let y_next = (&y + &correction).with_prec(guard);
        if y_next == y {
            break;
        }
        y = y_next;
    }
    Some(y)
}

pub const CONTEXT_CLASS: &str = "decimal.Context";
/// Marker class for `with localcontext() as ctx:`.
pub const LOCAL_CONTEXT_CLASS: &str = "decimal.LocalContext";

pub fn has_function(name: &str) -> bool {
    // from_float is a Decimal classmethod only (type_classmethod), not a
    // module-level import.
    matches!(name, "Decimal" | "getcontext" | "setcontext" | "localcontext" | "Context")
}

/// Classmethods on `decimal.Decimal`.
#[must_use]
pub fn type_classmethod(type_name: &str, method: &str) -> Option<&'static str> {
    match (type_name, method) {
        ("Decimal", "from_float") => Some("from_float"),
        _ => None,
    }
}

pub fn call(func: &str, args: &[Value], state: &mut crate::state::InterpreterState) -> EvalResult {
    match func {
        "Decimal" => construct_decimal(args.first()),
        "getcontext" => Ok(make_context_instance(state)),
        "localcontext" => {
            ensure_context_class(state);
            // Optional Context arg: if provided, its prec is applied on enter.
            let mut fields = std::collections::BTreeMap::new();
            fields.insert("saved_prec".into(), Value::Int(state.decimal_prec));
            if let Some(Value::Instance(inst)) = args.first() {
                if inst.class_name == CONTEXT_CLASS {
                    if let Some(Value::Int(n)) = inst.fields.lock().get("prec") {
                        fields.insert("enter_prec".into(), Value::Int(*n));
                    }
                }
            }
            // Also expose a nested Context for `as ctx` that mutates state.
            fields.insert("ctx".into(), make_context_instance(state));
            Ok(Value::Instance(crate::value::InstanceValue {
                class_name: LOCAL_CONTEXT_CLASS.into(),
                fields: crate::value::shared_fields(fields),
            }))
        }
        "setcontext" => {
            let Some(Value::Instance(inst)) = args.first() else {
                return Err(InterpreterError::TypeError(
                    "setcontext() argument must be a Context".into(),
                )
                .into());
            };
            if inst.class_name != CONTEXT_CLASS {
                return Err(InterpreterError::TypeError(
                    "setcontext() argument must be a Context".into(),
                )
                .into());
            }
            if let Some(Value::Int(n)) = inst.fields.lock().get("prec") {
                if *n < 1 {
                    return Err(InterpreterError::ValueError(
                        "valid range for prec is [1, MAX_PREC]".into(),
                    )
                    .into());
                }
                state.decimal_prec = *n;
            }
            Ok(Value::None)
        }
        // CPython: Decimal.from_float(0.1) — explicit opt-in to the binary expansion.
        "from_float" => {
            let Some(Value::Float(f)) = args.first() else {
                return Err(InterpreterError::TypeError(
                    "from_float() argument must be a float".into(),
                )
                .into());
            };
            // BigDecimal::try_from(f64) uses exact conversion of the binary value.
            let big = BigDecimal::try_from(*f).map_err(|_| {
                InterpreterError::ValueError(format!("cannot convert float {f} to Decimal"))
            })?;
            Ok(Value::Decimal(Box::new(big), DecimalKind::Normal))
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "module 'decimal' has no attribute '{func}'"
        ))
        .into()),
    }
}

/// `decimal.Decimal(x)` — accepts an int, a string with the exact
/// digit representation, or another Decimal. `Decimal(float)` raises
/// `TypeError`; this is a **deliberate divergence** from CPython, which
/// accepts `Decimal(0.1)` and constructs the exact expanded binary
/// representation (`Decimal('0.1000000000000000055511151231257827021181583404541015625')`).
/// We reject because that expanded value almost never matches the
/// source literal the user typed. See
/// CONFORMANCE.md#decimal-float-rejection for the full divergence note.
pub(crate) fn construct_decimal(arg: Option<&Value>) -> EvalResult {
    let Some(arg) = arg else {
        return Err(InterpreterError::TypeError(
            "Decimal() requires a value (int, str, or Decimal)".into(),
        )
        .into());
    };
    // `DecimalKind` carries what `bigdecimal` can't: the sign of a zero
    // (`Decimal('-0.0')` prints `-0.0`) and the special values inf/nan.
    let (big, kind) = match arg {
        Value::Int(i) => (BigDecimal::from(*i), DecimalKind::Normal),
        Value::Bool(b) => (BigDecimal::from(i64::from(*b)), DecimalKind::Normal),
        Value::String(s) => {
            use num_traits::Zero as _;
            let trimmed = s.trim();
            // Special values are case-insensitive with an optional sign:
            // `inf`/`infinity`/`nan`/`snan` (CPython also accepts `Infinity`).
            let lower = trimmed.to_ascii_lowercase();
            let (neg, body) = lower.strip_prefix('-').map_or_else(
                || (false, lower.strip_prefix('+').unwrap_or(lower.as_str())),
                |rest| (true, rest),
            );
            if body == "inf" || body == "infinity" {
                let kind = if neg { DecimalKind::NegInf } else { DecimalKind::PosInf };
                (BigDecimal::from(0), kind)
            } else if body == "nan" || body == "snan" {
                (BigDecimal::from(0), DecimalKind::Nan)
            } else {
                let bd = BigDecimal::from_str(trimmed).map_err(|e| {
                    EvalError::from(InterpreterError::ValueError(format!(
                        "invalid Decimal literal: {s:?} ({e})"
                    )))
                })?;
                let kind = if bd.is_zero() && trimmed.starts_with('-') {
                    DecimalKind::NegZero
                } else {
                    DecimalKind::Normal
                };
                (bd, kind)
            }
        }
        Value::Decimal(d, k) => ((**d).clone(), *k),
        Value::Float(_) => {
            return Err(InterpreterError::TypeError(
                "Decimal() does not accept float — use a string instead (see \
                 CONFORMANCE.md#decimal-float-rejection)"
                    .into(),
            )
            .into());
        }
        other => {
            return Err(InterpreterError::TypeError(format!(
                "Decimal() expects int / str / Decimal, got '{}'",
                other.type_name()
            ))
            .into());
        }
    };
    Ok(Value::Decimal(Box::new(big), kind))
}

fn make_context_instance(state: &mut crate::state::InterpreterState) -> Value {
    ensure_context_class(state);
    let mut fields = std::collections::BTreeMap::new();
    fields.insert("prec".into(), Value::Int(state.decimal_prec));
    // rounding accepted for read/write; only ROUND_HALF_EVEN is effective today.
    fields.insert("rounding".into(), Value::String("ROUND_HALF_EVEN".into()));
    Value::Instance(crate::value::InstanceValue {
        class_name: CONTEXT_CLASS.into(),
        fields: crate::value::shared_fields(fields),
    })
}

/// `with localcontext() as ctx` enter/exit special-case (saves/restores prec).
pub(crate) fn try_localcontext_method(
    state: &mut crate::state::InterpreterState,
    receiver: &Value,
    method: &str,
    _args: &[Value],
) -> Option<EvalResult> {
    let Value::Instance(inst) = receiver else {
        return None;
    };
    if inst.class_name != LOCAL_CONTEXT_CLASS {
        return None;
    }
    match method {
        "__enter__" => {
            let fields = inst.fields.lock();
            if let Some(Value::Int(n)) = fields.get("enter_prec") {
                if *n >= 1 {
                    state.decimal_prec = *n;
                }
            }
            // Return the nested Context instance for `as ctx`.
            let ctx = fields.get("ctx").cloned().unwrap_or(Value::None);
            // Refresh ctx.prec to current state.
            drop(fields);
            if let Value::Instance(ctx_inst) = &ctx {
                ctx_inst.fields.lock().insert("prec".into(), Value::Int(state.decimal_prec));
            }
            Some(Ok(ctx))
        }
        "__exit__" => {
            let fields = inst.fields.lock();
            if let Some(Value::Int(n)) = fields.get("saved_prec") {
                state.decimal_prec = *n;
            }
            Some(Ok(Value::Bool(false)))
        }
        _ => Some(Err(InterpreterError::AttributeError(format!(
            "'LocalContext' object has no attribute '{method}'"
        ))
        .into())),
    }
}

fn ensure_context_class(state: &mut crate::state::InterpreterState) {
    use crate::value::ClassValue;
    if !state.classes.contains_key(CONTEXT_CLASS) {
        state.classes.insert(CONTEXT_CLASS.to_string(), ClassValue::new(CONTEXT_CLASS));
    }
    if !state.classes.contains_key(LOCAL_CONTEXT_CLASS) {
        state.classes.insert(LOCAL_CONTEXT_CLASS.to_string(), ClassValue::new(LOCAL_CONTEXT_CLASS));
    }
}

/// `decimal` module registration.
pub struct DecimalModule;

#[async_trait::async_trait]
impl crate::eval::modules::Module for DecimalModule {
    fn name(&self) -> &'static str {
        "decimal"
    }
    fn has_function(&self, name: &str) -> bool {
        has_function(name)
    }
    fn constant(&self, name: &str) -> Option<Value> {
        // The module's exception types, usable in `except decimal.InvalidOperation`
        // and importable via `from decimal import ...`. Their raised type names
        // match these, and every one is an `ArithmeticError` subclass.
        if matches!(
            name,
            "InvalidOperation"
                | "DivisionByZero"
                | "Overflow"
                | "Underflow"
                | "Inexact"
                | "Rounded"
                | "Subnormal"
                | "Clamped"
                | "FloatOperation"
                | "DecimalException"
        ) {
            return Some(Value::ExceptionType(name.to_string()));
        }
        rounding_constant(name)
    }
    async fn call(
        &self,
        state: &mut crate::state::InterpreterState,
        func: &str,
        args: &[Value],
        kwargs: &indexmap::IndexMap<String, Value>,
        _tools: &crate::tools::Tools,
    ) -> EvalResult {
        // `Context(prec=…, rounding=…)` builds a fresh context instance carrying
        // the requested precision (used with `localcontext(ctx)` / `setcontext`).
        if func == "Context" {
            ensure_context_class(state);
            let ctx = make_context_instance(state);
            if let (Value::Instance(inst), Some(Value::Int(prec))) = (&ctx, kwargs.get("prec")) {
                inst.fields.lock().insert("prec".into(), Value::Int(*prec));
            }
            return Ok(ctx);
        }
        call(func, args, state)
    }
}

/// The `decimal` rounding-mode constants. CPython models each as a string
/// equal to its own name (`decimal.ROUND_HALF_UP == 'ROUND_HALF_UP'`), so
/// `quantize(exp, rounding=ROUND_HALF_UP)` receives the mode as a string.
/// Map a `decimal.ROUND_*` string constant to a `bigdecimal` rounding mode.
/// `ROUND_05UP` (round to nearest 0/5) has no `bigdecimal` equivalent and is
/// approximated by round-away-from-zero — a documented rare-mode divergence.
fn rounding_mode(name: &str) -> Result<bigdecimal::RoundingMode, EvalError> {
    use bigdecimal::RoundingMode;
    Ok(match name {
        "ROUND_CEILING" => RoundingMode::Ceiling,
        "ROUND_DOWN" => RoundingMode::Down,
        "ROUND_FLOOR" => RoundingMode::Floor,
        "ROUND_HALF_DOWN" => RoundingMode::HalfDown,
        "ROUND_HALF_EVEN" => RoundingMode::HalfEven,
        "ROUND_HALF_UP" => RoundingMode::HalfUp,
        "ROUND_UP" | "ROUND_05UP" => RoundingMode::Up,
        _ => {
            return Err(
                InterpreterError::ValueError(format!("invalid rounding mode: {name}")).into()
            );
        }
    })
}

pub(crate) fn rounding_constant(name: &str) -> Option<Value> {
    matches!(
        name,
        "ROUND_CEILING"
            | "ROUND_DOWN"
            | "ROUND_FLOOR"
            | "ROUND_HALF_DOWN"
            | "ROUND_HALF_EVEN"
            | "ROUND_HALF_UP"
            | "ROUND_UP"
            | "ROUND_05UP"
    )
    .then(|| Value::String(name.into()))
}