tabnas-parser 0.12.9

A dynamic JSON parser that isn't strict and can be customized.
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
// Copyright (c) 2013-2026 Richard Rodger, MIT License

use crate::token::{Tin, Token};
use crate::value::Value;
use crate::Lexer;
use crate::{ActionError, Context, ContextAction};
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use std::rc::Rc;
use std::sync::Arc;

/// Function-valued alternate condition. The candidate's matched tokens have
/// already been copied onto `rule` when this callback runs.
pub type AltCondition = Arc<dyn Fn(&mut Rule, &mut Context) -> bool + Send + Sync>;

/// Canonical condition shape, including the effective match record being
/// assembled for this candidate.
pub type AltConditionWithMatch =
    Arc<dyn Fn(&mut Rule, &mut Context, &mut AltMatch) -> bool + Send + Sync>;

/// Condition with access to the live lexer. This is the imperative form used
/// by plugins that perform controlled lookahead from a condition.
pub type AltConditionWithLexer =
    Arc<dyn for<'source> Fn(&mut Rule, &mut Context, &mut Lexer<'source>) -> bool + Send + Sync>;

/// Complete canonical condition shape: the live effective match plus access
/// to the lexer for bounded, plugin-controlled lookahead.
pub type AltConditionWithLexerAndMatch = Arc<
    dyn for<'source> Fn(&mut Rule, &mut Context, &mut AltMatch, &mut Lexer<'source>) -> bool
        + Send
        + Sync,
>;

/// Function-valued push/replace route.
pub type AltNext = Arc<dyn Fn(&mut Rule, &mut Context) -> Option<String> + Send + Sync>;
pub type AltNextWithMatch =
    Arc<dyn Fn(&mut Rule, &mut Context, &mut AltMatch) -> Option<String> + Send + Sync>;

/// Function-valued token backtrack count.
pub type AltBack = Arc<dyn Fn(&mut Rule, &mut Context) -> usize + Send + Sync>;
pub type AltBackWithMatch =
    Arc<dyn Fn(&mut Rule, &mut Context, &mut AltMatch) -> usize + Send + Sync>;

/// Function-valued alternate error. Returning a token rejects the alternate
/// at its match site and uses the token's `err`/`why` field as the error code.
pub type AltError = Arc<dyn Fn(&mut Rule, &mut Context) -> Option<Token> + Send + Sync>;
pub type AltErrorWithMatch =
    Arc<dyn Fn(&mut Rule, &mut Context, &mut AltMatch) -> Option<Token> + Send + Sync>;

/// Post-match alternate modifier. It takes and returns the effective match so
/// replacement is explicit rather than mutating shared grammar state.
pub type AltModifier = Arc<dyn Fn(AltSpec, &mut Rule, &mut Context) -> AltSpec + Send + Sync>;

/// Full canonical alternate modifier. `next` is the pre-routing next-rule
/// view (`Some(current)` during open, `None` during close). The returned
/// match is the one used for erroring, state mutation, action, and routing.
pub type AltModifierWithMatch =
    Arc<dyn Fn(AltMatch, &mut Rule, &mut Context, Option<&RuleSnapshot>) -> AltMatch + Send + Sync>;

/// Full canonical alternate action. A returned error token aborts the pass;
/// other returned tokens are ignored by the mature engine and should be
/// expressed as `None` here.
pub type AltAction = Arc<
    dyn Fn(&mut Rule, &mut Context, &mut AltMatch) -> Result<Option<Token>, ActionError>
        + Send
        + Sync,
>;

#[derive(Clone)]
pub enum AltActionBinding {
    Named(String),
    Context(ContextAction),
    Matched(AltAction),
}

/// One executable action in its exact declaration position. The mature
/// engines allow named function references and direct callbacks to be mixed;
/// retaining this sequence avoids losing prepend/append order while keeping
/// the serialized `a`/`bo`/`ao`/`bc`/`ac` lists available for inspection.
#[derive(Clone)]
pub enum ActionBinding {
    Named(String),
    Callback(ContextAction),
    State(StateAction),
}

/// Canonical rule lifecycle callback (`bo`/`ao`/`bc`/`ac`). `next` is the
/// rule selected for the following pass, or `None` for the no-rule sentinel;
/// `out` is the previous handler's token result in the same phase.
pub type StateAction = Arc<
    dyn Fn(
            &mut Rule,
            &mut Context,
            Option<&RuleSnapshot>,
            Option<Token>,
        ) -> Result<Option<Token>, ActionError>
        + Send
        + Sync,
>;

/// Effective result of matching one alternate. Dynamic error/routing/backtrack
/// callbacks are resolved into this record before the modifier runs, matching
/// TypeScript's `AltMatch` contract.
#[derive(Clone, Default)]
pub struct AltMatch {
    pub p: Option<String>,
    pub r: Option<String>,
    pub b: usize,
    pub n: HashMap<String, i32>,
    pub u: HashMap<String, Value>,
    pub k: HashMap<String, Value>,
    pub g: Vec<String>,
    /// The alternate's error token, boxed. A `Token` is 248 bytes and this
    /// record is moved twice per rule step, so carrying one inline made
    /// `AltMatch` 560 bytes of which 248 were an error almost no alternate
    /// raises. The box costs an allocation only on the error path, which
    /// is already the expensive one.
    pub e: Option<Box<Token>>,
    /// Canonical post-match modifier attached to the selected alternate.
    /// It remains visible to the modifier itself and later actions even
    /// though changing it after selection does not rerun the phase.
    pub h: Option<AltModifierWithMatch>,
    pub actions: Vec<AltActionBinding>,
    pub action_configs: HashMap<String, Value>,
}

impl AltMatch {
    /// Return the record to the state `AltMatch::default()` would give it,
    /// without giving up the buffers it has already allocated.
    ///
    /// The parse loop keeps one record for the whole parse and resets it at
    /// the head of each rule step, the shape TypeScript's `ctx._palt` has
    /// (ts/src/rules.ts): building a fresh 320-byte record twice per step
    /// and moving it twice more cost more than the nine fields are worth.
    /// Every field an earlier step or a rejected alternate can leave behind
    /// has to be cleared here -- a step can leave by the error path with
    /// `e`, `p`, `r`, `b` and `g` still set -- and the maps and vectors are
    /// cleared rather than replaced so the next step writes into the
    /// capacity the last one left.
    pub(crate) fn reset(&mut self) {
        self.p = None;
        self.r = None;
        self.b = 0;
        self.e = None;
        self.h = None;
        if !self.n.is_empty() {
            self.n.clear();
        }
        if !self.u.is_empty() {
            self.u.clear();
        }
        if !self.k.is_empty() {
            self.k.clear();
        }
        if !self.g.is_empty() {
            self.g.clear();
        }
        if !self.actions.is_empty() {
            self.actions.clear();
        }
        if !self.action_configs.is_empty() {
            self.action_configs.clear();
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuleState {
    Open,
    Close,
}

#[derive(Debug, Clone, PartialEq)]
pub struct RuleDoneAlt {
    pub b: usize,
    pub g: Vec<String>,
    pub p: String,
    pub r: String,
    pub err: Option<Token>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct RuleDone {
    /// Rule state before the completed pass.
    pub state: RuleState,
    /// `None` only when that state declared no alternatives.
    pub alt: Option<RuleDoneAlt>,
    /// True only for a close synthesized by recovery.
    pub forced: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompareOp {
    Eq,
    Ne,
    Lt,
    Lte,
    Gt,
    Gte,
    Exist,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Condition {
    pub path: Vec<String>,
    pub op: CompareOp,
    pub value: Value,
}

#[derive(Clone, Default)]
pub struct AltSpec {
    pub s: Vec<Vec<Tin>>,
    /// The token names each `s` slot was declared with, when the
    /// alternate came from a serialized grammar; empty for an alternate
    /// built from tins directly. A slot naming a token set (`#KEY`,
    /// `#VAL`, a custom set) is resolved again against the instance's
    /// options whenever the parser is rebuilt, so a set overridden after
    /// the alternate was installed still reaches it, as in TypeScript and
    /// Go (tabnas/parser#217).
    pub s_names: Vec<Vec<String>>,
    /// What `s_names` last resolved to, slot by slot. A slot whose `s`
    /// no longer equals this was set by hand after the alternate was
    /// installed, and that edit wins: the names are not applied over it.
    pub s_bound: Vec<Vec<Tin>>,
    pub p: Option<String>,
    pub p_fn: Option<AltNext>,
    pub p_match: Option<AltNextWithMatch>,
    pub r: Option<String>,
    pub r_fn: Option<AltNext>,
    pub r_match: Option<AltNextWithMatch>,
    pub b: usize,
    pub b_fn: Option<AltBack>,
    pub b_match: Option<AltBackWithMatch>,
    pub a: Vec<String>,
    /// Imperative actions installed directly by a native Rust plugin.
    /// Named actions in `a` remain the serialized grammar representation;
    /// `action_order` retains their exact interleaving with direct callbacks.
    pub action_fns: Vec<ContextAction>,
    pub action_order: Vec<AltActionBinding>,
    pub matched_action_fns: Vec<AltAction>,
    pub action_configs: HashMap<String, Value>,
    pub c: Vec<Condition>,
    pub c_ref: Option<String>,
    pub c_fn: Option<AltCondition>,
    pub c_match: Option<AltConditionWithMatch>,
    pub c_lex: Option<AltConditionWithLexer>,
    pub c_lex_match: Option<AltConditionWithLexerAndMatch>,
    pub n: HashMap<String, i32>,
    pub u: HashMap<String, Value>,
    pub k: HashMap<String, Value>,
    pub g: String,
    pub h: Option<AltModifier>,
    pub h_match: Option<AltModifierWithMatch>,
    pub e: Option<AltError>,
    pub e_match: Option<AltErrorWithMatch>,
}

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

#[derive(Clone)]
pub struct RuleSpec {
    pub name: String,
    pub open: Vec<AltSpec>,
    pub close: Vec<AltSpec>,
    pub bo: Vec<String>,
    pub ao: Vec<String>,
    pub bc: Vec<String>,
    pub ac: Vec<String>,
    /// Imperative lifecycle callbacks, parallel to the named serialized
    /// callback lists above.
    pub bo_fns: Vec<ContextAction>,
    pub ao_fns: Vec<ContextAction>,
    pub bc_fns: Vec<ContextAction>,
    pub ac_fns: Vec<ContextAction>,
    pub bo_state_fns: Vec<StateAction>,
    pub ao_state_fns: Vec<StateAction>,
    pub bc_state_fns: Vec<StateAction>,
    pub ac_state_fns: Vec<StateAction>,
    pub bo_order: Vec<ActionBinding>,
    pub ao_order: Vec<ActionBinding>,
    pub bc_order: Vec<ActionBinding>,
    pub ac_order: Vec<ActionBinding>,
}

impl fmt::Debug for RuleSpec {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RuleSpec")
            .field("name", &self.name)
            .field("open", &self.open.len())
            .field("close", &self.close.len())
            .field("bo", &self.bo.len())
            .field("ao", &self.ao.len())
            .field("bc", &self.bc.len())
            .field("ac", &self.ac.len())
            .finish_non_exhaustive()
    }
}

impl RuleSpec {
    pub fn new(name: impl Into<String>) -> Self {
        RuleSpec {
            name: name.into(),
            open: Vec::new(),
            close: Vec::new(),
            bo: Vec::new(),
            ao: Vec::new(),
            bc: Vec::new(),
            ac: Vec::new(),
            bo_fns: Vec::new(),
            ao_fns: Vec::new(),
            bc_fns: Vec::new(),
            ac_fns: Vec::new(),
            bo_state_fns: Vec::new(),
            ao_state_fns: Vec::new(),
            bc_state_fns: Vec::new(),
            ac_state_fns: Vec::new(),
            bo_order: Vec::new(),
            ao_order: Vec::new(),
            bc_order: Vec::new(),
            ac_order: Vec::new(),
        }
    }

    /// Remove all alternates and lifecycle actions from this rule.
    pub fn clear(&mut self) -> &mut Self {
        self.open.clear();
        self.close.clear();
        self.clear_actions(&[]);
        self
    }

    pub fn add_open(&mut self, alt: AltSpec) -> &mut Self {
        self.open.push(alt);
        self
    }

    pub fn prepend_open(&mut self, alt: AltSpec) -> &mut Self {
        self.open.insert(0, alt);
        self
    }

    pub fn add_close(&mut self, alt: AltSpec) -> &mut Self {
        self.close.push(alt);
        self
    }

    pub fn prepend_close(&mut self, alt: AltSpec) -> &mut Self {
        self.close.insert(0, alt);
        self
    }

    pub fn clear_open(&mut self) -> &mut Self {
        self.open.clear();
        self
    }

    pub fn clear_close(&mut self) -> &mut Self {
        self.close.clear();
        self
    }

    /// Delete then move entries using the same signed-index rules as the
    /// serialized grammar `inject` object.
    pub fn modify_open(&mut self, mods: &crate::utility::ListMods<AltSpec>) -> &mut Self {
        self.open = crate::utility::modlist(std::mem::take(&mut self.open), Some(mods));
        self
    }

    pub fn modify_close(&mut self, mods: &crate::utility::ListMods<AltSpec>) -> &mut Self {
        self.close = crate::utility::modlist(std::mem::take(&mut self.close), Some(mods));
        self
    }

    pub fn add_bo(
        &mut self,
        action: impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static,
    ) -> &mut Self {
        prepare_order(
            &self.bo,
            &self.bo_fns,
            &self.bo_state_fns,
            &mut self.bo_order,
        );
        let action = infallible_action(action);
        self.bo_fns.push(action.clone());
        self.bo_order.push(ActionBinding::Callback(action));
        self
    }

    pub fn prepend_bo(
        &mut self,
        action: impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static,
    ) -> &mut Self {
        prepare_order(
            &self.bo,
            &self.bo_fns,
            &self.bo_state_fns,
            &mut self.bo_order,
        );
        let action = infallible_action(action);
        self.bo_fns.insert(0, action.clone());
        self.bo_order.insert(0, ActionBinding::Callback(action));
        self
    }

    pub fn add_ao(
        &mut self,
        action: impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static,
    ) -> &mut Self {
        prepare_order(
            &self.ao,
            &self.ao_fns,
            &self.ao_state_fns,
            &mut self.ao_order,
        );
        let action = infallible_action(action);
        self.ao_fns.push(action.clone());
        self.ao_order.push(ActionBinding::Callback(action));
        self
    }

    pub fn prepend_ao(
        &mut self,
        action: impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static,
    ) -> &mut Self {
        prepare_order(
            &self.ao,
            &self.ao_fns,
            &self.ao_state_fns,
            &mut self.ao_order,
        );
        let action = infallible_action(action);
        self.ao_fns.insert(0, action.clone());
        self.ao_order.insert(0, ActionBinding::Callback(action));
        self
    }

    pub fn add_bc(
        &mut self,
        action: impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static,
    ) -> &mut Self {
        prepare_order(
            &self.bc,
            &self.bc_fns,
            &self.bc_state_fns,
            &mut self.bc_order,
        );
        let action = infallible_action(action);
        self.bc_fns.push(action.clone());
        self.bc_order.push(ActionBinding::Callback(action));
        self
    }

    pub fn prepend_bc(
        &mut self,
        action: impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static,
    ) -> &mut Self {
        prepare_order(
            &self.bc,
            &self.bc_fns,
            &self.bc_state_fns,
            &mut self.bc_order,
        );
        let action = infallible_action(action);
        self.bc_fns.insert(0, action.clone());
        self.bc_order.insert(0, ActionBinding::Callback(action));
        self
    }

    pub fn add_ac(
        &mut self,
        action: impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static,
    ) -> &mut Self {
        prepare_order(
            &self.ac,
            &self.ac_fns,
            &self.ac_state_fns,
            &mut self.ac_order,
        );
        let action = infallible_action(action);
        self.ac_fns.push(action.clone());
        self.ac_order.push(ActionBinding::Callback(action));
        self
    }

    pub fn prepend_ac(
        &mut self,
        action: impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static,
    ) -> &mut Self {
        prepare_order(
            &self.ac,
            &self.ac_fns,
            &self.ac_state_fns,
            &mut self.ac_order,
        );
        let action = infallible_action(action);
        self.ac_fns.insert(0, action.clone());
        self.ac_order.insert(0, ActionBinding::Callback(action));
        self
    }

    pub fn add_bo_result(&mut self, action: ContextAction) -> &mut Self {
        prepare_order(
            &self.bo,
            &self.bo_fns,
            &self.bo_state_fns,
            &mut self.bo_order,
        );
        self.bo_fns.push(action.clone());
        self.bo_order.push(ActionBinding::Callback(action));
        self
    }

    pub fn add_ao_result(&mut self, action: ContextAction) -> &mut Self {
        prepare_order(
            &self.ao,
            &self.ao_fns,
            &self.ao_state_fns,
            &mut self.ao_order,
        );
        self.ao_fns.push(action.clone());
        self.ao_order.push(ActionBinding::Callback(action));
        self
    }

    pub fn add_bc_result(&mut self, action: ContextAction) -> &mut Self {
        prepare_order(
            &self.bc,
            &self.bc_fns,
            &self.bc_state_fns,
            &mut self.bc_order,
        );
        self.bc_fns.push(action.clone());
        self.bc_order.push(ActionBinding::Callback(action));
        self
    }

    pub fn add_ac_result(&mut self, action: ContextAction) -> &mut Self {
        prepare_order(
            &self.ac,
            &self.ac_fns,
            &self.ac_state_fns,
            &mut self.ac_order,
        );
        self.ac_fns.push(action.clone());
        self.ac_order.push(ActionBinding::Callback(action));
        self
    }

    pub fn add_bo_with_state(&mut self, action: StateAction) -> &mut Self {
        prepare_order(
            &self.bo,
            &self.bo_fns,
            &self.bo_state_fns,
            &mut self.bo_order,
        );
        self.bo_state_fns.push(action.clone());
        self.bo_order.push(ActionBinding::State(action));
        self
    }

    pub fn prepend_bo_with_state(&mut self, action: StateAction) -> &mut Self {
        prepare_order(
            &self.bo,
            &self.bo_fns,
            &self.bo_state_fns,
            &mut self.bo_order,
        );
        self.bo_state_fns.insert(0, action.clone());
        self.bo_order.insert(0, ActionBinding::State(action));
        self
    }

    pub fn add_ao_with_state(&mut self, action: StateAction) -> &mut Self {
        prepare_order(
            &self.ao,
            &self.ao_fns,
            &self.ao_state_fns,
            &mut self.ao_order,
        );
        self.ao_state_fns.push(action.clone());
        self.ao_order.push(ActionBinding::State(action));
        self
    }

    pub fn prepend_ao_with_state(&mut self, action: StateAction) -> &mut Self {
        prepare_order(
            &self.ao,
            &self.ao_fns,
            &self.ao_state_fns,
            &mut self.ao_order,
        );
        self.ao_state_fns.insert(0, action.clone());
        self.ao_order.insert(0, ActionBinding::State(action));
        self
    }

    pub fn add_bc_with_state(&mut self, action: StateAction) -> &mut Self {
        prepare_order(
            &self.bc,
            &self.bc_fns,
            &self.bc_state_fns,
            &mut self.bc_order,
        );
        self.bc_state_fns.push(action.clone());
        self.bc_order.push(ActionBinding::State(action));
        self
    }

    pub fn prepend_bc_with_state(&mut self, action: StateAction) -> &mut Self {
        prepare_order(
            &self.bc,
            &self.bc_fns,
            &self.bc_state_fns,
            &mut self.bc_order,
        );
        self.bc_state_fns.insert(0, action.clone());
        self.bc_order.insert(0, ActionBinding::State(action));
        self
    }

    pub fn add_ac_with_state(&mut self, action: StateAction) -> &mut Self {
        prepare_order(
            &self.ac,
            &self.ac_fns,
            &self.ac_state_fns,
            &mut self.ac_order,
        );
        self.ac_state_fns.push(action.clone());
        self.ac_order.push(ActionBinding::State(action));
        self
    }

    pub fn prepend_ac_with_state(&mut self, action: StateAction) -> &mut Self {
        prepare_order(
            &self.ac,
            &self.ac_fns,
            &self.ac_state_fns,
            &mut self.ac_order,
        );
        self.ac_state_fns.insert(0, action.clone());
        self.ac_order.insert(0, ActionBinding::State(action));
        self
    }

    pub fn add_bo_ref(&mut self, action: impl Into<String>) -> &mut Self {
        add_named(
            &mut self.bo,
            &mut self.bo_fns,
            &mut self.bo_state_fns,
            &mut self.bo_order,
            action.into(),
            false,
        );
        self
    }

    pub fn prepend_bo_ref(&mut self, action: impl Into<String>) -> &mut Self {
        add_named(
            &mut self.bo,
            &mut self.bo_fns,
            &mut self.bo_state_fns,
            &mut self.bo_order,
            action.into(),
            true,
        );
        self
    }

    pub fn add_ao_ref(&mut self, action: impl Into<String>) -> &mut Self {
        add_named(
            &mut self.ao,
            &mut self.ao_fns,
            &mut self.ao_state_fns,
            &mut self.ao_order,
            action.into(),
            false,
        );
        self
    }

    pub fn prepend_ao_ref(&mut self, action: impl Into<String>) -> &mut Self {
        add_named(
            &mut self.ao,
            &mut self.ao_fns,
            &mut self.ao_state_fns,
            &mut self.ao_order,
            action.into(),
            true,
        );
        self
    }

    pub fn add_bc_ref(&mut self, action: impl Into<String>) -> &mut Self {
        add_named(
            &mut self.bc,
            &mut self.bc_fns,
            &mut self.bc_state_fns,
            &mut self.bc_order,
            action.into(),
            false,
        );
        self
    }

    pub fn prepend_bc_ref(&mut self, action: impl Into<String>) -> &mut Self {
        add_named(
            &mut self.bc,
            &mut self.bc_fns,
            &mut self.bc_state_fns,
            &mut self.bc_order,
            action.into(),
            true,
        );
        self
    }

    pub fn add_ac_ref(&mut self, action: impl Into<String>) -> &mut Self {
        add_named(
            &mut self.ac,
            &mut self.ac_fns,
            &mut self.ac_state_fns,
            &mut self.ac_order,
            action.into(),
            false,
        );
        self
    }

    pub fn prepend_ac_ref(&mut self, action: impl Into<String>) -> &mut Self {
        add_named(
            &mut self.ac,
            &mut self.ac_fns,
            &mut self.ac_state_fns,
            &mut self.ac_order,
            action.into(),
            true,
        );
        self
    }

    /// Clear named and imperative lifecycle actions. An empty phase slice
    /// clears all four; otherwise accepted phase names are `bo`, `ao`, `bc`,
    /// and `ac`.
    pub fn clear_actions(&mut self, phases: &[&str]) -> &mut Self {
        let clear_all = phases.is_empty();
        for phase in ["bo", "ao", "bc", "ac"] {
            if clear_all || phases.contains(&phase) {
                match phase {
                    "bo" => {
                        self.bo.clear();
                        self.bo_fns.clear();
                        self.bo_state_fns.clear();
                        self.bo_order.clear();
                    }
                    "ao" => {
                        self.ao.clear();
                        self.ao_fns.clear();
                        self.ao_state_fns.clear();
                        self.ao_order.clear();
                    }
                    "bc" => {
                        self.bc.clear();
                        self.bc_fns.clear();
                        self.bc_state_fns.clear();
                        self.bc_order.clear();
                    }
                    "ac" => {
                        self.ac.clear();
                        self.ac_fns.clear();
                        self.ac_state_fns.clear();
                        self.ac_order.clear();
                    }
                    _ => unreachable!(),
                }
            }
        }
        self
    }
}

fn infallible_action(
    action: impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static,
) -> ContextAction {
    Arc::new(move |rule, context| {
        action(rule, context);
        Ok::<(), ActionError>(())
    })
}

impl AltSpec {
    /// Append an imperative Rust action to this alternate.
    pub fn add_action(
        &mut self,
        action: impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static,
    ) -> &mut Self {
        prepare_alt_order(
            &self.a,
            &self.action_fns,
            &self.matched_action_fns,
            &mut self.action_order,
        );
        let action = infallible_action(action);
        self.action_fns.push(action.clone());
        self.action_order.push(AltActionBinding::Context(action));
        self
    }

    /// Prepend an imperative Rust action ahead of existing named or direct
    /// actions.
    pub fn prepend_action(
        &mut self,
        action: impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static,
    ) -> &mut Self {
        prepare_alt_order(
            &self.a,
            &self.action_fns,
            &self.matched_action_fns,
            &mut self.action_order,
        );
        let action = infallible_action(action);
        self.action_fns.insert(0, action.clone());
        self.action_order
            .insert(0, AltActionBinding::Context(action));
        self
    }

    /// Append a fallible imperative Rust action to this alternate.
    pub fn add_action_result(&mut self, action: ContextAction) -> &mut Self {
        prepare_alt_order(
            &self.a,
            &self.action_fns,
            &self.matched_action_fns,
            &mut self.action_order,
        );
        self.action_fns.push(action.clone());
        self.action_order.push(AltActionBinding::Context(action));
        self
    }

    pub fn prepend_action_result(&mut self, action: ContextAction) -> &mut Self {
        prepare_alt_order(
            &self.a,
            &self.action_fns,
            &self.matched_action_fns,
            &mut self.action_order,
        );
        self.action_fns.insert(0, action.clone());
        self.action_order
            .insert(0, AltActionBinding::Context(action));
        self
    }

    /// Append an action with the complete matched-alternate argument.
    pub fn add_action_with_match(
        &mut self,
        action: impl Fn(&mut Rule, &mut Context, &AltMatch) -> Option<Token> + Send + Sync + 'static,
    ) -> &mut Self {
        self.add_action_with_match_result(Arc::new(move |rule, context, matched| {
            Ok(action(rule, context, matched))
        }))
    }

    pub fn prepend_action_with_match(
        &mut self,
        action: impl Fn(&mut Rule, &mut Context, &AltMatch) -> Option<Token> + Send + Sync + 'static,
    ) -> &mut Self {
        self.prepend_action_with_match_result(Arc::new(move |rule, context, matched| {
            Ok(action(rule, context, matched))
        }))
    }

    pub fn add_action_with_match_result(&mut self, action: AltAction) -> &mut Self {
        prepare_alt_order(
            &self.a,
            &self.action_fns,
            &self.matched_action_fns,
            &mut self.action_order,
        );
        self.matched_action_fns.push(action.clone());
        self.action_order.push(AltActionBinding::Matched(action));
        self
    }

    pub fn prepend_action_with_match_result(&mut self, action: AltAction) -> &mut Self {
        prepare_alt_order(
            &self.a,
            &self.action_fns,
            &self.matched_action_fns,
            &mut self.action_order,
        );
        self.matched_action_fns.insert(0, action.clone());
        self.action_order
            .insert(0, AltActionBinding::Matched(action));
        self
    }

    pub fn add_action_ref(&mut self, action: impl Into<String>) -> &mut Self {
        add_alt_named(
            &mut self.a,
            &mut self.action_fns,
            &mut self.matched_action_fns,
            &mut self.action_order,
            action.into(),
            false,
        );
        self
    }

    pub fn prepend_action_ref(&mut self, action: impl Into<String>) -> &mut Self {
        add_alt_named(
            &mut self.a,
            &mut self.action_fns,
            &mut self.matched_action_fns,
            &mut self.action_order,
            action.into(),
            true,
        );
        self
    }
}

fn alt_order_matches(
    named: &[String],
    callbacks: &[ContextAction],
    matched: &[AltAction],
    order: &[AltActionBinding],
) -> bool {
    if order.len() != named.len() + callbacks.len() + matched.len() {
        return false;
    }
    // One pass. Written as three filtered views compared against their
    // lists, this walked `order` five times over -- once per view plus a
    // second walk of two of them to count -- and the parse loop asks this
    // question once per rule step. Taking the next expected entry from
    // whichever list a binding names says the same thing in one walk.
    let (mut next_name, mut next_callback, mut next_matched) = (0, 0, 0);
    for binding in order {
        match binding {
            AltActionBinding::Named(name) => {
                if named.get(next_name) != Some(name) {
                    return false;
                }
                next_name += 1;
            }
            AltActionBinding::Context(callback) => {
                if !callbacks
                    .get(next_callback)
                    .is_some_and(|expected| Arc::ptr_eq(expected, callback))
                {
                    return false;
                }
                next_callback += 1;
            }
            AltActionBinding::Matched(callback) => {
                if !matched
                    .get(next_matched)
                    .is_some_and(|expected| Arc::ptr_eq(expected, callback))
                {
                    return false;
                }
                next_matched += 1;
            }
        }
    }
    next_name == named.len() && next_callback == callbacks.len() && next_matched == matched.len()
}

fn prepare_alt_order(
    named: &[String],
    callbacks: &[ContextAction],
    matched: &[AltAction],
    order: &mut Vec<AltActionBinding>,
) {
    if !alt_order_matches(named, callbacks, matched, order) {
        *order = named
            .iter()
            .cloned()
            .map(AltActionBinding::Named)
            .chain(callbacks.iter().cloned().map(AltActionBinding::Context))
            .chain(matched.iter().cloned().map(AltActionBinding::Matched))
            .collect();
    }
}

fn add_alt_named(
    named: &mut Vec<String>,
    callbacks: &mut Vec<ContextAction>,
    matched: &mut Vec<AltAction>,
    order: &mut Vec<AltActionBinding>,
    action: String,
    prepend: bool,
) {
    prepare_alt_order(named, callbacks, matched, order);
    if prepend {
        named.insert(0, action.clone());
        order.insert(0, AltActionBinding::Named(action));
    } else {
        named.push(action.clone());
        order.push(AltActionBinding::Named(action));
    }
}

pub(crate) fn resolved_alt_action_order(
    named: &[String],
    callbacks: &[ContextAction],
    matched: &[AltAction],
    order: &[AltActionBinding],
) -> Vec<AltActionBinding> {
    if alt_order_matches(named, callbacks, matched, order) {
        order.to_vec()
    } else {
        named
            .iter()
            .cloned()
            .map(AltActionBinding::Named)
            .chain(callbacks.iter().cloned().map(AltActionBinding::Context))
            .chain(matched.iter().cloned().map(AltActionBinding::Matched))
            .collect()
    }
}

fn order_matches(
    named: &[String],
    callbacks: &[ContextAction],
    states: &[StateAction],
    order: &[ActionBinding],
) -> bool {
    if order.len() != named.len() + callbacks.len() + states.len() {
        return false;
    }
    // One pass, for the reason given on `alt_order_matches`.
    let (mut next_name, mut next_callback, mut next_state) = (0, 0, 0);
    for binding in order {
        match binding {
            ActionBinding::Named(name) => {
                if named.get(next_name) != Some(name) {
                    return false;
                }
                next_name += 1;
            }
            ActionBinding::Callback(callback) => {
                if !callbacks
                    .get(next_callback)
                    .is_some_and(|expected| Arc::ptr_eq(expected, callback))
                {
                    return false;
                }
                next_callback += 1;
            }
            ActionBinding::State(callback) => {
                if !states
                    .get(next_state)
                    .is_some_and(|expected| Arc::ptr_eq(expected, callback))
                {
                    return false;
                }
                next_state += 1;
            }
        }
    }
    next_name == named.len() && next_callback == callbacks.len() && next_state == states.len()
}

fn prepare_order(
    named: &[String],
    callbacks: &[ContextAction],
    states: &[StateAction],
    order: &mut Vec<ActionBinding>,
) {
    if !order_matches(named, callbacks, states, order) {
        *order = named
            .iter()
            .cloned()
            .map(ActionBinding::Named)
            .chain(callbacks.iter().cloned().map(ActionBinding::Callback))
            .chain(states.iter().cloned().map(ActionBinding::State))
            .collect();
    }
}

fn add_named(
    named: &mut Vec<String>,
    callbacks: &mut Vec<ContextAction>,
    states: &mut Vec<StateAction>,
    order: &mut Vec<ActionBinding>,
    action: String,
    prepend: bool,
) {
    prepare_order(named, callbacks, states, order);
    if prepend {
        named.insert(0, action.clone());
        order.insert(0, ActionBinding::Named(action));
    } else {
        named.push(action.clone());
        order.push(ActionBinding::Named(action));
    }
}

pub(crate) fn resolved_action_order(
    named: &[String],
    callbacks: &[ContextAction],
    states: &[StateAction],
    order: &[ActionBinding],
) -> Vec<ActionBinding> {
    if order_matches(named, callbacks, states, order) {
        order.to_vec()
    } else {
        named
            .iter()
            .cloned()
            .map(ActionBinding::Named)
            .chain(callbacks.iter().cloned().map(ActionBinding::Callback))
            .chain(states.iter().cloned().map(ActionBinding::State))
            .collect()
    }
}

/// A rule's name.
///
/// Rules are pushed and popped for every construct in a parse, so the
/// name is shared between a rule, its snapshots and whatever the next
/// rule records, rather than being copied at each step. It still
/// behaves like the `String` it replaced: compare it with a literal,
/// print it, or take a `&str` from it.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct RuleName(Arc<str>);

impl RuleName {
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::ops::Deref for RuleName {
    type Target = str;

    fn deref(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for RuleName {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

/// Keyed lookups borrow the name as a `str`, so `Hash` and `Eq` have to
/// agree with `str`'s. Both reach `str` through the `Arc`, so they do.
impl std::borrow::Borrow<str> for RuleName {
    fn borrow(&self) -> &str {
        &self.0
    }
}

/// Printed as the bare name, so a `{:?}` of a rule or a snapshot reads
/// the way it did when this was a `String`.
impl fmt::Debug for RuleName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&*self.0, f)
    }
}

impl fmt::Display for RuleName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl PartialEq<str> for RuleName {
    fn eq(&self, other: &str) -> bool {
        &*self.0 == other
    }
}

impl PartialEq<&str> for RuleName {
    fn eq(&self, other: &&str) -> bool {
        &*self.0 == *other
    }
}

impl PartialEq<String> for RuleName {
    fn eq(&self, other: &String) -> bool {
        &*self.0 == other.as_str()
    }
}

impl PartialEq<RuleName> for str {
    fn eq(&self, other: &RuleName) -> bool {
        self == &*other.0
    }
}

impl PartialEq<RuleName> for &str {
    fn eq(&self, other: &RuleName) -> bool {
        *self == &*other.0
    }
}

impl PartialEq<RuleName> for String {
    fn eq(&self, other: &RuleName) -> bool {
        self.as_str() == &*other.0
    }
}

impl From<&str> for RuleName {
    fn from(name: &str) -> Self {
        RuleName(Arc::from(name))
    }
}

impl From<String> for RuleName {
    fn from(name: String) -> Self {
        RuleName(Arc::from(name.as_str()))
    }
}

impl From<&String> for RuleName {
    fn from(name: &String) -> Self {
        RuleName(Arc::from(name.as_str()))
    }
}

impl From<Arc<str>> for RuleName {
    fn from(name: Arc<str>) -> Self {
        RuleName(name)
    }
}

impl From<RuleName> for String {
    fn from(name: RuleName) -> Self {
        name.0.to_string()
    }
}

/// A rule as the parse loop sees it.
///
/// Its state lives behind an `Rc` that it shares with every snapshot
/// taken of it, so `snapshot()` is a pointer copy. The copy happens
/// instead on the next write, and only while a snapshot is still
/// holding the current value — so a rule that is snapshotted several
/// times between writes pays for one copy, not several, and a rule
/// nobody snapshotted pays for none. Reads and writes both go through
/// `Deref`, so `rule.state` and `rule.state = ..` are unchanged at
/// every call site.
#[derive(Clone)]
pub struct Rule {
    shared: Rc<RuleSnapshot>,
    /// Not shared with snapshots, which do not carry it.
    pub parent_node: Option<Rc<RefCell<Value>>>,
    /// The completed child's node, likewise not shared. A `Value` is 72
    /// bytes, which was a third of a `RuleSnapshot`, and copy-on-write
    /// copied all of it on the next write to any field. Nothing reads
    /// this through a snapshot: every use in the engine and in the
    /// plugin repos is `rule.child_node` on a live rule.
    ///
    /// `Undefined` when the child shared this rule's node cell, so that
    /// this field is never a second handle on this rule's own
    /// accumulator (#195); [`Rule::child_value`] answers from the node
    /// in that case.
    pub child_node: Value,
    pub(crate) skip_befores: bool,
    pub(crate) child_node_is_self: bool,
    /// Whether the child link below still names the rule this one PUSHED,
    /// and that rule is still running.
    ///
    /// The link is frozen ONCE, by the first `freeze_child` after the push,
    /// and this says whether that has happened yet. It is deliberately not
    /// an identity carried on the child: a rule is handed to callbacks as
    /// `&mut Rule`, so an imperative action can assign `*rule = ...` and
    /// replace the whole value, resetting any field on it. Anything the
    /// engine needs to trust therefore cannot live there. This flag lives
    /// on the PARENT, which is buried on the parse stack for the whole of
    /// the child's life and is never handed to a callback, so no grammar
    /// can reach it.
    ///
    /// Getting this wrong is not a stale-looking value but a wrong one:
    /// `@node$`, `@value$`, `@object$`, `@fold$` and `@bubble$` all REPLACE
    /// `rule.node` with a fresh cell rather than writing through it
    /// (`rs/src/builtins.rs`), so a link left at its push-time cell holds
    /// the value from before the child did any work.
    ///
    /// TypeScript links `rule.child` at the push (`ts/src/rules.ts:665`)
    /// and never relinks it; Go does the same (`go/rule.go:1280`). A child
    /// that REPLACES itself therefore leaves the parent reading the first
    /// instance of the chain, which is why `@fold$` exists at all (see its
    /// doc comment in `ts/src/builtins.ts`). Closing the link on the first
    /// freeze is how that survives here, where the replaced rule is dropped
    /// rather than kept alive by a reference.
    pub(crate) child_link_open: bool,
    pub(crate) child_cell: Option<Rc<RefCell<Value>>>,
    /// The pushed rule's record, frozen at the moment it stopped being the
    /// current rule. Deliberately NOT a [`RuleSnapshot`] field: the parse
    /// loop writes it on a rule that is still buried on the stack, and
    /// `Context::sync_rule_stack` requires a buried frame's snapshot to
    /// keep describing it. It reaches `child_rule` only when the rule is
    /// resumed, which is the moment TypeScript's live reference would
    /// first be read from that rule again.
    pub(crate) child_record: Option<Rc<RuleSnapshot>>,
    /// Where this rule's prepared state sits in the parser's table, or
    /// `usize::MAX` for a rule the parser did not bind.
    ///
    /// A plain `usize` rather than a handle on the prepared record itself:
    /// the parse loop clones a `Rule` once per close and snapshots it
    /// several times per step, and an `Arc` here would make every one of
    /// those a pair of atomics. The table is reached through the parser's
    /// `&self` instead, and this only says where to look. It is a hint,
    /// not a fact -- a callback can write `spec` or `name` out from under
    /// it -- so the loop checks the record it finds against both before
    /// trusting it.
    pub(crate) slot: usize,
}

impl Drop for RuleSnapshot {
    /// Unlink iteratively, because the derived drop recurses and the links
    /// below form a chain as long as the input.
    ///
    /// `parent_rule`, `child_rule`, `prev_rule` and `next_rule` each own an
    /// `Rc<RuleSnapshot>`, so the generated glue walks a chain with the call
    /// stack: `drop_in_place<RuleSnapshot>` calls `Rc::drop_slow` calls
    /// `drop_in_place<RuleSnapshot>` again, one frame per link. A grammar
    /// that pushes or replaces a rule per input element builds one link per
    /// element, so a flat JSON array of 150,000 numbers -- nesting depth
    /// ONE, nothing recursive about the document -- overflowed the default
    /// 8 MiB main-thread stack and aborted the process.
    ///
    /// Fat LTO makes it worse rather than better: inlining the cycle into
    /// itself multiplies the per-link frame, so a default release build
    /// survived an input that a build in the configuration rs/README.md
    /// documents for shipping did not. That is the wrong way round, and it
    /// is why this is a `Drop` impl rather than advice about stack size.
    ///
    /// The scratch is a local rather than a thread-local. A thread-local
    /// is faster and was wrong twice over: its key can be destroyed before
    /// another thread-local holding a snapshot is, and touching a
    /// destroyed key panics from inside a destructor; and re-entering this
    /// function while its `RefCell` is borrowed panics too. A local is
    /// immune to both, and the early return below means most drops never
    /// reach it.
    fn drop(&mut self) {
        // The overwhelmingly common case, and the one on the parse loop's
        // hot path: nothing is linked, so there is nothing to walk. Four
        // loads and a branch, no scratch, no allocation.
        if self.parent_rule.is_none()
            && self.child_rule.is_none()
            && self.prev_rule.is_none()
            && self.next_rule.is_none()
        {
            return;
        }

        /// Move a snapshot's links out, preferring the single-slot
        /// `cursor` so that a pure chain -- one link per snapshot, which
        /// is what a rule replaced once per input element builds -- is
        /// walked without allocating anything at all. `pending` is only
        /// reached for a snapshot holding more than one link, and a `Vec`
        /// that is never pushed to never allocates.
        fn unlink(
            snapshot: &mut RuleSnapshot,
            cursor: &mut Option<Rc<RuleSnapshot>>,
            pending: &mut Vec<Rc<RuleSnapshot>>,
        ) {
            let mut hold = |held: Option<Rc<RuleSnapshot>>| {
                if let Some(held) = held {
                    if cursor.is_none() {
                        *cursor = Some(held);
                    } else {
                        pending.push(held);
                    }
                }
            };
            hold(snapshot.parent_rule.take());
            hold(snapshot.child_rule.take());
            hold(snapshot.prev_rule.take());
            hold(snapshot.next_rule.take());
        }

        let mut cursor: Option<Rc<RuleSnapshot>> = None;
        let mut pending: Vec<Rc<RuleSnapshot>> = Vec::new();
        unlink(self, &mut cursor, &mut pending);
        while let Some(mut link) = cursor.take().or_else(|| pending.pop()) {
            if Rc::weak_count(&link) == 0 {
                // No weak observers, so `get_mut` answers "am I the last
                // handle" without moving anything. `RuleSnapshot` is a
                // twenty-field struct carrying eight reference-counted
                // handles, and this is the path the parse loop takes.
                if let Some(owned) = Rc::get_mut(&mut link) {
                    unlink(owned, &mut cursor, &mut pending);
                }
            } else if let Ok(mut owned) = Rc::try_unwrap(link) {
                // `Rule::snapshot` is public and `Context` hands out
                // `Rc<RuleSnapshot>`, so an embedder can hold a `Weak` to
                // one. `get_mut` refuses while any weak observer exists,
                // even when we ARE the last strong owner and dropping will
                // run the destructor; `try_unwrap` is the one that
                // distinguishes those. Getting this wrong left the links
                // in place and recursed after all.
                unlink(&mut owned, &mut cursor, &mut pending);
            }
            // Anything reached here drops with its links already taken, so
            // its own `drop` returns at the check above.
        }
    }
}

impl std::ops::Deref for Rule {
    type Target = RuleSnapshot;

    fn deref(&self) -> &RuleSnapshot {
        &self.shared
    }
}

/// Every write to a rule's shared state goes through here, which is
/// what makes the copy happen on write rather than on snapshot.
///
/// The obvious next step — stop copying at all, so a snapshot aliases
/// the live rule the way TypeScript's and Go's rule handles do — was
/// measured here by making this return an aliasing pointer. It is
/// faster where it works: a 512-character palindrome drops from 31.7M
/// to 24.6M instructions, and a 16K-term adder from 72.7 ms to 57.8 ms.
/// But `next_rule` and the parent and child links then point at rules
/// that point back, and an `Rc` cycle is never freed: peak memory for
/// the benchmark set goes from 71 MB to 1214 MB, and a 32K-character
/// palindrome slows from 111 ms to 270 ms once the leak outweighs the
/// saving. Doing it properly needs `Weak` on every back-reference and
/// an upgrade on every traversal, which spends some of the same 1.3x
/// it is chasing. Worth knowing before anyone tries it again.
impl std::ops::DerefMut for Rule {
    fn deref_mut(&mut self) -> &mut RuleSnapshot {
        Rc::make_mut(&mut self.shared)
    }
}

#[derive(Debug, Clone)]
pub struct RuleSnapshot {
    pub i: usize,
    pub d: usize,
    pub name: RuleName,
    pub spec: Arc<RuleSpec>,
    pub state: RuleState,
    pub bo: bool,
    pub ao: bool,
    pub bc: bool,
    pub ac: bool,
    pub need: i32,
    pub node: Rc<RefCell<Value>>,
    pub parent_rule: Option<Rc<RuleSnapshot>>,
    pub child_rule: Option<Rc<RuleSnapshot>>,
    pub prev_rule: Option<Rc<RuleSnapshot>>,
    pub next_rule: Option<Rc<RuleSnapshot>>,
    pub next_rule_name: Option<RuleName>,
    pub n: Rc<HashMap<String, i32>>,
    pub u: Rc<HashMap<String, Value>>,
    pub k: Rc<HashMap<String, Value>>,
    /// Matched open and close tokens. Shared rather than owned: the parse
    /// loop only ever replaces these wholesale, and a snapshot that copied
    /// them copied every `Token`'s name and source text with them.
    pub o: Rc<Vec<Token>>,
    pub c: Rc<Vec<Token>>,
}

/// One shared empty map per thread, so a rule that never writes to `n`,
/// `u` or `k` costs no allocation for them. `Rc::make_mut` copies on the
/// first write, which for an empty map is close to free.
fn empty_counters() -> Rc<HashMap<String, i32>> {
    thread_local! {
        static EMPTY: Rc<HashMap<String, i32>> = Rc::new(HashMap::new());
    }
    EMPTY.with(Rc::clone)
}

fn empty_values() -> Rc<HashMap<String, Value>> {
    thread_local! {
        static EMPTY: Rc<HashMap<String, Value>> = Rc::new(HashMap::new());
    }
    EMPTY.with(Rc::clone)
}

/// The matched-token lists start empty and are replaced wholesale when an
/// alternate matches, so every rule created allocated two `Rc` boxes for two
/// vectors that never grew. Shared like the counter and value bags above.
fn empty_tokens() -> Rc<Vec<Token>> {
    thread_local! {
        static EMPTY: Rc<Vec<Token>> = Rc::new(Vec::new());
    }
    EMPTY.with(Rc::clone)
}

impl Rule {
    /// Mutable access to the per-rule counters and state. Copies only when
    /// a snapshot is still holding the current value.
    pub fn n_mut(&mut self) -> &mut HashMap<String, i32> {
        Rc::make_mut(&mut self.n)
    }

    pub fn u_mut(&mut self) -> &mut HashMap<String, Value> {
        Rc::make_mut(&mut self.u)
    }

    pub fn k_mut(&mut self) -> &mut HashMap<String, Value> {
        Rc::make_mut(&mut self.k)
    }

    pub fn new(name: impl Into<RuleName>, initial_node: Value) -> Self {
        let name: RuleName = name.into();
        let spec = Arc::new(RuleSpec::new(name.as_str()));
        Rule {
            shared: Rc::new(RuleSnapshot {
                i: 0,
                d: 0,
                name,
                spec,
                state: RuleState::Open,
                bo: true,
                ao: true,
                bc: true,
                ac: true,
                need: 0,
                node: Rc::new(RefCell::new(initial_node)),
                parent_rule: None,
                child_rule: None,
                prev_rule: None,
                next_rule: None,
                next_rule_name: None,
                n: empty_counters(),
                u: empty_values(),
                k: empty_values(),
                o: empty_tokens(),
                c: empty_tokens(),
            }),
            parent_node: None,
            child_node: Value::Undefined,
            skip_befores: false,
            child_node_is_self: false,
            child_link_open: false,
            child_cell: None,
            child_record: None,
            slot: usize::MAX,
        }
    }

    pub fn with_shared_node(name: impl Into<RuleName>, node: Rc<RefCell<Value>>) -> Self {
        Self::bound(name.into(), node, None, usize::MAX)
    }

    /// Build a rule already bound to its installed spec.
    ///
    /// An unbound rule reports its own name through `spec.name`, so building
    /// one with no spec has to invent a placeholder `RuleSpec` carrying that
    /// name: a `String` and an `Arc` box. Every push and replace in the parse
    /// loop then bound the installed spec straight over the placeholder, so
    /// both were allocated and freed once per rule step for nothing. The
    /// placeholder is still built for a name that names no installed rule,
    /// which is the case it exists for.
    pub(crate) fn bound(
        name: RuleName,
        node: Rc<RefCell<Value>>,
        installed: Option<&Arc<RuleSpec>>,
        slot: usize,
    ) -> Self {
        let spec = match installed {
            Some(spec) => Arc::clone(spec),
            None => Arc::new(RuleSpec::new(name.as_str())),
        };
        Rule {
            shared: Rc::new(RuleSnapshot {
                i: 0,
                d: 0,
                name,
                spec,
                state: RuleState::Open,
                bo: true,
                ao: true,
                bc: true,
                ac: true,
                need: 0,
                node,
                parent_rule: None,
                child_rule: None,
                prev_rule: None,
                next_rule: None,
                next_rule_name: None,
                n: empty_counters(),
                u: empty_values(),
                k: empty_values(),
                o: empty_tokens(),
                c: empty_tokens(),
            }),
            parent_node: None,
            child_node: Value::Undefined,
            skip_befores: false,
            child_node_is_self: false,
            child_link_open: false,
            child_cell: None,
            child_record: None,
            slot,
        }
    }

    /// `name` arrives already shared: the parser interns one handle per
    /// installed rule, so binding copies a pointer rather than the text.
    ///
    /// `slot` is the rule's position in the parser's prepared table, which
    /// the same lookup that found the spec already returned.
    pub(crate) fn bind_spec(&mut self, spec: &Arc<RuleSpec>, name: RuleName, slot: usize) {
        self.name = name;
        self.spec = Arc::clone(spec);
        self.slot = slot;
        // Rust RuleSpec lifecycle lists are always present (possibly empty),
        // matching the canonical normalized definition's non-null defaults.
        self.bo = true;
        self.ao = true;
        self.bc = true;
        self.ac = true;
    }

    pub fn o0(&self) -> Option<&Token> {
        self.o.first()
    }

    pub fn o1(&self) -> Option<&Token> {
        self.o.get(1)
    }

    pub fn c0(&self) -> Option<&Token> {
        self.c.first()
    }

    pub fn c1(&self) -> Option<&Token> {
        self.c.get(1)
    }

    pub fn os(&self) -> usize {
        self.o.len()
    }

    pub fn cs(&self) -> usize {
        self.c.len()
    }

    /// Resolve a matched opening token's eager or lazy semantic value without
    /// exposing the temporary token clone needed by Rust's borrow rules.
    pub fn resolve_open_value(&mut self, index: usize, context: &mut Context) -> Value {
        self.o
            .get(index)
            .cloned()
            .map_or(Value::Undefined, |token| token.resolve_val(self, context))
    }

    /// Resolve a matched closing token's eager or lazy semantic value.
    pub fn resolve_close_value(&mut self, index: usize, context: &mut Context) -> Value {
        self.c
            .get(index)
            .cloned()
            .map_or(Value::Undefined, |token| token.resolve_val(self, context))
    }

    /// Counter comparisons use zero for an unset counter, matching the
    /// canonical engine. `exist` distinguishes unset from explicitly zero.
    pub fn eq(&self, counter: &str, limit: i32) -> bool {
        self.n.get(counter).copied().unwrap_or(0) == limit
    }

    pub fn lt(&self, counter: &str, limit: i32) -> bool {
        self.n.get(counter).copied().unwrap_or(0) < limit
    }

    pub fn gt(&self, counter: &str, limit: i32) -> bool {
        self.n.get(counter).copied().unwrap_or(0) > limit
    }

    pub fn lte(&self, counter: &str, limit: i32) -> bool {
        self.n.get(counter).copied().unwrap_or(0) <= limit
    }

    pub fn gte(&self, counter: &str, limit: i32) -> bool {
        self.n.get(counter).copied().unwrap_or(0) >= limit
    }

    pub fn exist(&self, counter: &str) -> bool {
        self.n.contains_key(counter)
    }

    /// The rule's state as it stands, shared rather than copied. The
    /// copy, if one is still needed, happens on the rule's next write.
    pub fn snapshot(&self) -> Rc<RuleSnapshot> {
        Rc::clone(&self.shared)
    }

    /// Remember which rule this one pushed, and where its node cell was at
    /// the push. Called by the parse loop's push arm.
    pub(crate) fn note_child_push(&mut self, child: &Rule) {
        self.child_link_open = true;
        self.child_cell = Some(Rc::clone(&child.node));
        self.child_record = Some(child.snapshot());
    }

    /// The pushed child is about to stop being the current rule, either
    /// because it is being replaced or because it is popping. Freeze both
    /// halves of the link: the cell its `node` field ended on, and its
    /// record as it stands. That pair is what TypeScript would go on
    /// reading through the live `rule.child` reference.
    ///
    /// Only the FIRST call after the push freezes; the link is closed
    /// afterwards. A later link of a replacement chain would otherwise
    /// overwrite it and report a `rule.child` no canonical runtime can
    /// produce -- the pushed rule's node under the chain tail's name.
    /// Closing the link rather than comparing an identity on the child is
    /// deliberate: see `Rule::child_link_open`.
    /// Holding the cell costs a refcount and no copy-on-write: the `Value`
    /// itself is read out only when this rule is resumed. The record is
    /// `Rc<RuleSnapshot>`, which the replaced rule is about to stop
    /// writing to in any case.
    pub(crate) fn freeze_child(&mut self, child: &Rule) {
        if self.child_link_open {
            self.child_cell = Some(Rc::clone(&child.node));
            self.child_record = Some(child.snapshot());
            self.child_link_open = false;
        }
    }

    pub(crate) fn accept_child_node(&mut self, child: &Rule) {
        self.freeze_child(child);
        let cell = self
            .child_cell
            .clone()
            .unwrap_or_else(|| Rc::clone(&child.node));
        self.child_node_is_self = Rc::ptr_eq(&self.node, &cell);
        // A child that shared this rule's node cell wrote into this
        // rule's own container, so the value it hands back IS this
        // rule's node. Holding a clone of it here would be a second
        // `Arc` handle on the accumulator this rule is about to write
        // into again, and `Arc::make_mut` then copies the whole
        // container once per element: one rule with N elements cost
        // O(N^2), 46 seconds for 800 fields where TypeScript took a
        // tenth of a second (#195). The field stays `Undefined` in that
        // case and `child_value()` answers from the node instead, which
        // is what TypeScript's `rule.child.node` (the same object as
        // `rule.node` then) gives.
        self.child_node = if self.child_node_is_self {
            Value::Undefined
        } else {
            cell.borrow().clone()
        };
    }

    /// The completed child's value, as TypeScript's `rule.child.node`
    /// reads: `child_node` when the child had a node of its own, and
    /// this rule's own node when the child shared this rule's cell (see
    /// `Rule::accept_child_node`, which is crate-private, so this is a
    /// name and not a link). Read this rather than `child_node`
    /// wherever the shared case must be seen as a value.
    pub fn child_value(&self) -> Value {
        if self.child_node_is_self {
            self.node.borrow().clone()
        } else {
            self.child_node.clone()
        }
    }

    /// Whether [`Rule::child_value`] is defined.
    pub fn has_child_value(&self) -> bool {
        if self.child_node_is_self {
            !self.node.borrow().is_undefined()
        } else {
            !self.child_node.is_undefined()
        }
    }

    /// Resume this rule with the child that has just stopped running: its
    /// node, and the `rule.child` / `rule.next` links a grammar reads from
    /// the resumed rule.
    ///
    /// Both links name the rule this one PUSHED, never whichever link of a
    /// replacement chain happened to pop. TypeScript assigns `rule.child`
    /// and `rule.next` once, in the push arm (`ts/src/rules.ts:665`,
    /// `:720`), and relinks neither when a descendant pops; Go does the
    /// same (`go/rule.go:1280`, `:1343`). The chain's later links are
    /// separate rule objects there, so the parent goes on reading the
    /// first. Here that rule has been dropped, so [`Rule::freeze_child`]
    /// captured it at its replace and this call leaves that capture alone.
    pub(crate) fn accept_child(&mut self, child: &Rule) {
        self.accept_child_node(child);
        // `child_record` is `None` only for a rule resumed by a child it
        // did not push. No parse-loop path reaches that today -- the one
        // `stack.push` is the push arm, which records the child first --
        // and falling back to the popping rule keeps the link honest
        // rather than leaving a stale one behind.
        self.child_rule = self.child_record.clone().or_else(|| Some(child.snapshot()));
        self.next_rule = self.child_rule.clone();
    }

    /// Let go of `child_node` while this rule sits on the parse stack, in
    /// the one case where holding it is not free.
    ///
    /// A pushed child starts out on its PARENT's node cell, and a child
    /// that never installs a cell of its own still has it when it closes
    /// -- `child_node_is_self`. [`Rule::accept_child_node`] then leaves
    /// `child_node` holding a second `Value` handle on the very container
    /// the next child will write into. Containers are copy-on-write
    /// (`value.rs`), so that second handle turns the next `push` or
    /// `insert` into a copy of the whole container, and a rule with one
    /// such child per element copies its accumulated node once per
    /// element: quadratic in the number of elements inside ONE rule,
    /// where TypeScript and Go, whose nodes are plain references, stay
    /// linear.
    ///
    /// Parking is invisible because every pop that resumes a parked rule
    /// OVERWRITES the field before anything reads that rule. There are
    /// four pops in `parser.rs`: the two close-phase pops and the
    /// forced-close loop hand the popped rule to `accept_child`, which
    /// writes both `child_node` and `child_node_is_self` outright,
    /// and nothing touches the rule in between. The fourth, the
    /// fixed-depth recovery pop in `attempt_recover`, does not, and that
    /// pop is taken only when `recover.pop_until_valid` is off -- which
    /// is why `parser.rs` parks only when that option is on.
    /// `pop_until_valid` is read through `&self` and cannot change
    /// during a parse, so a rule parks exactly when the pop that will
    /// resume it is one of the three that overwrite.
    ///
    /// The field itself is only ever read on the CURRENT rule in any
    /// case: by the built-ins, by grammar actions and by the plugin
    /// repos, all of which are handed the rule the loop is working on.
    /// Snapshots do not carry it (see its declaration) and
    /// `Context::rule_stack` is snapshots, so no callback can reach a
    /// stacked rule's copy either. That is the second line of defence,
    /// not the argument: the argument is the overwrite.
    pub(crate) fn park_child_node(&mut self) {
        if self.child_node_is_self {
            self.child_node = Value::Undefined;
        }
    }
}

impl fmt::Display for Rule {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "[Rule {}~{}]", self.name, self.i)
    }
}

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

    fn cell(text: &str) -> Rc<RefCell<Value>> {
        Rc::new(RefCell::new(Value::String(text.into())))
    }

    /// The first freeze after the push is the one that lands.
    ///
    /// `@node$` and its relatives REPLACE `rule.node` with a fresh cell
    /// rather than writing through it, so a link left at the push-time cell
    /// holds the value from before the child ran. Freezing at the moment the
    /// child stops being current is what makes the parent read what the
    /// child actually produced.
    #[test]
    fn freeze_child_takes_the_cell_the_child_ended_on() {
        let mut parent = Rule::new("parent", Value::Undefined);
        let mut child = Rule::new("child", Value::Undefined);
        parent.note_child_push(&child);

        child.node = cell("done");
        parent.freeze_child(&child);

        assert_eq!(
            *parent
                .child_cell
                .as_ref()
                .expect("a frozen child cell")
                .borrow(),
            Value::String("done".into()),
            "the freeze kept the push-time cell instead of the one the child ended on"
        );
    }

    /// A later link of a replacement chain must not overwrite the link.
    ///
    /// TypeScript and Go both keep `rule.child` on the rule the parent
    /// PUSHED, so the parent must go on reading the first link of the chain
    /// and not its tail.
    #[test]
    fn freeze_child_ignores_every_link_after_the_first() {
        let mut parent = Rule::new("parent", Value::Undefined);
        let mut pushed = Rule::new("pushed", Value::Undefined);
        parent.note_child_push(&pushed);

        pushed.node = cell("pushed rule");
        parent.freeze_child(&pushed);

        // `pushed` is replaced; the chain runs on and each link stops being
        // current in turn.
        let mut tail = Rule::new("tail", Value::Undefined);
        tail.node = cell("chain tail");
        parent.freeze_child(&tail);

        assert_eq!(
            *parent
                .child_cell
                .as_ref()
                .expect("a frozen child cell")
                .borrow(),
            Value::String("pushed rule".into()),
            "a later link of the replacement chain overwrote the child link"
        );
    }

    /// A callback cannot break the link by replacing the whole rule.
    ///
    /// An imperative action holds `&mut Rule`, so `*rule = Rule::new(..)` is
    /// legal and resets every field on the value, `i` included. While the
    /// link was keyed on an identity carried by the child, that assignment
    /// silently cost the parent its link and left it on the push-time cell.
    /// The flag lives on the parent, which is buried on the parse stack for
    /// the whole of the child's life and is never handed to a callback, so
    /// the freeze still lands and the parent sees what the replacement
    /// holds.
    #[test]
    fn a_callback_replacing_the_whole_child_rule_does_not_break_the_link() {
        let mut parent = Rule::new("parent", Value::Undefined);
        let mut child = Rule::new("child", Value::Undefined);
        parent.note_child_push(&child);

        // What an imperative action is able to do to the rule it is given.
        child = Rule::new("child", Value::Undefined);
        child.node = cell("done");

        parent.freeze_child(&child);

        assert_eq!(
            *parent
                .child_cell
                .as_ref()
                .expect("a frozen child cell")
                .borrow(),
            Value::String("done".into()),
            "replacing the rule value cost the parent its child link"
        );
    }
}