lindera-dependency 7.3.0

Japanese bunsetsu dependency analysis for Lindera.
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
//! The schema of a dictionary: which feature column holds what, and which
//! morphemes of a bunsetsu are its head and its function word.
//!
//! The feature columns of a morpheme differ from one dictionary to another,
//! and so do the parts of speech that make a function word or a symbol.
//! What needs them (the chunker, the parser, the output) takes them from a
//! [`Schema`], and holds none of its own. A schema is data: a second
//! dictionary is a second value, not a second code path.
//!
//! # The head and the function word
//!
//! The head (主辞) of a bunsetsu is its last content word, and the function
//! word (機能語) its last particle or auxiliary. [`Schema::positions`] finds
//! them as `findHead` of CaboCha does:
//!
//! 1. Both start at the first morpheme of the bunsetsu. A space
//!    ([`is_space`]) is passed over everywhere: it is no word.
//! 2. From the left, a morpheme that matches one of
//!    [`Schema::function_words`] becomes the function word; a morpheme that
//!    matches none of them, none of [`Schema::not_heads`], and is not a
//!    symbol becomes the head.
//! 3. A head after the function word becomes the function word too.
//!
//! That is [`HeadRule::FunctionWordsApart`], the rule of the schemas of this
//! crate and of CaboCha for IPA. A model converted from CaboCha's for JUMAN
//! has [`HeadRule::LastWords`] in [`Schema::head_rule`]: the function word
//! is the last morpheme that is not a symbol, and the head the last one
//! that is neither a symbol nor one of [`Schema::not_heads`]. One morpheme
//! can be both, and nothing is moved afterwards.
//!
//! # Examples
//!
//! ```
//! use lindera_dependency::Schema;
//! use lindera_dependency::lattice::LatticeMorpheme;
//!
//! let schema = Schema::ipadic();
//! // 読ん / で / いる / 。
//! let bunsetsu = [
//!     LatticeMorpheme::new("読ん", "動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン"),
//!     LatticeMorpheme::new("で", "助詞,接続助詞,*,*,*,*,で,デ,デ"),
//!     LatticeMorpheme::new("いる", "動詞,非自立,*,*,一段,基本形,いる,イル,イル"),
//!     LatticeMorpheme::new("。", "記号,句点,*,*,*,*,。,。,。"),
//! ];
//! assert_eq!(schema.positions(&bunsetsu), Some((0, 2)));
//! assert!(schema.is_period(&bunsetsu[3]));
//! ```

mod normalization;
mod pattern;
mod symbols;

use std::borrow::Cow;
use std::ops::Range;

pub use normalization::Normalization;
pub use pattern::Pattern;
pub use symbols::{Marks, SurfaceRule, Symbols};

use crate::bytes::{Reader, push_u32};
use crate::error::{Error, Result};
use crate::morpheme::{Mark, Morpheme, is_sentence_end, is_space, marks, sentence_end};

/// The value that stands for a column the schema does not have, in its
/// bytes.
const NO_COLUMN: u32 = u32::MAX;

/// The first version of the model file whose schema holds
/// [`Schema::head_fallback`] and [`Schema::sentence_split`]. In an older
/// file the schema ends with the rule of the head: the head word of a
/// bunsetsu without one is its first morpheme, and a text is not cut into
/// sentences.
const HEAD_FALLBACK_VERSION: u32 = 4;

/// The value of a feature column that holds nothing.
const EMPTY: &str = "*";

/// The characters of the commas, in full width and half width.
/// The formal nouns of the schema of UniDic, by their 語彙素: こと, ため,
/// もの, 際, うえ and ところ.
const FORMAL_NOUNS: [&str; 6] = ["事", "為", "物", "際", "上", "所"];

const COMMAS: &str = "、,,";

/// The characters of the periods, in full width and half width.
const PERIODS: &str = "。..";

/// The opening brackets: those CaboCha knows, and the other ones of the
/// same blocks.
pub(crate) const OPEN_BRACKETS: &str = "(([[{{「『【〔〈《〘〚‘“";

/// The closing brackets, in the order of [`OPEN_BRACKETS`].
pub(crate) const CLOSE_BRACKETS: &str = "))]]}}」』】〕〉》〙〛’”";

/// The other characters of symbols: the punctuation of ASCII with its
/// full-width forms, and marks of Japanese text. `%` and `°` are not here:
/// they are units, which UD Japanese-GSD has as the content head (50 / %).
const OTHER_SYMBOLS: &str = concat!(
    "!\"#$&'*+-/:;<=>?@\\^_`|~",
    "!"#$&'*+-/:;<=>?@\^_`|~",
    "・…‥―—–‐〜※♪★☆○●◎◇◆□■△▲▽▼→←↑↓≠",
);

/// How [`Schema::positions`] finds the head word and the function word of
/// a bunsetsu: the two forms `findHead` of CaboCha has.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HeadRule {
    /// A morpheme that matches one of [`Schema::function_words`] is the
    /// function word, and is not the head; a morpheme that matches none of
    /// them, none of [`Schema::not_heads`], and is not a symbol is the
    /// head. The last of each is taken, and a head after the function word
    /// becomes the function word too. The rule of the schemas of this
    /// crate, and CaboCha's for IPA and for UniDic.
    #[default]
    FunctionWordsApart,
    /// The function word is the last morpheme that is not a symbol, and the
    /// head the last morpheme that is neither a symbol nor one of
    /// [`Schema::not_heads`]. The two are found apart: one morpheme can be
    /// both, as the noun of a bunsetsu of one noun, and nothing is moved
    /// afterwards. [`Schema::function_words`] is not read. CaboCha's rule
    /// for JUMAN, whose function word is the last morpheme that is not a
    /// 特殊, and whose head is the last that is not a 特殊, a 助詞 or a
    /// 接尾辞.
    LastWords,
}

impl HeadRule {
    /// The two rules with their codes in a model file.
    const ALL: [(HeadRule, u8); 2] = [(HeadRule::FunctionWordsApart, 0), (HeadRule::LastWords, 1)];

    /// The code of the rule in the bytes of a model.
    fn code(self) -> u8 {
        Self::ALL
            .iter()
            .find(|(rule, _)| *rule == self)
            .map_or(0, |(_, code)| *code)
    }

    /// The rule of a code, or the error of a code that is not one.
    fn from_code(code: u8) -> Result<Self> {
        Self::ALL
            .iter()
            .find(|(_, one)| *one == code)
            .map(|(rule, _)| *rule)
            .ok_or_else(|| Error::Schema(format!("{code} is not the code of a rule of the head")))
    }
}

/// What [`Schema::positions`] takes as the head word of a bunsetsu in which
/// no morpheme can be one: a bunsetsu of function words, of what is not a
/// head, and of symbols, such as 「 / する / 」 / と.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HeadFallback {
    /// The first morpheme, whatever it is: the bracket of 「 / する / 」 / と.
    /// What CaboCha does, so the schema of a model converted from CaboCha
    /// has it, and so does the schema of a model file older than the
    /// version 4, which has no such setting. A space is passed over, as
    /// everywhere: CaboCha is never given one.
    #[default]
    FirstMorpheme,
    /// The first morpheme that is a word: not a comma, a period or a
    /// bracket, not a space, and not a particle. する in 「 / する / 」 / と,
    /// and the first letter of a word that a dictionary cuts into letters
    /// it calls symbols (S / i / r / i / の). The first morpheme when the
    /// bunsetsu has no such word. The schemas of this crate have it.
    FirstWord,
}

impl HeadFallback {
    /// The two settings with their codes in a model file.
    const ALL: [(HeadFallback, u8); 2] = [
        (HeadFallback::FirstMorpheme, 0),
        (HeadFallback::FirstWord, 1),
    ];

    /// The code of the setting in the bytes of a model.
    fn code(self) -> u8 {
        Self::ALL
            .iter()
            .find(|(fallback, _)| *fallback == self)
            .map_or(0, |(_, code)| *code)
    }

    /// The setting of a code, or the error of a code that is not one.
    fn from_code(code: u8) -> Result<Self> {
        Self::ALL
            .iter()
            .find(|(_, one)| *one == code)
            .map(|(fallback, _)| *fallback)
            .ok_or_else(|| {
                Error::Schema(format!(
                    "{code} is not the code of a head word for a bunsetsu without one"
                ))
            })
    }
}

/// Whether a chunker cuts a text into sentences before it gives it to its
/// model.
///
/// A chunker is trained on sentences, and no sentence of its training data
/// goes on after its period: what a model does with the word after a `。` in
/// the middle of a text is not learned. With [`SentenceSplit::AfterEnds`]
/// the chunker cuts the text there and gives each part to the model on its
/// own ([`Schema::sentence_starts`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SentenceSplit {
    /// The text is one sentence for the model. What CaboCha does, so the
    /// schema of a model converted from CaboCha has it, and so does the
    /// schema of a model file older than the version 4, which has no such
    /// setting.
    #[default]
    None,
    /// The text is cut after each sentence end
    /// ([`is_sentence_end`]). The schemas
    /// of this crate have it.
    AfterEnds,
}

impl SentenceSplit {
    /// The two settings with their codes in a model file.
    const ALL: [(SentenceSplit, u8); 2] = [(SentenceSplit::None, 0), (SentenceSplit::AfterEnds, 1)];

    /// The code of the setting in the bytes of a model.
    fn code(self) -> u8 {
        Self::ALL
            .iter()
            .find(|(split, _)| *split == self)
            .map_or(0, |(_, code)| *code)
    }

    /// The setting of a code, or the error of a code that is not one.
    fn from_code(code: u8) -> Result<Self> {
        Self::ALL
            .iter()
            .find(|(_, one)| *one == code)
            .map(|(split, _)| *split)
            .ok_or_else(|| {
                Error::Schema(format!(
                    "{code} is not the code of a way to cut a text into sentences"
                ))
            })
    }
}

/// What is known about a dictionary: which feature columns hold the part of
/// speech, the conjugation and the base form, which morphemes are function
/// words, which are not heads, and which are symbols.
///
/// Columns are counted from 0, as [`Morpheme::feature`]
/// does.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Schema {
    /// The columns of the part of speech, from the coarsest level to the
    /// finest.
    pub part_of_speech: Range<usize>,
    /// The column of the conjugation type, when the dictionary has one.
    pub conjugation_type: Option<usize>,
    /// The column of the conjugation form, when the dictionary has one.
    pub conjugation_form: Option<usize>,
    /// The column of the base form, when the dictionary has one.
    pub base_form: Option<usize>,
    /// The function words: a morpheme that matches one of these patterns.
    pub function_words: Vec<Pattern>,
    /// What is neither a function word nor a head, besides the symbols: a
    /// morpheme that matches one of these patterns.
    pub not_heads: Vec<Pattern>,
    /// The particles: a morpheme that matches one of these patterns. The
    /// parser names the particles of a bunsetsu in its features.
    pub particles: Vec<Pattern>,
    /// The function words that tell by their surface how a bunsetsu
    /// modifies another: a morpheme that matches one of these patterns. For
    /// a bunsetsu that ends in any other word, the parser takes the
    /// conjugation form or the part of speech in its place.
    pub lexicalized: Vec<Pattern>,
    /// How symbols, punctuation and brackets are recognized.
    pub symbols: Symbols,
    /// What a surface is replaced by before it becomes a feature or is
    /// matched as a mark: empty for the schemas of this crate, the table
    /// of CaboCha for a model converted from CaboCha.
    pub normalization: Normalization,
    /// How the head word and the function word of a bunsetsu are found.
    pub head_rule: HeadRule,
    /// The head word of a bunsetsu in which the rule finds none.
    pub head_fallback: HeadFallback,
    /// Whether a chunker cuts a text into sentences before it gives it to
    /// its model.
    pub sentence_split: SentenceSplit,
}

impl Schema {
    /// The names of the dictionaries [`Schema::for_dictionary`] has a schema
    /// for.
    pub const DICTIONARIES: [&'static str; 4] = ["ipadic", "unidic", "unidic-cwj", "unidic-csj"];

    /// The schema of IPADIC.
    ///
    /// The columns are four levels of part of speech, then the conjugation
    /// type, the conjugation form and the base form.
    ///
    /// The function words are those of CaboCha for IPA (助詞, 助動詞,
    /// 動詞,非自立, 動詞,接尾, 形容詞,非自立, 形容詞,接尾), and する and
    /// できる (動詞,自立): in 利用 / し / た the head is 利用. At the start
    /// of a bunsetsu する is still the head, since the head starts there
    /// and only a head moves it.
    ///
    /// Besides the symbols, these are not heads: 名詞,非自立 (こと, の,
    /// よう); the suffixes 的 (名詞,接尾,形容動詞語幹) and さ
    /// (名詞,接尾,特殊), so that in 基本 / 的 / に the head is 基本; and a
    /// 動詞,自立 right after a 助詞, which is part of a compound function
    /// word (こと / に / なっ / た, かも / しれ / ない).
    ///
    /// With CaboCha's rule alone the head is the content head of UD
    /// Japanese-GSD in 85% of the bunsetsu; with these additions, in 97%.
    /// The README of the crate has the measurement.
    ///
    /// A symbol is a morpheme of the part of speech 記号, or one whose
    /// surface is made of symbol characters only: IPADIC has no half-width
    /// symbols, and gives `,` as 名詞,サ変接続.
    ///
    /// The particles are 助詞, and the function words taken by their
    /// surface are 助詞, 副詞, 連体詞 and 接続詞, as in CaboCha.
    ///
    /// # Returns
    ///
    /// The schema.
    pub fn ipadic() -> Self {
        Self {
            part_of_speech: 0..4,
            conjugation_type: Some(4),
            conjugation_form: Some(5),
            base_form: Some(6),
            function_words: vec![
                Pattern::new(&["助詞"]),
                Pattern::new(&["助動詞"]),
                Pattern::new(&["動詞", "非自立"]),
                Pattern::new(&["動詞", "接尾"]),
                Pattern::new(&["形容詞", "非自立"]),
                Pattern::new(&["形容詞", "接尾"]),
                Pattern::new(&["動詞", "自立"]).with_base_forms(&["する", "できる", "出来る"]),
            ],
            not_heads: vec![
                Pattern::new(&["名詞", "非自立"]),
                Pattern::new(&["名詞", "接尾", "形容動詞語幹"]),
                Pattern::new(&["名詞", "接尾", "特殊"]),
                Pattern::new(&["動詞", "自立"]).after(Pattern::new(&["助詞"])),
            ],
            particles: vec![Pattern::new(&["助詞"])],
            lexicalized: vec![
                Pattern::new(&["助詞"]),
                Pattern::new(&["副詞"]),
                Pattern::new(&["連体詞"]),
                Pattern::new(&["接続詞"]),
            ],
            symbols: Symbols {
                others: Marks::new(&[&["記号"]], OTHER_SYMBOLS),
                commas: Marks::new(&[&["記号", "読点"]], COMMAS),
                periods: Marks::new(&[&["記号", "句点"]], PERIODS),
                open_brackets: Marks::new(&[&["記号", "括弧開"]], OPEN_BRACKETS),
                close_brackets: Marks::new(&[&["記号", "括弧閉"]], CLOSE_BRACKETS),
                surface: SurfaceRule::EveryCharacter,
            },
            normalization: Normalization::default(),
            head_rule: HeadRule::FunctionWordsApart,
            head_fallback: HeadFallback::FirstWord,
            sentence_split: SentenceSplit::AfterEnds,
        }
    }

    /// The schema of UniDic: of `unidic` (unidic-mecab 2.1.2), `unidic-cwj`
    /// and `unidic-csj`, whose first columns are the same.
    ///
    /// The columns are 品詞大分類, 中分類, 小分類, 細分類, 活用型, 活用形,
    /// 語彙素読み and 語彙素; the base form is the 語彙素, so that of こと
    /// is 事.
    ///
    /// The function words are the ones of the pattern CaboCha has for
    /// UniDic (a particle, an auxiliary, and a suffix that is not nominal),
    /// and a verb or an adjective that is 非自立可能. What is not a head
    /// was measured on UD Japanese-GSD, as for IPADIC:
    ///
    /// * a verb right after に, と or を (に / よっ / て, と / し / て),
    /// * a 助動詞語幹 (よう, そう, みたい),
    /// * a formal noun (こと, ため, もの, 際, うえ, ところ) right after a
    ///   verb, an auxiliary or an adjective,
    /// * a nominal suffix right after an adjective (大き / さ).
    ///
    /// UniDic tags a letter of the Latin alphabet 記号,文字, and it is a
    /// symbol here as any 記号 is.
    ///
    /// # Returns
    ///
    /// The schema.
    ///
    /// # Examples
    ///
    /// ```
    /// use lindera_dependency::Schema;
    /// use lindera_dependency::lattice::LatticeMorpheme;
    ///
    /// let schema = Schema::unidic();
    /// // 利用 / する / こと / が
    /// let bunsetsu = [
    ///     LatticeMorpheme::new("利用", "名詞,普通名詞,サ変可能,*,*,*,リヨウ,利用"),
    ///     LatticeMorpheme::new("する", "動詞,非自立可能,*,*,サ行変格,連体形-一般,スル,為る"),
    ///     LatticeMorpheme::new("こと", "名詞,普通名詞,一般,*,*,*,コト,事"),
    ///     LatticeMorpheme::new("が", "助詞,格助詞,*,*,*,*,ガ,が"),
    /// ];
    /// // The head word is 利用 and the function word が: する is 非自立可能,
    /// // and こと is a formal noun after a verb.
    /// assert_eq!(schema.positions(&bunsetsu), Some((0, 3)));
    /// ```
    pub fn unidic() -> Self {
        Self {
            part_of_speech: 0..4,
            conjugation_type: Some(4),
            conjugation_form: Some(5),
            base_form: Some(7),
            function_words: vec![
                Pattern::new(&["助詞"]),
                Pattern::new(&["助動詞"]),
                Pattern::new(&["接尾辞", "形容詞的"]),
                Pattern::new(&["接尾辞", "形状詞的"]),
                Pattern::new(&["接尾辞", "動詞的"]),
                Pattern::new(&["動詞", "非自立可能"]),
                Pattern::new(&["形容詞", "非自立可能"]),
            ],
            not_heads: vec![
                Pattern::new(&["動詞"])
                    .after(Pattern::new(&["助詞"]).with_base_forms(&["に", "と", "を"])),
                Pattern::new(&["形状詞", "助動詞語幹"]),
                Pattern::new(&["名詞", "助動詞語幹"]),
                Pattern::new(&["名詞", "普通名詞"])
                    .with_base_forms(&FORMAL_NOUNS)
                    .after(Pattern::new(&["動詞"])),
                Pattern::new(&["名詞", "普通名詞"])
                    .with_base_forms(&FORMAL_NOUNS)
                    .after(Pattern::new(&["助動詞"])),
                Pattern::new(&["名詞", "普通名詞"])
                    .with_base_forms(&FORMAL_NOUNS)
                    .after(Pattern::new(&["形容詞"])),
                Pattern::new(&["接尾辞", "名詞的"]).after(Pattern::new(&["形容詞"])),
            ],
            particles: vec![Pattern::new(&["助詞"])],
            lexicalized: vec![
                Pattern::new(&["助詞"]),
                Pattern::new(&["副詞"]),
                Pattern::new(&["連体詞"]),
                Pattern::new(&["接続詞"]),
            ],
            symbols: Symbols {
                others: Marks::new(&[&["空白"], &["補助記号"], &["記号"]], ""),
                commas: Marks::new(&[&["補助記号", "読点"]], COMMAS),
                periods: Marks::new(&[&["補助記号", "句点"]], PERIODS),
                open_brackets: Marks::new(&[&["補助記号", "括弧開"]], OPEN_BRACKETS),
                close_brackets: Marks::new(&[&["補助記号", "括弧閉"]], CLOSE_BRACKETS),
                surface: SurfaceRule::EveryCharacter,
            },
            normalization: Normalization::default(),
            head_rule: HeadRule::FunctionWordsApart,
            head_fallback: HeadFallback::FirstWord,
            sentence_split: SentenceSplit::AfterEnds,
        }
    }

    /// The schema of a dictionary of Lindera, by the name of the dictionary.
    ///
    /// # Arguments
    ///
    /// * `dictionary` - The name of the dictionary, as its metadata has it:
    ///   `ipadic`, `unidic`, `unidic-cwj` or `unidic-csj`.
    ///
    /// # Returns
    ///
    /// The schema, or `None` for a dictionary this crate has no schema for.
    ///
    /// # Examples
    ///
    /// ```
    /// use lindera_dependency::Schema;
    ///
    /// assert_eq!(Schema::for_dictionary("ipadic"), Some(Schema::ipadic()));
    /// // The three UniDic dictionaries have one schema.
    /// assert_eq!(Schema::for_dictionary("unidic-cwj"), Some(Schema::unidic()));
    /// assert_eq!(Schema::for_dictionary("ko-dic"), None);
    /// assert_eq!(
    ///     Schema::DICTIONARIES,
    ///     ["ipadic", "unidic", "unidic-cwj", "unidic-csj"]
    /// );
    /// ```
    pub fn for_dictionary(dictionary: &str) -> Option<Self> {
        match dictionary {
            "ipadic" => Some(Self::ipadic()),
            "unidic" | "unidic-cwj" | "unidic-csj" => Some(Self::unidic()),
            _ => None,
        }
    }

    /// The positions of the head word and of the function word of a
    /// bunsetsu: what [`Bunsetsu::positions`](crate::Bunsetsu::positions)
    /// holds.
    ///
    /// See the [module documentation](self) for the rule. A bunsetsu
    /// without a function word has the function word at its head. A
    /// bunsetsu in which the rule finds no head word has the one
    /// [`Schema::head_fallback`] names, and both at its first morpheme when
    /// it is of symbols only. A space is neither of the two, unless the
    /// bunsetsu is of spaces alone.
    ///
    /// # Arguments
    ///
    /// * `bunsetsu` - The morphemes of the bunsetsu.
    ///
    /// # Returns
    ///
    /// The positions of the head word and of the function word, counted
    /// from the first morpheme of the bunsetsu; `None` for no morpheme.
    pub fn positions<M: Morpheme>(&self, bunsetsu: &[M]) -> Option<(usize, usize)> {
        if bunsetsu.is_empty() {
            return None;
        }
        let mut head = None;
        let mut function = 0;
        for (index, morpheme) in bunsetsu.iter().enumerate() {
            // A space is no word: it is neither of the two.
            if is_space(morpheme) {
                continue;
            }
            let matches = |patterns: &[Pattern]| {
                patterns
                    .iter()
                    .any(|one| one.matches(self, bunsetsu, index))
            };
            match self.head_rule {
                HeadRule::FunctionWordsApart => {
                    if matches(&self.function_words) {
                        function = index;
                    } else if !matches(&self.not_heads) && !self.is_symbol(morpheme) {
                        head = Some(index);
                    }
                }
                HeadRule::LastWords => {
                    if !self.is_symbol(morpheme) {
                        function = index;
                        if !matches(&self.not_heads) {
                            head = Some(index);
                        }
                    }
                }
            }
        }
        // No morpheme can be the head word: the setting of the schema says
        // which one is taken.
        let head = head.unwrap_or_else(|| {
            let word = match self.head_fallback {
                HeadFallback::FirstMorpheme => None,
                HeadFallback::FirstWord => self.first_word(bunsetsu),
            };
            // Without a word, the first morpheme that is not a space.
            word.or_else(|| bunsetsu.iter().position(|morpheme| !is_space(morpheme)))
                .unwrap_or(0)
        });
        // With `LastWords` a head is never after the function word: the
        // morpheme that becomes the head has just become the function word.
        if head > function {
            function = head;
        }
        Some((head, function))
    }

    /// Where the sentences of a text start, for a chunker: the words at
    /// which it cuts the text, so that its model is given one sentence at a
    /// time.
    ///
    /// With [`SentenceSplit::AfterEnds`], a sentence end
    /// ([`is_sentence_end`]) takes the
    /// ends and the closing brackets that follow it, and the word after
    /// them starts a sentence: 読んだ / 。 / 面白かっ / た is cut before
    /// 面白かっ. Two cases are left whole, where the word after the end
    /// belongs to the bunsetsu of a quotation:
    ///
    /// - a function word after a closing bracket, as と in
    ///   …。 / 」 / と / 言っ / た;
    /// - the particle of a quotation, と or って, also without a bracket, as
    ///   in …な / の / か / ? / と / 、.
    ///
    /// Another function word without a closing bracket starts a sentence as
    /// any word does: …。 / だ / が, and …。 / で / も, which UniDic gives as
    /// two particles.
    ///
    /// A sentence end that a dictionary joined with other marks is one too,
    /// and its closing bracket counts as one: IPADIC gives 本当 / ?」 / と,
    /// and nothing is cut before と.
    ///
    /// # Arguments
    ///
    /// * `words` - The words of the text: its morphemes without the spaces.
    ///
    /// # Returns
    ///
    /// The indices of the words that start a sentence, in order, each
    /// larger than 0: the first word starts one in any case and is not
    /// listed. Empty with [`SentenceSplit::None`], and for a text of one
    /// sentence.
    pub fn sentence_starts<M: Morpheme>(&self, words: &[M]) -> Vec<usize> {
        self.sentence_parts(words).0
    }

    /// Where the sentences of a text start ([`Schema::sentence_starts`]),
    /// and the words that stay with the end of a sentence.
    ///
    /// # Arguments
    ///
    /// * `words` - The words of the text: its morphemes without the spaces.
    ///
    /// # Returns
    ///
    /// The indices of the words that start a sentence, and those of the
    /// sentence ends with the ends and the closing brackets that follow
    /// them, each in order. Both empty with [`SentenceSplit::None`].
    pub(crate) fn sentence_parts<M: Morpheme>(&self, words: &[M]) -> (Vec<usize>, Vec<usize>) {
        let mut starts = Vec::new();
        let mut tails = Vec::new();
        if self.sentence_split == SentenceSplit::None {
            return (starts, tails);
        }
        let mut index = 0;
        while index < words.len() {
            let Some(mut closed) = sentence_end(&words[index], words.get(index + 1)) else {
                index += 1;
                continue;
            };
            tails.push(index);
            index += 1;
            // What follows and still belongs to the sentence.
            while index < words.len() {
                let end = sentence_end(&words[index], words.get(index + 1));
                let bracket = self.is_close_bracket(&words[index]);
                if end.is_none() && !bracket {
                    break;
                }
                closed |= bracket || end == Some(true);
                tails.push(index);
                index += 1;
            }
            if index < words.len()
                && !self.is_quotation_particle(words, index)
                && !(closed && self.is_function_word(words, index))
            {
                starts.push(index);
            }
        }
        (starts, tails)
    }

    /// Where the sentences of a text end, for a reader of text: what a
    /// chunker and a parser are given one at a time.
    ///
    /// The models are trained on single sentences. A sentence ends after a
    /// sentence end ([`is_sentence_end`])
    /// that is outside brackets, and takes the ends, the closing brackets
    /// and the spaces that follow it: a quotation is one sentence with the
    /// sentence around it. A word of marks that a dictionary joined is read
    /// one mark at a time ([`marks`]), and an
    /// opening bracket that nothing in the text closes is no bracket.
    ///
    /// The token filter `japanese_dependency` and the layer of text of
    /// `lindera dependency parse` cut their text with it, so that a text is
    /// analyzed the same way through either. [`Schema::sentence_starts`] is
    /// another cut, the one a chunker makes inside what it is given: it also
    /// cuts inside brackets, where a bunsetsu starts after a sentence end
    /// all the same.
    ///
    /// # Arguments
    ///
    /// * `morphemes` - The morphemes of the text, with its spaces.
    ///
    /// # Returns
    ///
    /// The end of each sentence, as the index after its last morpheme; the last
    /// one is the number of morphemes. Nothing for no morpheme.
    ///
    /// # Examples
    ///
    /// ```
    /// use lindera_dependency::Schema;
    /// use lindera_dependency::lattice::LatticeMorpheme;
    ///
    /// let noun = |surface| LatticeMorpheme::new(surface, "名詞,一般,*,*,*,*,*,*,*");
    /// let mark = |surface, kind| LatticeMorpheme::new(surface, format!("記号,{kind},*,*,*,*,*,*,*"));
    /// // 本 。 「 本 。 」 本: the second 。 is inside the brackets.
    /// let text = [
    ///     noun("本"),
    ///     mark("。", "句点"),
    ///     mark("「", "括弧開"),
    ///     noun("本"),
    ///     mark("。", "句点"),
    ///     mark("」", "括弧閉"),
    ///     noun("本"),
    /// ];
    /// assert_eq!(Schema::ipadic().sentence_ends(&text), [2, 7]);
    /// ```
    pub fn sentence_ends<M: Morpheme>(&self, morphemes: &[M]) -> Vec<usize> {
        let read: Vec<Vec<Mark>> = (0..morphemes.len())
            .map(|index| self.sentence_marks(&morphemes[index], morphemes.get(index + 1)))
            .collect();
        // The opening brackets that nothing closes, in order: `:(` and `(泣`
        // open no bracket, and a sentence ends after them as before them.
        let mut open = Vec::new();
        for (index, marks) in read.iter().enumerate() {
            for (offset, mark) in marks.iter().enumerate() {
                match mark {
                    Mark::OpenBracket => open.push((index, offset)),
                    Mark::CloseBracket => {
                        open.pop();
                    }
                    Mark::SentenceEnd | Mark::Other => {}
                }
            }
        }
        let mut unclosed = open.into_iter().peekable();
        let mut depth = 0usize;
        // Reads the marks of a morpheme, for the brackets it opens and closes,
        // and tells whether its last mark that is no closing bracket is a
        // sentence end with no bracket open.
        let mut step = |index: usize| {
            let mut ended = false;
            for (offset, mark) in read[index].iter().enumerate() {
                match mark {
                    Mark::SentenceEnd => ended = depth == 0,
                    Mark::CloseBracket => depth = depth.saturating_sub(1),
                    Mark::OpenBracket => {
                        if unclosed.next_if_eq(&(index, offset)).is_none() {
                            depth += 1;
                        }
                        ended = false;
                    }
                    Mark::Other => ended = false,
                }
            }
            ended
        };
        let mut ends = Vec::new();
        let mut index = 0;
        while index < morphemes.len() {
            let ended = step(index);
            index += 1;
            if ended {
                // What follows and still belongs to the sentence: more ends,
                // closing brackets, and spaces, which are no start of a
                // sentence.
                while morphemes.get(index).is_some_and(|next| {
                    is_sentence_end(next, morphemes.get(index + 1))
                        || self.is_close_bracket(next)
                        || is_space(next)
                }) {
                    step(index);
                    index += 1;
                }
                ends.push(index);
            }
        }
        if ends.last().copied().unwrap_or(0) < morphemes.len() {
            ends.push(morphemes.len());
        }
        ends
    }

    /// The marks of a morpheme, for the sentences of a text.
    ///
    /// A dictionary can join marks into one word, as IPADIC does with `)。`
    /// and `?」`: such a morpheme is read one mark at a time ([`marks`]), so
    /// that its brackets open and close, and its ends end, as they do when
    /// they are words of their own.
    ///
    /// # Arguments
    ///
    /// * `morpheme` - The morpheme.
    /// * `next` - The morpheme after it, when there is one.
    ///
    /// # Returns
    ///
    /// One bracket for a bracket of the schema; a sentence end or another mark
    /// for `.` alone, by what follows it ([`is_sentence_end`]); the marks of
    /// the surface for another morpheme of marks; nothing for a word.
    fn sentence_marks<M: Morpheme>(&self, morpheme: &M, next: Option<&M>) -> Vec<Mark> {
        if self.is_open_bracket(morpheme) {
            return vec![Mark::OpenBracket];
        }
        if self.is_close_bracket(morpheme) {
            return vec![Mark::CloseBracket];
        }
        let surface = morpheme.surface();
        if surface == "." {
            return if is_sentence_end(morpheme, next) {
                vec![Mark::SentenceEnd]
            } else {
                vec![Mark::Other]
            };
        }
        marks(surface).map(Iterator::collect).unwrap_or_default()
    }

    /// Whether a morpheme is a particle that closes a quotation: と or って.
    ///
    /// # Arguments
    ///
    /// * `morphemes` - The morphemes around it.
    /// * `index` - Its index among them.
    ///
    /// # Returns
    ///
    /// Whether it is a particle of the schema with one of the two surfaces.
    fn is_quotation_particle<M: Morpheme>(&self, morphemes: &[M], index: usize) -> bool {
        matches!(morphemes[index].surface(), "と" | "って") && self.is_particle(morphemes, index)
    }

    /// Whether a morpheme matches a function word pattern of the schema.
    ///
    /// # Arguments
    ///
    /// * `morphemes` - The morphemes around it.
    /// * `index` - Its index among them.
    ///
    /// # Returns
    ///
    /// Whether one of [`Schema::function_words`] matches it.
    fn is_function_word<M: Morpheme>(&self, morphemes: &[M], index: usize) -> bool {
        self.function_words
            .iter()
            .any(|one| one.matches(self, morphemes, index))
    }

    /// The first morpheme of a bunsetsu that is a word, for
    /// [`HeadFallback::FirstWord`].
    ///
    /// # Arguments
    ///
    /// * `bunsetsu` - The morphemes of the bunsetsu.
    ///
    /// # Returns
    ///
    /// The index of the first morpheme that is not a comma, a period or a
    /// bracket, not a space, and not a particle; `None` when there is none.
    fn first_word<M: Morpheme>(&self, bunsetsu: &[M]) -> Option<usize> {
        bunsetsu.iter().enumerate().position(|(index, morpheme)| {
            !(is_space(morpheme)
                || self.is_comma(morpheme)
                || self.is_period(morpheme)
                || self.is_open_bracket(morpheme)
                || self.is_close_bracket(morpheme)
                || self.is_particle(bunsetsu, index))
        })
    }

    /// The surface of a morpheme as the chunker and the parser use it:
    /// with [`Schema::normalization`] applied.
    ///
    /// # Arguments
    ///
    /// * `morpheme` - The morpheme.
    ///
    /// # Returns
    ///
    /// The normalized surface; the surface itself when the schema does not
    /// normalize, or when no rule matches in it.
    pub fn surface_of<'a, M: Morpheme>(&self, morpheme: &'a M) -> Cow<'a, str> {
        self.normalization.apply(morpheme.surface())
    }

    /// Whether a morpheme of a bunsetsu is a particle: it matches one of
    /// [`Schema::particles`].
    ///
    /// # Arguments
    ///
    /// * `bunsetsu` - The morphemes of the bunsetsu.
    /// * `index` - The index of the morpheme in the bunsetsu.
    ///
    /// # Returns
    ///
    /// Whether it is a particle; `false` for an index past the bunsetsu.
    pub fn is_particle<M: Morpheme>(&self, bunsetsu: &[M], index: usize) -> bool {
        self.particles
            .iter()
            .any(|one| one.matches(self, bunsetsu, index))
    }

    /// Whether a morpheme of a bunsetsu tells by its surface how the
    /// bunsetsu modifies another: it matches one of
    /// [`Schema::lexicalized`].
    ///
    /// # Arguments
    ///
    /// * `bunsetsu` - The morphemes of the bunsetsu.
    /// * `index` - The index of the morpheme in the bunsetsu.
    ///
    /// # Returns
    ///
    /// Whether it is such a word; `false` for an index past the bunsetsu.
    pub fn is_lexicalized<M: Morpheme>(&self, bunsetsu: &[M], index: usize) -> bool {
        self.lexicalized
            .iter()
            .any(|one| one.matches(self, bunsetsu, index))
    }

    /// Whether a morpheme is a symbol: a comma, a period, a bracket or any
    /// other one. A symbol is neither the head nor the function word of a
    /// bunsetsu.
    ///
    /// # Arguments
    ///
    /// * `morpheme` - The morpheme.
    ///
    /// # Returns
    ///
    /// Whether its part of speech is one of a symbol, or its surface is
    /// made of symbol characters only.
    pub fn is_symbol<M: Morpheme>(&self, morpheme: &M) -> bool {
        self.symbols.matches(self, morpheme)
    }

    /// Whether a morpheme is a comma (読点): `、`, or `,` and `,`.
    ///
    /// # Arguments
    ///
    /// * `morpheme` - The morpheme.
    ///
    /// # Returns
    ///
    /// Whether its part of speech or its surface is the one of a comma.
    pub fn is_comma<M: Morpheme>(&self, morpheme: &M) -> bool {
        self.symbols.commas.matches(self, morpheme)
    }

    /// Whether a morpheme is a period (句点): `。`, or `.` and `.`.
    ///
    /// # Arguments
    ///
    /// * `morpheme` - The morpheme.
    ///
    /// # Returns
    ///
    /// Whether its part of speech or its surface is the one of a period.
    pub fn is_period<M: Morpheme>(&self, morpheme: &M) -> bool {
        self.symbols.periods.matches(self, morpheme)
    }

    /// Whether a morpheme is an opening bracket.
    ///
    /// # Arguments
    ///
    /// * `morpheme` - The morpheme.
    ///
    /// # Returns
    ///
    /// Whether its part of speech or its surface is the one of an opening
    /// bracket.
    pub fn is_open_bracket<M: Morpheme>(&self, morpheme: &M) -> bool {
        self.symbols.open_brackets.matches(self, morpheme)
    }

    /// Whether a morpheme is a closing bracket.
    ///
    /// # Arguments
    ///
    /// * `morpheme` - The morpheme.
    ///
    /// # Returns
    ///
    /// Whether its part of speech or its surface is the one of a closing
    /// bracket.
    pub fn is_close_bracket<M: Morpheme>(&self, morpheme: &M) -> bool {
        self.symbols.close_brackets.matches(self, morpheme)
    }

    /// The part of speech of a morpheme as one string: its levels joined by
    /// `-`, up to the first one that is `*` or missing, as `名詞-サ変接続`.
    ///
    /// # Arguments
    ///
    /// * `morpheme` - The morpheme.
    ///
    /// # Returns
    ///
    /// The part of speech; an empty string without a first level.
    pub fn part_of_speech_of<M: Morpheme>(&self, morpheme: &M) -> String {
        self.levels_of(morpheme, self.part_of_speech.clone())
    }

    /// Some levels of the part of speech of a morpheme as one string.
    ///
    /// # Arguments
    ///
    /// * `morpheme` - The morpheme.
    /// * `levels` - The columns of the levels to join.
    ///
    /// # Returns
    ///
    /// The levels joined by `-`, up to the first one that is `*` or
    /// missing; an empty string without a first level.
    pub(crate) fn levels_of<M: Morpheme>(&self, morpheme: &M, levels: Range<usize>) -> String {
        let mut value = String::new();
        for index in levels {
            match morpheme.feature(index) {
                Some(level) if level != EMPTY => {
                    if !value.is_empty() {
                        value.push('-');
                    }
                    value.push_str(level);
                }
                _ => break,
            }
        }
        value
    }

    /// The number of feature columns the schema reads.
    ///
    /// # Returns
    ///
    /// One more than the largest index among the columns of the part of
    /// speech, of the conjugation and of the base form: a morpheme of the
    /// dictionary has at least this many columns.
    pub fn width(&self) -> usize {
        [
            Some(self.part_of_speech.end),
            self.conjugation_type.map(|index| index + 1),
            self.conjugation_form.map(|index| index + 1),
            self.base_form.map(|index| index + 1),
        ]
        .into_iter()
        .flatten()
        .max()
        .unwrap_or(0)
    }

    /// Checks that morphemes can be of the dictionary of the schema.
    ///
    /// A morpheme with fewer feature columns than the schema reads comes
    /// from another dictionary, or from a tokenizer that drops columns:
    /// analyzing it would give an answer from columns that are not there.
    /// Morphemes of another dictionary that are wide enough pass; the name
    /// of the dictionary in a model file is for those
    /// ([`Model::check_dictionary`](crate::model::Model::check_dictionary)).
    ///
    /// # Arguments
    ///
    /// * `morphemes` - The morphemes.
    ///
    /// # Returns
    ///
    /// `Ok(())`, or [`Error::Dictionary`] for the first morpheme that has
    /// fewer columns than [`Schema::width`].
    pub fn check<M: Morpheme>(&self, morphemes: &[M]) -> Result<()> {
        let width = self.width();
        let Some(last) = width.checked_sub(1) else {
            return Ok(());
        };
        for (index, morpheme) in morphemes.iter().enumerate() {
            if morpheme.feature(last).is_none() {
                return Err(Error::Dictionary(format!(
                    "the morpheme {} ({:?}) has fewer than the {width} feature columns the schema reads: it is not of the dictionary of the model",
                    index + 1,
                    morpheme.surface()
                )));
            }
        }
        Ok(())
    }

    /// Appends the schema to the bytes of a model.
    ///
    /// The columns, then the function word patterns, the patterns of what
    /// is not a head, the particles, the function words taken by their
    /// surface, the symbols, the normalization, the rule of the head, and
    /// the head word of a bunsetsu without one.
    ///
    /// # Arguments
    ///
    /// * `bytes` - The bytes to append to.
    pub(crate) fn write(&self, bytes: &mut Vec<u8>) {
        let column = |index: Option<usize>| index.map_or(NO_COLUMN, |index| index as u32);
        push_u32(bytes, self.part_of_speech.start as u32);
        push_u32(bytes, self.part_of_speech.end as u32);
        push_u32(bytes, column(self.conjugation_type));
        push_u32(bytes, column(self.conjugation_form));
        push_u32(bytes, column(self.base_form));
        for patterns in [
            &self.function_words,
            &self.not_heads,
            &self.particles,
            &self.lexicalized,
        ] {
            push_u32(bytes, patterns.len() as u32);
            for pattern in patterns {
                pattern.write(bytes);
            }
        }
        self.symbols.write(bytes);
        self.normalization.write(bytes);
        bytes.push(self.head_rule.code());
        bytes.push(self.head_fallback.code());
        bytes.push(self.sentence_split.code());
    }

    /// Reads a schema from the bytes of a model.
    ///
    /// # Arguments
    ///
    /// * `reader` - The bytes, at the schema.
    ///
    /// # Returns
    ///
    /// The schema, or the error of bytes that are not one.
    pub(crate) fn read(reader: &mut Reader, version: u32) -> Result<Self> {
        let start = reader.u32()? as usize;
        let end = reader.u32()? as usize;
        let mut column = || -> Result<Option<usize>> {
            let value = reader.u32()?;
            Ok((value != NO_COLUMN).then_some(value as usize))
        };
        let conjugation_type = column()?;
        let conjugation_form = column()?;
        let base_form = column()?;
        let mut patterns = || -> Result<Vec<Pattern>> {
            let count = reader.u32()?;
            let mut patterns = Vec::new();
            for _ in 0..count {
                patterns.push(Pattern::read(reader, 0)?);
            }
            Ok(patterns)
        };
        let function_words = patterns()?;
        let not_heads = patterns()?;
        let particles = patterns()?;
        let lexicalized = patterns()?;
        let symbols = Symbols::read(reader)?;
        let normalization = Normalization::read(reader)?;
        let head_rule = HeadRule::from_code(reader.u8()?)?;
        let (head_fallback, sentence_split) = if version >= HEAD_FALLBACK_VERSION {
            (
                HeadFallback::from_code(reader.u8()?)?,
                SentenceSplit::from_code(reader.u8()?)?,
            )
        } else {
            (HeadFallback::FirstMorpheme, SentenceSplit::None)
        };
        Ok(Self {
            part_of_speech: start..end,
            conjugation_type,
            conjugation_form,
            base_form,
            function_words,
            not_heads,
            particles,
            lexicalized,
            symbols,
            normalization,
            head_rule,
            head_fallback,
            sentence_split,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::Error;
    use crate::lattice::LatticeMorpheme;

    /// Morphemes of `(surface, features)`.
    fn morphemes(pairs: &[(&str, &str)]) -> Vec<LatticeMorpheme> {
        pairs
            .iter()
            .map(|(surface, features)| LatticeMorpheme::new(*surface, *features))
            .collect()
    }

    /// The positions the schema of IPADIC gives for a bunsetsu.
    fn positions(pairs: &[(&str, &str)]) -> (usize, usize) {
        Schema::ipadic().positions(&morphemes(pairs)).unwrap()
    }

    const HON: (&str, &str) = ("本", "名詞,一般,*,*,*,*,本,ホン,ホン");
    const WO: (&str, &str) = ("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ");
    const NI: (&str, &str) = ("に", "助詞,格助詞,一般,*,*,*,に,ニ,ニ");
    const GA: (&str, &str) = ("が", "助詞,格助詞,一般,*,*,*,が,ガ,ガ");
    const YON: (&str, &str) = ("読ん", "動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン");
    const YOMU: (&str, &str) = ("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム");
    const DA: (&str, &str) = ("だ", "助動詞,*,*,*,特殊・タ,基本形,だ,ダ,ダ");
    const TA: (&str, &str) = ("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ");
    const DE: (&str, &str) = ("で", "助詞,接続助詞,*,*,*,*,で,デ,デ");
    const IRU: (&str, &str) = ("いる", "動詞,非自立,*,*,一段,基本形,いる,イル,イル");
    const MARU: (&str, &str) = ("。", "記号,句点,*,*,*,*,。,。,。");
    const TEN: (&str, &str) = ("、", "記号,読点,*,*,*,*,、,、,、");
    const KAGI: (&str, &str) = ("「", "記号,括弧開,*,*,*,*,「,「,「");
    const KAGI_TOJI: (&str, &str) = ("」", "記号,括弧閉,*,*,*,*,」,」,」");
    const RIYOU: (&str, &str) = ("利用", "名詞,サ変接続,*,*,*,*,利用,リヨウ,リヨー");
    const SHI: (&str, &str) = ("し", "動詞,自立,*,*,サ変・スル,連用形,する,シ,シ");
    const KOTO: (&str, &str) = ("こと", "名詞,非自立,一般,*,*,*,こと,コト,コト");
    const KIHON: (&str, &str) = ("基本", "名詞,一般,*,*,*,*,基本,キホン,キホン");
    const TEKI: (&str, &str) = ("的", "名詞,接尾,形容動詞語幹,*,*,*,的,テキ,テキ");
    /// The half-width comma, an unknown word of IPADIC.
    const COMMA: (&str, &str) = (",", "名詞,サ変接続,*,*,*,*,*,*,*");

    #[test]
    fn ipadic_names_the_columns_of_mecab_ipadic() {
        // 読ん: 動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン
        let features = [
            "動詞",
            "自立",
            "*",
            "*",
            "五段・マ行",
            "連用タ接続",
            "読む",
            "ヨン",
            "ヨン",
        ];
        let schema = Schema::ipadic();
        assert_eq!(
            features[schema.part_of_speech.clone()],
            ["動詞", "自立", "*", "*"]
        );
        assert_eq!(features[schema.conjugation_type.unwrap()], "五段・マ行");
        assert_eq!(features[schema.conjugation_form.unwrap()], "連用タ接続");
        assert_eq!(features[schema.base_form.unwrap()], "読む");
    }

    #[test]
    fn a_content_word_and_a_particle_are_the_head_and_the_function_word() {
        assert_eq!(positions(&[HON, WO]), (0, 1));
        // The last content word and the last function word.
        assert_eq!(positions(&[KIHON, HON, NI, WO]), (1, 3));
    }

    #[test]
    fn a_content_word_alone_is_both() {
        assert_eq!(positions(&[HON]), (0, 0));
        assert_eq!(positions(&[KIHON, HON]), (1, 1));
    }

    #[test]
    fn punctuation_at_the_end_is_neither() {
        assert_eq!(positions(&[YON, DA, MARU]), (0, 1));
        assert_eq!(positions(&[HON, WO, TEN]), (0, 1));
        // By the surface too: the half-width comma is 名詞,サ変接続.
        assert_eq!(positions(&[HON, WO, COMMA]), (0, 1));
        assert_eq!(positions(&[HON, COMMA]), (0, 0));
    }

    #[test]
    fn a_bunsetsu_of_symbols_only_has_both_at_its_first_morpheme() {
        assert_eq!(positions(&[MARU]), (0, 0));
        assert_eq!(positions(&[KAGI_TOJI, MARU, COMMA]), (0, 0));
    }

    #[test]
    fn a_bracket_before_the_head_is_skipped() {
        assert_eq!(positions(&[KAGI, HON, WO]), (1, 2));
    }

    #[test]
    fn a_dependent_verb_is_the_function_word() {
        // 読ん / で / いる
        assert_eq!(positions(&[YON, DE, IRU]), (0, 2));
        assert_eq!(positions(&[YON, DE, IRU, MARU]), (0, 2));
    }

    #[test]
    fn a_head_after_the_function_word_takes_the_function_word_with_it() {
        // に / 本: a particle, then the content word.
        assert_eq!(positions(&[NI, HON]), (1, 1));
        // The same with a symbol after it.
        assert_eq!(positions(&[NI, HON, MARU]), (1, 1));
        // A function word after the head is kept.
        assert_eq!(positions(&[NI, HON, DA]), (1, 2));
    }

    #[test]
    fn the_function_words_of_cabocha_are_function_words() {
        // 読ま / れる (動詞,接尾)
        let yoma = ("読ま", "動詞,自立,*,*,五段・マ行,未然形,読む,ヨマ,ヨマ");
        let reru = ("れる", "動詞,接尾,*,*,一段,基本形,れる,レル,レル");
        assert_eq!(positions(&[yoma, reru]), (0, 1));
        // 読み / にくい (形容詞,非自立)
        let yomi = ("読み", "動詞,自立,*,*,五段・マ行,連用形,読む,ヨミ,ヨミ");
        let nikui = (
            "にくい",
            "形容詞,非自立,*,*,形容詞・アウオ段,基本形,にくい,ニクイ,ニクイ",
        );
        assert_eq!(positions(&[yomi, nikui]), (0, 1));
        // 本 / っぽい (形容詞,接尾)
        let ppoi = (
            "っぽい",
            "形容詞,接尾,*,*,形容詞・アウオ段,基本形,っぽい,ッポイ,ッポイ",
        );
        assert_eq!(positions(&[HON, ppoi]), (0, 1));
        // Each of the three after a particle: the last one wins.
        assert_eq!(positions(&[HON, WO, reru]), (0, 2));
        assert_eq!(positions(&[HON, WO, nikui]), (0, 2));
        assert_eq!(positions(&[HON, WO, ppoi]), (0, 2));
        // 助詞 and 助動詞 alone.
        assert_eq!(positions(&[HON, DA]), (0, 1));
        assert_eq!(positions(&[HON, WO]), (0, 1));
    }

    #[test]
    fn suru_and_dekiru_are_function_words() {
        // 利用 / し / た
        assert_eq!(positions(&[RIYOU, SHI, TA]), (0, 2));
        assert_eq!(positions(&[RIYOU, SHI]), (0, 1));
        // する at the start of a bunsetsu is the head.
        assert_eq!(positions(&[SHI, TA]), (0, 1));
        assert_eq!(positions(&[SHI]), (0, 0));
        // Another verb after a verbal noun is the head.
        assert_eq!(positions(&[RIYOU, YON, DA]), (1, 2));
        // できる too, in either spelling of its base form.
        let dekiru = ("でき", "動詞,自立,*,*,一段,連用形,できる,デキ,デキ");
        assert_eq!(positions(&[RIYOU, dekiru, TA]), (0, 2));
        let dekiru = ("出来", "動詞,自立,*,*,一段,連用形,出来る,デキ,デキ");
        assert_eq!(positions(&[RIYOU, dekiru, TA]), (0, 2));
    }

    #[test]
    fn a_dependent_noun_and_the_suffix_teki_are_not_heads() {
        // 読む / こと / が
        assert_eq!(positions(&[YOMU, KOTO, GA]), (0, 2));
        // At the start of a bunsetsu it stays the head, as nothing else is.
        assert_eq!(positions(&[KOTO, GA]), (0, 1));
        // 基本 / 的 / に
        assert_eq!(positions(&[KIHON, TEKI, NI]), (0, 2));
        // 長 / さ / は: the suffix さ (名詞,接尾,特殊).
        let naga = (
            "長",
            "形容詞,自立,*,*,形容詞・アウオ段,ガル接続,長い,ナガ,ナガ",
        );
        let sa = ("さ", "名詞,接尾,特殊,*,*,*,さ,サ,サ");
        assert_eq!(positions(&[naga, sa, GA]), (0, 2));
        // Another suffix is a head: 本 / 人 (名詞,接尾,助数詞).
        let nin = ("人", "名詞,接尾,助数詞,*,*,*,人,ニン,ニン");
        assert_eq!(positions(&[HON, nin, GA]), (1, 2));
    }

    #[test]
    fn a_verb_after_a_particle_is_part_of_a_compound_function_word() {
        let naru = ("なっ", "動詞,自立,*,*,五段・ラ行,連用タ接続,なる,ナッ,ナッ");
        // 読む / こと / に / なっ / た
        assert_eq!(positions(&[YOMU, KOTO, NI, naru, TA]), (0, 4));
        // 本 / に / なっ / た: the same in a shorter bunsetsu.
        assert_eq!(positions(&[HON, NI, naru, TA]), (0, 3));
        // A verb after a noun is the head.
        assert_eq!(positions(&[HON, naru, TA]), (1, 2));
        // At the start of a bunsetsu too.
        assert_eq!(positions(&[naru, TA]), (0, 1));
    }

    #[test]
    fn no_morpheme_has_no_positions() {
        let none: [LatticeMorpheme; 0] = [];
        assert_eq!(Schema::ipadic().positions(&none), None);
    }

    #[test]
    fn morphemes_with_fewer_columns_do_not_panic() {
        // No column, one column, and the columns up to the part of speech.
        assert_eq!(positions(&[("x", ""), ("y", "")]), (1, 1));
        assert_eq!(positions(&[("本", "名詞"), ("を", "助詞")]), (0, 1));
        assert_eq!(
            positions(&[("利用", "名詞,サ変接続"), ("し", "動詞,自立")]),
            (1, 1)
        );
        let schema = Schema::ipadic();
        let bare = LatticeMorpheme::new("x", "");
        assert!(!schema.is_symbol(&bare));
        assert_eq!(schema.part_of_speech_of(&bare), "");
        // A symbol by its surface needs no column.
        assert!(schema.is_comma(&LatticeMorpheme::new(",", "")));
    }

    #[test]
    fn a_schema_without_patterns_takes_the_last_morpheme() {
        // Every morpheme is a head, none a function word.
        let schema = Schema {
            part_of_speech: 0..4,
            ..Schema::default()
        };
        assert_eq!(schema.positions(&morphemes(&[HON, WO, MARU])), Some((2, 2)));
    }

    #[test]
    fn punctuation_and_brackets_are_recognized_by_part_of_speech_and_by_surface() {
        let schema = Schema::ipadic();
        let unknown = |surface: &str| LatticeMorpheme::new(surface, "名詞,サ変接続,*,*,*,*,*,*,*");
        let known = |pair: (&str, &str)| LatticeMorpheme::new(pair.0, pair.1);

        assert!(schema.is_comma(&known(TEN)));
        assert!(schema.is_period(&known(MARU)));
        assert!(schema.is_open_bracket(&known(KAGI)));
        assert!(schema.is_close_bracket(&known(KAGI_TOJI)));
        for surface in [",", ",", "、"] {
            assert!(schema.is_comma(&unknown(surface)), "{surface}");
            assert!(!schema.is_period(&unknown(surface)), "{surface}");
        }
        for surface in [".", ".", "。"] {
            assert!(schema.is_period(&unknown(surface)), "{surface}");
            assert!(!schema.is_comma(&unknown(surface)), "{surface}");
        }
        for surface in ["(", "(", "[", "「", "『", "“"] {
            assert!(schema.is_open_bracket(&unknown(surface)), "{surface}");
            assert!(!schema.is_close_bracket(&unknown(surface)), "{surface}");
        }
        for surface in [")", ")", "]", "」", "』", "”"] {
            assert!(schema.is_close_bracket(&unknown(surface)), "{surface}");
            assert!(!schema.is_open_bracket(&unknown(surface)), "{surface}");
        }
        // Each of them is a symbol, and so are the other marks.
        for surface in [
            ",", "。", "(", "」", "!", "?", "-", "/", "・", "…", ",“", "!?",
        ] {
            assert!(schema.is_symbol(&unknown(surface)), "{surface}");
        }
        // By the part of speech alone: the half-width forms of 、 。 「 」
        // are in no list of characters.
        let comma = LatticeMorpheme::new("、", "記号,読点,*,*,*,*,、,、,、");
        let period = LatticeMorpheme::new("。", "記号,句点,*,*,*,*,。,。,。");
        let open = LatticeMorpheme::new("「", "記号,括弧開,*,*,*,*,「,「,「");
        let close = LatticeMorpheme::new("」", "記号,括弧閉,*,*,*,*,」,」,」");
        assert!(schema.is_comma(&comma) && !schema.is_period(&comma));
        assert!(schema.is_period(&period) && !schema.is_comma(&period));
        assert!(schema.is_open_bracket(&open) && !schema.is_close_bracket(&open));
        assert!(schema.is_close_bracket(&close) && !schema.is_open_bracket(&close));
        assert!(!schema.is_comma(&unknown("、")));
        // The part of speech 記号 alone is a symbol of no finer kind.
        let alphabet = LatticeMorpheme::new("A", "記号,アルファベット,*,*,*,*,A,エイ,エイ");
        assert!(schema.is_symbol(&alphabet));
        assert!(!schema.is_comma(&alphabet) && !schema.is_period(&alphabet));
        // A unit, a word and a number are not symbols.
        for surface in ["%", "°", "%、", "本", "1", "a"] {
            assert!(!schema.is_symbol(&unknown(surface)), "{surface}");
        }
        assert!(!schema.is_comma(&known(HON)));
    }

    #[test]
    fn the_brackets_come_in_pairs() {
        assert_eq!(
            OPEN_BRACKETS.chars().count(),
            CLOSE_BRACKETS.chars().count()
        );
        // No character is of two kinds.
        let all = [
            COMMAS,
            PERIODS,
            OPEN_BRACKETS,
            CLOSE_BRACKETS,
            OTHER_SYMBOLS,
        ]
        .concat();
        let mut characters: Vec<char> = all.chars().collect();
        let count = characters.len();
        characters.sort_unstable();
        characters.dedup();
        assert_eq!(characters.len(), count);
    }

    #[test]
    fn the_part_of_speech_is_joined_up_to_the_first_empty_level() {
        let schema = Schema::ipadic();
        let of =
            |pair: (&str, &str)| schema.part_of_speech_of(&LatticeMorpheme::new(pair.0, pair.1));
        assert_eq!(of(HON), "名詞-一般");
        assert_eq!(of(TEKI), "名詞-接尾-形容動詞語幹");
        assert_eq!(of(DA), "助動詞");
        assert_eq!(of(("x", "*,名詞")), "");
    }

    #[test]
    fn particles_and_words_taken_by_their_surface_follow_the_patterns() {
        let schema = Schema::ipadic();
        let bunsetsu = morphemes(&[
            (
                "ゆっくり",
                "副詞,助詞類接続,*,*,*,*,ゆっくり,ユックリ,ユックリ",
            ),
            ("と", "助詞,格助詞,一般,*,*,*,と,ト,ト"),
            ("この", "連体詞,*,*,*,*,*,この,コノ,コノ"),
            ("しかし", "接続詞,*,*,*,*,*,しかし,シカシ,シカシ"),
            ("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
        ]);
        // The last index is past the bunsetsu.
        let particles: Vec<bool> = (0..6)
            .map(|index| schema.is_particle(&bunsetsu, index))
            .collect();
        assert_eq!(particles, [false, true, false, false, false, false]);
        let lexicalized: Vec<bool> = (0..6)
            .map(|index| schema.is_lexicalized(&bunsetsu, index))
            .collect();
        assert_eq!(lexicalized, [true, true, true, true, false, false]);
    }

    #[test]
    fn unidic_is_a_second_schema_of_data_only() {
        let schema = Schema::unidic();
        // 思っ / て / いる: いる (非自立可能) is a function word.
        let omotte_iru = morphemes(&[
            (
                "思っ",
                "動詞,一般,*,*,五段-ワア行,連用形-促音便,オモウ,思う",
            ),
            ("て", "助詞,接続助詞,*,*,*,*,テ,て"),
            (
                "いる",
                "動詞,非自立可能,*,*,上一段-ア行,終止形-一般,イル,居る",
            ),
        ]);
        assert_eq!(schema.positions(&omotte_iru), Some((0, 2)));

        // 事故 / に / よっ / て: よっ after に is not the head.
        let ni_yotte = morphemes(&[
            ("事故", "名詞,普通名詞,一般,*,*,*,ジコ,事故"),
            ("に", "助詞,格助詞,*,*,*,*,ニ,に"),
            ("よっ", "動詞,一般,*,*,五段-ラ行,連用形-促音便,ヨル,因る"),
            ("て", "助詞,接続助詞,*,*,*,*,テ,て"),
        ]);
        assert_eq!(schema.positions(&ni_yotte), Some((0, 3)));

        // 本 / が / 読む is not such a verb: が is not に, と or を.
        let ga_yomu = morphemes(&[
            ("本", "名詞,普通名詞,一般,*,*,*,ホン,本"),
            ("が", "助詞,格助詞,*,*,*,*,ガ,が"),
            ("読む", "動詞,一般,*,*,五段-マ行,終止形-一般,ヨム,読む"),
        ]);
        assert_eq!(schema.positions(&ga_yomu), Some((2, 2)));

        // 。 is 補助記号,句点.
        let period = LatticeMorpheme::new("。", "補助記号,句点,*,*,*,*,,。");
        assert!(schema.is_period(&period) && schema.is_symbol(&period));
        // The schema of IPADIC does not know these parts of speech.
        assert_eq!(Schema::ipadic().positions(&omotte_iru), Some((2, 2)));
    }

    const SURU_UNIDIC: (&str, &str) =
        ("する", "動詞,非自立可能,*,*,サ行変格,連体形-一般,スル,為る");
    const TA_UNIDIC: (&str, &str) = ("た", "助動詞,*,*,*,助動詞-タ,連体形-一般,タ,た");
    const NI_UNIDIC: (&str, &str) = ("に", "助詞,格助詞,*,*,*,*,ニ,に");
    const TSUKAU_UNIDIC: (&str, &str) =
        ("使う", "動詞,一般,*,*,五段-ワア行,連体形-一般,ツカウ,使う");

    #[test]
    fn unidic_does_not_take_an_auxiliary_stem_as_the_head() {
        let schema = Schema::unidic();
        // 使う / よう / に: よう is 形状詞,助動詞語幹.
        let you = morphemes(&[
            TSUKAU_UNIDIC,
            ("よう", "形状詞,助動詞語幹,*,*,*,*,ヨウ,様"),
            ("に", "助動詞,*,*,*,助動詞-ダ,連用形-ニ,ダ,だ"),
        ]);
        assert_eq!(schema.positions(&you), Some((0, 2)));
        // 働い / た / そう / だ: そう of hearsay is 名詞,助動詞語幹.
        let sou = morphemes(&[
            (
                "働い",
                "動詞,一般,*,*,五段-カ行,連用形-イ音便,ハタラク,働く",
            ),
            TA_UNIDIC,
            ("そう", "名詞,助動詞語幹,*,*,*,*,ソウ,そう-伝聞"),
            ("だ", "助動詞,*,*,*,助動詞-ダ,終止形-一般,ダ,だ"),
        ]);
        assert_eq!(schema.positions(&sou), Some((0, 3)));
    }

    #[test]
    fn unidic_does_not_take_a_formal_noun_after_a_predicate_as_the_head() {
        let schema = Schema::unidic();
        let koto = ("こと", "名詞,普通名詞,一般,*,*,*,コト,事");
        let tame = ("ため", "名詞,普通名詞,副詞可能,*,*,*,タメ,為");
        let kounyuu = ("購入", "名詞,普通名詞,サ変可能,*,*,*,コウニュウ,購入");
        // 購入 / する / こと / に: after a verb.
        let after_verb = morphemes(&[kounyuu, SURU_UNIDIC, koto, NI_UNIDIC]);
        assert_eq!(schema.positions(&after_verb), Some((0, 3)));
        // 購入 / する / た / ため / に: after an auxiliary.
        let after_auxiliary = morphemes(&[kounyuu, SURU_UNIDIC, TA_UNIDIC, tame, NI_UNIDIC]);
        assert_eq!(schema.positions(&after_auxiliary), Some((0, 4)));
        // 新しい / こと / に: after an adjective.
        let after_adjective = morphemes(&[
            (
                "新しい",
                "形容詞,一般,*,*,形容詞,連体形-一般,アタラシイ,新しい",
            ),
            koto,
            NI_UNIDIC,
        ]);
        assert_eq!(schema.positions(&after_adjective), Some((0, 2)));
        // こと / に, and 購入 / こと / に: not after one of them.
        assert_eq!(
            schema.positions(&morphemes(&[koto, NI_UNIDIC])),
            Some((0, 1))
        );
        assert_eq!(
            schema.positions(&morphemes(&[kounyuu, koto, NI_UNIDIC])),
            Some((1, 2))
        );
        // 使う / 人 / に: 人 is not a formal noun.
        let hito = morphemes(&[
            TSUKAU_UNIDIC,
            ("人", "名詞,普通名詞,一般,*,*,*,ヒト,人"),
            NI_UNIDIC,
        ]);
        assert_eq!(schema.positions(&hito), Some((1, 2)));
    }

    #[test]
    fn unidic_does_not_take_a_nominal_suffix_after_an_adjective_as_the_head() {
        let schema = Schema::unidic();
        // 大き / さ / に.
        let ookisa = morphemes(&[
            ("大き", "形容詞,一般,*,*,形容詞,語幹-一般,オオキイ,大きい"),
            ("さ", "接尾辞,名詞的,一般,*,*,*,サ,さ"),
            NI_UNIDIC,
        ]);
        assert_eq!(schema.positions(&ookisa), Some((0, 2)));
        // 市 / 長 / に: after a noun the suffix is the head.
        let shichou = morphemes(&[
            ("市", "名詞,普通名詞,一般,*,*,*,シ,市"),
            ("長", "接尾辞,名詞的,一般,*,*,*,チョウ,長"),
            NI_UNIDIC,
        ]);
        assert_eq!(schema.positions(&shichou), Some((1, 2)));
    }

    #[test]
    fn unidic_takes_a_letter_as_a_symbol() {
        let schema = Schema::unidic();
        // 5 / k / m: the letters are 記号,文字.
        let kilometers = morphemes(&[
            ("5", "名詞,数詞,*,*,*,*,ゴ,五"),
            ("k", "記号,文字,*,*,*,*,ケー,K"),
            ("m", "記号,文字,*,*,*,*,エム,M"),
        ]);
        assert!(schema.is_symbol(&kilometers[1]));
        assert_eq!(schema.positions(&kilometers), Some((0, 0)));
    }

    #[test]
    fn a_schema_is_chosen_by_the_name_of_the_dictionary() {
        assert_eq!(Schema::for_dictionary("ipadic"), Some(Schema::ipadic()));
        for name in ["unidic", "unidic-cwj", "unidic-csj"] {
            assert_eq!(Schema::for_dictionary(name), Some(Schema::unidic()));
        }
        // Every name of the list has a schema, and no other name has.
        for name in Schema::DICTIONARIES {
            assert!(Schema::for_dictionary(name).is_some(), "{name}");
        }
        for name in ["", "IPADIC", "ipadic-neologd", "ko-dic", "unidic-"] {
            assert_eq!(Schema::for_dictionary(name), None, "{name}");
        }
    }

    /// A schema with the rule of the last words: two levels of the part
    /// of speech, 特殊 as the symbols, and 助詞 and 接尾辞 as what is not a
    /// head. The rule CaboCha has for JUMAN.
    fn last_words() -> Schema {
        Schema {
            part_of_speech: 0..2,
            not_heads: vec![Pattern::new(&["助詞"]), Pattern::new(&["接尾辞"])],
            symbols: Symbols {
                others: Marks::new(&[&["特殊"]], ""),
                surface: SurfaceRule::OneCharacter,
                ..Symbols::default()
            },
            head_rule: HeadRule::LastWords,
            ..Schema::default()
        }
    }

    #[test]
    fn with_the_rule_of_the_last_words_the_two_positions_are_found_apart() {
        const NOUN: (&str, &str) = ("本", "名詞,普通名詞,*,*,本,ほん,*");
        const PARTICLE: (&str, &str) = ("を", "助詞,格助詞,*,*,を,を,*");
        const VERB: (&str, &str) = ("読んで", "動詞,*,子音動詞マ行,タ系連用テ形,読む,よんで,*");
        const SUFFIX: (&str, &str) = ("いる", "接尾辞,動詞性接尾辞,母音動詞,基本形,いる,いる,*");
        const PERIOD: (&str, &str) = ("。", "特殊,句点,*,*,。,。,*");
        const BRACKET: (&str, &str) = ("「", "特殊,括弧始,*,*,「,「,*");
        let schema = last_words();
        let positions = |pairs: &[(&str, &str)]| schema.positions(&morphemes(pairs)).unwrap();
        // One word is the head and the function word.
        assert_eq!(positions(&[NOUN]), (0, 0));
        // A particle and a suffix are function words, and not heads.
        assert_eq!(positions(&[NOUN, PARTICLE]), (0, 1));
        assert_eq!(positions(&[VERB, SUFFIX]), (0, 1));
        assert_eq!(positions(&[VERB, SUFFIX, PARTICLE]), (0, 2));
        // The last word that is not a symbol is the function word, a head
        // or not: nothing is moved to it, and it is moved to nothing.
        assert_eq!(positions(&[NOUN, PARTICLE, NOUN]), (2, 2));
        assert_eq!(positions(&[SUFFIX, NOUN, PARTICLE, PARTICLE]), (1, 3));
        // A symbol is neither.
        assert_eq!(positions(&[VERB, SUFFIX, PERIOD]), (0, 1));
        assert_eq!(positions(&[BRACKET, NOUN, PERIOD]), (1, 1));
        // Without a word that can be one, each stays at the first morpheme.
        assert_eq!(positions(&[PERIOD]), (0, 0));
        assert_eq!(positions(&[BRACKET, PERIOD]), (0, 0));
        assert_eq!(positions(&[PARTICLE]), (0, 0));
        assert_eq!(positions(&[BRACKET, PARTICLE]), (0, 1));
        assert_eq!(schema.positions::<LatticeMorpheme>(&[]), None);

        // The patterns of the function words are not read by this rule.
        let with_patterns = Schema {
            function_words: vec![Pattern::new(&["名詞"])],
            ..last_words()
        };
        assert_eq!(
            with_patterns.positions(&morphemes(&[NOUN, PARTICLE])),
            Some((0, 1))
        );
        // The other rule, with the same patterns, has no function word
        // here: both positions are at the head.
        let apart = Schema {
            head_rule: HeadRule::FunctionWordsApart,
            ..last_words()
        };
        assert_eq!(apart.positions(&morphemes(&[NOUN, PARTICLE])), Some((0, 0)));
        assert_eq!(apart.positions(&morphemes(&[VERB, SUFFIX])), Some((0, 0)));
    }

    #[test]
    fn the_rule_of_the_head_comes_back_from_the_bytes() {
        assert_eq!(Schema::default().head_rule, HeadRule::FunctionWordsApart);
        assert_eq!(Schema::ipadic().head_rule, HeadRule::FunctionWordsApart);
        assert_eq!(Schema::unidic().head_rule, HeadRule::FunctionWordsApart);
        for (rule, code) in HeadRule::ALL {
            assert_eq!(rule.code(), code);
            assert_eq!(HeadRule::from_code(code).unwrap(), rule);
            let schema = Schema {
                head_rule: rule,
                ..last_words()
            };
            let mut bytes = Vec::new();
            schema.write(&mut bytes);
            // The rule is the third byte from the end of a schema.
            assert_eq!(bytes[bytes.len() - 3], code);
            let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
            assert_eq!(
                Schema::read(&mut reader, crate::model::VERSION).unwrap(),
                schema
            );
            assert_eq!(reader.remaining(), 0);
        }
        // A byte that is not a rule is refused.
        let mut bytes = Vec::new();
        last_words().write(&mut bytes);
        let rule = bytes.len() - 3;
        bytes[rule] = 2;
        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
        assert_eq!(
            Schema::read(&mut reader, crate::model::VERSION)
                .unwrap_err()
                .to_string(),
            "2 is not the code of a rule of the head"
        );
    }

    #[test]
    fn a_schema_comes_back_from_its_bytes() {
        for schema in [Schema::ipadic(), Schema::unidic(), Schema::default()] {
            let mut bytes = Vec::new();
            schema.write(&mut bytes);
            let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
            assert_eq!(
                Schema::read(&mut reader, crate::model::VERSION).unwrap(),
                schema
            );
            assert_eq!(reader.remaining(), 0);
        }
    }

    #[test]
    fn the_two_lists_of_patterns_keep_their_places_in_the_bytes() {
        let schema = Schema {
            function_words: vec![Pattern::new(&["助詞"])],
            not_heads: vec![Pattern::new(&["名詞", "非自立"]), Pattern::default()],
            ..Schema::default()
        };
        let mut bytes = Vec::new();
        schema.write(&mut bytes);
        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
        let read = Schema::read(&mut reader, crate::model::VERSION).unwrap();
        assert_eq!(read.function_words, [Pattern::new(&["助詞"])]);
        assert_eq!(read.not_heads.len(), 2);
    }

    #[test]
    fn bytes_that_end_inside_a_schema_are_an_error() {
        let mut bytes = Vec::new();
        Schema::ipadic().write(&mut bytes);
        for length in [0, 4, 20, 24, bytes.len() / 2, bytes.len() - 1] {
            let mut reader = Reader::new(&bytes[..length], "test bytes", Error::Chunker);
            let message = Schema::read(&mut reader, crate::model::VERSION)
                .unwrap_err()
                .to_string();
            assert!(message.contains("ends early"), "{length}: {message}");
        }
    }

    #[test]
    fn the_width_is_the_number_of_columns_the_schema_reads() {
        // IPADIC: four levels of part of speech, the conjugation type and
        // form, the base form.
        assert_eq!(Schema::ipadic().width(), 7);
        let mut schema = Schema::ipadic();
        schema.base_form = None;
        assert_eq!(schema.width(), 6);
        schema.conjugation_form = None;
        schema.conjugation_type = Some(9);
        assert_eq!(schema.width(), 10);
        schema.conjugation_type = None;
        assert_eq!(schema.width(), 4);
        schema.part_of_speech = 0..0;
        assert_eq!(schema.width(), 0);
    }

    #[test]
    fn morphemes_with_fewer_columns_than_the_schema_reads_are_refused() {
        let schema = Schema::ipadic();
        let wide = LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ");
        // An unknown word of MeCab has no reading: seven columns.
        let unknown = LatticeMorpheme::new("x", "名詞,一般,*,*,*,*,*");
        let narrow = LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*");
        let none: [LatticeMorpheme; 0] = [];
        assert!(schema.check(&none).is_ok());
        assert!(schema.check(&[wide.clone(), unknown.clone()]).is_ok());

        let error = schema.check(&[wide.clone(), unknown, narrow]).unwrap_err();
        assert!(matches!(error, Error::Dictionary(_)), "{error:?}");
        assert_eq!(
            error.to_string(),
            "the morpheme 3 (\"彼\") has fewer than the 7 feature columns the schema reads: it is not of the dictionary of the model"
        );

        // A schema that reads nothing refuses nothing.
        let mut schema = Schema::ipadic();
        schema.part_of_speech = 0..0;
        schema.conjugation_type = None;
        schema.conjugation_form = None;
        schema.base_form = None;
        assert!(schema.check(&[LatticeMorpheme::new("彼", "")]).is_ok());
    }

    /// する, alone in brackets before a particle: a function word of the
    /// schema of IPADIC, so the bunsetsu has no morpheme that can be the
    /// head word.
    const SURU: (&str, &str) = ("する", "動詞,自立,*,*,サ変・スル,基本形,する,スル,スル");
    const TO: (&str, &str) = ("と", "助詞,格助詞,引用,*,*,*,と,ト,ト");
    /// A full-width space, as IPADIC gives it.
    const SPACE: (&str, &str) = ("\u{3000}", "記号,空白,*,*,*,*,\u{3000},\u{3000},\u{3000}");

    /// A morpheme of UniDic, from its surface, the levels of its part of
    /// speech and its lemma.
    fn unidic(surface: &'static str, part_of_speech: &str, lemma: &str) -> LatticeMorpheme {
        let levels: Vec<&str> = part_of_speech.split(',').collect();
        let mut columns = vec!["*"; 17];
        columns[..levels.len()].copy_from_slice(&levels);
        columns[7] = lemma;
        LatticeMorpheme::new(surface, columns.join(","))
    }

    #[test]
    fn the_schemas_of_this_crate_take_the_first_word() {
        assert_eq!(Schema::ipadic().head_fallback, HeadFallback::FirstWord);
        assert_eq!(Schema::unidic().head_fallback, HeadFallback::FirstWord);
        assert_eq!(Schema::default().head_fallback, HeadFallback::FirstMorpheme);
    }

    /// The schema of a model converted from CaboCha's: the `cabocha` module
    /// is behind the `train` feature.
    #[cfg(feature = "train")]
    #[test]
    fn the_schemas_of_cabocha_take_the_first_morpheme() {
        use crate::cabocha::{self, PartOfSpeechSet};

        for set in [
            PartOfSpeechSet::Ipa,
            PartOfSpeechSet::Juman,
            PartOfSpeechSet::Unidic,
        ] {
            assert_eq!(
                cabocha::schema(set).head_fallback,
                HeadFallback::FirstMorpheme,
                "{set:?}"
            );
        }
    }

    #[test]
    fn a_bunsetsu_without_a_head_word_has_its_first_word_as_the_head() {
        // 「 / する / 」 / と: the bracket is no word.
        assert_eq!(positions(&[KAGI, SURU, KAGI_TOJI, TO]), (1, 3));
        // する at the start is the head as before: it is the first word.
        assert_eq!(positions(&[SURU, TO]), (0, 1));
        // Brackets and a particle alone: there is no word, and the first
        // morpheme is taken.
        assert_eq!(positions(&[KAGI, KAGI_TOJI, TO]), (0, 2));
        // A bunsetsu with a head word is as it was.
        assert_eq!(positions(&[KAGI, HON, KAGI_TOJI, WO]), (1, 3));

        // With the first morpheme, as CaboCha: the bracket.
        let first_morpheme = Schema {
            head_fallback: HeadFallback::FirstMorpheme,
            ..Schema::ipadic()
        };
        assert_eq!(
            first_morpheme.positions(&morphemes(&[KAGI, SURU, KAGI_TOJI, TO])),
            Some((0, 3))
        );
    }

    #[test]
    fn a_word_in_letters_keeps_its_first_letter_and_a_mark_before_a_verb_is_passed_over() {
        let schema = Schema::unidic();
        let open = unidic("「", "補助記号,括弧開", "「");
        let close = unidic("」", "補助記号,括弧閉", "」");
        let to = unidic("と", "助詞,格助詞", "と");
        let no = unidic("の", "助詞,格助詞", "の");
        // 治す is 動詞,非自立可能 in UniDic: a function word of the schema.
        let naosu = unidic("治す", "動詞,非自立可能", "直す");
        let letter = |surface| unidic(surface, "記号,文字", surface);

        // 「 / 治す / 」 / と
        assert_eq!(
            schema.positions(&[open.clone(), naosu, close.clone(), to.clone()]),
            Some((1, 3))
        );
        // S / i / r / i / の: UniDic cuts the word into letters, which it
        // calls symbols, and the first one stays the head word.
        assert_eq!(
            schema.positions(&[
                letter("S"),
                letter("i"),
                letter("r"),
                letter("i"),
                no.clone()
            ]),
            Some((0, 4))
        );
        // 「 / S / M / T / 」 / と: the first letter, and not the bracket.
        assert_eq!(
            schema.positions(&[open, letter("S"), letter("M"), letter("T"), close, to]),
            Some((1, 5))
        );
        // ♂ / の: a mark and a particle. The particle is not taken.
        assert_eq!(
            schema.positions(&[unidic("♂", "補助記号,一般", "♂"), no]),
            Some((0, 1))
        );
    }

    #[test]
    fn a_space_is_neither_the_head_word_nor_the_function_word() {
        // A space before する, which is a function word: する is the head.
        assert_eq!(positions(&[SPACE, SURU]), (1, 1));
        // Between a noun and its particle, and after them.
        assert_eq!(positions(&[HON, SPACE, WO]), (0, 2));
        assert_eq!(positions(&[HON, WO, SPACE]), (0, 1));
        // Spaces alone: there is no word.
        assert_eq!(positions(&[SPACE, SPACE]), (0, 0));
        // A space is told by its surface, whatever part of speech the
        // dictionary gives it: one that is a noun there is no head word.
        const NOUN_SPACE: (&str, &str) = (" ", "名詞,一般,*,*,*,*,*,*,*");
        assert_eq!(positions(&[NOUN_SPACE, HON, WO]), (1, 2));
        assert_eq!(positions(&[HON, NOUN_SPACE, WO]), (0, 2));
        assert_eq!(positions(&[HON, WO, NOUN_SPACE]), (0, 1));
        // A space and marks alone: the first mark, and not the space.
        assert_eq!(positions(&[SPACE, KAGI, KAGI_TOJI]), (1, 1));

        // UniDic gives a space the part of speech 空白, and 治す is a
        // function word there.
        let space = unidic("\u{3000}", "空白", "\u{3000}");
        let naosu = unidic("治す", "動詞,非自立可能", "直す");
        assert_eq!(Schema::unidic().positions(&[space, naosu]), Some((1, 1)));

        // With the first morpheme, the space is passed over too: by the
        // rule, and when the rule finds no head word.
        let first_morpheme = Schema {
            head_fallback: HeadFallback::FirstMorpheme,
            ..Schema::ipadic()
        };
        assert_eq!(
            first_morpheme.positions(&morphemes(&[SPACE, HON, WO])),
            Some((1, 2))
        );
        assert_eq!(
            first_morpheme.positions(&morphemes(&[SPACE, SURU])),
            Some((1, 1))
        );
        assert_eq!(
            first_morpheme.positions(&morphemes(&[SPACE, KAGI, SURU])),
            Some((1, 2))
        );
    }

    #[test]
    fn the_head_word_of_a_bunsetsu_without_one_comes_back_from_the_bytes() {
        for (fallback, code) in HeadFallback::ALL {
            assert_eq!(fallback.code(), code);
            assert_eq!(HeadFallback::from_code(code).unwrap(), fallback);
            let schema = Schema {
                head_fallback: fallback,
                ..last_words()
            };
            let mut bytes = Vec::new();
            schema.write(&mut bytes);
            // It is the byte before the last of a schema.
            assert_eq!(bytes[bytes.len() - 2], code);
            let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
            assert_eq!(
                Schema::read(&mut reader, crate::model::VERSION).unwrap(),
                schema
            );
            assert_eq!(reader.remaining(), 0);
        }
        // A byte that is not one is refused.
        let mut bytes = Vec::new();
        last_words().write(&mut bytes);
        let fallback = bytes.len() - 2;
        bytes[fallback] = 2;
        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
        assert_eq!(
            Schema::read(&mut reader, crate::model::VERSION)
                .unwrap_err()
                .to_string(),
            "2 is not the code of a head word for a bunsetsu without one"
        );
    }

    #[test]
    fn the_schema_of_a_file_of_version_3_ends_with_the_rule_and_takes_the_first_morpheme() {
        // What the version 3 wrote: the bytes of today without the last
        // two.
        let schema = Schema {
            head_fallback: HeadFallback::FirstWord,
            sentence_split: SentenceSplit::AfterEnds,
            ..last_words()
        };
        let mut bytes = Vec::new();
        schema.write(&mut bytes);
        bytes.pop();
        bytes.pop();
        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
        let read = Schema::read(&mut reader, 3).unwrap();
        assert_eq!(reader.remaining(), 0);
        assert_eq!(
            read,
            Schema {
                head_fallback: HeadFallback::FirstMorpheme,
                sentence_split: SentenceSplit::None,
                ..schema
            }
        );
        // Read as the version 4, the same bytes end early.
        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
        assert!(Schema::read(&mut reader, 4).is_err());
    }

    const HATENA: (&str, &str) = ("?", "記号,一般,*,*,*,*,?,?,?");

    /// The words at which the schema of IPADIC cuts a text.
    fn starts(pairs: &[(&str, &str)]) -> Vec<usize> {
        Schema::ipadic().sentence_starts(&morphemes(pairs))
    }

    #[test]
    fn the_schemas_of_this_crate_cut_a_text_into_sentences() {
        assert_eq!(Schema::ipadic().sentence_split, SentenceSplit::AfterEnds);
        assert_eq!(Schema::unidic().sentence_split, SentenceSplit::AfterEnds);
        assert_eq!(Schema::default().sentence_split, SentenceSplit::None);
    }

    /// The schema of a model converted from CaboCha's: the `cabocha` module
    /// is behind the `train` feature.
    #[cfg(feature = "train")]
    #[test]
    fn the_schemas_of_cabocha_do_not_cut_a_text() {
        use crate::cabocha::{self, PartOfSpeechSet};

        for set in [
            PartOfSpeechSet::Ipa,
            PartOfSpeechSet::Juman,
            PartOfSpeechSet::Unidic,
        ] {
            let schema = cabocha::schema(set);
            assert_eq!(schema.sentence_split, SentenceSplit::None, "{set:?}");
            assert!(
                schema
                    .sentence_starts(&morphemes(&[HON, MARU, HON, WO]))
                    .is_empty(),
                "{set:?}"
            );
        }
    }

    #[test]
    fn a_text_is_cut_after_its_sentence_ends() {
        // 本 / 。 / 本 / を: the word after the period starts a sentence.
        assert_eq!(starts(&[HON, MARU, HON, WO]), [2]);
        // A sentence of its own has no start but its first word.
        assert!(starts(&[HON, WO, YOMU, MARU]).is_empty());
        assert!(starts(&[HON, WO, YOMU]).is_empty());
        assert!(starts(&[]).is_empty());
        // Three sentences, the second one a word alone.
        assert_eq!(starts(&[HON, MARU, YOMU, MARU, HON, MARU]), [2, 4]);
        // ? and ! end a sentence as 。 does, and ends in a row are one.
        assert_eq!(starts(&[HON, HATENA, HON]), [2]);
        assert_eq!(starts(&[HON, HATENA, HATENA, MARU, HON]), [4]);
        assert_eq!(
            starts(&[HON, ("!?", "記号,一般,*,*,*,*,*,*,*"), HON]),
            [2]
        );
        // A comma ends nothing.
        assert!(starts(&[HON, TEN, HON]).is_empty());
    }

    #[test]
    fn a_closing_bracket_stays_with_the_sentence_it_closes() {
        // 「 / 本 / 。 / 」 / 本: the bracket is of the first sentence.
        assert_eq!(starts(&[KAGI, HON, MARU, KAGI_TOJI, HON]), [4]);
        // Nothing after the bracket: one sentence.
        assert!(starts(&[KAGI, HON, MARU, KAGI_TOJI]).is_empty());
        // An opening bracket starts the next sentence.
        assert_eq!(starts(&[HON, MARU, KAGI, HON, KAGI_TOJI]), [2]);
    }

    /// A word of marks that IPADIC does not have: an unknown word, with
    /// the part of speech of a noun.
    fn joined(surface: &str) -> (&str, &str) {
        (surface, "名詞,サ変接続,*,*,*,*,*,*,*")
    }

    #[test]
    fn a_sentence_end_joined_with_other_marks_cuts_the_text() {
        // 読む / ~。 / 本, 読む / )。 / 本 and 読む / %。 / 本.
        for end in ["~。", ")。", "%。", "!?"] {
            assert_eq!(starts(&[YOMU, joined(end), HON]), [2], "{end}");
        }
        // The ends and the closing brackets after it stay with it.
        assert_eq!(
            starts(&[YOMU, joined("~。"), KAGI_TOJI, joined(")。"), HON]),
            [4]
        );
        // Marks without an end.
        for other in [",“", "~」", "()"] {
            assert!(starts(&[YOMU, joined(other), HON]).is_empty(), "{other}");
        }
        // 本 / (?) / 本 is cut as 本 / ( / ? / ) / 本 is, and not before a
        // function word: its bracket is closed.
        assert_eq!(starts(&[HON, joined("(?)"), HON]), [2]);
        assert_eq!(starts(&[HON, joined("("), HATENA, joined(")"), HON]), [4]);
        assert!(starts(&[HON, joined("(?)"), GA, YOMU]).is_empty());
        assert!(starts(&[HON, joined("("), HATENA, joined(")"), GA, YOMU]).is_empty());
    }

    #[test]
    fn the_closing_bracket_of_a_joined_sentence_end_is_one_of_the_exception() {
        // 「 / 本 / ?」 / で / 読む: で follows a closing bracket, the one of
        // ?」, and is of the bunsetsu of the quotation.
        assert!(starts(&[KAGI, HON, joined("?」"), DE, YOMU]).is_empty());
        assert!(starts(&[KAGI, HON, joined("?」"), DA]).is_empty());
        // Another word after it starts a sentence.
        assert_eq!(starts(&[KAGI, HON, joined("?」"), HON]), [3]);
        // The same when ?」 follows another end: 本 / 。 / ?」 / で.
        assert!(starts(&[HON, MARU, joined("?」"), DE, YOMU]).is_empty());
        // A closing bracket before the end closes nothing after it: で
        // starts a sentence, as after 。 alone.
        assert_eq!(starts(&[HON, joined(")。"), DE, YOMU]), [2]);
        assert_eq!(starts(&[HON, MARU, DE, YOMU]), [2]);
    }

    #[test]
    fn the_words_that_stay_with_the_end_of_a_sentence() {
        let tails = |pairs: &[(&str, &str)]| Schema::ipadic().sentence_parts(&morphemes(pairs)).1;
        // 本 / 。 / 」 / 本 / ?: the period, the bracket after it, and the
        // last mark.
        assert_eq!(tails(&[HON, MARU, KAGI_TOJI, HON, HATENA]), [1, 2, 4]);
        // A closing bracket that follows no end is none of them, and an
        // end joined with marks is one.
        assert_eq!(tails(&[KAGI, HON, KAGI_TOJI, HON, joined(")。")]), [4]);
        // Before a word that starts no sentence too.
        assert_eq!(tails(&[KAGI, HON, joined("?」"), TO, YOMU]), [2]);
        // A text that starts with an end.
        assert_eq!(tails(&[MARU, HON]), [0]);
        assert!(tails(&[HON, WO, YOMU]).is_empty());
        // A schema that does not cut names none.
        let whole = Schema {
            sentence_split: SentenceSplit::None,
            ..Schema::ipadic()
        };
        assert_eq!(
            whole.sentence_parts(&morphemes(&[HON, MARU, HON])),
            (Vec::new(), Vec::new())
        );
    }

    #[test]
    fn a_function_word_after_a_closing_bracket_does_not_start_a_sentence() {
        // 「 / 本 / を / 読む / 。 / 」 / と / 読む: と is of the bunsetsu of
        // the quotation.
        assert!(starts(&[KAGI, HON, WO, YOMU, MARU, KAGI_TOJI, TO, YOMU]).is_empty());
        // An auxiliary too: …。 / 」 / だ.
        assert!(starts(&[KAGI, HON, MARU, KAGI_TOJI, DA]).is_empty());
        // The sentence in the quotation that is not the last one is cut,
        // and the function word after the bracket is not.
        assert_eq!(
            starts(&[KAGI, YOMU, MARU, HON, WO, YOMU, MARU, KAGI_TOJI, TO, YOMU]),
            [3]
        );
        // Without a closing bracket, a function word starts a sentence as
        // any word does: 読む / 。 / だ / が (だが).
        assert_eq!(starts(&[YOMU, MARU, DA, GA, HON]), [2]);
        assert_eq!(starts(&[YOMU, MARU, DE, HON]), [2]);
        assert_eq!(starts(&[YOMU, MARU, NI, HON]), [2]);
        // A word that is no function word starts one after a bracket.
        assert_eq!(starts(&[KAGI, YOMU, MARU, KAGI_TOJI, HON, WO]), [4]);
    }

    #[test]
    fn the_particle_of_a_quotation_does_not_start_a_sentence() {
        // 読む / ? / と / 、 / 読む: a quotation without brackets.
        assert!(starts(&[YOMU, HATENA, TO, TEN, YOMU]).is_empty());
        assert!(starts(&[YOMU, MARU, TO, YOMU]).is_empty());
        let tte = ("って", "助詞,格助詞,連語,*,*,*,って,ッテ,ッテ");
        assert!(starts(&[YOMU, HATENA, tte, YOMU]).is_empty());
        // The sentence before it in the same text is cut.
        assert_eq!(starts(&[YOMU, HATENA, HON, HATENA, TO, YOMU]), [2]);
        // と that is no particle starts a sentence: by the part of speech,
        // and not by the surface alone.
        let noun = ("と", "名詞,一般,*,*,*,*,と,ト,ト");
        assert_eq!(starts(&[YOMU, MARU, noun, YOMU]), [2]);
        // The other particles do: UniDic gives でも as で / も, and
        // にもかかわらず as に / も / ….
        let schema = Schema::unidic();
        let text = [
            unidic("本", "名詞,普通名詞", "本"),
            unidic("。", "補助記号,句点", "。"),
            unidic("で", "助詞,格助詞", "で"),
            unidic("も", "助詞,係助詞", "も"),
            unidic("本", "名詞,普通名詞", "本"),
        ];
        assert_eq!(schema.sentence_starts(&text), [2]);
        let text = [
            unidic("本", "名詞,普通名詞", "本"),
            unidic("?", "補助記号,句点", "?"),
            unidic("と", "助詞,格助詞", "と"),
            unidic("本", "名詞,普通名詞", "本"),
        ];
        assert!(schema.sentence_starts(&text).is_empty());
    }

    #[test]
    fn a_half_width_period_and_a_period_before_a_digit_end_nothing() {
        // IPADIC: 4 / . / 20.
        let digits = |surface: &'static str| (surface, "名詞,数,*,*,*,*,*");
        assert!(starts(&[digits("4"), (".", "記号,句点,*,*,*,*,.,.,."), digits("20")]).is_empty());
        // 3 / . / 14 is a number, and 本 / . / 本 two sentences.
        let wide = (".", "記号,句点,*,*,*,*,.,.,.");
        assert!(starts(&[digits("3"), wide, digits("14")]).is_empty());
        assert_eq!(starts(&[HON, wide, HON]), [2]);
        // UniDic calls the half-width period 補助記号,句点: 1 / . / 060 is
        // one number, and L / . / E / . / D one word.
        let schema = Schema::unidic();
        let dot = || unidic(".", "補助記号,句点", ".");
        let number = [
            unidic("1", "名詞,数詞", "1"),
            dot(),
            unidic("060", "名詞,数詞", "060"),
        ];
        assert!(schema.sentence_starts(&number).is_empty());
        let letters = [
            unidic("L", "記号,文字", "L"),
            dot(),
            unidic("E", "記号,文字", "E"),
            dot(),
            unidic("D", "記号,文字", "D"),
        ];
        assert!(schema.sentence_starts(&letters).is_empty());
        // And cuts after 。 as IPADIC does.
        let text = [
            unidic("本", "名詞,普通名詞", "本"),
            unidic("。", "補助記号,句点", "。"),
            unidic("本", "名詞,普通名詞", "本"),
        ];
        assert_eq!(schema.sentence_starts(&text), [2]);
    }

    #[test]
    fn a_schema_that_does_not_cut_gives_no_start() {
        let whole = Schema {
            sentence_split: SentenceSplit::None,
            ..Schema::ipadic()
        };
        for text in [
            &[HON, MARU, HON, WO][..],
            &[HON, HATENA, HON],
            &[KAGI, HON, MARU, KAGI_TOJI, HON],
        ] {
            assert!(whole.sentence_starts(&morphemes(text)).is_empty());
            assert!(!starts(text).is_empty());
        }
    }

    #[test]
    fn the_cut_into_sentences_comes_back_from_the_bytes() {
        for (split, code) in SentenceSplit::ALL {
            assert_eq!(split.code(), code);
            assert_eq!(SentenceSplit::from_code(code).unwrap(), split);
            let schema = Schema {
                sentence_split: split,
                ..last_words()
            };
            let mut bytes = Vec::new();
            schema.write(&mut bytes);
            // It is the last byte of a schema.
            assert_eq!(bytes.last(), Some(&code));
            let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
            assert_eq!(
                Schema::read(&mut reader, crate::model::VERSION).unwrap(),
                schema
            );
            assert_eq!(reader.remaining(), 0);
        }
        // A byte that is not one is refused.
        let mut bytes = Vec::new();
        last_words().write(&mut bytes);
        *bytes.last_mut().unwrap() = 2;
        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
        assert_eq!(
            Schema::read(&mut reader, crate::model::VERSION)
                .unwrap_err()
                .to_string(),
            "2 is not the code of a way to cut a text into sentences"
        );
    }
}

#[cfg(test)]
mod sentence_ends_tests {
    use crate::Schema;
    use crate::lattice::LatticeMorpheme;

    /// The morphemes of a text, from their surfaces: brackets and periods
    /// with the features of IPADIC, anything else as a noun.
    fn morphemes(surfaces: &[&str]) -> Vec<LatticeMorpheme> {
        surfaces
            .iter()
            .map(|surface| {
                let features = match *surface {
                    "。" | "." | "." => {
                        format!("記号,句点,*,*,*,*,{surface},{surface},{surface}")
                    }
                    "「" | "(" => format!("記号,括弧開,*,*,*,*,{surface},{surface},{surface}"),
                    "」" | ")" => format!("記号,括弧閉,*,*,*,*,{surface},{surface},{surface}"),
                    "!" | "?" | "!" | "?" | "!?" => {
                        format!("記号,一般,*,*,*,*,{surface},{surface},{surface}")
                    }
                    "\u{3000}" => format!("記号,空白,*,*,*,*,{surface},{surface},{surface}"),
                    _ => format!("名詞,一般,*,*,*,*,{surface},{surface},{surface}"),
                };
                LatticeMorpheme::new(*surface, features)
            })
            .collect()
    }

    /// The ends of the sentences of a text.
    fn ends(surfaces: &[&str]) -> Vec<usize> {
        Schema::ipadic().sentence_ends(&morphemes(surfaces))
    }

    #[test]
    fn no_morpheme_is_no_sentence() {
        assert_eq!(ends(&[]), Vec::<usize>::new());
    }

    #[test]
    fn a_period_ends_a_sentence_and_the_rest_is_one() {
        assert_eq!(ends(&["本", "。"]), [2]);
        assert_eq!(ends(&["本", "。", "本", "。"]), [2, 4]);
        // Without a period at the end.
        assert_eq!(ends(&["本", ".", "本"]), [2, 3]);
        assert_eq!(ends(&["本", "。。", "本"]), [2, 3]);
        assert_eq!(ends(&["本", "本"]), [2]);
        // A period alone is a sentence.
        assert_eq!(ends(&["。"]), [1]);
    }

    #[test]
    fn marks_joined_into_one_word_are_read_one_at_a_time() {
        // 本 ( 笑 )。 本 。: the bracket is closed in )。, whose 。 ends the
        // sentence, and the next sentence is cut too.
        assert_eq!(ends(&["本", "(", "笑", ")。", "本", "。"]), [4, 6]);
        // The same with the marks as words of their own.
        assert_eq!(ends(&["本", "(", "笑", ")", "。", "本", "。"]), [5, 7]);
        // 「 本 ?」 と 本 。 本 。: the ? is inside the bracket, which ?」
        // closes.
        assert_eq!(
            ends(&["「", "本", "?」", "と", "本", "。", "本", "。"]),
            [6, 8]
        );
        assert_eq!(
            ends(&["「", "本", "?", "」", "と", "本", "。", "本", "。"]),
            [7, 9]
        );
        // An end after other marks, outside brackets.
        assert_eq!(ends(&["本", "~。", "本"]), [2, 3]);
        assert_eq!(ends(&["本", "%。", "本", "!?"]), [2, 4]);
        // Inside a bracket it ends nothing.
        assert_eq!(ends(&["「", "本", "~。", "本", "」", "本"]), [6]);
        // A bracket that a word of marks opens: 本 ,“ 本 。 ” 本 。
        assert_eq!(ends(&["本", ",“", "本", "。", "”", "本", "。"]), [7]);
        // (?) opens and closes its bracket, and ends nothing.
        assert_eq!(ends(&["本", "(?)", "本", "。", "本"]), [4, 5]);
        // An end and a closing bracket without an opening one.
        assert_eq!(ends(&["本", "?」", "本"]), [2, 3]);
        // A word with a letter is no mark.
        assert_eq!(ends(&["本。", "本"]), [2]);
        // An end that another mark follows in its word is not its last
        // mark, and one that an opening bracket follows is before it.
        assert_eq!(ends(&["本", "。~", "本"]), [3]);
        assert_eq!(ends(&["本", "?「", "本", "」", "本"]), [5]);
        // . alone inside a bracket ends nothing, as outside before a digit.
        assert_eq!(ends(&["「", "本", ".", "本", "」"]), [5]);
        assert_eq!(ends(&["本", ".", "本"]), [2, 3]);
    }

    #[test]
    fn an_opening_bracket_that_nothing_closes_is_no_bracket() {
        // 本 :(。 本 。 本 。 and 本 ( 泣 。 本 。 本 。: the sentences after
        // the bracket are cut.
        assert_eq!(ends(&["本", ":(。", "本", "。", "本", "。"]), [2, 4, 6]);
        assert_eq!(
            ends(&["本", "(", "泣", "。", "本", "。", "本", "。"]),
            [4, 6, 8]
        );
        // A bracket that is closed keeps what is inside it: only the one
        // nothing closes is left out. 本 ( 本 「 本 。 」 本 。
        assert_eq!(
            ends(&["本", "(", "本", "「", "本", "。", "」", "本", "。"]),
            [9]
        );
        // The closing bracket closes the last one that is open: 「 本 ( 本 。
        // 」 本 。 has ( … 」 as its bracket, and 「 open no more.
        assert_eq!(ends(&["「", "本", "(", "本", "。", "」", "本", "。"]), [8]);
        // A closing bracket that closes nothing changes nothing.
        assert_eq!(ends(&["本", ")", "本", "。", "本"]), [4, 5]);
        // Two that are open and one that is closed: the first is left out.
        assert_eq!(
            ends(&["(", "本", "。", "(", "本", "。", ")", "本", "。"]),
            [3, 9]
        );
    }

    #[test]
    fn a_period_of_a_number_and_a_half_width_period_end_nothing() {
        // The half-width period: 4.20, an ellipsis, and at the end.
        assert_eq!(ends(&["4", ".", "20", "本", "。", "本"]), [5, 6]);
        assert_eq!(ends(&["本", ".", ".", ".", "本", "."]), [6]);
        // The full-width one before a digit, of either width.
        assert_eq!(ends(&["3", ".", "14", "本", ".", "本"]), [5, 6]);
        assert_eq!(ends(&["3", ".", "14", "."]), [4]);
    }

    #[test]
    fn a_period_inside_brackets_ends_nothing() {
        assert_eq!(ends(&["「", "本", "。", "」", "本", "。", "本"]), [6, 7]);
        // Two levels.
        assert_eq!(
            ends(&["(", "「", "本", "。", "」", "本", "。", ")", "本", "。"]),
            [10]
        );
    }

    #[test]
    fn exclamation_and_question_marks_end_a_sentence() {
        assert_eq!(
            ends(&["本", "!", "本", "?", "本", "!", "本", "?", "本"]),
            [2, 4, 6, 8, 9]
        );
        assert_eq!(ends(&["本", "!?", "本"]), [2, 3]);
        assert_eq!(ends(&["「", "本", "!", "」", "本"]), [5]);
    }

    #[test]
    fn what_follows_an_end_and_belongs_to_it_stays_with_the_sentence() {
        // More ends, and a closing bracket that nothing opened.
        assert_eq!(ends(&["本", "。", "。", "本"]), [3, 4]);
        assert_eq!(ends(&["本", "!", "?", "本"]), [3, 4]);
        assert_eq!(ends(&["本", "。", "」", "本", "。"]), [3, 5]);
    }

    #[test]
    fn the_spaces_after_an_end_stay_with_the_sentence() {
        // 本。␣本。␣␣: no sentence starts with a space, and none is of
        // spaces alone.
        assert_eq!(
            ends(&["本", "。", "\u{3000}", "本", "。", "\u{3000}", "\u{3000}"]),
            [3, 7]
        );
        // A space elsewhere ends nothing.
        assert_eq!(ends(&["本", "\u{3000}", "本", "。"]), [4]);
        assert_eq!(ends(&["\u{3000}", "本"]), [2]);
    }

    #[test]
    fn a_bracket_by_the_part_of_speech_of_the_schema_is_a_bracket() {
        // < 本 。 > 本, with the part of speech of a bracket: the two
        // characters are no brackets of the crate.
        let bracket = |surface: &str, kind: &str| {
            LatticeMorpheme::new(
                surface,
                format!("記号,{kind},*,*,*,*,{surface},{surface},{surface}"),
            )
        };
        let mut text = morphemes(&["本", "。", "本"]);
        text.insert(0, bracket("<", "括弧開"));
        text.insert(3, bracket(">", "括弧閉"));
        assert_eq!(Schema::ipadic().sentence_ends(&text), [5]);
        // As nouns they are none.
        assert_eq!(ends(&["<", "本", "。", ">", "本"]), [3, 5]);
    }

    #[test]
    fn the_brackets_of_what_follows_an_end_are_counted() {
        // 本 。 (。 本 。 ) 本 。: (。 stays with the sentence the first 。
        // ends, and its bracket is open until ).
        assert_eq!(
            ends(&["本", "。", "(。", "本", "。", ")", "本", "。"]),
            [3, 8]
        );
    }

    #[test]
    fn a_bracket_that_is_never_closed_does_not_keep_the_rest_in_one_sentence() {
        // Lindera 7.2.0 gave one sentence.
        assert_eq!(ends(&["「", "本", "。", "本", "。"]), [3, 5]);
        // With its closing bracket, the sentence inside stays inside.
        assert_eq!(ends(&["「", "本", "。", "本", "。", "」"]), [6]);
    }
}