ruchy 4.2.0

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
#![allow(missing_docs)]
// CLI Contract Tests for `ruchy fmt` command
//
// Purpose: Validate fmt tool behavior via CLI interface (Layer 4: Black Box)
// Context: P0 CRITICAL - fmt had code-destroying bugs (operator mangling, let rewriting)
//          Bugs FIXED in src/quality/formatter.rs but ZERO regression prevention tests existed
//
// Critical Defects Prevented:
// - DEFECT-FMT-001: Operator mangling (`*` became `Multiply`)
// - DEFECT-FMT-002: Let statement rewriting (`let x = 42` became `let x = 42 in ()`)
//
// Reference: docs/defects/CRITICAL-FMT-CODE-DESTRUCTION.md

use assert_cmd::Command;
use predicates::prelude::*;
use std::fs;
use tempfile::TempDir;

fn ruchy_cmd() -> Command {
    assert_cmd::cargo::cargo_bin_cmd!("ruchy")
}

fn fixture_path(name: &str) -> String {
    format!("tests/fixtures/fmt/{name}")
}

// ============================================================================
// CRITICAL: Regression Prevention Tests (P0 Defects)
// ============================================================================

#[test]
fn test_fmt_no_operator_mangling() {
    // DEFECT-FMT-001 Prevention: Operators must use Display trait, not Debug
    // Bug: `x * 2` became `x Multiply 2` (Debug trait format)
    // Fix: Use `{}` instead of `{:?}` in formatter.rs:78

    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("operators.ruchy");
    fs::write(
        &test_file,
        "let a = 10 + 5\nlet b = a * 2\nlet c = b / 3\nlet d = c - 1",
    )
    .unwrap();

    ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .assert()
        .success()
        .stdout(predicate::str::contains("*").and(predicate::str::contains("Multiply").not()))
        .stdout(predicate::str::contains("+").and(predicate::str::contains("Add").not()))
        .stdout(predicate::str::contains("/").and(predicate::str::contains("Divide").not()))
        .stdout(predicate::str::contains("-").and(predicate::str::contains("Subtract").not()));
}

#[test]
fn test_fmt_no_let_statement_rewriting() {
    // DEFECT-FMT-002 Prevention: Statement-style let should not become functional style
    // Bug: `let x = 42` became `let x = 42 in ()`
    // Fix: Check for Unit body in formatter.rs:69-80

    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("simple.ruchy");
    fs::write(&test_file, "let x = 42\nlet y = x * 2\nprintln(y)").unwrap();

    ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .assert()
        .success()
        .stdout(predicate::str::contains("let x = 42 in ()").not())
        .stdout(predicate::str::contains("let y = x * 2 in ()").not());
}

#[test]
fn test_fmt_round_trip_idempotency() {
    // Round-trip validation: format(format(x)) == format(x)
    // Ensures formatting is stable and doesn't keep changing code
    //
    // BUG: First format: `{ let x = 42; let y = x * 2 + 10; println(y) }`
    //      Second format: `{ let x = 42 in { let y = x * 2 + 10; println(y) } }`
    //      This is a MEDIUM priority bug - formatting should be idempotent

    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("roundtrip.ruchy");
    fs::write(&test_file, "let x = 42\nlet y = x * 2 + 10\nprintln(y)").unwrap();

    // First format
    let output1 = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted1 = String::from_utf8(output1.stdout).unwrap();

    // Write formatted output to temp file
    let test_file2 = temp_dir.path().join("roundtrip2.ruchy");
    fs::write(&test_file2, &formatted1).unwrap();

    // Second format
    let output2 = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file2)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted2 = String::from_utf8(output2.stdout).unwrap();

    // They should be identical
    assert_eq!(formatted1, formatted2, "Formatting is not idempotent!");
}

// ============================================================================
// Basic Functionality Tests
// ============================================================================

#[test]
fn test_fmt_basic_file() {
    ruchy_cmd()
        .arg("fmt")
        .arg(fixture_path("simple.ruchy"))
        .arg("--stdout")
        .assert()
        .success()
        .stdout(predicate::str::contains("let"));
}

#[test]
fn test_fmt_stdout_option() {
    // --stdout should output formatted code to stdout without modifying file
    ruchy_cmd()
        .arg("fmt")
        .arg(fixture_path("simple.ruchy"))
        .arg("--stdout")
        .assert()
        .success()
        .stdout(predicate::str::is_empty().not());
}

#[test]
fn test_fmt_check_option() {
    // --check should verify formatting without modifying
    // Exit code 1 if formatting needed, 0 if already formatted
    ruchy_cmd()
        .arg("fmt")
        .arg(fixture_path("simple.ruchy"))
        .arg("--check")
        .assert()
        .code(predicate::eq(0).or(predicate::eq(1))); // Either formatted or needs formatting
}

#[test]
fn test_fmt_missing_file() {
    ruchy_cmd()
        .arg("fmt")
        .arg("tests/fixtures/fmt/nonexistent.ruchy")
        .assert()
        .failure()
        .stderr(predicate::str::contains("not found").or(predicate::str::contains("No such file")));
}

#[test]
fn test_fmt_operators() {
    ruchy_cmd()
        .arg("fmt")
        .arg(fixture_path("operators.ruchy"))
        .arg("--stdout")
        .assert()
        .success()
        .stdout(predicate::str::contains("+"))
        .stdout(predicate::str::contains("*"))
        .stdout(predicate::str::contains("/"))
        .stdout(predicate::str::contains("-"));
}

#[test]
fn test_fmt_control_flow() {
    ruchy_cmd()
        .arg("fmt")
        .arg(fixture_path("control_flow.ruchy"))
        .arg("--stdout")
        .assert()
        .success()
        .stdout(predicate::str::contains("if"))
        .stdout(predicate::str::contains("else"));
}

#[test]
fn test_fmt_functions() {
    ruchy_cmd()
        .arg("fmt")
        .arg(fixture_path("functions.ruchy"))
        .arg("--stdout")
        .assert()
        .success()
        .stdout(predicate::str::contains("fun").or(predicate::str::contains("fn")))
        .stdout(predicate::str::contains("add"));
}

// ============================================================================
// Option Tests
// ============================================================================

#[test]
fn test_fmt_line_width_option() {
    ruchy_cmd()
        .arg("fmt")
        .arg(fixture_path("simple.ruchy"))
        .arg("--line-width")
        .arg("80")
        .arg("--stdout")
        .assert()
        .success();
}

#[test]
fn test_fmt_indent_option() {
    ruchy_cmd()
        .arg("fmt")
        .arg(fixture_path("simple.ruchy"))
        .arg("--indent")
        .arg("2")
        .arg("--stdout")
        .assert()
        .success();
}

#[test]
fn test_fmt_use_tabs_option() {
    ruchy_cmd()
        .arg("fmt")
        .arg(fixture_path("simple.ruchy"))
        .arg("--use-tabs")
        .arg("--stdout")
        .assert()
        .success();
}

#[test]
fn test_fmt_diff_option() {
    ruchy_cmd()
        .arg("fmt")
        .arg(fixture_path("simple.ruchy"))
        .arg("--diff")
        .assert()
        .success();
}

#[test]
fn test_fmt_config_option() {
    // Config file doesn't exist yet, but option should be recognized
    ruchy_cmd()
        .arg("fmt")
        .arg(fixture_path("simple.ruchy"))
        .arg("--config")
        .arg("fmt.toml")
        .arg("--stdout")
        .assert()
        .code(predicate::ne(2)); // Not a CLI argument error
}

// ============================================================================
// Edge Cases
// ============================================================================

#[test]
fn test_fmt_empty_file() {
    // Empty files should be rejected (not valid Ruchy programs)
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("empty.ruchy");
    fs::write(&test_file, "").unwrap();

    ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .assert()
        .failure()
        .stderr(predicate::str::contains("Empty program"));
}

#[test]
fn test_fmt_whitespace_only() {
    // Whitespace-only files should be rejected (not valid programs)
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("whitespace.ruchy");
    fs::write(&test_file, "   \n\n  \t\n").unwrap();

    ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .assert()
        .failure()
        .stderr(predicate::str::contains("Empty program"));
}

#[test]
fn test_fmt_syntax_error() {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("syntax_error.ruchy");
    fs::write(&test_file, "let x = ").unwrap();

    ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("Error")
                .or(predicate::str::contains("Expected"))
                .or(predicate::str::contains("Unexpected")),
        );
}

#[test]
fn test_fmt_complex_expression() {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("complex.ruchy");
    fs::write(&test_file, "let x = (10 + 5) * (20 - 3) / 2").unwrap();

    ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .assert()
        .success()
        .stdout(predicate::str::contains("+"))
        .stdout(predicate::str::contains("*"))
        .stdout(predicate::str::contains("-"))
        .stdout(predicate::str::contains("/"));
}

#[test]
fn test_fmt_nested_blocks() {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("nested.ruchy");
    fs::write(
        &test_file,
        "if x > 0 { if y > 0 { println(\"both positive\") } }",
    )
    .unwrap();

    ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .assert()
        .success()
        .stdout(predicate::str::contains("if"));
}

// ============================================================================
// File Modification Tests
// ============================================================================

#[test]
fn test_fmt_modifies_file_in_place() {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("modify.ruchy");
    let original = "let x=42\nlet y=x*2";
    fs::write(&test_file, original).unwrap();

    ruchy_cmd().arg("fmt").arg(&test_file).assert().success();

    // File should be modified
    let modified = fs::read_to_string(&test_file).unwrap();
    // Should have some formatting applied (spaces, etc.)
    assert!(modified.contains("let"));
}

#[test]
fn test_fmt_check_no_modification() {
    // --check should NEVER modify the file, regardless of exit code
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("nomodify.ruchy");
    let original = "let x=42\nlet y=x*2";
    fs::write(&test_file, original).unwrap();

    ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--check")
        .assert()
        .code(predicate::eq(0).or(predicate::eq(1))); // Either formatted or needs formatting

    // File should NOT be modified (this is the critical assertion)
    let unchanged = fs::read_to_string(&test_file).unwrap();
    assert_eq!(unchanged, original, "File was modified with --check flag!");
}

// ============================================================================
// P0 CRITICAL: Debug Fallback Prevention Tests (DEFECT-FMT-003)
// ============================================================================
// Reference: docs/defects/CRITICAL-FMT-DEBUG-FALLBACK.md
//
// Bug: Formatter had catch-all pattern `_ => format!("{:?}", expr.kind)` that
//      output AST Debug representation for 70+ unhandled ExprKind variants
// Impact: Silent file corruption - any code using array indexing, assignments,
//         returns, field access, etc. would be corrupted with AST debug output
// Fix: Implemented formatting for all critical ExprKind variants

#[test]
fn test_fmt_no_debug_fallback_array_indexing() {
    // DEFECT-FMT-003: IndexAccess must format as `arr[i]`, not Debug output
    // Bug: `content[i]` became `IndexAccess { object: Expr { ... }, index: ... }`
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("indexing.ruchy");
    fs::write(
        &test_file,
        "let arr = [1, 2, 3]\nlet x = arr[0]\nlet y = arr[1]",
    )
    .unwrap();

    let output = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted = String::from_utf8(output.stdout).unwrap();

    // Must contain proper array indexing syntax
    assert!(
        formatted.contains("[0]") || formatted.contains("arr["),
        "Missing array indexing syntax"
    );

    // Must NOT contain Debug output
    assert!(
        !formatted.contains("IndexAccess"),
        "Debug fallback detected for IndexAccess"
    );
    assert!(
        !formatted.contains("Expr { kind:"),
        "AST Debug output detected"
    );
}

#[test]
fn test_fmt_no_debug_fallback_assignment() {
    // DEFECT-FMT-003: Assign must format as `x = value`, not Debug output
    // Bug: `result = result + ch` became `Assign { target: Expr { ... }, value: ... }`
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("assign.ruchy");
    fs::write(&test_file, "let x = 0\nx = 42\nx = x + 1").unwrap();

    let output = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted = String::from_utf8(output.stdout).unwrap();

    // Must contain proper assignment syntax
    assert!(formatted.contains(" = "), "Missing assignment operator");

    // Must NOT contain Debug output
    assert!(
        !formatted.contains("Assign {"),
        "Debug fallback detected for Assign"
    );
    assert!(
        !formatted.contains("target: Expr"),
        "AST Debug output detected"
    );
}

#[test]
fn test_fmt_no_debug_fallback_return() {
    // DEFECT-FMT-003: Return must format as `return value`, not Debug output
    // Bug: `return result` became `Return { value: Some(Expr { ... }) }`
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("return.ruchy");
    // Simplified version of return usage from head.ruchy
    fs::write(
        &test_file,
        "{\n\
         fun test(x: Any) {\n\
         if x > 10 {\n\
         return x\n\
         }\n\
         0\n\
         }\n\
         }",
    )
    .unwrap();

    let output = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted = String::from_utf8(output.stdout).unwrap();

    // Must contain proper return syntax
    assert!(formatted.contains("return"), "Missing return keyword");

    // Must NOT contain Debug output
    assert!(
        !formatted.contains("Return {"),
        "Debug fallback detected for Return"
    );
    assert!(
        !formatted.contains("value: Some("),
        "AST Debug output detected"
    );
}

#[test]
fn test_fmt_no_debug_fallback_field_access() {
    // DEFECT-FMT-003: FieldAccess must format as `obj.field`, not Debug output
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("field.ruchy");
    fs::write(&test_file, "let x = obj.field\nlet y = obj.method()").unwrap();

    let output = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted = String::from_utf8(output.stdout).unwrap();

    // Must contain proper field access syntax
    assert!(formatted.contains('.'), "Missing field access operator");

    // Must NOT contain Debug output
    assert!(
        !formatted.contains("FieldAccess"),
        "Debug fallback detected for FieldAccess"
    );
}

#[test]
fn test_fmt_no_debug_fallback_while_loop() {
    // DEFECT-FMT-003: While must format as `while cond { body }`, not Debug output
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("while.ruchy");
    fs::write(&test_file, "let x = 0\nwhile x < 10 {\nx = x + 1\n}").unwrap();

    let output = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted = String::from_utf8(output.stdout).unwrap();

    // Must contain proper while syntax
    assert!(formatted.contains("while"), "Missing while keyword");

    // Must NOT contain Debug output
    assert!(
        !formatted.contains("While {"),
        "Debug fallback detected for While"
    );
}

#[test]
fn test_fmt_no_debug_fallback_break_continue() {
    // DEFECT-FMT-003: Break/Continue must format as keywords, not Debug output
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("loop_control.ruchy");
    fs::write(
        &test_file,
        "while true {\nif x > 5 { break }\nif x == 3 { continue }\n}",
    )
    .unwrap();

    let output = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted = String::from_utf8(output.stdout).unwrap();

    // Must contain proper keywords
    assert!(formatted.contains("break"), "Missing break keyword");
    assert!(formatted.contains("continue"), "Missing continue keyword");

    // Must NOT contain Debug output
    assert!(
        !formatted.contains("Break {"),
        "Debug fallback detected for Break"
    );
    assert!(
        !formatted.contains("Continue {"),
        "Debug fallback detected for Continue"
    );
}

#[test]
fn test_fmt_no_debug_fallback_range() {
    // DEFECT-FMT-003: Range must format as `start..end`, not Debug output
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("range.ruchy");
    fs::write(&test_file, "for i in 0..10 {\nprintln(i)\n}").unwrap();

    let output = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted = String::from_utf8(output.stdout).unwrap();

    // Must contain proper range syntax
    assert!(formatted.contains(".."), "Missing range operator");

    // Must NOT contain Debug output
    assert!(
        !formatted.contains("Range {"),
        "Debug fallback detected for Range"
    );
}

#[test]
fn test_fmt_no_debug_fallback_unary_ops() {
    // DEFECT-FMT-003: Unary must format as `-x` or `!flag`, not Debug output
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("unary.ruchy");
    fs::write(&test_file, "let x = -42\nlet flag = !true").unwrap();

    let output = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted = String::from_utf8(output.stdout).unwrap();

    // Must contain proper unary operators
    assert!(
        formatted.contains('-') || formatted.contains('!'),
        "Missing unary operators"
    );

    // Must NOT contain Debug output
    assert!(
        !formatted.contains("Unary {"),
        "Debug fallback detected for Unary"
    );
    assert!(
        !formatted.contains("Negate"),
        "Debug fallback detected for Negate operator"
    );
}

#[test]
fn test_fmt_no_debug_fallback_list_literal() {
    // DEFECT-FMT-003: List must format as `[1, 2, 3]`, not Debug output
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("list.ruchy");
    fs::write(&test_file, "let arr = [1, 2, 3, 4, 5]").unwrap();

    let output = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted = String::from_utf8(output.stdout).unwrap();

    // Must contain proper list syntax
    assert!(formatted.contains('['), "Missing list opening bracket");
    assert!(formatted.contains(']'), "Missing list closing bracket");

    // Must NOT contain Debug output
    assert!(
        !formatted.contains("List {"),
        "Debug fallback detected for List"
    );
    assert!(
        !formatted.contains("elements:"),
        "AST Debug output detected"
    );
}

#[test]
fn test_fmt_no_debug_fallback_tuple_literal() {
    // DEFECT-FMT-003: Tuple must format as `(1, 2, 3)`, not Debug output
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("tuple.ruchy");
    fs::write(&test_file, "let pair = (1, 2)\nlet triple = (1, 2, 3)").unwrap();

    let output = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted = String::from_utf8(output.stdout).unwrap();

    // Must contain proper tuple syntax
    assert!(
        formatted.contains('(') && formatted.contains(')'),
        "Missing tuple parentheses"
    );

    // Must NOT contain Debug output
    assert!(
        !formatted.contains("Tuple {"),
        "Debug fallback detected for Tuple"
    );
}

#[test]
fn test_fmt_no_debug_fallback_match_expr() {
    // DEFECT-FMT-003: Match must format as `match x { ... }`, not Debug output
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("match.ruchy");
    fs::write(
        &test_file,
        "match x {\n1 => \"one\"\n2 => \"two\"\n_ => \"other\"\n}",
    )
    .unwrap();

    let output = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted = String::from_utf8(output.stdout).unwrap();

    // Must contain proper match syntax
    assert!(formatted.contains("match"), "Missing match keyword");

    // Must NOT contain Debug output
    assert!(
        !formatted.contains("Match {"),
        "Debug fallback detected for Match"
    );
    assert!(!formatted.contains("arms:"), "AST Debug output detected");
}

#[test]
fn test_fmt_no_debug_fallback_compound_assign() {
    // DEFECT-FMT-003: CompoundAssign must format as `x += 1`, not Debug output
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("compound.ruchy");
    fs::write(&test_file, "let x = 0\nx += 1\nx *= 2\nx -= 5").unwrap();

    let output = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted = String::from_utf8(output.stdout).unwrap();

    // Must contain proper compound assignment operators
    assert!(
        formatted.contains("+=") || formatted.contains("*=") || formatted.contains("-="),
        "Missing compound assignment operators"
    );

    // Must NOT contain Debug output
    assert!(
        !formatted.contains("CompoundAssign"),
        "Debug fallback detected for CompoundAssign"
    );
}

#[test]
fn test_fmt_real_world_head_example() {
    // INTEGRATION TEST: Validate with actual head.ruchy that triggered bug discovery
    // This is the EXACT code pattern from external bug report
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("head.ruchy");

    // Simplified version of head.ruchy that uses all critical constructs
    fs::write(
        &test_file,
        "fun head_lines(file_path, n) {\n\
         let content = fs_read(file_path)\n\
         let result = \"\"\n\
         let line_count = 0\n\
         for i in range(0, content.len()) {\n\
         let ch = content[i]\n\
         if line_count < n {\n\
         result = result + ch\n\
         }\n\
         if ch == \"\\n\" {\n\
         line_count = line_count + 1\n\
         if line_count >= n {\n\
         return result\n\
         }\n\
         }\n\
         }\n\
         result\n\
         }",
    )
    .unwrap();

    let output = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted = String::from_utf8(output.stdout).unwrap();

    // Critical assertions - NONE of these Debug patterns should appear
    assert!(
        !formatted.contains("IndexAccess {"),
        "CRITICAL: Array indexing corrupted with Debug output"
    );
    assert!(
        !formatted.contains("Assign {"),
        "CRITICAL: Assignment corrupted with Debug output"
    );
    assert!(
        !formatted.contains("Return {"),
        "CRITICAL: Return statement corrupted with Debug output"
    );
    assert!(
        !formatted.contains("Expr { kind:"),
        "CRITICAL: AST Debug output detected"
    );
    assert!(
        !formatted.contains("span: Span"),
        "CRITICAL: Span Debug output detected"
    );

    // Positive assertions - proper syntax should be present
    assert!(
        formatted.contains("[i]") || formatted.contains("content["),
        "Array indexing syntax missing"
    );
    assert!(formatted.contains("result = "), "Assignment syntax missing");
    assert!(formatted.contains("return"), "Return keyword missing");

    // The formatted code should pass syntax validation
    let check_result = ruchy_cmd()
        .arg("check")
        .arg(&test_file)
        .output()
        .expect("Failed to run check");

    assert!(
        check_result.status.success(),
        "Formatted code failed syntax validation"
    );
}

// ============================================================================
// Comprehensive Operator Coverage (CRITICAL)
// ============================================================================

#[test]
fn test_fmt_all_binary_operators() {
    // Ensure ALL operators use Display trait, not Debug
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("all_ops.ruchy");
    fs::write(
        &test_file,
        "let a = 1 + 2\n\
         let b = 3 - 4\n\
         let c = 5 * 6\n\
         let d = 7 / 8\n\
         let e = 9 % 10\n\
         let f = 11 == 12\n\
         let g = 13 != 14\n\
         let h = 15 < 16\n\
         let i = 17 > 18\n\
         let j = 19 <= 20\n\
         let k = 21 >= 22",
    )
    .unwrap();

    let output = ruchy_cmd()
        .arg("fmt")
        .arg(&test_file)
        .arg("--stdout")
        .output()
        .expect("Failed to run fmt");

    let formatted = String::from_utf8(output.stdout).unwrap();

    // Must contain actual operators, not Debug names
    assert!(formatted.contains('+'), "Missing + operator");
    assert!(formatted.contains('-'), "Missing - operator");
    assert!(formatted.contains('*'), "Missing * operator");
    assert!(formatted.contains('/'), "Missing / operator");

    // Must NOT contain Debug trait names
    assert!(!formatted.contains("Add"), "Operator mangling: Add found");
    assert!(
        !formatted.contains("Subtract"),
        "Operator mangling: Subtract found"
    );
    assert!(
        !formatted.contains("Multiply"),
        "Operator mangling: Multiply found"
    );
    assert!(
        !formatted.contains("Divide"),
        "Operator mangling: Divide found"
    );
}

#[test]
fn test_fmt_preserves_semantics() {
    // CRITICAL: Formatted code must have identical semantics to original
    // This is the ultimate regression test - run both versions

    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("semantics.ruchy");
    let code = "let x = 10\nlet y = x * 2 + 5\nprintln(y)";
    fs::write(&test_file, code).unwrap();

    // Run original
    let original_output = ruchy_cmd()
        .arg("run")
        .arg(&test_file)
        .output()
        .expect("Failed to run original");

    // Format the file
    ruchy_cmd().arg("fmt").arg(&test_file).assert().success();

    // Run formatted
    let formatted_output = ruchy_cmd()
        .arg("run")
        .arg(&test_file)
        .output()
        .expect("Failed to run formatted");

    // Both must produce identical output
    assert_eq!(
        original_output.stdout, formatted_output.stdout,
        "Formatted code has different semantics!"
    );
}