aether-azathoth 0.5.3

A lightweight, embeddable domain-specific language (DSL) interpreter with rich standard library
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
//! C-FFI interface for Aether language bindings
//!
//! This module provides C-compatible functions for use with other languages
//! through Foreign Function Interface (FFI).

use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int};
use std::panic;
use std::sync::Mutex;

use crate::{Aether, Value};
use serde_json::json;

/// Opaque handle for Aether engine
#[repr(C)]
pub struct AetherHandle {
    _opaque: [u8; 0],
}

/// Error codes returned by C-FFI functions
#[repr(C)]
pub enum AetherErrorCode {
    Success = 0,
    ParseError = 1,
    RuntimeError = 2,
    NullPointer = 3,
    Panic = 4,
    InvalidJSON = 5,
    VariableNotFound = 6,
}

/// Execution limits configuration
#[repr(C)]
pub struct AetherLimits {
    pub max_steps: c_int,
    pub max_recursion_depth: c_int,
    pub max_duration_ms: c_int,
}

/// Cache statistics
#[repr(C)]
pub struct AetherCacheStats {
    pub hits: c_int,
    pub misses: c_int,
    pub size: c_int,
}

/// Thread-safe wrapper for Aether engine
struct ThreadSafeEngine {
    #[allow(dead_code)]
    engine: Aether,
    #[allow(dead_code)]
    mutex: Mutex<()>,
}

impl ThreadSafeEngine {
    #[allow(dead_code)]
    fn new(engine: Aether) -> Self {
        Self {
            engine,
            mutex: Mutex::new(()),
        }
    }
}

/// Create a new Aether engine instance
///
/// Returns: Pointer to AetherHandle (must be freed with aether_free)
#[unsafe(no_mangle)]
pub extern "C" fn aether_new() -> *mut AetherHandle {
    let engine = Box::new(Aether::new());
    Box::into_raw(engine) as *mut AetherHandle
}

/// Create a new Aether engine with all IO permissions enabled
///
/// Returns: Pointer to AetherHandle (must be freed with aether_free)
#[unsafe(no_mangle)]
pub extern "C" fn aether_new_with_permissions() -> *mut AetherHandle {
    let engine = Box::new(Aether::with_all_permissions());
    Box::into_raw(engine) as *mut AetherHandle
}

/// Evaluate Aether code
///
/// # Parameters
/// - handle: Aether engine handle
/// - code: C string containing Aether code
/// - result: Output parameter for result (must be freed with aether_free_string)
/// - error: Output parameter for error message (must be freed with aether_free_string)
///
/// # Returns
/// - 0 (Success) if evaluation succeeded
/// - Non-zero error code if evaluation failed
#[unsafe(no_mangle)]
pub extern "C" fn aether_eval(
    handle: *mut AetherHandle,
    code: *const c_char,
    result: *mut *mut c_char,
    error: *mut *mut c_char,
) -> c_int {
    #![allow(clippy::not_unsafe_ptr_arg_deref)]
    if handle.is_null() || code.is_null() || result.is_null() || error.is_null() {
        return AetherErrorCode::NullPointer as c_int;
    }

    // Catch panics and convert them to errors
    let panic_result = panic::catch_unwind(|| unsafe {
        let engine = &mut *(handle as *mut Aether);
        let code_str = match CStr::from_ptr(code).to_str() {
            Ok(s) => s,
            Err(_) => return AetherErrorCode::RuntimeError as c_int,
        };

        match engine.eval(code_str) {
            Ok(val) => {
                let result_str = value_to_string(&val);
                match CString::new(result_str) {
                    Ok(cstr) => {
                        *result = cstr.into_raw();
                        *error = std::ptr::null_mut();
                        AetherErrorCode::Success as c_int
                    }
                    Err(_) => AetherErrorCode::RuntimeError as c_int,
                }
            }
            Err(e) => {
                let error_str = e.to_string();
                match CString::new(error_str) {
                    Ok(cstr) => {
                        *error = cstr.into_raw();
                        *result = std::ptr::null_mut();
                        // Determine error type from message
                        if e.contains("Parse error") {
                            AetherErrorCode::ParseError as c_int
                        } else {
                            AetherErrorCode::RuntimeError as c_int
                        }
                    }
                    Err(_) => AetherErrorCode::RuntimeError as c_int,
                }
            }
        }
    });

    match panic_result {
        Ok(code) => code,
        Err(_) => {
            unsafe {
                let panic_msg = CString::new("Panic occurred during evaluation").unwrap();
                *error = panic_msg.into_raw();
                *result = std::ptr::null_mut();
            }
            AetherErrorCode::Panic as c_int
        }
    }
}

/// Get the version string of Aether
///
/// Returns: C string with version (must NOT be freed)
#[unsafe(no_mangle)]
pub extern "C" fn aether_version() -> *const c_char {
    static VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "\0");
    VERSION.as_ptr() as *const c_char
}

/// Free an Aether engine handle
#[unsafe(no_mangle)]
pub extern "C" fn aether_free(handle: *mut AetherHandle) {
    if !handle.is_null() {
        unsafe {
            let _ = Box::from_raw(handle as *mut Aether);
        }
    }
}

/// Free a string allocated by Aether
#[unsafe(no_mangle)]
pub extern "C" fn aether_free_string(s: *mut c_char) {
    #![allow(clippy::not_unsafe_ptr_arg_deref)]
    if !s.is_null() {
        unsafe {
            let _ = CString::from_raw(s);
        }
    }
}

/// Helper function to convert Value to string representation
fn value_to_string(value: &Value) -> String {
    match value {
        Value::Number(n) => {
            // Format number nicely - remove trailing zeros
            if n.fract() == 0.0 {
                format!("{:.0}", n)
            } else {
                n.to_string()
            }
        }
        Value::String(s) => s.clone(),
        Value::Boolean(b) => b.to_string(),
        Value::Array(arr) => {
            let items: Vec<String> = arr.iter().map(value_to_string).collect();
            format!("[{}]", items.join(", "))
        }
        Value::Dict(map) => {
            let items: Vec<String> = map
                .iter()
                .map(|(k, v)| format!("{}: {}", k, value_to_string(v)))
                .collect();
            format!("{{{}}}", items.join(", "))
        }
        Value::Null => "null".to_string(),
        Value::Function { .. } => "<function>".to_string(),
        Value::BuiltIn { name, .. } => format!("<builtin: {}>", name),
        Value::Generator { .. } => "<generator>".to_string(),
        Value::Lazy { .. } => "<lazy>".to_string(),
        Value::Fraction(f) => f.to_string(),
    }
}

/// Helper function to convert Value to JSON string
fn value_to_json(value: &Value) -> String {
    match value {
        Value::Number(n) => {
            // 直接返回数字的 JSON 表示
            json!(n).to_string()
        }
        Value::String(s) => json!(s).to_string(),
        Value::Boolean(b) => json!(b).to_string(),
        Value::Array(arr) => {
            let items: Vec<serde_json::Value> = arr.iter().map(json_from_value).collect();
            json!(items).to_string()
        }
        Value::Dict(map) => {
            let mut obj = serde_json::Map::new();
            for (k, v) in map {
                obj.insert(k.clone(), json_from_value(v));
            }
            json!(obj).to_string()
        }
        Value::Null => "null".to_string(),
        Value::Function { .. } => json!("<function>").to_string(),
        Value::BuiltIn { name, .. } => json!(format!("<builtin: {}>", name)).to_string(),
        Value::Generator { .. } => json!("<generator>").to_string(),
        Value::Lazy { .. } => json!("<lazy>").to_string(),
        Value::Fraction(f) => json!(f.to_string()).to_string(),
    }
}

/// Helper function to convert Value to serde_json::Value
fn json_from_value(value: &Value) -> serde_json::Value {
    match value {
        Value::Number(n) => json!(n),
        Value::String(s) => json!(s),
        Value::Boolean(b) => json!(b),
        Value::Array(arr) => {
            let items: Vec<serde_json::Value> = arr.iter().map(json_from_value).collect();
            json!(items)
        }
        Value::Dict(map) => {
            let mut obj = serde_json::Map::new();
            for (k, v) in map {
                obj.insert(k.clone(), json_from_value(v));
            }
            json!(obj)
        }
        Value::Null => json!(null),
        Value::Function { .. } => json!("<function>"),
        Value::BuiltIn { name, .. } => json!(format!("<builtin: {}>", name)),
        Value::Generator { .. } => json!("<generator>"),
        Value::Lazy { .. } => json!("<lazy>"),
        Value::Fraction(f) => json!(f.to_string()),
    }
}

/// Helper function to parse JSON to Value
fn json_to_value(json_str: &str) -> Result<Value, String> {
    let v: serde_json::Value =
        serde_json::from_str(json_str).map_err(|e| format!("Invalid JSON: {}", e))?;

    Ok(match v {
        serde_json::Value::Number(n) => {
            if n.is_i64() {
                Value::Number(n.as_i64().unwrap() as f64)
            } else {
                Value::Number(n.as_f64().unwrap())
            }
        }
        serde_json::Value::String(s) => Value::String(s),
        serde_json::Value::Bool(b) => Value::Boolean(b),
        serde_json::Value::Array(arr) => {
            let items: Result<Vec<_>, _> =
                arr.iter().map(|v| json_to_value(&v.to_string())).collect();
            Value::Array(items?)
        }
        serde_json::Value::Object(obj) => {
            let mut map = std::collections::HashMap::new();
            for (k, v) in obj {
                map.insert(k, json_to_value(&v.to_string())?);
            }
            Value::Dict(map)
        }
        serde_json::Value::Null => Value::Null,
    })
}

// ============================================================
// Variable Operations
// ============================================================

/// Set a global variable from host application
///
/// # Parameters
/// - handle: Aether engine handle
/// - name: Variable name
/// - value_json: Variable value as JSON string
///
/// # Returns
/// - 0 (Success) if variable was set
/// - Non-zero error code if failed
///
/// # Safety
/// - `handle` must be a valid pointer to an AetherHandle created by `aether_new` or `aether_new_with_permissions`
/// - `name` must be a valid pointer to a null-terminated C string
/// - `value_json` must be a valid pointer to a null-terminated C string
#[unsafe(no_mangle)]
pub unsafe extern "C" fn aether_set_global(
    handle: *mut AetherHandle,
    name: *const c_char,
    value_json: *const c_char,
) -> c_int {
    if handle.is_null() || name.is_null() || value_json.is_null() {
        return AetherErrorCode::NullPointer as c_int;
    }

    let panic_result = panic::catch_unwind(|| unsafe {
        let engine = &mut *(handle as *mut Aether);
        let name_str = match CStr::from_ptr(name).to_str() {
            Ok(s) => s,
            Err(_) => return AetherErrorCode::RuntimeError as c_int,
        };
        let json_str = match CStr::from_ptr(value_json).to_str() {
            Ok(s) => s,
            Err(_) => return AetherErrorCode::RuntimeError as c_int,
        };

        // Parse JSON to Value
        let value = match json_to_value(json_str) {
            Ok(v) => v,
            Err(_) => return AetherErrorCode::InvalidJSON as c_int,
        };

        engine.set_global(name_str, value);
        AetherErrorCode::Success as c_int
    });

    match panic_result {
        Ok(code) => code,
        Err(_) => AetherErrorCode::Panic as c_int,
    }
}

/// Get a variable's value as JSON
///
/// # Parameters
/// - handle: Aether engine handle
/// - name: Variable name
/// - value_json: Output parameter (must be freed with aether_free_string)
///
/// # Returns
/// - 0 (Success) if variable was found
/// - VariableNotFound (6) if variable doesn't exist
/// - Non-zero error code for other failures
///
/// # Safety
/// - `handle` must be a valid pointer to an AetherHandle created by `aether_new` or `aether_new_with_permissions`
/// - `name` must be a valid pointer to a null-terminated C string
/// - `value_json` must be a valid pointer to a `*mut c_char` that will be set to point to the result
#[unsafe(no_mangle)]
pub unsafe extern "C" fn aether_get_global(
    handle: *mut AetherHandle,
    name: *const c_char,
    value_json: *mut *mut c_char,
) -> c_int {
    if handle.is_null() || name.is_null() || value_json.is_null() {
        return AetherErrorCode::NullPointer as c_int;
    }

    let panic_result = panic::catch_unwind(|| unsafe {
        let engine = &mut *(handle as *mut Aether);
        let name_str = match CStr::from_ptr(name).to_str() {
            Ok(s) => s,
            Err(_) => return AetherErrorCode::RuntimeError as c_int,
        };

        // 直接从环境获取变量值
        let value = engine.evaluator.get_global(name_str);

        match value {
            Some(val) => {
                let json_str = value_to_json(&val);
                match CString::new(json_str) {
                    Ok(cstr) => {
                        *value_json = cstr.into_raw();
                        AetherErrorCode::Success as c_int
                    }
                    Err(_) => AetherErrorCode::RuntimeError as c_int,
                }
            }
            None => AetherErrorCode::VariableNotFound as c_int,
        }
    });

    match panic_result {
        Ok(code) => code,
        Err(_) => AetherErrorCode::Panic as c_int,
    }
}

/// Reset the runtime environment (clears all variables)
///
/// # Parameters
/// - handle: Aether engine handle
#[unsafe(no_mangle)]
pub extern "C" fn aether_reset_env(handle: *mut AetherHandle) {
    if handle.is_null() {
        return;
    }

    let _ = panic::catch_unwind(|| unsafe {
        let engine = &mut *(handle as *mut Aether);
        engine.reset_env();
    });
}

// ============================================================
// Trace Operations
// ============================================================

/// Get all trace entries as JSON array
///
/// # Parameters
/// - handle: Aether engine handle
/// - trace_json: Output parameter (must be freed with aether_free_string)
///
/// # Returns
/// - 0 (Success) if trace was retrieved
/// - Non-zero error code if failed
///
/// # Safety
/// - `handle` must be a valid pointer to an AetherHandle created by `aether_new` or `aether_new_with_permissions`
/// - `trace_json` must be a valid pointer to a `*mut c_char` that will be set to point to the result
#[unsafe(no_mangle)]
pub unsafe extern "C" fn aether_take_trace(
    handle: *mut AetherHandle,
    trace_json: *mut *mut c_char,
) -> c_int {
    if handle.is_null() || trace_json.is_null() {
        return AetherErrorCode::NullPointer as c_int;
    }

    let panic_result = panic::catch_unwind(|| unsafe {
        let engine = &mut *(handle as *mut Aether);
        let traces = engine.take_trace();

        let json_array = json!(traces).to_string();
        match CString::new(json_array) {
            Ok(cstr) => {
                *trace_json = cstr.into_raw();
                AetherErrorCode::Success as c_int
            }
            Err(_) => AetherErrorCode::RuntimeError as c_int,
        }
    });

    match panic_result {
        Ok(code) => code,
        Err(_) => AetherErrorCode::Panic as c_int,
    }
}

/// Clear the trace buffer
///
/// # Parameters
/// - handle: Aether engine handle
#[unsafe(no_mangle)]
pub extern "C" fn aether_clear_trace(handle: *mut AetherHandle) {
    if handle.is_null() {
        return;
    }

    let _ = panic::catch_unwind(|| unsafe {
        let engine = &mut *(handle as *mut Aether);
        engine.clear_trace();
    });
}

/// Get structured trace entries as JSON
///
/// # Parameters
/// - handle: Aether engine handle
/// - trace_json: Output parameter (must be freed with aether_free_string)
///
/// # Returns
/// - 0 (Success) if trace was retrieved
/// - Non-zero error code if failed
///
/// # Safety
/// - `handle` must be a valid pointer to an AetherHandle created by `aether_new` or `aether_new_with_permissions`
/// - `trace_json` must be a valid pointer to a `*mut c_char` that will be set to point to the result
#[unsafe(no_mangle)]
pub unsafe extern "C" fn aether_trace_records(
    handle: *mut AetherHandle,
    trace_json: *mut *mut c_char,
) -> c_int {
    if handle.is_null() || trace_json.is_null() {
        return AetherErrorCode::NullPointer as c_int;
    }

    let panic_result = panic::catch_unwind(|| unsafe {
        let engine = &mut *(handle as *mut Aether);
        let records = engine.trace_records();

        // Convert TraceEntry to JSON
        let json_array: Vec<serde_json::Value> = records
            .iter()
            .map(|entry| {
                json!({
                    "level": format!("{:?}", entry.level),
                    "category": entry.category,
                    "timestamp": entry.timestamp.elapsed().as_secs(),
                    "values": entry.values.iter().map(value_to_json).collect::<Vec<_>>(),
                    "label": entry.label,
                })
            })
            .collect();

        match CString::new(json!(json_array).to_string()) {
            Ok(cstr) => {
                *trace_json = cstr.into_raw();
                AetherErrorCode::Success as c_int
            }
            Err(_) => AetherErrorCode::RuntimeError as c_int,
        }
    });

    match panic_result {
        Ok(code) => code,
        Err(_) => AetherErrorCode::Panic as c_int,
    }
}

/// Get trace statistics as JSON
///
/// # Parameters
/// - handle: Aether engine handle
/// - stats_json: Output parameter (must be freed with aether_free_string)
///
/// # Returns
/// - 0 (Success) if stats were retrieved
/// - Non-zero error code if failed
///
/// # Safety
/// - `handle` must be a valid pointer to an AetherHandle created by `aether_new` or `aether_new_with_permissions`
/// - `stats_json` must be a valid pointer to a `*mut c_char` that will be set to point to the result
#[unsafe(no_mangle)]
pub unsafe extern "C" fn aether_trace_stats(
    handle: *mut AetherHandle,
    stats_json: *mut *mut c_char,
) -> c_int {
    if handle.is_null() || stats_json.is_null() {
        return AetherErrorCode::NullPointer as c_int;
    }

    let panic_result = panic::catch_unwind(|| unsafe {
        let engine = &mut *(handle as *mut Aether);
        let stats = engine.trace_stats();

        let json_stats = json!({
            "total_entries": stats.total_entries,
            "by_level": stats.by_level,
            "by_category": stats.by_category,
            "buffer_size": stats.buffer_size,
            "buffer_full": stats.buffer_full,
        })
        .to_string();

        match CString::new(json_stats) {
            Ok(cstr) => {
                *stats_json = cstr.into_raw();
                AetherErrorCode::Success as c_int
            }
            Err(_) => AetherErrorCode::RuntimeError as c_int,
        }
    });

    match panic_result {
        Ok(code) => code,
        Err(_) => AetherErrorCode::Panic as c_int,
    }
}

// ============================================================
// Execution Limits
// ============================================================

/// Set execution limits
///
/// # Parameters
/// - handle: Aether engine handle
/// - limits: Limits configuration
///
/// # Safety
/// - `handle` must be a valid pointer to an AetherHandle created by `aether_new` or `aether_new_with_permissions`
/// - `limits` must be a valid pointer to an AetherLimits struct
#[unsafe(no_mangle)]
pub unsafe extern "C" fn aether_set_limits(handle: *mut AetherHandle, limits: *const AetherLimits) {
    if handle.is_null() || limits.is_null() {
        return;
    }

    let _ = panic::catch_unwind(|| unsafe {
        let engine = &mut *(handle as *mut Aether);
        let limits_ref = &*limits;

        let rust_limits = crate::runtime::ExecutionLimits {
            max_steps: if limits_ref.max_steps < 0 {
                None
            } else {
                Some(limits_ref.max_steps as usize)
            },
            max_recursion_depth: if limits_ref.max_recursion_depth < 0 {
                None
            } else {
                Some(limits_ref.max_recursion_depth as usize)
            },
            max_duration_ms: if limits_ref.max_duration_ms < 0 {
                None
            } else {
                Some(limits_ref.max_duration_ms as u64)
            },
            max_memory_bytes: None,
        };

        engine.set_limits(rust_limits);
    });
}

/// Get current execution limits
///
/// # Parameters
/// - handle: Aether engine handle
/// - limits: Output parameter
///
/// # Safety
/// - `handle` must be a valid pointer to an AetherHandle created by `aether_new` or `aether_new_with_permissions`
/// - `limits` must be a valid pointer to an AetherLimits struct that will be filled with the current limits
#[unsafe(no_mangle)]
pub unsafe extern "C" fn aether_get_limits(handle: *mut AetherHandle, limits: *mut AetherLimits) {
    if handle.is_null() || limits.is_null() {
        return;
    }

    let _ = panic::catch_unwind(|| unsafe {
        let engine = &mut *(handle as *mut Aether);
        let rust_limits = engine.limits();

        (*limits).max_steps = match rust_limits.max_steps {
            Some(v) => v as c_int,
            None => -1,
        };
        (*limits).max_recursion_depth = match rust_limits.max_recursion_depth {
            Some(v) => v as c_int,
            None => -1,
        };
        (*limits).max_duration_ms = match rust_limits.max_duration_ms {
            Some(v) => v as c_int,
            None => -1,
        };
    });
}

// ============================================================
// Cache Control
// ============================================================

/// Clear the AST cache
///
/// # Parameters
/// - handle: Aether engine handle
#[unsafe(no_mangle)]
pub extern "C" fn aether_clear_cache(handle: *mut AetherHandle) {
    if handle.is_null() {
        return;
    }

    let _ = panic::catch_unwind(|| unsafe {
        let engine = &mut *(handle as *mut Aether);
        engine.clear_cache();
    });
}

/// Get cache statistics
///
/// # Parameters
/// - handle: Aether engine handle
/// - stats: Output parameter
///
/// # Safety
/// - `handle` must be a valid pointer to an AetherHandle created by `aether_new` or `aether_new_with_permissions`
/// - `stats` must be a valid pointer to an AetherCacheStats struct that will be filled with the statistics
#[unsafe(no_mangle)]
pub unsafe extern "C" fn aether_cache_stats(
    handle: *mut AetherHandle,
    stats: *mut AetherCacheStats,
) {
    if handle.is_null() || stats.is_null() {
        return;
    }

    let _ = panic::catch_unwind(|| unsafe {
        let engine = &mut *(handle as *mut Aether);
        let rust_stats = engine.cache_stats();

        (*stats).hits = rust_stats.hits as c_int;
        (*stats).misses = rust_stats.misses as c_int;
        (*stats).size = rust_stats.size as c_int;
    });
}

// ============================================================
// Optimization Control
// ============================================================

/// Set optimization options
///
/// # Parameters
/// - handle: Aether engine handle
/// - constant_folding: Enable constant folding (1 = yes, 0 = no)
/// - dead_code_elimination: Enable dead code elimination (1 = yes, 0 = no)
/// - tail_recursion: Enable tail recursion optimization (1 = yes, 0 = no)
#[unsafe(no_mangle)]
pub extern "C" fn aether_set_optimization(
    handle: *mut AetherHandle,
    constant_folding: c_int,
    dead_code_elimination: c_int,
    tail_recursion: c_int,
) {
    if handle.is_null() {
        return;
    }

    let _ = panic::catch_unwind(|| unsafe {
        let engine = &mut *(handle as *mut Aether);
        engine.set_optimization(
            constant_folding != 0,
            dead_code_elimination != 0,
            tail_recursion != 0,
        );
    });
}