exp-rs 0.2.0

no_std expression parser, compiler, and evaluation engine for math expressions designed for embedded, with qemu examples
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
//! Foreign Function Interface (FFI) for C/C++ interoperability
//!
//! This module provides a simplified C API for expression evaluation with arena-based memory management.
//!
//! # Overview
//!
//! The exp-rs FFI provides two main APIs:
//!
//! ## Batch API (Advanced, Manual Memory Management)
//! - Create an arena for memory allocation
//! - Create a batch builder with the arena
//! - Add multiple expressions and parameters
//! - Evaluate all expressions at once
//! - Manually manage arena lifetime
//!
//!
//! ## Function Support
//!
//! The FFI supports two types of functions:
//!
//! ### Native Functions
//! - Implemented in C and passed as function pointers
//! - Registered with `expr_context_add_function()`
//! - Example: `sin`, `cos`, `sqrt` implementations
//!
//! ### Expression Functions
//! - Mathematical expressions that can call other functions
//! - Defined as strings and parsed when registered
//! - Registered with `expr_context_add_expression_function()`
//! - Can be removed with `expr_context_remove_expression_function()`
//! - Example: `distance(x1,y1,x2,y2) = sqrt((x2-x1)^2 + (y2-y1)^2)`
//!
//! # Example Usage
//!
//! ## Batch API Example
//! ```c
//! // Create context with functions
//! ExprContext* ctx = expr_context_new();
//! expr_context_add_function(ctx, "sin", 1, native_sin);
//!
//! // Add expression functions (mathematical expressions that can call other functions)
//! expr_context_add_expression_function(ctx, "distance", "x1,y1,x2,y2",
//!                                      "sqrt((x2-x1)^2 + (y2-y1)^2)");
//! expr_context_add_expression_function(ctx, "avg", "a,b", "(a+b)/2");
//!
//! // Create arena and batch
//! ExprArena* arena = expr_arena_new(8192);
//! ExprBatch* batch = expr_batch_new(arena);
//!
//! // Add expressions and parameters
//! expr_batch_add_expression(batch, "x + sin(y)");
//! expr_batch_add_expression(batch, "distance(0, 0, x, y)");
//! expr_batch_add_variable(batch, "x", 1.0);
//! expr_batch_add_variable(batch, "y", 3.14159);
//!
//! // Evaluate
//! expr_batch_evaluate(batch, ctx);
//! Real result1 = expr_batch_get_result(batch, 0);
//! Real result2 = expr_batch_get_result(batch, 1);
//!
//! // Remove expression functions when no longer needed
//! expr_context_remove_expression_function(ctx, "avg");
//!
//! // Cleanup
//! expr_batch_free(batch);
//! expr_arena_free(arena);
//! expr_context_free(ctx);
//! ```
//!

use crate::expression::Expression;
use crate::{EvalContext, Real};
use alloc::boxed::Box;
use alloc::string::ToString;
use alloc::vec::Vec;
use bumpalo::Bump;
use core::ffi::{CStr, c_char, c_void};
use core::ptr;

// Re-export for external visibility
pub use crate::expression::Expression as ExpressionExport;

// Magic numbers to detect valid vs freed batches
// Using 32-bit values for compatibility with 32-bit systems
const BATCH_MAGIC: usize = 0x7A9F4E82; // Random 32-bit value for valid batch
const BATCH_FREED: usize = 0x9C2E8B7D; // Random 32-bit value for freed batch

// Internal wrapper that owns both the arena and the batch
struct BatchWithArena {
    magic: usize,                    // Magic number for validation
    arena: *mut Bump,                // Raw pointer to the arena we leaked
    batch: *mut Expression<'static>, // Raw pointer to the batch
}

impl Drop for BatchWithArena {
    fn drop(&mut self) {
        // Mark as freed to detect double-free
        self.magic = BATCH_FREED;

        // Drop the batch first (it has references into the arena)
        if !self.batch.is_null() {
            unsafe {
                // Explicitly drop the batch
                drop(Box::from_raw(self.batch));
            }
            self.batch = ptr::null_mut();
        }
        // Then drop the arena - this should free Bumpalo's memory
        if !self.arena.is_null() {
            unsafe {
                // Get the arena back as a Box
                let mut arena_box = Box::from_raw(self.arena);
                // Reset it first to ensure all chunks are released
                arena_box.reset();
                // Now drop it - this should trigger Bump's Drop impl
                drop(arena_box);
            }
            self.arena = ptr::null_mut();
        }
    }
}

// ============================================================================
// Global Allocator - conditional based on custom_cbindgen_alloc feature
// ============================================================================

// Allocation tracking
#[cfg(feature = "alloc_tracking")]
static TOTAL_ALLOCATED: AtomicUsize = AtomicUsize::new(0);
#[cfg(feature = "alloc_tracking")]
static TOTAL_FREED: AtomicUsize = AtomicUsize::new(0);
#[cfg(feature = "alloc_tracking")]
static ALLOCATION_COUNT: AtomicUsize = AtomicUsize::new(0);
#[cfg(feature = "alloc_tracking")]
static FREE_COUNT: AtomicUsize = AtomicUsize::new(0);

// Detailed allocation tracking (when alloc_tracking feature is enabled)
#[cfg(feature = "alloc_tracking")]
mod allocation_tracking {
    use core::cell::RefCell;
    use critical_section::Mutex;
    use heapless::{FnvIndexMap, Vec};

    #[derive(Clone, Copy)]
    pub struct AllocationInfo {
        pub size: usize,
        pub line: u32,
        pub file: &'static str,
        pub ptr: usize,
        pub caller_addr: usize,  // First level caller address
        pub caller2_addr: usize, // Second level caller address
    }

    // ARM-specific function to get return addresses from stack
    #[cfg(target_arch = "arm")]
    unsafe fn get_caller_addresses() -> (usize, usize) {
        let lr: usize; // Link register (immediate caller)

        unsafe {
            // Get link register (return address of immediate caller)
            core::arch::asm!("mov {}, lr", out(reg) lr);
        }

        // Skip stack walking to avoid memory faults - just use link register
        (lr, 0)
    }

    // Fallback for non-ARM architectures
    #[cfg(not(target_arch = "arm"))]
    unsafe fn get_caller_addresses() -> (usize, usize) {
        (0, 0) // No stack walking support
    }

    const MAX_TRACKED_ALLOCATIONS: usize = 512;
    type TrackedAllocations = FnvIndexMap<usize, AllocationInfo, MAX_TRACKED_ALLOCATIONS>;

    static TRACKED_ALLOCATIONS: Mutex<RefCell<TrackedAllocations>> =
        Mutex::new(RefCell::new(TrackedAllocations::new()));

    pub fn track_allocation(ptr: *mut u8, size: usize, location: &'static core::panic::Location) {
        if ptr.is_null() {
            return;
        }

        // Get caller addresses using ARM stack walking
        let (caller_addr, caller2_addr) = unsafe { get_caller_addresses() };

        let info = AllocationInfo {
            size,
            line: location.line(),
            file: location.file(),
            ptr: ptr as usize,
            caller_addr,
            caller2_addr,
        };

        critical_section::with(|cs| {
            let mut tracked = TRACKED_ALLOCATIONS.borrow(cs).borrow_mut();
            // If we're at capacity, we'll just not track this allocation (silent failure)
            let _ = tracked.insert(ptr as usize, info);
        });
    }

    pub fn untrack_allocation(ptr: *mut u8) {
        if ptr.is_null() {
            return;
        }

        critical_section::with(|cs| {
            let mut tracked = TRACKED_ALLOCATIONS.borrow(cs).borrow_mut();
            tracked.remove(&(ptr as usize));
        });
    }

    pub fn get_remaining_allocations() -> Vec<AllocationInfo, MAX_TRACKED_ALLOCATIONS> {
        critical_section::with(|cs| {
            let tracked = TRACKED_ALLOCATIONS.borrow(cs).borrow();
            let mut result = Vec::new();
            for (_, info) in tracked.iter() {
                let _ = result.push(*info);
            }
            result
        })
    }
}

// When custom_cbindgen_alloc is enabled, use TlsfHeap for embedded targets
#[cfg(feature = "custom_cbindgen_alloc")]
mod embedded_allocator {
    use super::*;
    use core::alloc::{GlobalAlloc, Layout};
    use core::sync::atomic::{AtomicUsize, Ordering};
    use embedded_alloc::TlsfHeap;

    use core::sync::atomic::AtomicBool;

    // Wrapper around TlsfHeap to track allocations
    pub struct TrackingHeap {
        heap: TlsfHeap,
        initialized: AtomicBool,
    }

    impl TrackingHeap {
        pub const fn new() -> Self {
            Self {
                heap: TlsfHeap::empty(),
                initialized: AtomicBool::new(false),
            }
        }

        pub fn is_initialized(&self) -> bool {
            self.initialized.load(Ordering::Acquire)
        }

        pub unsafe fn init(&self, start_addr: usize, size: usize) {
            unsafe {
                self.heap.init(start_addr, size);
            }
            self.initialized.store(true, Ordering::Release);
        }

        // Ensure heap is initialized - panics if not explicitly initialized
        fn ensure_initialized(&self) {
            if !self.initialized.load(Ordering::Acquire) {
                // Heap was never explicitly initialized - this is an error
                panic!("Heap not initialized! Call exp_rs_heap_init() before any allocations");
            }
        }
    }

    unsafe impl GlobalAlloc for TrackingHeap {
        #[track_caller]
        unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
            self.ensure_initialized();
            let ptr = unsafe { self.heap.alloc(layout) };
            if !ptr.is_null() {
                #[cfg(feature = "alloc_tracking")]
                {
                    TOTAL_ALLOCATED.fetch_add(layout.size(), Ordering::Relaxed);
                    ALLOCATION_COUNT.fetch_add(1, Ordering::Relaxed);
                    // We can't get caller info from GlobalAlloc, but we can track the allocation
                    // For more detailed tracking, the user would need to use tracked wrapper functions
                    let location = core::panic::Location::caller();
                    allocation_tracking::track_allocation(ptr, layout.size(), location);
                }
            }
            ptr
        }

        #[track_caller]
        unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
            self.ensure_initialized();
            unsafe {
                self.heap.dealloc(ptr, layout);
            }
            #[cfg(feature = "alloc_tracking")]
            {
                TOTAL_FREED.fetch_add(layout.size(), Ordering::Relaxed);
                FREE_COUNT.fetch_add(1, Ordering::Relaxed);
            }

            // Detailed tracking if feature is enabled
            #[cfg(feature = "alloc_tracking")]
            {
                allocation_tracking::untrack_allocation(ptr);
            }
        }
    }

    // Global heap allocator using TLSF (Two-Level Segregated Fit) algorithm
    #[global_allocator]
    pub static HEAP: TrackingHeap = TrackingHeap::new();

    // No static heap allocation - memory provided by caller

    // Current configured heap size (initialized to 0, set by exp_rs_heap_init)
    pub static CURRENT_HEAP_SIZE: AtomicUsize = AtomicUsize::new(0);
}

// When custom_cbindgen_alloc is NOT enabled, use standard system allocator
#[cfg(not(feature = "custom_cbindgen_alloc"))]
mod system_allocator {
    extern crate std;
    use std::alloc::{GlobalAlloc, Layout, System};

    // Wrapper around System allocator to track allocations
    pub struct TrackingSystemHeap;

    unsafe impl GlobalAlloc for TrackingSystemHeap {
        #[track_caller]
        unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
            let ptr = unsafe { System.alloc(layout) };
            #[cfg(feature = "alloc_tracking")]
            if !ptr.is_null() {
                TOTAL_ALLOCATED.fetch_add(layout.size(), Ordering::Relaxed);
                ALLOCATION_COUNT.fetch_add(1, Ordering::Relaxed);
                let location = core::panic::Location::caller();
                allocation_tracking::track_allocation(ptr, layout.size(), location);
            }
            ptr
        }

        #[track_caller]
        unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
            unsafe {
                System.dealloc(ptr, layout);
            }
            #[cfg(feature = "alloc_tracking")]
            {
                TOTAL_FREED.fetch_add(layout.size(), Ordering::Relaxed);
                FREE_COUNT.fetch_add(1, Ordering::Relaxed);
                allocation_tracking::untrack_allocation(ptr);
            }
        }
    }

    // Global heap allocator using standard system allocator
    #[global_allocator]
    pub static HEAP: TrackingSystemHeap = TrackingSystemHeap;
}

// Initialize heap with provided memory buffer (only available with custom allocator)
// Returns 0 on success, negative error code on failure
#[cfg(feature = "custom_cbindgen_alloc")]
#[unsafe(no_mangle)]
pub extern "C" fn exp_rs_heap_init(heap_ptr: *mut u8, heap_size: usize) -> i32 {
    use embedded_allocator::*;

    // Validate parameters
    if heap_ptr.is_null() {
        return -1; // Null pointer
    }
    if heap_size == 0 {
        return -3; // Invalid heap size (must be non-zero)
    }

    // Check if already initialized
    if HEAP.is_initialized() {
        return -2; // Already initialized
    }

    unsafe {
        HEAP.init(heap_ptr as usize, heap_size);
        CURRENT_HEAP_SIZE.store(heap_size, core::sync::atomic::Ordering::Release);
    }
    0
}

// Get current configured heap size (only available with custom allocator)
#[cfg(feature = "custom_cbindgen_alloc")]
#[unsafe(no_mangle)]
pub extern "C" fn exp_rs_get_heap_size() -> usize {
    embedded_allocator::CURRENT_HEAP_SIZE.load(core::sync::atomic::Ordering::Acquire)
}

// Get allocation statistics for C code
#[cfg(feature = "alloc_tracking")]
#[unsafe(no_mangle)]
pub extern "C" fn exp_rs_get_total_allocated() -> usize {
    TOTAL_ALLOCATED.load(Ordering::Relaxed)
}

#[cfg(feature = "alloc_tracking")]
#[unsafe(no_mangle)]
pub extern "C" fn exp_rs_get_total_freed() -> usize {
    TOTAL_FREED.load(Ordering::Relaxed)
}

#[cfg(feature = "alloc_tracking")]
#[unsafe(no_mangle)]
pub extern "C" fn exp_rs_get_allocation_count() -> usize {
    ALLOCATION_COUNT.load(Ordering::Relaxed)
}

#[cfg(feature = "alloc_tracking")]
#[unsafe(no_mangle)]
pub extern "C" fn exp_rs_get_free_count() -> usize {
    FREE_COUNT.load(Ordering::Relaxed)
}

#[cfg(feature = "alloc_tracking")]
#[unsafe(no_mangle)]
pub extern "C" fn exp_rs_get_current_allocated() -> usize {
    let allocated = TOTAL_ALLOCATED.load(Ordering::Relaxed);
    let freed = TOTAL_FREED.load(Ordering::Relaxed);
    allocated.saturating_sub(freed)
}

// C-compatible allocation info struct
#[cfg(feature = "alloc_tracking")]
#[repr(C)]
#[derive(Clone, Copy)]
pub struct CAllocationInfo {
    pub size: usize,
    pub line: u32,
    pub file_ptr: *const c_char,
    pub ptr: usize,
    pub caller_addr: usize,  // First level caller address
    pub caller2_addr: usize, // Second level caller address
}

// Get count of remaining allocations (available with alloc_tracking feature)
#[cfg(feature = "alloc_tracking")]
#[unsafe(no_mangle)]
pub extern "C" fn exp_rs_get_remaining_allocation_count() -> usize {
    use allocation_tracking::*;
    let remaining = get_remaining_allocations();
    remaining.len()
}

// Get a single remaining allocation by index using ExprResult
// Returns allocation info in the result fields:
// - status: 0 on success, -1 if index out of bounds, -2 if no tracking
// - value: allocation size (as Real)
// - index: allocation line number
// - error: contains "file:ptr" format string
#[cfg(feature = "alloc_tracking")]
#[unsafe(no_mangle)]
pub extern "C" fn exp_rs_get_remaining_allocation_by_index(allocation_index: usize) -> ExprResult {
    use allocation_tracking::*;
    let remaining = get_remaining_allocations();

    if allocation_index >= remaining.len() {
        return ExprResult::from_ffi_error(-1, "Allocation index out of bounds");
    }

    let allocation = &remaining[allocation_index];

    // Create info string with caller addresses (limited formatting for no_std)
    // Format: "filename caller1 caller2" (space separated for parsing)
    let info_str = allocation.file;

    ExprResult {
        status: 0,
        value: allocation.size as Real,
        index: allocation.line as i32,
        error: ExprResult::copy_to_error_buffer(info_str),
    }
}

// Get remaining allocations data (available with alloc_tracking feature)
// Returns the number of allocations copied to the output buffer
// If output_buffer is null, returns the total count needed
#[cfg(feature = "alloc_tracking")]
#[unsafe(no_mangle)]
pub extern "C" fn exp_rs_get_remaining_allocations(
    output_buffer: *mut CAllocationInfo,
    buffer_size: usize,
) -> usize {
    use allocation_tracking::*;
    let remaining = get_remaining_allocations();

    if output_buffer.is_null() {
        return remaining.len();
    }

    let copy_count = core::cmp::min(remaining.len(), buffer_size);

    for (i, allocation) in remaining.iter().enumerate().take(copy_count) {
        unsafe {
            let c_info = CAllocationInfo {
                size: allocation.size,
                line: allocation.line,
                file_ptr: allocation.file.as_ptr() as *const c_char,
                ptr: allocation.ptr,
                caller_addr: allocation.caller_addr,
                caller2_addr: allocation.caller2_addr,
            };
            output_buffer.add(i).write(c_info);
        }
    }

    copy_count
}

// Critical section implementation for single-core ARM targets
#[cfg(all(target_arch = "arm", not(test)))]
#[unsafe(no_mangle)]
fn _critical_section_1_0_acquire() -> critical_section::RawRestoreState {
    // Read current PRIMASK state and disable interrupts
    let primask: u32;
    unsafe {
        core::arch::asm!("mrs {}, primask", out(reg) primask);
        core::arch::asm!("cpsid i");
    }
    primask
}

#[cfg(all(target_arch = "arm", not(test)))]
#[unsafe(no_mangle)]
unsafe fn _critical_section_1_0_release(restore_state: critical_section::RawRestoreState) {
    // Restore previous interrupt state
    if restore_state & 1 == 0 {
        // Interrupts were enabled before, re-enable them
        unsafe {
            core::arch::asm!("cpsie i");
        }
    }
    // If bit 0 was set, interrupts were already disabled, so leave them disabled
}

// Critical section implementation for native/host targets (tests and native builds)
#[cfg(not(all(target_arch = "arm", not(test))))]
#[unsafe(no_mangle)]
fn _critical_section_1_0_acquire() -> critical_section::RawRestoreState {
    // For native builds, we don't need real critical sections
    // Just return a dummy value - there are no interrupts to disable
    0
}

#[cfg(not(all(target_arch = "arm", not(test))))]
#[unsafe(no_mangle)]
unsafe fn _critical_section_1_0_release(_restore_state: critical_section::RawRestoreState) {
    // For native builds, no-op - there are no interrupts to restore
}

// ============================================================================
// Panic Handler Support
// ============================================================================

/// Global panic flag pointer - set by C code
#[allow(dead_code)]
static mut EXP_RS_PANIC_FLAG: *mut i32 = ptr::null_mut();

/// Global log function pointer - set by C code
#[allow(dead_code)]
static mut EXP_RS_LOG_FUNCTION: *const c_void = ptr::null();

/// Type for the logging function
#[allow(dead_code)]
type LogFunctionType = unsafe extern "C" fn(*const u8, usize);

/// Default panic message
#[allow(dead_code)]
static PANIC_DEFAULT_MSG: &[u8] = b"Rust panic occurred\0";

/// Register a panic handler
///
/// # Parameters
/// - `flag_ptr`: Pointer to an integer that will be set to 1 on panic
/// - `log_func`: Optional logging function pointer (can be NULL)
///
/// # Safety
/// The provided pointers must remain valid for the lifetime of the program
#[cfg(not(test))]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn exp_rs_register_panic_handler(
    flag_ptr: *mut i32,
    log_func: *const c_void,
) {
    unsafe {
        EXP_RS_PANIC_FLAG = flag_ptr;
        EXP_RS_LOG_FUNCTION = log_func;
    }
}

// ============================================================================
// Error Handling
// ============================================================================

/// Result structure for FFI operations
#[repr(C)]
pub struct ExprResult {
    /// Error code: 0 for success, positive for ExprError, negative for FFI errors
    status: i32,
    /// Result value (valid only if status == 0)
    value: Real,
    /// Result index (for functions that return an index)
    index: i32,
    /// Error message buffer (empty string on success, no freeing needed)
    error: [c_char; crate::types::EXP_RS_ERROR_BUFFER_SIZE],
}

impl ExprResult {
    /// Helper function to copy a string to the error buffer
    fn copy_to_error_buffer(msg: &str) -> [c_char; crate::types::EXP_RS_ERROR_BUFFER_SIZE] {
        let mut buffer = [0; crate::types::EXP_RS_ERROR_BUFFER_SIZE];
        let bytes = msg.as_bytes();
        let copy_len = core::cmp::min(bytes.len(), crate::types::EXP_RS_ERROR_BUFFER_SIZE - 1);

        for i in 0..copy_len {
            buffer[i] = bytes[i] as c_char;
        }
        buffer[copy_len] = 0; // Null terminator
        buffer
    }
    /// Create a success result with a value
    fn success_value(value: Real) -> Self {
        ExprResult {
            status: 0,
            value,
            index: 0,
            error: [0; crate::types::EXP_RS_ERROR_BUFFER_SIZE],
        }
    }

    /// Create a success result with an index
    fn success_index(index: usize) -> Self {
        ExprResult {
            status: 0,
            value: 0.0,
            index: index as i32,
            error: [0; crate::types::EXP_RS_ERROR_BUFFER_SIZE],
        }
    }

    /// Create an error result from an ExprError
    fn from_expr_error(err: crate::error::ExprError) -> Self {
        let error_code = err.error_code();
        let error_msg = err.to_string(); // Use Display trait

        ExprResult {
            status: error_code,
            value: Real::NAN,
            index: -1,
            error: Self::copy_to_error_buffer(&error_msg),
        }
    }

    /// Create an error result for FFI-specific errors
    fn from_ffi_error(code: i32, msg: &str) -> Self {
        ExprResult {
            status: code,
            value: Real::NAN,
            index: -1,
            error: Self::copy_to_error_buffer(msg),
        }
    }
}

/// FFI error codes (negative to distinguish from ExprError codes)
pub const FFI_ERROR_NULL_POINTER: i32 = -1;
pub const FFI_ERROR_INVALID_UTF8: i32 = -2;
pub const FFI_ERROR_NO_ARENA_AVAILABLE: i32 = -3;
pub const FFI_ERROR_CANNOT_GET_MUTABLE_ACCESS: i32 = -4;
pub const FFI_ERROR_INVALID_POINTER: i32 = -5;

// ============================================================================
// Opaque Types with Better Names
// ============================================================================

/// Opaque type for evaluation context
#[repr(C)]
pub struct ExprContext {
    _private: [u8; 0],
}

/// Opaque type for expression batch
#[repr(C)]
pub struct ExprBatch {
    _private: [u8; 0],
}

/// Opaque type for memory arena
#[repr(C)]
pub struct ExprArena {
    _private: [u8; 0],
}

// ============================================================================
// Native Function Support
// ============================================================================

/// Native function signature
pub type NativeFunc = extern "C" fn(args: *const Real, n_args: usize) -> Real;

// ============================================================================
// Context Management
// ============================================================================

/// Create a new evaluation context
///
/// The context holds function definitions and can be reused across evaluations.
///
/// # Returns
/// Pointer to new context, or NULL on allocation failure
///
/// # Safety
/// The returned pointer must be freed with expr_context_free()
#[unsafe(no_mangle)]
pub extern "C" fn expr_context_new() -> *mut ExprContext {
    let ctx = EvalContext::new();
    let ctx_rc = alloc::rc::Rc::new(ctx);
    let ctx = Box::new(ctx_rc);
    Box::into_raw(ctx) as *mut ExprContext
}

/// Create a new evaluation context without any pre-registered functions
///
/// This creates a context with no built-in functions or constants.
/// Note that basic operators (+, -, *, /, %, <, >, <=, >=, ==, !=) are still
/// available as they are handled by the parser, not the function registry.
///
/// # Returns
/// Pointer to new empty context, or NULL on allocation failure
///
/// # Safety
/// The returned pointer must be freed with expr_context_free()
///
/// # Example
/// ```c
/// ExprContext* ctx = expr_context_new_empty();
/// // Must register all functions manually
/// expr_context_add_function(ctx, "+", 2, add_func);
/// expr_context_add_function(ctx, "*", 2, mul_func);
/// ```
#[unsafe(no_mangle)]
pub extern "C" fn expr_context_new_empty() -> *mut ExprContext {
    let ctx = EvalContext::empty();
    let ctx_rc = alloc::rc::Rc::new(ctx);
    let ctx = Box::new(ctx_rc);
    Box::into_raw(ctx) as *mut ExprContext
}

/// Free an evaluation context
///
/// # Safety
/// - The pointer must have been created by expr_context_new()
/// - The pointer must not be used after calling this function
#[unsafe(no_mangle)]
pub extern "C" fn expr_context_free(ctx: *mut ExprContext) {
    if ctx.is_null() {
        return;
    }
    unsafe {
        let _ = Box::from_raw(ctx as *mut alloc::rc::Rc<EvalContext>);
    }
}

/// Get the count of native functions in a context
#[unsafe(no_mangle)]
pub extern "C" fn expr_context_native_function_count(ctx: *const ExprContext) -> usize {
    if ctx.is_null() {
        return 0;
    }

    unsafe {
        let ctx = &*(ctx as *const alloc::rc::Rc<EvalContext>);
        ctx.list_native_functions().len()
    }
}

/// Get a native function name by index
/// Returns the length of the name, or 0 if index is out of bounds
/// If buffer is NULL, just returns the length needed
#[unsafe(no_mangle)]
pub extern "C" fn expr_context_get_native_function_name(
    ctx: *const ExprContext,
    index: usize,
    buffer: *mut u8,
    buffer_size: usize,
) -> usize {
    if ctx.is_null() {
        return 0;
    }

    unsafe {
        let ctx = &*(ctx as *const alloc::rc::Rc<EvalContext>);
        let functions = ctx.list_native_functions();

        if index >= functions.len() {
            return 0;
        }

        let name = &functions[index];
        let name_bytes = name.as_bytes();

        if buffer.is_null() {
            return name_bytes.len();
        }

        let copy_len = core::cmp::min(name_bytes.len(), buffer_size);
        core::ptr::copy_nonoverlapping(name_bytes.as_ptr(), buffer, copy_len);

        name_bytes.len()
    }
}

/// Add a native function to the context
///
/// # Parameters
/// - `ctx`: The context
/// - `name`: Function name (must be valid UTF-8)
/// - `arity`: Number of arguments the function expects
/// - `func`: Function pointer
///
/// # Returns
/// 0 on success, non-zero on error
#[unsafe(no_mangle)]
pub extern "C" fn expr_context_add_function(
    ctx: *mut ExprContext,
    name: *const c_char,
    arity: usize,
    func: NativeFunc,
) -> i32 {
    if ctx.is_null() || name.is_null() {
        return -1;
    }

    let ctx_handle = unsafe { &mut *(ctx as *mut alloc::rc::Rc<EvalContext>) };

    let name_cstr = unsafe { CStr::from_ptr(name) };
    let name_str = match name_cstr.to_str() {
        Ok(s) => s,
        Err(_) => return -2, // Invalid UTF-8
    };

    // Create a wrapper that calls the C function
    let implementation = move |args: &[Real]| -> Real {
        if args.len() != arity {
            return Real::NAN;
        }
        func(args.as_ptr(), args.len())
    };

    // Get mutable access to register the function
    match alloc::rc::Rc::get_mut(ctx_handle) {
        Some(ctx_mut) => {
            match ctx_mut.register_native_function(name_str, arity, implementation) {
                Ok(_) => 0,
                Err(_) => -3, // Registration failed
            }
        }
        None => -4, // Cannot get mutable access
    }
}

/// Add an expression function to a batch
///
/// Expression functions are mathematical expressions that can call other functions.
/// They are specific to this batch and take precedence over context functions.
///
/// # Parameters
/// - `batch`: The batch
/// - `name`: Function name (must be valid UTF-8)
/// - `params`: Comma-separated parameter names (e.g., "x,y,z")
/// - `expression`: The expression string defining the function
///
/// # Returns
/// 0 on success, non-zero on error
#[unsafe(no_mangle)]
pub extern "C" fn expr_batch_add_expression_function(
    batch: *mut ExprBatch,
    name: *const c_char,
    params: *const c_char,
    expression: *const c_char,
) -> i32 {
    if batch.is_null() || name.is_null() || params.is_null() || expression.is_null() {
        return -1;
    }

    let wrapper = unsafe { &*(batch as *const BatchWithArena) };
    let builder = unsafe { &mut *wrapper.batch };

    // Parse strings
    let name_cstr = unsafe { CStr::from_ptr(name) };
    let name_str = match name_cstr.to_str() {
        Ok(s) => s,
        Err(_) => return -2, // Invalid UTF-8
    };

    let params_cstr = unsafe { CStr::from_ptr(params) };
    let params_str = match params_cstr.to_str() {
        Ok(s) => s,
        Err(_) => return -2, // Invalid UTF-8
    };

    let expr_cstr = unsafe { CStr::from_ptr(expression) };
    let expr_str = match expr_cstr.to_str() {
        Ok(s) => s,
        Err(_) => return -2, // Invalid UTF-8
    };

    // Split parameters by comma
    let param_vec: Vec<&str> = if params_str.is_empty() {
        Vec::new()
    } else {
        params_str.split(',').map(|s| s.trim()).collect()
    };

    // Register function
    match builder.register_expression_function(name_str, &param_vec, expr_str) {
        Ok(_) => 0,
        Err(_) => -3, // Registration failed
    }
}

/// Remove an expression function from a batch
///
/// # Parameters
/// - `batch`: The batch
/// - `name`: Function name to remove
///
/// # Returns
/// - 1 if the function was removed
/// - 0 if the function didn't exist
/// - negative error code on failure
#[unsafe(no_mangle)]
pub extern "C" fn expr_batch_remove_expression_function(
    batch: *mut ExprBatch,
    name: *const c_char,
) -> i32 {
    if batch.is_null() || name.is_null() {
        return -1;
    }

    let wrapper = unsafe { &*(batch as *const BatchWithArena) };
    let builder = unsafe { &mut *wrapper.batch };

    let name_cstr = unsafe { CStr::from_ptr(name) };
    let name_str = match name_cstr.to_str() {
        Ok(s) => s,
        Err(_) => return -2, // Invalid UTF-8
    };

    match builder.unregister_expression_function(name_str) {
        Ok(was_removed) => {
            if was_removed {
                1
            } else {
                0
            }
        }
        Err(_) => -3, // Error
    }
}

// ============================================================================
// Arena Management - DEPRECATED (arena is now managed internally by batch)
// ============================================================================

// These functions are no longer needed as the batch now manages its own arena.
// They are kept here commented out for reference.

// /// Create a new memory arena
// ///
// /// # Parameters
// /// - `size_hint`: Suggested size in bytes (0 for default)
// ///
// /// # Returns
// /// Pointer to new arena, or NULL on allocation failure
// ///
// /// # Safety
// /// The returned pointer must be freed with expr_arena_free()
// #[unsafe(no_mangle)]
// pub extern "C" fn expr_arena_new(size_hint: usize) -> *mut ExprArena {
//     let size = if size_hint == 0 { 8192 } else { size_hint };
//     let arena = Box::new(Bump::with_capacity(size));
//     Box::into_raw(arena) as *mut ExprArena
// }

// /// Free a memory arena
// ///
// /// # Safety
// /// - The pointer must have been created by expr_arena_new()
// /// - All batches using this arena must be freed first
// #[unsafe(no_mangle)]
// pub extern "C" fn expr_arena_free(arena: *mut ExprArena) {
//     if arena.is_null() {
//         return;
//     }
//     unsafe {
//         let _ = Box::from_raw(arena as *mut Bump);
//     }
// }

// /// Reset an arena for reuse
// ///
// /// This clears all allocations but keeps the memory for reuse.
// ///
// /// # Safety
// /// No references to arena-allocated data must exist
// #[unsafe(no_mangle)]
// pub extern "C" fn expr_arena_reset(arena: *mut ExprArena) {
//     if arena.is_null() {
//         return;
//     }
//     let arena = unsafe { &mut *(arena as *mut Bump) };
//     arena.reset();
// }

// ============================================================================
// Batch Evaluation (Primary API)
// ============================================================================

/// Create a new expression batch with its own arena
///
/// This creates both an arena and a batch in a single allocation.
/// The arena is automatically sized based on the size_hint parameter.
///
/// # Parameters
/// - `size_hint`: Suggested arena size in bytes (0 for default of 8KB)
///
/// # Returns
/// Pointer to new batch, or NULL on failure
///
/// # Safety
/// - The returned pointer must be freed with expr_batch_free()
#[unsafe(no_mangle)]
pub extern "C" fn expr_batch_new(size_hint: usize) -> *mut ExprBatch {
    // Use default size if 0 is passed
    let arena_size = if size_hint == 0 { 8192 } else { size_hint };

    // Create the arena and leak it to get a 'static reference
    let arena = Box::new(Bump::with_capacity(arena_size));
    let arena_ptr = Box::into_raw(arena);
    let arena_ref: &'static Bump = unsafe { &*arena_ptr };

    // Create the batch with the leaked arena reference
    let batch = Box::new(Expression::new(arena_ref));
    let batch_ptr = Box::into_raw(batch);

    // Create the wrapper that tracks both pointers for cleanup
    let wrapper = Box::new(BatchWithArena {
        magic: BATCH_MAGIC,
        arena: arena_ptr,
        batch: batch_ptr,
    });

    Box::into_raw(wrapper) as *mut ExprBatch
}

/// Check if a batch pointer is valid (not freed or corrupted)
///
/// # Parameters
/// - `batch`: The batch pointer to check
///
/// # Returns
/// - ExprResult with status 0 and value 1.0 if the batch is valid
/// - ExprResult with error status and message describing the issue if invalid
///
/// # Safety
/// The pointer should have been created by expr_batch_new()
#[unsafe(no_mangle)]
pub extern "C" fn expr_batch_is_valid(batch: *const ExprBatch) -> ExprResult {
    if batch.is_null() {
        return ExprResult::from_ffi_error(FFI_ERROR_NULL_POINTER, "Batch pointer is NULL");
    }

    unsafe {
        let wrapper = batch as *const BatchWithArena;
        let magic = (*wrapper).magic;

        if magic == BATCH_MAGIC {
            // Valid batch - return success with value 1.0
            ExprResult::success_value(1.0)
        } else if magic == BATCH_FREED {
            // Batch has been freed
            ExprResult::from_ffi_error(
                FFI_ERROR_INVALID_POINTER,
                "Batch has already been freed (double-free detected)",
            )
        } else {
            // Invalid/corrupted pointer
            // Use a static message since format! isn't available in no_std
            ExprResult::from_ffi_error(
                FFI_ERROR_INVALID_POINTER,
                "Invalid or corrupted batch pointer",
            )
        }
    }
}

/// Free an expression batch and its arena
///
/// This frees both the batch and its associated arena in one operation.
///
/// # Safety
/// The pointer must have been created by expr_batch_new()
#[unsafe(no_mangle)]
pub extern "C" fn expr_batch_free(batch: *mut ExprBatch) {
    if batch.is_null() {
        return;
    }

    unsafe {
        // Check the magic number to detect double-free
        let wrapper = batch as *mut BatchWithArena;
        let magic = (*wrapper).magic;

        if magic == BATCH_FREED {
            // Already freed - this is a double-free attempt
            // In debug builds, we could panic here. In release, just return safely.
            #[cfg(debug_assertions)]
            panic!("Double-free detected on ExprBatch at {:p}", batch);

            #[cfg(not(debug_assertions))]
            return; // Silently ignore in release mode
        }

        if magic != BATCH_MAGIC {
            // Invalid magic - this pointer wasn't created by expr_batch_new
            // or memory corruption occurred
            #[cfg(debug_assertions)]
            panic!(
                "Invalid ExprBatch pointer at {:p} (magic: 0x{:x})",
                batch, magic
            );

            #[cfg(not(debug_assertions))]
            return; // Silently ignore in release mode
        }

        // Valid batch - proceed with cleanup
        let _ = Box::from_raw(wrapper);
    }
}

/// Clear all expressions, parameters, and results from a batch
///
/// This allows the batch to be reused without recreating it. The arena memory
/// used by previous expressions remains allocated but unused until the arena
/// is reset. This is safer than freeing and recreating the batch.
///
/// # Parameters
/// - `batch`: The batch to clear
///
/// # Returns
/// 0 on success, negative error code on failure
///
/// # Safety
/// The pointer must have been created by expr_batch_new()
#[unsafe(no_mangle)]
pub extern "C" fn expr_batch_clear(batch: *mut ExprBatch) -> i32 {
    if batch.is_null() {
        return FFI_ERROR_NULL_POINTER;
    }

    unsafe {
        let wrapper = &mut *(batch as *mut BatchWithArena);

        // Validate magic number
        if wrapper.magic != BATCH_MAGIC {
            #[cfg(debug_assertions)]
            panic!(
                "Invalid or freed ExprBatch pointer at {:p} (magic: 0x{:x})",
                batch, wrapper.magic
            );

            #[cfg(not(debug_assertions))]
            return FFI_ERROR_INVALID_POINTER; // Return error in release mode
        }

        (*wrapper.batch).clear();
    }

    0
}

/// Add an expression to the batch
///
/// # Parameters
/// - `batch`: The batch
/// - `expr`: Expression string (must be valid UTF-8)
///
/// # Returns
/// ExprResult with index on success, or error details on failure
#[unsafe(no_mangle)]
pub extern "C" fn expr_batch_add_expression(
    batch: *mut ExprBatch,
    expr: *const c_char,
) -> ExprResult {
    if batch.is_null() || expr.is_null() {
        return ExprResult::from_ffi_error(
            FFI_ERROR_NULL_POINTER,
            "Null pointer passed to expr_batch_add_expression",
        );
    }

    let wrapper = unsafe { &*(batch as *const BatchWithArena) };
    let builder = unsafe { &mut *wrapper.batch };

    let expr_cstr = unsafe { CStr::from_ptr(expr) };
    let expr_str = match expr_cstr.to_str() {
        Ok(s) => s,
        Err(_) => {
            return ExprResult::from_ffi_error(
                FFI_ERROR_INVALID_UTF8,
                "Invalid UTF-8 in expression string",
            );
        }
    };

    match builder.add_expression(expr_str) {
        Ok(idx) => ExprResult::success_index(idx),
        Err(e) => ExprResult::from_expr_error(e),
    }
}

/// Add a variable to the batch
///
/// # Parameters
/// - `batch`: The batch
/// - `name`: Variable name (must be valid UTF-8)
/// - `value`: Initial value
///
/// # Returns
/// ExprResult with index on success, or error details on failure
#[unsafe(no_mangle)]
pub extern "C" fn expr_batch_add_variable(
    batch: *mut ExprBatch,
    name: *const c_char,
    value: Real,
) -> ExprResult {
    if batch.is_null() || name.is_null() {
        return ExprResult::from_ffi_error(
            FFI_ERROR_NULL_POINTER,
            "Null pointer passed to expr_batch_add_variable",
        );
    }

    let wrapper = unsafe { &*(batch as *const BatchWithArena) };
    let builder = unsafe { &mut *wrapper.batch };

    let name_cstr = unsafe { CStr::from_ptr(name) };
    let name_str = match name_cstr.to_str() {
        Ok(s) => s,
        Err(_) => {
            return ExprResult::from_ffi_error(
                FFI_ERROR_INVALID_UTF8,
                "Invalid UTF-8 in variable name",
            );
        }
    };

    match builder.add_parameter(name_str, value) {
        Ok(idx) => ExprResult::success_index(idx),
        Err(e) => ExprResult::from_expr_error(e),
    }
}

/// Update a variable value by index
///
/// # Parameters
/// - `batch`: The batch
/// - `index`: Variable index from expr_batch_add_variable()
/// - `value`: New value
///
/// # Returns
/// 0 on success, negative error code on failure
#[unsafe(no_mangle)]
pub extern "C" fn expr_batch_set_variable(batch: *mut ExprBatch, index: usize, value: Real) -> i32 {
    if batch.is_null() {
        return -1;
    }

    let wrapper = unsafe { &*(batch as *const BatchWithArena) };
    let builder = unsafe { &mut *wrapper.batch };

    match builder.set_param(index, value) {
        Ok(_) => 0,
        Err(_) => -2, // Invalid index
    }
}

/// Evaluate all expressions in the batch
///
/// # Parameters
/// - `batch`: The batch
/// - `ctx`: Optional context with functions (can be NULL)
///
/// # Returns
/// 0 on success, negative error code on failure
#[unsafe(no_mangle)]
pub extern "C" fn expr_batch_evaluate(batch: *mut ExprBatch, ctx: *mut ExprContext) -> i32 {
    if batch.is_null() {
        return -1;
    }

    let wrapper = unsafe { &*(batch as *const BatchWithArena) };
    let builder = unsafe { &mut *wrapper.batch };

    let eval_ctx = if ctx.is_null() {
        alloc::rc::Rc::new(EvalContext::new())
    } else {
        unsafe {
            let ctx_rc = &*(ctx as *const alloc::rc::Rc<EvalContext>);
            ctx_rc.clone()
        }
    };

    match builder.eval(&eval_ctx) {
        Ok(_) => 0,
        Err(_) => -2, // Evaluation error
    }
}

/// Get the result of an expression
///
/// # Parameters
/// - `batch`: The batch
/// - `index`: Expression index from expr_batch_add_expression()
///
/// # Returns
/// Result value, or NaN if index is invalid
#[unsafe(no_mangle)]
pub extern "C" fn expr_batch_get_result(batch: *const ExprBatch, index: usize) -> Real {
    if batch.is_null() {
        return Real::NAN;
    }

    let wrapper = unsafe { &*(batch as *const BatchWithArena) };
    let builder = unsafe { &*wrapper.batch };
    builder.get_result(index).unwrap_or(Real::NAN)
}

/// Get the high water mark of arena memory usage for a batch
///
/// # Parameters
/// - `batch`: The batch
///
/// # Returns
/// Number of bytes currently allocated in the batch's arena.
/// This represents the maximum memory usage of the arena.
#[unsafe(no_mangle)]
pub extern "C" fn expr_batch_arena_bytes(batch: *const ExprBatch) -> usize {
    if batch.is_null() {
        return 0;
    }

    let wrapper = unsafe { &*(batch as *const BatchWithArena) };
    let builder = unsafe { &*wrapper.batch };
    builder.arena_allocated_bytes()
}

/// Evaluate all expressions in the batch with detailed error reporting
///
/// # Parameters
/// - `batch`: The batch
/// - `ctx`: Optional context with functions (can be NULL)
///
/// # Returns
/// ExprResult with status 0 on success, or error details on failure
#[unsafe(no_mangle)]
pub extern "C" fn expr_batch_evaluate_ex(
    batch: *mut ExprBatch,
    ctx: *mut ExprContext,
) -> ExprResult {
    if batch.is_null() {
        return ExprResult::from_ffi_error(FFI_ERROR_NULL_POINTER, "Null batch pointer");
    }

    let wrapper = unsafe { &*(batch as *const BatchWithArena) };
    let builder = unsafe { &mut *wrapper.batch };

    let eval_ctx = if ctx.is_null() {
        alloc::rc::Rc::new(EvalContext::new())
    } else {
        unsafe {
            let ctx_rc = &*(ctx as *const alloc::rc::Rc<EvalContext>);
            ctx_rc.clone()
        }
    };

    match builder.eval(&eval_ctx) {
        Ok(_) => ExprResult::success_value(0.0), // No specific value for batch eval
        Err(e) => ExprResult::from_expr_error(e),
    }
}

// ============================================================================
// Utility Functions
// ============================================================================

/// Estimate arena size needed for expressions
///
/// # Parameters
/// - `expression_count`: Number of expressions
/// - `total_expr_length`: Total length of all expression strings
/// - `param_count`: Number of parameters
/// - `estimated_iterations`: Estimated evaluation iterations
///
/// # Returns
/// Recommended arena size in bytes
#[unsafe(no_mangle)]
pub extern "C" fn expr_estimate_arena_size(
    expression_count: usize,
    total_expr_length: usize,
    param_count: usize,
    _estimated_iterations: usize,
) -> usize {
    // Base overhead per expression (AST nodes, etc)
    let expr_overhead = expression_count * 512;

    // String storage
    let string_storage = total_expr_length * 2;

    // Parameter storage
    let param_storage = param_count * 64;

    // Add 50% buffer
    let total = expr_overhead + string_storage + param_storage;
    total + (total / 2)
}

// ============================================================================
// Test-only Panic Trigger
// ============================================================================

/// Force a panic for testing purposes (only available in debug builds)
#[cfg(debug_assertions)]
#[unsafe(no_mangle)]
pub extern "C" fn exp_rs_test_trigger_panic() {
    panic!("Test panic triggered from C");
}

// ============================================================================
// Panic Handler Implementation
// ============================================================================

/// Panic handler for no_std environments (ARM targets)
#[cfg(all(not(test), target_arch = "arm"))]
#[panic_handler]
fn panic(info: &core::panic::PanicInfo) -> ! {
    // Try to set the panic flag to let C code know about the panic
    unsafe {
        if !EXP_RS_PANIC_FLAG.is_null() {
            *EXP_RS_PANIC_FLAG = 1;
        }

        // Try to log if we have a logging function
        if !EXP_RS_LOG_FUNCTION.is_null() {
            // Cast the raw pointer to a function pointer and call it
            let log_func: LogFunctionType = core::mem::transmute(EXP_RS_LOG_FUNCTION);

            // Try to extract panic information
            // Note: The .message() method was removed in newer Rust versions
            // We'll use location information which is more stable
            if let Some(location) = info.location() {
                // Create a simple message with file and line info
                let file = location.file();
                let _line = location.line(); // We have line number but can't easily format it in no_std

                // Log the file path first
                log_func(file.as_ptr(), file.len());

                // In a no_std environment, we can't easily format strings with line numbers
                // The C side logger can at least see which file panicked
            } else {
                // Fallback to default message
                log_func(PANIC_DEFAULT_MSG.as_ptr(), PANIC_DEFAULT_MSG.len() - 1);
            }
        }
    }

    // Trigger a fault that the debugger can catch
    #[cfg(target_arch = "arm")]
    loop {
        unsafe {
            // Trigger a HardFault by executing an undefined instruction
            // This allows the debugger to catch the fault and inspect the state
            core::arch::asm!("udf #0");
        }
        // If the fault handler returns, we'll trigger it again
        // This prevents execution from continuing past the panic
    }

    // Fallback for non-ARM architectures
    #[cfg(not(target_arch = "arm"))]
    loop {
        // Busy loop for debugging - debugger can break here
        core::hint::spin_loop();
    }
}

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

    #[test]
    fn test_error_buffer_null_termination() {
        use core::ffi::c_char;

        // Test normal message (well within buffer size)
        let short_msg = "Test error message";
        let buffer = ExprResult::copy_to_error_buffer(short_msg);

        // Find the null terminator
        let mut found_null = false;
        for (i, &byte) in buffer.iter().enumerate() {
            if byte == 0 {
                found_null = true;
                // Verify the message is correct up to null terminator
                let recovered_msg = unsafe {
                    core::str::from_utf8_unchecked(core::slice::from_raw_parts(
                        buffer.as_ptr() as *const u8,
                        i,
                    ))
                };
                assert_eq!(recovered_msg, short_msg);
                break;
            }
        }
        assert!(found_null, "Error buffer should be null terminated");

        // Test maximum length message (exactly buffer size - 1)
        let max_msg = "a".repeat(crate::types::EXP_RS_ERROR_BUFFER_SIZE - 1);
        let buffer = ExprResult::copy_to_error_buffer(&max_msg);

        // Last byte should be null terminator
        assert_eq!(buffer[crate::types::EXP_RS_ERROR_BUFFER_SIZE - 1], 0);

        // Second-to-last byte should contain message data
        assert_eq!(
            buffer[crate::types::EXP_RS_ERROR_BUFFER_SIZE - 2],
            b'a' as c_char
        );

        // Test over-length message (gets truncated)
        let long_msg = "a".repeat(crate::types::EXP_RS_ERROR_BUFFER_SIZE + 10);
        let buffer = ExprResult::copy_to_error_buffer(&long_msg);

        // Last byte should still be null terminator
        assert_eq!(buffer[crate::types::EXP_RS_ERROR_BUFFER_SIZE - 1], 0);

        // Message should be truncated but still valid
        let recovered_msg = unsafe {
            core::str::from_utf8_unchecked(core::slice::from_raw_parts(
                buffer.as_ptr() as *const u8,
                crate::types::EXP_RS_ERROR_BUFFER_SIZE - 1,
            ))
        };
        assert_eq!(
            recovered_msg.len(),
            crate::types::EXP_RS_ERROR_BUFFER_SIZE - 1
        );
        assert!(recovered_msg.chars().all(|c| c == 'a'));
    }
}