grift_eval 1.4.0

Lisp evaluator for the Grift Scheme language
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
//! Edge Case Tests for Grift's Syntax-Case Implementation
//!
//! These tests explore the boundaries of grift's macro system, particularly
//! behaviors that differ from Racket/Guile due to grift's single-phase model.
//!
//! Test categories:
//! 1. First-class syntax object manipulation
//! 2. Runtime-created syntax
//! 3. Cross-environment syntax usage
//! 4. Phase violation tests (things that work in grift but not Racket/Guile)
//! 5. Hygiene edge cases

mod common;

use grift_eval::*;
use common::eval_to_num;

// ═══════════════════════════════════════════════════════════════════════════
// Test Suite A: First-Class Syntax Object Manipulation
// ═══════════════════════════════════════════════════════════════════════════
// These tests verify that syntax objects behave as first-class values,
// which is a key feature of grift's single-phase model.

/// Test A.1: Syntax objects can be stored in variables
///
/// In Racket/Guile, runtime-created syntax has limited lexical context.
/// In grift, syntax objects preserve their full creation-site environment.
#[test]
fn test_a1_syntax_in_variable() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define my-stx
          (let ((x 42))
            (syntax x)))
    "#).unwrap();
    
    eval.eval_str(r#"
        (define-syntax use-my-stx
          (lambda (_) my-stx))
    "#).unwrap();
    
    assert_eq!(eval_to_num(&lisp, &mut eval, "(use-my-stx)"), 42,
        "Syntax stored in variable should preserve its binding");
}

/// Test A.2: Syntax objects in pairs
///
/// Syntax objects can be consed like any other value.
#[test]
fn test_a2_syntax_in_pair() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define stx-pair
          (let ((a 10) (b 20))
            (cons (syntax a) (syntax b))))
    "#).unwrap();
    
    eval.eval_str(r#"
        (define-syntax use-car
          (lambda (_) (car stx-pair)))
    "#).unwrap();
    
    eval.eval_str(r#"
        (define-syntax use-cdr
          (lambda (_) (cdr stx-pair)))
    "#).unwrap();
    
    assert_eq!(eval_to_num(&lisp, &mut eval, "(use-car)"), 10);
    assert_eq!(eval_to_num(&lisp, &mut eval, "(use-cdr)"), 20);
}

/// Test A.3: Syntax objects in vectors
///
/// Syntax objects can be stored in vectors.
#[test]
fn test_a3_syntax_in_vector() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define stx-vec
          (let ((x 100))
            (vector (syntax x) (syntax x))))
    "#).unwrap();
    
    eval.eval_str(r#"
        (define-syntax use-first
          (lambda (_) (vector-ref stx-vec 0)))
    "#).unwrap();
    
    assert_eq!(eval_to_num(&lisp, &mut eval, "(use-first)"), 100);
}

// ═══════════════════════════════════════════════════════════════════════════
// Test Suite B: Runtime Syntax Creation
// ═══════════════════════════════════════════════════════════════════════════
// These tests demonstrate grift's ability to create syntax at runtime,
// which would be restricted in phase-separated systems.

/// Test B.1: Function that returns syntax
///
/// A regular function can return syntax objects for use in macros.
#[test]
fn test_b1_function_returning_syntax() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define (make-const-syntax n)
          (let ((val n))
            (syntax val)))
    "#).unwrap();
    
    eval.eval_str("(define stx-5 (make-const-syntax 5))").unwrap();
    eval.eval_str("(define stx-10 (make-const-syntax 10))").unwrap();
    
    eval.eval_str(r#"
        (define-syntax get-5
          (lambda (_) stx-5))
    "#).unwrap();
    
    eval.eval_str(r#"
        (define-syntax get-10
          (lambda (_) stx-10))
    "#).unwrap();
    
    assert_eq!(eval_to_num(&lisp, &mut eval, "(get-5)"), 5);
    assert_eq!(eval_to_num(&lisp, &mut eval, "(get-10)"), 10);
}

/// Test B.2: Conditional syntax creation
///
/// Syntax can be created conditionally at runtime.
#[test]
fn test_b2_conditional_syntax_creation() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define (make-syntax-or-literal use-syntax)
          (let ((x 42))
            (if use-syntax
                (syntax x)
                x)))
    "#).unwrap();
    
    // When using syntax, we get the captured binding
    eval.eval_str("(define my-stx (make-syntax-or-literal #t))").unwrap();
    eval.eval_str(r#"
        (define-syntax use-stx
          (lambda (_) my-stx))
    "#).unwrap();
    
    assert_eq!(eval_to_num(&lisp, &mut eval, "(use-stx)"), 42);
}

/// Test B.3: Recursive syntax creation
///
/// Syntax can be created recursively.
#[test]
fn test_b3_recursive_syntax_creation() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define (nested-syntax depth)
          (let ((x depth))
            (if (= depth 0)
                (syntax x)
                (nested-syntax (- depth 1)))))
    "#).unwrap();
    
    eval.eval_str("(define deep-stx (nested-syntax 5))").unwrap();
    eval.eval_str(r#"
        (define-syntax use-deep
          (lambda (_) deep-stx))
    "#).unwrap();
    
    // The innermost call creates syntax with x=0
    assert_eq!(eval_to_num(&lisp, &mut eval, "(use-deep)"), 0);
}

// ═══════════════════════════════════════════════════════════════════════════
// Test Suite C: Hygiene Edge Cases
// ═══════════════════════════════════════════════════════════════════════════

/// Test C.1: Multiple macro invocations with same introduced names
///
/// Each macro expansion should have its own hygienic scope.
#[test]
fn test_c1_multiple_expansions_hygiene() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax with-temp
          (lambda (stx)
            (syntax-case stx ()
              ((_ val body)
               (syntax (let ((temp val))
                         body))))))
    "#).unwrap();
    
    // Nested uses of with-temp should each have their own 'temp'
    let result = eval.eval_str(r#"
        (with-temp 10
          (with-temp 20
            (+ temp temp)))
    "#).unwrap();
    
    // The innermost temp is 20, so 20+20=40
    assert_eq!(lisp.get(result).unwrap().as_number(), Some(40));
}

/// Test C.2: Pattern variable shadowing local binding
///
/// When a local binding shadows a pattern variable, syntax should use the local.
#[test]
fn test_c2_pattern_shadowing() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax shadow-test
          (lambda (stx)
            (syntax-case stx ()
              ((kw x)
               (let ((outer-x (syntax x)))
                 (let ((x 999))  ; Shadows pattern variable x
                   (let ((inner-x (syntax x)))
                     ;; outer-x refers to pattern x, inner-x refers to local x
                     (if (free-identifier=? outer-x inner-x)
                         (syntax 'same)
                         (syntax 'different)))))))))
    "#).unwrap();
    
    let result = eval.eval_str("(shadow-test 123)").unwrap();
    assert!(lisp.symbol_matches(result, "different").unwrap(),
        "Pattern variable and local binding should be different identifiers");
}

/// Test C.3: Hygiene with recursive macros
///
/// Recursive macro calls should maintain proper hygiene.
#[test]
fn test_c3_recursive_macro_hygiene() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax sum-to
          (lambda (stx)
            (syntax-case stx ()
              ((kw n)
               (let ((num (syntax->datum (syntax n))))
                 (if (= num 0)
                     (syntax 0)
                     (with-syntax ((m (- num 1)))
                       (syntax (+ n (sum-to m))))))))))
    "#).unwrap();
    
    // sum-to 3 = 3 + 2 + 1 + 0 = 6
    assert_eq!(eval_to_num(&lisp, &mut eval, "(sum-to 3)"), 6);
}

// ═══════════════════════════════════════════════════════════════════════════
// Test Suite D: datum->syntax and syntax->datum
// ═══════════════════════════════════════════════════════════════════════════

/// Test D.1: datum->syntax with template context
///
/// datum->syntax should create an identifier with the template's lexical context.
#[test]
fn test_d1_datum_to_syntax_context() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax make-ref
          (lambda (stx)
            (syntax-case stx ()
              ((kw name)
               (datum->syntax (syntax kw) (syntax->datum (syntax name)))))))
    "#).unwrap();
    
    eval.eval_str("(define foo 42)").unwrap();
    
    // make-ref should create a reference that resolves in the macro's context
    assert_eq!(eval_to_num(&lisp, &mut eval, "(make-ref foo)"), 42);
}

/// Test D.2: syntax->datum round-trip
///
/// Converting syntax to datum and back should preserve structure.
#[test]
fn test_d2_syntax_datum_roundtrip() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax structure-test
          (lambda (stx)
            (syntax-case stx ()
              ((kw (a b c))
               (let ((datum (syntax->datum (syntax (a b c)))))
                 (if (and (pair? datum)
                          (eq? (car datum) 'a)
                          (eq? (cadr datum) 'b)
                          (eq? (caddr datum) 'c))
                     (syntax 'correct)
                     (syntax 'wrong)))))))
    "#).unwrap();
    
    let result = eval.eval_str("(structure-test (a b c))").unwrap();
    assert!(lisp.symbol_matches(result, "correct").unwrap());
}

// ═══════════════════════════════════════════════════════════════════════════
// Test Suite E: with-syntax Edge Cases
// ═══════════════════════════════════════════════════════════════════════════

/// Test E.1: with-syntax with computed values
///
/// with-syntax should work with values computed at macro expansion time.
#[test]
fn test_e1_with_syntax_computed() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax double-literal
          (lambda (stx)
            (syntax-case stx ()
              ((kw n)
               (let ((doubled (* 2 (syntax->datum (syntax n)))))
                 (with-syntax ((result doubled))
                   (syntax result)))))))
    "#).unwrap();
    
    assert_eq!(eval_to_num(&lisp, &mut eval, "(double-literal 21)"), 42);
}

/// Test E.2: with-syntax with multiple bindings
///
/// with-syntax should handle multiple bindings correctly.
#[test]
fn test_e2_with_syntax_multiple() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax swap-and-add
          (lambda (stx)
            (syntax-case stx ()
              ((kw a b)
               (with-syntax ((x (syntax b))
                             (y (syntax a)))
                 (syntax (+ x y)))))))
    "#).unwrap();
    
    // Should compute (+ 20 10) = 30
    assert_eq!(eval_to_num(&lisp, &mut eval, "(swap-and-add 10 20)"), 30);
}

// ═══════════════════════════════════════════════════════════════════════════
// Test Suite F: Ellipsis Edge Cases
// ═══════════════════════════════════════════════════════════════════════════

/// Test F.1: Empty ellipsis match
///
/// Ellipsis should correctly handle zero matches.
#[test]
fn test_f1_empty_ellipsis() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax list-or-zero
          (lambda (stx)
            (syntax-case stx ()
              ((kw x ...)
               (syntax (list x ...))))))
    "#).unwrap();
    
    // Empty case
    let result = eval.eval_str("(list-or-zero)").unwrap();
    assert!(lisp.get(result).unwrap().is_nil(),
        "Empty ellipsis should produce empty list");
    
    // Non-empty case
    assert_eq!(eval_to_num(&lisp, &mut eval, "(length (list-or-zero 1 2 3))"), 3);
}

/// Test F.2: Ellipsis with multiple pattern variables
///
/// Multiple pattern variables under ellipsis should expand in parallel.
#[test]
fn test_f2_parallel_ellipsis() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax zip-add
          (lambda (stx)
            (syntax-case stx ()
              ((kw (a b) ...)
               (syntax (list (+ a b) ...))))))
    "#).unwrap();
    
    // (zip-add (1 10) (2 20) (3 30)) => (11 22 33)
    let result = eval.eval_str("(zip-add (1 10) (2 20) (3 30))").unwrap();
    let first = lisp.car(result).unwrap();
    assert_eq!(lisp.get(first).unwrap().as_number(), Some(11));
}

/// Test F.3: Ellipsis after fixed elements
///
/// Patterns with fixed elements followed by ellipsis.
#[test]
fn test_f3_fixed_then_ellipsis() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax first-then-rest
          (lambda (stx)
            (syntax-case stx ()
              ((kw first rest ...)
               (syntax (cons first (list rest ...)))))))
    "#).unwrap();
    
    let result = eval.eval_str("(first-then-rest 1 2 3 4)").unwrap();
    let car = lisp.car(result).unwrap();
    let cdr = lisp.cdr(result).unwrap();
    
    assert_eq!(lisp.get(car).unwrap().as_number(), Some(1));
    // Verify the rest is a list of (2 3 4)
    assert_eq!(lisp.list_len(cdr).unwrap(), 3);
}

// ═══════════════════════════════════════════════════════════════════════════
// Test Suite G: Identifier Comparison Edge Cases
// ═══════════════════════════════════════════════════════════════════════════

/// Test G.1: bound-identifier=? with identifiers from different contexts
///
/// Identifiers from different macro invocations should not be bound-identifier=?.
#[test]
fn test_g1_different_contexts_not_bound_eq() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    // Create identifiers in two separate let bindings - they should have different marks
    eval.eval_str(r#"
        (define-syntax check-different-contexts
          (lambda (stx)
            (syntax-case stx ()
              ((kw)
               (let ((id1 (datum->syntax (syntax kw) 'x))
                     (id2 (datum->syntax (syntax kw) 'x)))
                 ;; Same name, same template context - should be bound-identifier=?
                 (if (bound-identifier=? id1 id2)
                     (syntax 'same)
                     (syntax 'different)))))))
    "#).unwrap();
    
    let result = eval.eval_str("(check-different-contexts)").unwrap();
    // When created in the same macro expansion with same template, should be same
    assert!(lisp.symbol_matches(result, "same").unwrap(),
        "Identifiers with same name and template context should be bound-identifier=?");
}

/// Test G.2: free-identifier=? across environments
///
/// free-identifier=? should check if identifiers refer to the same binding.
#[test]
fn test_g2_free_identifier_same_binding() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str("(define global-x 100)").unwrap();
    
    eval.eval_str(r#"
        (define-syntax check-free-eq
          (lambda (stx)
            (syntax-case stx ()
              ((kw a b)
               (if (free-identifier=? (syntax a) (syntax b))
                   (syntax 'same)
                   (syntax 'different))))))
    "#).unwrap();
    
    // Same identifier twice should be free-identifier=?
    let result = eval.eval_str("(check-free-eq global-x global-x)").unwrap();
    assert!(lisp.symbol_matches(result, "same").unwrap());
}

// ═══════════════════════════════════════════════════════════════════════════
// Test Suite H: Macro-Defining Macros
// ═══════════════════════════════════════════════════════════════════════════

/// Test H.1: Simple macro-defining macro
///
/// A macro that defines another macro.
#[test]
fn test_h1_macro_defining_macro() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax define-constant-macro
          (lambda (stx)
            (syntax-case stx ()
              ((kw name val)
               (syntax (define-syntax name
                         (lambda (_) (syntax val))))))))
    "#).unwrap();
    
    eval.eval_str("(define-constant-macro forty-two 42)").unwrap();
    
    assert_eq!(eval_to_num(&lisp, &mut eval, "(forty-two)"), 42);
}

/// Test H.2: Parameterized macro generator
///
/// A macro that generates macros with different behavior.
#[test]
fn test_h2_parameterized_macro_generator() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax define-adder-macro
          (lambda (stx)
            (syntax-case stx ()
              ((kw name amount)
               (syntax (define-syntax name
                         (lambda (inner-stx)
                           (syntax-case inner-stx ()
                             ((_ x) (syntax (+ x amount)))))))))))
    "#).unwrap();
    
    eval.eval_str("(define-adder-macro add-5 5)").unwrap();
    eval.eval_str("(define-adder-macro add-10 10)").unwrap();
    
    assert_eq!(eval_to_num(&lisp, &mut eval, "(add-5 100)"), 105);
    assert_eq!(eval_to_num(&lisp, &mut eval, "(add-10 100)"), 110);
}

// ═══════════════════════════════════════════════════════════════════════════
// Test Suite I: Stress Tests
// ═══════════════════════════════════════════════════════════════════════════

/// Test I.1: Deeply nested let-syntax
///
/// Many levels of nested let-syntax should maintain proper scoping.
#[test]
fn test_i1_deeply_nested_let_syntax() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    let result = eval.eval_str(r#"
        (let-syntax ((a (lambda (stx) (syntax 1))))
          (let-syntax ((b (lambda (stx) (syntax (+ (a) 2)))))
            (let-syntax ((c (lambda (stx) (syntax (+ (b) 3)))))
              (c))))
    "#).unwrap();
    
    // 1 + 2 + 3 = 6
    assert_eq!(lisp.get(result).unwrap().as_number(), Some(6));
}

/// Test I.2: Large ellipsis expansion
///
/// Ellipsis should handle larger lists without issues.
#[test]
fn test_i2_large_ellipsis() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax sum-all
          (lambda (stx)
            (syntax-case stx ()
              ((kw x ...)
               (syntax (+ x ...))))))
    "#).unwrap();
    
    // Sum of 1 to 10
    assert_eq!(eval_to_num(&lisp, &mut eval, 
        "(sum-all 1 2 3 4 5 6 7 8 9 10)"), 55);
}

// ═══════════════════════════════════════════════════════════════════════════
// Test Suite J: Macro Limitation Tests
// ═══════════════════════════════════════════════════════════════════════════
// Tests that verify specific macro behaviors that were thought to be limitations
// but actually work correctly in Grift.

/// Test J.1: Compile-Time Arithmetic Without Runtime Values
///
/// Tests that datum->syntax can properly convert computed numeric results
/// back to syntax at macro expansion time.
#[test]
fn test_j1_compile_time_arithmetic() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax static-compute
          (lambda (stx)
            (syntax-case stx ()
              ((_ n m)
               (datum->syntax stx
                 (+ (syntax->datum (syntax n)) 
                    (syntax->datum (syntax m))))))))
    "#).unwrap();
    
    assert_eq!(eval_to_num(&lisp, &mut eval, "(static-compute 10 20)"), 30,
        "datum->syntax should properly convert computed numeric results");
}

/// Test J.2: Match Multiple Patterns with Different Arities
///
/// Tests that syntax-case can match patterns with different numbers of arguments.
/// This demonstrates that macros can have multiple clauses for different arities.
#[test]
fn test_j2_flexible_macro_simple_arities() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax flexible-macro
          (lambda (stx)
            (syntax-case stx ()
              ((_ a) 
               (syntax (list a)))
              ((_ a b)
               (syntax (list a b)))
              ((_ a b c)
               (syntax (list a b c))))))
    "#).unwrap();
    
    // Test single argument
    let result1 = eval.eval_str("(flexible-macro 1)").unwrap();
    assert_eq!(lisp.list_len(result1), Ok(1));
    
    // Test two arguments
    let result2 = eval.eval_str("(flexible-macro 1 2)").unwrap();
    assert_eq!(lisp.list_len(result2), Ok(2));
    
    // Test three arguments
    let result3 = eval.eval_str("(flexible-macro 1 2 3)").unwrap();
    assert_eq!(lisp.list_len(result3), Ok(3));
}

/// Test J.3: Nested Ellipsis Patterns
///
/// Tests that deeply nested ellipsis patterns like `((a ...) ...)` work correctly.
/// This was documented as a limitation but actually works in Grift.
#[test]
fn test_j3_nested_ellipsis_patterns() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax matrix-transpose
          (lambda (stx)
            (syntax-case stx ()
              ((_ ((a ...) ...))
               (syntax (quote ((a ...) ...)))))))
    "#).unwrap();
    
    let result = eval.eval_str("(matrix-transpose ((1 2 3) (4 5 6)))").unwrap();
    
    // The result should be ((1 2 3) (4 5 6))
    // Verify it's a list of two elements
    assert_eq!(lisp.list_len(result), Ok(2),
        "Nested ellipsis patterns should preserve structure");
    
    // Verify first sublist is (1 2 3)
    let first = lisp.car(result).unwrap();
    assert_eq!(lisp.list_len(first), Ok(3));
    let first_car = lisp.car(first).unwrap();
    assert_eq!(lisp.get(first_car).unwrap().as_number(), Some(1));
}

/// Test J.4: Fenders (Guards) in Patterns
///
/// Tests that fenders (guard expressions) in syntax-case work correctly
/// to conditionally match patterns based on the pattern variable values.
/// This was documented as a limitation but actually works in Grift.
#[test]
fn test_j4_fenders_guards() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax only-positive
          (lambda (stx)
            (syntax-case stx ()
              ((_ n)
               (> (syntax->datum (syntax n)) 0)
               (syntax (quote positive)))
              ((_ n)
               (syntax (quote non-positive))))))
    "#).unwrap();
    
    // Test positive number
    let result_pos = eval.eval_str("(only-positive 5)").unwrap();
    assert!(lisp.symbol_matches(result_pos, "positive").unwrap(),
        "Fender should match positive numbers");
    
    // Test negative number
    let result_neg = eval.eval_str("(only-positive -3)").unwrap();
    assert!(lisp.symbol_matches(result_neg, "non-positive").unwrap(),
        "Fender should reject negative numbers and fall through to next clause");
    
    // Test zero
    let result_zero = eval.eval_str("(only-positive 0)").unwrap();
    assert!(lisp.symbol_matches(result_zero, "non-positive").unwrap(),
        "Fender should reject zero and fall through to next clause");
}

/// Test J.5: Complex Literal Matching
///
/// Tests that syntax-case can correctly match literal keywords and
/// distinguish them from pattern variables.
#[test]
fn test_j5_complex_literal_matching() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax match-literals
          (lambda (stx)
            (syntax-case stx (foo bar baz)
              ((_ foo x) (syntax (quote (matched-foo x))))
              ((_ bar x) (syntax (quote (matched-bar x))))
              ((_ baz x) (syntax (quote (matched-baz x))))
              ((_ other x) (syntax (quote (matched-other other x)))))))
    "#).unwrap();
    
    // Test literal 'foo'
    let result_foo = eval.eval_str("(match-literals foo 1)").unwrap();
    let foo_car = lisp.car(result_foo).unwrap();
    assert!(lisp.symbol_matches(foo_car, "matched-foo").unwrap(),
        "Literal 'foo' should be matched as literal");
    
    // Test literal 'bar'
    let result_bar = eval.eval_str("(match-literals bar 2)").unwrap();
    let bar_car = lisp.car(result_bar).unwrap();
    assert!(lisp.symbol_matches(bar_car, "matched-bar").unwrap(),
        "Literal 'bar' should be matched as literal");
    
    // Test non-literal 'qux' (should match 'other' pattern variable)
    let result_qux = eval.eval_str("(match-literals qux 3)").unwrap();
    let qux_car = lisp.car(result_qux).unwrap();
    assert!(lisp.symbol_matches(qux_car, "matched-other").unwrap(),
        "Non-literal 'qux' should be captured by pattern variable 'other'");
}

/// Test J.6: Identifier Comparison in Templates
///
/// Tests that bound-identifier=? works correctly with identifiers
/// created via datum->syntax with the same lexical context.
#[test]
fn test_j6_identifier_comparison() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();
    
    eval.eval_str(r#"
        (define-syntax test-hygiene
          (lambda (stx)
            (syntax-case stx ()
              ((_ x)
               (let ((id1 (datum->syntax (syntax x) (quote temp)))
                     (id2 (datum->syntax (syntax x) (quote temp))))
                 (if (bound-identifier=? id1 id2)
                     (syntax (lambda (temp) temp))
                     (syntax (lambda (y) y))))))))
    "#).unwrap();
    
    eval.eval_str("(define f (test-hygiene dummy))").unwrap();
    
    // If bound-identifier=? works correctly, f should be (lambda (temp) temp)
    // and (f 42) should return 42
    assert_eq!(eval_to_num(&lisp, &mut eval, "(f 42)"), 42,
        "bound-identifier=? should identify that id1 and id2 are the same identifier");
}

// ═══════════════════════════════════════════════════════════════════════════
// Test Suite I: datum->syntax-object and syntax-object->datum (R6RS aliases)
// ═══════════════════════════════════════════════════════════════════════════

/// Test I.1: datum->syntax-object basic usage
///
/// datum->syntax-object is the R6RS name for datum->syntax.
#[test]
fn test_i1_datum_to_syntax_object_basic() {
    let lisp: Lisp<30000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();

    eval.eval_str(r#"
        (define-syntax make-ref
          (lambda (stx)
            (syntax-case stx ()
              ((kw name)
               (datum->syntax-object (syntax kw) (syntax-object->datum (syntax name)))))))
    "#).unwrap();

    eval.eval_str("(define foo 42)").unwrap();

    assert_eq!(eval_to_num(&lisp, &mut eval, "(make-ref foo)"), 42);
}

/// Test I.2: define-structure macro using datum->syntax-object
///
/// This is the full example from the R6RS specification demonstrating
/// datum->syntax-object for hygienic identifier generation.
#[test]
fn test_i2_define_structure() {
    let lisp: Lisp<80000> = Lisp::new();
    let mut eval = Evaluator::new(&lisp).unwrap();

    eval.eval_str(r#"
        (define-syntax define-structure
          (lambda (x)
            (define gen-id
              (lambda (template-id . args)
                (datum->syntax-object template-id
                  (string->symbol
                    (apply string-append
                           (map (lambda (x)
                                  (if (string? x)
                                      x
                                      (symbol->string
                                        (syntax-object->datum x))))
                                args))))))
            (syntax-case x ()
              ((_ name field ...)
               (with-syntax
                 ((constructor (gen-id (syntax name) "make-" (syntax name)))
                  (predicate (gen-id (syntax name) (syntax name) "?"))
                  ((access ...)
                   (map (lambda (x) (gen-id x (syntax name) "-" x))
                        (syntax (field ...))))
                  ((assign ...)
                   (map (lambda (x) (gen-id x "set-" (syntax name) "-" x "!"))
                        (syntax (field ...))))
                  (structure-length (+ (length (syntax (field ...))) 1))
                  ((index ...) (let f ((i 1) (ids (syntax (field ...))))
                                 (if (null? ids)
                                     '()
                                     (cons i (f (+ i 1) (cdr ids)))))))
                 (syntax (begin
                           (define constructor
                             (lambda (field ...)
                               (vector 'name field ...)))
                           (define predicate
                             (lambda (x)
                               (and (vector? x)
                                    (= (vector-length x) structure-length)
                                    (eq? (vector-ref x 0) 'name))))
                           (define access
                             (lambda (x)
                               (vector-ref x index)))
                           ...
                           (define assign
                             (lambda (x update)
                               (vector-set! x index update)))
                           ...)))))))
    "#).unwrap();

    // Define a tree structure
    eval.eval_str("(define-structure tree left right)").unwrap();

    // Create a nested tree
    eval.eval_str(r#"
        (define t
          (make-tree
            (make-tree 0 1)
            (make-tree 2 3)))
    "#).unwrap();

    // Test tree? predicate
    let result = eval.eval_str("(tree? t)").unwrap();
    assert!(matches!(lisp.get(result).unwrap(), Value::True));

    // Test tree-left accessor
    let result = eval.eval_str("(tree? (tree-left t))").unwrap();
    assert!(matches!(lisp.get(result).unwrap(), Value::True));

    // Test tree-left returns subtree with expected values
    assert_eq!(eval_to_num(&lisp, &mut eval, "(tree-left (tree-left t))"), 0);
    assert_eq!(eval_to_num(&lisp, &mut eval, "(tree-right (tree-left t))"), 1);

    // Test tree-right accessor
    assert_eq!(eval_to_num(&lisp, &mut eval, "(tree-left (tree-right t))"), 2);
    assert_eq!(eval_to_num(&lisp, &mut eval, "(tree-right (tree-right t))"), 3);

    // Test set-tree-left! mutation
    eval.eval_str("(set-tree-left! t 0)").unwrap();
    assert_eq!(eval_to_num(&lisp, &mut eval, "(tree-left t)"), 0);

    // After mutation, tree-right should still be the original subtree
    assert_eq!(eval_to_num(&lisp, &mut eval, "(tree-left (tree-right t))"), 2);
}