1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
use self::intooperation::{IntoOperation, IntoVariadicOperation};
use crate::Error;
use crate::MAX_EVAL_DEPTH;
use crate::ast::Value;
use crate::builtinops::get_builtin_ops;
use std::sync::Arc;
pub(crate) mod intooperation;
pub use self::intooperation::{BoolIter, NumIter, StringIter, ValueIter};
use std::collections::HashMap;
/// Represents the expected number of arguments for an operation.
#[derive(Debug, Clone, PartialEq)]
pub enum Arity {
/// Exactly n arguments required
Exact(usize),
/// At least n arguments required
AtLeast(usize),
/// Between min and max arguments (inclusive)
Range(usize, usize),
/// Any number of arguments (0 or more)
Any,
}
impl Arity {
/// Check if the given number of arguments is valid for this arity constraint.
pub(crate) fn validate(&self, arg_count: usize) -> Result<(), Error> {
let valid = match self {
Arity::Exact(n) => arg_count == *n,
Arity::AtLeast(n) => arg_count >= *n,
Arity::Range(min, max) => arg_count >= *min && arg_count <= *max,
Arity::Any => true,
};
if valid {
Ok(())
} else {
Err(Error::ArityError {
expected: match self {
Arity::Exact(n) | Arity::AtLeast(n) => *n,
Arity::Range(min, _) => *min,
Arity::Any => 0,
},
got: arg_count,
expression: None, // Builtin validation doesn't have expression context
})
}
}
}
/// Environment for variable bindings
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Environment {
bindings: HashMap<String, Value>,
parent: Option<Box<Environment>>,
}
impl Environment {
pub(crate) fn new() -> Self {
Environment {
bindings: HashMap::new(),
parent: None,
}
}
pub(crate) fn with_parent(parent: Environment) -> Self {
Environment {
bindings: HashMap::new(),
parent: Some(Box::new(parent)),
}
}
pub(crate) fn define(&mut self, name: String, value: Value) {
self.bindings.insert(name, value);
}
pub(crate) fn get(&self, name: &str) -> Option<&Value> {
self.bindings
.get(name)
.or_else(|| self.parent.as_ref().and_then(|parent| parent.get(name)))
}
/// Register a strongly-typed Rust function as a builtin operation using
/// automatic argument extraction and result conversion.
///
/// This allows writing natural Rust functions like:
///
/// ```rust
/// use rulesxp::{Error, evaluator};
///
/// // Infallible builtin: returns a bare i64
/// fn add(a: i64, b: i64) -> i64 {
/// a + b
/// }
/// let mut env = evaluator::create_global_env();
/// env.register_builtin_operation::<(i64, i64)>("add", add);
/// // Now (+ 2 3) and (add 2 3) both work if + also registered
/// ```
///
/// Builtins that may fail return `Result<T, Error>` where `T` is either
/// a Value or a type convertible into Value, and encode
/// their own error messages:
///
/// ```rust
/// use rulesxp::{Error, evaluator};
///
/// fn safe_div(a: i64, b: i64) -> Result<i64, Error> {
/// if b == 0 {
/// Err(Error::EvalError("division by zero".into()))
/// } else {
/// Ok(a / b)
/// }
/// }
///
/// let mut env = evaluator::create_global_env();
/// env.register_builtin_operation::<(i64, i64)>("safe-div", safe_div);
/// ```
///
/// Supported parameter types (initial set):
/// - `i64` (number)
/// - `bool` (boolean)
/// - `&str` (borrowed string slices)
/// - `Value` (owned access to the raw AST value)
/// - `ValueIter<'_>` (iterates over elements of a list argument as `&Value`)
/// - `NumIter<'_>` (iterates over numeric elements of a list argument)
/// - `BoolIter<'_>` (iterates over boolean elements of a list argument)
/// - `StringIter<'_>` (iterates over string elements of a list argument)
///
/// Additional scalar parameter types can be supported by adding
/// `impl TryInto<T, Error = Error> for Value`.
///
/// More advanced list-style and variadic behavior (e.g. rest
/// parameters spanning multiple arguments) can be expressed using
/// the iterator-based APIs described on
/// [`Environment::register_variadic_builtin_operation`].
///
/// Supported return types:
/// - `Result<Value, Error>`
/// - `Result<T, Error>` where `T: Into<Value>` (for example
/// `i64`, `bool`, `&str`, or arrays/vectors of these types)
/// - bare `T` where `T: Into<Value>` (for infallible helpers,
/// automatically wrapped as `Ok(T)`)
///
/// If you need true rest-parameter / variadic behavior (functions
/// that see all arguments via iterators over the argument tail),
/// use [`Environment::register_variadic_builtin_operation`] instead.
///
/// Arity is enforced automatically. Conversion errors yield
/// `TypeError`, and builtin errors are surfaced directly as
/// `Error` values.
#[expect(private_bounds)] // IntoOperation is an internal adapter trait modeling an input function
pub fn register_builtin_operation<Args>(
&mut self,
name: &str,
func: impl IntoOperation<Args> + 'static,
) {
let wrapped = func.into_operation();
self.bindings.insert(
name.to_string(),
Value::BuiltinFunction {
id: name.to_string(),
func: wrapped,
},
);
}
/// Register a variadic builtin operation with explicit arity metadata.
///
/// This is intended for functions whose Rust signature includes a
/// "rest" parameter, expressed using iterator types such as
/// [`ValueIter`] and [`NumIter`].
///
/// Examples:
/// - rest of all arguments as values:
/// `fn(ValueIter<'_>) -> Result<Value, Error>` with
/// `Args = (ValueIter<'static>,)`
/// - numeric tail:
/// `fn(NumIter<'_>) -> Result<Value, Error>` with
/// `Args = (NumIter<'static>,)`
/// - fixed prefix plus numeric tail:
/// `fn(i64, NumIter<'_>) -> Result<Value, Error>` with
/// `Args = (i64, NumIter<'static>)`
///
/// Fixed-arity functions should use
/// [`Environment::register_builtin_operation`] instead.
///
/// The provided [`Arity`] is used to validate the total number of
/// arguments at call time, since minimum/maximum argument counts for
/// variadic operations are not always derivable from the Rust type
/// signature alone.
#[expect(private_bounds)] // IntoVariadicOperation is an internal trait modeling an input function
pub fn register_variadic_builtin_operation<Args>(
&mut self,
name: &str,
arity: Arity,
func: impl IntoVariadicOperation<Args> + 'static,
) {
let inner = func.into_variadic_operation();
let arity_for_closure = arity;
let wrapped = std::sync::Arc::new(move |args: Vec<Value>| {
arity_for_closure.validate(args.len())?;
inner(args)
});
self.bindings.insert(
name.to_string(),
Value::BuiltinFunction {
id: name.to_string(),
func: wrapped,
},
);
}
/// Get all bindings in this environment and its parents
/// Returns a Vec of (name, value) pairs sorted by name
pub fn get_all_bindings(&self) -> Vec<(String, Value)> {
let mut bindings = HashMap::new();
// Start with parent bindings (so they can be overridden by local bindings)
if let Some(parent) = &self.parent {
for (name, value) in parent.get_all_bindings() {
bindings.insert(name, value);
}
}
// Add/override with local bindings
for (name, value) in &self.bindings {
bindings.insert(name.clone(), value.clone());
}
// Convert to sorted vector
let mut result: Vec<_> = bindings.into_iter().collect();
result.sort_by(|a, b| a.0.cmp(&b.0));
result
}
}
/// Evaluate an S-expression (public API)
pub fn eval(expr: &Value, env: &mut Environment) -> Result<Value, Error> {
eval_with_depth_tracking(expr, env, 0)
}
/// Evaluate an S-expression with depth tracking to prevent stack overflow
fn eval_with_depth_tracking(
expr: &Value,
env: &mut Environment,
depth: usize,
) -> Result<Value, Error> {
if depth >= MAX_EVAL_DEPTH {
return Err(Error::EvalError(format!(
"Evaluation depth limit exceeded (max: {MAX_EVAL_DEPTH})"
)));
}
match expr {
// Self-evaluating forms (empty lists are NOT self-evaluating for strict semantics)
Value::Number(_)
| Value::String(_)
| Value::Bool(_)
| Value::BuiltinFunction { .. }
| Value::Function { .. }
| Value::Unspecified => Ok(expr.clone()),
// Variable lookup
Value::Symbol(name) => env
.get(name)
.cloned()
.ok_or_else(|| Error::UnboundVariable(name.clone())),
// PrecompiledOp evaluation (optimized path for builtin operations and special forms)
// This is where special forms are actually handled - they are converted to PrecompiledOps
// during parsing since they are syntax structures, not dynamic function calls.
// Note: Arity is already validated at parse time, so no runtime checking needed
Value::PrecompiledOp { op, args, .. } => {
use crate::builtinops::OpKind;
match &op.op_kind {
OpKind::Function(f) => {
// Evaluate all arguments using helper function with depth tracking
let evaluated_args = eval_args(args, env, depth)?;
// Apply the function (arity already validated at parse time)
f(evaluated_args)
}
OpKind::SpecialForm(special_form) => {
// Special forms are syntax structures handled here after being converted
// to PrecompiledOps during parsing. They get unevaluated arguments.
// (arity already validated at parse time)
// Note: Special forms handle their own depth tracking via eval_with_depth_tracking calls
special_form(args, env, depth)
}
}
}
// List evaluation (function application or special forms)
Value::List(elements) => {
eval_list(elements, env, depth).map_err(|err| add_context(err, expr))
}
}
}
/// Helper function to add expression context to errors
fn add_context(error: Error, expr: &Value) -> Error {
let context = format!("while evaluating: {expr}");
match error {
Error::EvalError(msg) => Error::EvalError(format!("{msg}\n Context: {context}")),
Error::TypeError(msg) => Error::TypeError(format!("{msg}\n Context: {context}")),
// Don't add context to parse errors, unbound variables, or arity errors (they have their own context)
other => other,
}
}
/// Helper function to evaluate a list of argument expressions with depth tracking
fn eval_args(args: &[Value], env: &mut Environment, depth: usize) -> Result<Vec<Value>, Error> {
args.iter()
.map(|arg| eval_with_depth_tracking(arg, env, depth + 1))
.collect()
}
/// Evaluate a list expression (function application)
///
/// Note: Both builtin functions and special forms are converted to PrecompiledOps
/// during parsing for optimization. Special forms are syntax structures that cannot
/// be dynamically generated, while builtin functions benefit from pre-validation.
/// All PrecompiledOps are handled in the main eval() function. Therefore, eval_list()
/// only needs to handle dynamic function application cases.
///
/// If the PrecompiledOps optimization were removed, special forms would need
/// special handling here. Builtin functions are added to the environment and
/// can be called dynamically through normal symbol lookup and function application.
fn eval_list(elements: &[Value], env: &mut Environment, depth: usize) -> Result<Value, Error> {
// Note: Dynamic calls (not PrecompiledOps) still need runtime arity checking
match elements {
[] => Err(Error::EvalError("Cannot evaluate empty list".to_owned())),
// Function application: evaluate function expression, then apply to arguments
// Note: If PrecompiledOps optimization were removed, we would need to check for
// special forms here before function application (builtin functions work via symbol lookup)
[func_expr, arg_exprs @ ..] => {
// Evaluate the function with depth tracking
let func = eval_with_depth_tracking(func_expr, env, depth + 1)?;
// Evaluate the arguments with depth tracking
let args = eval_args(arg_exprs, env, depth + 1)?;
// Apply the function
match &func {
// Dynamic function calls
Value::BuiltinFunction { func, .. } => func(args),
Value::Function {
params,
body,
env: closure_env,
} => {
if params.len() != args.len() {
return Err(Error::arity_error(params.len(), args.len()));
}
// Create new environment with closure environment as parent
let mut new_env = Environment::with_parent(closure_env.clone());
// Bind parameters to arguments
for (param, arg) in params.iter().zip(args.iter()) {
new_env.define(param.clone(), arg.clone());
}
// Evaluate body with depth tracking and context
eval_with_depth_tracking(body, &mut new_env, depth + 1).map_err(|err| match err
{
Error::EvalError(msg) => {
Error::EvalError(format!("{msg}\n In lambda: {body}"))
}
Error::TypeError(msg) => {
Error::TypeError(format!("{msg}\n In lambda: {body}"))
}
other => other,
})
}
_ => Err(Error::TypeError(format!(
"Cannot apply non-function: {func}"
))),
}
}
}
}
/// Evaluate quote special form
pub(crate) fn eval_quote(
args: &[Value],
_env: &mut Environment,
_depth: usize,
) -> Result<Value, Error> {
match args {
[expr] => Ok(expr.clone()), // Quote content is already unoptimized during parsing
_ => Err(Error::arity_error(1, args.len())),
}
}
/// Evaluate define special form
pub(crate) fn eval_define(
args: &[Value],
env: &mut Environment,
depth: usize,
) -> Result<Value, Error> {
match args {
[Value::Symbol(name), expr] => {
let value = eval_with_depth_tracking(expr, env, depth + 1)?;
env.define(name.clone(), value);
Ok(Value::Unspecified)
}
[_, _] => Err(Error::TypeError("define requires a symbol".to_owned())),
_ => Err(Error::arity_error(2, args.len())),
}
}
/// Evaluate if special form
pub(crate) fn eval_if(args: &[Value], env: &mut Environment, depth: usize) -> Result<Value, Error> {
match args {
[condition_expr, then_expr, else_expr] => {
let condition = eval_with_depth_tracking(condition_expr, env, depth + 1)?;
match condition {
Value::Bool(true) => eval_with_depth_tracking(then_expr, env, depth + 1),
Value::Bool(false) => eval_with_depth_tracking(else_expr, env, depth + 1),
_ => Err(Error::TypeError(
"SCHEME-JSONLOGIC-STRICT: if condition must be a boolean".to_owned(),
)),
}
}
_ => Err(Error::arity_error(3, args.len())),
}
}
/// Evaluate lambda special form
pub(crate) fn eval_lambda(
args: &[Value],
env: &mut Environment,
_depth: usize,
) -> Result<Value, Error> {
match args {
[Value::List(param_list), body] => {
let mut params = Vec::new();
for param in param_list {
match param {
Value::Symbol(name) => {
// Check for duplicate parameter names (R7RS compliant)
if params.contains(name) {
return Err(Error::EvalError(format!(
"Duplicate parameter name: {name}"
)));
}
params.push(name.clone());
}
_ => {
return Err(Error::TypeError(
"Lambda parameters must be symbols".to_owned(),
));
}
}
}
// SCHEME-STRICT: We do not support Scheme's variadic lambda forms:
// - (lambda args body) - where args is a symbol that collects all arguments as a list
// - (lambda (a b . rest) body) - where rest collects remaining arguments (dot notation)
// Our implementation only supports fixed-arity lambdas with explicit parameter lists.
Ok(Value::Function {
params,
body: Box::new(body.clone()),
env: env.clone(),
})
}
[_, _] => Err(Error::TypeError(
"Lambda parameters must be a list".to_owned(),
)),
_ => Err(Error::arity_error(2, args.len())),
}
}
/// Check if a value is obviously non-boolean (before evaluation)
/// This catches literals and some obvious cases, but can't check function call results
fn is_obviously_non_boolean(value: &Value) -> bool {
match value {
Value::Number(_) | Value::String(_) | Value::Unspecified => true, // Obviously non-boolean
Value::Bool(_)
| Value::List(_)
| Value::PrecompiledOp { .. }
| Value::Symbol(_)
| Value::BuiltinFunction { .. }
| Value::Function { .. } => false, // Boolean, or could be function calls/variables that return booleans
}
}
macro_rules! boolean_logic_op {
($name:ident, $op_name:expr, $short_circuit:literal, $default:literal) => {
pub(crate) fn $name(
args: &[Value],
env: &mut Environment,
depth: usize,
) -> Result<Value, Error> {
// SCHEME-STRICT: Require at least 1 argument (Scheme R7RS allows 0 args, returns #t)
if args.is_empty() {
return Err(Error::arity_error(1, 0));
}
// First pass: check for obviously non-boolean arguments before evaluation, so that short-circuit evaluation doesn't hide gross errors
for arg in args.iter() {
if is_obviously_non_boolean(arg) {
return Err(Error::TypeError(
concat!(
"SCHEME-JSONLOGIC-STRICT: '",
$op_name,
"' requires boolean arguments (no truthiness)"
)
.to_string(),
));
}
}
// Second pass: evaluate and short-circuit
for arg in args.iter() {
let result = eval_with_depth_tracking(arg, env, depth + 1)?;
match result {
Value::Bool($short_circuit) => return Ok(Value::Bool($short_circuit)),
Value::Bool(_) => continue,
_ => {
return Err(Error::TypeError(
concat!(
"SCHEME-JSONLOGIC-STRICT: '",
$op_name,
"' requires boolean arguments (no truthiness)"
)
.to_string(),
));
}
}
}
Ok(Value::Bool($default))
}
};
}
// Generate boolean logic functions
boolean_logic_op!(eval_and, "and", false, true);
boolean_logic_op!(eval_or, "or", true, false);
/// Create a global environment with built-in functions
pub fn create_global_env() -> Environment {
let mut env = Environment::new();
// Add all regular functions from the registry
for builtin_op in get_builtin_ops() {
if let crate::builtinops::OpKind::Function(func) = &builtin_op.op_kind {
// Use BuiltinFunction for environment bindings (dynamic calls through symbols)
env.define(
builtin_op.scheme_id.to_owned(),
Value::BuiltinFunction {
id: builtin_op.scheme_id.to_owned(),
func: Arc::clone(func),
},
);
}
}
env
}
#[cfg(test)]
#[cfg(feature = "scheme")]
mod tests {
use super::*;
use crate::Error;
use crate::ast::{nil, sym, val};
use crate::evaluator::{BoolIter, NumIter, StringIter, ValueIter};
use crate::scheme::parse_scheme;
/// Test result variants for comprehensive testing
#[derive(Debug)]
enum TestResult {
EvalResult(Value), // Evaluation should succeed with this value
SpecificError(&'static str), // Evaluation should fail with error containing this string
Error, // Evaluation should fail (any error)
ArityError, // Evaluation should fail specifically with an ArityError
}
use TestResult::*;
/// Test environment containing test cases that share state
struct TestEnvironment(Vec<(&'static str, TestResult)>);
/// Micro-helper for success cases in comprehensive tests
fn success<T: Into<Value>>(value: T) -> TestResult {
EvalResult(val(value))
}
/// Macro for setup expressions that return Unspecified (like define)
macro_rules! test_setup {
($expr:expr) => {
($expr, EvalResult(Value::Unspecified))
};
}
/// Run tests in isolated environments with shared state
fn run_tests_in_environment(test_environments: Vec<TestEnvironment>) {
for (env_idx, TestEnvironment(test_cases)) in test_environments.iter().enumerate() {
let mut env = create_global_env();
// Run test cases in this environment using shared logic
for (test_idx, (input, expected)) in test_cases.iter().enumerate() {
let test_id = format!("Environment #{} test #{}", env_idx + 1, test_idx + 1);
execute_test_case(input, expected, &mut env, &test_id);
}
}
}
/// Execute a single test case with detailed error reporting
fn execute_test_case(input: &str, expected: &TestResult, env: &mut Environment, test_id: &str) {
let expr = match parse_scheme(input) {
Ok(expr) => expr,
Err(parse_err) => {
panic!("{test_id}: unexpected parse error for '{input}': {parse_err:?}");
}
};
match (eval(&expr, env), expected) {
(Ok(actual), EvalResult(expected_val)) => {
// Special handling for Unspecified values - they should match type but not equality
match (&actual, expected_val) {
(Value::Unspecified, Value::Unspecified) => {} // Both unspecified - OK
_ => {
assert!(
!(actual != *expected_val),
"{test_id}: expected {expected_val:?}, got {actual:?}"
);
}
}
}
(Err(crate::Error::ArityError { .. }), ArityError) => {} // Expected specific arity error
(Ok(actual), ArityError) => {
panic!("{test_id}: expected ArityError, got successful result {actual:?}");
}
(Err(err), ArityError) => {
panic!("{test_id}: expected ArityError, got different error {err:?}");
}
(Err(_), Error) => {} // Expected generic error
(Err(e), SpecificError(expected_text)) => {
let error_msg = format!("{e}");
assert!(
error_msg.contains(expected_text),
"{test_id}: error should contain '{expected_text}', got: {error_msg}"
);
}
(Ok(actual), Error) => {
panic!("{test_id}: expected error, got {actual:?}");
}
(Ok(actual), SpecificError(expected_text)) => {
panic!("{test_id}: expected error containing '{expected_text}', got {actual:?}");
}
(Err(err), EvalResult(expected_val)) => {
panic!("{test_id}: expected {expected_val:?}, got error {err:?}");
}
}
}
/// Simplified test runner with specific error message support
fn run_comprehensive_tests(test_cases: Vec<(&str, TestResult)>) {
for (i, (input, expected)) in test_cases.iter().enumerate() {
let mut env = create_global_env();
let test_id = format!("#{}", i + 1);
execute_test_case(input, expected, &mut env, &test_id);
}
}
/// Run tests in a caller-provided environment (e.g., with custom builtins registered).
fn run_tests_in_specific_environment(
env: &mut Environment,
test_cases: Vec<(&str, TestResult)>,
) {
for (i, (input, expected)) in test_cases.iter().enumerate() {
let test_id = format!("#custom-{}", i + 1);
execute_test_case(input, expected, env, &test_id);
}
}
#[test]
fn test_custom_builtin_operations() {
// Custom builtins exercise the adapter layer: fixed arity, zero-arg,
// list iterators, explicit arity metadata, and variadic rest-parameters.
fn add(a: i64, b: i64) -> i64 {
a + b
}
fn forty_two() -> i64 {
42
}
fn safe_div(a: i64, b: i64) -> Result<i64, Error> {
if b == 0 {
Err(Error::EvalError("division by zero".into()))
} else {
Ok(a / b)
}
}
fn sum_list(nums: NumIter<'_>) -> Result<i64, Error> {
Ok(nums.sum())
}
fn first_and_rest_count(mut args: ValueIter<'_>) -> Result<Vec<i64>, Error> {
let first = match args.next() {
Some(Value::Number(n)) => *n,
Some(_) => return Err(Error::TypeError("first argument must be a number".into())),
None => return Err(Error::arity_error(1, 0)),
};
let rest_count = args.count() as i64;
Ok(vec![first, rest_count])
}
fn count_numbers(args: ValueIter<'_>) -> Result<i64, Error> {
let count = args.filter(|v| matches!(v, Value::Number(_))).count() as i64;
Ok(count)
}
fn sum_all(nums: NumIter<'_>) -> Result<i64, Error> {
Ok(nums.sum::<i64>())
}
fn weighted_sum(weight: i64, nums: NumIter<'_>) -> Result<i64, Error> {
Ok(weight * nums.sum::<i64>())
}
fn sum_all_min1(nums: NumIter<'_>) -> Result<i64, Error> {
Ok(nums.sum::<i64>())
}
fn string_length(s: &str) -> i64 {
s.len() as i64
}
fn all_true(mut bools: BoolIter<'_>) -> bool {
bools.all(|b| b)
}
fn join_strings(strings: StringIter<'_>) -> String {
strings.collect::<Vec<_>>().join(",")
}
let mut env = create_global_env();
// Fixed-arity and zero-arg builtins.
env.register_builtin_operation::<(i64, i64)>("add2", add);
env.register_builtin_operation::<()>("forty-two", forty_two);
env.register_builtin_operation::<(i64, i64)>("safe-div", safe_div);
env.register_builtin_operation::<(&str,)>("str-len", string_length);
// Iterator-based list and variadic builtins.
env.register_builtin_operation::<(NumIter<'static>,)>("sum-list", sum_list);
env.register_builtin_operation::<(BoolIter<'static>,)>("all-true", all_true);
env.register_variadic_builtin_operation::<(StringIter<'static>,)>(
"join-strings",
Arity::AtLeast(0),
join_strings,
);
env.register_variadic_builtin_operation::<(ValueIter<'static>,)>(
"first-rest-count",
Arity::AtLeast(1),
first_and_rest_count,
);
env.register_variadic_builtin_operation::<(ValueIter<'static>,)>(
"count-numbers",
Arity::AtLeast(0),
count_numbers,
);
env.register_variadic_builtin_operation::<(NumIter<'static>,)>(
"sum-varargs-all",
Arity::AtLeast(0),
sum_all,
);
env.register_variadic_builtin_operation::<(i64, NumIter<'static>)>(
"weighted-sum",
Arity::AtLeast(1),
weighted_sum,
);
env.register_variadic_builtin_operation::<(NumIter<'static>,)>(
"sum-all-min1",
Arity::AtLeast(1),
sum_all_min1,
);
let test_cases = vec![
// Fixed-arity and zero-arg builtins.
("(add2 7 5)", success(12)),
("(forty-two)", success(42)),
("(forty-two 1)", ArityError), // 0-arg arity check should reject
("(safe-div 6 3)", success(2)),
// Error case: division by zero surfaces as EvalError containing the message.
("(safe-div 1 0)", SpecificError("division by zero")),
// Iterator-based list and variadic builtins.
("(sum-list (list 1 2 3 4))", success(10)),
("(first-rest-count 42 \"x\" #t 7)", success([42, 3])),
("(count-numbers 1 \"x\" 2 #t 3)", success(3)),
("(sum-varargs-all 1 2 3 4)", success(10)),
("(weighted-sum 2 1 2 3)", success(12)),
// Explicit arity checking for variadic builtin.
("(sum-all-min1 1 2 3)", success(6)),
("(sum-all-min1)", ArityError),
// &str, BoolIter, StringIter parameter types & validation in custom builtins.
("(str-len \"hello\")", success(5)),
("(str-len 42)", SpecificError("expected string")),
("(str-len)", ArityError),
("(all-true (list #t #t #t))", success(true)),
("(all-true (list 1 2))", SpecificError("expected boolean")),
("(join-strings \"a\" \"b\" \"c\")", success("a,b,c")),
("(join-strings 1 2)", SpecificError("expected string")),
// Dynamic higher-order use of a builtin comparison: pass `>` as a value.
("((lambda (op a b c) (op a b c)) > 9 6 2)", success(true)),
("((lambda (op a b c) (op a b c)) > 9 6 7)", success(false)),
];
run_tests_in_specific_environment(&mut env, test_cases);
}
#[test]
fn test_get_all_bindings_with_parent() {
let mut parent = create_global_env();
parent.define("parent-var".into(), val(1));
let mut child = Environment::with_parent(parent);
child.define("child-var".into(), val(2));
let bindings = child.get_all_bindings();
assert!(bindings.iter().any(|(n, _)| n == "child-var"));
assert!(bindings.iter().any(|(n, _)| n == "parent-var"));
}
#[test]
#[expect(clippy::too_many_lines)] // Comprehensive test coverage is intentionally thorough
fn test_comprehensive_operations_data_driven() {
let test_cases = vec![
// === SELF-EVALUATING FORMS ===
// Numbers
("42", success(42)),
("-271", success(-271)),
("0", success(0)),
("9223372036854775807", success(i64::MAX)),
("-9223372036854775808", success(i64::MIN)),
// Booleans
("#t", success(true)),
("#f", success(false)),
// Strings
("\"hello\"", success("hello")),
("\"hello world\"", success("hello world")),
("\"\"", success("")),
("\"with\\\"quotes\"", success("with\"quotes")),
// === ARITHMETIC OPERATIONS ===
// Addition (allows 0 arguments - returns 0)
("(+ 1 2 3)", success(6)),
("(+ 0)", success(0)),
("(+ 42)", success(42)),
("(+ -5 10)", success(5)),
("(+)", success(0)), // Addition with no args returns 0
// Subtraction (requires at least 1 argument)
("(- 10 3 2)", success(5)),
("(- 10)", success(-10)), // Unary negation
("(- 0)", success(0)),
("(- -5)", success(5)),
("(- 100 50 25)", success(25)),
// Multiplication (requires at least 1 argument)
("(* 2 3 4)", success(24)),
("(* 0 100)", success(0)),
("(* 1)", success(1)),
("(* -2 3)", success(-6)),
("(* 7)", success(7)), // Single argument returns itself
// Mixed operations with nested expressions
("(+ (* 2 3) (- 8 2))", success(12)),
("(* (+ 1 2) (- 5 2))", success(9)),
("(- (+ 10 5) (* 2 3))", success(9)),
// Arithmetic overflow errors
("(+ 9223372036854775807 1)", Error), // i64::MAX + 1
("(- -9223372036854775808)", Error), // -(i64::MIN)
("(- -9223372036854775808 1)", Error), // i64::MIN - 1
("(* 4611686018427387904 2)", Error), // (i64::MAX/2 + 1) * 2
// === EQUALITY AND COMPARISON OPERATIONS ===
// Numeric equality (spec-compliant - only accepts numbers)
("(= 5 5)", success(true)),
("(= 5 6)", success(false)),
("(= 0 0)", success(true)),
("(= -1 -1)", success(true)),
("(= 100 200)", success(false)),
// = rejects non-numbers (type errors)
("(= \"hello\" \"hello\")", Error),
("(= #t #t)", Error),
("(= #f #f)", Error),
// General equality with equal? (works for all types)
("(equal? 5 5)", success(true)),
("(equal? 5 6)", success(false)),
("(equal? \"hello\" \"hello\")", success(true)),
("(equal? \"hello\" \"world\")", success(false)),
("(equal? #t #t)", success(true)),
("(equal? #t #f)", success(false)),
("(equal? #f #f)", success(true)),
// Numeric comparison operators
("(< 3 5)", success(true)),
("(< 5 3)", success(false)),
("(< 0 1)", success(true)),
("(< -5 -3)", success(true)),
("(> 5 3)", success(true)),
("(> 3 5)", success(false)),
("(> 1 0)", success(true)),
("(> -3 -5)", success(true)),
("(<= 3 5)", success(true)),
("(<= 5 5)", success(true)),
("(<= 5 3)", success(false)),
("(<= 0 0)", success(true)),
("(>= 5 3)", success(true)),
("(>= 5 5)", success(true)),
("(>= 3 5)", success(false)),
("(>= 0 0)", success(true)),
// === QUOTE OPERATIONS ===
// Longhand quote syntax
("(quote hello)", success(sym("hello"))),
("(quote foo)", success(sym("foo"))),
("(quote (1 2 3))", success([1, 2, 3])),
("(quote (+ 1 2))", success([sym("+"), val(1), val(2)])),
("(quote (a b c))", success([sym("a"), sym("b"), sym("c")])),
("(quote ())", success(nil())), // Empty list (nil)
// Shorthand quote syntax
("'hello", success(sym("hello"))),
("'(1 2 3)", success([1, 2, 3])),
("'(+ 1 2)", success([sym("+"), val(1), val(2)])),
("'()", success(nil())), // Empty list (nil) via shorthand
("'42", success(42)),
("'#t", success(true)),
// Nested quotes
("'(quote x)", success([sym("quote"), sym("x")])),
("''x", success([sym("quote"), sym("x")])),
// === DYNAMIC FUNCTION CALLS IN OPERATOR POSITION ===
// Test that expressions in operator position are evaluated correctly
("((if #t + *) 2 3)", success(5)), // + was chosen, 2 + 3 = 5
("((if #f + *) 2 3)", success(6)), // * was chosen, 2 * 3 = 6
// Test lambda in operator position
("((lambda (x) (* x x)) 4)", success(16)), // 4 * 4 = 16
// === LIST OPERATIONS ===
// Basic list access
("(car (list 1 2 3))", success(1)),
("(car (list \"first\" \"second\"))", success("first")),
("(cdr (list 1 2 3))", success([2, 3])),
("(cdr (list \"a\" \"b\" \"c\"))", success(["b", "c"])),
// List construction
("(cons 1 (list 2 3))", success([1, 2, 3])),
("(cons \"x\" (list \"y\" \"z\"))", success(["x", "y", "z"])),
("(list)", success(nil())),
("(list 1)", success([1])),
("(list 1 2 3 4)", success([1, 2, 3, 4])),
// === NIL REPRESENTATION AND OPERATIONS ===
// Test strict evaluation semantics: () is NOT self-evaluating
// This is a very common Scheme extension, but we're trying to be minimalist to the spec
("()", Error), // Empty list cannot be evaluated.
// null? predicate tests
("(null? '())", success(true)),
("(null? (list))", success(true)),
("(null? (quote ()))", success(true)),
("(null? 42)", success(false)),
("(null? #f)", success(false)),
// cons with nil (additional cases beyond basic list construction)
("(cons 1 '())", success([1])),
("(cons 'a (cons 'b '()))", success([sym("a"), sym("b")])),
// Lambda with empty parameter list
("((lambda () 42))", success(42)),
// === STRING OPERATIONS ===
// Basic string concatenation
("(string-append)", success("")),
("(string-append \"hello\")", success("hello")),
(
"(string-append \"hello\" \" \" \"world\")",
success("hello world"),
),
("(string-append \"\" \"test\" \"\")", success("test")),
("(string-append 42)", Error),
("(string-append \"hello\" 123)", Error),
("(string-append #t \"world\")", Error),
// === MATH OPERATIONS - MAX/MIN ===
// Basic max operations
("(max 5)", success(5)),
("(max 1 2 3)", success(3)),
("(max 3 1 2)", success(3)),
("(max -5 -1 -10)", success(-1)),
// Basic min operations
("(min 5)", success(5)),
("(min 1 2 3)", success(1)),
("(min 3 1 2)", success(1)),
("(min -5 -1 -10)", success(-10)),
// Error cases - non-number arguments
("(max \"hello\")", Error),
("(min #t)", Error),
("(max 1 \"hello\")", Error),
("(min 1 #t)", Error),
// === CONDITIONAL OPERATIONS ===
// Basic if expressions
("(if #t 1 2)", success(1)),
("(if #f 1 2)", success(2)),
("(if #t \"yes\" \"no\")", success("yes")),
("(if #f \"yes\" \"no\")", success("no")),
// if with computed conditions
("(if (> 5 3) \"greater\" \"lesser\")", success("greater")),
("(if (< 5 3) \"greater\" \"lesser\")", success("lesser")),
("(if (equal? 1 1) 42 0)", success(42)),
// SCHEME-JSONLOGIC-STRICT: if condition must be a boolean (rejects truthy/falsy)
("(if 0 1 2)", Error),
("(if 42 1 2)", Error),
("(if () 1 2)", Error),
("(if \"hello\" 1 2)", Error),
("(if '() 1 2)", Error), // nil as condition should error
("(if #f 42 '())", success(nil())), // if returning nil is valid
// Note: Arity errors are now caught at parse time - see scheme.rs tests
// === BOOLEAN LOGIC OPERATIONS ===
// and operator - SCHEME-STRICT: Require at least 1 argument (Scheme R7RS allows 0 args, returns #t)
("(and #t)", success(true)),
("(and #f)", success(false)),
("(and #t #t)", success(true)),
("(and #t #f)", success(false)),
("(and #f #t)", success(false)),
("(and #t #t #t)", success(true)),
("(and #t #t #f)", success(false)),
// and errors - SCHEME-JSONLOGIC-STRICT: and requires boolean arguments
// Note: Arity errors are now caught at parse time - see scheme.rs tests
("(and 1 2 3)", Error), // rejects non-booleans
("(and 1 #f 3)", Error), // rejects non-booleans
// or operator - SCHEME-STRICT: Require at least 1 argument (Scheme R7RS allows 0 args, returns #f)
("(or #t)", success(true)),
("(or #f)", success(false)),
("(or #t #f)", success(true)),
("(or #f #t)", success(true)),
("(or #f #f)", success(false)),
("(or #f #f #t)", success(true)),
("(or #f #f #f)", success(false)),
// or errors - SCHEME-JSONLOGIC-STRICT: or requires boolean arguments
// Note: Arity errors are now caught at parse time - see scheme.rs tests
("(or #f 2 3)", Error), // rejects non-booleans
("(or 1 2 3)", Error), // rejects non-booleans
// not operator (requires exactly 1 boolean argument)
("(not #t)", success(false)),
("(not #f)", success(true)),
// not errors - SCHEME-JSONLOGIC-STRICT: not requires boolean arguments
("(not ())", Error), // rejects non-booleans
("(not 0)", Error), // rejects non-booleans
("(not 42)", Error), // rejects non-booleans
("(not \"hello\")", Error), // rejects non-booleans
// Complex boolean expressions
("(and (or #f #t) (not #f))", success(true)),
("(or (and #f #t) (not #f))", success(true)),
("(not (and #t #f))", success(true)),
("(and (> 5 3) (< 2 4))", success(true)),
("(or (= 1 2) (= 2 2))", success(true)),
// Short-circuit evaluation - undefined variables not evaluated due to short-circuit
("(and #f undefined-var)", success(false)), // should not evaluate undefined-var
("(or #t undefined-var)", success(true)), // should not evaluate undefined-var
// === STRICT EVALUATION SEMANTICS ===
// SCHEME-STRICT: Empty list () is NOT self-evaluating (must be quoted)
// This is stricter than standard Scheme but more predictable
("()", Error), // Empty list should error when evaluated directly
// SCHEME-STRICT: if condition must be boolean (rejects truthy/falsy including nil)
("(if '() 1 2)", Error), // nil as condition should error
// null? function works with quoted empty lists
("(null? '())", success(true)),
("(null? (list 1))", success(false)),
// === ERROR FUNCTION OPERATIONS ===
// Test error with string message
(
"(error \"Something went wrong\")",
SpecificError("Something went wrong"),
),
// Test error with symbol message
("(error oops)", SpecificError("oops")),
// Test error with number message
("(error 42)", SpecificError("42")),
// Test error with multiple arguments
(
"(error \"Error:\" 42 \"occurred\")",
SpecificError("Error: 42 occurred"),
),
// Test error with no arguments
("(error)", SpecificError("Error")),
// === ERROR PROPAGATION AND HANDLING ===
// Test undefined variable errors
("undefined-var", Error),
// Test type errors propagate through calls
("(not 42)", SpecificError("expected boolean")), // Type error with specific message
("(car \"not-a-list\")", Error), // Type error
// Test errors in nested expressions
("(+ 1 (car \"not-a-list\"))", Error),
("(if (not 42) 1 2)", Error),
// Test lambda parameter errors
("(lambda (x x) x)", Error), // Duplicate params
("(lambda \"not-a-list\" 42)", Error), // Invalid params
// Test define errors
("(define 123 42)", Error), // Invalid var name
("(define \"not-symbol\" 42)", Error), // Invalid var name
// === ERROR CASES ===
// Unbound variables
(
"undefined-var",
SpecificError("Unbound variable: undefined-var"),
),
// set! special form test - not implemented in this interpreter
// This Environment model uses immutable bindings where variables are looked up
// by traversing the environment chain, but mutation would require mutable references
// throughout the chain. If set! were supported this design would need revisiting
("(set! x 42)", SpecificError("Unbound variable: set!")), // Unsupported special forms appear as unbound variables
// Type errors
("(+ 1 \"hello\")", SpecificError("expected number")),
// TypeError has extra annotation inside lambda body
(
"((lambda (x) (+ x \"hello\")) 1)",
SpecificError("In lambda"),
),
("(1 2 3)", SpecificError("Cannot apply non-function")),
];
run_comprehensive_tests(test_cases);
// === ENVIRONMENT-SENSITIVE TESTS ===
// Tests that require shared state between expressions in the same environment
let environment_test_cases = vec![
// === DEFINE AND LOOKUP ===
// Basic variable definition and lookup
TestEnvironment(vec![
test_setup!("(define x 42)"), // Define variable
("x", success(42)), // Should be able to lookup defined variable
("y", Error), // Undefined variable should error
]),
// === DEFINE AND VARIABLES ===
// Variable redefinition and usage in expressions
TestEnvironment(vec![
// Define a variable
test_setup!("(define x 42)"),
("x", success(42)),
// Use variable in expressions
("(+ x 8)", success(50)),
// Redefine variable
test_setup!("(define x 100)"),
("x", success(100)),
]),
// === BUILTIN FUNCTIONS VIA DYNAMIC SYMBOL LOOKUP ===
// Builtin functions called dynamically through symbols
TestEnvironment(vec![
// Store a reference to + in a variable, then call it
test_setup!("(define my-add +)"),
("(my-add 10 20)", success(30)),
// Store reference to equal? and call it
test_setup!("(define my-eq equal?)"),
("(my-eq 5 5)", success(true)),
]),
// === LAMBDA FUNCTIONS VIA EVAL_LIST (Test 1) ===
// Test immediate lambda call
TestEnvironment(vec![("((lambda (x y) (+ x y)) 3 4)", success(7))]),
// === LAMBDA FUNCTIONS VIA EVAL_LIST (Test 2) ===
// Test lambda definition and call
TestEnvironment(vec![
test_setup!("(define add-one (lambda (x) (+ x 1)))"),
("(add-one 42)", success(43)),
]),
// === DEFINE WITH VARIOUS VALUE TYPES ===
// Test defining and retrieving different types
TestEnvironment(vec![
// Define numbers, booleans, strings
test_setup!("(define x 42)"),
test_setup!("(define flag #t)"),
test_setup!("(define name \"test\")"),
// Verify they can be retrieved
("x", success(42)),
("flag", success(true)),
("name", success("test")),
// Define and retrieve builtin functions (test that it's a BuiltinFunction)
test_setup!("(define my-plus +)"),
]),
// === NESTED EVALUATION PATHS ===
// Test deeply nested expressions that exercise multiple evaluation paths
TestEnvironment(vec![
test_setup!("(define square (lambda (x) (* x x)))"), // Define helper function
// This expression exercises multiple evaluation paths:
// - if (special form via PrecompiledOp)
// - > (builtin via PrecompiledOp)
// - square (lambda via dynamic call)
// - + (builtin via PrecompiledOp)
("(if (> 5 3) (square (+ 2 1)) 0)", success(9)), // (+ 2 1) = 3, square(3) = 9
]),
// === SELF EVALUATING FORMS ===
// BuiltinFunction and Function are self-evaluating (test with environment)
TestEnvironment(vec![
test_setup!("(define f +)"),
// Note: We can't easily test the type in data-driven approach,
// but we can verify it behaves correctly as a function
("(f 2 3)", success(5)),
]),
// === IMPOSSIBLE PRECOMPILED OP IN EVAL_LIST ===
// This test documents that PrecompiledOp can never reach eval_list
TestEnvironment(vec![
// Set up dynamic builtin reference and lambda function
test_setup!("(define add +)"),
test_setup!("(define sq (lambda (x) (* x x)))"),
// 1. Direct builtin calls (via PrecompiledOp in main eval)
("(+ 1 2)", success(3)),
// 2. Dynamic builtin calls (via BuiltinFunction in eval_list)
("(add 1 2)", success(3)),
// 3. Lambda calls (via Function in eval_list)
("(sq 3)", success(9)),
// 4. Complex nested calls - still no PrecompiledOp in eval_list
("((lambda (f x) (f x x)) + 5)", success(10)), // f=+, x=5, so (+ 5 5) = 10
("((lambda (g y) (g y)) sq 6)", success(36)), // g=sq, y=6, so (sq 6) = 36
// 5. Higher-order function combinations
("((lambda (op a b) (op a b)) * 3 4)", success(12)), // op=*, a=3, b=4
("((lambda (fn) (fn 7)) sq)", success(49)), // fn=sq, so (sq 7) = 49
]),
// === HIGHER ORDER FUNCTIONS ===
// Define a function that takes another function as argument
TestEnvironment(vec![
test_setup!("(define twice (lambda (f x) (f (f x))))"),
test_setup!("(define inc (lambda (x) (+ x 1)))"),
("(twice inc 5)", success(7)),
]),
// === LEXICAL SCOPING ===
// Test that lambda captures its environment and parameter shadowing
TestEnvironment(vec![
// Test that lambda captures its environment
test_setup!("(define x 10)"),
test_setup!("(define make-adder (lambda (n) (lambda (x) (+ x n))))"),
test_setup!("(define add5 (make-adder 5))"),
("(add5 3)", success(8)),
// Test parameter shadowing
test_setup!("(define f (lambda (x) (lambda (x) (* x 2))))"),
test_setup!("(define g (f 10))"),
("(g 3)", success(6)),
]),
// === LAMBDA AND DEFINE EDGE CASES ===
// Test lambda with various parameter patterns
TestEnvironment(vec![
test_setup!("(define id (lambda (x) x))"),
("(id 42)", success(42)),
// Test lambda with multiple parameters
test_setup!("(define add3 (lambda (a b c) (+ a b c)))"),
("(add3 1 2 3)", success(6)),
// Test lambda with no parameters
test_setup!("(define const42 (lambda () 42))"),
("(const42)", success(42)),
// Test closures capture environment
test_setup!("(define x 10)"),
test_setup!("(define add-x (lambda (y) (+ x y)))"),
("(add-x 5)", success(15)),
// Test nested lambdas (higher-order functions)
test_setup!("(define make-adder (lambda (n) (lambda (x) (+ n x))))"),
test_setup!("(define add5 (make-adder 5))"),
("(add5 3)", success(8)),
// Test lambda arity checking
("(id)", Error), // Too few args
("(id 1 2)", Error), // Too many args
// Test define with function values
test_setup!("(define plus +)"),
("(plus 2 3)", success(5)),
// Test redefining variables
test_setup!("(define y 100)"),
("y", success(100)),
test_setup!("(define y 200)"),
("y", success(200)),
]),
// === ENVIRONMENT SCOPING EDGE CASES (Test 1) ===
// Global vs local scope (parameter shadowing)
TestEnvironment(vec![
test_setup!("(define x 1)"),
test_setup!("(define f (lambda (x) (+ x 10)))"), // parameter x shadows global x
("(f 5)", success(15)), // uses parameter x=5, not global x=1
("x", success(1)), // global x unchanged
("(f x)", success(11)), // uses global x=1 as argument: 1+10=11
]),
// === ENVIRONMENT SCOPING EDGE CASES (Test 2) ===
// Closure behavior with variable redefinition
TestEnvironment(vec![
test_setup!("(define y 100)"),
test_setup!("(define g (lambda () y))"), // closure captures y=100
test_setup!("(define y 200)"), // redefine y to 200
// This implementation uses lexical scoping - closures see binding at definition time
("(g)", success(100)), // closure still sees original y=100
("y", success(200)), // global y is now 200
]),
// === ENVIRONMENT SCOPING EDGE CASES (Test 3) ===
// Nested function definitions (higher-order functions)
TestEnvironment(vec![
test_setup!("(define outer (lambda (a) (lambda (b) (+ a b))))"),
test_setup!("(define add10 (outer 10))"), // creates a function that adds 10
("(add10 5)", success(15)), // 10 + 5 = 15
("(add10 25)", success(35)), // 10 + 25 = 35
("((outer 3) 7)", success(10)), // direct call: 3 + 7 = 10
]),
// === LAMBDA AND FUNCTION CALLS (Test 1) ===
// Test valid lambda definitions and calls
TestEnvironment(vec![
// Define a simple lambda
test_setup!("(define square (lambda (x) (* x x)))"),
("(square 5)", success(25)),
// Lambda with multiple parameters
test_setup!("(define add (lambda (a b) (+ a b)))"),
("(add 3 4)", success(7)),
// Lambda with no parameters
test_setup!("(define get-answer (lambda () 42))"),
("(get-answer)", success(42)),
]),
// === LAMBDA AND FUNCTION CALLS (Test 2) ===
// Test error cases for lambda (each in separate environment to avoid interference)
TestEnvironment(vec![
// Duplicate parameter names should be rejected
("(lambda (x x) (+ x x))", Error),
("(lambda (a b a) (* a b))", Error),
// Variadic lambda forms should be rejected (we only support fixed-arity)
("(lambda args (+ 1 2))", Error), // Symbol parameter list
// Non-symbol parameters should be rejected
("(lambda (1 2) (+ 1 2))", Error),
("(lambda (\"x\" y) (+ x y))", Error),
]),
// === COMPLEX EXPRESSIONS (Test 1) ===
// Test complex nested expression in isolation
TestEnvironment(vec![(
"(((lambda (x) (lambda (y) (+ x y))) 10) 5)",
success(15),
)]),
// === COMPLEX EXPRESSIONS (Test 2) ===
// Test list processing functions
TestEnvironment(vec![
// Simple list processing (non-recursive version)
test_setup!("(define first (lambda (lst) (car lst)))"),
("(first (list 1 2 3 4))", success(1)),
// Test list construction and access
test_setup!("(define make-pair (lambda (a b) (list a b)))"),
test_setup!("(define get-first (lambda (pair) (car pair)))"),
test_setup!("(define get-second (lambda (pair) (car (cdr pair))))"),
test_setup!("(define my-pair (make-pair 42 \"hello\"))"),
("(get-first my-pair)", success(42)),
("(get-second my-pair)", success("hello")),
]),
];
run_tests_in_environment(environment_test_cases);
}
// Additional type check that can't be done data-driven
#[test]
fn test_builtin_function_self_evaluation() {
let mut env = create_global_env();
eval(&parse_scheme("(define f +)").unwrap(), &mut env).unwrap();
let result = eval(&parse_scheme("f").unwrap(), &mut env).unwrap();
match result {
Value::BuiltinFunction { .. } => {} // Self-evaluating
_ => panic!("Expected BuiltinFunction to be self-evaluating"),
}
}
#[test]
fn test_recursive_functions() {
// This test demonstrates the current limitation: recursive functions fail
// because the function name is not yet bound when the lambda body is created.
// In a full Scheme implementation with letrec semantics, these should work.
let recursive_test_cases = vec![
// === SINGLE RECURSIVE FUNCTIONS (Currently Failing) ===
TestEnvironment(vec![
// Simple factorial function - should fail because 'factorial' is unbound in lambda body
test_setup!(
"(define factorial (lambda (n) (if (= n 0) 1 (* n (factorial (- n 1))))))"
),
(
"(factorial 5)",
SpecificError("Unbound variable: factorial"),
), // Current limitation
]),
// === MUTUALLY RECURSIVE FUNCTIONS (Currently Failing) ===
TestEnvironment(vec![
// Even/odd mutual recursion - fails because functions can't see each other during definition
test_setup!("(define is-even (lambda (n) (if (= n 0) #t (is-odd (- n 1)))))"),
test_setup!("(define is-odd (lambda (n) (if (= n 0) #f (is-even (- n 1)))))"),
("(is-even 4)", SpecificError("Unbound variable: is-odd")), // is-even tries to call is-odd but it's not visible
("(is-odd 3)", SpecificError("Unbound variable: is-odd")), // is-odd -> is-even -> is-odd, but is-odd not visible in is-even
]),
// === EDGE CASES FOR RECURSION ===
TestEnvironment(vec![
// Self-referencing lambda in complex expression
test_setup!(
"(define countdown (lambda (n) (if (<= n 0) (list) (cons n (countdown (- n 1))))))"
),
(
"(countdown 3)",
SpecificError("Unbound variable: countdown"),
), // Current limitation
]),
TestEnvironment(vec![
// Indirect self-reference through higher-order function
test_setup!("(define apply-self (lambda (f x) (f x)))"),
test_setup!(
"(define factorial-indirect (lambda (n) (if (= n 0) 1 (* n (apply-self factorial-indirect (- n 1))))))"
),
(
"(factorial-indirect 3)",
SpecificError("Unbound variable: factorial-indirect"),
), // Current limitation
]),
// === EDGE CASES THAT ACTUALLY WORK (Recursion Workarounds) ===
TestEnvironment(vec![
// Self-application trick (Y combinator style) - this actually works!
test_setup!("(define self-apply (lambda (f x) (f f x)))"),
test_setup!(
"(define factorial-trick (lambda (self n) (if (= n 0) 1 (* n (self self (- n 1))))))"
),
("(self-apply factorial-trick 5)", success(120)), // Works by passing function to itself
]),
TestEnvironment(vec![
// Higher-order function recursion maker - this also works!
test_setup!("(define make-recursive (lambda (f) (lambda (x) ((f f) x))))"),
test_setup!(
"(define fib-maker (lambda (self) (lambda (n) (if (< n 2) n (+ ((self self) (- n 1)) ((self self) (- n 2)))))))"
),
test_setup!("(define fib (make-recursive fib-maker))"),
("(fib 6)", success(8)), // Fibonacci works through self-application
]),
TestEnvironment(vec![
// Countdown using self-application - redefine helper for this environment
test_setup!("(define make-recursive (lambda (f) (lambda (x) ((f f) x))))"),
test_setup!(
"(define countdown-maker (lambda (self) (lambda (n) (if (<= n 0) (list) (cons n ((self self) (- n 1)))))))"
),
test_setup!("(define countdown (make-recursive countdown-maker))"),
("(countdown 3)", success([3, 2, 1])), // Recursive list building works
]),
TestEnvironment(vec![
// Mutual recursion simulation - alternating even/odd through single recursive function
test_setup!(
"(define parity-maker (lambda (self) (lambda (n is-even) (if (= n 0) is-even ((self self) (- n 1) (not is-even))))))"
),
test_setup!("(define check-parity (parity-maker parity-maker))"),
("(check-parity 4 #t)", success(true)), // 4 is even
("(check-parity 3 #t)", success(false)), // 3 is not even
("(check-parity 3 #f)", success(true)), // 3 is odd
]),
];
// Run all the recursive function tests that demonstrate current limitations
// and successful workarounds
run_tests_in_environment(recursive_test_cases);
}
#[test]
fn test_evaluation_depth_limit() {
let depth_test_environments = vec![TestEnvironment(vec![
// Define the deep recursion helper function
test_setup!(
"(define make-deep (lambda (self depth) (if (= depth 0) 42 (+ 1 (self self (- depth 1))))))"
),
// Test that shallow depth works
("(make-deep make-deep 10)", success(52)), // 42 + 10
// Test that deep evaluation is caught - use a value that should exceed MAX_EVAL_DEPTH
// Each recursive call increases depth through function calls and if statements
("(make-deep make-deep 1000)", SpecificError("depth")),
])];
run_tests_in_environment(depth_test_environments);
}
}