keleusma 0.2.2

Total Functional Stream Processor with definitive WCET and WCMU verification, targeting no_std + alloc embedded scripting
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
//! Standard DSL libraries packaged as host-registerable bundles.
//!
//! Each bundle is a unit struct implementing the
//! [`Library`](crate::stddsl::Library) trait. Hosts register a
//! bundle through [`crate::vm::Vm::register_library`]:
//!
//! ```ignore
//! use keleusma::stddsl;
//! vm.register_library(stddsl::Math);
//! vm.register_library(stddsl::Audio);
//! ```
//!
//! ## Available libraries
//!
//! - [`Math`](crate::stddsl::Math) - pure floating-point math
//!   routines and named constants under the `math::` namespace.
//! - [`Audio`](crate::stddsl::Audio) - digital signal processing
//!   helpers under the `audio::` namespace. The Audio bundle does
//!   not register `math::` entries; a host script that needs both
//!   should register Math and Audio.
//! - [`Shell`](crate::stddsl::Shell) - shell-script utilities
//!   (`shell::getenv`, `shell::run`, `shell::run_checked`,
//!   `shell::exit`). Requires the `shell` cargo feature, which adds
//!   a `std` dependency. `shell` is incompatible with the no_std
//!   build profile.
//!
//! ## Single-file scripts
//!
//! Keleusma scripts are necessarily single-file. There is no
//! `import` or `mod` mechanism inside the language; cross-script
//! reuse is intentionally outside the scope of the V0.2 surface.
//! If your application's needs grow to where you find yourself
//! wishing for modularisation, the recommended path is to roll a
//! custom DSL library: implement
//! [`Library`](crate::stddsl::Library) on a host-side unit struct
//! that registers the natives your scripts call, and let every
//! script consume the same vocabulary through `use` declarations.
//! The host-side library is the unit of reuse, not the script.

extern crate alloc;

use crate::address::Address;
use crate::float::Float;
use crate::vm::GenericVm;
use crate::word::Word;

/// Host-registerable bundle of native functions.
///
/// A `Library` registers a related set of native functions on a
/// VM. Implementors are typically unit structs in the `stddsl`
/// module or in host crates that want to ship their own bundles.
/// The trait method takes `self` by value so unit structs can be
/// dropped after registration.
///
/// Hosts call [`GenericVm::register_library`] which delegates to
/// [`Library::register`]; the trait is the extensibility surface
/// for third-party bundles.
///
/// The trait is parametric over the runtime's word, address, and
/// float types so library authors can opt their bundles into
/// narrow-runtime support. The standard bundles ([`Math`],
/// [`Audio`], [`Shell`]) are presently implemented only for the
/// default `(i64, u64, f64)` shape.
pub trait Library<W: Word, A: Address, F: Float> {
    /// Register every native function in this bundle on `vm`.
    fn register<'a, 'arena>(self, vm: &mut GenericVm<'a, 'arena, W, A, F>);
}

/// Pure floating-point math routines and named constants.
///
/// Registers the following entries under the `math::` namespace.
///
/// Algebraic and rounding routines: `sqrt`, `pow`, `abs`, `sign`,
/// `floor`, `ceil`, `round`, `trunc`, `fmod`, `hypot`, `min`,
/// `max`, `clamp`, `lerp`.
///
/// Trigonometric routines: `sin`, `cos`, `tan`, `asin`, `acos`,
/// `atan`, `atan2`, `tanh`.
///
/// Exponential and logarithmic routines: `exp`, `ln`, `log10`,
/// `log2`.
///
/// Zero-argument constant accessors: `pi`, `tau`, `e`, `sqrt_2`,
/// `ln_2`, `ln_10`.
///
/// Backed by `libm` and `core::f64::consts` so the bundle works
/// in `no_std` builds.
pub struct Math;

/// Digital signal processing helpers for audio applications.
///
/// Registers the following entries under the `audio::` namespace.
///
/// Pitch conversion: `midi_to_freq`, `freq_to_midi`,
/// `cents_to_ratio`, `ratio_to_cents`, `semitones_to_ratio`,
/// `ratio_to_semitones`.
///
/// Amplitude conversion: `db_to_linear`, `linear_to_db`.
///
/// Time conversion: `ms_to_samples`, `samples_to_ms`.
///
/// Filter coefficient helpers: `onepole_lpf_alpha`,
/// `onepole_hpf_alpha`.
///
/// Spatial helper: `pan_law` returning an equal-power
/// `(left, right)` gain pair.
///
/// The Audio bundle does not register entries under the `math::`
/// namespace. A host script that needs both audio and math
/// helpers should register the [`Math`] bundle as well. Backed by
/// `libm`.
pub struct Audio;

/// Shell-script utilities. Requires the `shell` cargo feature.
///
/// Registers `shell::getenv` (returns `Option<Text>`),
/// `shell::run` (returns `(Word, Text)`), `shell::run_full`
/// (returns `(Word, Text, Text)` including stderr),
/// `shell::run_checked` (returns `Text`, traps on non-zero exit),
/// and `shell::exit` (terminates the host process).
///
/// The Shell bundle is unavailable when the `shell` feature is
/// disabled because it depends on `std::process` and `std::env`.
/// The Vm cannot be constructed in `no_std` mode with the
/// `shell` feature enabled.
pub struct Shell;

impl Math {
    /// Source-form signature declarations for the Math bundle.
    /// Hosts that want compile-time signature validation prepend
    /// this string to the script source before parsing.
    ///
    /// All math functions declare `Float` parameters. The
    /// typechecker allows a `Word` argument where a `Float`
    /// parameter is declared at the native call boundary; the
    /// runtime auto-widens the value. Scripts can therefore write
    /// `math::sin(1)` even though the signature is `(Float) -> Float`.
    pub const SIGNATURES: &'static str = concat!(
        // Algebraic and rounding.
        "use math::sqrt(Float) -> Float\n",
        "use math::pow(Float, Float) -> Float\n",
        "use math::abs(Float) -> Float\n",
        "use math::sign(Float) -> Float\n",
        "use math::floor(Float) -> Float\n",
        "use math::ceil(Float) -> Float\n",
        "use math::round(Float) -> Float\n",
        "use math::trunc(Float) -> Float\n",
        "use math::fmod(Float, Float) -> Float\n",
        "use math::hypot(Float, Float) -> Float\n",
        "use math::min(Float, Float) -> Float\n",
        "use math::max(Float, Float) -> Float\n",
        "use math::clamp(Float, Float, Float) -> Float\n",
        "use math::lerp(Float, Float, Float) -> Float\n",
        // Trigonometric.
        "use math::sin(Float) -> Float\n",
        "use math::cos(Float) -> Float\n",
        "use math::tan(Float) -> Float\n",
        "use math::asin(Float) -> Float\n",
        "use math::acos(Float) -> Float\n",
        "use math::atan(Float) -> Float\n",
        "use math::atan2(Float, Float) -> Float\n",
        "use math::tanh(Float) -> Float\n",
        // Exponential and logarithmic.
        "use math::exp(Float) -> Float\n",
        "use math::ln(Float) -> Float\n",
        "use math::log10(Float) -> Float\n",
        "use math::log2(Float) -> Float\n",
        // Named constants.
        "use math::pi() -> Float\n",
        "use math::tau() -> Float\n",
        "use math::e() -> Float\n",
        "use math::sqrt_2() -> Float\n",
        "use math::ln_2() -> Float\n",
        "use math::ln_10() -> Float\n",
    );
}

impl Audio {
    /// Source-form signature declarations for the Audio bundle.
    /// Hosts that want compile-time signature validation prepend
    /// this string to the script source before parsing.
    ///
    /// As with Math, `Float` parameters accept `Word` arguments
    /// through the native-boundary auto-widening rule.
    pub const SIGNATURES: &'static str = concat!(
        "use audio::midi_to_freq(Word) -> Float\n",
        "use audio::freq_to_midi(Float) -> Word\n",
        "use audio::cents_to_ratio(Float) -> Float\n",
        "use audio::ratio_to_cents(Float) -> Float\n",
        "use audio::semitones_to_ratio(Float) -> Float\n",
        "use audio::ratio_to_semitones(Float) -> Float\n",
        "use audio::db_to_linear(Float) -> Float\n",
        "use audio::linear_to_db(Float) -> Float\n",
        "use audio::ms_to_samples(Float, Float) -> Float\n",
        "use audio::samples_to_ms(Float, Float) -> Float\n",
        "use audio::onepole_lpf_alpha(Float, Float) -> Float\n",
        "use audio::onepole_hpf_alpha(Float, Float) -> Float\n",
        "use audio::pan_law(Float) -> (Float, Float)\n",
    );
}

impl<W: Word, A: Address, F: Float> Library<W, A, F> for Math {
    fn register<'a, 'arena>(self, vm: &mut GenericVm<'a, 'arena, W, A, F>) {
        math::register(vm);
    }
}

impl<W: Word, A: Address, F: Float> Library<W, A, F> for Audio {
    fn register<'a, 'arena>(self, vm: &mut GenericVm<'a, 'arena, W, A, F>) {
        crate::audio_natives::register_audio_natives(vm);
    }
}

#[cfg(feature = "shell")]
impl<W: Word, A: Address, F: Float> Library<W, A, F> for Shell {
    fn register<'a, 'arena>(self, vm: &mut GenericVm<'a, 'arena, W, A, F>) {
        shell::register(vm);
    }
}

mod math {
    extern crate alloc;
    use alloc::string::String;
    use core::f64::consts;

    use crate::address::Address;
    use crate::float::Float;
    use crate::vm::{GenericVm, VmError};
    use crate::word::Word;

    pub fn register<'a, 'arena, W: Word, A: Address, F: Float>(
        vm: &mut GenericVm<'a, 'arena, W, A, F>,
    ) {
        // Algebraic and rounding routines.
        vm.register_fn("math::sqrt", |x: f64| -> f64 { libm::sqrt(x) });
        vm.register_fn("math::pow", |base: f64, exp: f64| -> f64 {
            libm::pow(base, exp)
        });
        vm.register_fn("math::abs", |x: f64| -> f64 { libm::fabs(x) });
        vm.register_fn("math::sign", |x: f64| -> f64 {
            // Branchless on the not-NaN path. Preserves -0.0 as 0.0
            // and propagates NaN.
            if x.is_nan() {
                f64::NAN
            } else if x > 0.0 {
                1.0
            } else if x < 0.0 {
                -1.0
            } else {
                0.0
            }
        });
        vm.register_fn("math::floor", |x: f64| -> f64 { libm::floor(x) });
        vm.register_fn("math::ceil", |x: f64| -> f64 { libm::ceil(x) });
        vm.register_fn("math::round", |x: f64| -> f64 { libm::round(x) });
        vm.register_fn("math::trunc", |x: f64| -> f64 { libm::trunc(x) });
        vm.register_fn_fallible("math::fmod", |x: f64, y: f64| -> Result<f64, VmError> {
            if y == 0.0 {
                return Err(VmError::NativeError(String::from(
                    "math::fmod: divisor must be non-zero",
                )));
            }
            Ok(libm::fmod(x, y))
        });
        vm.register_fn("math::hypot", |x: f64, y: f64| -> f64 { libm::hypot(x, y) });
        vm.register_fn("math::min", |a: f64, b: f64| -> f64 { libm::fmin(a, b) });
        vm.register_fn("math::max", |a: f64, b: f64| -> f64 { libm::fmax(a, b) });
        vm.register_fn("math::clamp", |val: f64, min: f64, max: f64| -> f64 {
            if val < min {
                min
            } else if val > max {
                max
            } else {
                val
            }
        });
        vm.register_fn("math::lerp", |a: f64, b: f64, t: f64| -> f64 {
            a + (b - a) * t
        });

        // Trigonometric routines. `tanh` is grouped with the
        // trigonometric block because it is the standard
        // hyperbolic shaping primitive used alongside sine and
        // cosine in audio waveshapers.
        vm.register_fn("math::sin", |x: f64| -> f64 { libm::sin(x) });
        vm.register_fn("math::cos", |x: f64| -> f64 { libm::cos(x) });
        vm.register_fn("math::tan", |x: f64| -> f64 { libm::tan(x) });
        vm.register_fn_fallible("math::asin", |x: f64| -> Result<f64, VmError> {
            if !(-1.0..=1.0).contains(&x) {
                return Err(VmError::NativeError(String::from(
                    "math::asin: argument must lie in [-1, 1]",
                )));
            }
            Ok(libm::asin(x))
        });
        vm.register_fn_fallible("math::acos", |x: f64| -> Result<f64, VmError> {
            if !(-1.0..=1.0).contains(&x) {
                return Err(VmError::NativeError(String::from(
                    "math::acos: argument must lie in [-1, 1]",
                )));
            }
            Ok(libm::acos(x))
        });
        vm.register_fn("math::atan", |x: f64| -> f64 { libm::atan(x) });
        vm.register_fn("math::atan2", |y: f64, x: f64| -> f64 { libm::atan2(y, x) });
        vm.register_fn("math::tanh", |x: f64| -> f64 { libm::tanh(x) });

        // Exponential and logarithmic routines.
        vm.register_fn("math::exp", |x: f64| -> f64 { libm::exp(x) });
        vm.register_fn_fallible("math::ln", |x: f64| -> Result<f64, VmError> {
            if x <= 0.0 {
                return Err(VmError::NativeError(String::from(
                    "math::ln: argument must be strictly positive",
                )));
            }
            Ok(libm::log(x))
        });
        vm.register_fn_fallible("math::log10", |x: f64| -> Result<f64, VmError> {
            if x <= 0.0 {
                return Err(VmError::NativeError(String::from(
                    "math::log10: argument must be strictly positive",
                )));
            }
            Ok(libm::log10(x))
        });
        vm.register_fn_fallible("math::log2", |x: f64| -> Result<f64, VmError> {
            if x <= 0.0 {
                return Err(VmError::NativeError(String::from(
                    "math::log2: argument must be strictly positive",
                )));
            }
            Ok(libm::log2(x))
        });

        // Named constants, exposed as zero-argument functions.
        // The pi, tau, and e constants are universally agreed.
        // The sqrt_2 entry serves the common diagonal-norm idiom;
        // ln_2 and ln_10 support manual change-of-base operations
        // against the script-side natural log.
        vm.register_fn("math::pi", || -> f64 { consts::PI });
        vm.register_fn("math::tau", || -> f64 { consts::TAU });
        vm.register_fn("math::e", || -> f64 { consts::E });
        vm.register_fn("math::sqrt_2", || -> f64 { consts::SQRT_2 });
        vm.register_fn("math::ln_2", || -> f64 { consts::LN_2 });
        vm.register_fn("math::ln_10", || -> f64 { consts::LN_10 });
    }
}

#[cfg(feature = "shell")]
pub mod shell;

#[cfg(feature = "shell")]
impl Shell {
    /// Source-form signature declarations for the Shell bundle's
    /// natives. Hosts that want compile-time signature validation
    /// prepend this string to the script source before invoking
    /// the parser; the bundled `use` declarations populate the
    /// type checker's native-signature map so qualified call sites
    /// such as `shell::exit(code)` are checked against the
    /// declared parameter and return types.
    ///
    /// The constant is plain source text rather than a structured
    /// list because the existing parser already handles the `use
    /// path::name(params) -> return` syntax. The bundle author
    /// writes signatures in the same syntax a script author would.
    ///
    /// Embedders that register a subset of the bundle should
    /// either prepend only the relevant lines or accept that
    /// unused signatures will register harmlessly into the type
    /// checker's native map.
    pub const SIGNATURES: &'static str = concat!(
        "use shell::getenv(Text) -> Option<Text>\n",
        "use shell::has_env(Text) -> bool\n",
        "use shell::run(Text) -> (Word, Text)\n",
        "use shell::run_full(Text) -> (Word, Text, Text)\n",
        "use shell::run_checked(Text) -> Text\n",
        "use shell::exit(Word) -> ()\n",
        "use shell::sleep_ms(Word) -> ()\n",
        "use shell::now_unix_ms() -> Word\n",
        "use shell::read_file(Text) -> Text\n",
        "use shell::write_file(Text, Text) -> ()\n",
        "use shell::append_file(Text, Text) -> ()\n",
        "use shell::file_exists(Text) -> bool\n",
        "use shell::write_err(Text) -> ()\n",
        "use shell::writeln_err(Text) -> ()\n",
        "use shell::pid() -> Word\n",
        "use shell::hostname() -> Text\n",
        "use shell::arg_count() -> Word\n",
        "use shell::arg(Word) -> Option<Text>\n",
        "use shell::setenv(Text, Text) -> ()\n",
        "use shell::pwd() -> Text\n",
        "use shell::cd(Text) -> ()\n",
        "use shell::run_timeout(Text, Word) -> (Word, Text)\n",
    );
}

#[cfg(all(test, feature = "compile", feature = "verify"))]
mod tests {
    use super::*;
    use crate::bytecode::Value;
    use crate::compiler::compile;
    use crate::lexer::tokenize;
    use crate::parser::parse;
    use crate::vm::{DEFAULT_ARENA_CAPACITY, Vm, VmState};

    /// Run a Keleusma program with the Math bundle registered and
    /// return the result. Test helper local to the Math bundle
    /// tests below.
    fn run_with_math(src: &str) -> Value {
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        vm.register_library(Math);
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => v,
            VmState::Yielded(v) => panic!("unexpected yield: {:?}", v),
            VmState::Reset => panic!("unexpected reset"),
            VmState::BreakpointHit { chunk, op } => {
                panic!("unexpected breakpoint at chunk {} op {}", chunk, op)
            }
        }
    }

    fn assert_close(val: Value, expected: f64, tol: f64) {
        match val {
            Value::Float(f) => assert!(
                (f - expected).abs() < tol,
                "expected ~{}, got {}",
                expected,
                f
            ),
            other => panic!("expected Float, got {:?}", other),
        }
    }

    // -- Algebraic and rounding routines --

    #[test]
    fn math_sqrt() {
        assert_close(
            run_with_math("use math::sqrt\nfn main() -> Float { math::sqrt(9.0) }"),
            3.0,
            1e-9,
        );
    }

    #[test]
    fn math_pow() {
        assert_close(
            run_with_math("use math::pow\nfn main() -> Float { math::pow(2.0, 10.0) }"),
            1024.0,
            1e-9,
        );
    }

    #[test]
    fn math_abs() {
        assert_close(
            run_with_math("use math::abs\nfn main() -> Float { math::abs(-3.25) }"),
            3.25,
            1e-9,
        );
    }

    #[test]
    fn math_sign_positive() {
        assert_close(
            run_with_math("use math::sign\nfn main() -> Float { math::sign(7.5) }"),
            1.0,
            1e-9,
        );
    }

    #[test]
    fn math_sign_negative() {
        assert_close(
            run_with_math("use math::sign\nfn main() -> Float { math::sign(-0.001) }"),
            -1.0,
            1e-9,
        );
    }

    #[test]
    fn math_sign_zero() {
        assert_close(
            run_with_math("use math::sign\nfn main() -> Float { math::sign(0.0) }"),
            0.0,
            1e-12,
        );
    }

    #[test]
    fn math_floor() {
        assert_close(
            run_with_math("use math::floor\nfn main() -> Float { math::floor(3.7) }"),
            3.0,
            1e-9,
        );
    }

    #[test]
    fn math_ceil() {
        assert_close(
            run_with_math("use math::ceil\nfn main() -> Float { math::ceil(3.2) }"),
            4.0,
            1e-9,
        );
    }

    #[test]
    fn math_round() {
        assert_close(
            run_with_math("use math::round\nfn main() -> Float { math::round(3.5) }"),
            4.0,
            1e-9,
        );
    }

    #[test]
    fn math_trunc_positive() {
        assert_close(
            run_with_math("use math::trunc\nfn main() -> Float { math::trunc(3.7) }"),
            3.0,
            1e-9,
        );
    }

    #[test]
    fn math_trunc_negative() {
        assert_close(
            run_with_math("use math::trunc\nfn main() -> Float { math::trunc(-3.7) }"),
            -3.0,
            1e-9,
        );
    }

    #[test]
    fn math_fmod() {
        assert_close(
            run_with_math("use math::fmod\nfn main() -> Float { math::fmod(7.5, 2.0) }"),
            1.5,
            1e-9,
        );
    }

    #[test]
    fn math_hypot() {
        assert_close(
            run_with_math("use math::hypot\nfn main() -> Float { math::hypot(3.0, 4.0) }"),
            5.0,
            1e-9,
        );
    }

    #[test]
    fn math_min_max_clamp_lerp() {
        assert_close(
            run_with_math(
                "use math::min\nuse math::max\nfn main() -> Float { math::min(10.0, math::max(3.0, 5.0)) }",
            ),
            5.0,
            1e-9,
        );
        assert_close(
            run_with_math("use math::clamp\nfn main() -> Float { math::clamp(5.0, 0.0, 1.0) }"),
            1.0,
            1e-9,
        );
        assert_close(
            run_with_math("use math::lerp\nfn main() -> Float { math::lerp(0.0, 100.0, 0.25) }"),
            25.0,
            1e-9,
        );
    }

    // -- Trigonometric routines --

    #[test]
    fn math_sin_cos_tan() {
        assert_close(
            run_with_math("use math::sin\nfn main() -> Float { math::sin(0.0) }"),
            0.0,
            1e-9,
        );
        assert_close(
            run_with_math("use math::cos\nfn main() -> Float { math::cos(0.0) }"),
            1.0,
            1e-9,
        );
        assert_close(
            run_with_math("use math::tan\nfn main() -> Float { math::tan(0.0) }"),
            0.0,
            1e-9,
        );
    }

    #[test]
    fn math_asin_acos_atan() {
        assert_close(
            run_with_math("use math::asin\nfn main() -> Float { math::asin(1.0) }"),
            core::f64::consts::FRAC_PI_2,
            1e-9,
        );
        assert_close(
            run_with_math("use math::acos\nfn main() -> Float { math::acos(0.0) }"),
            core::f64::consts::FRAC_PI_2,
            1e-9,
        );
        assert_close(
            run_with_math("use math::atan\nfn main() -> Float { math::atan(1.0) }"),
            core::f64::consts::FRAC_PI_4,
            1e-9,
        );
    }

    #[test]
    fn math_atan2_quadrants() {
        assert_close(
            run_with_math("use math::atan2\nfn main() -> Float { math::atan2(1.0, 1.0) }"),
            core::f64::consts::FRAC_PI_4,
            1e-9,
        );
        assert_close(
            run_with_math("use math::atan2\nfn main() -> Float { math::atan2(1.0, -1.0) }"),
            3.0 * core::f64::consts::FRAC_PI_4,
            1e-9,
        );
    }

    #[test]
    fn math_tanh_zero_and_large() {
        assert_close(
            run_with_math("use math::tanh\nfn main() -> Float { math::tanh(0.0) }"),
            0.0,
            1e-12,
        );
        assert_close(
            run_with_math("use math::tanh\nfn main() -> Float { math::tanh(100.0) }"),
            1.0,
            1e-9,
        );
    }

    // -- Exponential and logarithmic routines --

    #[test]
    fn math_exp_zero_and_one() {
        assert_close(
            run_with_math("use math::exp\nfn main() -> Float { math::exp(0.0) }"),
            1.0,
            1e-9,
        );
        assert_close(
            run_with_math("use math::exp\nfn main() -> Float { math::exp(1.0) }"),
            core::f64::consts::E,
            1e-9,
        );
    }

    #[test]
    fn math_ln_e() {
        assert_close(
            run_with_math("use math::ln\nfn main() -> Float { math::ln(2.718281828459045) }"),
            1.0,
            1e-12,
        );
    }

    #[test]
    fn math_log10_and_log2() {
        assert_close(
            run_with_math("use math::log10\nfn main() -> Float { math::log10(1000.0) }"),
            3.0,
            1e-9,
        );
        assert_close(
            run_with_math("use math::log2\nfn main() -> Float { math::log2(8.0) }"),
            3.0,
            1e-9,
        );
    }

    // -- Domain errors --

    #[test]
    fn math_asin_domain_error() {
        let tokens = tokenize("use math::asin\nfn main() -> Float { math::asin(2.0) }").unwrap();
        let program = parse(&tokens).unwrap();
        let module = compile(&program).unwrap();
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        vm.register_library(Math);
        assert!(vm.call(&[]).is_err());
    }

    #[test]
    fn math_ln_nonpositive_error() {
        let tokens = tokenize("use math::ln\nfn main() -> Float { math::ln(0.0) }").unwrap();
        let program = parse(&tokens).unwrap();
        let module = compile(&program).unwrap();
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        vm.register_library(Math);
        assert!(vm.call(&[]).is_err());
    }

    #[test]
    fn math_fmod_zero_divisor_error() {
        let tokens =
            tokenize("use math::fmod\nfn main() -> Float { math::fmod(1.0, 0.0) }").unwrap();
        let program = parse(&tokens).unwrap();
        let module = compile(&program).unwrap();
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        vm.register_library(Math);
        assert!(vm.call(&[]).is_err());
    }

    // -- Constants --

    #[test]
    fn math_pi() {
        assert_close(
            run_with_math("use math::pi\nfn main() -> Float { math::pi() }"),
            core::f64::consts::PI,
            1e-15,
        );
    }

    #[test]
    fn math_tau() {
        assert_close(
            run_with_math("use math::tau\nfn main() -> Float { math::tau() }"),
            core::f64::consts::TAU,
            1e-15,
        );
    }

    #[test]
    fn math_e_constant() {
        assert_close(
            run_with_math("use math::e\nfn main() -> Float { math::e() }"),
            core::f64::consts::E,
            1e-15,
        );
    }

    #[test]
    fn math_sqrt_2_constant() {
        assert_close(
            run_with_math("use math::sqrt_2\nfn main() -> Float { math::sqrt_2() }"),
            core::f64::consts::SQRT_2,
            1e-15,
        );
    }

    #[test]
    fn math_ln_2_constant() {
        assert_close(
            run_with_math("use math::ln_2\nfn main() -> Float { math::ln_2() }"),
            core::f64::consts::LN_2,
            1e-15,
        );
    }

    #[test]
    fn math_ln_10_constant() {
        assert_close(
            run_with_math("use math::ln_10\nfn main() -> Float { math::ln_10() }"),
            core::f64::consts::LN_10,
            1e-15,
        );
    }
}