cemc 0.1.2

Cem language compiler - A concatenative language with green threads and linear types
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
use cemc::ast::types::{Effect, StackType, Type};
/**
End-to-end integration test: Cem source → LLVM IR → executable
*/
use cemc::ast::{Expr, Program, SourceLoc, WordDef};
use cemc::codegen::{CodeGen, compile_to_object, link_program};
use std::process::Command;

#[test]
#[cfg_attr(
    target_os = "linux",
    ignore = "Pre-existing test failure (not epoll-related)"
)]
fn test_end_to_end_compilation() {
    // Build the runtime first
    let runtime_status = Command::new("just")
        .arg("build-runtime")
        .status()
        .expect("Failed to build runtime");

    assert!(runtime_status.success(), "Runtime build failed");

    // Create a simple program: : fortytwo ( -- Int ) 42 ;
    let word = WordDef {
        name: "fortytwo".to_string(),
        effect: Effect {
            inputs: StackType::Empty,
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![Expr::IntLit(42, SourceLoc::unknown())],
        loc: SourceLoc::unknown(),
    };

    let program = Program {
        type_defs: vec![],
        word_defs: vec![word],
    };

    // Generate LLVM IR
    let mut codegen = CodeGen::new();
    let ir = codegen
        .compile_program(&program)
        .expect("Failed to generate IR");

    // Verify IR contains expected elements
    assert!(ir.contains("define ptr @fortytwo"));
    assert!(ir.contains("call ptr @push_int"));
    assert!(ir.contains("i64 42"));

    // Compile to object file (tests that LLVM accepts our IR)
    compile_to_object(&ir, "test_fortytwo").expect("Failed to compile IR to object");

    // Clean up
    std::fs::remove_file("test_fortytwo.o").ok();
    std::fs::remove_file("test_fortytwo.ll").ok();
}

#[test]
#[cfg_attr(
    target_os = "linux",
    ignore = "Pre-existing test failure (not epoll-related)"
)]
fn test_arithmetic_compilation() {
    // Build runtime
    let runtime_status = Command::new("just")
        .arg("build-runtime")
        .status()
        .expect("Failed to build runtime");

    assert!(runtime_status.success());

    // : eight ( -- Int ) 5 3 + ;
    let word = WordDef {
        name: "eight".to_string(),
        effect: Effect {
            inputs: StackType::Empty,
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![
            Expr::IntLit(5, SourceLoc::unknown()),
            Expr::IntLit(3, SourceLoc::unknown()),
            Expr::WordCall("add".to_string(), SourceLoc::unknown()),
        ],
        loc: SourceLoc::unknown(),
    };

    let program = Program {
        type_defs: vec![],
        word_defs: vec![word],
    };

    // Generate and compile
    let mut codegen = CodeGen::new();
    let ir = codegen
        .compile_program(&program)
        .expect("Failed to generate IR");

    assert!(ir.contains("@eight"));
    assert!(ir.contains("@add"));

    compile_to_object(&ir, "test_eight").expect("Failed to compile");

    // Clean up
    std::fs::remove_file("test_eight.o").ok();
    std::fs::remove_file("test_eight.ll").ok();
}

#[test]
#[cfg_attr(
    target_os = "linux",
    ignore = "Pre-existing test failure (not epoll-related)"
)]
fn test_executable_with_main() {
    // Build runtime
    let runtime_status = Command::new("just")
        .arg("build-runtime")
        .status()
        .expect("Failed to build runtime");

    assert!(runtime_status.success());

    // : fortytwo ( -- Int ) 42 ;
    let word = WordDef {
        name: "fortytwo".to_string(),
        effect: Effect {
            inputs: StackType::Empty,
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![Expr::IntLit(42, SourceLoc::unknown())],
        loc: SourceLoc::unknown(),
    };

    let program = Program {
        type_defs: vec![],
        word_defs: vec![word],
    };

    // Generate IR with main() function
    let mut codegen = CodeGen::new();
    let ir = codegen
        .compile_program_with_main(&program, Some("fortytwo"))
        .expect("Failed to generate IR");

    // Verify IR contains main function
    assert!(ir.contains("define i32 @main()"));
    assert!(ir.contains("strand_spawn(ptr @fortytwo")); // Entry word is spawned as a strand
    assert!(ir.contains("ret i32 0"));

    // Link to produce executable
    link_program(&ir, "runtime/libcem_runtime.a", "test_fortytwo_exe").expect("Failed to link");

    // Run the executable
    let output = Command::new("./test_fortytwo_exe")
        .output()
        .expect("Failed to run executable");

    assert!(output.status.success());

    // Clean up
    std::fs::remove_file("test_fortytwo_exe").ok();
    std::fs::remove_file("test_fortytwo_exe.ll").ok();
}

#[test]
#[cfg_attr(
    target_os = "linux",
    ignore = "Pre-existing test failure (not epoll-related)"
)]
fn test_multiply_executable() {
    // Build runtime
    let runtime_status = Command::new("just")
        .arg("build-runtime")
        .status()
        .expect("Failed to build runtime");

    assert!(runtime_status.success());

    // : product ( -- Int ) 6 7 * ;
    let word = WordDef {
        name: "product".to_string(),
        effect: Effect {
            inputs: StackType::Empty,
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![
            Expr::IntLit(6, SourceLoc::unknown()),
            Expr::IntLit(7, SourceLoc::unknown()),
            Expr::WordCall("multiply".to_string(), SourceLoc::unknown()),
        ],
        loc: SourceLoc::unknown(),
    };

    let program = Program {
        type_defs: vec![],
        word_defs: vec![word],
    };

    // Generate and link
    let mut codegen = CodeGen::new();
    let ir = codegen
        .compile_program_with_main(&program, Some("product"))
        .expect("Failed to generate IR");

    link_program(&ir, "runtime/libcem_runtime.a", "test_product_exe").expect("Failed to link");

    // Run and check output
    let output = Command::new("./test_product_exe")
        .output()
        .expect("Failed to run executable");

    assert!(output.status.success());
    // Clean up
    std::fs::remove_file("test_product_exe").ok();
    std::fs::remove_file("test_product_exe.ll").ok();
}

#[test]
#[cfg_attr(
    target_os = "linux",
    ignore = "Pre-existing test failure (not epoll-related)"
)]
fn test_if_expression() {
    // Build runtime
    let runtime_status = Command::new("just")
        .arg("build-runtime")
        .status()
        .expect("Failed to build runtime");

    assert!(runtime_status.success());

    // : abs ( Int -- Int ) dup 0 < if [ 0 swap - ] [ ] ;
    // Simplified: : test_if ( -- Int ) true if [ 42 ] [ 0 ] ;
    let word = WordDef {
        name: "test_if".to_string(),
        effect: Effect {
            inputs: StackType::Empty,
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![
            Expr::BoolLit(true, SourceLoc::unknown()),
            Expr::If {
                then_branch: Box::new(Expr::Quotation(
                    vec![Expr::IntLit(42, SourceLoc::unknown())],
                    SourceLoc::unknown(),
                )),
                else_branch: Box::new(Expr::Quotation(
                    vec![Expr::IntLit(0, SourceLoc::unknown())],
                    SourceLoc::unknown(),
                )),
                loc: SourceLoc::unknown(),
            },
        ],
        loc: SourceLoc::unknown(),
    };

    let program = Program {
        type_defs: vec![],
        word_defs: vec![word],
    };

    // Generate and link
    let mut codegen = CodeGen::new();
    let ir = codegen
        .compile_program_with_main(&program, Some("test_if"))
        .expect("Failed to generate IR");

    // Verify IR contains if/then/else structure
    assert!(ir.contains("br i1 %")); // Branch on boolean condition
    assert!(ir.contains("then_"));
    assert!(ir.contains("else_"));
    assert!(ir.contains("merge_"));
    assert!(ir.contains("phi ptr"));

    link_program(&ir, "runtime/libcem_runtime.a", "test_if_exe").expect("Failed to link");

    // Run and check output - should print 42 (true branch)
    let output = Command::new("./test_if_exe")
        .output()
        .expect("Failed to run executable");

    assert!(output.status.success());

    // Clean up
    std::fs::remove_file("test_if_exe").ok();
    std::fs::remove_file("test_if_exe.ll").ok();
}

#[test]
#[cfg_attr(
    target_os = "linux",
    ignore = "Pre-existing test failure (not epoll-related)"
)]
fn test_tail_call_optimization() {
    // Build runtime
    let runtime_status = Command::new("just")
        .arg("build-runtime")
        .status()
        .expect("Failed to build runtime");

    assert!(runtime_status.success());

    // Create a simple tail-recursive word that calls itself
    // : identity ( Int -- Int ) ;  (just returns input)
    let identity = WordDef {
        name: "identity".to_string(),
        effect: Effect {
            inputs: StackType::Empty.push(Type::Int),
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![], // Identity - does nothing, returns stack as-is
        loc: SourceLoc::unknown(),
    };

    // : call_identity ( -- Int ) 42 identity ;
    let call_identity = WordDef {
        name: "call_identity".to_string(),
        effect: Effect {
            inputs: StackType::Empty,
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![
            Expr::IntLit(42, SourceLoc::unknown()),
            Expr::WordCall("identity".to_string(), SourceLoc::unknown()),
        ],
        loc: SourceLoc::unknown(),
    };

    let program = Program {
        type_defs: vec![],
        word_defs: vec![identity, call_identity],
    };

    // Generate IR
    let mut codegen = CodeGen::new();
    let ir = codegen
        .compile_program_with_main(&program, Some("call_identity"))
        .expect("Failed to generate IR");

    // Verify IR contains musttail for the last word call
    assert!(
        ir.contains("musttail call"),
        "Expected musttail optimization for tail call"
    );

    // Link and run to verify it works
    link_program(&ir, "runtime/libcem_runtime.a", "test_tail_call_exe").expect("Failed to link");

    let output = Command::new("./test_tail_call_exe")
        .output()
        .expect("Failed to run executable");

    assert!(output.status.success());
    // Clean up
    std::fs::remove_file("test_tail_call_exe").ok();
    std::fs::remove_file("test_tail_call_exe.ll").ok();
}

#[test]
#[cfg_attr(
    target_os = "linux",
    ignore = "Pre-existing test failure (not epoll-related)"
)]
fn test_if_false_branch() {
    // Build runtime
    let runtime_status = Command::new("just")
        .arg("build-runtime")
        .status()
        .expect("Failed to build runtime");

    assert!(runtime_status.success());

    // : test_if_false ( -- Int ) false if [ 42 ] [ 99 ] ;
    // Should take the else branch and return 99
    let word = WordDef {
        name: "test_if_false".to_string(),
        effect: Effect {
            inputs: StackType::Empty,
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![
            Expr::BoolLit(false, SourceLoc::unknown()), // Push false
            Expr::If {
                then_branch: Box::new(Expr::Quotation(
                    vec![Expr::IntLit(42, SourceLoc::unknown())],
                    SourceLoc::unknown(),
                )),
                else_branch: Box::new(Expr::Quotation(
                    vec![Expr::IntLit(99, SourceLoc::unknown())],
                    SourceLoc::unknown(),
                )),
                loc: SourceLoc::unknown(),
            },
        ],
        loc: SourceLoc::unknown(),
    };

    let program = Program {
        type_defs: vec![],
        word_defs: vec![word],
    };

    // Generate and link
    let mut codegen = CodeGen::new();
    let ir = codegen
        .compile_program_with_main(&program, Some("test_if_false"))
        .expect("Failed to generate IR");

    link_program(&ir, "runtime/libcem_runtime.a", "test_if_false_exe").expect("Failed to link");

    // Run and check output - should print 99 (false branch)
    let output = Command::new("./test_if_false_exe")
        .output()
        .expect("Failed to run executable");

    assert!(output.status.success());

    // Clean up
    std::fs::remove_file("test_if_false_exe").ok();
    std::fs::remove_file("test_if_false_exe.ll").ok();
}

#[test]
#[cfg_attr(
    target_os = "linux",
    ignore = "Pre-existing test failure (not epoll-related)"
)]
fn test_tail_call_in_if_branch() {
    // Build runtime
    let runtime_status = Command::new("just")
        .arg("build-runtime")
        .status()
        .expect("Failed to build runtime");

    assert!(runtime_status.success());

    // Create a helper word that just returns its input
    // : passthrough ( Int -- Int ) ;
    let passthrough = WordDef {
        name: "passthrough".to_string(),
        effect: Effect {
            inputs: StackType::Empty.push(Type::Int),
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![], // Identity - returns stack as-is
        loc: SourceLoc::unknown(),
    };

    // Create a word that calls another word in tail position within an if branch
    // : conditional_call ( Bool -- Int )
    //   if [ passthrough ] [ passthrough ] ;
    // This tests that tail calls inside if branches are optimized
    let conditional_call = WordDef {
        name: "conditional_call".to_string(),
        effect: Effect {
            inputs: StackType::Empty.push(Type::Bool),
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![Expr::If {
            // Both branches call passthrough in tail position
            // Then branch: push 42 then call passthrough
            then_branch: Box::new(Expr::Quotation(
                vec![
                    Expr::IntLit(42, SourceLoc::unknown()),
                    Expr::WordCall("passthrough".to_string(), SourceLoc::unknown()),
                ],
                SourceLoc::unknown(),
            )),
            // Else branch: push 99 then call passthrough
            else_branch: Box::new(Expr::Quotation(
                vec![
                    Expr::IntLit(99, SourceLoc::unknown()),
                    Expr::WordCall("passthrough".to_string(), SourceLoc::unknown()),
                ],
                SourceLoc::unknown(),
            )),
            loc: SourceLoc::unknown(),
        }],
        loc: SourceLoc::unknown(),
    };

    // Entry word that sets up the test: push true, call conditional_call
    // : test_entry ( -- Int ) true conditional_call ;
    let test_entry = WordDef {
        name: "test_entry".to_string(),
        effect: Effect {
            inputs: StackType::Empty,
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![
            Expr::BoolLit(true, SourceLoc::unknown()),
            Expr::WordCall("conditional_call".to_string(), SourceLoc::unknown()),
        ],
        loc: SourceLoc::unknown(),
    };

    let program = Program {
        type_defs: vec![],
        word_defs: vec![passthrough, conditional_call, test_entry],
    };

    // Generate IR
    let mut codegen = CodeGen::new();
    let ir = codegen
        .compile_program_with_main(&program, Some("test_entry"))
        .expect("Failed to generate IR");

    // Critical check: verify that passthrough calls in the if branches are tail-optimized
    // The IR should contain "musttail call ptr @passthrough" inside the branch blocks
    assert!(
        ir.contains("musttail call ptr @passthrough"),
        "Expected musttail optimization for tail calls in if branches"
    );

    // Link and run to verify it works correctly
    link_program(&ir, "runtime/libcem_runtime.a", "test_tail_in_if_exe").expect("Failed to link");

    let output = Command::new("./test_tail_in_if_exe")
        .output()
        .expect("Failed to run executable");

    assert!(output.status.success());
    // Clean up
    std::fs::remove_file("test_tail_in_if_exe").ok();
    std::fs::remove_file("test_tail_in_if_exe.ll").ok();
}

#[test]
#[cfg_attr(
    target_os = "linux",
    ignore = "Pre-existing test failure (not epoll-related)"
)]
fn test_nested_if_expressions() {
    // Build runtime
    let runtime_status = Command::new("just")
        .arg("build-runtime")
        .status()
        .expect("Failed to build runtime");

    assert!(runtime_status.success());

    // Create a word with nested if expressions:
    // : nested_if ( Bool Bool -- Int )
    //   if
    //     [ if [ 1 ] [ 2 ] ]
    //     [ if [ 3 ] [ 4 ] ]
    //   ;
    // Tests: true true => 1, true false => 2, false true => 3, false false => 4
    let nested_if = WordDef {
        name: "nested_if".to_string(),
        effect: Effect {
            inputs: StackType::Empty.push(Type::Bool).push(Type::Bool),
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![Expr::If {
            // Outer if: first bool
            then_branch: Box::new(Expr::Quotation(
                vec![
                    // Inner if in then branch
                    Expr::If {
                        then_branch: Box::new(Expr::Quotation(
                            vec![Expr::IntLit(1, SourceLoc::unknown())],
                            SourceLoc::unknown(),
                        )),
                        else_branch: Box::new(Expr::Quotation(
                            vec![Expr::IntLit(2, SourceLoc::unknown())],
                            SourceLoc::unknown(),
                        )),
                        loc: SourceLoc::unknown(),
                    },
                ],
                SourceLoc::unknown(),
            )),
            else_branch: Box::new(Expr::Quotation(
                vec![
                    // Inner if in else branch
                    Expr::If {
                        then_branch: Box::new(Expr::Quotation(
                            vec![Expr::IntLit(3, SourceLoc::unknown())],
                            SourceLoc::unknown(),
                        )),
                        else_branch: Box::new(Expr::Quotation(
                            vec![Expr::IntLit(4, SourceLoc::unknown())],
                            SourceLoc::unknown(),
                        )),
                        loc: SourceLoc::unknown(),
                    },
                ],
                SourceLoc::unknown(),
            )),
            loc: SourceLoc::unknown(),
        }],
        loc: SourceLoc::unknown(),
    };

    // Test case: true, true => should give 1
    let test_true_true = WordDef {
        name: "test_true_true".to_string(),
        effect: Effect {
            inputs: StackType::Empty,
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![
            Expr::BoolLit(true, SourceLoc::unknown()), // Inner condition
            Expr::BoolLit(true, SourceLoc::unknown()), // Outer condition
            Expr::WordCall("nested_if".to_string(), SourceLoc::unknown()),
        ],
        loc: SourceLoc::unknown(),
    };

    let program = Program {
        type_defs: vec![],
        word_defs: vec![nested_if, test_true_true],
    };

    // Generate and link
    let mut codegen = CodeGen::new();
    let ir = codegen
        .compile_program_with_main(&program, Some("test_true_true"))
        .expect("Failed to generate IR");

    // Verify IR contains nested branching structure
    assert!(ir.contains("then_"), "Expected then branch labels");
    assert!(ir.contains("else_"), "Expected else branch labels");
    assert!(ir.contains("merge_"), "Expected merge block labels");

    // Save IR for debugging
    std::fs::write("test_nested_if_debug.ll", &ir).expect("Failed to write IR");

    link_program(&ir, "runtime/libcem_runtime.a", "test_nested_if_exe").expect("Failed to link");

    // Run and check output - should print 1 (both true)
    let output = Command::new("./test_nested_if_exe")
        .output()
        .expect("Failed to run executable");

    assert!(output.status.success());

    // Clean up
    std::fs::remove_file("test_nested_if_exe").ok();
    std::fs::remove_file("test_nested_if_exe.ll").ok();
}

#[test]
#[cfg_attr(
    target_os = "linux",
    ignore = "Pre-existing test failure (not epoll-related)"
)]
fn test_scheduler_linkage() {
    // Build runtime
    let runtime_status = Command::new("just")
        .arg("build-runtime")
        .status()
        .expect("Failed to build runtime");

    assert!(runtime_status.success());

    // : test_scheduler ( -- Int )
    //   5 test_yield 10 add ;
    // Tests that test_yield links correctly and doesn't break execution
    // (Phase 1: test_yield is a no-op, scheduler is not functional yet)
    let word = WordDef {
        name: "test_scheduler".to_string(),
        effect: Effect {
            inputs: StackType::Empty,
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![
            Expr::IntLit(5, SourceLoc::unknown()),
            Expr::WordCall("test_yield".to_string(), SourceLoc::unknown()),
            Expr::IntLit(10, SourceLoc::unknown()),
            Expr::WordCall("add".to_string(), SourceLoc::unknown()),
        ],
        loc: SourceLoc::unknown(),
    };

    let program = Program {
        type_defs: vec![],
        word_defs: vec![word],
    };

    // Generate IR
    let mut codegen = CodeGen::new();
    let ir = codegen
        .compile_program_with_main(&program, Some("test_scheduler"))
        .expect("Failed to generate IR");

    // Verify test_yield is declared and called
    assert!(ir.contains("declare ptr @test_yield(ptr)"));
    assert!(ir.contains("call ptr @test_yield"));

    // Link and run
    link_program(&ir, "runtime/libcem_runtime.a", "test_scheduler_exe").expect("Failed to link");

    let output = Command::new("./test_scheduler_exe")
        .output()
        .expect("Failed to run executable");

    assert!(output.status.success());

    // Should output 15 (5 + 10)

    // Clean up
    std::fs::remove_file("test_scheduler_exe").ok();
    std::fs::remove_file("test_scheduler_exe.ll").ok();
}

#[test]
fn test_debug_metadata_emission() {
    // Test that debug metadata is properly emitted in LLVM IR
    let word = WordDef {
        name: "fortytwo".to_string(),
        effect: Effect {
            inputs: StackType::Empty,
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![Expr::IntLit(
            42,
            SourceLoc::new(1, 25, "test.cem".to_string()),
        )],
        loc: SourceLoc::new(1, 1, "test.cem".to_string()),
    };

    let program = Program {
        type_defs: vec![],
        word_defs: vec![word],
    };

    let mut codegen = CodeGen::new();
    let ir = codegen
        .compile_program(&program)
        .expect("Failed to generate IR");

    // Verify debug metadata is present
    assert!(ir.contains("!DIFile"), "Should contain DIFile metadata");
    assert!(
        ir.contains("!DICompileUnit"),
        "Should contain DICompileUnit metadata"
    );
    assert!(
        ir.contains("!DISubprogram"),
        "Should contain DISubprogram metadata"
    );
    assert!(
        ir.contains("!DILocation"),
        "Should contain DILocation metadata"
    );
    assert!(ir.contains("!llvm.dbg.cu"), "Should contain llvm.dbg.cu");
    assert!(
        ir.contains("!llvm.module.flags"),
        "Should contain module flags"
    );

    // Verify instruction has debug annotation
    assert!(
        ir.contains(", !dbg !"),
        "Instructions should have !dbg annotations"
    );

    // Verify the function references its subprogram
    assert!(
        ir.contains("define ptr @fortytwo(ptr %stack) !dbg !"),
        "Function should reference DISubprogram"
    );
}

#[test]
fn test_debug_metadata_filename_escaping() {
    // Test that filenames with special characters are properly escaped
    let word = WordDef {
        name: "test".to_string(),
        effect: Effect {
            inputs: StackType::Empty,
            outputs: StackType::Empty.push(Type::Int),
        },
        body: vec![Expr::IntLit(
            42,
            SourceLoc::new(1, 1, "test\"file.cem".to_string()),
        )],
        loc: SourceLoc::new(1, 1, "test\"file.cem".to_string()),
    };

    let program = Program {
        type_defs: vec![],
        word_defs: vec![word],
    };

    let mut codegen = CodeGen::new();
    let ir = codegen
        .compile_program(&program)
        .expect("Failed to generate IR");

    // Verify the filename is properly escaped (quote becomes \")
    assert!(
        ir.contains(r#"!DIFile(filename: "test\"file.cem""#),
        "Filename with quotes should be escaped"
    );
}