ryo-source 0.2.0

High-speed Rust AST manipulation engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
//! Comprehensive tests for Pure → syn → source roundtrip conversion.
//!
//! These tests verify that:
//! 1. Source code can be parsed into PureFile
//! 2. PureFile can be converted back to syn types
//! 3. syn types can be formatted back to source code
//! 4. The roundtrip preserves semantic meaning
//! 5. Generated code is valid Rust syntax (parseable by syn)
//! 6. Representative cases compile with rustc (cargo check)

use super::helpers::try_parse_path;
use super::ToSyn;
use crate::pure::ast::PureFile;

// ============================================
// Test Harness
// ============================================

/// Converts source through Pure roundtrip and validates the output is valid Rust.
///
/// This function:
/// 1. Parses source into PureFile
/// 2. Converts back to source via to_source()
/// 3. Validates the output can be parsed by syn (syntax check)
///
/// Returns the generated output for further assertions.
fn assert_valid_rust(source: &str) -> String {
    let pure = PureFile::from_source(source).expect("Input should parse into PureFile");
    let output = pure
        .to_source()
        .expect("to_source should succeed for valid PureFile");

    // P1 validation: Generated code must be valid Rust syntax
    syn::parse_str::<syn::File>(&output).unwrap_or_else(|_| {
        panic!(
            "Generated code must be valid Rust syntax.\nInput:\n{}\nOutput:\n{}",
            source, output
        )
    });

    output
}

/// Validates generated code compiles with rustc via cargo check.
///
/// This is a heavier validation that catches:
/// - Type errors
/// - Name resolution errors
/// - Semantic issues that syn doesn't catch
///
/// Use sparingly on representative cases due to execution time (~1-2s per test).
fn assert_compiles(source: &str) -> String {
    use std::io::Write;
    use std::process::Command;

    let output = assert_valid_rust(source);

    // Create temp directory with Cargo project structure
    let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
    let src_dir = temp_dir.path().join("src");
    std::fs::create_dir_all(&src_dir).expect("Failed to create src dir");

    // Write lib.rs
    let lib_path = src_dir.join("lib.rs");
    let mut file = std::fs::File::create(&lib_path).expect("Failed to create lib.rs");
    // Add common preludes to avoid "not found" errors for std types
    writeln!(file, "#![allow(unused, dead_code)]").unwrap();
    write!(file, "{}", output).expect("Failed to write source");

    // Write Cargo.toml
    let cargo_toml = temp_dir.path().join("Cargo.toml");
    std::fs::write(
        &cargo_toml,
        r#"[package]
name = "roundtrip_test"
version = "0.1.0"
edition = "2021"
"#,
    )
    .expect("Failed to write Cargo.toml");

    // Run cargo check
    let result = Command::new("cargo")
        .args(["check", "--message-format=short"])
        .current_dir(temp_dir.path())
        .output()
        .expect("Failed to run cargo check");

    if !result.status.success() {
        let stderr = String::from_utf8_lossy(&result.stderr);
        panic!(
            "Generated code failed to compile.\n\
             === Input ===\n{}\n\
             === Generated ===\n{}\n\
             === Errors ===\n{}",
            source, output, stderr
        );
    }

    output
}

#[test]
fn test_roundtrip_simple_fn() {
    let source = "fn main() {}";
    let output = assert_valid_rust(source);
    assert!(output.contains("fn main()"));
}

#[test]
fn test_roundtrip_struct() {
    let source = r#"
struct Point {
    x: i32,
    y: i32,
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("struct Point"));
    assert!(output.contains("x: i32"));
    assert!(output.contains("y: i32"));
}

#[test]
fn test_roundtrip_let_else() {
    // `let Some(x) = expr else { return; };` (let-else) must keep its else
    // arm. Losing the `else { ... }` would leave a refutable pattern in a
    // plain `let`, which cargo rejects with E0005 "refutable pattern in
    // local binding". This matches the residual FN class observed by
    // precheck_real_fn_probe after the struct-rest fix landed.
    let source = r#"
fn run(opt: Option<i32>) -> i32 {
    let Some(x) = opt else { return 0; };
    x
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("else"),
        "let-else arm must survive roundtrip.\nOutput:\n{output}"
    );
}

#[test]
fn test_roundtrip_let_mut() {
    // `let mut x = ...;` must keep the `mut` qualifier across roundtrip.
    // Dropping `mut` produces E0596 "cannot borrow as mutable" the next time
    // the executor re-renders an affected file, because subsequent `x.push(..)`
    // / `&mut x` sites lose their backing mutability. This matches the residual
    // FN class hinted at by precheck_real_fn_probe diag
    // "cannot borrow `goal.intents` as mutable".
    let source = r#"
fn run() -> i32 {
    let mut x = 1;
    x += 2;
    x
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("let mut x"),
        "`let mut x` must survive roundtrip.\nOutput:\n{output}"
    );
}

#[test]
fn test_roundtrip_fn_arg_mut() {
    // `fn f(mut goal: Goal)` — function-arg `mut` must survive. Dropping it
    // produces E0596 "cannot borrow `goal.intents` as mutable" at every
    // subsequent mutating use. Direct match for the residual FN diag observed
    // by precheck_real_fn_probe.
    let source = r#"
fn run(mut goal: Vec<i32>) -> Vec<i32> {
    goal.push(1);
    goal
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("mut goal"),
        "fn arg `mut goal` must survive roundtrip.\nOutput:\n{output}"
    );
}

#[test]
fn test_roundtrip_closure_param_mut() {
    // `|mut x| { x.push(..); x }` — closure param `mut` must survive.
    let source = r#"
fn run() -> Vec<i32> {
    let f = |mut x: Vec<i32>| { x.push(1); x };
    f(Vec::new())
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("|mut x"),
        "closure param `|mut x|` must survive roundtrip.\nOutput:\n{output}"
    );
}

#[test]
fn test_roundtrip_for_binding_mut() {
    // `for mut x in iter { x.push(..); }` — for-loop binding `mut` must survive.
    let source = r#"
fn run(items: Vec<Vec<i32>>) {
    for mut x in items {
        x.push(1);
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("for mut x"),
        "for-loop binding `mut` must survive roundtrip.\nOutput:\n{output}"
    );
}

#[test]
fn test_roundtrip_struct_destructure_mut() {
    // `let Foo { mut field, .. } = x;` — struct-destructure field `mut` must
    // survive. Loss would silently demote a mutating field binding into a
    // read-only one, producing E0596 on subsequent `field.push(..)`.
    let source = r#"
struct Foo { field: Vec<i32> }
fn run(foo: Foo) -> Vec<i32> {
    let Foo { mut field } = foo;
    field.push(1);
    field
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("mut field"),
        "struct destructure `mut field` must survive roundtrip.\nOutput:\n{output}"
    );
}

#[test]
fn test_roundtrip_cfg_test_mod_preserves_attribute() {
    // `#[cfg(test)] mod tests { use tempfile::TempDir; ... }` — an inline
    // test module gated by `#[cfg(test)]` whose body imports a dev-only
    // crate (`tempfile`). Losing the `#[cfg(test)]` attribute on round-trip
    // would leak the `use tempfile::TempDir` into the production scope, and
    // cargo check rejects it with `unresolved import tempfile` because
    // `tempfile` is a dev-dependency only.
    //
    // Direct match for the residual Lint FN RL061 axis 2 captured by
    // `rl061_tempfile_fn_observe`: ExtractTrait against
    // `<impl AllowStore>` / `<impl AcChanges>` syncs 23 files in
    // ryo-suggest, and the diagnostics surface as
    // `unresolved import tempfile` originating from the inline test
    // module of `generator/store.rs` / `pattern/rule_store.rs`.
    let source = r#"
pub struct Service;

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn helper() -> TempDir { TempDir::new().unwrap() }
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("#[cfg(test)]"),
        "`#[cfg(test)]` on an inline test module must survive roundtrip.\nOutput:\n{output}"
    );
    assert!(
        output.contains("use tempfile"),
        "test-module body must survive roundtrip with its dev-only imports intact.\nOutput:\n{output}"
    );
}

#[test]
fn test_roundtrip_fn_arg_struct_pattern() {
    // `fn execute_group(SpecGroup { x, .. }: SpecGroup)` — the source
    // uses a struct destructure pattern as the parameter binding. The
    // previous `pat_to_name` collapse turned this into
    // `PureParam::Typed { name: "SpecGroup", .. }`, and re-emission
    // synthesised `SpecGroup: SpecGroup`. Rust's grammar parses the
    // uppercase-leading identifier as a `Pat::Path` and cargo rejects
    // it with "patterns aren't allowed in functions without bodies"
    // whenever the function happens to be inside a trait body-less
    // signature (the residual RL061 axis-1 captured by
    // `rl061_tempfile_fn_observe` against `<impl ExecutionOrchestrator>`).
    //
    // PureParam::Typed now carries an `Option<PurePattern>` that
    // preserves the original pattern, and `to_syn` re-emits it
    // verbatim. Round-trip must keep `SpecGroup { x, .. }` intact.
    let source = r#"
struct SpecGroup { x: u32 }
fn execute_group(SpecGroup { x, .. }: SpecGroup) -> u32 { x }
"#;
    let output = assert_valid_rust(source);
    // prettyplease expands the shorthand `{ x }` to `{ x: x }`, which is
    // semantically identical; check for the struct-destructure shape
    // (`SpecGroup { ... }`) rather than the exact original spelling.
    assert!(
        output.contains("SpecGroup {") && output.contains(".. }: SpecGroup"),
        "fn-arg struct-destructure pattern must survive roundtrip.\nOutput:\n{output}"
    );
    // Crucially: the lossy `SpecGroup: SpecGroup` collapse must NOT appear.
    assert!(
        !output.contains("(SpecGroup: SpecGroup)"),
        "fn-arg must not collapse to the lossy `Name: Type` form that cargo \
         rejects with `patterns aren't allowed`.\nOutput:\n{output}"
    );
}

#[test]
fn test_roundtrip_tuple_variant_from_attribute() {
    // `enum E { Foo(#[from] Inner) }` — thiserror's `#[from]` on a tuple
    // variant's inner field is the trigger for auto-deriving
    // `impl From<Inner> for E`. Dropping the attribute on round-trip removes
    // the From impl and downstream `?` operator usages stop compiling with
    // "couldn't convert the error". This is the residual Pattern FN observed
    // by `dsl-macro-verbatim` × `Api::suggest_scan_with_precheck_limit`
    // (10 × "`?` couldn't convert the error to `ApiError`") — the root cause
    // is the `PureFields::Tuple` carrier dropping per-field attrs, fixed by
    // promoting the carrier to `Vec<PureTupleField>`.
    let source = r#"
#[derive(Debug, thiserror::Error)]
pub enum ApiError {
    #[error("Storage error: {0}")]
    Storage(#[from] StorageError),
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("#[from]"),
        "Tuple-variant `#[from]` attribute must survive roundtrip.\nOutput:\n{output}"
    );
}

#[test]
fn test_roundtrip_tuple_struct_field_attribute() {
    // Same shape on a tuple struct (rather than an enum variant). Confirms
    // the fix covers tuple-struct fields as well — relevant for any derive
    // macro that inspects positional field attrs (`#[serde(skip)]`,
    // `#[validate(...)]`, etc.).
    let source = r#"
#[derive(Debug)]
pub struct Wrapper(#[from] Inner);
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("#[from]"),
        "Tuple-struct field `#[from]` attribute must survive roundtrip.\nOutput:\n{output}"
    );
}

#[test]
fn test_roundtrip_external_mod_decl_preserves_private_vis() {
    // `mod types;` (private external module declaration) must survive
    // roundtrip with its visibility intact. Dropping the privacy promotes
    // the declaration to `pub mod types;`, which is a real-world cargo
    // hazard: at scale (`dsl_macro_verbatim_diff_observe` on
    // `crates/ryo-app/src/api/mod.rs`) the AST round-trip surfaces
    // `pub mod types;` appended to file tail while the original
    // `mod types;` is also dropped from its declared position. The
    // promoted re-emission then collides with re-export rules
    // (`pub use types::*;` flagged as `pub use of private item`)
    // and downstream visibility lints fire on the entire `types::`
    // surface.
    let source = r#"
mod types;
pub mod public_types;

pub use types::*;
"#;
    let output = assert_valid_rust(source);

    // `mod types;` (no `pub`) must remain `mod types;` post-roundtrip.
    // Both `mod types;` and `pub mod types;` would satisfy a naive
    // contains check on the bare identifier, so assert the explicit
    // private form survives.
    assert!(
        output.contains("mod types;"),
        "External `mod types;` declaration must survive roundtrip.\nOutput:\n{output}"
    );
    assert!(
        !output
            .replace("pub mod public_types;", "")
            .contains("pub mod types"),
        "Private `mod types;` must NOT be promoted to `pub mod types;`.\nOutput:\n{output}"
    );
    // Sanity: the actually-public declaration is still public.
    assert!(
        output.contains("pub mod public_types;"),
        "`pub mod public_types;` must remain public.\nOutput:\n{output}"
    );
}

#[test]
fn test_roundtrip_external_mod_decl_preserves_compound_cfg_attribute() {
    // `#[cfg(any(test, feature = "test-utils"))] mod test_harness;` must
    // preserve its compound cfg attribute across roundtrip. The simple
    // `#[cfg(test)] mod foo;` form has its own `extract_cfg_test_scope`
    // path that lifts the attribute into `ModScope::Test`, but compound
    // cfg meta lists (`any(...)` / `all(...)` / `not(...)`) do not match
    // the exact-`cfg(test)` predicate and therefore must remain in
    // `PureMod.attrs` untouched. Real-world hazard surfaced by
    // `r9_symbol_path_resolver_diff_observe` on
    // `crates/ryo-symbol/src/lib.rs`:
    //
    //     -#[cfg(any(test, feature = "test-utils"))]
    //      mod test_harness;
    //
    // After the cfg attribute is silently dropped the module body is
    // visible in every cargo build configuration, but the original
    // `#[cfg(any(test, feature = "test-utils"))] use crate::test_harness::...;`
    // call sites elsewhere in the workspace fail with `unresolved
    // import test_harness` because their cfg conjunction no longer
    // matches the (now unconditional) `mod test_harness` decl.
    let source = r#"
#[cfg(any(test, feature = "test-utils"))]
mod test_harness;
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("#[cfg(any(test, feature = \"test-utils\"))]"),
        "Compound `#[cfg(any(test, feature = \"test-utils\"))]` attribute must survive roundtrip on `mod test_harness;`.\nOutput:\n{output}"
    );
    assert!(
        output.contains("mod test_harness;"),
        "External `mod test_harness;` declaration must survive roundtrip.\nOutput:\n{output}"
    );
}

#[test]
fn test_roundtrip_external_mod_decl() {
    // `mod foo;` (external file module — body-less, semi-terminated) must
    // survive roundtrip. Dropping it leaves `pub use foo::*;` and any other
    // path referring to the submodule unresolved, which cargo eventually
    // reports as a cascade of name-resolution errors. In real workloads the
    // surfaced symptom is "`?` couldn't convert the error to `ApiError`"
    // (S182g0 dsl-macro-verbatim Pattern FN, ryo-app::api::Api::suggest_scan_with_precheck_limit
    // — every method that returns `ApiResult<T>` loses its outer error type
    // once `mod types;` falls off the top of `api/mod.rs` and the rest of
    // the file's type lookups fail).
    let source = r#"
mod types;
pub use types::*;
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("mod types"),
        "External `mod types;` declaration must survive roundtrip.\nOutput:\n{output}"
    );
}

#[test]
fn test_roundtrip_struct_functional_update() {
    // PureExpr::Struct must preserve `..rest` (functional update syntax).
    // Regression: struct literals with `..Default::default()` dropped the rest
    // field on roundtrip, producing spurious "missing fields" cargo errors when
    // a mutation re-rendered an affected file.
    let source = r#"
fn make() -> Foo {
    Foo { a: 1, ..Default::default() }
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains(".."),
        "Functional update `..Default::default()` must survive roundtrip.\nOutput:\n{output}"
    );
}

#[test]
fn test_roundtrip_impl() {
    let source = r#"
impl Point {
    fn new(x: i32, y: i32) -> Self {
        Self { x, y }
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("impl Point"));
    assert!(output.contains("fn new"));
}

#[test]
fn test_roundtrip_use() {
    let source = "use std::io;";
    let output = assert_valid_rust(source);
    assert!(output.contains("use std::io"));
}

#[test]
fn test_roundtrip_complex() {
    let source = r#"
use std::collections::HashMap;

struct Config {
    name: String,
    value: i32,
}

impl Config {
    fn new(name: &str, value: i32) -> Self {
        Self {
            name: name.to_string(),
            value,
        }
    }

    fn get_value(&self) -> i32 {
        self.value
    }
}

fn main() {
    let config = Config::new("test", 42);
    let result = config.get_value();
    println!("{}", result);
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("use std::collections::HashMap"));
    assert!(output.contains("struct Config"));
    assert!(output.contains("impl Config"));
    assert!(output.contains("fn main()"));
}

// ============================================
// Regression tests for DOGFOODING_BUGS.md
// ============================================

/// Bug 1: Pat::Verbatim panic (qualified path pattern)
/// prettyplease panicked on `Pat::Verbatim` for path patterns like `Some`, `None`, `Enum::Variant`
#[test]
fn test_roundtrip_path_pattern_option() {
    let source = r#"
fn handle_option(x: Option<i32>) {
    match x {
        Some(v) => println!("{}", v),
        None => println!("none"),
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("Some"));
    assert!(output.contains("None"));
}

/// Bug 1: Qualified path with enum variant (e.g., `Enum::Variant`)
#[test]
fn test_roundtrip_qualified_path_pattern() {
    let source = r#"
enum Status {
    Ok,
    Err,
}

fn check(s: Status) {
    match s {
        Status::Ok => println!("ok"),
        Status::Err => println!("err"),
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("Status::Ok"));
    assert!(output.contains("Status::Err"));
}

/// Bug 2: Tuple struct pattern with numbered fields (e.g., `Some(x)`, `Ok(v)`)
/// `to_syn.rs` panicked with "Ident cannot be a number" for tuple struct patterns
#[test]
fn test_roundtrip_tuple_struct_pattern() {
    let source = r#"
fn extract(opt: Option<i32>) {
    if let Some(v) = opt {
        println!("{}", v);
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("Some"));
}

/// Bug 2: Multiple fields in tuple struct pattern
#[test]
fn test_roundtrip_tuple_struct_multi_field() {
    let source = r#"
struct Point(i32, i32);

fn extract(p: Point) {
    let Point(x, y) = p;
    println!("{} {}", x, y);
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("Point"));
}

/// Bug 3: Raw identifier (e.g., `r#async`, `r#type`)
/// `ident()` function panicked with "r#async is not a valid Ident"
#[test]
fn test_roundtrip_raw_identifier_fn() {
    let source = r#"
fn r#async() -> i32 {
    42
}
"#;
    let output = assert_valid_rust(source);
    // The output should contain the raw identifier
    assert!(output.contains("r#async") || output.contains("async"));
}

/// Bug 3: Raw identifier in variable binding
#[test]
fn test_roundtrip_raw_identifier_variable() {
    let source = r#"
fn use_raw() {
    let r#type = 1;
    let r#match = 2;
    println!("{} {}", r#type, r#match);
}
"#;
    let output = assert_valid_rust(source);
    // Should compile without panic
    assert!(output.contains("fn use_raw"));
}

/// Additional pattern: Range pattern
#[test]
fn test_roundtrip_range_pattern() {
    let source = r#"
fn check_range(n: i32) {
    match n {
        0..=10 => println!("small"),
        _ => println!("large"),
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("0"));
    assert!(output.contains("10"));
}

/// Additional pattern: Slice pattern
#[test]
fn test_roundtrip_slice_pattern() {
    let source = r#"
fn check_slice(arr: &[i32]) {
    match arr {
        [] => println!("empty"),
        [first] => println!("{}", first),
        [first, rest @ ..] => println!("{} and more", first),
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("first"));
}

// ============================================
// Fix tests for generics and assignment
// ============================================

/// Test try_parse_path with generic type parameters
#[test]
fn test_parse_path_with_generics() {
    // Simple generic
    let path = try_parse_path("Vec<i32>").unwrap();
    assert_eq!(path.segments.len(), 1);
    assert_eq!(path.segments[0].ident.to_string(), "Vec");

    // Nested generic
    let path = try_parse_path("Vec<Option<String>>").unwrap();
    assert_eq!(path.segments.len(), 1);

    // Module path with generic
    let path = try_parse_path("std::vec::Vec<i32>").unwrap();
    assert_eq!(path.segments.len(), 3);
}

/// Test roundtrip for assignment expression
#[test]
fn test_roundtrip_assignment_expression() {
    let source = r#"
fn assign_test() {
    let mut x = 0;
    x = 42;
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("x = 42"));
}

/// Test roundtrip for derive attribute
#[test]
fn test_roundtrip_derive_attribute() {
    let source = r#"
#[derive(Debug, Clone)]
struct Foo {
    x: i32,
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("#[derive(Debug, Clone)]"));
}

/// Test roundtrip for type with generic parameters
#[test]
fn test_roundtrip_generic_type() {
    let source = r#"
fn generic_fn() -> Vec<String> {
    Vec::new()
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("Vec<String>") || output.contains("Vec< String >"));
}

/// Test roundtrip for field type with generic
#[test]
fn test_roundtrip_struct_with_generic_field() {
    let source = r#"
struct Container {
    items: Vec<LintCategory>,
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("Vec"));
    assert!(output.contains("LintCategory"));
}

/// Test roundtrip for struct pattern with rest (..)
#[test]
fn test_roundtrip_struct_pattern_with_rest() {
    let source = r#"
struct Point { x: i32, y: i32, z: i32 }

fn use_pattern(p: Point) {
    let Point { x, .. } = p;
    println!("{}", x);
}
"#;
    let output = assert_valid_rust(source);
    // Should contain rest pattern
    assert!(
        output.contains(".."),
        "Output should contain '..': {}",
        output
    );
}

/// Test roundtrip for rest-only struct pattern (no fields, just `{ .. }`)
#[test]
fn test_roundtrip_rest_only_struct_pattern() {
    let source = r#"
enum Foo {
    Bar { x: i32, y: i32 },
    Baz,
}

fn match_foo(f: Foo) {
    match f {
        Foo::Bar { .. } => println!("bar"),
        Foo::Baz => println!("baz"),
    }
}
"#;
    let output = assert_valid_rust(source);
    // Should preserve `{ .. }` not convert to `()`
    assert!(
        output.contains("Bar { .. }") || output.contains("Bar {..}"),
        "Output should contain 'Bar {{ .. }}', got: {}",
        output
    );
    // Should NOT contain `Bar()`
    assert!(
        !output.contains("Bar()"),
        "Output should NOT contain 'Bar()', got: {}",
        output
    );
}

/// Test roundtrip for turbofish in method call (e.g., `.collect::<Vec<_>>()`)
#[test]
fn test_roundtrip_turbofish_method_call() {
    let source = r#"
fn turbofish_test() {
    let v = [1, 2, 3].iter().collect::<Vec<_>>();
    let s = "hello".parse::<i32>();
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("collect::<") || output.contains("collect ::< "),
        "Output should contain turbofish 'collect::<': {}",
        output
    );
    assert!(
        output.contains("parse::<") || output.contains("parse ::< "),
        "Output should contain turbofish 'parse::<': {}",
        output
    );
}

/// Test roundtrip for range expressions
#[test]
fn test_roundtrip_range_expression() {
    let source = r#"
fn range_test() {
    let a = 0..10;
    let b = 0..=10;
    let c = ..10;
    let d = 0..;
    for i in 0..5 {
        println!("{}", i);
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("0..10") || output.contains("0 .. 10"),
        "Output should contain '0..10': {}",
        output
    );
    assert!(
        output.contains("0..=10") || output.contains("0 ..= 10"),
        "Output should contain '0..=10': {}",
        output
    );
}

/// Test roundtrip for cast expressions
#[test]
fn test_roundtrip_cast_expression() {
    let source = r#"
fn cast_test() {
    let x = 42u8 as i32;
    let y = 3.14f64 as i64;
    let ptr = &x as *const i32;
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("as i32"),
        "Output should contain 'as i32': {}",
        output
    );
    assert!(
        output.contains("as i64"),
        "Output should contain 'as i64': {}",
        output
    );
}

/// Test roundtrip for if let expression
#[test]
fn test_roundtrip_if_let_expression() {
    let source = r#"
fn if_let_test(opt: Option<i32>) {
    if let Some(x) = opt {
        println!("{}", x);
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("if let Some"),
        "Output should contain 'if let Some': {}",
        output
    );
}

/// Test roundtrip for while let expression
#[test]
fn test_roundtrip_while_let_expression() {
    let source = r#"
fn while_let_test(mut iter: std::vec::IntoIter<i32>) {
    while let Some(x) = iter.next() {
        println!("{}", x);
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("while let Some"),
        "Output should contain 'while let Some': {}",
        output
    );
}

/// Test roundtrip for move closure
#[test]
fn test_roundtrip_move_closure() {
    let source = r#"
fn move_closure_test() {
    let x = 42;
    let f = move || x + 1;
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("move"),
        "Output should contain 'move': {}",
        output
    );
}

/// Test roundtrip for async closure (unstable, but should parse)
#[test]
fn test_roundtrip_async_closure() {
    let source = r#"
fn async_closure_test() {
    let f = async || 42;
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("async"),
        "Output should contain 'async': {}",
        output
    );
}

/// Test roundtrip for typed closure params and return type
#[test]
fn test_roundtrip_typed_closure() {
    let source = r#"
fn typed_closure_test() {
    let f = |x: i32, y: String| -> bool { x > 0 };
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("i32"),
        "Output should contain param type 'i32': {}",
        output
    );
    assert!(
        output.contains("String"),
        "Output should contain param type 'String': {}",
        output
    );
    assert!(
        output.contains("bool"),
        "Output should contain return type 'bool': {}",
        output
    );
}

/// Test roundtrip for async block
#[test]
fn test_roundtrip_async_block() {
    let source = r#"
fn async_block_test() {
    let fut = async {
        42
    };
    let fut_move = async move {
        42
    };
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("async"),
        "Output should contain 'async': {}",
        output
    );
}

/// Test roundtrip for unsafe block
#[test]
fn test_roundtrip_unsafe_block() {
    let source = r#"
fn unsafe_block_test() {
    let x = unsafe {
        std::mem::zeroed::<i32>()
    };
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("unsafe"),
        "Output should contain 'unsafe': {}",
        output
    );
}

/// Test roundtrip for array repeat
#[test]
fn test_roundtrip_array_repeat() {
    let source = r#"
fn array_repeat_test() {
    let zeros = [0; 10];
    let ones = [1u8; 256];
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("[0; 10]") || output.contains("[0 ; 10]"),
        "Output should contain '[0; 10]': {}",
        output
    );
}

/// Test adding derive via PureAttribute (simulates AddDeriveMutation)
#[test]
fn test_add_derive_via_pure_attribute() {
    use crate::pure::ast::{
        PureAttrMeta, PureAttribute, PureField, PureFields, PureGenerics, PureStruct, PureType,
        PureVis,
    };

    // Create a struct without derives
    let mut s = PureStruct {
        name: "Foo".to_string(),
        vis: PureVis::Public,
        generics: PureGenerics::default(),
        attrs: vec![],
        fields: PureFields::Named(vec![PureField {
            name: "x".to_string(),
            vis: PureVis::Private,
            ty: PureType::Path("i32".to_string()),
            attrs: vec![],
        }]),
    };

    // Add derive attribute (as AddDeriveMutation does)
    s.attrs.push(PureAttribute {
        path: "derive".to_string(),
        meta: PureAttrMeta::List("Debug, Clone".to_string()),
        is_inner: false,
    });

    // Convert to syn and back to string
    let syn_struct = s.to_syn().unwrap();
    let output = prettyplease::unparse(&syn::File {
        shebang: None,
        attrs: vec![],
        items: vec![syn::Item::Struct(syn_struct)],
    });

    assert!(
        output.contains("#[derive(Debug, Clone)]") || output.contains("#[derive(Debug , Clone)]"),
        "Output should contain '#[derive(Debug, Clone)]': {}",
        output
    );
}

// ============================================
// Compile Verification Tests (P1 - cargo check)
// ============================================
//
// These tests verify that generated code actually compiles with rustc.
// They are slower (~1-2s each) but catch type errors and semantic issues.
// Run with: cargo test compile_check -- --ignored

/// Struct with impl block - representative of typical mutation output
#[test]
#[ignore = "slow: requires cargo check"]
fn compile_check_struct_with_impl() {
    let source = r#"
#[derive(Debug, Clone)]
pub struct Point {
    pub x: i32,
    pub y: i32,
}

impl Point {
    pub fn new(x: i32, y: i32) -> Self {
        Self { x, y }
    }

    pub fn distance(&self, other: &Point) -> f64 {
        let dx = (self.x - other.x) as f64;
        let dy = (self.y - other.y) as f64;
        (dx * dx + dy * dy).sqrt()
    }
}
"#;
    assert_compiles(source);
}

/// Enum with match - tests pattern generation
#[test]
#[ignore = "slow: requires cargo check"]
fn compile_check_enum_with_match() {
    let source = r#"
#[derive(Debug, Clone, PartialEq)]
pub enum Status {
    Pending,
    InProgress { progress: u8 },
    Done,
}

impl Status {
    pub fn is_complete(&self) -> bool {
        matches!(self, Status::Done)
    }

    pub fn description(&self) -> &'static str {
        match self {
            Status::Pending => "Not started",
            Status::InProgress { progress } if *progress > 50 => "More than half done",
            Status::InProgress { .. } => "In progress",
            Status::Done => "Complete",
        }
    }
}
"#;
    assert_compiles(source);
}

/// Generics and traits - complex type system usage
#[test]
#[ignore = "slow: requires cargo check"]
fn compile_check_generics_and_traits() {
    let source = r#"
use std::fmt::Display;

pub trait Printable {
    fn print(&self);
}

pub struct Container<T> {
    value: T,
}

impl<T: Display> Container<T> {
    pub fn new(value: T) -> Self {
        Self { value }
    }
}

impl<T: Display> Printable for Container<T> {
    fn print(&self) {
        println!("{}", self.value);
    }
}
"#;
    assert_compiles(source);
}

/// Complex expressions - closures, iterators, method chains
#[test]
#[ignore = "slow: requires cargo check"]
fn compile_check_complex_expressions() {
    let source = r#"
pub fn process_data(data: Vec<i32>) -> Vec<i32> {
    data.iter()
        .filter(|&x| *x > 0)
        .map(|x| x * 2)
        .collect::<Vec<_>>()
}

pub fn with_closure() -> impl Fn(i32) -> i32 {
    let multiplier = 3;
    move |x| x * multiplier
}
"#;
    assert_compiles(source);
}

/// Full module structure - simulates real-world file
#[test]
#[ignore = "slow: requires cargo check"]
fn compile_check_full_module() {
    let source = r#"
//! A simple todo list module.

use std::collections::HashMap;

/// A single todo item.
#[derive(Debug, Clone)]
pub struct TodoItem {
    pub id: u32,
    pub title: String,
    pub completed: bool,
}

impl TodoItem {
    pub fn new(id: u32, title: impl Into<String>) -> Self {
        Self {
            id,
            title: title.into(),
            completed: false,
        }
    }

    pub fn complete(&mut self) {
        self.completed = true;
    }
}

/// A collection of todo items.
#[derive(Debug, Default)]
pub struct TodoList {
    items: HashMap<u32, TodoItem>,
    next_id: u32,
}

impl TodoList {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn add(&mut self, title: impl Into<String>) -> u32 {
        let id = self.next_id;
        self.next_id += 1;
        self.items.insert(id, TodoItem::new(id, title));
        id
    }

    pub fn get(&self, id: u32) -> Option<&TodoItem> {
        self.items.get(&id)
    }

    pub fn complete(&mut self, id: u32) -> bool {
        if let Some(item) = self.items.get_mut(&id) {
            item.complete();
            true
        } else {
            false
        }
    }

    pub fn pending(&self) -> impl Iterator<Item = &TodoItem> {
        self.items.values().filter(|item| !item.completed)
    }
}
"#;
    assert_compiles(source);
}

/// Test that type annotations on let bindings are preserved during roundtrip
#[test]
fn test_roundtrip_let_type_annotation() {
    let source = r#"
fn test_type_annotations() {
    let x: i32 = 42;
    let args: Vec<String> = vec![];
    let map: std::collections::HashMap<String, i32> = Default::default();
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains(": i32"),
        "Output should preserve ': i32' type annotation: {}",
        output
    );
    assert!(
        output.contains(": Vec<String>"),
        "Output should preserve ': Vec<String>' type annotation: {}",
        output
    );
    assert!(
        output.contains("HashMap<String, i32>"),
        "Output should preserve 'HashMap<String, i32>' type annotation: {}",
        output
    );
}

/// Test type annotations with mut bindings
#[test]
fn test_roundtrip_let_mut_type_annotation() {
    let source = r#"
fn test_mut_type_annotations() {
    let mut count: usize = 0;
    let mut buffer: Vec<u8> = Vec::new();
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("mut count: usize"),
        "Output should preserve 'mut count: usize': {}",
        output
    );
    assert!(
        output.contains("mut buffer: Vec<u8>"),
        "Output should preserve 'mut buffer: Vec<u8>': {}",
        output
    );
}

// ============================================
// Label and ABI Roundtrip Tests
// ============================================

/// Test roundtrip for labeled loop
#[test]
fn test_roundtrip_labeled_loop() {
    let source = r#"
fn labeled_loop_test() {
    'outer: loop {
        'inner: loop {
            break 'outer;
        }
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("'outer") || output.contains("' outer"),
        "Output should contain 'outer label: {}",
        output
    );
    assert!(
        output.contains("'inner") || output.contains("' inner"),
        "Output should contain 'inner label: {}",
        output
    );
    assert!(
        output.contains("break 'outer") || output.contains("break ' outer"),
        "Output should contain 'break 'outer': {}",
        output
    );
}

/// Test roundtrip for labeled while loop
#[test]
fn test_roundtrip_labeled_while() {
    let source = r#"
fn labeled_while_test() {
    let mut i = 0;
    'outer: while i < 10 {
        i += 1;
        if i == 5 {
            continue 'outer;
        }
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("'outer") || output.contains("' outer"),
        "Output should contain 'outer label: {}",
        output
    );
    assert!(
        output.contains("continue 'outer") || output.contains("continue ' outer"),
        "Output should contain 'continue 'outer': {}",
        output
    );
}

/// Test roundtrip for labeled for loop
#[test]
fn test_roundtrip_labeled_for() {
    let source = r#"
fn labeled_for_test() {
    'outer: for i in 0..10 {
        for j in 0..10 {
            if i + j > 15 {
                break 'outer;
            }
        }
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("'outer") || output.contains("' outer"),
        "Output should contain 'outer label: {}",
        output
    );
}

/// Test roundtrip for labeled block
#[test]
fn test_roundtrip_labeled_block() {
    let source = r#"
fn labeled_block_test() -> i32 {
    let result = 'block: {
        if true {
            break 'block 42;
        }
        0
    };
    result
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("'block") || output.contains("' block"),
        "Output should contain 'block label: {}",
        output
    );
    assert!(
        output.contains("break 'block 42") || output.contains("break ' block 42"),
        "Output should contain 'break 'block 42': {}",
        output
    );
}

/// Test roundtrip for break with value (no label)
#[test]
fn test_roundtrip_break_with_value() {
    let source = r#"
fn break_with_value_test() -> i32 {
    loop {
        break 42;
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("break 42"),
        "Output should contain 'break 42': {}",
        output
    );
}

/// Test roundtrip for break with label and value
#[test]
fn test_roundtrip_break_label_and_value() {
    let source = r#"
fn break_label_value_test() -> i32 {
    'outer: loop {
        loop {
            break 'outer 100;
        }
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("break 'outer 100") || output.contains("break ' outer 100"),
        "Output should contain 'break 'outer 100': {}",
        output
    );
}

/// Test roundtrip for continue with label
#[test]
fn test_roundtrip_continue_with_label() {
    let source = r#"
fn continue_label_test() {
    'outer: for i in 0..5 {
        for j in 0..5 {
            if j == 2 {
                continue 'outer;
            }
        }
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("continue 'outer") || output.contains("continue ' outer"),
        "Output should contain 'continue 'outer': {}",
        output
    );
}

/// Test roundtrip for extern "C" function
#[test]
fn test_roundtrip_extern_c_fn() {
    let source = r#"
extern "C" fn c_function(x: i32) -> i32 {
    x + 1
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains(r#"extern "C""#),
        r#"Output should contain 'extern "C"': {}"#,
        output
    );
}

/// Test roundtrip for extern "system" function
#[test]
fn test_roundtrip_extern_system_fn() {
    let source = r#"
extern "system" fn system_function() {}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains(r#"extern "system""#),
        r#"Output should contain 'extern "system"': {}"#,
        output
    );
}

/// Test roundtrip for extern block with multiple functions
#[test]
fn test_roundtrip_extern_block() {
    let source = r#"
extern "C" {
    fn strlen(s: *const u8) -> usize;
    fn memcpy(dest: *mut u8, src: *const u8, n: usize) -> *mut u8;
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains(r#"extern "C""#),
        r#"Output should contain 'extern "C"': {}"#,
        output
    );
    assert!(
        output.contains("strlen"),
        "Output should contain 'strlen': {}",
        output
    );
    assert!(
        output.contains("memcpy"),
        "Output should contain 'memcpy': {}",
        output
    );
}

/// Test roundtrip for nested labeled loops
#[test]
fn test_roundtrip_nested_labeled_loops() {
    let source = r#"
fn nested_labels() {
    'a: loop {
        'b: loop {
            'c: loop {
                break 'a;
            }
            continue 'b;
        }
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("'a") || output.contains("' a"),
        "Output should contain label 'a: {}",
        output
    );
    assert!(
        output.contains("'b") || output.contains("' b"),
        "Output should contain label 'b: {}",
        output
    );
    assert!(
        output.contains("'c") || output.contains("' c"),
        "Output should contain label 'c: {}",
        output
    );
    assert!(
        output.contains("break 'a") || output.contains("break ' a"),
        "Output should contain 'break 'a': {}",
        output
    );
    assert!(
        output.contains("continue 'b") || output.contains("continue ' b"),
        "Output should contain 'continue 'b': {}",
        output
    );
}

/// Compile verification test for labeled loops
#[test]
#[ignore = "slow: requires cargo check"]
fn compile_check_labeled_loops() {
    let source = r#"
pub fn search_matrix(matrix: Vec<Vec<i32>>, target: i32) -> Option<(usize, usize)> {
    'row: for (i, row) in matrix.iter().enumerate() {
        for (j, &val) in row.iter().enumerate() {
            if val == target {
                return Some((i, j));
            }
            if val > target {
                continue 'row;
            }
        }
    }
    None
}

pub fn find_first_match(data: &[&[i32]], predicate: impl Fn(i32) -> bool) -> Option<i32> {
    'outer: for slice in data {
        for &item in *slice {
            if predicate(item) {
                break 'outer Some(item);
            }
        }
    }
    None
}
"#;
    assert_compiles(source);
}

/// Compile verification test for extern functions
#[test]
#[ignore = "slow: requires cargo check"]
fn compile_check_extern_functions() {
    let source = r#"
extern "C" fn add_c(a: i32, b: i32) -> i32 {
    a + b
}

extern "C" fn noop() {}

pub fn use_extern() -> i32 {
    add_c(1, 2)
}
"#;
    assert_compiles(source);
}

// ============================================
// Inline Module Tests
// ============================================

/// Test inline module with use statements
#[test]
fn test_roundtrip_inline_mod_with_uses() {
    let source = r#"
mod utils {
    use std::collections::HashMap;
    use std::io::Write;

    pub fn helper() {}
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("mod utils"), "Output: {}", output);
    assert!(
        output.contains("use std::collections::HashMap"),
        "Output: {}",
        output
    );
    assert!(output.contains("use std::io::Write"), "Output: {}", output);
    assert!(output.contains("pub fn helper"), "Output: {}", output);
}

/// Test inline module with multiple items and uses
#[test]
fn test_roundtrip_inline_mod_complex() {
    let source = r#"
pub mod models {
    use serde::{Deserialize, Serialize};

    pub struct User {
        pub name: String,
        pub age: u32,
    }

    pub fn create_user(name: String, age: u32) -> User {
        User { name, age }
    }
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("pub mod models"), "Output: {}", output);
    assert!(output.contains("use serde"), "Output: {}", output);
    assert!(output.contains("struct User"), "Output: {}", output);
}

/// Test file module declaration (mod foo;)
#[test]
fn test_roundtrip_file_mod_declaration() {
    let source = r#"
mod utils;
pub mod config;
"#;
    let output = assert_valid_rust(source);
    assert!(
        output.contains("mod utils ;") || output.contains("mod utils;"),
        "Output: {}",
        output
    );
    assert!(
        output.contains("pub mod config ;") || output.contains("pub mod config;"),
        "Output: {}",
        output
    );
}

/// Test nested inline modules
#[test]
fn test_roundtrip_nested_inline_mods() {
    let source = r#"
mod outer {
    use std::io;

    mod inner {
        use std::fmt;

        pub fn format_it() {}
    }

    pub fn outer_fn() {}
}
"#;
    let output = assert_valid_rust(source);
    assert!(output.contains("mod outer"), "Output: {}", output);
    assert!(output.contains("mod inner"), "Output: {}", output);
    assert!(output.contains("use std::io"), "Output: {}", output);
    assert!(output.contains("use std::fmt"), "Output: {}", output);
}

/// Test inline module preserves use statement ordering
#[test]
fn test_roundtrip_mod_use_ordering() {
    let source = r#"
mod ordered {
    use a::A;
    use b::B;
    use c::C;

    struct Item;
}
"#;
    let output = assert_valid_rust(source);
    // Uses should appear before struct
    let use_pos = output.find("use a::A").expect("use a::A not found");
    let struct_pos = output.find("struct Item").expect("struct Item not found");
    assert!(
        use_pos < struct_pos,
        "Use statements should come before items. Output: {}",
        output
    );
}

// ============================================
// ToSyn Result Tests
// ============================================

/// Test that to_source() returns Ok for valid input
#[test]
fn test_to_source_result_success() {
    let source = r#"
fn hello() -> String {
    "world".to_string()
}
"#;
    let pure = PureFile::from_source(source).expect("Should parse");
    let result = pure.to_source();
    assert!(
        result.is_ok(),
        "to_source should succeed: {:?}",
        result.err()
    );

    let output = result.unwrap();
    assert!(output.contains("fn hello"));
    assert!(output.contains("world"));
}

/// Test that to_syn() returns Ok for valid input
#[test]
fn test_to_syn_result_success() {
    let source = r#"
struct Point { x: i32, y: i32 }
"#;
    let pure = PureFile::from_source(source).expect("Should parse");
    let result = pure.to_syn();
    assert!(result.is_ok(), "to_syn should succeed: {:?}", result.err());

    let file = result.unwrap();
    assert_eq!(file.items.len(), 1);
}

// =====================================================================
// B-3: PureExpr::Verbatim end-to-end
// =====================================================================

/// Build a tiny PureFile with a single fn whose body returns an
/// expression-level Verbatim, and assert the raw bytes survive
/// `to_source` 1:1 (the stub identifier is replaced by the raw text).
#[test]
fn test_pureexpr_verbatim_splices_raw_bytes_in_fn_body() {
    use crate::pure::ast::{
        PureBlock, PureExpr, PureFn, PureGenerics, PureItem, PureStmt, PureVis,
    };

    let raw = "html ! { < div > { value } < / div > }";
    let body = PureBlock {
        stmts: vec![PureStmt::Expr(PureExpr::Verbatim(raw.to_string()))],
    };
    let f = PureFn {
        attrs: vec![],
        vis: PureVis::Private,
        is_async: false,
        is_async_inferred: false,
        is_const: false,
        is_unsafe: false,
        abi: None,
        name: "dsl_body".to_string(),
        generics: PureGenerics::default(),
        params: vec![],
        ret: None,
        body,
    };
    let file = PureFile {
        attrs: vec![],
        items: vec![PureItem::Fn(f)],
    };

    let out = file.to_source().expect("to_source");

    // Raw payload survived 1:1.
    assert!(
        out.contains(raw),
        "raw expr-verbatim payload should survive 1:1, got:\n{}",
        out
    );
    // Stub identifier must NOT leak into the output (splice succeeded).
    assert!(
        !out.contains("__ryo_verbatim_expr_"),
        "stub identifier should be spliced away, got:\n{}",
        out
    );
}

/// Multiple PureExpr::Verbatim instances should each get a fresh
/// per-call index and splice independently — no collisions.
#[test]
fn test_pureexpr_verbatim_multiple_get_independent_indices() {
    use crate::pure::ast::{
        PureBlock, PureExpr, PureFn, PureGenerics, PureItem, PureStmt, PureVis,
    };

    let raw_a = "html ! { < a > }";
    let raw_b = "html ! { < b > }";
    let mk_fn = |name: &str, raw: &str| PureFn {
        attrs: vec![],
        vis: PureVis::Private,
        is_async: false,
        is_async_inferred: false,
        is_const: false,
        is_unsafe: false,
        abi: None,
        name: name.to_string(),
        generics: PureGenerics::default(),
        params: vec![],
        ret: None,
        body: PureBlock {
            stmts: vec![PureStmt::Expr(PureExpr::Verbatim(raw.to_string()))],
        },
    };
    let file = PureFile {
        attrs: vec![],
        items: vec![
            PureItem::Fn(mk_fn("a", raw_a)),
            PureItem::Fn(mk_fn("b", raw_b)),
        ],
    };

    let out = file.to_source().expect("to_source");

    assert!(
        out.contains(raw_a),
        "raw_a should be present, got:\n{}",
        out
    );
    assert!(
        out.contains(raw_b),
        "raw_b should be present, got:\n{}",
        out
    );
    assert!(
        !out.contains("__ryo_verbatim_expr_"),
        "no stub identifier should leak, got:\n{}",
        out
    );
}

// =====================================================================
// B-3-cont: PureStmt::Verbatim end-to-end
// =====================================================================

/// Verify that a stmt-level Verbatim survives `to_source` 1:1 and the
/// stub identifier does not leak.
#[test]
fn test_purestmt_verbatim_splices_raw_line_in_fn_body() {
    use crate::pure::ast::{PureBlock, PureFn, PureGenerics, PureItem, PureStmt, PureVis};

    // Raw stmt with deliberate spacing the user wants to keep verbatim.
    let raw = "let __x  =  \"keep   me\".to_string();";
    let body = PureBlock {
        stmts: vec![PureStmt::Verbatim(raw.to_string())],
    };
    let f = PureFn {
        attrs: vec![],
        vis: PureVis::Private,
        is_async: false,
        is_async_inferred: false,
        is_const: false,
        is_unsafe: false,
        abi: None,
        name: "stmt_carrier".to_string(),
        generics: PureGenerics::default(),
        params: vec![],
        ret: None,
        body,
    };
    let file = PureFile {
        attrs: vec![],
        items: vec![PureItem::Fn(f)],
    };

    let out = file.to_source().expect("to_source");

    assert!(
        out.contains(raw),
        "raw stmt-verbatim payload should survive 1:1, got:\n{}",
        out
    );
    assert!(
        !out.contains("__ryo_verbatim_stmt_"),
        "stmt stub identifier should be spliced away, got:\n{}",
        out
    );
}

/// PureStmt::Verbatim and PureExpr::Verbatim use **independent
/// registries / index counters** — verify that mixing both in the
/// same file does not collide their splices.
#[test]
fn test_purestmt_and_pureexpr_verbatim_coexist_without_collision() {
    use crate::pure::ast::{
        PureBlock, PureExpr, PureFn, PureGenerics, PureItem, PureStmt, PureVis,
    };

    let stmt_raw = "tracing :: info ! ( \"hi\" );";
    let expr_raw = "html ! { < div > }";
    let body = PureBlock {
        stmts: vec![
            PureStmt::Verbatim(stmt_raw.to_string()),
            PureStmt::Expr(PureExpr::Verbatim(expr_raw.to_string())),
        ],
    };
    let f = PureFn {
        attrs: vec![],
        vis: PureVis::Private,
        is_async: false,
        is_async_inferred: false,
        is_const: false,
        is_unsafe: false,
        abi: None,
        name: "mix".to_string(),
        generics: PureGenerics::default(),
        params: vec![],
        ret: None,
        body,
    };
    let file = PureFile {
        attrs: vec![],
        items: vec![PureItem::Fn(f)],
    };

    let out = file.to_source().expect("to_source");

    assert!(
        out.contains(stmt_raw),
        "stmt raw must survive, got:\n{}",
        out
    );
    assert!(
        out.contains(expr_raw),
        "expr raw must survive, got:\n{}",
        out
    );
    assert!(
        !out.contains("__ryo_verbatim_stmt_"),
        "no stmt stub should leak, got:\n{}",
        out
    );
    assert!(
        !out.contains("__ryo_verbatim_expr_"),
        "no expr stub should leak, got:\n{}",
        out
    );
}

/// Successive calls must reset both registries — same contract as the
/// expr-level reset test, extended to cover stmt.
#[test]
fn test_purestmt_verbatim_registry_resets_between_calls() {
    use crate::pure::ast::{PureBlock, PureFn, PureGenerics, PureItem, PureStmt, PureVis};

    let raw = "let n = 1 + 2 ;";
    let mk = || PureFile {
        attrs: vec![],
        items: vec![PureItem::Fn(PureFn {
            attrs: vec![],
            vis: PureVis::Private,
            is_async: false,
            is_async_inferred: false,
            is_const: false,
            is_unsafe: false,
            abi: None,
            name: "f".to_string(),
            generics: PureGenerics::default(),
            params: vec![],
            ret: None,
            body: PureBlock {
                stmts: vec![PureStmt::Verbatim(raw.to_string())],
            },
        })],
    };
    let first = mk().to_source().expect("first");
    let second = mk().to_source().expect("second");
    assert_eq!(
        first, second,
        "successive to_source calls must be byte-identical"
    );
    assert!(first.contains(raw) && second.contains(raw));
    assert!(!first.contains("__ryo_verbatim_stmt_"));
}

/// A second call to to_source after a successful first call must
/// reset the registry — otherwise indices would accumulate and the
/// stub identifier search would miss.
#[test]
fn test_pureexpr_verbatim_registry_resets_between_calls() {
    use crate::pure::ast::{
        PureBlock, PureExpr, PureFn, PureGenerics, PureItem, PureStmt, PureVis,
    };

    let raw = "tracing :: info ! ( \"x\" )";
    let mk = || PureFile {
        attrs: vec![],
        items: vec![PureItem::Fn(PureFn {
            attrs: vec![],
            vis: PureVis::Private,
            is_async: false,
            is_async_inferred: false,
            is_const: false,
            is_unsafe: false,
            abi: None,
            name: "f".to_string(),
            generics: PureGenerics::default(),
            params: vec![],
            ret: None,
            body: PureBlock {
                stmts: vec![PureStmt::Expr(PureExpr::Verbatim(raw.to_string()))],
            },
        })],
    };
    let first = mk().to_source().expect("first call");
    let second = mk().to_source().expect("second call");
    assert!(first.contains(raw) && second.contains(raw));
    assert!(!first.contains("__ryo_verbatim_expr_"));
    assert!(!second.contains("__ryo_verbatim_expr_"));
    // The two outputs should be byte-identical: a leaky registry
    // would cause the second run to use idx=1 instead of idx=0,
    // shifting the stub identifier (which would never be found,
    // and a stub would leak — already covered above) or simply
    // producing a different formatted form.
    assert_eq!(
        first, second,
        "successive to_source calls should produce identical output"
    );
}