harn-vm 0.8.167

Async bytecode virtual machine for the Harn programming language
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
use std::sync::Arc;

use crate::stdlib::macros::{harn_builtin, VmBuiltinDef};
use crate::value::{VmError, VmRange, VmRngHandle, VmValue};
use crate::vm::Vm;
use parking_lot::Mutex;

pub(crate) fn register_math_builtins(vm: &mut Vm) {
    for def in MODULE_BUILTINS {
        vm.register_builtin_def(def);
    }

    vm.set_global("pi", VmValue::Float(std::f64::consts::PI));
    vm.set_global("e", VmValue::Float(std::f64::consts::E));
}

#[harn_builtin(sig = "abs(value: number) -> number", category = "math")]
fn abs_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    match args.first().unwrap_or(&VmValue::Nil) {
        VmValue::Int(i64::MIN) => Ok(VmValue::Float(9_223_372_036_854_775_808.0)),
        VmValue::Int(n) => Ok(VmValue::Int(n.abs())),
        VmValue::Float(n) => Ok(VmValue::Float(n.abs())),
        _ => Ok(VmValue::Nil),
    }
}

#[harn_builtin(sig = "min(...args: any) -> any", category = "math")]
fn min_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    if args.len() >= 2 {
        match (&args[0], &args[1]) {
            (VmValue::Int(x), VmValue::Int(y)) => Ok(VmValue::Int(*x.min(y))),
            (VmValue::Float(x), VmValue::Float(y)) => Ok(VmValue::Float(x.min(*y))),
            (VmValue::Int(x), VmValue::Float(y)) => Ok(VmValue::Float((*x as f64).min(*y))),
            (VmValue::Float(x), VmValue::Int(y)) => Ok(VmValue::Float(x.min(*y as f64))),
            (VmValue::Decimal(x), VmValue::Decimal(y)) => Ok(VmValue::decimal((**x).min(**y))),
            _ => Ok(VmValue::Nil),
        }
    } else {
        Ok(VmValue::Nil)
    }
}

#[harn_builtin(sig = "max(...args: any) -> any", category = "math")]
fn max_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    if args.len() >= 2 {
        match (&args[0], &args[1]) {
            (VmValue::Int(x), VmValue::Int(y)) => Ok(VmValue::Int(*x.max(y))),
            (VmValue::Float(x), VmValue::Float(y)) => Ok(VmValue::Float(x.max(*y))),
            (VmValue::Int(x), VmValue::Float(y)) => Ok(VmValue::Float((*x as f64).max(*y))),
            (VmValue::Float(x), VmValue::Int(y)) => Ok(VmValue::Float(x.max(*y as f64))),
            (VmValue::Decimal(x), VmValue::Decimal(y)) => Ok(VmValue::decimal((**x).max(**y))),
            _ => Ok(VmValue::Nil),
        }
    } else {
        Ok(VmValue::Nil)
    }
}

#[harn_builtin(sig = "floor(value: number) -> int", category = "math")]
fn floor_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    match args.first().unwrap_or(&VmValue::Nil) {
        VmValue::Float(n) => finite_float_to_i64(n.floor()).map(VmValue::Int),
        VmValue::Int(n) => Ok(VmValue::Int(*n)),
        _ => Ok(VmValue::Nil),
    }
}

#[harn_builtin(sig = "ceil(value: number) -> int", category = "math")]
fn ceil_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    match args.first().unwrap_or(&VmValue::Nil) {
        VmValue::Float(n) => finite_float_to_i64(n.ceil()).map(VmValue::Int),
        VmValue::Int(n) => Ok(VmValue::Int(*n)),
        _ => Ok(VmValue::Nil),
    }
}

#[harn_builtin(
    sig = "round(value: number | decimal, digits?: int) -> number | decimal",
    category = "math"
)]
fn round_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let digits = match args.get(1) {
        None | Some(VmValue::Nil) => None,
        Some(VmValue::Int(d)) => Some(*d),
        Some(other) => {
            return Err(VmError::TypeError(format!(
                "round(value, digits): digits must be an integer, got {}",
                other.type_name()
            )))
        }
    };
    match (args.first().unwrap_or(&VmValue::Nil), digits) {
        // 1-arg form: nearest integer, halves away from zero.
        (VmValue::Float(n), None) => finite_float_to_i64(n.round()).map(VmValue::Int),
        (VmValue::Int(n), None) => Ok(VmValue::Int(*n)),
        // Round to a whole-unit decimal (stays exact + keeps the decimal type),
        // rather than collapsing money to an int. Note: decimal keeps
        // rust_decimal's banker's rounding for the whole-unit form.
        (VmValue::Decimal(d), None) => Ok(VmValue::decimal(d.round())),
        // 2-arg form: round to `digits` decimal places (negative digits round
        // to tens / hundreds / ...). Floats stay floats and keep the 1-arg
        // half-away-from-zero midpoint rule; ints stay ints when possible.
        (VmValue::Float(n), Some(d)) => Ok(VmValue::Float(round_float_to_digits(*n, d))),
        (VmValue::Int(n), Some(d)) => Ok(round_int_to_digits(*n, d)),
        (VmValue::Decimal(x), Some(d)) => Ok(VmValue::decimal(round_decimal_to_digits(**x, d))),
        _ => Ok(VmValue::Nil),
    }
}

/// `round(x, digits)` for floats: half-away-from-zero at the requested
/// decimal place, implemented by scale → `f64::round` → unscale. Non-finite
/// inputs pass through unchanged.
fn round_float_to_digits(x: f64, digits: i64) -> f64 {
    if !x.is_finite() {
        return x;
    }
    if digits == 0 {
        return x.round();
    }
    // f64 decimal exponents span roughly ±308; beyond that the scale factor
    // is not representable, and the answer is degenerate anyway: rounding to
    // more fractional digits than the value resolves is the identity, and
    // rounding to a coarser bucket than the largest float magnitude is zero.
    if digits > 308 {
        return x;
    }
    if digits < -308 {
        return 0.0 * x.signum();
    }
    let factor = 10f64.powi(digits as i32);
    let scaled = x * factor;
    if !scaled.is_finite() {
        // Scaling overflowed (huge value, large positive `digits`): every
        // such value is already integral well past `digits` places.
        return x;
    }
    scaled.round() / factor
}

/// `round(n, digits)` for ints: identity for `digits >= 0`; negative digits
/// round to the nearest power-of-ten bucket, halves away from zero. Uses
/// exact i128 arithmetic; a result outside the i64 range promotes to float,
/// matching integer arithmetic overflow behavior elsewhere.
fn round_int_to_digits(n: i64, digits: i64) -> VmValue {
    if digits >= 0 || n == 0 {
        return VmValue::Int(n);
    }
    if digits <= -19 {
        // 10^19 exceeds i64::MAX, so every i64 rounds to the zero bucket.
        return VmValue::Int(0);
    }
    let factor = 10i128.pow((-digits) as u32);
    let n128 = n as i128;
    let rem = n128 % factor;
    let base = n128 - rem;
    let rounded = if rem.abs() * 2 >= factor {
        base + factor * n128.signum()
    } else {
        base
    };
    match i64::try_from(rounded) {
        Ok(v) => VmValue::Int(v),
        Err(_) => VmValue::Float(rounded as f64),
    }
}

/// `round(d, digits)` for decimals: keeps the decimal type and rust_decimal's
/// banker's (midpoint-nearest-even) rounding, consistent with the 1-arg
/// `round(decimal)` form. Negative digits round to power-of-ten buckets via
/// exact scale/unscale.
fn round_decimal_to_digits(x: rust_decimal::Decimal, digits: i64) -> rust_decimal::Decimal {
    use rust_decimal::Decimal;
    if digits >= 0 {
        // Decimal carries at most 28 fractional digits, so any larger request
        // is the identity; `round_dp` already treats it that way.
        let dp = u32::try_from(digits).unwrap_or(u32::MAX).min(28);
        return x.round_dp(dp);
    }
    let neg = (-digits) as u32;
    // 96-bit decimals top out just under 8e28, so any coarser bucket is zero.
    if neg > 28 {
        return Decimal::ZERO;
    }
    let factor = Decimal::from_i128_with_scale(10i128.pow(neg), 0);
    match x.checked_div(factor).map(|scaled| scaled.round()) {
        Some(rounded) => rounded.checked_mul(factor).unwrap_or(x),
        None => x,
    }
}

#[harn_builtin(sig = "sqrt(...args: any) -> any", category = "math")]
fn sqrt_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    match args.first().unwrap_or(&VmValue::Nil) {
        VmValue::Float(n) => Ok(VmValue::Float(n.sqrt())),
        VmValue::Int(n) => Ok(VmValue::Float((*n as f64).sqrt())),
        // No exact decimal square root; refuse rather than silently return nil.
        VmValue::Decimal(_) => Err(decimal_not_supported("sqrt")),
        _ => Ok(VmValue::Nil),
    }
}

#[harn_builtin(sig = "pow(...args: any) -> any", category = "math")]
fn pow_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    if args.len() >= 2 {
        match (&args[0], &args[1]) {
            (VmValue::Int(base), VmValue::Int(exp)) => {
                if u32::try_from(*exp).is_ok() {
                    match base.checked_pow(*exp as u32) {
                        Some(value) => Ok(VmValue::Int(value)),
                        None => Ok(VmValue::Float((*base as f64).powf(*exp as f64))),
                    }
                } else {
                    Ok(VmValue::Float((*base as f64).powf(*exp as f64)))
                }
            }
            (VmValue::Float(base), VmValue::Int(exp)) => {
                if i32::try_from(*exp).is_ok() {
                    Ok(VmValue::Float(base.powi(*exp as i32)))
                } else {
                    Ok(VmValue::Float(base.powf(*exp as f64)))
                }
            }
            (VmValue::Int(base), VmValue::Float(exp)) => {
                Ok(VmValue::Float((*base as f64).powf(*exp)))
            }
            (VmValue::Float(base), VmValue::Float(exp)) => Ok(VmValue::Float(base.powf(*exp))),
            // No exact decimal exponentiation; refuse rather than return nil.
            (VmValue::Decimal(_), _) | (_, VmValue::Decimal(_)) => {
                Err(decimal_not_supported("pow"))
            }
            _ => Ok(VmValue::Nil),
        }
    } else {
        Ok(VmValue::Nil)
    }
}

#[harn_builtin(sig = "rng_seed(...args: any) -> any", category = "math")]
fn rng_seed_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    use rand::SeedableRng;
    let seed = args
        .first()
        .and_then(|arg| arg.as_int())
        .ok_or_else(|| VmError::TypeError("rng_seed(seed): seed must be an integer".to_string()))?;
    Ok(VmValue::rng(VmRngHandle {
        rng: Arc::new(Mutex::new(rand::rngs::StdRng::seed_from_u64(seed as u64))),
    }))
}

#[harn_builtin(sig = "random(...args: any) -> float", category = "math")]
fn random_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    use rand::RngExt;
    let val: f64 = if let Some(VmValue::Rng(handle)) = args.first() {
        handle.rng.lock().random()
    } else {
        rand::rng().random()
    };
    Ok(VmValue::Float(val))
}

#[harn_builtin(sig = "random_int(...args: any) -> any", category = "math")]
fn random_int_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    use rand::RngExt;
    let (rng, min_idx) = match args.first() {
        Some(VmValue::Rng(handle)) => (Some(handle), 1),
        _ => (None, 0),
    };
    if args.len() >= min_idx + 2 {
        let min = args[min_idx]
            .as_int()
            .ok_or_else(|| VmError::TypeError("random_int: min must be an integer".to_string()))?;
        let max = args[min_idx + 1]
            .as_int()
            .ok_or_else(|| VmError::TypeError("random_int: max must be an integer".to_string()))?;
        if min > max {
            return Ok(VmValue::Nil);
        }
        let val = if let Some(handle) = rng {
            handle.rng.lock().random_range(min..=max)
        } else {
            rand::rng().random_range(min..=max)
        };
        return Ok(VmValue::Int(val));
    }
    Ok(VmValue::Nil)
}

#[harn_builtin(sig = "random_choice(...args: any) -> any", category = "math")]
fn random_choice_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    use rand::RngExt;
    let (rng, list_idx) = match args.first() {
        Some(VmValue::Rng(handle)) => (Some(handle), 1),
        _ => (None, 0),
    };
    let Some(VmValue::List(items)) = args.get(list_idx) else {
        return Ok(VmValue::Nil);
    };
    if items.is_empty() {
        return Ok(VmValue::Nil);
    }
    let idx = if let Some(handle) = rng {
        handle.rng.lock().random_range(0..items.len())
    } else {
        rand::rng().random_range(0..items.len())
    };
    Ok(items[idx].clone())
}

#[harn_builtin(sig = "random_shuffle(...args: any) -> list", category = "math")]
fn random_shuffle_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    use rand::seq::SliceRandom;
    let (rng, list_idx) = match args.first() {
        Some(VmValue::Rng(handle)) => (Some(handle), 1),
        _ => (None, 0),
    };
    let Some(VmValue::List(items)) = args.get(list_idx) else {
        return Ok(VmValue::Nil);
    };
    let mut shuffled = items.as_ref().clone();
    if let Some(handle) = rng {
        shuffled.shuffle(&mut *handle.rng.lock());
    } else {
        shuffled.shuffle(&mut rand::rng());
    }
    Ok(VmValue::List(std::sync::Arc::new(shuffled)))
}

#[harn_builtin(sig = "mean(...args: any) -> float", category = "math")]
fn mean_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let values = numeric_list_arg(args, "mean")?;
    if values.is_empty() {
        return Ok(VmValue::Float(0.0));
    }
    Ok(VmValue::Float(
        values.iter().sum::<f64>() / values.len() as f64,
    ))
}

#[harn_builtin(sig = "median(...args: any) -> float", category = "math")]
fn median_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let mut values = non_empty_numeric_list_arg(args, "median")?;
    values.sort_by(|a, b| a.total_cmp(b));
    let mid = values.len() / 2;
    if values.len() % 2 == 1 {
        Ok(VmValue::Float(values[mid]))
    } else {
        Ok(VmValue::Float(f64::midpoint(values[mid - 1], values[mid])))
    }
}

#[harn_builtin(sig = "percentile(...args: any) -> float", category = "math")]
fn percentile_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let mut values = non_empty_numeric_list_arg(args, "percentile")?;
    let p = number_arg(args.get(1), "percentile")?;
    if !(0.0..=100.0).contains(&p) {
        return Err(VmError::Runtime(
            "percentile must be between 0 and 100".to_string(),
        ));
    }
    values.sort_by(|a, b| a.total_cmp(b));
    if values.len() == 1 {
        return Ok(VmValue::Float(values[0]));
    }
    let h = 1.0 + (values.len() as f64 - 1.0) * (p / 100.0);
    let lower = h.floor();
    let upper = h.ceil();
    if lower == upper {
        return Ok(VmValue::Float(values[lower as usize - 1]));
    }
    let weight = h - lower;
    let lo = values[lower as usize - 1];
    let hi = values[upper as usize - 1];
    Ok(VmValue::Float(lo + weight * (hi - lo)))
}

#[harn_builtin(sig = "variance(...args: any) -> float", category = "math")]
fn variance_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let values = non_empty_numeric_list_arg(args, "variance")?;
    let sample = args.get(1).is_some_and(VmValue::is_truthy);
    Ok(VmValue::Float(variance_for(&values, sample, "variance")?))
}

#[harn_builtin(sig = "stddev(...args: any) -> float", category = "math")]
fn stddev_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let values = non_empty_numeric_list_arg(args, "stddev")?;
    let sample = args.get(1).is_some_and(VmValue::is_truthy);
    Ok(VmValue::Float(
        variance_for(&values, sample, "stddev")?.sqrt(),
    ))
}

#[harn_builtin(sig = "sin(...args: any) -> float", category = "math")]
fn sin_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    unary_float(args, f64::sin)
}

#[harn_builtin(sig = "cos(value: number) -> float", category = "math")]
fn cos_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    unary_float(args, f64::cos)
}

#[harn_builtin(sig = "tan(...args: any) -> float", category = "math")]
fn tan_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    unary_float(args, f64::tan)
}

#[harn_builtin(sig = "asin(value: number) -> float", category = "math")]
fn asin_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    unary_float(args, f64::asin)
}

#[harn_builtin(sig = "acos(value: number) -> float", category = "math")]
fn acos_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    unary_float(args, f64::acos)
}

#[harn_builtin(sig = "atan(value: number) -> float", category = "math")]
fn atan_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    unary_float(args, f64::atan)
}

#[harn_builtin(sig = "log2(value: number) -> float", category = "math")]
fn log2_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    unary_float(args, f64::log2)
}

#[harn_builtin(sig = "log10(value: number) -> float", category = "math")]
fn log10_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    unary_float(args, f64::log10)
}

#[harn_builtin(sig = "ln(value: number) -> float", category = "math")]
fn ln_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    unary_float(args, f64::ln)
}

#[harn_builtin(sig = "exp(value: number) -> float", category = "math")]
fn exp_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    unary_float(args, f64::exp)
}

#[harn_builtin(sig = "atan2(y: number, x: number) -> float", category = "math")]
fn atan2_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    if args.len() >= 2 {
        let y = match &args[0] {
            VmValue::Float(n) => *n,
            VmValue::Int(n) => *n as f64,
            _ => return Ok(VmValue::Nil),
        };
        let x = match &args[1] {
            VmValue::Float(n) => *n,
            VmValue::Int(n) => *n as f64,
            _ => return Ok(VmValue::Nil),
        };
        Ok(VmValue::Float(y.atan2(x)))
    } else {
        Ok(VmValue::Nil)
    }
}

#[harn_builtin(sig = "sign(...args: any) -> int", category = "math")]
fn sign_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    match args.first().unwrap_or(&VmValue::Nil) {
        VmValue::Int(n) => Ok(VmValue::Int(n.signum())),
        VmValue::Float(n) => {
            if n.is_nan() {
                Ok(VmValue::Float(f64::NAN))
            } else if *n == 0.0 {
                Ok(VmValue::Int(0))
            } else if *n > 0.0 {
                Ok(VmValue::Int(1))
            } else {
                Ok(VmValue::Int(-1))
            }
        }
        VmValue::Decimal(d) => Ok(VmValue::Int(
            match (**d).cmp(&rust_decimal::Decimal::ZERO) {
                std::cmp::Ordering::Less => -1,
                std::cmp::Ordering::Equal => 0,
                std::cmp::Ordering::Greater => 1,
            },
        )),
        _ => Ok(VmValue::Nil),
    }
}

#[harn_builtin(sig = "is_nan(value: number) -> bool", category = "math")]
fn is_nan_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    match args.first().unwrap_or(&VmValue::Nil) {
        VmValue::Float(n) => Ok(VmValue::Bool(n.is_nan())),
        _ => Ok(VmValue::Bool(false)),
    }
}

#[harn_builtin(sig = "is_infinite(value: number) -> bool", category = "math")]
fn is_infinite_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    match args.first().unwrap_or(&VmValue::Nil) {
        VmValue::Float(n) => Ok(VmValue::Bool(n.is_infinite())),
        _ => Ok(VmValue::Bool(false)),
    }
}

#[harn_builtin(
    sig = "__range__(start: int, end: int, inclusive?: bool) -> any",
    runtime_only = true,
    category = "math"
)]
fn range_internal_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let start = args.first().and_then(|a| a.as_int()).unwrap_or(0);
    let end = args.get(1).and_then(|a| a.as_int()).unwrap_or(0);
    let inclusive = args.get(2).map(|a| a.is_truthy()).unwrap_or(false);
    Ok(VmValue::range(VmRange {
        start,
        end,
        inclusive,
    }))
}

// `range()` is Python-style and always half-open. Use `a to b [exclusive]`
// for human-readable inclusive math.
#[harn_builtin(sig = "range(...args: any) -> list", category = "math")]
fn range_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let (start, end) = match args.len() {
        1 => {
            let n = args[0].as_int().ok_or_else(|| {
                VmError::TypeError("range(n): expected integer argument".to_string())
            })?;
            (0, n)
        }
        2 => {
            let a = args[0].as_int().ok_or_else(|| {
                VmError::TypeError("range(a, b): expected integer arguments".to_string())
            })?;
            let b = args[1].as_int().ok_or_else(|| {
                VmError::TypeError("range(a, b): expected integer arguments".to_string())
            })?;
            (a, b)
        }
        n => {
            return Err(VmError::TypeError(format!(
                "range expects 1 or 2 integer arguments, got {n}"
            )));
        }
    };
    Ok(VmValue::range(VmRange {
        start,
        end,
        inclusive: false,
    }))
}

fn number_arg(value: Option<&VmValue>, label: &str) -> Result<f64, VmError> {
    match value {
        Some(VmValue::Int(n)) => Ok(*n as f64),
        Some(VmValue::Float(n)) => Ok(*n),
        _ => Err(VmError::TypeError(format!("{label} must be numeric"))),
    }
}

fn numeric_list_arg(args: &[VmValue], label: &str) -> Result<Vec<f64>, VmError> {
    let Some(VmValue::List(items)) = args.first() else {
        return Err(VmError::TypeError(format!("{label}: items must be a list")));
    };
    items
        .iter()
        .map(|item| number_arg(Some(item), label))
        .collect()
}

fn non_empty_numeric_list_arg(args: &[VmValue], label: &str) -> Result<Vec<f64>, VmError> {
    let values = numeric_list_arg(args, label)?;
    if values.is_empty() {
        return Err(VmError::Runtime(format!(
            "{label}: items must not be empty"
        )));
    }
    Ok(values)
}

fn variance_for(values: &[f64], sample: bool, label: &str) -> Result<f64, VmError> {
    if sample && values.len() < 2 {
        return Err(VmError::Runtime(format!(
            "sample {label} requires at least 2 values"
        )));
    }
    let mean = values.iter().sum::<f64>() / values.len() as f64;
    let total = values
        .iter()
        .map(|value| {
            let delta = value - mean;
            delta * delta
        })
        .sum::<f64>();
    let denom = if sample {
        values.len() - 1
    } else {
        values.len()
    };
    Ok(total / denom as f64)
}

fn finite_float_to_i64(n: f64) -> Result<i64, VmError> {
    if !n.is_finite() {
        return Err(VmError::Runtime(
            "cannot convert non-finite float to int".to_string(),
        ));
    }
    if n < i64::MIN as f64 || n >= 9_223_372_036_854_775_808.0 {
        return Err(VmError::Runtime(
            "float is outside the representable int range".to_string(),
        ));
    }
    Ok(n as i64)
}

/// Helper used by sin/cos/tan/etc. Coerces the first arg to `f64` (Int → cast),
/// applies `f`, and wraps in `VmValue::Float`. Non-numeric arg returns `Nil`
/// to preserve the existing closure semantics.
fn unary_float(args: &[VmValue], f: fn(f64) -> f64) -> Result<VmValue, VmError> {
    let n = match args.first().unwrap_or(&VmValue::Nil) {
        VmValue::Float(n) => *n,
        VmValue::Int(n) => *n as f64,
        // Transcendental float math has no exact decimal result; refuse rather
        // than silently return nil.
        VmValue::Decimal(_) => return Err(decimal_not_supported("this function")),
        _ => return Ok(VmValue::Nil),
    };
    Ok(VmValue::Float(f(n)))
}

/// A `decimal` operand was passed to a float-only math builtin (sqrt, pow,
/// trig, …). These have no exact base-10 result, so we error with guidance
/// instead of silently returning `nil`.
fn decimal_not_supported(name: &str) -> VmError {
    VmError::TypeError(format!(
        "{name} is not defined for decimal; convert with to_float(value) first"
    ))
}

pub(crate) const MODULE_BUILTINS: &[&VmBuiltinDef] = &[
    &ABS_IMPL_DEF,
    &MIN_IMPL_DEF,
    &MAX_IMPL_DEF,
    &FLOOR_IMPL_DEF,
    &CEIL_IMPL_DEF,
    &ROUND_IMPL_DEF,
    &SQRT_IMPL_DEF,
    &POW_IMPL_DEF,
    &RNG_SEED_IMPL_DEF,
    &RANDOM_IMPL_DEF,
    &RANDOM_INT_IMPL_DEF,
    &RANDOM_CHOICE_IMPL_DEF,
    &RANDOM_SHUFFLE_IMPL_DEF,
    &MEAN_IMPL_DEF,
    &MEDIAN_IMPL_DEF,
    &PERCENTILE_IMPL_DEF,
    &VARIANCE_IMPL_DEF,
    &STDDEV_IMPL_DEF,
    &SIN_IMPL_DEF,
    &COS_IMPL_DEF,
    &TAN_IMPL_DEF,
    &ASIN_IMPL_DEF,
    &ACOS_IMPL_DEF,
    &ATAN_IMPL_DEF,
    &LOG2_IMPL_DEF,
    &LOG10_IMPL_DEF,
    &LN_IMPL_DEF,
    &EXP_IMPL_DEF,
    &ATAN2_IMPL_DEF,
    &SIGN_IMPL_DEF,
    &IS_NAN_IMPL_DEF,
    &IS_INFINITE_IMPL_DEF,
    &RANGE_INTERNAL_IMPL_DEF,
    &RANGE_IMPL_DEF,
];

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

    fn vm() -> Vm {
        let mut vm = Vm::new();
        register_math_builtins(&mut vm);
        vm
    }

    fn call(vm: &mut Vm, name: &str, args: Vec<VmValue>) -> Result<VmValue, VmError> {
        let f = vm.builtins.get(name).unwrap().clone();
        let mut out = String::new();
        f(&args, &mut out)
    }

    #[test]
    fn abs_does_not_wrap_i64_min() {
        let mut vm = vm();
        let value = call(&mut vm, "abs", vec![VmValue::Int(i64::MIN)]).unwrap();
        assert_eq!(value.display(), "9223372036854776000");
    }

    #[test]
    fn integer_pow_does_not_wrap_on_overflow() {
        let mut vm = vm();
        let value = call(&mut vm, "pow", vec![VmValue::Int(2), VmValue::Int(63)]).unwrap();
        assert_eq!(value.display(), "9223372036854776000");
    }

    #[test]
    fn rounding_rejects_non_finite_float_to_int() {
        let mut vm = vm();
        let error = call(&mut vm, "floor", vec![VmValue::Float(f64::INFINITY)])
            .expect_err("infinite float cannot become int");
        assert!(error.to_string().contains("non-finite"));
    }

    #[test]
    fn round_digits_float_half_away_from_zero() {
        assert_eq!(round_float_to_digits(2.567, 2), 2.57);
        assert_eq!(round_float_to_digits(-2.567, 2), -2.57);
        // Exactly representable midpoints round away from zero.
        assert_eq!(round_float_to_digits(1.25, 1), 1.3);
        assert_eq!(round_float_to_digits(-1.25, 1), -1.3);
        // Binary-arithmetic noise just above the target still lands on it.
        assert_eq!(round_float_to_digits(0.1 + 0.2, 2), 0.3);
        // Negative digits round to power-of-ten buckets.
        assert_eq!(round_float_to_digits(1234.5678, -2), 1200.0);
        assert_eq!(round_float_to_digits(1250.0, -2), 1300.0);
        // Extreme digit counts degrade gracefully.
        assert_eq!(round_float_to_digits(1.5, 400), 1.5);
        assert_eq!(round_float_to_digits(1.5, -400), 0.0);
        assert!(round_float_to_digits(f64::NAN, 2).is_nan());
        assert_eq!(round_float_to_digits(f64::INFINITY, 2), f64::INFINITY);
    }

    #[test]
    fn round_digits_int_negative_buckets() {
        assert!(matches!(round_int_to_digits(1250, -2), VmValue::Int(1300)));
        assert!(matches!(
            round_int_to_digits(-1250, -2),
            VmValue::Int(-1300)
        ));
        assert!(matches!(round_int_to_digits(1249, -2), VmValue::Int(1200)));
        assert!(matches!(round_int_to_digits(7, 3), VmValue::Int(7)));
        assert!(matches!(round_int_to_digits(123, -19), VmValue::Int(0)));
        // A bucket boundary past i64::MAX promotes to float instead of wrapping
        // (i64::MAX rounds up to 9_223_400_000_000_000_000 at -14 digits).
        assert!(matches!(round_int_to_digits(i64::MAX, -14), VmValue::Float(f) if f == 9.2234e18));
    }

    #[test]
    fn stddev_sample_error_names_stddev() {
        let mut vm = vm();
        let values = VmValue::List(std::sync::Arc::new(vec![VmValue::Int(1)]));
        let error = call(&mut vm, "stddev", vec![values, VmValue::Bool(true)])
            .expect_err("sample stddev needs at least two values");
        assert!(error.to_string().contains("sample stddev"));
    }
}