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
//! Pure AST types - Span-free, thread-safe.
//!
//! All types support optional serde serialization via the `serde` feature.

use std::sync::Arc;

/// A complete Rust source file (pure, no spans).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureFile {
    /// Attributes on the file (e.g., `#![allow(...)]`).
    pub attrs: Vec<PureAttribute>,
    /// Items in the file.
    pub items: Vec<PureItem>,
}

// SAFETY: PureFile contains no raw pointers or non-Send types
unsafe impl Send for PureFile {}
unsafe impl Sync for PureFile {}

impl PureFile {
    /// Create a new empty file.
    pub fn new() -> Self {
        Self {
            attrs: Vec::new(),
            items: Vec::new(),
        }
    }

    /// Get all functions.
    pub fn functions(&self) -> Vec<&PureFn> {
        self.items
            .iter()
            .filter_map(|item| {
                if let PureItem::Fn(f) = item {
                    Some(f)
                } else {
                    None
                }
            })
            .collect()
    }

    /// Get all structs.
    pub fn structs(&self) -> Vec<&PureStruct> {
        self.items
            .iter()
            .filter_map(|item| {
                if let PureItem::Struct(s) = item {
                    Some(s)
                } else {
                    None
                }
            })
            .collect()
    }

    /// Get all use statements.
    pub fn uses(&self) -> Vec<&PureUse> {
        self.items
            .iter()
            .filter_map(|item| {
                if let PureItem::Use(u) = item {
                    Some(u)
                } else {
                    None
                }
            })
            .collect()
    }

    /// Find a function by name.
    pub fn find_fn(&self, name: &str) -> Option<&PureFn> {
        self.functions().into_iter().find(|f| f.name == name)
    }

    /// Get all traits.
    pub fn traits(&self) -> Vec<&PureTrait> {
        self.items
            .iter()
            .filter_map(|item| {
                if let PureItem::Trait(t) = item {
                    Some(t)
                } else {
                    None
                }
            })
            .collect()
    }

    /// Get all impl blocks.
    pub fn impls(&self) -> Vec<&PureImpl> {
        self.items
            .iter()
            .filter_map(|item| {
                if let PureItem::Impl(i) = item {
                    Some(i)
                } else {
                    None
                }
            })
            .collect()
    }

    /// Wrap in Arc for thread-safe sharing.
    pub fn into_arc(self) -> Arc<Self> {
        Arc::new(self)
    }
}

impl Default for PureFile {
    fn default() -> Self {
        Self::new()
    }
}

/// An item in a file or module.
///
/// # Future: PureAnyItem
///
/// If unified handling across PureItem, PureImplItem, and PureTraitItem
/// is needed, consider adding a `PureAnyItem` enum that wraps all item types.
/// This would be separate from PureItem to maintain context-specific type safety.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PureItem {
    /// Use statement.
    Use(PureUse),
    /// Function definition.
    Fn(PureFn),
    /// Struct definition.
    Struct(PureStruct),
    /// Enum definition.
    Enum(PureEnum),
    /// Impl block.
    Impl(PureImpl),
    /// Const item.
    Const(PureConst),
    /// Static item.
    Static(PureStatic),
    /// Type alias.
    Type(PureTypeAlias),
    /// Module.
    Mod(PureMod),
    /// Trait definition.
    Trait(PureTrait),
    /// Macro invocation.
    Macro(PureMacro),
    /// Other/unsupported item (stored as string, **parsed and re-emitted via
    /// `syn::parse_str`** — trivia like `//` line comments and blank lines is
    /// lost in the round-trip).
    Other(String),
    /// Verbatim Rust source bytes that must survive round-trip exactly as
    /// authored. Unlike `Other`, the contents are **never** parsed: a
    /// sentinel stub is emitted into the syn::File so prettyplease can lay
    /// out neighbouring items, and `PureFile::to_source` splices the raw
    /// bytes back over the stub afterwards. This is the structural escape
    /// hatch for the β path (RyoLang subset + ReplaceCode) and is the only
    /// way to preserve DSL macro spacing, `//` comments, blank lines, and
    /// other lexer-stripped trivia through ryo's codegen pipeline.
    Verbatim(String),
}

/// The meta content of an attribute.
///
/// Follows the structure of `syn::Meta`:
/// - `Path`: Simple path attribute like `#[test]`
/// - `List`: List attribute like `#[derive(Debug, Clone)]`
/// - `NameValue`: Name-value attribute like `#[doc = "comment"]`
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PureAttrMeta {
    /// Path only (e.g., `#[test]`, `#[inline]`)
    Path,
    /// List with arguments (e.g., `#[derive(Debug, Clone)]` → args = "Debug, Clone")
    List(String),
    /// Name-value pair (e.g., `#[doc = "comment"]` → value = "\"comment\"")
    NameValue(String),
}

/// An attribute (e.g., `#[derive(Debug)]`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureAttribute {
    /// The attribute path (e.g., "derive", "cfg").
    pub path: String,
    /// The meta content.
    pub meta: PureAttrMeta,
    /// Is this an inner attribute (`#![...]`)?
    pub is_inner: bool,
}

/// A use statement.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureUse {
    /// Visibility.
    pub vis: PureVis,
    /// The use tree.
    pub tree: PureUseTree,
}

/// A use tree.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PureUseTree {
    /// Simple path: `use std::io;`
    Path {
        /// Path segment (e.g. `std`).
        path: String,
        /// Continuation of the use tree after this segment.
        tree: Box<PureUseTree>,
    },
    /// Name: `use std::io;` (the `io` part)
    Name(String),
    /// Rename: `use std::io as stdio;`
    Rename {
        /// Original name (`io`).
        name: String,
        /// Alias (`stdio`).
        rename: String,
    },
    /// Glob: `use std::io::*;`
    Glob,
    /// Group: `use std::{io, fs};`
    Group(Vec<PureUseTree>),
}

/// Visibility.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PureVis {
    /// Private (default).
    #[default]
    Private,
    /// `pub`
    Public,
    /// `pub(crate)`
    Crate,
    /// `pub(super)`
    Super,
    /// `pub(in path)`
    In(String),
}

/// A function definition.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureFn {
    /// Attributes.
    pub attrs: Vec<PureAttribute>,
    /// Visibility.
    pub vis: PureVis,
    /// Is async (explicit `async fn`)?
    pub is_async: bool,
    /// Is async inferred from return type (`Pin<Box<dyn Future<...>>>`)?
    /// This is typically set when `#[async_trait]` or similar macros are used.
    #[cfg_attr(feature = "serde", serde(default))]
    pub is_async_inferred: bool,
    /// Is const?
    pub is_const: bool,
    /// Is unsafe?
    pub is_unsafe: bool,
    /// ABI (e.g., `"C"`, `"Rust"`, `"system"`). None means default Rust ABI.
    #[cfg_attr(feature = "serde", serde(default))]
    pub abi: Option<String>,
    /// Function name.
    pub name: String,
    /// Generic parameters.
    pub generics: PureGenerics,
    /// Parameters.
    pub params: Vec<PureParam>,
    /// Return type (None = unit).
    pub ret: Option<PureType>,
    /// Function body.
    pub body: PureBlock,
}

impl PureFn {
    /// Returns true if the function is async (either explicit or inferred).
    ///
    /// This includes:
    /// - Explicit `async fn` declarations
    /// - Functions with `Pin<Box<dyn Future<...>>>` return type (e.g., from `#[async_trait]`)
    pub fn is_effectively_async(&self) -> bool {
        self.is_async || self.is_async_inferred
    }
}

/// Function parameter.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PureParam {
    /// `self`
    SelfValue {
        /// `&self` / `&mut self` (i.e. taken by reference).
        is_ref: bool,
        /// `mut self` / `&mut self`.
        is_mut: bool,
    },
    /// Named parameter.
    Typed {
        /// Parameter binding name.
        name: String,
        /// Parameter type.
        ty: PureType,
        /// `mut` binding qualifier (e.g. `fn f(mut x: T)`).
        ///
        /// Must be preserved across roundtrip; losing it produces E0596
        /// "cannot borrow as mutable" the next time the executor re-renders
        /// the file, because every mutating use of `x` loses its backing
        /// mutability.
        is_mut: bool,
        /// Original parameter pattern, when the source used something
        /// richer than a bare identifier — e.g.
        /// `fn execute_group(SpecGroup { x, .. }: SpecGroup)` or
        /// `fn tuple((a, b): (u32, u32))`.
        ///
        /// `None` for the common `Pat::Ident` case (the binding name in
        /// `name` is sufficient to re-emit). `Some` instructs `to_syn`
        /// to render the original pattern verbatim instead of
        /// synthesising a `Pat::Ident { name }`, which would parse as
        /// `Pat::Path` (and the cargo "patterns aren't allowed in
        /// functions without bodies" error) whenever the lossy
        /// `pat_to_name` collapse produced an uppercase-leading binding
        /// like `SpecGroup`. Retires the defensive RL061 detect filter
        /// added in `f196d30d`.
        pat: Option<PurePattern>,
    },
}

/// Closure parameter with optional type annotation.
///
/// Unlike function parameters (`PureParam`), closure parameters:
/// - Use patterns (destructuring, wildcards, etc.) not just names
/// - Type annotations are optional (often inferred)
///
/// # Examples
/// - `|x|` → `PureClosureParam { pattern: Ident("x"), ty: None }`
/// - `|x: Foo|` → `PureClosureParam { pattern: Ident("x"), ty: Some(Path("Foo")) }`
/// - `|(a, b): (Foo, Bar)|` → `PureClosureParam { pattern: Tuple(..), ty: Some(Tuple(..)) }`
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureClosureParam {
    /// The parameter pattern.
    pub pattern: PurePattern,
    /// Optional type annotation.
    pub ty: Option<PureType>,
}

impl PureClosureParam {
    /// Create an untyped closure parameter (type will be inferred).
    pub fn untyped(pattern: PurePattern) -> Self {
        Self { pattern, ty: None }
    }

    /// Create a typed closure parameter.
    pub fn typed(pattern: PurePattern, ty: PureType) -> Self {
        Self {
            pattern,
            ty: Some(ty),
        }
    }
}

/// A block of statements.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureBlock {
    /// Statements in the block.
    pub stmts: Vec<PureStmt>,
}

impl PureBlock {
    /// Get statement at index.
    #[inline]
    pub fn get_stmt(&self, index: usize) -> Option<&PureStmt> {
        self.stmts.get(index)
    }

    /// Get mutable statement at index.
    #[inline]
    pub fn get_stmt_mut(&mut self, index: usize) -> Option<&mut PureStmt> {
        self.stmts.get_mut(index)
    }

    /// Number of statements.
    #[inline]
    pub fn len(&self) -> usize {
        self.stmts.len()
    }

    /// Is block empty?
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.stmts.is_empty()
    }
}

/// A statement.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PureStmt {
    /// Local variable: `let x = 1;` or `let Some(x) = opt else { ... };` (let-else).
    Local {
        /// Binding pattern (LHS of `let`).
        pattern: PurePattern,
        /// Optional explicit type annotation.
        ty: Option<PureType>,
        /// Optional initializer expression.
        init: Option<PureExpr>,
        /// Optional diverging else-block for let-else (`else { <block> }`).
        ///
        /// Corresponds to `syn::LocalInit::diverge`. Must be present when the
        /// pattern is refutable; losing this field causes E0005 at compile time.
        else_branch: Option<Box<PureExpr>>,
    },
    /// Expression with semicolon.
    Semi(PureExpr),
    /// Expression without semicolon (tail expression).
    Expr(PureExpr),
    /// Item statement (function inside function, etc.).
    Item(Box<PureItem>),
    /// Verbatim raw bytes that must survive `PureFile::to_source` exactly
    /// as authored. Same staging mechanism as `PureExpr::Verbatim` but at
    /// the statement level: lowered to a unique sentinel
    /// `__ryo_verbatim_stmt_<N>;` expression-statement stub, then the
    /// post-prettyplease splice step replaces the **entire line**
    /// containing that identifier with the raw bytes (matching the
    /// item-level splice semantics, because a Stmt occupies its own
    /// line in prettyplease output). Used for raw `let x = ...;`,
    /// macro invocation stmts (`tracing::info!(...);`), and other
    /// shapes where the entire stmt — not just the contained expr —
    /// must carry user trivia (B-3-cont).
    Verbatim(String),
}

impl PureStmt {
    /// Get the expression contained in this statement.
    ///
    /// Returns `Some` for `Local` (init expr), `Semi`, and `Expr` variants.
    /// Returns `None` for `Item` or if `Local` has no initializer.
    pub fn get_expr(&self) -> Option<&PureExpr> {
        match self {
            PureStmt::Local { init, .. } => init.as_ref(),
            PureStmt::Semi(e) | PureStmt::Expr(e) => Some(e),
            PureStmt::Item(_) | PureStmt::Verbatim(_) => None,
        }
    }

    /// Get mutable expression contained in this statement.
    pub fn get_expr_mut(&mut self) -> Option<&mut PureExpr> {
        match self {
            PureStmt::Local { init, .. } => init.as_mut(),
            PureStmt::Semi(e) | PureStmt::Expr(e) => Some(e),
            PureStmt::Item(_) | PureStmt::Verbatim(_) => None,
        }
    }

    /// Check if this statement contains an expression.
    pub fn has_expr(&self) -> bool {
        match self {
            PureStmt::Local { init, .. } => init.is_some(),
            PureStmt::Semi(_) | PureStmt::Expr(_) => true,
            PureStmt::Item(_) | PureStmt::Verbatim(_) => false,
        }
    }
}

/// A pattern.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PurePattern {
    /// Identifier: `x`, `mut x`, `ref x`, `ref mut x`
    Ident {
        /// Binding name.
        name: String,
        /// `mut` qualifier.
        is_mut: bool,
        /// `ref` binding mode.
        by_ref: bool,
    },
    /// Wildcard: `_`
    Wild,
    /// Tuple: `(a, b)`
    Tuple(Vec<PurePattern>),
    /// Struct: `Point { x, y }` or `Point { x, .. }`
    Struct {
        /// Struct path (e.g. `Point`).
        path: String,
        /// Field bindings (name, sub-pattern).
        fields: Vec<(String, PurePattern)>,
        /// Whether the pattern has a rest (`..`) at the end
        rest: bool,
    },
    /// Reference: `&x`, `&mut x`
    Ref {
        /// `mut` qualifier (`&mut`).
        is_mut: bool,
        /// Inner pattern after `&` / `&mut`.
        pattern: Box<PurePattern>,
    },
    /// Literal (for matching).
    Lit(String),
    /// Or pattern: `A | B`
    Or(Vec<PurePattern>),
    /// Path pattern: `Some`, `None`, `Enum::Variant`
    Path(String),
    /// Range pattern: `1..=5`, `'a'..='z'`
    Range {
        /// Start literal (None = unbounded below).
        start: Option<String>,
        /// End literal (None = unbounded above).
        end: Option<String>,
        /// `..=` (inclusive) vs `..` (exclusive).
        inclusive: bool,
    },
    /// Slice pattern: `[a, b, ..]`
    Slice(Vec<PurePattern>),
    /// Rest pattern: `..`
    Rest,
    /// Other (as string) - unsupported patterns with error guidance.
    Other(String),
}

/// An expression.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PureExpr {
    /// Literal: `1`, `"hello"`, `true`
    Lit(String),
    /// Path: `x`, `std::io::stdin`
    Path(String),
    /// Binary operation: `a + b`
    Binary {
        /// Operator token (e.g. `+`, `==`).
        op: String,
        /// Left operand.
        left: Box<PureExpr>,
        /// Right operand.
        right: Box<PureExpr>,
    },
    /// Unary operation: `-x`, `!x`, `*x`, `&x`
    Unary {
        /// Operator token (`-` / `!` / `*` / `&`).
        op: String,
        /// Operand expression.
        expr: Box<PureExpr>,
    },
    /// Function call: `foo(a, b)`
    Call {
        /// Callee expression.
        func: Box<PureExpr>,
        /// Argument expressions.
        args: Vec<PureExpr>,
    },
    /// Method call: `x.foo(a, b)` or `x.foo::<T>(a, b)`
    MethodCall {
        /// Receiver expression (LHS of `.`).
        receiver: Box<PureExpr>,
        /// Method name.
        method: String,
        /// Turbofish type arguments: `::<T, U>` → `"< T , U >"`
        turbofish: Option<String>,
        /// Argument expressions.
        args: Vec<PureExpr>,
    },
    /// Field access: `x.field`
    Field {
        /// Base expression.
        expr: Box<PureExpr>,
        /// Field name (or tuple index as string).
        field: String,
    },
    /// Index: `x[i]`
    Index {
        /// Base expression (`x`).
        expr: Box<PureExpr>,
        /// Index expression (`i`).
        index: Box<PureExpr>,
    },
    /// Block: `{ ... }` or `'label: { ... }`
    Block {
        /// Optional label (e.g., `'block`)
        label: Option<String>,
        /// Inner block.
        block: PureBlock,
    },
    /// If: `if cond { ... } else { ... }`
    If {
        /// Condition expression.
        cond: Box<PureExpr>,
        /// `then` branch block.
        then_branch: PureBlock,
        /// Optional `else` branch (another expression).
        else_branch: Option<Box<PureExpr>>,
    },
    /// Match: `match x { ... }`
    Match {
        /// Scrutinee expression.
        expr: Box<PureExpr>,
        /// Match arms.
        arms: Vec<PureMatchArm>,
    },
    /// Loop: `loop { ... }` or `'label: loop { ... }`
    Loop {
        /// Optional label (e.g., `'outer`)
        label: Option<String>,
        /// Loop body block.
        body: PureBlock,
    },
    /// While: `while cond { ... }` or `'label: while cond { ... }`
    While {
        /// Optional label (e.g., `'outer`)
        label: Option<String>,
        /// Loop condition.
        cond: Box<PureExpr>,
        /// Loop body block.
        body: PureBlock,
    },
    /// For: `for pat in expr { ... }` or `'label: for pat in expr { ... }`
    For {
        /// Optional label (e.g., `'outer`)
        label: Option<String>,
        /// Iteration binding pattern.
        pat: PurePattern,
        /// Iterator expression.
        expr: Box<PureExpr>,
        /// Loop body block.
        body: PureBlock,
    },
    /// Return: `return x`
    Return(Option<Box<PureExpr>>),
    /// Break: `break x` or `break 'label x`
    Break {
        /// Optional label to break to (e.g., `'outer`)
        label: Option<String>,
        /// Optional value carried out of the loop.
        expr: Option<Box<PureExpr>>,
    },
    /// Continue: `continue` or `continue 'label`
    Continue {
        /// Optional label to continue to (e.g., `'outer`)
        label: Option<String>,
    },
    /// Closure: `|x| x + 1`, `|x: Foo| -> Bar { x }`, `move |x| x`
    Closure {
        /// Is async closure?
        is_async: bool,
        /// Is move closure?
        is_move: bool,
        /// Parameters with optional type annotations.
        params: Vec<PureClosureParam>,
        /// Optional return type annotation.
        ret: Option<PureType>,
        /// Closure body expression.
        body: Box<PureExpr>,
    },
    /// Struct literal: `Point { x: 1, y: 2 }` or with functional update `Foo { a: 1, ..Default::default() }`
    Struct {
        /// Struct path (e.g. `Point`).
        path: String,
        /// Field initializers (name, expr).
        fields: Vec<(String, PureExpr)>,
        /// Functional update base expression (`..expr`). `None` means no update.
        rest: Option<Box<PureExpr>>,
    },
    /// Tuple: `(a, b, c)`
    Tuple(Vec<PureExpr>),
    /// Array: `[1, 2, 3]`
    Array(Vec<PureExpr>),
    /// Reference: `&x`, `&mut x`
    Ref {
        /// `mut` qualifier (`&mut`).
        is_mut: bool,
        /// Referent expression.
        expr: Box<PureExpr>,
    },
    /// Macro invocation: `println!(...)`
    Macro {
        /// Macro name (without `!`).
        name: String,
        /// Delimiter style around tokens.
        delimiter: MacroDelimiter,
        /// Raw token stream as a string.
        tokens: String,
    },
    /// Await: `x.await`
    Await(Box<PureExpr>),
    /// Try: `x?`
    Try(Box<PureExpr>),
    /// Range: `a..b`, `..b`, `a..`, `..`, `a..=b`
    Range {
        /// Start bound expression (None = unbounded).
        start: Option<Box<PureExpr>>,
        /// End bound expression (None = unbounded).
        end: Option<Box<PureExpr>>,
        /// true for `..=`, false for `..`
        inclusive: bool,
    },
    /// Cast: `x as T`
    Cast {
        /// Source expression.
        expr: Box<PureExpr>,
        /// Target type.
        ty: PureType,
    },
    /// Let expression (in conditions): `let Some(x) = y`
    Let {
        /// Pattern on the LHS of `let`.
        pattern: PurePattern,
        /// Scrutinee expression on the RHS.
        expr: Box<PureExpr>,
    },
    /// Async block: `async { ... }` or `async move { ... }`
    Async {
        /// `move` qualifier.
        is_move: bool,
        /// Async block body.
        body: PureBlock,
    },
    /// Unsafe block: `unsafe { ... }`
    Unsafe(PureBlock),
    /// Array repeat: `[expr; N]`
    Repeat {
        /// Element expression to repeat.
        expr: Box<PureExpr>,
        /// Repeat count expression.
        len: Box<PureExpr>,
    },
    /// Other (as string).
    Other(String),
    /// Verbatim Rust source bytes that must survive round-trip exactly as
    /// authored. Like `PureItem::Verbatim` but at the expression level:
    /// during `PureFile::to_source` the expression is lowered to a
    /// unique sentinel path stub (`__ryo_verbatim_expr_<N>`) that
    /// prettyplease emits unchanged, then the post-process splice
    /// step replaces that exact identifier with the raw bytes. This
    /// is the carrier for B-3 (expr-level Verbatim) — see journal
    /// 2026-05-30 §B-3.
    Verbatim(String),
}

impl PureExpr {
    /// Create a MethodCall with default turbofish (None)
    pub fn method_call(receiver: Box<PureExpr>, method: String, args: Vec<PureExpr>) -> Self {
        PureExpr::MethodCall {
            receiver,
            method,
            turbofish: None,
            args,
        }
    }

    /// Create a Closure with untyped params and no return type annotation.
    pub fn closure(params: Vec<PureClosureParam>, body: Box<PureExpr>) -> Self {
        PureExpr::Closure {
            is_async: false,
            is_move: false,
            params,
            ret: None,
            body,
        }
    }

    // ========== AST Navigation ==========

    /// Get child expression at index.
    ///
    /// Index mapping varies by variant:
    /// - `Binary`: 0=left, 1=right
    /// - `Unary`, `Field`, `Ref`, `Await`, `Try`, `Cast`, `Let`: 0=expr
    /// - `Call`: 0=func, 1..=args
    /// - `MethodCall`: 0=receiver, 1..=args
    /// - `Index`, `Repeat`: 0=expr, 1=index/len
    /// - `Range`: 0=start, 1=end (if present)
    /// - `If`: 0=cond, 1=else_branch (if present)
    /// - `While`, `For`: 0=cond/expr
    /// - `Match`: 0=expr
    /// - `Return`, `Break`: 0=inner (if present)
    /// - `Closure`: 0=body
    /// - `Tuple`, `Array`: 0..n=elements
    /// - `Struct`: 0..n=field values
    /// - Others: None
    pub fn get_child(&self, index: usize) -> Option<&PureExpr> {
        match self {
            // Single child at index 0
            PureExpr::Unary { expr, .. }
            | PureExpr::Field { expr, .. }
            | PureExpr::Ref { expr, .. }
            | PureExpr::Await(expr)
            | PureExpr::Try(expr)
            | PureExpr::Cast { expr, .. }
            | PureExpr::Let { expr, .. } => {
                if index == 0 {
                    Some(expr)
                } else {
                    None
                }
            }

            // Two children
            PureExpr::Binary { left, right, .. } => match index {
                0 => Some(left),
                1 => Some(right),
                _ => None,
            },
            PureExpr::Index { expr, index: idx } => match index {
                0 => Some(expr),
                1 => Some(idx),
                _ => None,
            },
            PureExpr::Repeat { expr, len } => match index {
                0 => Some(expr),
                1 => Some(len),
                _ => None,
            },

            // func/receiver + args
            PureExpr::Call { func, args } => {
                if index == 0 {
                    Some(func)
                } else {
                    args.get(index - 1)
                }
            }
            PureExpr::MethodCall { receiver, args, .. } => {
                if index == 0 {
                    Some(receiver)
                } else {
                    args.get(index - 1)
                }
            }

            // Optional children
            PureExpr::Range { start, end, .. } => match index {
                0 => start.as_deref(),
                1 => end.as_deref(),
                _ => None,
            },
            PureExpr::If {
                cond, else_branch, ..
            } => match index {
                0 => Some(cond),
                1 => else_branch.as_deref(),
                _ => None,
            },
            PureExpr::Return(opt) => {
                if index == 0 {
                    opt.as_deref()
                } else {
                    None
                }
            }
            PureExpr::Break { expr: opt, .. } => {
                if index == 0 {
                    opt.as_deref()
                } else {
                    None
                }
            }

            // Control flow with expr
            PureExpr::While { cond, .. } => {
                if index == 0 {
                    Some(cond)
                } else {
                    None
                }
            }
            PureExpr::For { expr, .. } => {
                if index == 0 {
                    Some(expr)
                } else {
                    None
                }
            }
            PureExpr::Match { expr, .. } => {
                if index == 0 {
                    Some(expr)
                } else {
                    None
                }
            }

            // Closure body
            PureExpr::Closure { body, .. } => {
                if index == 0 {
                    Some(body)
                } else {
                    None
                }
            }

            // Collections
            PureExpr::Tuple(exprs) | PureExpr::Array(exprs) => exprs.get(index),
            PureExpr::Struct { fields, .. } => fields.get(index).map(|(_, e)| e),

            // No direct children (use get_block for Block, Loop, Async, Unsafe)
            PureExpr::Lit(_)
            | PureExpr::Path(_)
            | PureExpr::Block { .. }
            | PureExpr::Loop { .. }
            | PureExpr::Async { .. }
            | PureExpr::Unsafe(_)
            | PureExpr::Continue { .. }
            | PureExpr::Macro { .. }
            | PureExpr::Other(_)
            | PureExpr::Verbatim(_) => None,
        }
    }

    /// Get mutable child expression at index.
    pub fn get_child_mut(&mut self, index: usize) -> Option<&mut PureExpr> {
        match self {
            PureExpr::Unary { expr, .. }
            | PureExpr::Field { expr, .. }
            | PureExpr::Ref { expr, .. }
            | PureExpr::Await(expr)
            | PureExpr::Try(expr)
            | PureExpr::Cast { expr, .. }
            | PureExpr::Let { expr, .. } => {
                if index == 0 {
                    Some(expr)
                } else {
                    None
                }
            }

            PureExpr::Binary { left, right, .. } => match index {
                0 => Some(left),
                1 => Some(right),
                _ => None,
            },
            PureExpr::Index { expr, index: idx } => match index {
                0 => Some(expr),
                1 => Some(idx),
                _ => None,
            },
            PureExpr::Repeat { expr, len } => match index {
                0 => Some(expr),
                1 => Some(len),
                _ => None,
            },

            PureExpr::Call { func, args } => {
                if index == 0 {
                    Some(func)
                } else {
                    args.get_mut(index - 1)
                }
            }
            PureExpr::MethodCall { receiver, args, .. } => {
                if index == 0 {
                    Some(receiver)
                } else {
                    args.get_mut(index - 1)
                }
            }

            PureExpr::Range { start, end, .. } => match index {
                0 => start.as_deref_mut(),
                1 => end.as_deref_mut(),
                _ => None,
            },
            PureExpr::If {
                cond, else_branch, ..
            } => match index {
                0 => Some(cond.as_mut()),
                1 => else_branch.as_deref_mut(),
                _ => None,
            },
            PureExpr::Return(opt) => {
                if index == 0 {
                    opt.as_deref_mut()
                } else {
                    None
                }
            }
            PureExpr::Break { expr: opt, .. } => {
                if index == 0 {
                    opt.as_deref_mut()
                } else {
                    None
                }
            }

            PureExpr::While { cond, .. } => {
                if index == 0 {
                    Some(cond)
                } else {
                    None
                }
            }
            PureExpr::For { expr, .. } => {
                if index == 0 {
                    Some(expr)
                } else {
                    None
                }
            }
            PureExpr::Match { expr, .. } => {
                if index == 0 {
                    Some(expr)
                } else {
                    None
                }
            }

            PureExpr::Closure { body, .. } => {
                if index == 0 {
                    Some(body)
                } else {
                    None
                }
            }

            PureExpr::Tuple(exprs) | PureExpr::Array(exprs) => exprs.get_mut(index),
            PureExpr::Struct { fields, .. } => fields.get_mut(index).map(|(_, e)| e),

            PureExpr::Lit(_)
            | PureExpr::Path(_)
            | PureExpr::Block { .. }
            | PureExpr::Loop { .. }
            | PureExpr::Async { .. }
            | PureExpr::Unsafe(_)
            | PureExpr::Continue { .. }
            | PureExpr::Macro { .. }
            | PureExpr::Other(_)
            | PureExpr::Verbatim(_) => None,
        }
    }

    /// Get the contained block (for Block, Loop, Async, Unsafe, If, While, For).
    pub fn get_block(&self) -> Option<&PureBlock> {
        match self {
            PureExpr::Block { block: b, .. }
            | PureExpr::Loop { body: b, .. }
            | PureExpr::Unsafe(b) => Some(b),
            PureExpr::Async { body, .. } => Some(body),
            PureExpr::If { then_branch, .. } => Some(then_branch),
            PureExpr::While { body, .. } | PureExpr::For { body, .. } => Some(body),
            _ => None,
        }
    }

    /// Get mutable contained block.
    pub fn get_block_mut(&mut self) -> Option<&mut PureBlock> {
        match self {
            PureExpr::Block { block: b, .. }
            | PureExpr::Loop { body: b, .. }
            | PureExpr::Unsafe(b) => Some(b),
            PureExpr::Async { body, .. } => Some(body),
            PureExpr::If { then_branch, .. } => Some(then_branch),
            PureExpr::While { body, .. } | PureExpr::For { body, .. } => Some(body),
            _ => None,
        }
    }

    /// Number of direct child expressions.
    pub fn child_count(&self) -> usize {
        match self {
            PureExpr::Lit(_)
            | PureExpr::Path(_)
            | PureExpr::Continue { .. }
            | PureExpr::Macro { .. }
            | PureExpr::Other(_)
            | PureExpr::Verbatim(_)
            | PureExpr::Block { .. }
            | PureExpr::Loop { .. }
            | PureExpr::Async { .. }
            | PureExpr::Unsafe(_) => 0,

            PureExpr::Unary { .. }
            | PureExpr::Field { .. }
            | PureExpr::Ref { .. }
            | PureExpr::Await(_)
            | PureExpr::Try(_)
            | PureExpr::Cast { .. }
            | PureExpr::Let { .. }
            | PureExpr::Closure { .. }
            | PureExpr::While { .. }
            | PureExpr::For { .. }
            | PureExpr::Match { .. } => 1,

            PureExpr::Binary { .. } | PureExpr::Index { .. } | PureExpr::Repeat { .. } => 2,

            PureExpr::Range { start, end, .. } => start.is_some() as usize + end.is_some() as usize,
            PureExpr::If { else_branch, .. } => 1 + else_branch.is_some() as usize,
            PureExpr::Return(opt) => opt.is_some() as usize,
            PureExpr::Break { expr: opt, .. } => opt.is_some() as usize,

            PureExpr::Call { args, .. } => 1 + args.len(),
            PureExpr::MethodCall { args, .. } => 1 + args.len(),
            PureExpr::Tuple(v) | PureExpr::Array(v) => v.len(),
            PureExpr::Struct { fields, .. } => fields.len(),
        }
    }

    /// Navigate to a nested expression by path (slice of indices).
    ///
    /// # Example
    /// ```ignore
    /// // For: x.foo(a + b, c)
    /// // Path [1, 0] navigates to: args[0].left = `a`
    /// expr.navigate(&[1, 0])
    /// ```
    pub fn navigate(&self, path: &[usize]) -> Option<&PureExpr> {
        let mut current = self;
        for &idx in path {
            current = current.get_child(idx)?;
        }
        Some(current)
    }

    /// Navigate to a nested expression mutably.
    pub fn navigate_mut(&mut self, path: &[usize]) -> Option<&mut PureExpr> {
        let mut current = self;
        for &idx in path {
            current = current.get_child_mut(idx)?;
        }
        Some(current)
    }
}

/// Match arm.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureMatchArm {
    /// Pattern.
    pub pattern: PurePattern,
    /// Guard: `if cond`
    pub guard: Option<PureExpr>,
    /// Body.
    pub body: PureExpr,
}

/// A type.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PureType {
    /// Path type: `String`, `std::io::Result<T>`
    Path(String),
    /// Reference: `&T`, `&mut T`, `&'a T`
    Ref {
        /// Optional explicit lifetime (`'a`).
        lifetime: Option<String>,
        /// `mut` qualifier (`&mut`).
        is_mut: bool,
        /// Referent type.
        ty: Box<PureType>,
    },
    /// Tuple: `(A, B, C)`
    Tuple(Vec<PureType>),
    /// Array: `[T; N]`
    Array {
        /// Element type.
        ty: Box<PureType>,
        /// Length expression as a raw string.
        len: String,
    },
    /// Slice: `[T]`
    Slice(Box<PureType>),
    /// Function pointer: `fn(A) -> B`
    Fn {
        /// Parameter types.
        params: Vec<PureType>,
        /// Optional return type (None = unit).
        ret: Option<Box<PureType>>,
    },
    /// Impl trait: `impl Trait`
    ImplTrait(Vec<String>),
    /// Dyn trait: `dyn Trait`
    TraitObject(Vec<String>),
    /// Inferred: `_`
    Infer,
    /// Never: `!`
    Never,
    /// Other (as string).
    Other(String),
}

/// Generic parameters.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureGenerics {
    /// Type parameters.
    pub params: Vec<PureGenericParam>,
    /// Where clause.
    pub where_clause: Vec<String>,
}

/// A generic parameter.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PureGenericParam {
    /// Type parameter: `T`, `T: Clone`
    Type {
        /// Parameter name (`T`).
        name: String,
        /// Trait bounds (`Clone + Send`).
        bounds: Vec<String>,
    },
    /// Lifetime: `'a`, `'a: 'b`
    Lifetime {
        /// Lifetime name (`'a`).
        name: String,
        /// Lifetime bounds (`'b`).
        bounds: Vec<String>,
    },
    /// Const: `const N: usize`
    Const {
        /// Const parameter name (`N`).
        name: String,
        /// Const parameter type as a raw string (`usize`).
        ty: String,
    },
}

/// A struct definition.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureStruct {
    /// Attributes.
    pub attrs: Vec<PureAttribute>,
    /// Visibility.
    pub vis: PureVis,
    /// Name.
    pub name: String,
    /// Generics.
    pub generics: PureGenerics,
    /// Fields.
    pub fields: PureFields,
}

/// Struct fields.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PureFields {
    /// Named fields: `{ x: i32, y: i32 }`
    Named(Vec<PureField>),
    /// Tuple fields: `(i32, i32)` — carried as [`PureTupleField`] so per-field
    /// `attrs` (e.g. `#[from]`) and `vis` survive AST round-trip.
    ///
    /// Pre-fix this variant carried `Vec<PureType>`, which silently dropped
    /// every `#[derive(thiserror::Error)] enum E { Foo(#[from] InnerErr) }`-
    /// style attribute and broke `?` operator conversions in regenerated
    /// files (see `test_roundtrip_tuple_variant_from_attribute`).
    Tuple(Vec<PureTupleField>),
    /// Unit struct: no fields.
    Unit,
}

/// A struct field.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureField {
    /// Attributes.
    pub attrs: Vec<PureAttribute>,
    /// Visibility.
    pub vis: PureVis,
    /// Name.
    pub name: String,
    /// Type.
    pub ty: PureType,
}

/// A tuple-style field (positional, no name).
///
/// Used by [`PureFields::Tuple`] for both tuple structs (`struct S(u32, u32)`)
/// and tuple enum variants (`enum E { V(#[from] Inner) }`). Keeps `attrs` and
/// `vis` alongside the field type so attributes such as `#[from]` and `#[serde(...)]`
/// survive the syn ↔ pure ↔ syn round-trip — critical for `?`-operator
/// `From` impl generation and for derive macros that inspect field-level
/// attributes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureTupleField {
    /// Attributes (outer `#[...]`).
    pub attrs: Vec<PureAttribute>,
    /// Visibility (mostly relevant for tuple structs; tuple variants are
    /// always public alongside their parent variant).
    pub vis: PureVis,
    /// Type.
    pub ty: PureType,
}

/// An enum definition.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureEnum {
    /// Attributes.
    pub attrs: Vec<PureAttribute>,
    /// Visibility.
    pub vis: PureVis,
    /// Name.
    pub name: String,
    /// Generics.
    pub generics: PureGenerics,
    /// Variants.
    pub variants: Vec<PureVariant>,
}

/// An enum variant.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureVariant {
    /// Attributes.
    pub attrs: Vec<PureAttribute>,
    /// Name.
    pub name: String,
    /// Fields.
    pub fields: PureFields,
    /// Discriminant: `= 1`
    pub discriminant: Option<String>,
}

/// An impl block.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureImpl {
    /// Attributes.
    pub attrs: Vec<PureAttribute>,
    /// Generics.
    pub generics: PureGenerics,
    /// Whether this is an unsafe impl.
    pub is_unsafe: bool,
    /// Trait being implemented (if any).
    pub trait_: Option<String>,
    /// Type being implemented for.
    pub self_ty: String,
    /// Items in the impl.
    pub items: Vec<PureImplItem>,
}

/// An item in an impl block.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PureImplItem {
    /// Method.
    Fn(PureFn),
    /// Const.
    Const(PureConst),
    /// Type alias.
    Type(PureTypeAlias),
    /// Other.
    Other(String),
}

/// A const item.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureConst {
    /// Attributes.
    pub attrs: Vec<PureAttribute>,
    /// Visibility.
    pub vis: PureVis,
    /// Name.
    pub name: String,
    /// Type.
    pub ty: PureType,
    /// Value expression (None for trait consts without default).
    pub value: Option<PureExpr>,
}

/// A static item.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureStatic {
    /// Attributes.
    pub attrs: Vec<PureAttribute>,
    /// Visibility.
    pub vis: PureVis,
    /// Is mutable?
    pub is_mut: bool,
    /// Name.
    pub name: String,
    /// Type.
    pub ty: PureType,
    /// Value expression.
    pub value: PureExpr,
}

/// A type alias.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureTypeAlias {
    /// Attributes.
    pub attrs: Vec<PureAttribute>,
    /// Visibility.
    pub vis: PureVis,
    /// Name.
    pub name: String,
    /// Generics.
    pub generics: PureGenerics,
    /// The aliased type.
    pub ty: PureType,
}

/// A module definition.
///
/// Contains all items belonging to this module.
/// File vs inline distinction is handled at the file system layer,
/// not in the AST representation.
///
/// The `scope` field is the sole source of truth for `#[cfg(test)]` semantics.
/// Downstream layers (store, regen, emitter) must consume `scope` directly and
/// must not re-derive Prod/Test scope by inspecting `attrs` or `items.is_empty()`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureMod {
    /// Attributes (both outer `#[...]` and inner `#![...]`).
    /// Use `PureAttribute::is_inner` to distinguish.
    pub attrs: Vec<PureAttribute>,
    /// Visibility.
    pub vis: PureVis,
    /// Module name.
    pub name: String,
    /// Module items.
    pub items: Vec<PureItem>,
    /// Prod/Test scope of this module.
    ///
    /// `ModScope::Test` means this module is gated by `#[cfg(test)]`.
    /// Set at parse time; must not be re-derived from `attrs` or `items` in
    /// any downstream layer.
    pub scope: ModScope,
}

/// A trait definition.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureTrait {
    /// Attributes.
    pub attrs: Vec<PureAttribute>,
    /// Visibility.
    pub vis: PureVis,
    /// Is unsafe?
    pub is_unsafe: bool,
    /// Is auto?
    pub is_auto: bool,
    /// Name.
    pub name: String,
    /// Generics.
    pub generics: PureGenerics,
    /// Supertraits.
    pub supertraits: Vec<String>,
    /// Items in the trait.
    pub items: Vec<PureTraitItem>,
}

/// An item in a trait.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PureTraitItem {
    /// Method (with optional default impl).
    Fn(PureFn),
    /// Const.
    Const(PureConst),
    /// Type.
    Type {
        /// Associated type name.
        name: String,
        /// Trait bounds on the associated type.
        bounds: Vec<String>,
        /// Optional default type.
        default: Option<PureType>,
    },
    /// Other.
    Other(String),
}

/// A macro invocation at item level.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PureMacro {
    /// Macro path.
    pub path: String,
    /// Optional definition name. Set for `macro_rules! NAME { ... }` — syn
    /// stores this on `ItemMacro.ident` rather than inside `mac.path`. For
    /// regular call-site macros (`println!`, `vec!`, `html!`) this is `None`.
    /// Without this field, `macro_rules! square { ... }` round-trips into
    /// nameless `macro_rules! { ... }`.
    #[cfg_attr(feature = "serde", serde(default))]
    pub name: Option<String>,
    /// Delimiter used.
    pub delimiter: MacroDelimiter,
    /// Tokens inside (as string).
    pub tokens: String,
}

/// Macro delimiter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum MacroDelimiter {
    /// `( ... )`
    Paren,
    /// `{ ... }`
    Brace,
    /// `[ ... ]`
    Bracket,
}

/// Prod/Test scope discriminant for `PureMod`.
///
/// 2-value enum. `#[cfg(test)]` 専用 SoT primitive.
///
/// `ModScope` is the sole source of truth for whether a module is test-scoped.
/// No downstream layer (store, regen, emitter) may re-derive Prod/Test scope by
/// inspecting raw attrs or `items.is_empty()`; each layer must consume this field
/// directly.
///
/// 非 binary cfg (`cfg(not(test))` / `cfg(feature="...")`) は ModScope::Prod に保持しつつ、
/// 元の cfg attribute は PureMod.attrs に残し透過 emit する。将来拡張需要が出た場合は
/// ModScope に variant を追加する設計に拡張可能。
///
/// `ryo_suggest::suggest::SymbolScope` (Lib/Bin/Test) とは意味論軸が直交
/// (AST primitive vs post-hoc classification)。統合は本 Issue scope 外。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ModScope {
    /// Production code: module is not gated by `#[cfg(test)]`.
    ///
    /// This is the default. Modules with non-binary cfg gates
    /// (`cfg(not(test))`, `cfg(feature="...")`) are also represented as `Prod`
    /// with the original cfg attribute preserved in `PureMod.attrs`.
    #[default]
    Prod,
    /// Test code: module is gated by `#[cfg(test)]`.
    ///
    /// The `#[cfg(test)]` attribute is removed from `PureMod.attrs` at parse
    /// time and re-injected by the emitter (`ToSyn for PureMod`).
    Test,
}

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

    #[test]
    fn test_pure_file_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<PureFile>();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_json_roundtrip() {
        let file = PureFile::from_source(
            r#"
            use std::io;

            fn hello(name: &str) -> String {
                format!("Hello, {}!", name)
            }

            struct Point {
                x: i32,
                y: i32,
            }
            "#,
        )
        .unwrap();

        // Serialize to JSON
        let json = serde_json::to_string_pretty(&file).unwrap();
        assert!(json.contains("hello"));
        assert!(json.contains("Point"));

        // Deserialize back
        let restored: PureFile = serde_json::from_str(&json).unwrap();
        assert_eq!(file, restored);
    }

    #[test]
    fn test_verbatim_item_preserves_raw_bytes() {
        // Boundary: PureItem::Verbatim(raw) must survive PureFile::to_source
        // intact — including `//` line comments, blank lines, DSL macro
        // spacing, and any other trivia that the syn lexer would normally
        // strip. This is the ReplaceCode escape hatch for the β route.
        let raw = "// preserved comment 1\nlet _ = html! { <div class=\"foo\">{ name }</div> };\n// preserved comment 2";
        let file = PureFile {
            attrs: vec![],
            items: vec![
                PureItem::Struct(PureStruct {
                    attrs: vec![],
                    vis: PureVis::Public,
                    name: "Foo".to_string(),
                    generics: PureGenerics::default(),
                    fields: PureFields::Unit,
                }),
                PureItem::Verbatim(raw.to_string()),
                PureItem::Struct(PureStruct {
                    attrs: vec![],
                    vis: PureVis::Public,
                    name: "Bar".to_string(),
                    generics: PureGenerics::default(),
                    fields: PureFields::Unit,
                }),
            ],
        };

        let out = file.to_source().unwrap();
        assert!(
            out.contains("// preserved comment 1"),
            "line comment 1 must survive verbatim splice; got:\n{}",
            out
        );
        assert!(
            out.contains("// preserved comment 2"),
            "line comment 2 must survive; got:\n{}",
            out
        );
        assert!(
            out.contains("<div class=\"foo\">"),
            "HTML-DSL token spacing inside the verbatim chunk must survive; \
             got:\n{}",
            out
        );
        assert!(
            !out.contains("__ryo_verbatim_"),
            "sentinel marker must not leak into the final output; got:\n{}",
            out
        );
        assert!(out.contains("struct Foo;") && out.contains("struct Bar;"));
    }

    #[test]
    fn test_macro_rules_name_round_trip() {
        // Boundary: `macro_rules! NAME { ... }` must round-trip with the NAME
        // preserved. Pre-fix `PureMacro` had no `name` field so the ident on
        // syn::ItemMacro was dropped, producing nameless `macro_rules! { ... }`
        // on regeneration.
        let pf =
            PureFile::from_source("macro_rules! square { ($x:expr) => { $x * $x }; }").unwrap();
        let out = pf.to_source().unwrap();
        assert!(
            out.contains("macro_rules! square"),
            "macro_rules ident must round-trip; got: {}",
            out
        );
    }

    #[test]
    fn test_regular_macro_call_no_name_field() {
        // Boundary: regular call-site macros (e.g. `println!`, `vec!`) do not
        // set `ItemMacro.ident` at item level — only `macro_rules!` does.
        // The `name` field stays None and is not emitted into the output.
        let pf = PureFile::from_source("lazy_static! { static ref X: i32 = 1; }").unwrap();
        let out = pf.to_source().unwrap();
        // The path "lazy_static" survives as the macro path; no spurious
        // ident insertion before the `{`.
        assert!(
            out.contains("lazy_static!"),
            "macro path must survive: {}",
            out
        );
        assert!(
            !out.contains("lazy_static! lazy_static"),
            "no duplicated ident: {}",
            out
        );
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_compact() {
        let file = PureFile::from_source("fn main() {}").unwrap();

        // Compact JSON
        let json = serde_json::to_string(&file).unwrap();

        // Should be relatively compact
        assert!(json.len() < 500);

        // Roundtrip
        let restored: PureFile = serde_json::from_str(&json).unwrap();
        assert_eq!(file, restored);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_complex_ast() {
        let file = PureFile::from_source(
            r#"
            pub struct Config<T: Clone> {
                pub name: String,
                pub value: T,
            }

            impl<T: Clone> Config<T> {
                pub fn new(name: String, value: T) -> Self {
                    Self { name, value }
                }
            }

            pub trait Configurable {
                fn config(&self) -> &str;
            }
            "#,
        )
        .unwrap();

        let json = serde_json::to_string(&file).unwrap();
        let restored: PureFile = serde_json::from_str(&json).unwrap();
        assert_eq!(file, restored);

        // Verify structure preserved
        assert_eq!(restored.structs().len(), 1);
        assert_eq!(restored.structs()[0].name, "Config");
    }

    // ========== Navigation Tests ==========

    #[test]
    fn test_pure_block_navigation() {
        let block = PureBlock {
            stmts: vec![
                PureStmt::Semi(PureExpr::Lit("1".into())),
                PureStmt::Semi(PureExpr::Lit("2".into())),
                PureStmt::Expr(PureExpr::Lit("3".into())),
            ],
        };

        assert_eq!(block.len(), 3);
        assert!(!block.is_empty());

        let stmt0 = block.get_stmt(0).unwrap();
        assert!(matches!(stmt0, PureStmt::Semi(PureExpr::Lit(s)) if s == "1"));

        let stmt2 = block.get_stmt(2).unwrap();
        assert!(matches!(stmt2, PureStmt::Expr(PureExpr::Lit(s)) if s == "3"));

        assert!(block.get_stmt(3).is_none());
    }

    #[test]
    fn test_pure_stmt_get_expr() {
        let semi = PureStmt::Semi(PureExpr::Lit("x".into()));
        assert!(semi.has_expr());
        assert!(matches!(semi.get_expr(), Some(PureExpr::Lit(_))));

        let local_with_init = PureStmt::Local {
            pattern: PurePattern::Ident {
                name: "x".into(),
                is_mut: false,
                by_ref: false,
            },
            ty: None,
            init: Some(PureExpr::Lit("42".into())),
            else_branch: None,
        };
        assert!(local_with_init.has_expr());
        assert!(matches!(local_with_init.get_expr(), Some(PureExpr::Lit(_))));

        let local_no_init = PureStmt::Local {
            pattern: PurePattern::Ident {
                name: "x".into(),
                is_mut: false,
                by_ref: false,
            },
            ty: None,
            init: None,
            else_branch: None,
        };
        assert!(!local_no_init.has_expr());
        assert!(local_no_init.get_expr().is_none());
    }

    #[test]
    fn test_pure_expr_get_child_binary() {
        // a + b
        let expr = PureExpr::Binary {
            op: "+".into(),
            left: Box::new(PureExpr::Path("a".into())),
            right: Box::new(PureExpr::Path("b".into())),
        };

        assert_eq!(expr.child_count(), 2);

        let left = expr.get_child(0).unwrap();
        assert!(matches!(left, PureExpr::Path(s) if s == "a"));

        let right = expr.get_child(1).unwrap();
        assert!(matches!(right, PureExpr::Path(s) if s == "b"));

        assert!(expr.get_child(2).is_none());
    }

    #[test]
    fn test_pure_expr_get_child_method_call() {
        // x.foo(a, b)
        let expr = PureExpr::MethodCall {
            receiver: Box::new(PureExpr::Path("x".into())),
            method: "foo".into(),
            turbofish: None,
            args: vec![PureExpr::Path("a".into()), PureExpr::Path("b".into())],
        };

        assert_eq!(expr.child_count(), 3); // receiver + 2 args

        let receiver = expr.get_child(0).unwrap();
        assert!(matches!(receiver, PureExpr::Path(s) if s == "x"));

        let arg0 = expr.get_child(1).unwrap();
        assert!(matches!(arg0, PureExpr::Path(s) if s == "a"));

        let arg1 = expr.get_child(2).unwrap();
        assert!(matches!(arg1, PureExpr::Path(s) if s == "b"));

        assert!(expr.get_child(3).is_none());
    }

    #[test]
    fn test_pure_expr_navigate() {
        // x.foo(a + b, c)
        let expr = PureExpr::MethodCall {
            receiver: Box::new(PureExpr::Path("x".into())),
            method: "foo".into(),
            turbofish: None,
            args: vec![
                PureExpr::Binary {
                    op: "+".into(),
                    left: Box::new(PureExpr::Path("a".into())),
                    right: Box::new(PureExpr::Path("b".into())),
                },
                PureExpr::Path("c".into()),
            ],
        };

        // Navigate to receiver
        let r = expr.navigate(&[0]).unwrap();
        assert!(matches!(r, PureExpr::Path(s) if s == "x"));

        // Navigate to first arg (a + b)
        let arg0 = expr.navigate(&[1]).unwrap();
        assert!(matches!(arg0, PureExpr::Binary { .. }));

        // Navigate to left of first arg (a)
        let a = expr.navigate(&[1, 0]).unwrap();
        assert!(matches!(a, PureExpr::Path(s) if s == "a"));

        // Navigate to right of first arg (b)
        let b = expr.navigate(&[1, 1]).unwrap();
        assert!(matches!(b, PureExpr::Path(s) if s == "b"));

        // Invalid path
        assert!(expr.navigate(&[1, 2]).is_none());
        assert!(expr.navigate(&[5]).is_none());
    }

    #[test]
    fn test_pure_expr_get_block() {
        let block_expr = PureExpr::Block {
            label: None,
            block: PureBlock {
                stmts: vec![PureStmt::Expr(PureExpr::Lit("1".into()))],
            },
        };
        assert!(block_expr.get_block().is_some());
        assert_eq!(block_expr.get_block().unwrap().len(), 1);

        let lit = PureExpr::Lit("x".into());
        assert!(lit.get_block().is_none());
    }
}