simplicityhl 0.6.0-rc.0

Rust-like language that compiles to Simplicity bytecode.
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
//! Library for parsing and compiling SimplicityHL

pub mod array;
pub mod ast;
pub mod compile;
pub mod debug;
#[cfg(feature = "docs")]
pub mod docs;
pub mod driver;
pub mod dummy_env;
pub mod error;
pub mod jet;
pub mod lexer;
pub mod named;
pub mod num;
pub mod parse;
pub mod pattern;
pub mod resolution;
#[cfg(feature = "serde")]
mod serde;
pub mod str;
#[cfg(test)]
pub mod test_utils;
pub mod tracker;
pub mod types;
pub mod value;
mod witness;

use std::sync::Arc;

use simplicity::jet::elements::ElementsEnv;
use simplicity::{jet::Elements, CommitNode, RedeemNode};

pub extern crate either;
pub extern crate simplicity;
pub use simplicity::elements;

use crate::debug::DebugSymbols;
use crate::driver::DependencyGraph;
use crate::error::{ErrorCollector, WithContent, WithSource as _};
use crate::parse::ParseFromStrWithErrors;
use crate::resolution::{DependencyMap, SourceFile};
pub use crate::types::ResolvedType;
pub use crate::value::Value;
pub use crate::witness::{Arguments, Parameters, WitnessTypes, WitnessValues};

/// The template of a SimplicityHL program.
///
/// A template has parameterized values that need to be supplied with arguments.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TemplateProgram {
    simfony: ast::Program,
    file: Arc<str>,
}

impl TemplateProgram {
    // TODO: Consider passing `CanonSourceFile`` deeper into the driver to avoid paying the path canonicalization cost multiple times.
    /// Parse the template of a SimplicityHL program.
    ///
    /// ## Errors
    ///
    /// The string is not a valid SimplicityHL program.
    pub fn new_with_dep(
        source: SourceFile,
        dependency_map: &DependencyMap,
    ) -> Result<Self, String> {
        let mut error_handler = ErrorCollector::new();

        // 1. Parse root file
        let parsed_program =
            parse::Program::parse_from_str_with_errors(source.clone(), &mut error_handler)
                .ok_or_else(|| error_handler.to_string())?;

        // 2. Create the driver program
        let driver_program: driver::Program = if dependency_map.is_empty() {
            driver::Program::from_parse(&parsed_program, source.content(), &mut error_handler)
                .ok_or_else(|| error_handler.to_string())?
        } else {
            let graph = DependencyGraph::new(
                source.clone(),
                Arc::from(dependency_map.clone()),
                &parsed_program,
                &mut error_handler,
            )?
            .ok_or_else(|| error_handler.to_string())?;

            graph
                .linearize_and_build(&mut error_handler)?
                .ok_or_else(|| error_handler.to_string())?
        };

        // 3. AST Analysis
        let ast_program = ast::Program::analyze(&driver_program).with_source(source.clone())?;
        Ok(Self {
            simfony: ast_program,
            file: source.content(),
        })
    }

    /// Parse the template of a SimplicityHL program.
    ///
    /// ## Errors
    ///
    /// The string is not a valid SimplicityHL program.
    pub fn new<Str: Into<Arc<str>>>(s: Str) -> Result<Self, String> {
        let file = s.into();
        let source = SourceFile::anonymous(file.clone());
        let mut error_handler = ErrorCollector::new();
        let parse_program = parse::Program::parse_from_str_with_errors(source, &mut error_handler);

        let driver_program = if let Some(parse_program) = parse_program {
            driver::Program::from_parse(&parse_program, file.clone(), &mut error_handler)
        } else {
            None
        };

        if let Some(program) = driver_program {
            let ast_program = ast::Program::analyze(&program).with_content(Arc::clone(&file))?;
            Ok(Self {
                simfony: ast_program,
                file,
            })
        } else {
            Err(ErrorCollector::to_string(&error_handler))?
        }
    }

    /// Access the parameters of the program.
    pub fn parameters(&self) -> &Parameters {
        self.simfony.parameters()
    }

    /// Access the witness types of the program.
    pub fn witness_types(&self) -> &WitnessTypes {
        self.simfony.witness_types()
    }

    /// Instantiate the template program with the given `arguments`.
    ///
    /// ## Errors
    ///
    /// The arguments are not consistent with the parameters of the program.
    /// Use [`TemplateProgram::parameters`] to see which parameters the program has.
    pub fn instantiate(
        &self,
        arguments: Arguments,
        include_debug_symbols: bool,
    ) -> Result<CompiledProgram, String> {
        arguments
            .is_consistent(self.simfony.parameters())
            .map_err(|error| error.to_string())?;

        let commit = self
            .simfony
            .compile(arguments, include_debug_symbols)
            .with_content(Arc::clone(&self.file))?;

        Ok(CompiledProgram {
            debug_symbols: self.simfony.debug_symbols(self.file.as_ref()),
            simplicity: commit,
            witness_types: self.simfony.witness_types().shallow_clone(),
            parameter_types: self.simfony.parameters().shallow_clone(),
        })
    }

    pub fn generate_abi_meta(&self) -> Result<AbiMeta, String> {
        Ok(AbiMeta {
            witness_types: self.simfony.witness_types().shallow_clone(),
            param_types: self.parameters().shallow_clone(),
        })
    }
}

/// A SimplicityHL program, compiled to Simplicity.
#[derive(Clone, Debug)]
pub struct CompiledProgram {
    simplicity: Arc<named::CommitNode<Elements>>,
    witness_types: WitnessTypes,
    debug_symbols: DebugSymbols,
    parameter_types: Parameters,
}

impl CompiledProgram {
    /// Parse and compile a SimplicityHL program from the given
    ///
    /// ## See
    ///
    /// - [`TemplateProgram::new_with_dep`]
    /// - [`TemplateProgram::instantiate`]
    pub fn new_with_dep(
        source: SourceFile,
        dependency_map: &DependencyMap,
        arguments: Arguments,
        include_debug_symbols: bool,
    ) -> Result<Self, String> {
        TemplateProgram::new_with_dep(source, dependency_map)
            .and_then(|template| template.instantiate(arguments, include_debug_symbols))
    }

    /// Parse and compile a SimplicityHL program from the given string.
    ///
    /// ## See
    ///
    /// - [`TemplateProgram::new`]
    /// - [`TemplateProgram::instantiate`]
    pub fn new<Str: Into<Arc<str>>>(
        s: Str,
        arguments: Arguments,
        include_debug_symbols: bool,
    ) -> Result<Self, String> {
        TemplateProgram::new(s)
            .and_then(|template| template.instantiate(arguments, include_debug_symbols))
    }

    /// Access the debug symbols for the Simplicity target code.
    pub fn debug_symbols(&self) -> &DebugSymbols {
        &self.debug_symbols
    }

    /// Access the Simplicity target code, without witness data.
    pub fn commit(&self) -> Arc<CommitNode<Elements>> {
        named::forget_names(&self.simplicity)
    }

    /// Satisfy the SimplicityHL program with the given `witness_values`.
    ///
    /// ## Errors
    ///
    /// - Witness values have a different type than declared in the SimplicityHL program.
    /// - There are missing witness values.
    pub fn satisfy(&self, witness_values: WitnessValues) -> Result<SatisfiedProgram, String> {
        self.satisfy_with_env(witness_values, None)
    }

    /// Satisfy the SimplicityHL program with the given `witness_values`.
    /// If `env` is `None`, the program is not pruned, otherwise it is pruned with the given environment.
    ///
    /// ## Errors
    ///
    /// - Witness values have a different type than declared in the SimplicityHL program.
    /// - There are missing witness values.
    pub fn satisfy_with_env(
        &self,
        witness_values: WitnessValues,
        env: Option<&ElementsEnv<Arc<elements::Transaction>>>,
    ) -> Result<SatisfiedProgram, String> {
        witness_values
            .is_consistent(&self.witness_types)
            .map_err(|e| e.to_string())?;

        let mut simplicity_redeem = named::populate_witnesses(&self.simplicity, witness_values)?;
        if let Some(env) = env {
            simplicity_redeem = simplicity_redeem.prune(env).map_err(|e| e.to_string())?;
        }
        Ok(SatisfiedProgram {
            simplicity: simplicity_redeem,
            debug_symbols: self.debug_symbols.clone(),
        })
    }

    pub fn generate_abi_meta(&self) -> Result<AbiMeta, String> {
        Ok(AbiMeta {
            witness_types: self.witness_types.shallow_clone(),
            param_types: self.parameter_types.shallow_clone(),
        })
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AbiMeta {
    pub witness_types: WitnessTypes,
    pub param_types: Parameters,
}

/// A SimplicityHL program, compiled to Simplicity and satisfied with witness data.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SatisfiedProgram {
    simplicity: Arc<RedeemNode<Elements>>,
    debug_symbols: DebugSymbols,
}

impl SatisfiedProgram {
    /// Parse, compile and satisfy a SimplicityHL program from the given string.
    ///
    /// ## See
    ///
    /// - [`TemplateProgram::new`]
    /// - [`TemplateProgram::instantiate`]
    /// - [`CompiledProgram::satisfy`]
    pub fn new<Str: Into<Arc<str>>>(
        s: Str,
        arguments: Arguments,
        witness_values: WitnessValues,
        include_debug_symbols: bool,
    ) -> Result<Self, String> {
        let compiled = CompiledProgram::new(s, arguments, include_debug_symbols)?;
        compiled.satisfy(witness_values)
    }

    /// Access the Simplicity target code, including witness data.
    pub fn redeem(&self) -> &Arc<RedeemNode<Elements>> {
        &self.simplicity
    }

    /// Access the debug symbols for the Simplicity target code.
    pub fn debug_symbols(&self) -> &DebugSymbols {
        &self.debug_symbols
    }
}

/// Recursively implement [`PartialEq`], [`Eq`] and [`std::hash::Hash`]
/// using selected members of a given type. The type must have a getter
/// method for each selected member.
#[macro_export]
macro_rules! impl_eq_hash {
    ($ty: ident; $($member: ident),*) => {
        impl PartialEq for $ty {
            fn eq(&self, other: &Self) -> bool {
                true $(&& self.$member() == other.$member())*
            }
        }

        impl Eq for $ty {}

        impl std::hash::Hash for $ty {
            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                $(self.$member().hash(state);)*
            }
        }
    };

    ($ty:ident < $($gen:ident),+ > ; $($member:ident),*) => {
        impl<$($gen),+> PartialEq for $ty<$($gen),+>
        where
            $($gen: PartialEq,)+
        {
            fn eq(&self, other: &Self) -> bool {
                true $(&& self.$member() == other.$member())*
            }
        }

        impl<$($gen),+> Eq for $ty<$($gen),+>
        where
            $($gen: Eq,)+
        {}

        impl<$($gen),+> std::hash::Hash for $ty<$($gen),+>
        where
            $($gen: std::hash::Hash,)+
        {
            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                $(self.$member().hash(state);)*
            }
        }
    };
}

/// Helper trait for implementing [`arbitrary::Arbitrary`] for recursive structures.
///
/// [`ArbitraryRec::arbitrary_rec`] allows the caller to set a budget that is decreased every time
/// the generated structure gets deeper. The maximum depth of the generated structure is equal to
/// the initial budget. The budget prevents the generated structure from becoming too deep, which
/// could cause issues in the code that processes these structures.
///
/// <https://github.com/rust-fuzz/arbitrary/issues/78>
#[cfg(feature = "arbitrary")]
trait ArbitraryRec: Sized {
    /// Generate a recursive structure from unstructured data.
    ///
    /// Generate leaves or parents when the budget is positive.
    /// Generate only leaves when the budget is zero.
    ///
    /// ## Implementation
    ///
    /// Recursive calls of [`arbitrary_rec`] must decrease the budget by one.
    fn arbitrary_rec(u: &mut arbitrary::Unstructured, budget: usize) -> arbitrary::Result<Self>;
}

/// Helper trait for implementing [`arbitrary::Arbitrary`] for typed structures.
///
/// [`arbitrary::Arbitrary`] is intended to produce well-formed values.
/// Structures with an internal type should be generated in a well-typed fashion.
///
/// [`arbitrary::Arbitrary`] can be implemented for a typed structure as follows:
/// 1. Generate the type via [`arbitrary::Arbitrary`].
/// 2. Generate the structure via [`ArbitraryOfType::arbitrary_of_type`].
#[cfg(feature = "arbitrary")]
pub trait ArbitraryOfType: Sized {
    /// Internal type of the structure.
    type Type;

    /// Generate a structure of the given type.
    fn arbitrary_of_type(
        u: &mut arbitrary::Unstructured,
        ty: &Self::Type,
    ) -> arbitrary::Result<Self>;
}

#[cfg(test)]
pub(crate) mod tests {
    use crate::parse::ParseFromStr;
    use crate::resolution::CanonPath;
    use base64::display::Base64Display;
    use base64::engine::general_purpose::STANDARD;
    use simplicity::BitMachine;
    use std::borrow::Cow;
    use std::path::{Path, PathBuf};

    use crate::*;

    pub(crate) struct TestCase<T> {
        program: T,
        lock_time: elements::LockTime,
        sequence: elements::Sequence,
        include_fee_output: bool,
    }

    impl TestCase<TemplateProgram> {
        pub fn template_file<P: AsRef<Path>>(program_file_path: P) -> Self {
            let program_text = std::fs::read_to_string(program_file_path).unwrap();
            Self::template_text(Cow::Owned(program_text))
        }

        pub fn template_deps(prog_path: &Path, dependency_map: &DependencyMap) -> Self {
            let program_text = std::fs::read_to_string(prog_path).unwrap();
            let source = SourceFile::new(prog_path, Arc::from(program_text));

            let program = match TemplateProgram::new_with_dep(source, dependency_map) {
                Ok(x) => x,
                Err(error) => panic!("{error}"),
            };

            Self {
                program,
                lock_time: elements::LockTime::ZERO,
                sequence: elements::Sequence::MAX,
                include_fee_output: false,
            }
        }

        pub fn template_text(program_text: Cow<str>) -> Self {
            let program = match TemplateProgram::new(program_text.as_ref()) {
                Ok(x) => x,
                Err(error) => panic!("{error}"),
            };
            Self {
                program,
                lock_time: elements::LockTime::ZERO,
                sequence: elements::Sequence::MAX,
                include_fee_output: false,
            }
        }

        #[cfg(feature = "serde")]
        pub fn with_argument_file<P: AsRef<Path>>(
            self,
            arguments_file_path: P,
        ) -> TestCase<CompiledProgram> {
            let arguments_text = std::fs::read_to_string(arguments_file_path).unwrap();
            let arguments = match serde_json::from_str::<Arguments>(&arguments_text) {
                Ok(x) => x,
                Err(error) => panic!("{error}"),
            };
            self.with_arguments(arguments)
        }

        pub fn with_arguments(self, arguments: Arguments) -> TestCase<CompiledProgram> {
            let program = match self.program.instantiate(arguments, true) {
                Ok(x) => x,
                Err(error) => panic!("{error}"),
            };
            TestCase {
                program,
                lock_time: self.lock_time,
                sequence: self.sequence,
                include_fee_output: self.include_fee_output,
            }
        }
    }

    impl TestCase<CompiledProgram> {
        pub fn program_file<P: AsRef<Path>>(program_file_path: P) -> Self {
            TestCase::<TemplateProgram>::template_file(program_file_path)
                .with_arguments(Arguments::default())
        }

        pub fn program_text(program_text: Cow<str>) -> Self {
            TestCase::<TemplateProgram>::template_text(program_text)
                .with_arguments(Arguments::default())
        }

        pub fn program_file_with_deps<P, I, K>(prog_path: P, dependencies: I) -> Self
        where
            P: AsRef<Path>,
            I: IntoIterator<Item = (P, K, P)>,
            K: Into<String>,
        {
            let mut dependency_map = DependencyMap::new();
            for (context, alias, target) in dependencies {
                let context = CanonPath::canonicalize(context.as_ref()).unwrap();
                let target = CanonPath::canonicalize(target.as_ref()).unwrap();

                dependency_map
                    .insert(context, alias.into(), target)
                    .unwrap();
            }

            TestCase::<TemplateProgram>::template_deps(prog_path.as_ref(), &dependency_map)
                .with_arguments(Arguments::default())
        }

        #[cfg(feature = "serde")]
        pub fn with_witness_file<P: AsRef<Path>>(
            self,
            witness_file_path: P,
        ) -> TestCase<SatisfiedProgram> {
            let witness_text = std::fs::read_to_string(witness_file_path).unwrap();
            let witness_values = match serde_json::from_str::<WitnessValues>(&witness_text) {
                Ok(x) => x,
                Err(error) => panic!("{error}"),
            };
            self.with_witness_values(witness_values)
        }

        pub fn with_witness_values(
            self,
            witness_values: WitnessValues,
        ) -> TestCase<SatisfiedProgram> {
            let program = match self.program.satisfy(witness_values) {
                Ok(x) => x,
                Err(error) => panic!("{error}"),
            };
            TestCase {
                program,
                lock_time: self.lock_time,
                sequence: self.sequence,
                include_fee_output: self.include_fee_output,
            }
        }

        pub fn get_encoding(self) -> String {
            let program_bytes = self.program.commit().to_vec_without_witness();
            Base64Display::new(&program_bytes, &STANDARD).to_string()
        }
    }

    impl<T> TestCase<T> {
        #[allow(dead_code)]
        pub fn with_lock_time(mut self, height: u32) -> Self {
            let height = elements::locktime::Height::from_consensus(height).unwrap();
            self.lock_time = elements::LockTime::Blocks(height);
            if self.sequence.is_final() {
                self.sequence = elements::Sequence::ENABLE_LOCKTIME_NO_RBF;
            }
            self
        }

        #[allow(dead_code)]
        pub fn with_sequence(mut self, distance: u16) -> Self {
            self.sequence = elements::Sequence::from_height(distance);
            self
        }

        #[allow(dead_code)]
        pub fn print_sighash_all(self) -> Self {
            let env = dummy_env::dummy_with(self.lock_time, self.sequence, self.include_fee_output);
            dbg!(env.c_tx_env().sighash_all());
            self
        }
    }

    impl TestCase<SatisfiedProgram> {
        #[allow(dead_code)]
        pub fn print_encoding(self) -> Self {
            let (program_bytes, witness_bytes) = self.program.redeem().to_vec_with_witness();
            println!(
                "Program:\n{}",
                Base64Display::new(&program_bytes, &STANDARD)
            );
            println!(
                "Witness:\n{}",
                Base64Display::new(&witness_bytes, &STANDARD)
            );
            self
        }

        fn run(self) -> Result<(), simplicity::bit_machine::ExecutionError> {
            let env = dummy_env::dummy_with(self.lock_time, self.sequence, self.include_fee_output);
            let pruned = self.program.redeem().prune(&env)?;
            let mut mac = BitMachine::for_program(&pruned)
                .expect("program should be within reasonable bounds");
            mac.exec(&pruned, &env).map(|_| ())
        }

        pub fn assert_run_success(self) {
            match self.run() {
                Ok(()) => {}
                Err(error) => panic!("Unexpected error: {error}"),
            }
        }

        pub fn get_encoding_with_witness(self) -> (String, String) {
            let (program_bytes, witness_bytes) = self.program.redeem().to_vec_with_witness();
            (
                Base64Display::new(&program_bytes, &STANDARD).to_string(),
                Base64Display::new(&witness_bytes, &STANDARD).to_string(),
            )
        }
    }

    /// THE DEFAULT HELPER
    /// Automatically sets up the standard `lib` self-referencing dependency.
    pub(crate) fn run_dependency_test(root_path: &str, lib_alias: &str) {
        let root_path = PathBuf::from(root_path);
        let lib_path = root_path.join(lib_alias);
        let main_path = root_path.join("main.simf");

        TestCase::program_file_with_deps(
            &main_path,
            [
                (&root_path, lib_alias, &lib_path),
                (&lib_path, lib_alias, &lib_path),
            ],
        )
        .with_witness_values(WitnessValues::default())
        .assert_run_success();
    }

    /// THE ADVANCED HELPER
    /// A helper function to run standard library dependency tests.
    /// `deps` expects an array of tuples: `(context_folder, alias, target_folder)`.
    /// Use `"."` for the `context_folder` if the context is the root test directory.
    pub(crate) fn run_multidep_test(root_path: &str, deps: &[(&str, &str, &str)]) {
        let root_path = PathBuf::from(root_path);
        let main_path = root_path.join("main.simf");

        // Convert the string slices into proper PathBufs dynamically
        let mapped_deps: Vec<(PathBuf, &str, PathBuf)> = deps
            .iter()
            .map(|(ctx, alias, target)| {
                let ctx_path = if *ctx == "." {
                    root_path.clone()
                } else {
                    root_path.join(ctx)
                };

                let target_path = root_path.join(target);

                (ctx_path, *alias, target_path)
            })
            .collect();

        let ref_deps = mapped_deps.iter().map(|(c, a, t)| (c, *a, t));

        TestCase::program_file_with_deps(&main_path, ref_deps)
            .with_witness_values(WitnessValues::default())
            .assert_run_success();
    }

    /// Run with `simc` command:
    ///
    /// ```
    /// simc examples/single_dep/main.simf \
    ///   --dep examples/single_dep/:temp=examples/single_dep/temp/
    /// ```
    #[test]
    fn single_dep() {
        run_dependency_test("./examples/single_dep", "temp");
    }

    /// Run with `simc` command:
    ///
    /// ```
    /// simc examples/simple_multidep/main.simf \
    ///   --dep examples/simple_multidep/:math=examples/simple_multidep/math/ \
    ///   --dep examples/simple_multidep/:crypto=examples/simple_multidep/crypto/
    /// ```
    #[test]
    fn simple_multidep() {
        run_multidep_test(
            "./examples/simple_multidep",
            &[(".", "math", "math"), (".", "crypto", "crypto")],
        );
    }

    /// Run with `simc` command:
    ///
    /// ```
    /// simc examples/multiple_deps/main.simf \
    ///   --dep examples/multiple_deps/:merkle=examples/multiple_deps/merkle/ \
    ///   --dep examples/multiple_deps/:base_math=examples/multiple_deps/math/ \
    ///   --dep examples/multiple_deps/merkle/:math=examples/multiple_deps/math/
    /// ```
    #[test]
    fn multiple_deps() {
        run_multidep_test(
            "./examples/multiple_deps",
            &[
                (".", "merkle", "merkle"),
                (".", "base_math", "math"),
                ("merkle", "math", "math"),
            ],
        );
    }

    #[test]
    fn cat() {
        TestCase::program_file("./examples/cat.simf")
            .with_witness_values(WitnessValues::default())
            .assert_run_success();
    }

    #[test]
    fn ctv() {
        TestCase::program_file("./examples/ctv.simf")
            .with_witness_values(WitnessValues::default())
            .assert_run_success();
    }

    #[test]
    fn regression_153() {
        TestCase::program_file("./examples/array_fold_2n.simf")
            .with_witness_values(WitnessValues::default())
            .assert_run_success();
    }

    #[test]
    fn pattern_matching() {
        TestCase::program_file("./examples/pattern_matching.simf")
            .with_witness_values(WitnessValues::default())
            .assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn sighash_non_interactive_fee_bump() {
        let mut t = TestCase::program_file("./examples/non_interactive_fee_bump.simf")
            .with_witness_file("./examples/non_interactive_fee_bump.wit");
        t.sequence = elements::Sequence::ENABLE_LOCKTIME_NO_RBF;
        t.lock_time = elements::LockTime::from_time(1734967235 + 600).unwrap();
        t.include_fee_output = true;
        t.assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn escrow_with_delay_timeout() {
        TestCase::program_file("./examples/escrow_with_delay.simf")
            .with_sequence(1000)
            .print_sighash_all()
            .with_witness_file("./examples/escrow_with_delay.timeout.wit")
            .assert_run_success();
    }

    #[test]
    fn hash_loop() {
        TestCase::program_file("./examples/hash_loop.simf")
            .with_witness_values(WitnessValues::default())
            .assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn hodl_vault() {
        TestCase::program_file("./examples/hodl_vault.simf")
            .with_lock_time(1000)
            .print_sighash_all()
            .with_witness_file("./examples/hodl_vault.wit")
            .assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn htlc_complete() {
        TestCase::program_file("./examples/htlc.simf")
            .print_sighash_all()
            .with_witness_file("./examples/htlc.complete.wit")
            .assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn last_will_inherit() {
        TestCase::program_file("./examples/last_will.simf")
            .with_sequence(25920)
            .print_sighash_all()
            .with_witness_file("./examples/last_will.inherit.wit")
            .assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn p2ms() {
        TestCase::program_file("./examples/p2ms.simf")
            .print_sighash_all()
            .with_witness_file("./examples/p2ms.wit")
            .assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn p2pk() {
        TestCase::template_file("./examples/p2pk.simf")
            .with_argument_file("./examples/p2pk.args")
            .print_sighash_all()
            .with_witness_file("./examples/p2pk.wit")
            .assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn p2pkh() {
        TestCase::program_file("./examples/p2pkh.simf")
            .print_sighash_all()
            .with_witness_file("./examples/p2pkh.wit")
            .assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn presigned_vault_complete() {
        TestCase::program_file("./examples/presigned_vault.simf")
            .with_sequence(1000)
            .print_sighash_all()
            .with_witness_file("./examples/presigned_vault.complete.wit")
            .assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn sighash_all_anyonecanpay() {
        TestCase::program_file("./examples/sighash_all_anyonecanpay.simf")
            .with_witness_file("./examples/sighash_all_anyonecanpay.wit")
            .assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn sighash_all_anyprevout() {
        TestCase::program_file("./examples/sighash_all_anyprevout.simf")
            .with_witness_file("./examples/sighash_all_anyprevout.wit")
            .assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn sighash_all_anyprevoutanyscript() {
        TestCase::program_file("./examples/sighash_all_anyprevoutanyscript.simf")
            .with_witness_file("./examples/sighash_all_anyprevoutanyscript.wit")
            .assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn sighash_none() {
        TestCase::program_file("./examples/sighash_none.simf")
            .with_witness_file("./examples/sighash_none.wit")
            .assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn sighash_single() {
        TestCase::program_file("./examples/sighash_single.simf")
            .with_witness_file("./examples/sighash_single.wit")
            .assert_run_success();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn transfer_with_timeout_transfer() {
        TestCase::program_file("./examples/transfer_with_timeout.simf")
            .print_sighash_all()
            .with_witness_file("./examples/transfer_with_timeout.transfer.wit")
            .assert_run_success();
    }

    #[test]
    fn redefined_variable() {
        let prog_text = r#"fn main() {
    let beefbabe: (u16, u16) = (0xbeef, 0xbabe);
    let beefbabe: u32 = <(u16, u16)>::into(beefbabe);
}
"#;
        TestCase::program_text(Cow::Borrowed(prog_text))
            .with_witness_values(WitnessValues::default())
            .assert_run_success();
    }

    #[test]
    fn empty_function_body_nonempty_return() {
        let prog_text = r#"fn my_true() -> bool {
    // function body is empty, although function must return `bool`
}

fn main() {
    assert!(my_true());
}
"#;
        match SatisfiedProgram::new(
            prog_text,
            Arguments::default(),
            WitnessValues::default(),
            false,
        ) {
            Ok(_) => panic!("Accepted faulty program"),
            Err(error) => {
                assert!(
                    error.contains("Expected expression of type `bool`, found type `()`"),
                    "Unexpected error: {error}",
                );
            }
        }
    }

    #[test]
    fn fuzz_regression_2() {
        parse::Program::parse_from_str("fn dbggscas(h: bool, asyxhaaaa: a) {\nfalse}\n\n").unwrap();
    }

    #[test]
    fn fuzz_slow_unit_1() {
        parse::Program::parse_from_str("fn fnnfn(MMet:(((sssss,((((((sssss,ssssss,ss,((((((sssss,ss,((((((sssss,ssssss,ss,((((((sssss,ssssss,((((((sssss,sssssssss,(((((((sssss,sssssssss,(((((ssss,((((((sssss,sssssssss,(((((((sssss,ssss,((((((sssss,ss,((((((sssss,ssssss,ss,((((((sssss,ssssss,((((((sssss,sssssssss,(((((((sssss,sssssssss,(((((ssss,((((((sssss,sssssssss,(((((((sssss,sssssssssssss,(((((((((((u|(").unwrap_err();
    }

    #[test]
    fn type_alias() {
        let prog_text = r#"type MyAlias = u32;

fn main() {
    let x: MyAlias = 32;
    assert!(jet::eq_32(x, 32));
}"#;
        TestCase::program_text(Cow::Borrowed(prog_text))
            .with_witness_values(WitnessValues::default())
            .assert_run_success();
    }

    #[test]
    fn type_error_regression() {
        let prog_text = r#"fn main() {
    let (a, b): (u32, u32) = (0, 1);
    assert!(jet::eq_32(a, 0));

    let (c, d): (u32, u32) = (2, 3);
    assert!(jet::eq_32(c, 2));
    assert!(jet::eq_32(d, 3));
}"#;
        TestCase::program_text(Cow::Borrowed(prog_text))
            .with_witness_values(WitnessValues::default())
            .assert_run_success();
    }

    #[cfg(feature = "serde")]
    mod regression {
        use super::TestCase;

        #[derive(serde::Deserialize)]
        struct Program {
            program: String,
            witness: Option<String>,
        }

        fn regression_test(name: &str) {
            let program = serde_json::from_str::<Program>(
                std::fs::read_to_string(format!("./test-data/{}.json", name))
                    .unwrap()
                    .as_str(),
            )
            .unwrap();

            let test_case = TestCase::program_file(format!("./examples/{}.simf", name));
            match program.witness {
                Some(wit) => {
                    let (new_program, new_witness) = test_case
                        .with_witness_file(format!("./examples/{}.wit", name))
                        .get_encoding_with_witness();
                    assert_eq!(
                        program.program, new_program,
                        "Byte code of programs should be the same"
                    );
                    assert_eq!(
                        wit, new_witness,
                        "Byte code of witnesses should be the same"
                    );
                }
                None => {
                    let new_program = test_case.get_encoding();

                    assert_eq!(
                        program.program, new_program,
                        "Byte code of programs should be the same"
                    )
                }
            }
        }

        #[test]
        fn array_fold_2n_regression() {
            regression_test("array_fold_2n");
        }

        #[test]
        fn array_fold_regression() {
            regression_test("array_fold");
        }

        #[test]
        fn cat_regression() {
            regression_test("cat");
        }

        #[test]
        fn ctv_regression() {
            regression_test("ctv");
        }

        #[test]
        fn escrow_with_delay_regression() {
            regression_test("escrow_with_delay");
        }

        #[test]
        fn hash_loop_regression() {
            regression_test("hash_loop");
        }

        #[test]
        fn hodl_vault_regression() {
            regression_test("hodl_vault");
        }

        #[test]
        fn htlc_regression() {
            regression_test("htlc");
        }

        #[test]
        fn last_will_regression() {
            regression_test("last_will");
        }

        #[test]
        fn non_interactive_fee_bump_regression() {
            regression_test("non_interactive_fee_bump");
        }

        #[test]
        fn p2ms_regression() {
            regression_test("p2ms");
        }

        #[test]
        fn p2pkh_regression() {
            regression_test("p2pkh");
        }

        #[test]
        fn presigned_vault_regression() {
            regression_test("presigned_vault");
        }

        #[test]
        fn reveal_collision_regression() {
            regression_test("reveal_collision");
        }

        #[test]
        fn reveal_fix_point_regression() {
            regression_test("reveal_fix_point");
        }

        #[test]
        fn sighash_all_anyonecanpay_regression() {
            regression_test("sighash_all_anyonecanpay");
        }

        #[test]
        fn sighash_all_anyprevoutanyscript_regression() {
            regression_test("sighash_all_anyprevoutanyscript");
        }

        #[test]
        fn sighash_all_anyprevout_regression() {
            regression_test("sighash_all_anyprevout");
        }

        #[test]
        fn sighash_none_regression() {
            regression_test("sighash_none");
        }

        #[test]
        fn sighash_single_regression() {
            regression_test("sighash_single");
        }

        #[test]
        fn transfer_with_timeout_regression() {
            regression_test("transfer_with_timeout");
        }
    }
}

#[cfg(test)]
mod error_tests {
    use std::path::Path;

    use super::*;

    use crate::resolution::tests::canon;
    use crate::resolution::CanonPath;
    use crate::test_utils::TempWorkspace;

    fn dependency_map(root_dir: &Path, drp: &str, lib_dir: &Path) -> DependencyMap {
        let mut dependency_map = DependencyMap::new();

        let context = CanonPath::canonicalize(root_dir).unwrap();
        let target = CanonPath::canonicalize(lib_dir).unwrap();

        dependency_map.insert(context, drp.into(), target).unwrap();

        dependency_map
    }

    fn source_file(path: &Path) -> SourceFile {
        let content = std::fs::read_to_string(path).expect("Failed to read test file");
        SourceFile::new(path, Arc::from(content))
    }

    #[test]
    #[ignore = "TODO: Bug in Error Handler. Expected to be fixed in a future update to correctly point to dependency source files."]
    fn dependency_ast_errors_use_dependency_source_file() {
        let ws = TempWorkspace::new("dependency_ast_error_source");
        let root_dir = ws.create_dir("workspace");
        let lib_dir = ws.create_dir("workspace/lib");
        let main_path = ws.create_file(
            "workspace/main.simf",
            "use lib::bad::f;\nfn main() { f(); }\n",
        );
        let bad_path = ws.create_file(
            "workspace/lib/bad.simf",
            "pub fn f() { let x: u32 = true; }\n",
        );

        let dependencies = dependency_map(&root_dir, "lib", &lib_dir);

        let err = TemplateProgram::new_with_dep(source_file(&main_path), &dependencies)
            .expect_err("dependency body has a type error");
        let dependency_source = canon(&bad_path).as_path().display().to_string();

        assert!(
            err.contains(&dependency_source),
            "expected diagnostic to point at dependency source {dependency_source}, got:\n{err}"
        );
    }

    #[test]
    fn omitted_context_dependency_applies_inside_dependency_files() {
        let ws = TempWorkspace::new("omitted_context_dependency");
        let lib_dir = ws.create_dir("workspace/lib");
        let main_path = ws.create_file(
            "workspace/main.simf",
            "use lib::nested::two;\nfn main() { assert!(jet::eq_32(two(), 2)); }\n",
        );
        ws.create_file(
            "workspace/lib/nested.simf",
            "use lib::base::one;\npub fn two() -> u32 {\n    let (_, out): (bool, u32) = jet::add_32(one(), 1);\n    out\n}\n",
        );
        ws.create_file("workspace/lib/base.simf", "pub fn one() -> u32 { 1 }\n");

        let dependencies = dependency_map(&main_path, "lib", &lib_dir);
        let _err = TemplateProgram::new_with_dep(source_file(&main_path), &dependencies)
            .expect_err("omitted-context dependencies");
    }

    #[test]
    fn missing_mapped_module_is_reported_as_file_not_found() {
        let ws = TempWorkspace::new("missing_mapped_module");
        let root_dir = ws.create_dir("workspace");
        let lib_dir = ws.create_dir("workspace/lib");
        let main_path = ws.create_file(
            "workspace/main.simf",
            "use lib::missing::Thing;\nfn main() {}\n",
        );
        let dependencies = dependency_map(&root_dir, "lib", &lib_dir);

        let err = TemplateProgram::new_with_dep(source_file(&main_path), &dependencies)
            .expect_err("missing imported module should fail");

        assert!(
            err.contains("missing.simf"),
            "diagnostic should mention the missing module path, got:\n{err}"
        );
    }
}

#[cfg(test)]
mod functional_tests {
    use crate::tests::{run_dependency_test, run_multidep_test};

    const VALID_TESTS_DIR: &str = "./functional-tests/valid-test-cases";
    const ERROR_TESTS_DIR: &str = "./functional-tests/error-test-cases";

    // Real test cases
    #[test]
    fn module_simple() {
        run_dependency_test(format!("{}/module-simple", VALID_TESTS_DIR).as_str(), "lib");
    }

    #[test]
    fn diamond_dependency_resolution() {
        run_dependency_test(
            format!("{}/diamond-dependency-resolution", VALID_TESTS_DIR).as_str(),
            "lib",
        );
    }

    #[test]
    fn deep_reexport_chain() {
        run_dependency_test(
            format!("{}/deep-reexport-chain", VALID_TESTS_DIR).as_str(),
            "lib",
        );
    }

    #[test]
    fn leaky_signature() {
        run_dependency_test(
            format!("{}/leaky-signature", VALID_TESTS_DIR).as_str(),
            "lib",
        );
    }

    #[test]
    fn reexport_diamond() {
        run_dependency_test(
            format!("{}/reexport-diamond", VALID_TESTS_DIR).as_str(),
            "lib",
        );
    }

    #[test]
    fn multi_lib_facade_resolution() {
        run_multidep_test(
            format!("{}/multi-lib-facade", VALID_TESTS_DIR).as_str(),
            &[
                (".", "api", "api"),
                ("crypto", "math", "math"),
                ("api", "crypto", "crypto"),
                ("api", "math", "math"),
            ],
        );
    }

    #[test]
    fn interleaved_waterfall() {
        run_multidep_test(
            format!("{}/interleaved-waterfall", VALID_TESTS_DIR).as_str(),
            &[
                (".", "orch", "orch"),
                ("orch", "db", "db"),
                ("orch", "auth", "auth"),
                ("orch", "types", "types"),
                ("db", "types", "types"),
                ("auth", "types", "types"),
                ("auth", "db", "db"),
            ],
        );
    }

    // Error tests
    #[test]
    #[should_panic(expected = "Circular dependency detected:")]
    fn cyclic_dependency_error() {
        run_dependency_test(
            format!("{}/cyclic-dependency", ERROR_TESTS_DIR).as_str(),
            "lib",
        );
    }

    #[test]
    #[should_panic(expected = "No such file or directory")]
    fn file_not_found_error() {
        run_dependency_test(
            format!("{}/file-not-found", ERROR_TESTS_DIR).as_str(),
            "lib",
        );
    }

    #[test]
    #[should_panic(expected = "No such file or directory")]
    fn lib_not_found_error() {
        run_dependency_test(format!("{}/lib-not-found", ERROR_TESTS_DIR).as_str(), "lib");
    }

    #[test]
    #[should_panic(expected = "Item `SecretType` is private")]
    fn private_type_visibility_error() {
        run_dependency_test(
            format!("{}/private-visibility", ERROR_TESTS_DIR).as_str(),
            "lib",
        );
    }

    #[test]
    #[should_panic(expected = "The alias `add` was defined multiple times")]
    fn name_collision_error() {
        run_dependency_test(
            format!("{}/name-collision", ERROR_TESTS_DIR).as_str(),
            "lib",
        );
    }

    // Reference to the following bug: https://github.com/BlockstreamResearch/SimplicityHL/issues/220
    #[test]
    #[should_panic(expected = "Type alias `A` was defined multiple times")]
    fn type_alias_duplication_error() {
        run_dependency_test(
            format!("{}/type-alias-duplication", ERROR_TESTS_DIR).as_str(),
            "lib",
        );
    }
}