cairo-native 0.2.6

A compiler to convert Cairo's intermediate representation Sierra code to MLIR.
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
//! # Various utilities

pub(crate) use self::{
    block_ext::{BlockExt, GepIndex},
    program_registry_ext::ProgramRegistryExt,
    range_ext::RangeExt,
};
use crate::{metadata::MetadataStorage, OptLevel};
use cairo_lang_compiler::CompilerConfig;
use cairo_lang_runner::token_gas_cost;
use cairo_lang_sierra::{
    extensions::gas::CostTokenType,
    ids::FunctionId,
    program::{GenFunction, Program, StatementIdx},
};
use melior::{
    ir::Module,
    pass::{self, PassManager},
    Context, Error, ExecutionEngine,
};
use num_bigint::{BigInt, BigUint, Sign};
use serde::{Deserialize, Serialize};
use starknet_types_core::felt::Felt;
use std::sync::{Arc, LazyLock};
use std::{
    alloc::Layout,
    borrow::Cow,
    fmt::{self, Display},
    path::Path,
};
use thiserror::Error;

mod block_ext;
pub mod mem_tracing;
mod program_registry_ext;
mod range_ext;

#[cfg(target_os = "macos")]
pub const SHARED_LIBRARY_EXT: &str = "dylib";
#[cfg(target_os = "linux")]
pub const SHARED_LIBRARY_EXT: &str = "so";

/// The `felt252` prime modulo.
pub static PRIME: LazyLock<BigUint> = LazyLock::new(|| {
    "3618502788666131213697322783095070105623107215331596699973092056135872020481"
        .parse()
        .expect("hardcoded prime constant should be valid")
});
pub static HALF_PRIME: LazyLock<BigUint> = LazyLock::new(|| {
    "1809251394333065606848661391547535052811553607665798349986546028067936010240"
        .parse()
        .expect("hardcoded half prime constant should be valid")
});

#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
pub struct BuiltinCosts {
    pub r#const: u64,
    pub pedersen: u64,
    pub bitwise: u64,
    pub ecop: u64,
    pub poseidon: u64,
    pub add_mod: u64,
    pub mul_mod: u64,
}

impl From<BuiltinCosts> for [u64; 7] {
    // Order matters, for the libfunc impl
    // https://github.com/starkware-libs/sequencer/blob/1b7252f8a30244d39614d7666aa113b81291808e/crates/blockifier/src/execution/entry_point_execution.rs#L208
    fn from(value: BuiltinCosts) -> Self {
        [
            value.r#const,
            value.pedersen,
            value.bitwise,
            value.ecop,
            value.poseidon,
            value.add_mod,
            value.mul_mod,
        ]
    }
}

impl Default for BuiltinCosts {
    fn default() -> Self {
        Self {
            r#const: token_gas_cost(CostTokenType::Const) as u64,
            pedersen: token_gas_cost(CostTokenType::Pedersen) as u64,
            bitwise: token_gas_cost(CostTokenType::Bitwise) as u64,
            ecop: token_gas_cost(CostTokenType::EcOp) as u64,
            poseidon: token_gas_cost(CostTokenType::Poseidon) as u64,
            add_mod: token_gas_cost(CostTokenType::AddMod) as u64,
            mul_mod: token_gas_cost(CostTokenType::MulMod) as u64,
        }
    }
}

#[cfg(feature = "with-mem-tracing")]
#[allow(unused_imports)]
pub(crate) use self::mem_tracing::{
    _wrapped_free as libc_free, _wrapped_malloc as libc_malloc, _wrapped_realloc as libc_realloc,
};
#[cfg(not(feature = "with-mem-tracing"))]
#[allow(unused_imports)]
pub(crate) use libc::{free as libc_free, malloc as libc_malloc, realloc as libc_realloc};

/// Generate a function name.
///
/// If the program includes function identifiers, return those. Otherwise return `f` followed by the
/// identifier number.
pub fn generate_function_name(
    function_id: &FunctionId,
    is_for_contract_executor: bool,
) -> Cow<str> {
    // Generic functions can omit their type in the debug_name, leading to multiple functions
    // having the same name, we solve this by adding the id number even if the function has a debug_name

    if is_for_contract_executor {
        Cow::Owned(format!("f{}", function_id.id))
    } else if let Some(name) = function_id.debug_name.as_deref() {
        Cow::Owned(format!("{}(f{})", name, function_id.id))
    } else {
        Cow::Owned(format!("f{}", function_id.id))
    }
}

/// Decode an UTF-8 error message replacing invalid bytes with their hexadecimal representation, as
/// done by Python's `x.decode('utf-8', errors='backslashreplace')`.
pub fn decode_error_message(data: &[u8]) -> String {
    let mut pos = 0;
    utf8_iter::ErrorReportingUtf8Chars::new(data).fold(String::new(), |mut acc, ch| {
        match ch {
            Ok(ch) => {
                acc.push(ch);
                pos += ch.len_utf8();
            }
            Err(_) => {
                acc.push_str(&format!("\\x{:02x}", data[pos]));
                pos += 1;
            }
        };

        acc
    })
}

/// Return the layout for an integer of arbitrary width.
///
/// This assumes the platform's maximum (effective) alignment is 16 bytes, and that every integer
/// with a size in bytes of a power of two has the same alignment as its size.
pub fn get_integer_layout(width: u32) -> Layout {
    if width == 0 {
        Layout::new::<()>()
    } else if width <= 8 {
        Layout::new::<u8>()
    } else if width <= 16 {
        Layout::new::<u16>()
    } else if width <= 32 {
        Layout::new::<u32>()
    } else if width <= 64 {
        Layout::new::<u64>()
    } else if width <= 128 {
        Layout::new::<u128>()
    } else {
        // According to the docs this should never return an error.
        Layout::from_size_align((width as usize).next_multiple_of(8) >> 3, 16)
            .expect("only fails if size is greater than ISIZE::MAX")
    }
}

/// Compile a cairo program found at the given path to sierra.
pub fn cairo_to_sierra(program: &Path) -> crate::error::Result<Arc<Program>> {
    if program
        .extension()
        .map(|x| {
            x.to_ascii_lowercase()
                .to_string_lossy()
                .eq_ignore_ascii_case("cairo")
        })
        .unwrap_or(false)
    {
        cairo_lang_compiler::compile_cairo_project_at_path(
            program,
            CompilerConfig {
                replace_ids: true,
                ..Default::default()
            },
        )
        .map_err(|err| crate::error::Error::ProgramParser(err.to_string()))
    } else {
        let source = std::fs::read_to_string(program)?;
        cairo_lang_sierra::ProgramParser::new()
            .parse(&source)
            .map_err(|err| crate::error::Error::ProgramParser(err.to_string()))
    }
    .map(Arc::new)
}

/// Returns the given entry point if present.
pub fn find_entry_point<'a>(
    program: &'a Program,
    entry_point: &str,
) -> Option<&'a GenFunction<StatementIdx>> {
    program
        .funcs
        .iter()
        .find(|x| x.id.debug_name.as_deref() == Some(entry_point))
}

/// Returns the given entry point if present.
pub fn find_entry_point_by_idx(
    program: &Program,
    entry_point_idx: usize,
) -> Option<&GenFunction<StatementIdx>> {
    program
        .funcs
        .iter()
        .find(|x| x.id.id == entry_point_idx as u64)
}

/// Given a string representing a function name, searches in the program for the id corresponding
/// to said function, and returns a reference to it.
#[track_caller]
pub fn find_function_id<'a>(program: &'a Program, function_name: &str) -> Option<&'a FunctionId> {
    program
        .funcs
        .iter()
        .find(|x| x.id.debug_name.as_deref() == Some(function_name))
        .map(|func| &func.id)
}

/// Parse a numeric string into felt, wrapping negatives around the prime modulo.
pub fn felt252_str(value: &str) -> Felt {
    let value = value
        .parse::<BigInt>()
        .expect("value must be a digit number");

    let value = match value.sign() {
        Sign::Minus => &*PRIME - value.magnitude(),
        _ => value.magnitude().clone(),
    };

    value.into()
}

/// Parse any type that can be a bigint to a felt that can be used in the cairo-native input.
pub fn felt252_bigint(value: impl Into<BigInt>) -> Felt {
    let value: BigInt = value.into();
    let value = match value.sign() {
        Sign::Minus => Cow::Owned(&*PRIME - value.magnitude()),
        _ => Cow::Borrowed(value.magnitude()),
    };

    value.as_ref().into()
}

/// Parse a short string into a felt that can be used in the cairo-native input.
pub fn felt252_short_str(value: &str) -> Felt {
    let values: Vec<_> = value
        .chars()
        .filter_map(|c| c.is_ascii().then_some(c as u8))
        .collect();

    assert!(values.len() < 32, "A felt can't longer than 32 bytes");
    Felt::from_bytes_be_slice(&values)
}

/// Creates the execution engine, with all symbols registered.
pub fn create_engine(
    module: &Module,
    _metadata: &MetadataStorage,
    opt_level: OptLevel,
) -> ExecutionEngine {
    // Create the JIT engine.
    let engine = ExecutionEngine::new(module, opt_level.into(), &[], false);

    #[cfg(feature = "with-runtime")]
    register_runtime_symbols(&engine);

    #[cfg(feature = "with-debug-utils")]
    _metadata
        .get::<crate::metadata::debug_utils::DebugUtils>()
        .unwrap()
        .register_impls(&engine);

    #[cfg(feature = "with-mem-tracing")]
    self::mem_tracing::register_bindings(&engine);

    engine
}

pub fn run_pass_manager(context: &Context, module: &mut Module) -> Result<(), Error> {
    let pass_manager = PassManager::new(context);
    pass_manager.enable_verifier(true);
    pass_manager.add_pass(pass::transform::create_canonicalizer());
    pass_manager.add_pass(pass::conversion::create_scf_to_control_flow()); // needed because to_llvm doesn't include it.
    pass_manager.add_pass(pass::conversion::create_to_llvm());
    pass_manager.run(module)
}

#[cfg(feature = "with-runtime")]
pub fn register_runtime_symbols(engine: &ExecutionEngine) {
    use cairo_native_runtime::FeltDict;

    unsafe {
        engine.register_symbol(
            "cairo_native__libfunc__debug__print",
            cairo_native_runtime::cairo_native__libfunc__debug__print
                as *const fn(i32, *const [u8; 32], usize) -> i32 as *mut (),
        );

        engine.register_symbol(
            "cairo_native__libfunc__pedersen",
            cairo_native_runtime::cairo_native__libfunc__pedersen
                as *const fn(*mut u8, *mut u8, *mut u8) -> () as *mut (),
        );

        engine.register_symbol(
            "cairo_native__libfunc__hades_permutation",
            cairo_native_runtime::cairo_native__libfunc__hades_permutation
                as *const fn(*mut u8, *mut u8, *mut u8) -> () as *mut (),
        );

        engine.register_symbol(
            "cairo_native__libfunc__ec__ec_point_from_x_nz",
            cairo_native_runtime::cairo_native__libfunc__ec__ec_point_from_x_nz
                as *const fn(*mut [[u8; 32]; 2]) -> bool as *mut (),
        );

        engine.register_symbol(
            "cairo_native__libfunc__ec__ec_state_add",
            cairo_native_runtime::cairo_native__libfunc__ec__ec_state_add
                as *const fn(*mut [[u8; 32]; 4], *const [[u8; 32]; 2]) -> bool
                as *mut (),
        );

        engine.register_symbol(
            "cairo_native__libfunc__ec__ec_state_init",
            cairo_native_runtime::cairo_native__libfunc__ec__ec_state_init
                as *const fn(*mut [[u8; 32]; 4]) as *mut (),
        );

        engine.register_symbol(
            "cairo_native__libfunc__ec__ec_state_add_mul",
            cairo_native_runtime::cairo_native__libfunc__ec__ec_state_add_mul
                as *const fn(*mut [[u8; 32]; 4], *const [u8; 32], *const [[u8; 32]; 2]) -> bool
                as *mut (),
        );

        engine.register_symbol(
            "cairo_native__libfunc__ec__ec_state_try_finalize_nz",
            cairo_native_runtime::cairo_native__libfunc__ec__ec_state_try_finalize_nz
                as *const fn(*const [[u8; 32]; 2], *mut [[u8; 32]; 4]) -> bool
                as *mut (),
        );

        engine.register_symbol(
            "cairo_native__libfunc__ec__ec_point_try_new_nz",
            cairo_native_runtime::cairo_native__libfunc__ec__ec_point_try_new_nz
                as *const fn(*const [[u8; 32]; 2]) -> bool as *mut (),
        );

        engine.register_symbol(
            "cairo_native__dict_new",
            cairo_native_runtime::cairo_native__dict_new as *const fn() -> *mut FeltDict as *mut (),
        );

        engine.register_symbol(
            "cairo_native__dict_drop",
            cairo_native_runtime::cairo_native__dict_drop
                as *const fn(*mut FeltDict, Option<extern "C" fn(*mut std::ffi::c_void)>) -> ()
                as *mut (),
        );

        engine.register_symbol(
            "cairo_native__dict_dup",
            cairo_native_runtime::cairo_native__dict_dup
                as *const fn(
                    *mut FeltDict,
                    extern "C" fn(*mut std::ffi::c_void) -> *mut std::ffi::c_void,
                ) -> *mut FeltDict as *mut (),
        );

        engine.register_symbol(
            "cairo_native__dict_get",
            cairo_native_runtime::cairo_native__dict_get
                as *const fn(*mut FeltDict, &[u8; 32]) -> *mut std::ffi::c_void
                as *mut (),
        );

        engine.register_symbol(
            "cairo_native__dict_gas_refund",
            cairo_native_runtime::cairo_native__dict_gas_refund as *const fn(*const FeltDict) -> u64
                as *mut (),
        );

        engine.register_symbol(
            "cairo_native__set_costs_builtin",
            cairo_native_runtime::cairo_native__set_costs_builtin as *const fn(*const u64) -> ()
                as *mut (),
        );

        engine.register_symbol(
            "cairo_native__get_costs_builtin",
            cairo_native_runtime::cairo_native__get_costs_builtin as *const fn() -> *const u64
                as *mut (),
        );

        #[cfg(feature = "with-cheatcode")]
        {
            engine.register_symbol(
                "cairo_native__vtable_cheatcode",
                crate::starknet::cairo_native__vtable_cheatcode as *mut (),
            );
        }
    }
}

/// Return a type that calls a closure when formatted using [Debug](std::fmt::Debug).
pub fn debug_with<F>(fmt: F) -> impl fmt::Debug
where
    F: Fn(&mut fmt::Formatter) -> fmt::Result,
{
    struct FmtWrapper<F>(F)
    where
        F: Fn(&mut fmt::Formatter) -> fmt::Result;

    impl<F> fmt::Debug for FmtWrapper<F>
    where
        F: Fn(&mut fmt::Formatter) -> fmt::Result,
    {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            self.0(f)
        }
    }

    FmtWrapper(fmt)
}

/// Edit: Copied from the std lib.
///
/// Returns the amount of padding we must insert after `layout`
/// to ensure that the following address will satisfy `align`
/// (measured in bytes).
///
/// e.g., if `layout.size()` is 9, then `layout.padding_needed_for(4)`
/// returns 3, because that is the minimum number of bytes of
/// padding required to get a 4-aligned address (assuming that the
/// corresponding memory block starts at a 4-aligned address).
///
/// The return value of this function has no meaning if `align` is
/// not a power-of-two.
///
/// Note that the utility of the returned value requires `align`
/// to be less than or equal to the alignment of the starting
/// address for the whole allocated block of memory. One way to
/// satisfy this constraint is to ensure `align <= layout.align()`.
#[inline]
pub const fn padding_needed_for(layout: &Layout, align: usize) -> usize {
    let len = layout.size();

    // Rounded up value is:
    //   len_rounded_up = (len + align - 1) & !(align - 1);
    // and then we return the padding difference: `len_rounded_up - len`.
    //
    // We use modular arithmetic throughout:
    //
    // 1. align is guaranteed to be > 0, so align - 1 is always
    //    valid.
    //
    // 2. `len + align - 1` can overflow by at most `align - 1`,
    //    so the &-mask with `!(align - 1)` will ensure that in the
    //    case of overflow, `len_rounded_up` will itself be 0.
    //    Thus the returned padding, when added to `len`, yields 0,
    //    which trivially satisfies the alignment `align`.
    //
    // (Of course, attempts to allocate blocks of memory whose
    // size and padding overflow in the above manner should cause
    // the allocator to yield an error anyway.)

    let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
    len_rounded_up.wrapping_sub(len)
}

#[derive(Clone, PartialEq, Eq, Debug, Error)]
pub struct LayoutError;

impl Display for LayoutError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("layout error")
    }
}

/// Copied from std.
///
/// Creates a layout describing the record for `n` instances of
/// `self`, with a suitable amount of padding between each to
/// ensure that each instance is given its requested size and
/// alignment. On success, returns `(k, offs)` where `k` is the
/// layout of the array and `offs` is the distance between the start
/// of each element in the array.
///
/// On arithmetic overflow, returns `LayoutError`.
//#[unstable(feature = "alloc_layout_extra", issue = "55724")]
#[inline]
pub fn layout_repeat(layout: &Layout, n: usize) -> Result<(Layout, usize), LayoutError> {
    // This cannot overflow. Quoting from the invariant of Layout:
    // > `size`, when rounded up to the nearest multiple of `align`,
    // > must not overflow isize (i.e., the rounded value must be
    // > less than or equal to `isize::MAX`)
    let padded_size = layout.size() + padding_needed_for(layout, layout.align());
    let alloc_size = padded_size.checked_mul(n).ok_or(LayoutError)?;

    // The safe constructor is called here to enforce the isize size limit.
    let layout = Layout::from_size_align(alloc_size, layout.align()).map_err(|_| LayoutError)?;
    Ok((layout, padded_size))
}

#[cfg(test)]
pub mod test {
    use crate::{
        context::NativeContext, execution_result::ExecutionResult, executor::JitNativeExecutor,
        starknet_stub::StubSyscallHandler, utils::*, values::Value,
    };
    use cairo_lang_compiler::{
        compile_prepared_db, db::RootDatabase, diagnostics::DiagnosticsReporter,
        project::setup_project, CompilerConfig,
    };
    use cairo_lang_filesystem::db::init_dev_corelib;
    use cairo_lang_sierra::{
        ids::FunctionId,
        program::Program,
        program::{FunctionSignature, GenFunction, StatementIdx},
    };
    use cairo_lang_starknet::{compile::compile_contract_in_prepared_db, starknet_plugin_suite};
    use cairo_lang_starknet_classes::contract_class::ContractClass;
    use pretty_assertions_sorted::assert_eq;
    use std::io::Write;
    use std::{env::var, fmt::Formatter, fs, path::Path};

    macro_rules! load_cairo {
        ( $( $program:tt )+ ) => {
            $crate::utils::test::load_cairo_str(stringify!($($program)+))
        };
    }
    macro_rules! load_starknet {
        ( $( $program:tt )+ ) => {
            $crate::utils::test::load_starknet_str(stringify!($($program)+))
        };
    }
    macro_rules! load_starknet_contract {
        ( $( $program:tt )+ ) => {
            $crate::utils::test::load_starknet_contract_str(stringify!($($program)+))
        };
    }
    pub(crate) use load_cairo;
    pub(crate) use load_starknet;
    pub(crate) use load_starknet_contract;

    // Helper macros for faster testing.
    macro_rules! jit_struct {
        ($($y:expr),* $(,)? ) => {
            crate::values::Value::Struct {
                fields: vec![$($y), *],
                debug_name: None
            }
        };
    }
    macro_rules! jit_enum {
        ( $tag:expr, $value:expr ) => {
            crate::values::Value::Enum {
                tag: $tag,
                value: Box::new($value),
                debug_name: None,
            }
        };
    }
    macro_rules! jit_dict {
        ( $($key:expr $(=>)+ $value:expr),* $(,)? ) => {
            crate::values::Value::Felt252Dict {
                value: {
                    let mut map = std::collections::HashMap::new();
                    $(map.insert($key.into(), $value.into());)*
                    map
                },
                debug_name: None,
            }
        };
    }
    macro_rules! jit_panic {
        ( $($value:expr)? ) => {
            crate::utils::test::jit_enum!(1, crate::utils::test::jit_struct!(
                crate::utils::test::jit_struct!(),
                [$($value), *].into()
            ))
        };
    }
    pub(crate) use jit_dict;
    pub(crate) use jit_enum;
    pub(crate) use jit_panic;
    pub(crate) use jit_struct;

    pub(crate) fn load_cairo_str(program_str: &str) -> (String, Program) {
        compile_program(program_str, RootDatabase::default())
    }

    pub(crate) fn load_starknet_str(program_str: &str) -> (String, Program) {
        compile_program(
            program_str,
            RootDatabase::builder()
                .with_plugin_suite(starknet_plugin_suite())
                .build()
                .unwrap(),
        )
    }

    pub(crate) fn load_starknet_contract_str(program_str: &str) -> (String, ContractClass) {
        compile_contract(
            program_str,
            RootDatabase::builder()
                .with_plugin_suite(starknet_plugin_suite())
                .build()
                .unwrap(),
        )
    }

    pub(crate) fn compile_contract(
        program_str: &str,
        mut db: RootDatabase,
    ) -> (String, ContractClass) {
        let mut program_file = tempfile::Builder::new()
            .prefix("test_")
            .suffix(".cairo")
            .tempfile()
            .unwrap();
        fs::write(&mut program_file, program_str).unwrap();

        init_dev_corelib(
            &mut db,
            Path::new(&var("CARGO_MANIFEST_DIR").unwrap()).join("corelib/src"),
        );
        let main_crate_ids = setup_project(&mut db, program_file.path()).unwrap();
        let contract = compile_contract_in_prepared_db(
            &db,
            None,
            main_crate_ids,
            CompilerConfig {
                diagnostics_reporter: DiagnosticsReporter::stderr(),
                replace_ids: true,
                ..Default::default()
            },
        )
        .unwrap();

        let module_name = program_file.path().with_extension("");
        let module_name = module_name.file_name().unwrap().to_str().unwrap();
        (module_name.to_string(), contract)
    }

    pub(crate) fn compile_program(program_str: &str, mut db: RootDatabase) -> (String, Program) {
        let mut program_file = tempfile::Builder::new()
            .prefix("test_")
            .suffix(".cairo")
            .tempfile()
            .unwrap();
        fs::write(&mut program_file, program_str).unwrap();

        init_dev_corelib(
            &mut db,
            Path::new(&var("CARGO_MANIFEST_DIR").unwrap()).join("corelib/src"),
        );
        let main_crate_ids = setup_project(&mut db, program_file.path()).unwrap();
        let sierra_program_with_dbg = compile_prepared_db(
            &db,
            main_crate_ids,
            CompilerConfig {
                diagnostics_reporter: DiagnosticsReporter::stderr(),
                replace_ids: true,
                ..Default::default()
            },
        )
        .unwrap();

        let module_name = program_file.path().with_extension("");
        let module_name = module_name.file_name().unwrap().to_str().unwrap();
        (module_name.to_string(), sierra_program_with_dbg.program)
    }

    pub fn run_program(
        program: &(String, Program),
        entry_point: &str,
        args: &[Value],
    ) -> ExecutionResult {
        let entry_point = format!("{0}::{0}::{1}", program.0, entry_point);
        let program = &program.1;

        let entry_point_id = &program
            .funcs
            .iter()
            .find(|x| x.id.debug_name.as_deref() == Some(&entry_point))
            .expect("Test program entry point not found.")
            .id;

        let context = NativeContext::new();

        let module = context
            .compile(program, false, Some(Default::default()))
            .expect("Could not compile test program to MLIR.");

        let executor = JitNativeExecutor::from_native_module(module, OptLevel::Less).unwrap();
        executor
            .invoke_dynamic_with_syscall_handler(
                entry_point_id,
                args,
                Some(u64::MAX),
                &mut StubSyscallHandler::default(),
            )
            .unwrap()
    }

    #[track_caller]
    pub fn run_program_assert_output(
        program: &(String, Program),
        entry_point: &str,
        args: &[Value],
        output: Value,
    ) {
        let result = run_program(program, entry_point, args);
        assert_eq!(result.return_value, output);
    }

    // ==============================
    // == TESTS: get_integer_layout
    // ==============================
    /// Ensures that the host's `u8` is compatible with its compiled counterpart.
    #[test]
    fn test_alignment_compatibility_u8() {
        assert_eq!(get_integer_layout(8).align(), 1);
    }

    /// Ensures that the host's `u16` is compatible with its compiled counterpart.
    #[test]
    fn test_alignment_compatibility_u16() {
        assert_eq!(get_integer_layout(16).align(), 2);
    }

    /// Ensures that the host's `u32` is compatible with its compiled counterpart.
    #[test]
    fn test_alignment_compatibility_u32() {
        assert_eq!(get_integer_layout(32).align(), 4);
    }

    /// Ensures that the host's `u64` is compatible with its compiled counterpart.
    #[test]
    fn test_alignment_compatibility_u64() {
        assert_eq!(get_integer_layout(64).align(), 8);
    }

    /// Ensures that the host's `u128` is compatible with its compiled counterpart.
    #[test]
    fn test_alignment_compatibility_u128() {
        assert_eq!(get_integer_layout(128).align(), 16);
    }

    /// Ensures that the host's `u256` is compatible with its compiled counterpart.
    #[test]
    fn test_alignment_compatibility_u256() {
        assert_eq!(get_integer_layout(256).align(), 16);
    }

    /// Ensures that the host's `u512` is compatible with its compiled counterpart.
    #[test]
    fn test_alignment_compatibility_u512() {
        assert_eq!(get_integer_layout(512).align(), 16);
    }

    /// Ensures that the host's `Felt` is compatible with its compiled counterpart.
    #[test]
    fn test_alignment_compatibility_felt() {
        assert_eq!(get_integer_layout(252).align(), 16);
    }

    // ==============================
    // == TESTS: find_entry_point
    // ==============================
    #[test]
    fn test_find_entry_point_with_empty_program() {
        let program = Program {
            type_declarations: vec![],
            libfunc_declarations: vec![],
            statements: vec![],
            funcs: vec![],
        };
        let entry_point = find_entry_point(&program, "entry_point");
        assert!(entry_point.is_none());
    }

    #[test]
    fn test_entry_point_not_found() {
        let program = Program {
            type_declarations: vec![],
            libfunc_declarations: vec![],
            statements: vec![],
            funcs: vec![GenFunction {
                id: FunctionId {
                    id: 0,
                    debug_name: Some("not_entry_point".into()),
                },
                signature: FunctionSignature {
                    ret_types: vec![],
                    param_types: vec![],
                },
                params: vec![],
                entry_point: StatementIdx(0),
            }],
        };
        let entry_point = find_entry_point(&program, "entry_point");
        assert!(entry_point.is_none());
    }

    #[test]
    fn test_entry_point_found() {
        let program = Program {
            type_declarations: vec![],
            libfunc_declarations: vec![],
            statements: vec![],
            funcs: vec![GenFunction {
                id: FunctionId {
                    id: 0,
                    debug_name: Some("entry_point".into()),
                },
                signature: FunctionSignature {
                    ret_types: vec![],
                    param_types: vec![],
                },
                params: vec![],
                entry_point: StatementIdx(0),
            }],
        };
        let entry_point = find_entry_point(&program, "entry_point");
        assert!(entry_point.is_some());
        assert_eq!(entry_point.unwrap().id.id, 0);
    }

    // ====================================
    // == TESTS: find_entry_point_by_idx
    // ====================================
    #[test]
    fn test_find_entry_point_by_idx_with_empty_program() {
        let program = Program {
            type_declarations: vec![],
            libfunc_declarations: vec![],
            statements: vec![],
            funcs: vec![],
        };
        let entry_point = find_entry_point_by_idx(&program, 0);
        assert!(entry_point.is_none());
    }

    #[test]
    fn test_entry_point_not_found_by_id() {
        let program = Program {
            type_declarations: vec![],
            libfunc_declarations: vec![],
            statements: vec![],
            funcs: vec![GenFunction {
                id: FunctionId {
                    id: 0,
                    debug_name: Some("some_name".into()),
                },
                signature: FunctionSignature {
                    ret_types: vec![],
                    param_types: vec![],
                },
                params: vec![],
                entry_point: StatementIdx(0),
            }],
        };
        let entry_point = find_entry_point_by_idx(&program, 1);
        assert!(entry_point.is_none());
    }

    #[test]
    fn test_entry_point_found_by_id() {
        let program = Program {
            type_declarations: vec![],
            libfunc_declarations: vec![],
            statements: vec![],
            funcs: vec![GenFunction {
                id: FunctionId {
                    id: 15,
                    debug_name: Some("some_name".into()),
                },
                signature: FunctionSignature {
                    ret_types: vec![],
                    param_types: vec![],
                },
                params: vec![],
                entry_point: StatementIdx(0),
            }],
        };
        let entry_point = find_entry_point_by_idx(&program, 15);
        assert!(entry_point.is_some());
        assert_eq!(entry_point.unwrap().id.id, 15);
    }

    #[test]
    fn decode_error_message() {
        // Checkout [issue 795](https://github.com/lambdaclass/cairo_native/issues/795) for context.
        assert_eq!(
            super::decode_error_message(&[
                97, 114, 103, 101, 110, 116, 47, 109, 117, 108, 116, 105, 99, 97, 108, 108, 45,
                102, 97, 105, 108, 101, 100, 3, 232, 78, 97, 116, 105, 118, 101, 32, 101, 120, 101,
                99, 117, 116, 105, 111, 110, 32, 101, 114, 114, 111, 114, 58, 32, 69, 114, 114,
                111, 114, 32, 97, 116, 32, 112, 99, 61, 48, 58, 49, 48, 52, 58, 10, 71, 111, 116,
                32, 97, 110, 32, 101, 120, 99, 101, 112, 116, 105, 111, 110, 32, 119, 104, 105,
                108, 101, 32, 101, 120, 101, 99, 117, 116, 105, 110, 103, 32, 97, 32, 104, 105,
                110, 116, 58, 32, 69, 114, 114, 111, 114, 32, 97, 116, 32, 112, 99, 61, 48, 58, 49,
                56, 52, 58, 10, 71, 111, 116, 32, 97, 110, 32, 101, 120, 99, 101, 112, 116, 105,
                111, 110, 32, 119, 104, 105, 108, 101, 32, 101, 120, 101, 99, 117, 116, 105, 110,
                103, 32, 97, 32, 104, 105, 110, 116, 58, 32, 69, 120, 99, 101, 101, 100, 101, 100,
                32, 116, 104, 101, 32, 109, 97, 120, 105, 109, 117, 109, 32, 110, 117, 109, 98,
                101, 114, 32, 111, 102, 32, 101, 118, 101, 110, 116, 115, 44, 32, 110, 117, 109,
                98, 101, 114, 32, 101, 118, 101, 110, 116, 115, 58, 32, 49, 48, 48, 49, 44, 32,
                109, 97, 120, 32, 110, 117, 109, 98, 101, 114, 32, 101, 118, 101, 110, 116, 115,
                58, 32, 49, 48, 48, 48, 46, 10, 67, 97, 105, 114, 111, 32, 116, 114, 97, 99, 101,
                98, 97, 99, 107, 32, 40, 109, 111, 115, 116, 32, 114, 101, 99, 101, 110, 116, 32,
                99, 97, 108, 108, 32, 108, 97, 115, 116, 41, 58, 10, 85, 110, 107, 110, 111, 119,
                110, 32, 108, 111, 99, 97, 116, 105, 111, 110, 32, 40, 112, 99, 61, 48, 58, 49, 52,
                51, 52, 41, 10, 85, 110, 107, 110, 111, 119, 110, 32, 108, 111, 99, 97, 116, 105,
                111, 110, 32, 40, 112, 99, 61, 48, 58, 49, 51, 57, 53, 41, 10, 85, 110, 107, 110,
                111, 119, 110, 32, 108, 111, 99, 97, 116, 105, 111, 110, 32, 40, 112, 99, 61, 48,
                58, 57, 53, 51, 41, 10, 85, 110, 107, 110, 111, 119, 110, 32, 108, 111, 99, 97,
                116, 105, 111, 110, 32, 40, 112, 99, 61, 48, 58, 51, 51, 57, 41, 10, 10, 67, 97,
                105, 114, 111, 32, 116, 114, 97, 99, 101, 98, 97, 99, 107, 32, 40, 109, 111, 115,
                116, 32, 114, 101, 99, 101, 110, 116, 32, 99, 97, 108, 108, 32, 108, 97, 115, 116,
                41, 58, 10, 85, 110, 107, 110, 111, 119, 110, 32, 108, 111, 99, 97, 116, 105, 111,
                110, 32, 40, 112, 99, 61, 48, 58, 49, 54, 55, 56, 41, 10, 85, 110, 107, 110, 111,
                119, 110, 32, 108, 111, 99, 97, 116, 105, 111, 110, 32, 40, 112, 99, 61, 48, 58,
                49, 54, 54, 52, 41, 10
            ]),
            "argent/multicall-failed\x03\\xe8Native execution error: Error at pc=0:104:\nGot an exception while executing a hint: Error at pc=0:184:\nGot an exception while executing a hint: Exceeded the maximum number of events, number events: 1001, max number events: 1000.\nCairo traceback (most recent call last):\nUnknown location (pc=0:1434)\nUnknown location (pc=0:1395)\nUnknown location (pc=0:953)\nUnknown location (pc=0:339)\n\nCairo traceback (most recent call last):\nUnknown location (pc=0:1678)\nUnknown location (pc=0:1664)\n",
        );
    }

    // ==============================
    // == TESTS: felt252_str
    // ==============================
    #[test]
    #[should_panic(expected = "value must be a digit number")]
    fn test_felt252_str_invalid_input() {
        let value = "not_a_number";
        felt252_str(value);
    }

    #[test]
    fn test_felt252_str_positive_number() {
        let value = "123";
        let result = felt252_str(value);
        assert_eq!(result, 123.into());
    }

    #[test]
    fn test_felt252_str_negative_number() {
        let value = "-123";
        let result = felt252_str(value);
        assert_eq!(
            result,
            Felt::from_dec_str(
                "3618502788666131213697322783095070105623107215331596699973092056135872020358"
            )
            .unwrap()
        );
    }

    #[test]
    fn test_felt252_str_zero() {
        let value = "0";
        let result = felt252_str(value);
        assert_eq!(result, Felt::ZERO);
    }

    // ==============================
    // == TESTS: felt252_short_str
    // ==============================
    #[test]
    fn test_felt252_short_str_short_numeric_string() {
        let value = "12345";
        let result = felt252_short_str(value);
        assert_eq!(result, 211295614005u64.into());
    }

    #[test]
    fn test_felt252_short_str_short_string_with_non_numeric_characters() {
        let value = "hello";
        let result = felt252_short_str(value);
        assert_eq!(result, 448378203247u64.into());
    }

    #[test]
    #[should_panic]
    fn test_felt252_short_str_long_numeric_string() {
        felt252_short_str("1234567890123456789012345678901234567890");
    }

    #[test]
    fn test_felt252_short_str_empty_string() {
        let value = "";
        let result = felt252_short_str(value);
        assert_eq!(result, Felt::ZERO);
    }

    #[test]
    fn test_felt252_short_str_string_with_non_ascii_characters() {
        let value = "h€llø";
        let result = felt252_short_str(value);
        assert_eq!(result, 6843500.into());
    }

    // ==============================
    // == TESTS: debug_with
    // ==============================
    #[test]
    fn test_debug_with_empty_closure() {
        let closure = |_f: &mut Formatter| -> fmt::Result { Ok(()) };
        let debug_wrapper = debug_with(closure);
        assert_eq!(format!("{:?}", debug_wrapper), "");
    }

    #[test]
    #[should_panic]
    fn test_debug_with_error_closure() {
        let closure = |_f: &mut Formatter| -> Result<(), fmt::Error> { Err(fmt::Error) };
        let debug_wrapper = debug_with(closure);
        let _ = format!("{:?}", debug_wrapper);
    }

    #[test]
    fn test_debug_with_simple_closure() {
        let closure = |f: &mut fmt::Formatter| write!(f, "Hello, world!");
        let debug_wrapper = debug_with(closure);
        assert_eq!(format!("{:?}", debug_wrapper), "Hello, world!");
    }

    #[test]
    fn test_debug_with_complex_closure() {
        let closure = |f: &mut fmt::Formatter| write!(f, "Name: William, Age: {}", 28);
        let debug_wrapper = debug_with(closure);
        assert_eq!(format!("{:?}", debug_wrapper), "Name: William, Age: 28");
    }

    #[test]
    fn test_generate_function_name_debug_name() {
        let function_id = FunctionId {
            id: 123,
            debug_name: Some("function_name".into()),
        };

        assert_eq!(
            generate_function_name(&function_id, false),
            "function_name(f123)"
        );
    }

    #[test]
    fn test_generate_function_name_debug_name_for_contract_executor() {
        let function_id = FunctionId {
            id: 123,
            debug_name: Some("function_name".into()),
        };

        assert_eq!(generate_function_name(&function_id, true), "f123");
    }

    #[test]
    fn test_generate_function_name_without_debug_name() {
        let function_id = FunctionId {
            id: 123,
            debug_name: None,
        };

        assert_eq!(generate_function_name(&function_id, false), "f123");
    }

    #[test]
    fn test_cairo_to_sierra_path() {
        // Define the path to the cairo program.
        let program_path = Path::new("programs/examples/hello.cairo");
        // Compile the cairo program to sierra.
        let sierra_program = cairo_to_sierra(program_path).unwrap();

        // Define the entry point function for comparison.
        let entry_point = "hello::hello::greet";
        // Find the function ID of the entry point function in the sierra program.
        let entry_point_id = find_function_id(&sierra_program, entry_point).unwrap();

        // Assert that the debug name of the entry point function matches the expected value.
        assert_eq!(
            entry_point_id.debug_name,
            Some("hello::hello::greet".into())
        );
    }

    #[test]
    fn test_cairo_to_sierra_source() {
        // Define the content of the cairo program as a string.
        let content = "type u8 = u8;";

        // Create a named temporary file and write the content to it.
        let mut file = tempfile::NamedTempFile::new().unwrap();
        file.write_all(content.as_bytes()).unwrap();
        // Get the path of the temporary file.
        let file_path = file.path().to_path_buf();

        // Compile the cairo program to sierra using the path of the temporary file.
        let sierra_program = cairo_to_sierra(&file_path).unwrap();

        // Assert that the sierra program has no library function declarations, statements, or functions.
        assert!(sierra_program.libfunc_declarations.is_empty());
        assert!(sierra_program.statements.is_empty());
        assert!(sierra_program.funcs.is_empty());

        // Assert that the debug name of the first type declaration matches the expected value.
        assert_eq!(sierra_program.type_declarations.len(), 1);
        assert_eq!(
            sierra_program.type_declarations[0].id.debug_name,
            Some("u8".into())
        );
    }
}