aozora 0.5.0

Aozora Bunko notation parser with incremental document snapshots
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
//! Body-keyword directive classifier.
//!
//! The `[#<keyword>]` body dispatcher: the `BODY_PATTERNS` table and
//! its Aho-Corasick DFA, `classify_annotation_body`, and the per-family
//! body parsers. Operates purely on the trimmed body string (no event
//! context); the forward-reference recognisers that need event context
//! live in the parent module. Extracted verbatim from the classify-stage
//! classifier.

use std::sync::OnceLock;

use aho_corasick::{AhoCorasick, AhoCorasickBuilder, Anchored, Input, MatchKind, StartKind};
use core::num::{NonZeroI8, NonZeroU8};

use crate::syntax::alloc::Allocator;
use crate::syntax::ast::Directive;
use crate::syntax::{
    AbsoluteSize, BOUTEN_KINDS, BlockStyles, BoutenKind, BoutenPosition, ColumnCount,
    DirectiveKind, EnclosureKind, FontShift, HeadingKind, HeadingStyle, IndentBlock, IndentLayout,
    Kumi, LineFormat, LineWidth, RegionClose, RegionFormat, SectionKind,
};

use super::EmitKind;

/// One row of [`BODY_PATTERNS`]: the byte sequence the DFA matches at
/// `body[0..match_end]`, and the family that decides what to emit.
#[derive(Clone, Copy)]
struct BodyPattern {
    needle: &'static str,
    family: BodyFamily,
}

/// Outcome category for an anchored AC match against the annotation
/// body. Each variant carries enough information to either emit a
/// constant `EmitKind` directly (when the family is exact-match) or to
/// dispatch to a small per-family parser for the body remainder.
#[derive(Clone, Copy)]
enum BodyFamily {
    // === Exact-match (body must equal needle) ===
    PageBreak,
    BodyEnd,     // 本文終わり
    ForcedBreak, // 改行
    SectionKaicho,
    SectionKaidan,
    SectionKaimihiraki,
    AlignEnd0,           // 地付き
    CenterMarker,        // ページの左右中央 / 中央揃え
    LineGothic,          // この行はゴシック体
    KeigakomiOpen,       // 罫囲み
    KeigakomiClose,      // 罫囲み終わり
    IndentBlock1,        // ここから字下げ → Indent { amount: 1 }
    PageCenterBlockOpen, // ここからページの左右中央 → Indent { amount: 0, center }
    AlignEndBlock0,      // ここから地付き → AlignEnd { offset: 0 }
    IndentBlockEnd,      // ここで字下げ終わり
    AlignEndBlockEnd,    // ここで地付き終わり
    LineWidthBlockEnd,   // ここで字詰め終わり
    TableBlockOpen,      // ここから表
    TableBlockEnd,       // ここで表終わり
    HorizontalBlockOpen, // ここから横組み
    HorizontalBlockEnd,  // ここで横組み終わり
    FontSizeBlockEnd,    // ここで大きな/小さな文字終わり
    ColumnsBlockEnd,     // ここで段組(み)終わり
    WarichuOpen,         // 割り注
    WarichuClose,        // 割り注終わり
    KaeritenSingle,      // body must equal one of 12 single-char marks
    KaeritenCompound,    // body must equal one of 8 compound marks

    // === Prefix-with-parameter (parse body[match_end..]) ===
    AlignEndParamPrefix,      // 地から → 地から{N}字上げ
    SashiePrefix,             // 挿絵( → 挿絵(X)入る
    IndentBlockParamPrefix,   // ここから → ここから{N}字下げ
    AlignEndBlockParamPrefix, // ここから地から → ここから地から{N}字上げ
    IndentKumiBlockEnd,       // ここで字下げ、 → ここで字下げ、{W}字組み終わり (#78)
    OkuriganaPrefix,          // ( → kaeriten okurigana (X)

    // === Body-equals-pattern then parse from body[0] ===
    IndentParamPrefix, // {digit} → {N}字下げ (re-parse from body[0])

    /// 傍点 / 傍線 range form (`傍点` / `白丸傍点` / `二重傍線` / `左に傍線`
    /// …, with optional `終わり` close suffix). The needle matches the
    /// variant (or the `左に` prefix); `parse_bouten_range_body` reads the
    /// full body for the kind, the `左に` position, and the `終わり` close.
    BoutenRange,

    /// 太字 / 斜体 range / block form (`太字` / `斜体` inline,
    /// `ここから太字` / `ここで斜体終わり` block, with `終わり` close). The
    /// needle anchors the body; `parse_emphasis_body` reads the full body
    /// for the kind, the block vs inline form, and open vs close.
    Emphasis,

    /// 小書き range form (`行右小書き` / `行左小書き`, with optional `終わり`
    /// close). The bare-range sibling of the forward `「X」は行右小書き`
    /// emphasis leaf; `parse_small_script_range_body` reads the full body
    /// for the 右/左 side and open vs close.
    SmallScriptRange,

    /// キャプション range / block (`キャプション` / `キャプション終わり` inline,
    /// `ここからキャプション` / `ここでキャプション終わり` block).
    /// `parse_caption_body` reads the full body for the block-vs-inline form
    /// and open vs close.
    CaptionRange,

    /// `ここから割り注` — block 割り注 opener (the multi-line region form;
    /// the inline `[#割り注]` is [`Self::WarichuOpen`]). → `Container(Warichu)`.
    WarichuBlockOpen,
    /// `ここで割り注終わり` — block 割り注 closer.
    WarichuBlockEnd,
    /// `天から` / `天より` → `天X{N}字下げ` — a single-line indent measured
    /// from the top margin; identical to a plain `{N}字下げ`, so it emits an
    /// `Indent` leaf. Also carries the both-margin compound
    /// (`天X{N}字下げ、地より{M}字上げで`) — see [`parse_both_margin_tail`].
    TopIndentPrefix,
    /// `改行天付き` → `改行天付き、折り返して{N}字下げ` — the ここから-less
    /// bare sibling of the top-flush hanging indent (amount 0 + wrap N).
    KaigyouTentsukiPrefix,

    /// Absolute font-size line directive (`大文字` … `特大文字、太字`). The
    /// needle anchors on the size keyword; `parse_line_font_size` re-reads the
    /// full body for the size and an optional `、太字` / `、ゴシック体` compound.
    LineFontSize,
}

/// How a [`BodyFamily`] consumes its DFA match: an `Exact` family must
/// equal the whole body, a `Prefix` family parses `body[match_end..]`,
/// and a `Reparse` family re-reads the full body from `body[0]`. Derived
/// 1:1 from the family so the exact-vs-not contract lives in one place
/// instead of being split across the per-arm `if exact` guards and a
/// parallel catch-all `None`.
#[derive(Clone, Copy, PartialEq, Eq)]
enum MatchMode {
    Exact,
    Prefix,
    Reparse,
}

/// The [`MatchMode`] of a [`BodyFamily`] (see [`MatchMode`]).
const fn body_family_mode(family: BodyFamily) -> MatchMode {
    match family {
        BodyFamily::PageBreak
        | BodyFamily::BodyEnd
        | BodyFamily::ForcedBreak
        | BodyFamily::SectionKaicho
        | BodyFamily::SectionKaidan
        | BodyFamily::SectionKaimihiraki
        | BodyFamily::AlignEnd0
        | BodyFamily::CenterMarker
        | BodyFamily::LineGothic
        | BodyFamily::KeigakomiOpen
        | BodyFamily::KeigakomiClose
        | BodyFamily::WarichuBlockOpen
        | BodyFamily::WarichuBlockEnd
        | BodyFamily::IndentBlock1
        | BodyFamily::PageCenterBlockOpen
        | BodyFamily::AlignEndBlock0
        | BodyFamily::AlignEndBlockEnd
        | BodyFamily::LineWidthBlockEnd
        | BodyFamily::TableBlockOpen
        | BodyFamily::TableBlockEnd
        | BodyFamily::HorizontalBlockOpen
        | BodyFamily::HorizontalBlockEnd
        | BodyFamily::FontSizeBlockEnd
        | BodyFamily::WarichuOpen
        | BodyFamily::WarichuClose
        | BodyFamily::KaeritenSingle
        | BodyFamily::KaeritenCompound => MatchMode::Exact,
        BodyFamily::AlignEndParamPrefix
        | BodyFamily::SashiePrefix
        | BodyFamily::IndentBlockParamPrefix
        | BodyFamily::AlignEndBlockParamPrefix
        | BodyFamily::IndentBlockEnd
        | BodyFamily::IndentKumiBlockEnd
        | BodyFamily::ColumnsBlockEnd
        | BodyFamily::OkuriganaPrefix
        | BodyFamily::TopIndentPrefix
        | BodyFamily::KaigyouTentsukiPrefix => MatchMode::Prefix,
        BodyFamily::IndentParamPrefix
        | BodyFamily::BoutenRange
        | BodyFamily::Emphasis
        | BodyFamily::SmallScriptRange
        | BodyFamily::CaptionRange
        | BodyFamily::LineFontSize => MatchMode::Reparse,
    }
}

/// Static pattern table. Order is irrelevant for behavior because the
/// DFA is built with [`MatchKind::LeftmostLongest`]: the longer needle
/// always wins (so `罫囲み終わり` beats `罫囲み`, `ここから字下げ` beats
/// `ここから`, `一レ` beats `一`, etc.). Keeping families together for
/// readability instead of sorting by length.
static BODY_PATTERNS: &[BodyPattern] = &[
    // Block container with full-keyword bodies.
    BodyPattern {
        needle: "ここから字下げ",
        family: BodyFamily::IndentBlock1,
    },
    BodyPattern {
        needle: "ここからページの左右中央",
        family: BodyFamily::PageCenterBlockOpen,
    },
    BodyPattern {
        needle: "ここから地付き",
        family: BodyFamily::AlignEndBlock0,
    },
    BodyPattern {
        needle: "ここから地から",
        family: BodyFamily::AlignEndBlockParamPrefix,
    },
    BodyPattern {
        needle: "ここから",
        family: BodyFamily::IndentBlockParamPrefix,
    },
    BodyPattern {
        needle: "ここで字下げ終わり",
        family: BodyFamily::IndentBlockEnd,
    },
    // The 字組み compound closer carries the width (`ここで字下げ、20字組み終わり`,
    // #78). Distinct from the generic `ここで字下げ終わり` above — the char after
    // `ここで字下げ` is `、` vs `終`, so the two needles never overlap.
    BodyPattern {
        needle: "ここで字下げ、",
        family: BodyFamily::IndentKumiBlockEnd,
    },
    BodyPattern {
        needle: "ここで地付き終わり",
        family: BodyFamily::AlignEndBlockEnd,
    },
    // The 字上げ block ([#ここから地から N 字上げ]) is closed by either
    // [#ここで字上げ終わり] or [#ここで地付き終わり] — both end the same
    // AlignEnd container. The open-side offset is authoritative when
    // pairing, so this closer reuses AlignEndBlockEnd.
    BodyPattern {
        needle: "ここで字上げ終わり",
        family: BodyFamily::AlignEndBlockEnd,
    },
    BodyPattern {
        needle: "ここで字詰め終わり",
        family: BodyFamily::LineWidthBlockEnd,
    },
    BodyPattern {
        needle: "ここから表",
        family: BodyFamily::TableBlockOpen,
    },
    BodyPattern {
        needle: "ここで表終わり",
        family: BodyFamily::TableBlockEnd,
    },
    BodyPattern {
        needle: "ここから横組み",
        family: BodyFamily::HorizontalBlockOpen,
    },
    BodyPattern {
        needle: "ここで横組み終わり",
        family: BodyFamily::HorizontalBlockEnd,
    },
    BodyPattern {
        needle: "ここで大きな文字終わり",
        family: BodyFamily::FontSizeBlockEnd,
    },
    BodyPattern {
        needle: "ここで小さな文字終わり",
        family: BodyFamily::FontSizeBlockEnd,
    },
    // Bare-range font-size close (ここ-less): [#大きな/小さな文字終わり],
    // the sibling of ここで…終わり. Reuses FontSizeBlockEnd; the open side
    // ([#{N}段階…文字]) routes through IndentParamPrefix (leading digit).
    // LeftmostLongest keeps ここで… winning over the bare needle.
    BodyPattern {
        needle: "大きな文字終わり",
        family: BodyFamily::FontSizeBlockEnd,
    },
    BodyPattern {
        needle: "小さな文字終わり",
        family: BodyFamily::FontSizeBlockEnd,
    },
    // Bare-range horizontal (ここ-less): [#横組み] … [#横組み終わり],
    // the sibling of ここから横組み / ここで横組み終わり. Same Horizontal
    // container; LeftmostLongest keeps 横組み終わり winning over 横組み, and
    // the exact-match guard rejects compounds like 横組みで、… (→ Unknown).
    BodyPattern {
        needle: "横組み",
        family: BodyFamily::HorizontalBlockOpen,
    },
    BodyPattern {
        needle: "横組み終わり",
        family: BodyFamily::HorizontalBlockEnd,
    },
    // 小書き range: [#行右小書き] … [#行右小書き終わり] (and 行左).
    // LeftmostLongest keeps 行右小書き終わり winning over 行右小書き.
    BodyPattern {
        needle: "行右小書き",
        family: BodyFamily::SmallScriptRange,
    },
    BodyPattern {
        needle: "行右小書き終わり",
        family: BodyFamily::SmallScriptRange,
    },
    BodyPattern {
        needle: "行左小書き",
        family: BodyFamily::SmallScriptRange,
    },
    BodyPattern {
        needle: "行左小書き終わり",
        family: BodyFamily::SmallScriptRange,
    },
    // キャプション range / block. LeftmostLongest keeps キャプション終わり
    // over キャプション, and ここからキャプション over ここから.
    BodyPattern {
        needle: "キャプション",
        family: BodyFamily::CaptionRange,
    },
    BodyPattern {
        needle: "キャプション終わり",
        family: BodyFamily::CaptionRange,
    },
    BodyPattern {
        needle: "ここからキャプション",
        family: BodyFamily::CaptionRange,
    },
    BodyPattern {
        needle: "ここでキャプション終わり",
        family: BodyFamily::CaptionRange,
    },
    // 縦中横 has no paired-range form (spec §6.3 defines only the forward-
    // reference `「X」は縦中横` leaf). A bare `[#縦中横]…[#縦中横終わり]` is a
    // non-canonical corpus convention that used to open a styling range,
    // contradicting the handbook's own tcy page; it now stays verbatim
    // `Directive{Unknown}` and never opens a block (#435).
    // Block 罫囲み (ここから form; the bare 罫囲み is also KeigakomiOpen).
    // LeftmostLongest keeps ここから罫囲み over the ここから indent prefix.
    BodyPattern {
        needle: "ここから罫囲み",
        family: BodyFamily::KeigakomiOpen,
    },
    BodyPattern {
        needle: "ここで罫囲み終わり",
        family: BodyFamily::KeigakomiClose,
    },
    // 表罫囲み / ミシン罫囲み (specific rule styles) are non-canonical and
    // corpus-vanishing (2 / 1 works); they are *not* folded onto Rule (which
    // would erase the rule-style spelling) — they decline to Directive{Unknown}
    // (lossless verbatim), the core recognising only the canonical 罫囲み (#435).
    // Block 割り注 (multi-line region; inline [#割り注] stays WarichuOpen).
    BodyPattern {
        needle: "ここから割り注",
        family: BodyFamily::WarichuBlockOpen,
    },
    BodyPattern {
        needle: "ここで割り注終わり",
        family: BodyFamily::WarichuBlockEnd,
    },
    // 天から{N}字下げ (single-line indent from the top) and the bare
    // 改行天付き、折り返して{N}字下げ hanging indent.
    BodyPattern {
        needle: "天から",
        family: BodyFamily::TopIndentPrefix,
    },
    // 天より — the alternate wording of 天から (both "measured from the top
    // margin"); attested only in the both-margin compound
    // (`天より{N}字下げ、地より{M}字上げで`). Routes through the same
    // TopIndentPrefix arm, which canonicalises to a plain `{N}字下げ` head.
    BodyPattern {
        needle: "天より",
        family: BodyFamily::TopIndentPrefix,
    },
    BodyPattern {
        needle: "改行天付き",
        family: BodyFamily::KaigyouTentsukiPrefix,
    },
    // Columns close: ここで[N]段組[み]終わり. Bare ここで mirrors the ここから
    // opener catch-all (IndentBlockParamPrefix); LeftmostLongest keeps every
    // longer ここで…終わり closer winning over it, and the handler validates the
    // 段組[み]終わり tail so non-columns ここで… bodies (and 、-joined compounds)
    // decline to Unknown.
    BodyPattern {
        needle: "ここで",
        family: BodyFamily::ColumnsBlockEnd,
    },
    // Section / page break (exact).
    BodyPattern {
        needle: "改ページ",
        family: BodyFamily::PageBreak,
    },
    // 改頁 — the kanji spelling of 改ページ (annotation/layout_1.html);
    // canonicalises to 改ページ on serialize.
    BodyPattern {
        needle: "改頁",
        family: BodyFamily::PageBreak,
    },
    BodyPattern {
        needle: "改丁",
        family: BodyFamily::SectionKaicho,
    },
    BodyPattern {
        needle: "改段",
        family: BodyFamily::SectionKaidan,
    },
    BodyPattern {
        needle: "改見開き",
        family: BodyFamily::SectionKaimihiraki,
    },
    // Structural markers (#78). `改行` is an exact match: a bare `[#改行]`
    // forced line break. The longer `改行天付き` needle wins under
    // LeftmostLongest for the hanging-indent form, and the Exact mode rejects
    // any `改行X` tail, so only the bare body reaches `ForcedBreak`.
    BodyPattern {
        needle: "本文終わり",
        family: BodyFamily::BodyEnd,
    },
    BodyPattern {
        needle: "改行",
        family: BodyFamily::ForcedBreak,
    },
    // Geographic alignment.
    BodyPattern {
        needle: "地から",
        family: BodyFamily::AlignEndParamPrefix,
    },
    // 地より — the alternate wording of 地から (both "measured from the
    // bottom margin"); `地よりN字上げ` parses identically and canonicalises
    // to 地から on serialize. LeftmostLongest keeps ここから地より winning.
    BodyPattern {
        needle: "地より",
        family: BodyFamily::AlignEndParamPrefix,
    },
    BodyPattern {
        needle: "ここから地より",
        family: BodyFamily::AlignEndBlockParamPrefix,
    },
    // 文末より / 行末より — raised alignment measured from the END of the
    // text (vs 地から = bottom margin). Same zero-width AlignEnd hook.
    // `この行は行末より…` needs its own anchored needle.
    BodyPattern {
        needle: "文末より",
        family: BodyFamily::AlignEndParamPrefix,
    },
    BodyPattern {
        needle: "行末より",
        family: BodyFamily::AlignEndParamPrefix,
    },
    BodyPattern {
        needle: "この行は行末より",
        family: BodyFamily::AlignEndParamPrefix,
    },
    BodyPattern {
        needle: "地付き",
        family: BodyFamily::AlignEnd0,
    },
    // 右寄せ / 地寄せ — wording variants of 地付き (inline-end alignment; in
    // horizontal render inline-end == the right edge). Canonicalize to 地付き.
    BodyPattern {
        needle: "右寄せ",
        family: BodyFamily::AlignEnd0,
    },
    BodyPattern {
        needle: "地寄せ",
        family: BodyFamily::AlignEnd0,
    },
    BodyPattern {
        needle: "ページの左右中央",
        family: BodyFamily::CenterMarker,
    },
    BodyPattern {
        needle: "中央揃え",
        family: BodyFamily::CenterMarker,
    },
    BodyPattern {
        needle: "この行はゴシック体",
        family: BodyFamily::LineGothic,
    },
    // Absolute font-size line directives (`大文字` … `特大文字、太字`). All four
    // size keywords anchor `LineFontSize`; `parse_line_font_size` re-reads the
    // body for the size and the optional `、太字` compound. `特大文字` is the
    // longest, so LeftmostLongest prefers it over `大文字`.
    BodyPattern {
        needle: "特大文字",
        family: BodyFamily::LineFontSize,
    },
    BodyPattern {
        needle: "大文字",
        family: BodyFamily::LineFontSize,
    },
    BodyPattern {
        needle: "中文字",
        family: BodyFamily::LineFontSize,
    },
    BodyPattern {
        needle: "小文字",
        family: BodyFamily::LineFontSize,
    },
    // Other inline / block. Needle is bare 挿絵 (not 挿絵() so the numbered
    // form 挿絵{N}(…) also reaches classify_sashie_body, which re-validates.
    BodyPattern {
        needle: "挿絵",
        family: BodyFamily::SashiePrefix,
    },
    BodyPattern {
        needle: "罫囲み終わり",
        family: BodyFamily::KeigakomiClose,
    },
    BodyPattern {
        needle: "罫囲み",
        family: BodyFamily::KeigakomiOpen,
    },
    BodyPattern {
        needle: "割り注終わり",
        family: BodyFamily::WarichuClose,
    },
    BodyPattern {
        needle: "割り注",
        family: BodyFamily::WarichuOpen,
    },
    // 傍点 / 傍線 range form openers (`[#傍点] … [#傍点終わり]`). One
    // needle per emphasis variant `bouten_kind_from_suffix` recognises,
    // plus the `左に` left-side prefix. LeftmostLongest disambiguates
    // overlaps (`二重丸傍点` vs `丸傍点`, `白丸傍点` vs `丸傍点`); the close
    // form (`…終わり`) matches the same variant needle as a prefix and is
    // re-parsed in full by `parse_bouten_range_body`.
    BodyPattern {
        needle: "左に",
        family: BodyFamily::BoutenRange,
    },
    BodyPattern {
        needle: "白ゴマ傍点",
        family: BodyFamily::BoutenRange,
    },
    BodyPattern {
        needle: "白丸傍点",
        family: BodyFamily::BoutenRange,
    },
    BodyPattern {
        needle: "二重丸傍点",
        family: BodyFamily::BoutenRange,
    },
    BodyPattern {
        needle: "蛇の目傍点",
        family: BodyFamily::BoutenRange,
    },
    BodyPattern {
        needle: "ばつ傍点",
        family: BodyFamily::BoutenRange,
    },
    BodyPattern {
        needle: "白三角傍点",
        family: BodyFamily::BoutenRange,
    },
    BodyPattern {
        needle: "黒三角傍点",
        family: BodyFamily::BoutenRange,
    },
    BodyPattern {
        needle: "丸傍点",
        family: BodyFamily::BoutenRange,
    },
    BodyPattern {
        needle: "傍点",
        family: BodyFamily::BoutenRange,
    },
    BodyPattern {
        needle: "二重傍線",
        family: BodyFamily::BoutenRange,
    },
    BodyPattern {
        needle: "鎖線",
        family: BodyFamily::BoutenRange,
    },
    BodyPattern {
        needle: "破線",
        family: BodyFamily::BoutenRange,
    },
    BodyPattern {
        needle: "波線",
        family: BodyFamily::BoutenRange,
    },
    BodyPattern {
        needle: "傍線",
        family: BodyFamily::BoutenRange,
    },
    // 太字 / 斜体 emphasis. The inline-range openers (`太字` / `斜体`)
    // also anchor their `…終わり` closers (re-parsed in full by
    // `parse_emphasis_body`); the block forms need their own anchors
    // (`ここから太字` beats the generic `ここから` via LeftmostLongest;
    // `ここで太字終わり` has no shorter generic anchor).
    BodyPattern {
        needle: "太字",
        family: BodyFamily::Emphasis,
    },
    BodyPattern {
        needle: "斜体",
        family: BodyFamily::Emphasis,
    },
    BodyPattern {
        needle: "ここから太字",
        family: BodyFamily::Emphasis,
    },
    BodyPattern {
        needle: "ここから斜体",
        family: BodyFamily::Emphasis,
    },
    BodyPattern {
        needle: "ここで太字終わり",
        family: BodyFamily::Emphasis,
    },
    BodyPattern {
        needle: "ここで斜体終わり",
        family: BodyFamily::Emphasis,
    },
    // ゴシック体 — a first-class gothic typeface, distinct from 太字 (#435):
    // the corpus uses ゴシック体 and 太字 in disjoint works and print sets a
    // gothic family apart from a bold weight, so the parser keeps its own
    // spelling and never folds it to 太字. The bare openers also anchor their
    // `…終わり` closers and the forward-reference `「X」はゴシック体` leaf.
    // ゴチック (1 corpus work) is *not* recognised — it declines to
    // Directive{Unknown} and a Tier1 lint suggests ゴシック体.
    BodyPattern {
        needle: "ゴシック体",
        family: BodyFamily::Emphasis,
    },
    BodyPattern {
        needle: "ここからゴシック体",
        family: BodyFamily::Emphasis,
    },
    BodyPattern {
        needle: "ここでゴシック体終わり",
        family: BodyFamily::Emphasis,
    },
    // Kaeriten okurigana opener (full-width left paren U+FF08).
    BodyPattern {
        needle: "",
        family: BodyFamily::OkuriganaPrefix,
    },
    // Kaeriten compound marks (6) — must precede the single forms in
    // the table only for documentation; LeftmostLongest does the
    // actual disambiguation (`一レ` 6 bytes > `一` 3 bytes).
    BodyPattern {
        needle: "一レ",
        family: BodyFamily::KaeritenCompound,
    },
    BodyPattern {
        needle: "上レ",
        family: BodyFamily::KaeritenCompound,
    },
    BodyPattern {
        needle: "下レ",
        family: BodyFamily::KaeritenCompound,
    },
    BodyPattern {
        needle: "中レ",
        family: BodyFamily::KaeritenCompound,
    },
    BodyPattern {
        needle: "二レ",
        family: BodyFamily::KaeritenCompound,
    },
    BodyPattern {
        needle: "三レ",
        family: BodyFamily::KaeritenCompound,
    },
    // Group + level combinations (上二 / 下二) — the outer 上中下 mark paired
    // with an inner order number, attested in kanbun corpus text.
    BodyPattern {
        needle: "上二",
        family: BodyFamily::KaeritenCompound,
    },
    BodyPattern {
        needle: "下二",
        family: BodyFamily::KaeritenCompound,
    },
    // Kaeriten single marks (12).
    BodyPattern {
        needle: "",
        family: BodyFamily::KaeritenSingle,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::KaeritenSingle,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::KaeritenSingle,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::KaeritenSingle,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::KaeritenSingle,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::KaeritenSingle,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::KaeritenSingle,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::KaeritenSingle,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::KaeritenSingle,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::KaeritenSingle,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::KaeritenSingle,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::KaeritenSingle,
    },
    // {N}字下げ — anchored on each digit (ASCII + full-width).
    BodyPattern {
        needle: "0",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "1",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "2",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "3",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "4",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "5",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "6",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "7",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "8",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "9",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::IndentParamPrefix,
    },
    BodyPattern {
        needle: "",
        family: BodyFamily::IndentParamPrefix,
    },
];

/// Build the annotation-body Aho-Corasick automaton from `BODY_PATTERNS`.
#[must_use]
pub(crate) fn build_body_dispatcher() -> AhoCorasick {
    AhoCorasickBuilder::new()
        .match_kind(MatchKind::LeftmostLongest)
        .start_kind(StartKind::Anchored)
        .build(BODY_PATTERNS.iter().map(|p| p.needle))
        .expect("BODY_PATTERNS is a static, non-empty, valid set")
}

/// One-time DFA build, amortised across the entire process lifetime.
/// Lookup cost is a few ns per call so the build pays back in under a
/// thousand annotations.
static BODY_DISPATCHER: OnceLock<AhoCorasick> = OnceLock::new();

fn body_dispatcher() -> &'static AhoCorasick {
    BODY_DISPATCHER.get_or_init(build_body_dispatcher)
}

/// Force the one-time Aho-Corasick DFA build now.
///
/// This is the bulk of parser boot cost. Idempotent — the `OnceLock` is
/// set at most once per process. `body_dispatcher` stays private; this
/// only triggers its init.
pub(crate) fn prewarm() -> &'static AhoCorasick {
    body_dispatcher()
}

/// Classify an input-editor note body into its [`DirectiveKind`], or
/// `None` if the body is not a recognised editorial note.
///
/// These are the corpus's two dominant editorial families:
/// - `ママ` / `「X」はママ` (and `ルビの「X」はママ`) — *sic*: X is reproduced
///   as it stands in the source. `底本のまま` ("as in the base text") is the
///   same kept-irregularity note. → [`DirectiveKind::Sic`].
/// - `…底本では…` (`「X」は底本では「Y」`, `「X」は底本では脱落`, …) — a
///   source-text divergence note. `…初出では…` ("in the first appearance …")
///   is the same shape against the first publication. →
///   [`DirectiveKind::BaseTextVariant`].
///
/// Called only at the tail of `RecogniseCtx::recognize_annotation`, after
/// every styling recogniser has declined, so a target-bearing form like
/// `「ママ」に傍点` has already been claimed as a Bouten and never reaches
/// here. The note does not restyle its target, so the caller leaves X in
/// the text and consumes only the bracket.
pub(super) fn editorial_note_kind(body: &str) -> Option<DirectiveKind> {
    if body == "ママ" || body.ends_with("はママ") || body == "底本のまま" {
        Some(DirectiveKind::Sic)
    } else if body.contains("底本では") || body.contains("初出では") {
        // Checked before EditorNote so a 底本 correction that happens to cite a
        // numbered note (`底本では…誤記。入力者注(6)`) stays a BaseTextVariant.
        Some(DirectiveKind::BaseTextVariant)
    } else if is_editor_note_body(body) {
        Some(DirectiveKind::EditorNote)
    } else if is_ruby_attached_body(body) {
        Some(DirectiveKind::RubyAttached)
    } else if is_ruby_retarget_body(body) {
        Some(DirectiveKind::RubyRetarget)
    } else if body == "左にルビ付き" {
        Some(DirectiveKind::RubyPairOpen)
    } else if is_ruby_pair_close_body(body) {
        Some(DirectiveKind::RubyPairClose)
    } else if body == "注記付き" || body == "左に注記付き" {
        Some(DirectiveKind::MarginNotePairOpen)
    } else if is_margin_note_pair_close_body(body) {
        Some(DirectiveKind::MarginNotePairClose)
    } else {
        None
    }
}

/// Whether `body` is exactly a ruby-presence note `「X」にルビ` (whole body, `X`
/// non-empty). A proofreading marker that the run `X` carries a ruby gloss.
fn is_ruby_attached_body(body: &str) -> bool {
    body.strip_prefix("")
        .and_then(|r| r.strip_suffix("」にルビ"))
        .is_some_and(|x| !x.is_empty())
}

/// Whether `body` is exactly a ruby-binding note `ルビは「X」にかかる` (whole body,
/// `X` non-empty). Records that a nearby ruby applies to the run `X`.
fn is_ruby_retarget_body(body: &str) -> bool {
    body.strip_prefix("ルビは「")
        .and_then(|r| r.strip_suffix("」にかかる"))
        .is_some_and(|x| !x.is_empty())
}

/// Whether `body` is a left-side-ruby span closer `左に「Y」のルビ付き終わり`
/// (whole body, reading `Y` non-empty). The matching opener is the fixed
/// `左にルビ付き` body.
fn is_ruby_pair_close_body(body: &str) -> bool {
    body.strip_prefix("左に「")
        .and_then(|r| r.strip_suffix("」のルビ付き終わり"))
        .is_some_and(|y| !y.is_empty())
}

/// Whether `body` is a margin-note span closer `「Y」の注記付き終わり` or
/// `左に「Y」の注記付き終わり` (whole body, note text `Y` non-empty). The matching
/// opener is the fixed `注記付き` / `左に注記付き` body. `Y` may contain a nested
/// `[#…]` gaiji, which the bracket pairer keeps inside the outer directive.
fn is_margin_note_pair_close_body(body: &str) -> bool {
    body.strip_prefix("左に「")
        .or_else(|| body.strip_prefix(""))
        .and_then(|r| r.strip_suffix("」の注記付き終わり"))
        .is_some_and(|y| !y.is_empty())
}

/// Whether `body` is exactly a numbered input-typist note `入力者注(N)` with an
/// ASCII-paren, ASCII-digit index — the corpus form. A compound note that
/// merely *contains* the phrase is excluded (the whole body must match).
fn is_editor_note_body(body: &str) -> bool {
    let Some(rest) = body.strip_prefix("入力者注(") else {
        return false;
    };
    let Some(digits) = rest.strip_suffix(')') else {
        return false;
    };
    !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
}

/// Single-pass classification of `body` (the trimmed bytes between
/// `[#` and `]`) into an `EmitKind` for body-only annotation
/// families. Returns `None` if the body matches no body-only family;
/// the caller then falls through to forward classifiers and finally
/// the `Directive{Unknown}` catch-all.
#[expect(
    clippy::too_many_lines,
    reason = "single match arm per BodyFamily — splitting would scatter \
              the dispatch logic and obscure the intentional 1:1 mapping"
)]
pub(super) fn classify_annotation_body(
    body: &str,
    alloc: &mut Allocator,
) -> Option<(EmitKind, Option<Directive>)> {
    if body.is_empty() {
        return None;
    }
    // Paired / block headings route through the container machinery as
    // `ContainerKind::Heading`. Tried before the body dispatcher: their
    // keywords overlap the `ここから…` / `…終わり` shapes but always carry a
    // `見出し` keyword, so a non-heading `ここから…` body falls through.
    if let Some(emit) = parse_heading_directive(body) {
        return Some((emit, None));
    }
    let dfa = body_dispatcher();
    let mat = dfa.find(Input::new(body).anchored(Anchored::Yes))?;
    let pat = BODY_PATTERNS[mat.pattern().as_usize()];
    let match_end = mat.end();
    let exact = match_end == body.len();
    // An exact-match family must consume the whole body; a prefix-only
    // DFA hit (`罫囲みfoo` matches the needle `罫囲み`) makes no claim.
    // Checking the mode once here lets every exact arm below drop its
    // `if exact` guard and replaces the parallel catch-all `None`.
    if body_family_mode(pat.family) == MatchMode::Exact && !exact {
        return None;
    }
    match pat.family {
        // ----- Exact-match families (must consume the entire body) -----
        BodyFamily::PageBreak => Some((EmitKind::Aozora(alloc.page_break()), None)),
        BodyFamily::BodyEnd => Some((EmitKind::Aozora(alloc.body_end()), None)),
        BodyFamily::ForcedBreak => Some((EmitKind::Aozora(alloc.forced_break()), None)),
        BodyFamily::SectionKaicho => Some((
            EmitKind::Aozora(alloc.section_break(SectionKind::Kaicho)),
            None,
        )),
        BodyFamily::SectionKaidan => Some((
            EmitKind::Aozora(alloc.section_break(SectionKind::Kaidan)),
            None,
        )),
        BodyFamily::SectionKaimihiraki => Some((
            EmitKind::Aozora(alloc.section_break(SectionKind::Kaimihiraki)),
            None,
        )),
        BodyFamily::AlignEnd0 => Some((
            EmitKind::Aozora(alloc.line(LineFormat::AlignEnd { offset: 0 })),
            None,
        )),
        BodyFamily::CenterMarker => {
            // ページの左右中央 (page centre) vs 中央揃え — a single-line
            // zero-width centring marker.
            let page = body == "ページの左右中央";
            Some((
                EmitKind::Aozora(alloc.line(LineFormat::Center { page })),
                None,
            ))
        }
        BodyFamily::LineGothic => Some((EmitKind::Aozora(alloc.line(LineFormat::Gothic)), None)),
        BodyFamily::LineFontSize => parse_line_font_size(body).map(|(size, bold)| {
            (
                EmitKind::Aozora(alloc.line(LineFormat::FontSizeAbsolute { size, bold })),
                None,
            )
        }),
        BodyFamily::KeigakomiOpen => Some((
            EmitKind::BlockOpen(RegionFormat::Framed(EnclosureKind::Rule)),
            None,
        )),
        BodyFamily::KeigakomiClose => Some((
            EmitKind::BlockClose(RegionClose::Framed(EnclosureKind::Rule)),
            None,
        )),
        BodyFamily::WarichuBlockOpen => Some((EmitKind::BlockOpen(RegionFormat::Warichu), None)),
        BodyFamily::WarichuBlockEnd => Some((EmitKind::BlockClose(RegionClose::Warichu), None)),
        BodyFamily::IndentBlock1 => Some((
            EmitKind::BlockOpen(RegionFormat::Indent(IndentBlock {
                amount: 1,
                wrap: None,
                center: false,
                layout: IndentLayout::None,
                styles: BlockStyles::EMPTY,
            })),
            None,
        )),
        // `ここからページの左右中央` — a page-centred block with no indent. Reuses
        // the indent-region model (`center` flag, `amount: 0`) so it pairs with
        // the shared `ここで字下げ終わり` close; `emit_indent_open` renders the
        // short opener back verbatim.
        BodyFamily::PageCenterBlockOpen => Some((
            EmitKind::BlockOpen(RegionFormat::Indent(IndentBlock {
                amount: 0,
                wrap: None,
                center: true,
                layout: IndentLayout::None,
                styles: BlockStyles::EMPTY,
            })),
            None,
        )),
        BodyFamily::AlignEndBlock0 => Some((
            EmitKind::BlockOpen(RegionFormat::AlignEnd { offset: 0 }),
            None,
        )),
        BodyFamily::IndentBlockEnd => {
            // ここで字下げ終わり, optionally with a redundant compound tail
            // `、{style}も終わり` (e.g. `…終わり、小さい活字も終わり`, #78). The
            // open payload is authoritative and the generic 字下げ終わり closes
            // the whole stack, so any `、…も終わり` tail maps to the same generic
            // close (it re-serializes to the canonical `ここで字下げ終わり`). A
            // non-`、` tail is not this family → decline to Unknown.
            let tail = &body[match_end..];
            (tail.is_empty() || (tail.starts_with('') && tail.ends_with("終わり"))).then_some((
                EmitKind::BlockClose(RegionClose::Indent { kumi_width: None }),
                None,
            ))
        }
        BodyFamily::AlignEndBlockEnd => Some((EmitKind::BlockClose(RegionClose::AlignEnd), None)),
        BodyFamily::LineWidthBlockEnd => {
            // The close marker carries no width; the open-side payload is
            // authoritative when pairing (mirrors the generic 字下げ終わり).
            Some((EmitKind::BlockClose(RegionClose::LineWidth), None))
        }
        BodyFamily::IndentKumiBlockEnd => {
            // ここで字下げ、{W}字組み終わり (#78) — the 字組み compound closer.
            // The close carries its own `W` so the marker round-trips byte-exact
            // (it pairs with the Indent open by family). Tolerate an optional
            // leading `{L}行`. Declines (→ Unknown) on any other shape.
            let rest = &body[match_end..];
            let rest = rest.split_once('').map_or(rest, |(_lines, after)| after);
            let (width, tail) = parse_decimal_u8_prefix(rest)?;
            (tail == "字組み終わり")
                .then(|| NonZeroU8::new(width))
                .flatten()
                .map(|w| {
                    (
                        EmitKind::BlockClose(RegionClose::Indent {
                            kumi_width: Some(LineWidth(w)),
                        }),
                        None,
                    )
                })
        }
        BodyFamily::TableBlockOpen => Some((EmitKind::BlockOpen(RegionFormat::Table), None)),
        BodyFamily::TableBlockEnd => Some((EmitKind::BlockClose(RegionClose::Table), None)),
        BodyFamily::HorizontalBlockOpen => {
            Some((EmitKind::BlockOpen(RegionFormat::Horizontal), None))
        }
        BodyFamily::HorizontalBlockEnd => {
            Some((EmitKind::BlockClose(RegionClose::Horizontal), None))
        }
        BodyFamily::FontSizeBlockEnd => {
            // The close marker carries only the direction (大きな / 小さな);
            // its magnitude is the open's. Matches both ここで…終わり and the
            // bare …終わり sibling, so key on the direction word.
            let larger = !body.contains("小さな");
            Some((EmitKind::BlockClose(RegionClose::FontSize { larger }), None))
        }
        BodyFamily::ColumnsBlockEnd => {
            // ここで[N]段組[み]終わり. An optional leading digit run (full/half-width)
            // is a redundant restatement of the open-side ColumnCount, which is
            // authoritative for pairing/render, so it is validated then DISCARDED
            // (RegionClose::Columns is a unit variant). Requires the exact 段組/段組み
            // tail; any other remainder (incl. 、-joined compounds) declines → Unknown.
            let rest = &body[match_end..]; // after ここで
            let rest = parse_decimal_u8_prefix(rest).map_or(rest, |(_n, tail)| tail);
            (rest == "段組終わり" || rest == "段組み終わり")
                .then_some((EmitKind::BlockClose(RegionClose::Columns), None))
        }
        BodyFamily::WarichuOpen => {
            let p = alloc.make_directive("[#割り注]", DirectiveKind::WarichuOpen);
            let node = alloc.annotation(p);
            // Re-build a payload for the segment-wrap case. The
            // Allocator interns by string content, so the second
            // call hits the dedup table; it pays at most a single
            // `Box<str>` clone, which is cheap relative
            // to the rare nested-Warichu shape this case targets.
            let p2 = alloc.make_directive("[#割り注]", DirectiveKind::WarichuOpen);
            Some((EmitKind::Aozora(node), Some(p2)))
        }
        BodyFamily::WarichuClose => {
            let p = alloc.make_directive("[#割り注終わり]", DirectiveKind::WarichuClose);
            let node = alloc.annotation(p);
            let p2 = alloc.make_directive("[#割り注終わり]", DirectiveKind::WarichuClose);
            Some((EmitKind::Aozora(node), Some(p2)))
        }
        BodyFamily::KaeritenSingle | BodyFamily::KaeritenCompound => {
            Some((EmitKind::Aozora(alloc.kaeriten(body)), None))
        }

        // ----- Prefix-with-parameter families -----
        BodyFamily::AlignEndParamPrefix => {
            // body == 地から/文末より/行末より{N}字上げ; remainder = body[match_end..].
            // The verb is the intransitive 字上がり as well as 字上げ, with an
            // optional 揃え suffix (`文末よりN字上げ揃え`).
            let rest = &body[match_end..];
            let (n, tail) = parse_decimal_u8_prefix(rest)?;
            (matches!(tail, "字上げ" | "字上がり" | "字上げ揃え" | "字上がり揃え") && n >= 1).then(
                || {
                    (
                        EmitKind::Aozora(alloc.line(LineFormat::AlignEnd { offset: n })),
                        None,
                    )
                },
            )
        }
        BodyFamily::TopIndentPrefix => {
            // body == 天から/天より{N}字下げ[、地より{M}字…] — single-line indent
            // from the top margin. The plain form is identical to a plain
            // {N}字下げ (Indent leaf); the both-margin compound also lifts M
            // chars off the foot edge.
            let rest = &body[match_end..];
            let (n, tail) = parse_decimal_u8_prefix(rest)?;
            if tail == "字下げ" && n >= 1 {
                Some((
                    EmitKind::Aozora(alloc.line(LineFormat::Indent {
                        amount: n,
                        end_offset: None,
                    })),
                    None,
                ))
            } else {
                parse_both_margin_tail(n, tail).map(|lf| (EmitKind::Aozora(alloc.line(lf)), None))
            }
        }
        BodyFamily::KaigyouTentsukiPrefix => {
            // body == 改行天付き、折り返して{N}字下げ — the ここから-less bare
            // top-flush hanging indent (amount 0 + wrap N), closed by the
            // shared 字下げ終わり.
            let rest = &body[match_end..];
            let after = rest.strip_prefix("、折り返して")?;
            let (m, tail) = parse_decimal_u8_prefix(after)?;
            (tail == "字下げ").then_some((
                EmitKind::BlockOpen(RegionFormat::Indent(IndentBlock {
                    amount: 0,
                    wrap: Some(m),
                    center: false,
                    layout: IndentLayout::None,
                    styles: BlockStyles::EMPTY,
                })),
                None,
            ))
        }
        BodyFamily::SashiePrefix => classify_sashie_body(body, alloc).map(|e| (e, None)),
        BodyFamily::IndentBlockParamPrefix => {
            // body == ここから{N}字下げ; remainder = body[match_end..]
            let rest = &body[match_end..];
            // ここから[改行]天付き、折り返して{M}字下げ — top-flush hanging
            // indent: the first line sits at the top margin (天付き = no
            // indent), wrapped continuation lines indent M. Models as the same
            // Indent container with amount 0 + wrap M, so it closes with the
            // shared 字下げ終わり (pairing is by family). Both the `改行天付き`
            // (corpus's most common top form) and the bare `天付き` spellings
            // appear; accept either before the leading-digit parse below.
            if let Some(after) = rest
                .strip_prefix("改行天付き、折り返して")
                .or_else(|| rest.strip_prefix("天付き、折り返して"))
            {
                let (m, tail2) = parse_decimal_u8_prefix(after)?;
                return (tail2 == "字下げ").then_some((
                    EmitKind::BlockOpen(RegionFormat::Indent(IndentBlock {
                        amount: 0,
                        wrap: Some(m),
                        center: false,
                        layout: IndentLayout::None,
                        styles: BlockStyles::EMPTY,
                    })),
                    None,
                ));
            }
            let (n, tail) = parse_decimal_u8_prefix(rest)?;
            if tail == "字下げ" {
                Some((
                    EmitKind::BlockOpen(RegionFormat::Indent(IndentBlock {
                        amount: n,
                        wrap: None,
                        center: false,
                        layout: IndentLayout::None,
                        styles: BlockStyles::EMPTY,
                    })),
                    None,
                ))
            } else if let Some(after) = tail.strip_prefix("字下げ、") {
                // ここから{N}字下げ、… compound (#78): the indent opener carries
                // a trailing `、`-separated stack of clauses — `折り返して{M}字下げ`
                // (wrap), `ページの左右中央`/`中央揃え` (center), `{W}字詰め` /
                // `{L}行{W}字組み[で]` (line layout), and the decorative styles
                // `ゴシック体` / `小さい活字` / `横書き` / `罫囲み`. Resolved as a
                // set in canonical-order-independent fashion; the whole compound
                // is declined to a generic Unknown if ANY clause is unrecognised
                // (lossless — e.g. `横組み右揃えで`, `数式`, embedded `「」は返り点`).
                // All forms still close with the shared 字下げ終わり (by family).
                parse_indent_compound(n, after)
                    .map(|block| (EmitKind::BlockOpen(RegionFormat::Indent(block)), None))
            } else if tail == "字詰め" {
                // ここから{N}字詰め — line-width container (字詰め): N
                // full-width characters per line. Shares the `ここから`
                // opener prefix with 字下げ; block-only, closes with
                // `ここで字詰め終わり`. `NonZero` folds the `N >= 1` guard.
                NonZeroU8::new(n).map(|w| {
                    (
                        EmitKind::BlockOpen(RegionFormat::LineWidth(LineWidth(w))),
                        None,
                    )
                })
            } else if tail == "段組" || tail == "段組み" {
                // ここから{N}段組(み) — multi-column container (段組): N
                // columns. Shares the `ここから` prefix; closes with
                // `ここで段組(み)終わり`. `NonZero` folds the `N >= 1` guard.
                NonZeroU8::new(n).map(|c| {
                    (
                        EmitKind::BlockOpen(RegionFormat::Columns(ColumnCount(c))),
                        None,
                    )
                })
            } else {
                // ここから{N}段階大きな/小さな文字 — block font-size shift.
                // Shares the `ここから` prefix; closes with the direction-only
                // `ここで大きな/小さな文字終わり`.
                font_size_block_open_steps(tail, n)
                    .and_then(NonZeroI8::new)
                    .map(|s| {
                        (
                            EmitKind::BlockOpen(RegionFormat::FontSize(FontShift(s))),
                            None,
                        )
                    })
            }
        }
        BodyFamily::AlignEndBlockParamPrefix => {
            // body == ここから地から{N}字上げ; remainder = body[match_end..]
            let rest = &body[match_end..];
            let (n, tail) = parse_decimal_u8_prefix(rest)?;
            (tail == "字上げ").then_some((
                EmitKind::BlockOpen(RegionFormat::AlignEnd { offset: n }),
                None,
            ))
        }
        BodyFamily::OkuriganaPrefix => {
            // The DFA matched `(` at body[0..3]. Defer to the same
            // parens-recognising helper as the legacy code so the
            // length / character-class invariants stay in one place.
            is_okurigana_body(body).then(|| (EmitKind::Aozora(alloc.kaeriten(body)), None))
        }
        BodyFamily::IndentParamPrefix => {
            // The DFA matched a single digit. Re-parse from body[0]
            // for full multi-digit support.
            let (n, tail) = parse_decimal_u8_prefix(body)?;
            if tail == "字下げ" && n >= 1 {
                Some((
                    EmitKind::Aozora(alloc.line(LineFormat::Indent {
                        amount: n,
                        end_offset: None,
                    })),
                    None,
                ))
            } else if let Some(lf) = parse_both_margin_tail(n, tail) {
                // Both-margin compound: [#{N}字下げ[て][、]地より{M}字(あき|上げ)[で|て]]
                // — a head indent plus a foot-edge lift on one single line.
                Some((EmitKind::Aozora(alloc.line(lf)), None))
            } else {
                // Bare-range font-size open: [#{N}段階大きな/小さな文字] —
                // the ここから-less sibling of the block opener, closed by the
                // bare [#大きな/小さな文字終わり]. Reuses the FontSize
                // region so render / pairing / serialize already apply.
                font_size_block_open_steps(tail, n)
                    .and_then(NonZeroI8::new)
                    .map(|s| {
                        (
                            EmitKind::BlockOpen(RegionFormat::FontSize(FontShift(s))),
                            None,
                        )
                    })
            }
        }
        BodyFamily::BoutenRange => {
            // `傍点` / `白丸傍点` / `二重傍線` / `左に傍線` … with an optional
            // `終わり` close suffix. Re-parse the full body for the variant,
            // the `左に` position, and open vs close.
            let (kind, position, is_close) = parse_bouten_range_body(body)?;
            Some((
                open_or_close(RegionFormat::Bouten { kind, position }, is_close),
                None,
            ))
        }
        BodyFamily::Emphasis => {
            // `太字` / `斜体` / `ここから太字` / `ここで斜体終わり` … —
            // re-parse the full body for the kind, the block vs inline
            // form, and open vs close.
            let (weight, padded, is_close) = parse_emphasis_body(body)?;
            let region = match weight {
                EmphasisWeight::Bold => RegionFormat::Bold { padded },
                EmphasisWeight::Gothic => RegionFormat::Gothic { padded },
                EmphasisWeight::Italic => RegionFormat::Italic { padded },
            };
            Some((open_or_close(region, is_close), None))
        }
        BodyFamily::SmallScriptRange => {
            // `行右小書き` / `行左小書き` with an optional `終わり` close.
            // Re-parse the full body so `行右小書きほげ` (needle prefix but
            // longer body) declines to Directive{Unknown}.
            let (side, is_close) = parse_small_script_range_body(body)?;
            Some((
                open_or_close(RegionFormat::SmallScript(side), is_close),
                None,
            ))
        }
        BodyFamily::CaptionRange => {
            // `キャプション` (inline) / `ここからキャプション` (block) with an
            // optional `終わり` close; re-parse the full body.
            let (padded, is_close) = parse_caption_body(body)?;
            Some((
                open_or_close(RegionFormat::Caption { padded }, is_close),
                None,
            ))
        }
    }
}

/// Wrap an open [`RegionFormat`] as the matching [`EmitKind`]: the open marker
/// carries the full payload; the close projects to its [`RegionClose`]
/// discriminant via [`RegionClose::of`] (the open side stays authoritative).
fn open_or_close(region: RegionFormat, is_close: bool) -> EmitKind {
    if is_close {
        EmitKind::BlockClose(RegionClose::of(region))
    } else {
        EmitKind::BlockOpen(region)
    }
}

/// Whether `body` is the okurigana shape `(X)` where X is a short
/// run of Japanese characters.
///
/// The length bound guards against accidentally claiming long
/// parenthesised glosses (which belong to the generic annotation
/// catch-all). 6 characters is the ~99th-percentile okurigana length
/// in Aozora corpora; anything longer is practically always editorial
/// prose rather than an inflection marker.
fn is_okurigana_body(body: &str) -> bool {
    let Some(inner) = body.strip_prefix('').and_then(|s| s.strip_suffix('')) else {
        return false;
    };
    // Byte-length prefilter: every accepted okurigana char is a CJK
    // glyph in {hiragana, katakana, half-width katakana, CJK unified}.
    // Hiragana/katakana/CJK are 3 bytes UTF-8; half-width katakana
    // is also 3 bytes (U+FF61..U+FF9F). So a 1..=6 char inner has
    // byte length in `3..=18`. Any inner outside that range cannot
    // satisfy `is_okurigana_char.all` and we skip the char decode.
    if !(3..=18).contains(&inner.len()) {
        return false;
    }
    // Single-pass fusion of `chars().count()` + `chars().all()`:
    // count and class-check in one walk, with early-out at >6 chars
    // or first non-conforming char. Replaces two iterations over
    // the same byte stream.
    let mut count = 0usize;
    for c in inner.chars() {
        count += 1;
        if count > 6 || !is_okurigana_char(c) {
            return false;
        }
    }
    count >= 1
}

/// Character class accepted inside okurigana parens: hiragana,
/// katakana (incl. half-width), CJK unified ideographs. Deliberately
/// narrower than "any non-whitespace" so editorial `(注)` or
/// punctuation-rich glosses fall through to the annotation path.
const fn is_okurigana_char(ch: char) -> bool {
    matches!(
        ch,
        '\u{3041}'..='\u{309F}'      // hiragana
        | '\u{30A0}'..='\u{30FF}'    // katakana
        | '\u{FF66}'..='\u{FF9F}'    // half-width katakana
        | '\u{4E00}'..='\u{9FFF}'    // CJK unified
        | '\u{3400}'..='\u{4DBF}'    // CJK ext A
        | '\u{F900}'..='\u{FAFF}'    // CJK compat
    )
}

/// Classify a `[#挿絵(file)入る]` sashie (illustration insert),
/// optionally bundling a caption: `[#挿絵(file)「caption」入る]`.
///
/// Called from [`classify_annotation_body`]'s `SashiePrefix` arm —
/// the AC has already verified the `挿絵(` prefix at body[0..9]; this
/// function captures the filename between `(` and `)`, an optional
/// `「caption」` (per <https://www.aozora.gr.jp/annotation/graphics.html>),
/// and confirms the trailing `入る` keyword. The caption is plain content,
/// rendered into `<figcaption>` (§8).
fn classify_sashie_body(body: &str, alloc: &mut Allocator) -> Option<EmitKind> {
    // `挿絵(file)入る` and the numbered `挿絵{N}(file)入る` (N a run of
    // half/full-width digits before the `(`). A description *before* 挿絵
    // (`女性と犬の挿絵(…)`, `「…」のキャプション付きの挿絵(…)`) is a separate,
    // unhandled form — it does not start with 挿絵, so the needle misses it.
    let after_kw = body.strip_prefix("挿絵")?;
    let paren = after_kw.find('')?;
    let number = if paren == 0 {
        None
    } else {
        let num = &after_kw[..paren];
        if num
            .chars()
            .all(|c| c.is_ascii_digit() || (''..='').contains(&c))
        {
            Some(num)
        } else {
            return None;
        }
    };
    let rest = &after_kw[paren + ''.len_utf8()..];
    // `)` is a full-width right parenthesis (U+FF09). Find its first
    // occurrence — corpus rarely nests `()` inside a filename.
    let close_off = rest.find('')?;
    // The `(…)` body is either a bare `file` or `file、横W×縦H` — split off
    // the optional pixel-size note so `file` stays a clean `<img src>` path
    // and the dimensions render as `width`/`height` (see render_node).
    let inside = &rest[..close_off];
    let (file, dimensions) = match inside.split_once('') {
        Some((f, dims)) if !f.is_empty() && !dims.is_empty() => (f, Some(dims)),
        _ => (inside, None),
    };
    if file.is_empty() {
        return None;
    }
    let tail = &rest[close_off + ''.len_utf8()..];
    // After `)` the tail is either the bare `入る` keyword or a bundled
    // `「caption」入る`. Any other shape declines (→ `Directive{Unknown}`).
    let caption = if tail == "入る" {
        None
    } else {
        let inner = tail
            .strip_prefix('')
            .and_then(|t| t.strip_suffix("」入る"))?;
        if inner.is_empty() {
            return None;
        }
        Some(alloc.content_plain(inner))
    };
    Some(EmitKind::Aozora(
        alloc.sashie(file, number, dimensions, caption),
    ))
}

/// Classify the *general* image form `[#<説明>(file[、横W×縦H])入る]`
/// (図 / 地図 / 口絵 / 表紙 / コンドル博士の図 / 神代文字ア …) per
/// <https://www.aozora.gr.jp/annotation/graphics.html>: the leading text
/// before `(` is the image's alt-description (the guide lists 図 / 地図 /
/// 絵 / 挿絵 / 表 / 写真 as type words but the description is free text),
/// the parenthesised part is `file` (+ optional `、横W×縦H` pixel size),
/// and `入る` closes it.
///
/// The keyword `挿絵` form is claimed earlier by [`classify_sashie_body`]
/// via its anchored needle; this is the fallback for every other
/// description, tried just before the `Directive{Unknown}` catch-all (it
/// has no prefix needle because the description is arbitrary). Returns
/// `None` for any body that is not a complete `<非空>(<file>)入る`.
pub(super) fn classify_general_image_body(body: &str, alloc: &mut Allocator) -> Option<EmitKind> {
    let middle = body.strip_suffix("入る")?;
    // The file spec `(file、横W×縦H)` is always the LAST paren group before
    // `入る`; use `rfind` so a description that itself embeds `(…)` (e.g.
    // `…(1798)…の図(fig.png、…)入る`) splits at the file paren, not the
    // first inner one. For a single-paren body `rfind == find`, so every
    // already-recognized body is byte-identical.
    let paren = middle.rfind('')?;
    let description = &middle[..paren];
    if description.is_empty() {
        return None;
    }
    let rest = &middle[paren + ''.len_utf8()..];
    let close_off = rest.find('')?;
    // Once `入る` is stripped, `)` must be the final byte — a trailing
    // `「caption」` or any other shape is not this form and declines.
    if close_off + ''.len_utf8() != rest.len() {
        return None;
    }
    let inside = &rest[..close_off];
    let (file, dimensions) = match inside.split_once('') {
        Some((f, dims)) if !f.is_empty() && !dims.is_empty() => (f, Some(dims)),
        _ => (inside, None),
    };
    if file.is_empty() {
        return None;
    }
    Some(EmitKind::Aozora(alloc.sashie_general(
        file,
        description,
        dimensions,
    )))
}

/// Parse a heading keyword into `(style, kind)`. An optional `同行`
/// (same-line) / `窓` (window) prefix selects the style; the remaining
/// `大 / 中 / 小見出し` selects the level. Shared by the forward-reference
/// hint (`「X」はSTYLEレベル見出し`) and the paired / block container forms
/// ([`parse_heading_directive`]).
///
/// `副見出し` is not a real annotation — it never occurs in the corpus — so
/// it matches nothing and the directive falls through to `Directive{Unknown}`.
/// The 同行 / 窓 styles cross with every level (`同行中見出し`, `窓小見出し`, …).
pub(super) fn parse_heading_keyword(s: &str) -> Option<(HeadingStyle, HeadingKind)> {
    let (style, rest) = strip_heading_style(s);
    let kind = match rest {
        "大見出し" => HeadingKind::Large,
        "中見出し" => HeadingKind::Medium,
        "小見出し" => HeadingKind::Small,
        _ => return None,
    };
    Some((style, kind))
}

/// Strip an optional 同行 / 窓 style prefix, returning the style and the
/// remaining `大/中/小見出(し)` stem. Shared by the strict open/hint parser
/// and the 送り仮名-tolerant close parser.
fn strip_heading_style(s: &str) -> (HeadingStyle, &str) {
    [
        ("同行", HeadingStyle::SameLine),
        ("", HeadingStyle::Window),
    ]
    .into_iter()
    .find_map(|(prefix, style)| s.strip_prefix(prefix).map(|rest| (style, rest)))
    .unwrap_or((HeadingStyle::Standard, s))
}

/// Heading level for a **close** marker only. Requires the full `見出し`
/// keyword — the 送り仮名-elided stem (`中見出` for `中見出し`) is **not**
/// recognised (#435): it declines to `Directive{Unknown}` (lossless) and a
/// Tier1 lint suggests the canonical `見出し終わり`, matching how the
/// structurally identical `字下げ` close okurigana is handled. A leveled close
/// serializes back to the canonical `見出し` keyword, so the round-trip is a
/// fixed point.
///
/// The bare `見出し` close (no 大/中/小 level) yields `None` for the level, but
/// only in [`HeadingStyle::Standard`]: a level-less serialize drops the style
/// word, so `窓見出し` etc. must stay Unknown to remain lossless.
fn parse_heading_close_level(s: &str) -> Option<(HeadingStyle, Option<HeadingKind>)> {
    let (style, rest) = strip_heading_style(s);
    let level = match rest {
        "大見出し" => Some(HeadingKind::Large),
        "中見出し" => Some(HeadingKind::Medium),
        "小見出し" => Some(HeadingKind::Small),
        // Bare close: no level. Style-less only — `窓見出し` etc. never occur, and
        // a level-less serialize drops style, so keep those Unknown (lossless).
        "見出し" if matches!(style, HeadingStyle::Standard) => None,
        _ => return None,
    };
    Some((style, level))
}

/// Recognise a **paired** (`STYLEレベル見出し` / `…見出し終わり`) or **block**
/// (`ここからSTYLEレベル見出し` / `ここでSTYLEレベル見出し終わり`) heading
/// directive body, returning the [`EmitKind`] to emit. These delimit their
/// content and route through the container pairing machinery as
/// [`RegionFormat::Heading`] (the counterpart of the `は`-form leaf heading).
///
/// A close carries its own level via [`RegionClose::Heading`] so the bare,
/// level-less `ここで見出し終わり` close can round-trip as `level: None` rather
/// than backfilling a lossy level from the open.
///
/// The forward-reference `「X」は…見出し` hint starts with `「`, so it never
/// matches here; a `ここから…` / `…終わり` body that is not a heading keyword
/// (e.g. `ここから2字下げ`) fails `parse_heading_keyword` and falls through to
/// the body dispatcher.
fn parse_heading_directive(body: &str) -> Option<EmitKind> {
    if let Some(rest) = body.strip_prefix("ここから") {
        let (style, level) = parse_heading_keyword(rest)?;
        return Some(EmitKind::BlockOpen(RegionFormat::Heading {
            level,
            style,
            padded: true,
        }));
    }
    if let Some(rest) = body.strip_prefix("ここで") {
        let (style, level) = parse_heading_close_level(rest.strip_suffix("終わり")?)?;
        return Some(EmitKind::BlockClose(RegionClose::Heading {
            level,
            style,
            padded: true,
        }));
    }
    if let Some(inner) = body.strip_suffix("終わり") {
        let (style, level) = parse_heading_close_level(inner)?;
        // The paired (`…終わり`, no `ここで`) close REQUIRES an explicit level: a
        // bare `見出し終わり` has neither the `ここで` block-scope signal nor a
        // level word, so it is too ambiguous to claim (0 corpus occ) and stays
        // Unknown. Only the `ここで` block close (below) admits the level-less form.
        let level = Some(level?);
        return Some(EmitKind::BlockClose(RegionClose::Heading {
            level,
            style,
            padded: false,
        }));
    }
    let (style, level) = parse_heading_keyword(body)?;
    Some(EmitKind::BlockOpen(RegionFormat::Heading {
        level,
        style,
        padded: false,
    }))
}

/// Signed stage count for a `ここから{N}段階大きな/小さな文字` block opener,
/// where `tail` is the body after the `ここから{N}` prefix and `magnitude`
/// is `N`. `大きな` → `+N`, `小さな` → `-N`; `None` for a zero/overflowing
/// magnitude or any other tail.
fn font_size_block_open_steps(tail: &str, magnitude: u8) -> Option<i8> {
    let steps = i8::try_from(magnitude).ok()?;
    if steps == 0 {
        return None;
    }
    match tail {
        "段階大きな文字" => Some(steps),
        "段階小さな文字" => Some(-steps),
        _ => None,
    }
}

/// Parse the line-layout clause after `ここから{N}字下げ、` (#78).
///
/// `after` is the text following `字下げ、` in the opener body. Two
/// corpus-attested forms:
///   * `{W}字詰め`          → [`IndentLayout::LineWidth`] (`W` chars per line)
///   * `{L}行{W}字組み[で]`  → [`IndentLayout::Kumi`] (`L` lines of `W` chars)
///
/// Returns `None` for anything else, so the bracket falls through to
/// `Directive{Unknown}` (round-trips byte-identical) instead of being
/// claimed in error.
/// Parse the `、`-separated clause stack following `ここから{N}字下げ、` into a
/// fully-resolved [`IndentBlock`] (#78 compound indent).
///
/// Each clause is resolved by [`resolve_indent_segment`]; the whole compound is
/// declined (`None` → generic `Unknown`, lossless) if any clause is unknown or
/// a clause repeats / conflicts. Clause order in the source is irrelevant — the
/// serializer re-emits a canonical order — so the same set always round-trips.
fn parse_indent_compound(amount: u8, after: &str) -> Option<IndentBlock> {
    let mut block = IndentBlock {
        amount,
        wrap: None,
        center: false,
        layout: IndentLayout::None,
        styles: BlockStyles::EMPTY,
    };
    for segment in after.split('') {
        resolve_indent_segment(segment, &mut block)?;
    }
    Some(block)
}

/// Fold one `字下げ、`-tail clause into `block`. Returns `None` (declining the
/// whole compound) for an unknown clause or one that conflicts with an already
/// resolved clause (a repeated wrap / layout / style — an ambiguous re-emission
/// must never arise).
fn resolve_indent_segment(segment: &str, block: &mut IndentBlock) -> Option<()> {
    // 折り返して{M}字下げ — hanging-indent continuation width.
    if let Some(rest) = segment.strip_prefix("折り返して") {
        let (m, tail) = parse_decimal_u8_prefix(rest)?;
        if tail != "字下げ" || block.wrap.is_some() {
            return None;
        }
        block.wrap = Some(m);
        return Some(());
    }
    // ページの左右中央[に] / 左右中央 / 中央揃え — page centring.
    if matches!(
        segment,
        "ページの左右中央" | "ページの左右中央に" | "左右中央" | "中央揃え"
    ) {
        if block.center {
            return None;
        }
        block.center = true;
        return Some(());
    }
    // {W}字詰め / {L}行{W}字組み[で] — secondary line layout.
    if let Some(layout) = parse_indent_line_layout(segment) {
        if !matches!(block.layout, IndentLayout::None) {
            return None;
        }
        block.layout = layout;
        return Some(());
    }
    // Decorative styles (co-applied, close with the generic 字下げ終わり).
    let styles = &mut block.styles;
    match segment {
        "ゴシック体" if !styles.gothic => styles.gothic = true,
        "横書き" | "横組み" if !styles.horizontal => styles.horizontal = true,
        "罫囲み" if !styles.framed => styles.framed = true,
        // 小さい活字 = one stage smaller (FontShift(-1)).
        "小さい活字" if styles.font.is_none() => {
            styles.font = Some(FontShift(NonZeroI8::new(-1)?));
        }
        _ => return None,
    }
    Some(())
}

/// Parse the both-margin compound tail of a head-indent directive into a
/// single-line [`LineFormat::Indent`] carrying both margins.
///
/// `amount` is the head indent already parsed from the digits before `字下げ`;
/// `tail` is the remainder starting at that `字下げ` verb. This one recogniser
/// covers the whole single-line family
/// (`[#{N}字下げ[て][、]地より{M}字(あき|上げ)[で|て]]`, and the
/// `天より`-headed variant via [`BodyFamily::TopIndentPrefix`]): the `字あき`
/// spelling is normalised to `字上げ` (both lift `M` full-width chars off the
/// foot edge), the `、` join is optional (a bare join also appears), and the
/// trailing `で` / `て` connective is optional. Returns `None` for a tail that
/// is not a well-formed both-margin compound, so the caller falls through to
/// the `Directive{Unknown}` catch-all (lossless). The region opener
/// `[#ここから…、地から…字下げ]` and the count-less `[#下げて、…]` never reach
/// here — the former routes through `IndentBlockParamPrefix`, the latter has no
/// anchored needle.
fn parse_both_margin_tail(amount: u8, tail: &str) -> Option<LineFormat> {
    // Head verb: 字下げ, with an optional て connective (字下げて).
    let rest = tail.strip_prefix("字下げ")?;
    let rest = rest.strip_prefix('').unwrap_or(rest);
    // Optional 、 between the head and bottom clauses (a bare join also appears).
    let rest = rest.strip_prefix('').unwrap_or(rest);
    // Bottom clause: 地より{M}字(あき|上げ)[で|て].
    let rest = rest.strip_prefix("地より")?;
    let (offset, rest) = parse_decimal_u8_prefix(rest)?;
    let rest = rest
        .strip_prefix("字あき")
        .or_else(|| rest.strip_prefix("字上げ"))?;
    // Optional trailing で / て connective; nothing else may follow.
    let rest = rest
        .strip_prefix('')
        .or_else(|| rest.strip_prefix(''))
        .unwrap_or(rest);
    (amount >= 1 && offset >= 1 && rest.is_empty()).then_some(LineFormat::Indent {
        amount,
        end_offset: Some(offset),
    })
}

fn parse_indent_line_layout(after: &str) -> Option<IndentLayout> {
    let (lead, rest) = parse_decimal_u8_prefix(after)?;
    let lead = NonZeroU8::new(lead)?; // folds the `lead >= 1` guard
    if rest == "字詰め" {
        return Some(IndentLayout::LineWidth(LineWidth(lead)));
    }
    // `{L}行{W}字組み[で]` — the leading number is the line count.
    let after_lines = rest.strip_prefix('')?;
    let (width, tail) = parse_decimal_u8_prefix(after_lines)?;
    let width = NonZeroU8::new(width)?; // folds the `width >= 1` guard
    if matches!(tail, "字組み" | "字組みで") {
        return Some(IndentLayout::Kumi(Kumi { lines: lead, width }));
    }
    None
}

/// Map the trailing keyword (after `に`) to a [`BoutenKind`].
///
/// The reverse of [`BoutenKind::keyword`], derived by walking the single
/// [`BOUTEN_KINDS`] source rather than a hand-maintained second table —
/// so a mark can never be recognised in the forward direction
/// (`keyword`) yet silently missed here. `×傍点` is accepted as an input
/// alias for the canonical ばつ傍点. Only the canonical mark-prefix keywords
/// (`白丸傍点`, …) are recognised; the non-canonical `傍点(白丸)` /
/// `傍点◎` marker-suffix spellings decline to `Directive{Unknown}` (#435),
/// served by a Tier1 lint suggesting the canonical keyword. Unknown suffixes
/// return `None`, letting the annotation fall through to the
/// `Directive{Unknown}` catch-all. Lookup is a short linear scan (14 entries,
/// dominated by the leading-byte mismatch on the first compare).
pub(super) fn bouten_kind_from_suffix(s: &str) -> Option<BoutenKind> {
    if s == "×傍点" {
        return Some(BoutenKind::Cross);
    }
    BOUTEN_KINDS.iter().copied().find(|k| k.keyword() == s)
}

/// Parse a 傍点/傍線 range-form body into `(kind, position, is_close)`.
/// Strips an optional `左に` left-side prefix and an optional `終わり`
/// close suffix; the remainder must be a [`bouten_kind_from_suffix`]
/// keyword (all fourteen kinds, incl. the rare 鎖線 / 破線 / 黒三角傍点).
/// Returns `None` (→ `Directive{Unknown}`) for any non-bouten body.
fn parse_bouten_range_body(body: &str) -> Option<(BoutenKind, BoutenPosition, bool)> {
    let (position, rest) = body
        .strip_prefix("左に")
        .map_or((BoutenPosition::Right, body), |r| (BoutenPosition::Left, r));
    let (is_close, kind_str) = rest
        .strip_suffix("終わり")
        .map_or((false, rest), |k| (true, k));
    let kind = bouten_kind_from_suffix(kind_str)?;
    Some((kind, position, is_close))
}

/// Parse a 小書き range body into `(side, is_close)`. `行右小書き` →
/// `BoutenPosition::Right`, `行左小書き` → `Left`; an optional `終わり`
/// suffix marks the close. Returns `None` (→ `Directive{Unknown}`) for any
/// other body, so a needle-prefix-but-longer body like `行右小書きほげ`
/// declines cleanly.
fn parse_small_script_range_body(body: &str) -> Option<(BoutenPosition, bool)> {
    let (is_close, core) = body
        .strip_suffix("終わり")
        .map_or((false, body), |c| (true, c));
    let side = match core {
        "行右小書き" => BoutenPosition::Right,
        "行左小書き" => BoutenPosition::Left,
        _ => return None,
    };
    Some((side, is_close))
}

/// Parse a 太字 / 斜体 range / block body into `(kind, block, is_close)`.
/// `block` is `true` for the `ここから…` / `ここで…終わり` block form,
/// `false` for the bare inline range `[#太字]…[#太字終わり]`. Returns
/// `None` (→ `Directive{Unknown}`) for any non-emphasis body.
/// Parse a キャプション range / block body into `(block, is_close)`.
/// `block` is `true` for `ここから…` / `ここで…終わり`, `false` for the bare
/// inline range `[#キャプション]…[#キャプション終わり]`.
fn parse_caption_body(body: &str) -> Option<(bool, bool)> {
    Some(match body {
        "キャプション" => (false, false),
        "キャプション終わり" => (false, true),
        "ここからキャプション" => (true, false),
        "ここでキャプション終わり" => (true, true),
        _ => return None,
    })
}

/// Parse an absolute font-size line body into `(size, bold)`. The body is a
/// size keyword (`特大文字` / `大文字` / `中文字` / `小文字`) optionally followed
/// by the `、太字` compound. Any other shape (a trailing run, an unknown
/// compound) declines to `Directive{Unknown}` — keeping `大文字下げ` and the like
/// out.
///
/// Only the `、太字` spelling is recognised: `bold` is a flag, not a spelling, so
/// serialization is canonical `、太字`; recognising the rarer `、ゴシック体`
/// (1 corpus occurrence) would lose its spelling and break the verbatim
/// round-trip — it stays `Directive{Unknown}` instead (mirrors §6.12 `この行は
/// ゴシック体` recognising a single spelling).
fn parse_line_font_size(body: &str) -> Option<(AbsoluteSize, bool)> {
    let (size, rest) = if let Some(r) = body.strip_prefix("特大文字") {
        (AbsoluteSize::ExtraLarge, r)
    } else if let Some(r) = body.strip_prefix("大文字") {
        (AbsoluteSize::Large, r)
    } else if let Some(r) = body.strip_prefix("中文字") {
        (AbsoluteSize::Medium, r)
    } else {
        let r = body.strip_prefix("小文字")?;
        (AbsoluteSize::Small, r)
    };
    let bold = match rest {
        "" => false,
        "、太字" => true,
        _ => return None,
    };
    Some((size, bold))
}

/// The weight / typeface axis of an emphasis range: 太字 / ゴシック体 / 斜体.
#[derive(Clone, Copy)]
pub(super) enum EmphasisWeight {
    /// 太字 (bold).
    Bold,
    /// ゴシック体 (gothic) — distinct from 太字 (#435).
    Gothic,
    /// 斜体 (italic).
    Italic,
}

/// Parse a 太字 / ゴシック体 / 斜体 range / block body into
/// `(weight, padded, is_close)`. `padded` is `true` for the `ここから…` /
/// `ここで…終わり` block form, `false` for the bare inline range. Returns `None`
/// (→ `Directive{Unknown}`) for any non-emphasis body. ゴシック体 keeps its own
/// [`EmphasisWeight::Gothic`] rather than folding to 太字 (#435); ゴチック is not
/// recognised (declines to Unknown + Tier1 → ゴシック体).
pub(super) fn parse_emphasis_body(body: &str) -> Option<(EmphasisWeight, bool, bool)> {
    use EmphasisWeight::{Bold, Gothic, Italic};
    Some(match body {
        "太字" => (Bold, false, false),
        "太字終わり" => (Bold, false, true),
        "ここから太字" => (Bold, true, false),
        "ここで太字終わり" => (Bold, true, true),
        "ゴシック体" => (Gothic, false, false),
        "ゴシック体終わり" => (Gothic, false, true),
        "ここからゴシック体" => (Gothic, true, false),
        "ここでゴシック体終わり" => (Gothic, true, true),
        "斜体" => (Italic, false, false),
        "斜体終わり" => (Italic, false, true),
        "ここから斜体" => (Italic, true, false),
        "ここで斜体終わり" => (Italic, true, true),
        _ => return None,
    })
}

/// Parse a leading run of ASCII / full-width decimal digits into a
/// [`u8`] and return the remainder slice.
///
/// Returns `None` if the leading char is not a digit, or if the value
/// overflows `u8` (> 255). `saturating_mul` / `saturating_add` during
/// accumulation keep the `u32` intermediate bounded, but the final
/// `try_from` enforces the `u8` range — a body like `300字下げ` fails
/// cleanly rather than wrapping to 44.
pub(super) fn parse_decimal_u8_prefix(s: &str) -> Option<(u8, &str)> {
    let mut value: u32 = 0;
    let mut consumed = 0;
    for (idx, ch) in s.char_indices() {
        let digit = match ch {
            '0'..='9' => Some(u32::from(ch) - u32::from('0')),
            ''..='' => Some(u32::from(ch) - u32::from('')),
            _ => None,
        };
        let Some(d) = digit else { break };
        value = value.saturating_mul(10).saturating_add(d);
        consumed = idx + ch.len_utf8();
    }
    if consumed == 0 {
        return None;
    }
    let value_u8 = u8::try_from(value).ok()?;
    Some((value_u8, &s[consumed..]))
}

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

    /// Every both-margin spelling attested in the corpus resolves to the same
    /// `Indent { amount, end_offset: Some }` leaf. `tail` is the remainder after
    /// the head digits (the `字下げ…` verb onward); `天より`/`天から` heads reach
    /// the helper with the same tail after the prefix + digits are stripped.
    #[test]
    fn corpus_both_margin_spellings_all_resolve() {
        for (amount, tail, want) in [
            // [#21字下げ、地より2字あきで] — 字あき normalises to 字上げ.
            (21, "字下げ、地より2字あきで", (21u8, 2u8)),
            // [#天より31字下げ、地より2字上げで] (post-prefix tail).
            (31, "字下げ、地より2字上げで", (31, 2)),
            // [#28字下げて、地より3字上げて] — て head + て tail.
            (28, "字下げて、地より3字上げて", (28, 3)),
            // [#20字下げて、地より1字あきで] — て head + 字あき + で.
            (20, "字下げて、地より1字あきで", (20, 1)),
            // [#天より32字下げて地より3字上げで] — BARE join (no 、).
            (32, "字下げて地より3字上げで", (32, 3)),
        ] {
            assert_eq!(
                parse_both_margin_tail(amount, tail),
                Some(LineFormat::Indent {
                    amount: want.0,
                    end_offset: Some(want.1),
                }),
                "both-margin tail {tail:?} must resolve",
            );
        }
    }

    /// Forms that are deliberately NOT both-margin decline (fall through to the
    /// `Directive{Unknown}` catch-all): a plain head indent with no bottom
    /// clause, and a bottom clause missing its explicit count.
    #[test]
    fn non_both_margin_tails_decline() {
        // Plain head indent, no 地より clause — the caller's plain arm owns this.
        assert_eq!(parse_both_margin_tail(2, "字下げ"), None);
        // Bottom clause without an explicit count declines.
        assert_eq!(parse_both_margin_tail(2, "字下げ、地より字上げで"), None);
        // A trailing remnant after the bottom clause declines (lossless).
        assert_eq!(parse_both_margin_tail(2, "字下げ、地より2字上げでX"), None);
    }
}

#[cfg(test)]
mod tests {
    //! Body-keyword classifier unit tests — one keyword-family boundary per
    //! assertion, driving the private per-family parsers directly (via
    //! `super::*`) and the `classify_annotation_body` dispatcher through a fresh
    //! `Allocator`. Each recogniser's *actual* classification (variant, offset,
    //! open/close, decision flag) is pinned, not merely that parsing succeeds.

    use core::ptr;

    use super::*;
    use crate::syntax::ast::Node;

    #[test]
    fn prewarm_initializes_the_body_dispatcher() {
        assert!(
            ptr::eq(prewarm(), body_dispatcher()),
            "prewarm must return the initialized dispatcher"
        );
    }

    // --- helpers over the classify dispatcher (payloads are Copy + 'static) ---

    /// Whether `classify_annotation_body` claims `body` at all.
    fn recognized(body: &str) -> bool {
        let mut alloc = Allocator::new();
        classify_annotation_body(body, &mut alloc).is_some()
    }

    /// The `EmitKind::Aozora` leaf node `body` classifies to (else `None`).
    fn line_node(body: &str) -> Option<Node> {
        let mut alloc = Allocator::new();
        match classify_annotation_body(body, &mut alloc) {
            Some((EmitKind::Aozora(node), _)) => Some(node),
            _ => None,
        }
    }

    /// The `RegionFormat` of the block opener `body` classifies to (else `None`).
    fn block_open(body: &str) -> Option<RegionFormat> {
        let mut alloc = Allocator::new();
        match classify_annotation_body(body, &mut alloc) {
            Some((EmitKind::BlockOpen(region), _)) => Some(region),
            _ => None,
        }
    }

    /// The `RegionClose` of the block closer `body` classifies to (else `None`).
    fn block_close(body: &str) -> Option<RegionClose> {
        let mut alloc = Allocator::new();
        match classify_annotation_body(body, &mut alloc) {
            Some((EmitKind::BlockClose(close), _)) => Some(close),
            _ => None,
        }
    }

    /// Resolved 挿絵 fields: `(file, number, dimensions, has_caption)`.
    fn sashie(body: &str) -> Option<(String, Option<String>, Option<String>, bool)> {
        let mut alloc = Allocator::new();
        let emit = classify_sashie_body(body, &mut alloc)?;
        let EmitKind::Aozora(node) = emit else {
            panic!("sashie must classify to an Aozora leaf")
        };
        let Node::Illustration(ill) = node else {
            panic!("sashie must classify to an Illustration, got {node:?}");
        };
        let store = alloc.store();
        Some((
            store.resolve_str(ill.file).to_owned(),
            ill.number.map(|s| store.resolve_str(s).to_owned()),
            ill.dimensions.map(|s| store.resolve_str(s).to_owned()),
            ill.caption.is_some(),
        ))
    }

    /// Resolved general-image fields: `(description, file, dimensions)`.
    fn general(body: &str) -> Option<(String, String, Option<String>)> {
        let mut alloc = Allocator::new();
        let emit = classify_general_image_body(body, &mut alloc)?;
        let EmitKind::Aozora(node) = emit else {
            panic!("general image must classify to an Aozora leaf")
        };
        let Node::Illustration(ill) = node else {
            panic!("general image must classify to an Illustration, got {node:?}");
        };
        let store = alloc.store();
        Some((
            store
                .resolve_str(
                    ill.description
                        .expect("general image carries a description"),
                )
                .to_owned(),
            store.resolve_str(ill.file).to_owned(),
            ill.dimensions.map(|s| store.resolve_str(s).to_owned()),
        ))
    }

    /// A comparable projection of `parse_emphasis_body` (the weight axis has no
    /// `PartialEq`): `(weight_tag, padded, is_close)` with `0=Bold 1=Gothic 2=Italic`.
    fn emphasis(body: &str) -> Option<(u8, bool, bool)> {
        parse_emphasis_body(body).map(|(weight, padded, is_close)| {
            let tag = match weight {
                EmphasisWeight::Bold => 0,
                EmphasisWeight::Gothic => 1,
                EmphasisWeight::Italic => 2,
            };
            (tag, padded, is_close)
        })
    }

    /// A pristine indent block for `resolve_indent_segment` folds.
    fn empty_indent_block() -> IndentBlock {
        IndentBlock {
            amount: 1,
            wrap: None,
            center: false,
            layout: IndentLayout::None,
            styles: BlockStyles::EMPTY,
        }
    }

    // ================= editorial_note_kind =================

    #[test]
    fn editorial_note_sic_family() {
        // Each `||` clause of the Sic guard on its own (kills the `||`->`&&`
        // swaps at 856): only the matching disjunct is true for each input.
        assert_eq!(editorial_note_kind("ママ"), Some(DirectiveKind::Sic));
        assert_eq!(editorial_note_kind("犬はママ"), Some(DirectiveKind::Sic));
        assert_eq!(editorial_note_kind("底本のまま"), Some(DirectiveKind::Sic));
    }

    #[test]
    fn editorial_note_base_text_variant() {
        // 底本では / 初出では each alone (kills the `||`->`&&` swap at 858).
        assert_eq!(
            editorial_note_kind("「犬」は底本では「猫」"),
            Some(DirectiveKind::BaseTextVariant)
        );
        assert_eq!(
            editorial_note_kind("初出では脱落"),
            Some(DirectiveKind::BaseTextVariant)
        );
    }

    #[test]
    fn editorial_note_pairs_and_editor() {
        assert_eq!(
            editorial_note_kind("入力者注(6)"),
            Some(DirectiveKind::EditorNote)
        );
        assert_eq!(
            editorial_note_kind("「犬」にルビ"),
            Some(DirectiveKind::RubyAttached)
        );
        assert_eq!(
            editorial_note_kind("ルビは「犬」にかかる"),
            Some(DirectiveKind::RubyRetarget)
        );
        assert_eq!(
            editorial_note_kind("左にルビ付き"),
            Some(DirectiveKind::RubyPairOpen)
        );
        assert_eq!(
            editorial_note_kind("左に「かい」のルビ付き終わり"),
            Some(DirectiveKind::RubyPairClose)
        );
        // Each 注記付き disjunct alone (kills the `||`->`&&` swap at 872).
        assert_eq!(
            editorial_note_kind("注記付き"),
            Some(DirectiveKind::MarginNotePairOpen)
        );
        assert_eq!(
            editorial_note_kind("左に注記付き"),
            Some(DirectiveKind::MarginNotePairOpen)
        );
        assert_eq!(
            editorial_note_kind("「かい」の注記付き終わり"),
            Some(DirectiveKind::MarginNotePairClose)
        );
        // A plain run is no editorial note.
        assert_eq!(editorial_note_kind("ただの文"), None);
    }

    // ================= ruby / editor note body predicates =================

    #[test]
    fn ruby_attached_body_boundary() {
        // true case (kills `-> false` and the deleted `!`) + empty-target false
        // case (kills the deleted `!` in the other direction).
        assert!(is_ruby_attached_body("「犬」にルビ"));
        assert!(!is_ruby_attached_body("「」にルビ"));
        assert!(!is_ruby_attached_body("にルビ"));
    }

    #[test]
    fn ruby_retarget_body_boundary() {
        assert!(is_ruby_retarget_body("ルビは「犬」にかかる"));
        assert!(!is_ruby_retarget_body("ルビは「」にかかる"));
        assert!(!is_ruby_retarget_body("犬にかかる"));
    }

    #[test]
    fn ruby_pair_close_body_boundary() {
        assert!(is_ruby_pair_close_body("左に「かい」のルビ付き終わり"));
        assert!(!is_ruby_pair_close_body("左に「」のルビ付き終わり"));
        assert!(!is_ruby_pair_close_body("「かい」のルビ付き終わり"));
    }

    #[test]
    fn margin_note_pair_close_body_boundary() {
        assert!(is_margin_note_pair_close_body("「かい」の注記付き終わり"));
        assert!(is_margin_note_pair_close_body(
            "左に「かい」の注記付き終わり"
        ));
        assert!(!is_margin_note_pair_close_body("「」の注記付き終わり"));
        assert!(!is_margin_note_pair_close_body("かいの注記付き終わり"));
    }

    #[test]
    fn editor_note_body_boundary() {
        // true (kills `-> false` and the deleted `!`).
        assert!(is_editor_note_body("入力者注(6)"));
        assert!(is_editor_note_body("入力者注(12)"));
        // empty digits (kills the `&&`->`||` swap: `||` would accept the
        // vacuous all-digit on an empty run).
        assert!(!is_editor_note_body("入力者注()"));
        // non-digit index and missing prefix decline.
        assert!(!is_editor_note_body("入力者注(a)"));
        assert!(!is_editor_note_body("他の注(6)"));
    }

    // ================= CenterMarker (classify_annotation_body) =================

    #[test]
    fn center_marker_page_flag() {
        // `page` distinguishes ページの左右中央 (true) from 中央揃え (false);
        // kills the `==`->`!=` swap at 992.
        assert_eq!(
            line_node("ページの左右中央"),
            Some(Node::Line(LineFormat::Center { page: true }))
        );
        assert_eq!(
            line_node("中央揃え"),
            Some(Node::Line(LineFormat::Center { page: false }))
        );
    }

    // ================= block-close tail validations =================

    #[test]
    fn indent_block_end_tail() {
        // Bare close is a generic Indent close.
        assert_eq!(
            block_close("ここで字下げ終わり"),
            Some(RegionClose::Indent { kumi_width: None })
        );
        // A `、`-tail that does NOT end in 終わり must decline (kills the
        // `&&`->`||` swap at 1051, which would accept it).
        assert!(!recognized("ここで字下げ終わり、活字"));
    }

    #[test]
    fn indent_kumi_block_end_width() {
        // The 字組み compound close carries its own width (kills the `==`->`!=`
        // swap at 1070, which would reject the exact tail).
        assert_eq!(
            block_close("ここで字下げ、20字組み終わり"),
            Some(RegionClose::Indent {
                kumi_width: Some(LineWidth(NonZeroU8::new(20).unwrap())),
            })
        );
    }

    #[test]
    fn font_size_block_end_direction() {
        // `larger` is derived from the 小さな substring (kills the deleted `!`
        // at 1094): 大きな -> true, 小さな -> false.
        assert_eq!(
            block_close("ここで大きな文字終わり"),
            Some(RegionClose::FontSize { larger: true })
        );
        assert_eq!(
            block_close("ここで小さな文字終わり"),
            Some(RegionClose::FontSize { larger: false })
        );
    }

    #[test]
    fn columns_block_end_tail() {
        // Both 段組 and 段組み close markers claim (kills the `||`->`&&` at 1105
        // — which accepts neither — and both `==`->`!=` swaps, each of which
        // rejects one spelling).
        assert_eq!(block_close("ここで2段組終わり"), Some(RegionClose::Columns));
        assert_eq!(
            block_close("ここで2段組み終わり"),
            Some(RegionClose::Columns)
        );
    }

    // ================= prefix-parameter families =================

    #[test]
    fn align_end_param_prefix_offset() {
        // 地から3字上げ -> AlignEnd{offset:3}; kills the `>=`->`<` swap at 1136.
        assert_eq!(
            line_node("地から3字上げ"),
            Some(Node::Line(LineFormat::AlignEnd { offset: 3 }))
        );
        // 0字上げ must decline: the `&&`->`||` swap (1136) and the `>=`->`<`
        // swap both wrongly accept it.
        assert!(!recognized("地から0字上げ"));
    }

    #[test]
    fn top_indent_prefix() {
        // 天から3字下げ -> Indent{amount:3}; kills the `==`->`!=` swap at 1152.
        assert_eq!(
            line_node("天から3字下げ"),
            Some(Node::Line(LineFormat::Indent {
                amount: 3,
                end_offset: None,
            }))
        );
        // 天から0字下げ declines: the `&&`->`||` and `>=`->`<` swaps (1152) both
        // wrongly accept the zero head-indent.
        assert!(!recognized("天から0字下げ"));
    }

    #[test]
    fn kaigyou_tentsuki_prefix() {
        // 改行天付き、折り返して3字下げ -> hanging indent (amount 0 + wrap 3);
        // kills the `==`->`!=` swap at 1171.
        assert_eq!(
            block_open("改行天付き、折り返して3字下げ"),
            Some(RegionFormat::Indent(IndentBlock {
                amount: 0,
                wrap: Some(3),
                center: false,
                layout: IndentLayout::None,
                styles: BlockStyles::EMPTY,
            }))
        );
    }

    #[test]
    fn indent_block_param_prefix_forms() {
        // ここから改行天付き、折り返して3字下げ (kills the `==`->`!=` swap at 1198).
        assert_eq!(
            block_open("ここから改行天付き、折り返して3字下げ"),
            Some(RegionFormat::Indent(IndentBlock {
                amount: 0,
                wrap: Some(3),
                center: false,
                layout: IndentLayout::None,
                styles: BlockStyles::EMPTY,
            }))
        );
        // ここから20字詰め -> LineWidth (kills the `==`->`!=` swap at 1233).
        assert_eq!(
            block_open("ここから20字詰め"),
            Some(RegionFormat::LineWidth(LineWidth(
                NonZeroU8::new(20).unwrap()
            )))
        );
        // ここから3段組 / ここから3段組み -> Columns (kills the `||`->`&&` at
        // 1244 and both `==`->`!=` swaps there).
        assert_eq!(
            block_open("ここから3段組"),
            Some(RegionFormat::Columns(ColumnCount(
                NonZeroU8::new(3).unwrap()
            )))
        );
        assert_eq!(
            block_open("ここから3段組み"),
            Some(RegionFormat::Columns(ColumnCount(
                NonZeroU8::new(3).unwrap()
            )))
        );
    }

    #[test]
    fn indent_param_prefix_line_form() {
        // 3字下げ -> line Indent{amount:3}.
        assert_eq!(
            line_node("3字下げ"),
            Some(Node::Line(LineFormat::Indent {
                amount: 3,
                end_offset: None,
            }))
        );
        // 0字下げ declines: the `&&`->`||` swap at 1287 wrongly accepts it.
        assert!(!recognized("0字下げ"));
    }

    // ================= is_okurigana_body / is_okurigana_char =================

    #[test]
    fn okurigana_body_length_and_class_boundary() {
        // A short kana run is okurigana.
        assert!(is_okurigana_body("(あ)"));
        // Exactly 6 chars still passes; the count check must be `> 6`, not
        // `== 6` or `>= 6` (kills both comparison swaps at 1397).
        assert!(is_okurigana_body("(あいうえおか)"));
        // A non-kana glyph inside makes it decline; the guard is
        // `count > 6 || !is_char`, not `&&` (kills the `||`->`&&` at 1397).
        assert!(!is_okurigana_body("(A)"));
        // Non-parenthesised body is never okurigana.
        assert!(!is_okurigana_body(""));
    }

    #[test]
    fn okurigana_char_class() {
        // hiragana / katakana / CJK accepted; ASCII + fullwidth latin rejected
        // (kills the `-> true` stub at 1409).
        assert!(is_okurigana_char(''));
        assert!(is_okurigana_char(''));
        assert!(is_okurigana_char(''));
        assert!(!is_okurigana_char('A'));
        assert!(!is_okurigana_char(''));
    }

    // ================= classify_sashie_body =================

    #[test]
    fn sashie_plain_bare() {
        // Bare 挿絵(file)入る (kills `-> None` at 1434, the `+`->`-` offset at
        // 1464, and the `==`->`!=` 入る check at 1467).
        assert_eq!(
            sashie("挿絵(fig.png)入る"),
            Some(("fig.png".to_owned(), None, None, false))
        );
    }

    #[test]
    fn sashie_numbered() {
        // 挿絵1(…)入る: the ASCII figure number survives (kills the `==`->`!=`
        // paren-position swap at 1436 and the `+`->`*` offset at 1449).
        assert_eq!(
            sashie("挿絵1(fig.png)入る"),
            Some(("fig.png".to_owned(), Some("1".to_owned()), None, false))
        );
        // Fullwidth digit number (kills the `||`->`&&` digit-class swap at 1442).
        assert_eq!(
            sashie("挿絵1(fig.png)入る"),
            Some(("fig.png".to_owned(), Some("".to_owned()), None, false))
        );
    }

    #[test]
    fn sashie_dimensions_split() {
        // file + dims split (kills the guard->true/false and both deleted `!`
        // at 1458: any of those would fold 、dims into the filename or drop dims).
        assert_eq!(
            sashie("挿絵(fig.png、横100×縦200)入る"),
            Some((
                "fig.png".to_owned(),
                None,
                Some("横100×縦200".to_owned()),
                false,
            ))
        );
        // Empty dims after 、 keeps the whole inner as the file, no dims (kills
        // the guard->true swap and the `&&`->`||` at 1458).
        assert_eq!(
            sashie("挿絵(fig.png、)入る"),
            Some(("fig.png、".to_owned(), None, None, false))
        );
    }

    // ================= classify_general_image_body =================

    #[test]
    fn general_image_plain() {
        // 地図(file)入る (kills `-> None` at 1499, the `+`->`-`/`+`->`*`
        // offset at 1510, and the `!=`->`==` / `+`->`-` / `+`->`*` tail-length
        // check at 1514 — each of which returns None or the wrong file here).
        assert_eq!(
            general("地図(map.png)入る"),
            Some(("地図".to_owned(), "map.png".to_owned(), None))
        );
    }

    #[test]
    fn general_image_dimensions_split() {
        // file + dims (kills the guard->false and both deleted `!` at 1519).
        assert_eq!(
            general("地図(map.png、横10×縦20)入る"),
            Some((
                "地図".to_owned(),
                "map.png".to_owned(),
                Some("横10×縦20".to_owned()),
            ))
        );
        // Empty dims after 、 keeps the whole inner as the file (kills the
        // guard->true swap and the `&&`->`||` at 1519).
        assert_eq!(
            general("地図(map.png、)入る"),
            Some(("地図".to_owned(), "map.png、".to_owned(), None))
        );
    }

    // ================= heading keyword parsers =================

    #[test]
    fn parse_heading_keyword_levels_and_styles() {
        // Each level arm (kills `-> None` at 1542 and the three deleted arms).
        assert_eq!(
            parse_heading_keyword("大見出し"),
            Some((HeadingStyle::Standard, HeadingKind::Large))
        );
        assert_eq!(
            parse_heading_keyword("中見出し"),
            Some((HeadingStyle::Standard, HeadingKind::Medium))
        );
        assert_eq!(
            parse_heading_keyword("小見出し"),
            Some((HeadingStyle::Standard, HeadingKind::Small))
        );
        // Style prefixes cross with levels.
        assert_eq!(
            parse_heading_keyword("同行中見出し"),
            Some((HeadingStyle::SameLine, HeadingKind::Medium))
        );
        assert_eq!(
            parse_heading_keyword("窓小見出し"),
            Some((HeadingStyle::Window, HeadingKind::Small))
        );
        // 副見出し is not a heading.
        assert_eq!(parse_heading_keyword("副見出し"), None);
    }

    #[test]
    fn strip_heading_style_prefixes() {
        // The returned stem must survive verbatim (kills both `-> (Default, "")`
        // and `-> (Default, "xyzzy")` stubs at 1556).
        assert_eq!(
            strip_heading_style("同行大見出し"),
            (HeadingStyle::SameLine, "大見出し")
        );
        assert_eq!(
            strip_heading_style("窓大見出し"),
            (HeadingStyle::Window, "大見出し")
        );
        assert_eq!(
            strip_heading_style("大見出し"),
            (HeadingStyle::Standard, "大見出し")
        );
    }

    #[test]
    fn parse_heading_close_levels() {
        // Leveled closes (kills `-> None` at 1577 and the three deleted arms).
        assert_eq!(
            parse_heading_close_level("大見出し"),
            Some((HeadingStyle::Standard, Some(HeadingKind::Large)))
        );
        assert_eq!(
            parse_heading_close_level("中見出し"),
            Some((HeadingStyle::Standard, Some(HeadingKind::Medium)))
        );
        assert_eq!(
            parse_heading_close_level("小見出し"),
            Some((HeadingStyle::Standard, Some(HeadingKind::Small)))
        );
        // Bare, style-less close: the guard must hold (kills the `-> false`
        // guard swap at 1584, which would decline it).
        assert_eq!(
            parse_heading_close_level("見出し"),
            Some((HeadingStyle::Standard, None))
        );
        // A styled bare close is NOT admitted (kills the `-> true` guard swap at
        // 1584, which would accept it).
        assert_eq!(parse_heading_close_level("窓見出し"), None);
    }

    // ================= font_size_block_open_steps =================

    #[test]
    fn font_size_block_open_steps_sign_and_zero() {
        // 大きな -> +N, 小さな -> -N (kills the two deleted arms, the deleted `-`
        // sign at 1653, and every `-> Some(_)/None` return stub).
        assert_eq!(font_size_block_open_steps("段階大きな文字", 3), Some(3));
        assert_eq!(font_size_block_open_steps("段階小さな文字", 3), Some(-3));
        // A zero magnitude declines; a non-zero one does not (kills the
        // `==`->`!=` swap at 1648).
        assert_eq!(font_size_block_open_steps("段階大きな文字", 0), None);
        // Unknown tail declines.
        assert_eq!(font_size_block_open_steps("段階中くらいな文字", 3), None);
    }

    // ================= resolve_indent_segment =================

    #[test]
    fn resolve_indent_wrap_clause() {
        // 折り返して{M}字下げ sets wrap.
        let mut block = empty_indent_block();
        assert_eq!(
            resolve_indent_segment("折り返して3字下げ", &mut block),
            Some(())
        );
        assert_eq!(block.wrap, Some(3));
        // A non-字下げ wrap tail declines (kills the `!=`->`==` swap at 1697 —
        // which would accept it — and, on a fresh block, the `||`->`&&` swap
        // there, which would also accept it).
        let mut fresh = empty_indent_block();
        assert_eq!(
            resolve_indent_segment("折り返して3字あき", &mut fresh),
            None
        );
        assert_eq!(fresh.wrap, None);
    }

    #[test]
    fn resolve_indent_layout_clause() {
        // {W}字詰め sets the line-width layout (kills the deleted `!` at 1716,
        // which would decline a first, un-set layout).
        let mut block = empty_indent_block();
        assert_eq!(resolve_indent_segment("5字詰め", &mut block), Some(()));
        assert_eq!(
            block.layout,
            IndentLayout::LineWidth(LineWidth(NonZeroU8::new(5).unwrap()))
        );
    }

    #[test]
    fn resolve_indent_style_clauses() {
        // Each decorative style folds once on a fresh block (kills the
        // guard->false swaps and the deleted `!`s: all would decline a first
        // application).
        let mut gothic = empty_indent_block();
        assert_eq!(resolve_indent_segment("ゴシック体", &mut gothic), Some(()));
        assert!(gothic.styles.gothic);

        let mut horizontal = empty_indent_block();
        assert_eq!(resolve_indent_segment("横書き", &mut horizontal), Some(()));
        assert!(horizontal.styles.horizontal);

        let mut framed = empty_indent_block();
        assert_eq!(resolve_indent_segment("罫囲み", &mut framed), Some(()));
        assert!(framed.styles.framed);

        // 小さい活字 = FontShift(-1); the sign must survive (kills the deleted
        // `-` at 1730 and the guard->false swap at 1729).
        let mut font = empty_indent_block();
        assert_eq!(resolve_indent_segment("小さい活字", &mut font), Some(()));
        assert_eq!(
            font.styles.font,
            Some(FontShift(NonZeroI8::new(-1).unwrap()))
        );
    }

    #[test]
    fn resolve_indent_repeated_style_declines() {
        // A repeated decoration conflicts and declines (kills the guard->true
        // swaps at 1725/1726/1727/1729, which would silently re-accept).
        let mut gothic = empty_indent_block();
        gothic.styles.gothic = true;
        assert_eq!(resolve_indent_segment("ゴシック体", &mut gothic), None);

        let mut horizontal = empty_indent_block();
        horizontal.styles.horizontal = true;
        assert_eq!(resolve_indent_segment("横書き", &mut horizontal), None);

        let mut framed = empty_indent_block();
        framed.styles.framed = true;
        assert_eq!(resolve_indent_segment("罫囲み", &mut framed), None);

        let mut font = empty_indent_block();
        font.styles.font = Some(FontShift(NonZeroI8::new(1).unwrap()));
        assert_eq!(resolve_indent_segment("小さい活字", &mut font), None);
    }

    // ================= parse_indent_line_layout =================

    #[test]
    fn parse_indent_line_layout_forms() {
        // {W}字詰め (kills `-> None` at 1777 and the `==`->`!=` swap at 1779).
        assert_eq!(
            parse_indent_line_layout("5字詰め"),
            Some(IndentLayout::LineWidth(LineWidth(
                NonZeroU8::new(5).unwrap()
            )))
        );
        // {L}行{W}字組み for coverage of the second branch.
        assert_eq!(
            parse_indent_line_layout("3行20字組み"),
            Some(IndentLayout::Kumi(Kumi {
                lines: NonZeroU8::new(3).unwrap(),
                width: NonZeroU8::new(20).unwrap(),
            }))
        );
        assert_eq!(parse_indent_line_layout("字詰め"), None);
    }

    // ================= parse_small_script_range_body =================

    #[test]
    fn parse_small_script_range_forms() {
        // Each side + open/close (kills `-> None`, the two `Some(Default, _)`
        // stubs, and both deleted arms at 1834-1839).
        assert_eq!(
            parse_small_script_range_body("行右小書き"),
            Some((BoutenPosition::Right, false))
        );
        assert_eq!(
            parse_small_script_range_body("行右小書き終わり"),
            Some((BoutenPosition::Right, true))
        );
        assert_eq!(
            parse_small_script_range_body("行左小書き"),
            Some((BoutenPosition::Left, false))
        );
        assert_eq!(
            parse_small_script_range_body("行左小書き終わり"),
            Some((BoutenPosition::Left, true))
        );
        assert_eq!(parse_small_script_range_body("行右小書きほげ"), None);
    }

    // ================= parse_caption_body =================

    #[test]
    fn parse_caption_forms() {
        // All four (block, close) combinations (kills `-> None`, every
        // `Some((_, _))` stub, and all four deleted arms at 1853-1857).
        assert_eq!(parse_caption_body("キャプション"), Some((false, false)));
        assert_eq!(
            parse_caption_body("キャプション終わり"),
            Some((false, true))
        );
        assert_eq!(
            parse_caption_body("ここからキャプション"),
            Some((true, false))
        );
        assert_eq!(
            parse_caption_body("ここでキャプション終わり"),
            Some((true, true))
        );
        assert_eq!(parse_caption_body("ほげ"), None);
    }

    // ================= parse_line_font_size =================

    #[test]
    fn parse_line_font_size_forms() {
        // Size + optional 、太字 (kills `-> None` at 1874 and the two deleted
        // bold-match arms at 1886/1887).
        assert_eq!(
            parse_line_font_size("大文字"),
            Some((AbsoluteSize::Large, false))
        );
        assert_eq!(
            parse_line_font_size("大文字、太字"),
            Some((AbsoluteSize::Large, true))
        );
        assert_eq!(
            parse_line_font_size("特大文字"),
            Some((AbsoluteSize::ExtraLarge, false))
        );
        assert_eq!(
            parse_line_font_size("小文字、太字"),
            Some((AbsoluteSize::Small, true))
        );
        // A trailing run that is neither "" nor 、太字 declines.
        assert_eq!(parse_line_font_size("大文字げ"), None);
    }

    // ================= parse_emphasis_body =================

    #[test]
    fn parse_emphasis_all_arms() {
        // Every (weight, padded, is_close) arm (kills all twelve deleted arms at
        // 1913-1924).
        assert_eq!(emphasis("太字"), Some((0, false, false)));
        assert_eq!(emphasis("太字終わり"), Some((0, false, true)));
        assert_eq!(emphasis("ここから太字"), Some((0, true, false)));
        assert_eq!(emphasis("ここで太字終わり"), Some((0, true, true)));
        assert_eq!(emphasis("ゴシック体"), Some((1, false, false)));
        assert_eq!(emphasis("ゴシック体終わり"), Some((1, false, true)));
        assert_eq!(emphasis("ここからゴシック体"), Some((1, true, false)));
        assert_eq!(emphasis("ここでゴシック体終わり"), Some((1, true, true)));
        assert_eq!(emphasis("斜体"), Some((2, false, false)));
        assert_eq!(emphasis("斜体終わり"), Some((2, false, true)));
        assert_eq!(emphasis("ここから斜体"), Some((2, true, false)));
        assert_eq!(emphasis("ここで斜体終わり"), Some((2, true, true)));
        assert_eq!(emphasis("ほげ"), None);
    }

    // ================= parse_decimal_u8_prefix =================

    #[test]
    fn parse_decimal_u8_prefix_fullwidth_digit_value() {
        // A fullwidth multi-digit run decodes by subtraction of '0', not
        // division (kills the `-`->`/` swap at 1943): 34, not 11.
        assert_eq!(parse_decimal_u8_prefix("34字下げ"), Some((34, "字下げ")));
        // ASCII sibling for coverage.
        assert_eq!(parse_decimal_u8_prefix("34字下げ"), Some((34, "字下げ")));
        // Non-digit lead and overflow both decline.
        assert_eq!(parse_decimal_u8_prefix("字下げ"), None);
        assert_eq!(parse_decimal_u8_prefix("300字下げ"), None);
    }
}