suiko 0.3.10

Deterministic diagnostics for natural and readable Japanese writing
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
//! 品詞列(Sudachi形態素)ベースの検出器と、文単位のtoken補助。

use std::collections::{BTreeMap, BTreeSet};

use regex::Regex;

use crate::Error;
use crate::morphology::{Morpheme, Morphology};
use crate::text::Sentence;

use super::{Finding, Span, Suggestion, make_span};

// Sudachi品詞体系。IPADICで名詞に含まれた代名詞と形容動詞語幹(形状詞)を
// 独立品詞として持つため、内容語の範囲を揃えて列挙する。
pub(super) const CONTENT_POS: &[&str] = &["名詞", "代名詞", "形状詞", "動詞", "形容詞", "副詞"];

const TRANSITIVE_SMELL_VERBS: &[&str] = &[
    "もたらす",
    "示す",
    "意味する",
    "証明する",
    "生み出す",
    "反映する",
    "示唆する",
    "物語る",
    "浮き彫りにする",
    "後押しする",
];

const ABSTRACT_METAPHOR_NOUNS: &[&str] = &[
    "地図",
    "羅針盤",
    "\u{5951}\u{7d04}",
    "道標",
    "土台",
    "架け橋",
];

const ABSTRACT_CONTEXT_NOUNS: &[&str] = &[
    "実装",
    "判断",
    "設計",
    "仕様",
    "方針",
    "計画",
    "戦略",
    "議論",
    "思考",
    "理解",
    "運用",
    "開発",
    "組織",
    "事業",
    "変革",
    "成長",
    "課題",
    "解決",
    "意思決定",
];

const SELF_LABEL_EVALUATIONS: &[&str] = &["必要", "重要", "大切", "面白い", "興味深い"];

const TECHNICAL_STATUS_NOUNS: &[&str] = &[
    "テスト",
    "テスト結果",
    "検査結果",
    "CI",
    "ビルド",
    "パイプライン",
];

const DISPLAY_NOUNS: &[&str] = &[
    "表示",
    "アイコン",
    "ランプ",
    "バッジ",
    "画面",
    "背景",
    "文字",
    "色",
    "線",
];

const SOFTWARE_NOUNS: &[&str] = &[
    "コード",
    "機能",
    "変更",
    "修正",
    "ソフトウェア",
    "API",
    "実装",
];

const PHYSICAL_SHIPMENT_NOUNS: &[&str] = &[
    "工場", "倉庫", "在庫", "配送", "端末", "機器", "製品", "検品",
];

const ABSTRACT_TRANSPORT_SUBJECTS: &[&str] = &["仕様", "設計", "仕組み", "指標", "議論"];

const ABSTRACT_TRANSPORT_OBJECTS: &[&str] = &["意図", "判断", "理解", "実装", "成果"];

const ABSTRACT_EFFECT_SUBJECTS: &[&str] = &["複雑", "品質", "生産性", "リスク"];

const QUANTITY_NOUN_ENDINGS: &[&str] = &["量", "数"];

const TECHNICAL_WORDING_NOUNS: &[&str] = &[
    "コード",
    "機能",
    "実装",
    "設定",
    "データ",
    "入力",
    "出力",
    "処理",
    "ログ",
    "API",
    "テスト",
    "ビルド",
    "キャッシュ",
    "クエリ",
];

#[derive(Clone, Debug)]
pub(super) struct TokenizedSentence {
    pub(super) line: usize,
    pub(super) text: String,
    pub(super) raw_text: String,
    pub(super) end_mark: Option<char>,
    pub(super) line_byte_start: usize,
    pub(super) tokens: Vec<Morpheme>,
}

impl TokenizedSentence {
    /// 文内のtoken byte範囲を行内のbyte範囲へ写す。
    pub(super) fn span(
        &self,
        raw_lines: &[&str],
        byte_start: usize,
        byte_end: usize,
    ) -> Option<Span> {
        make_span(
            raw_lines,
            self.line,
            self.line_byte_start + byte_start,
            self.line,
            self.line_byte_start + byte_end,
        )
    }

    /// 文内byte範囲の抜粋。raw側が範囲を切り出せない場合はmasked本文へ落とす。
    pub(super) fn excerpt(&self, byte_start: usize, byte_end: usize) -> String {
        self.raw_text
            .get(byte_start..byte_end)
            .unwrap_or(&self.text[byte_start..byte_end])
            .to_owned()
    }

    fn info_finding(
        &self,
        raw_lines: &[&str],
        bytes: std::ops::Range<usize>,
        category: &str,
        detail: impl Into<String>,
    ) -> Finding {
        let mut finding = Finding::new(
            self.line,
            category,
            self.excerpt(bytes.start, bytes.end),
            "info",
            detail,
        );
        finding.span = self.span(raw_lines, bytes.start, bytes.end);
        finding
    }
}

pub(super) fn tokenize(
    split: &[Sentence],
    morphology: &Morphology,
) -> Result<Vec<TokenizedSentence>, Error> {
    split
        .iter()
        .map(|sentence| {
            Ok(TokenizedSentence {
                line: sentence.line,
                text: sentence.text.clone(),
                raw_text: sentence.raw_text.clone(),
                end_mark: sentence.end_mark,
                line_byte_start: sentence.line_byte_start,
                tokens: morphology.tokenize(&sentence.text)?,
            })
        })
        .collect()
}

pub(super) fn significant_tokens(tokens: &[Morpheme]) -> &[Morpheme] {
    let start = tokens
        .iter()
        .position(|token| !matches!(token.pos(0), "記号" | "補助記号" | "空白"))
        .unwrap_or(tokens.len());
    &tokens[start..]
}

pub(super) fn short_topic_comma_findings(
    tokenized: &[TokenizedSentence],
    raw_lines: &[&str],
) -> Vec<Finding> {
    let mut findings = Vec::new();
    for sentence in tokenized {
        let tokens = &sentence.tokens;
        let Some(comma_index) = tokens.iter().position(|token| token.surface == "、") else {
            continue;
        };
        // nwiizo-coding-style: 5文字以内の名詞句+係助詞「は」に限定する;
        // 節やほかの読点へ広げる場合は、必要な区切りを残す評価例を先に追加する。
        if comma_index < 2 {
            continue;
        }
        let comma = &tokens[comma_index];
        let topic = &tokens[comma_index - 1];
        let prefix = &sentence.text[..comma.byte_start];
        if topic.surface != "は"
            || topic.pos(0) != "助詞"
            || topic.pos(1) != "係助詞"
            || prefix.chars().count() > 5
            || !tokens[..comma_index - 1].iter().all(|token| {
                matches!(
                    token.pos(0),
                    "名詞" | "代名詞" | "連体詞" | "接頭辞" | "接尾辞"
                )
            })
            || !tokens[comma_index + 1..]
                .iter()
                .any(|token| CONTENT_POS.contains(&token.pos(0)))
            || !sentence
                .raw_text
                .starts_with(&sentence.text[..comma.byte_end])
        {
            continue;
        }
        let mut finding = sentence.info_finding(
            raw_lines,
            comma.byte_start..comma.byte_end,
            "short_topic_comma",
            "短い主題の直後に読点があります。区切りが読みやすさや意図した間に必要か確認してください。必要な読点は残せます。",
        );
        finding.excerpt = sentence.excerpt(0, comma.byte_end);
        findings.push(finding);
    }
    findings
}

pub(super) fn punctuation_between(tokens: &[Morpheme], first: usize, second: usize) -> bool {
    tokens[first + 1..second]
        .iter()
        .any(|token| matches!(token.pos(0), "記号" | "補助記号"))
}

pub(super) fn noun_ended(tokens: &[Morpheme]) -> bool {
    tokens
        .iter()
        .rev()
        .find(|token| !matches!(token.pos(0), "記号" | "補助記号" | "空白"))
        .is_some_and(|token| matches!(token.pos(0), "名詞" | "代名詞"))
}

/// 名詞で終わる区画が読点で並ぶ最長の列挙。戻り値は(開始, 終了, 項目数, 最後の項目より
/// 前に並んだ区画の字数)。最後の項目は述語に溶けるので、読み手が抱える並びの長さは
/// それより前の区画で測る。
pub(super) fn buried_list(tokens: &[Morpheme]) -> Option<(usize, usize, usize, usize)> {
    let mut bounds = Vec::new();
    let mut start = 0;
    for (index, token) in tokens.iter().enumerate() {
        if token.surface == "、" {
            bounds.push((start, index));
            start = index + 1;
        }
    }
    bounds.push((start, tokens.len()));
    // 「〜を試したところ」「〜したとき」は形式名詞で終わる副詞的な節で、名詞句の項目ではない。
    // 「〜したこと、〜したこと」のように「こと」で名詞化した節は項目として数える。
    let clause_end = |segment: &[Morpheme]| {
        let content = segment
            .iter()
            .rposition(|token| !matches!(token.pos(0), "記号" | "補助記号" | "空白"));
        content.is_some_and(|last| {
            last > 0
                && matches!(
                    segment[last].surface.as_str(),
                    "ところ"
                        | "とき"
                        | "ため"
                        | "場合"
                        | "まま"
                        | "うち"
                        | "際"
                        | "たび"
                        | "とおり"
                        | "通り"
                )
                && matches!(segment[last - 1].pos(0), "動詞" | "助動詞" | "形容詞")
        })
    };
    let mut run = Vec::new();
    let mut best = None;
    for (index, (start, end)) in bounds.iter().copied().enumerate() {
        if end > start && noun_ended(&tokens[start..end]) && !clause_end(&tokens[start..end]) {
            run.push((start, end));
        } else {
            run.clear();
        }
        if run.len() >= 2 && index + 1 < bounds.len() {
            let items = run.len() + 1;
            if best.is_none_or(|(_, _, best_items, _)| items > best_items) {
                // 1つ目の項目は、「エンジニアが向けてきた観察」の「観察」のように、並び全体に
                // 掛かる修飾を除いた最後の名詞句から数える。
                let (first_start, first_end) = run[0];
                let head_start = tokens[first_start..first_end - 1]
                    .iter()
                    .rposition(|token| {
                        // 「業務プロセス運用の見直し」の「の」は項目の内側の名詞句をつなぐ。
                        (token.pos(0) == "助詞" && token.surface != "の")
                            || matches!(
                                token.pos(0),
                                "助動詞" | "動詞" | "形容詞" | "補助記号" | "記号" | "空白"
                            )
                    })
                    .map_or(first_start, |offset| first_start + offset + 1);
                // 「〜が進んだこと」のように名詞化した節は、節全体が一つの項目になる。
                let head_start = if tokens[head_start..first_end]
                    .iter()
                    .all(|token| matches!(token.surface.as_str(), "こと" | "もの" | "の"))
                {
                    first_start
                } else {
                    head_start
                };
                let held = tokens[head_start..run[run.len() - 1].1]
                    .iter()
                    .map(|token| token.surface.chars().count())
                    .sum::<usize>();
                best = Some((run[0].0, bounds[index + 1].1, items, held));
            }
        }
    }
    best
}

/// 読点で並べた疑問節「〜か、〜か」が、末尾の「か」に続く格助詞・係助詞で
/// 一つの述語へ係る範囲。`start..end`は最初の節から末尾の助詞までのtoken範囲。
#[derive(Clone, Copy, Debug)]
pub(super) struct BuriedQuestionList {
    pub(super) start: usize,
    pub(super) end: usize,
    pub(super) clauses: usize,
    pub(super) chars: usize,
}

// 選択肢を受けて選ぶ・決める・比べる・見分ける述語。サ変名詞は名詞の辞書形で照合する。
const ALTERNATIVE_PREDICATES: &[&str] = &[
    "分ける",
    "見分ける",
    "切り分ける",
    "見極める",
    "区別",
    "判別",
    "識別",
    "選ぶ",
    "選択",
    "決める",
    "決まる",
    "比べる",
    "比較",
    "判断",
    "判定",
    "確定",
];

// 疑問詞を含む節は、選択肢ではなく別々に答える問いになる。
const INTERROGATIVES: &[&str] = &[
    "何",
    "なに",
    "誰",
    "だれ",
    "どこ",
    "どう",
    "なぜ",
    "いつ",
    "どの",
    "どれ",
    "どちら",
    "どんな",
    "いくつ",
    "いくら",
    "どれほど",
    "どれだけ",
    "どうして",
];

/// 疑問節を受ける助詞の後、次の読点・句点までで最初の述語が選択肢を受ける動作か。
/// 「〜のかを、〜と選ぶ」のように助詞の直後に置いた読点は一つだけ越える。
fn governs_alternatives(tokens: &[Morpheme]) -> bool {
    let skip = usize::from(tokens.first().is_some_and(|token| token.surface == "、"));
    tokens[skip..]
        .iter()
        .take_while(|token| !matches!(token.pos(0), "補助記号" | "記号"))
        .find(|token| {
            token.pos(0) == "動詞" || (token.pos(0) == "名詞" && token.pos(2) == "サ変可能")
        })
        .is_some_and(|token| ALTERNATIVE_PREDICATES.contains(&token.dictionary_form()))
}

fn question_ka(token: &Morpheme) -> bool {
    token.surface == "か" && token.pos(0) == "助詞" && matches!(token.pos(1), "副助詞" | "終助詞")
}

/// 疑問節の同格列挙(カタログ F1の節版)。読み手は最初の「〜か、」で節が
/// 終わったと受け取り、末尾の「〜かを」で全体が一つの項だったと分かる。
/// 「はいか、いいえかを」のような短い選択肢は、節の字数と述語の有無で外す。
pub(super) fn buried_question_list(
    tokens: &[Morpheme],
    clause_min_chars: usize,
    list_min_chars: usize,
) -> Option<BuriedQuestionList> {
    // 「〜かどうか」「〜か否か」は一つの節の中にある「か」なので区切りに数えない。
    let whether_inner = |index: usize| {
        tokens
            .get(index + 1)
            .is_some_and(|token| matches!(token.surface.as_str(), "どう" | "否"))
            && tokens.get(index + 2).is_some_and(question_ka)
    };
    let whether_end = |index: usize| {
        index >= 2
            && matches!(tokens[index - 1].surface.as_str(), "どう" | "否")
            && question_ka(&tokens[index - 2])
    };
    let clause_ok = |start: usize, ka: usize| {
        tokens[start..=ka]
            .iter()
            .map(|token| token.surface.chars().count())
            .sum::<usize>()
            >= clause_min_chars
            && tokens[start..ka]
                .iter()
                .any(|token| matches!(token.pos(0), "動詞" | "形容詞" | "助動詞" | "形状詞"))
    };

    // 節の始点は、直前の文を閉じる太字記号や空白を読み飛ばした位置にする。
    let content_start = |start: usize| {
        tokens[start..]
            .iter()
            .position(|token| !matches!(token.pos(0), "記号" | "補助記号" | "空白"))
            .map_or(tokens.len(), |offset| start + offset)
    };
    let mut clause_start = content_start(0);
    let mut run = Vec::<usize>::new();
    let mut best: Option<BuriedQuestionList> = None;
    for (index, token) in tokens.iter().enumerate() {
        if token.surface == "、" {
            let closes_question = index > 0
                && question_ka(&tokens[index - 1])
                && !whether_end(index - 1)
                && clause_ok(clause_start, index - 1);
            if closes_question {
                run.push(clause_start);
            } else {
                run.clear();
            }
            clause_start = content_start(index + 1);
            continue;
        }
        if run.is_empty()
            || !question_ka(token)
            || whether_inner(index)
            || tokens
                .get(index + 1)
                .is_some_and(|next| next.surface == "、")
        {
            continue;
        }
        let Some(particle) = tokens.get(index + 1).filter(|next| {
            next.pos(0) == "助詞" && matches!(next.surface.as_str(), "を" | "が" | "は" | "も")
        }) else {
            // 「〜か、〜かで」のように別の形で続く並びは、項の列挙として数えない。
            run.clear();
            continue;
        };
        // 「〜かもしれない」は推量で、疑問節を項にしない。
        let conjecture = particle.surface == "も"
            && tokens
                .get(index + 2)
                .is_some_and(|next| matches!(next.dictionary_form(), "しれる" | "知れる"));
        // 「〜場なのか、〜場なのか、誰が〜かを決める場なのか」のように、後ろに別の疑問の
        // 「か」が続くなら、この「かを」は最後の項目の内側にある。
        let embedded = tokens[index + 2..]
            .iter()
            .take_while(|token| token.surface != "、")
            .any(question_ka);
        let clauses = run.len() + 1;
        // 「Aなのか、Bなのかを分ける」「〜するか、〜するかを選ぶ」「〜のか、それとも〜のかを」の
        // 2節は、一つの選択疑問の選択肢になる。節ごとに切ると問いが崩れるため数えない。
        // 疑問詞を含む節(「何を〜か、誰が〜かを決める」)は別々の問いなので残す。
        // Sudachiは「それとも」を「それ/と/も」に分けるため、表層をつないで照合する。
        let lead = tokens[clause_start..index]
            .iter()
            .take(3)
            .map(|token| token.surface.as_str())
            .collect::<String>();
        // 「何も」「誰か」のように「も」「か」が続く形は疑問詞ではない。
        let yes_no_clauses = !(run[0]..index).any(|position| {
            INTERROGATIVES.contains(&tokens[position].surface.as_str())
                && !tokens
                    .get(position + 1)
                    .is_some_and(|next| matches!(next.surface.as_str(), "も" | "か"))
        });
        let alternative = clauses == 2
            && (["それとも", "あるいは", "または", "もしくは"]
                .iter()
                .any(|marker| lead.starts_with(marker))
                || (yes_no_clauses && governs_alternatives(&tokens[index + 2..])));
        // 読み手が係り先まで抱えるのは並んだ節の全体なので、その字数で負担を測る。
        let list_chars = tokens[run[0]..=index]
            .iter()
            .map(|token| token.surface.chars().count())
            .sum::<usize>();
        if !conjecture
            && !embedded
            && !alternative
            && list_chars >= list_min_chars
            && clause_ok(clause_start, index)
            && best.is_none_or(|best| clauses > best.clauses)
        {
            best = Some(BuriedQuestionList {
                start: run[0],
                end: index + 2,
                clauses,
                chars: list_chars,
            });
        }
        run.clear();
    }
    best
}

/// 一つの被修飾名詞に前置された連体修飾節。`start..head`が修飾節、
/// `head..head_end`が被修飾名詞句のtoken範囲。
#[derive(Clone, Copy, Debug)]
pub(super) struct AttributiveSpan {
    pub(super) start: usize,
    pub(super) head: usize,
    pub(super) head_end: usize,
    pub(super) chars: usize,
    pub(super) predicates: usize,
}

// 連体修飾を受けても、読み手が保留する項にならない名詞。形式名詞・非自立の名詞と、
// 「〜する必要がある」「〜する可能性がある」のように述語の枕になる名詞を含む。
// 削除済みの nested_attributive(連体形の個数)が人間文書で全発火した主因は
// 「〜すること」「〜したとき」のような結びなので、被修飾名詞を実質名詞に限る。
const FORMAL_NOUNS: &[&str] = &[
    "こと",
    "もの",
    "ため",
    "とき",
    "時",
    "場合",
    "ところ",
    "はず",
    "わけ",
    "つもり",
    "まま",
    "うち",
    "際",
    "たび",
    "ほう",
    "方",
    "かぎり",
    "限り",
    "以上",
    "以外",
    "前",
    "後",
    "よう",
    "上",
    "中",
    "間",
    "度",
    "ごと",
    "くらい",
    "ぐらい",
    "ほど",
    "せい",
    "おかげ",
    "かわり",
    "代わり",
    "つど",
    "ゆえ",
    "点",
    "面",
    "形",
    "意味",
    "必要",
    "余地",
    "可能性",
    "恐れ",
    "おそれ",
    "危険",
    "傾向",
    "予定",
    "見込み",
    "機会",
    "状態",
    "程度",
    "気",
    "事",
    "感じ",
    "始末",
    "場面",
    "所",
    "ためし",
    "よし",
];

fn is_noun(token: &Morpheme) -> bool {
    token.pos(0) == "名詞" && matches!(token.pos(1), "普通名詞" | "固有名詞")
}

fn is_argument_head(token: &Morpheme) -> bool {
    is_noun(token) && token.pos(2) != "副詞可能" && !FORMAL_NOUNS.contains(&token.surface.as_str())
}

// 格助詞に続いて複合助詞として働く動詞(によって、について、に関する、における)。
// 形態素としては動詞だが、読み手が節として保留する述語ではないので数えない。
const COMPOUND_PARTICLE_VERBS: &[&str] = &[
    "よる",
    "つく",
    "対する",
    "関する",
    "基づく",
    "伴う",
    "おく",
    "わたる",
    "通じる",
    "沿う",
    "応じる",
    "際する",
    "めぐる",
    "つれる",
    "従う",
    "比べる",
    "加える",
    "向ける",
    "限る",
    "当たる",
    "至る",
    "関わる",
    "即する",
];

fn is_compound_particle_verb(tokens: &[Morpheme], index: usize) -> bool {
    let token = &tokens[index];
    token.pos(0) == "動詞"
        && COMPOUND_PARTICLE_VERBS.contains(&token.dictionary_form())
        && index > 0
        && tokens[index - 1].pos(1) == "格助詞"
}

/// 節の述語として数える語。複合助詞の動詞は数えない。Sudachiが非自立可能と品詞づける
/// 動詞(する、かける、始める、いる)は、「〜している」「〜し始める」のように「て」や
/// 別の動詞へ直接続くときだけ補助動詞として除き、「電話をかけた」「対応を始め」の
/// ように名詞句へ続くときは述語に数える。
fn is_predicate(tokens: &[Morpheme], index: usize) -> bool {
    let token = &tokens[index];
    match token.pos(0) {
        "形容詞" => token.pos(1) != "非自立可能",
        "動詞" => {
            if is_compound_particle_verb(tokens, index) {
                return false;
            }
            if token.pos(1) != "非自立可能" {
                return true;
            }
            let Some(previous) = index.checked_sub(1).map(|index| &tokens[index]) else {
                return true;
            };
            previous.pos(1) != "接続助詞" && !matches!(previous.pos(0), "動詞" | "助動詞")
        }
        _ => false,
    }
}

fn count_predicates(tokens: &[Morpheme], range: std::ops::Range<usize>) -> usize {
    range.filter(|&index| is_predicate(tokens, index)).count()
}

/// 読点の直前の語が、引用される終止形の並列(考えている、)か。
fn ends_terminal_clause(token: &Morpheme) -> bool {
    matches!(token.pos(0), "動詞" | "形容詞" | "助動詞") && token.pos(5).starts_with("終止形")
}

/// 読点の直前の語が、連用中止(選び、置き、触れず)か。「て」「が」などの接続助詞、
/// 「であり」「している」の補助動詞、「により」の複合助詞、手段や状態を表す
/// 「〜ことで、」「〜のままで、」の助動詞「だ」は含めない。
fn ends_conjunctive_clause(tokens: &[Morpheme], index: usize) -> bool {
    let token = &tokens[index];
    token.pos(5).starts_with("連用形")
        && match token.pos(0) {
            "助動詞" => token.dictionary_form() != "だ",
            "動詞" | "形容詞" => is_predicate(tokens, index),
            _ => false,
        }
}

/// 節の中に格助詞「が」で示した主語があるか。
fn has_subject_marker(tokens: &[Morpheme], range: std::ops::Range<usize>) -> bool {
    tokens[range]
        .iter()
        .any(|token| token.pos(1) == "格助詞" && token.surface == "が")
}

/// 係助詞「は」が主題を示すか。名詞に直接付くか、格助詞を挟んで付く「では」「には」
/// 「ことは」は主題として止める。「ときには」のように副詞可能の名詞に付くものは節の
/// 中の副詞句なので止めない。
fn is_topic_marker(tokens: &[Morpheme], index: usize) -> bool {
    let token = &tokens[index];
    if token.pos(0) != "助詞" || token.pos(1) != "係助詞" || token.surface != "は" {
        return false;
    }
    let mut cursor = index;
    while cursor > 0 && tokens[cursor - 1].pos(0) == "空白" {
        cursor -= 1;
    }
    if cursor > 0 && tokens[cursor - 1].pos(1) == "格助詞" {
        cursor -= 1;
    }
    let Some(noun) = cursor.checked_sub(1).map(|index| &tokens[index]) else {
        return false;
    };
    match noun.pos(0) {
        "代名詞" | "接尾辞" => true,
        "名詞" => noun.pos(2) != "副詞可能",
        _ => false,
    }
}

/// `end`の直前から前へたどり、読点・主題・括弧・文頭で区切られる節の始点を返す。
fn segment_start(tokens: &[Morpheme], end: usize) -> usize {
    let mut start = end;
    while start > 0 {
        let prev = &tokens[start - 1];
        if matches!(prev.pos(1), "読点" | "句点" | "括弧開" | "括弧閉")
            || is_topic_marker(tokens, start - 1)
        {
            break;
        }
        start -= 1;
    }
    start
}

/// 被修飾名詞から前へたどり、修飾節の始点を返す。文頭、主題の係助詞「は」、括弧、
/// 越えられない読点で止める。
///
/// 読点は、引用される終止形の並列なら越える。連用中止は一度だけ、読点の両側の節に
/// それぞれ述語が2つ以上あり、手前の節が「が」で示す主語を持たないときに越える。
/// 単独の述語しかない節や主語を持つ節は主節の連用中止であることが多く、含めると
/// 修飾節でない部分まで指してしまう。
fn attributive_clause_start(tokens: &[Morpheme], head: usize) -> usize {
    let mut start = head - 1;
    let mut crossed_conjunctive = false;
    while start > 0 {
        let prev = &tokens[start - 1];
        if is_topic_marker(tokens, start - 1) || matches!(prev.pos(1), "句点" | "括弧開" | "括弧閉")
        {
            break;
        }
        if prev.pos(1) == "読点" {
            let Some(before) = start.checked_sub(2) else {
                break;
            };
            if ends_terminal_clause(&tokens[before]) {
                start -= 2;
                continue;
            }
            // nwiizo-coding-style: 連用中止の読点越えは1回に限る; 三つ以上の連体節が
            // 並列する文を拾う必要が出たら、主節の連用中止と区別できる評価例を先に足す。
            let outer = segment_start(tokens, before)..start - 1;
            if !crossed_conjunctive
                && ends_conjunctive_clause(tokens, before)
                && count_predicates(tokens, start..head) >= 2
                && count_predicates(tokens, outer.clone()) >= 2
                && !has_subject_marker(tokens, outer)
            {
                crossed_conjunctive = true;
                start -= 2;
                continue;
            }
            break;
        }
        start -= 1;
    }
    start
}

/// 述語を2つ以上含み、`min_chars`字以上の連体修飾節が一つの実質名詞に前置され、
/// その名詞句が格助詞・係助詞で主節の項になっている箇所を返す。
/// 複数あれば修飾節が最も長いものを返す。
pub(super) fn long_attributive_span(
    text: &str,
    tokens: &[Morpheme],
    min_chars: usize,
) -> Option<AttributiveSpan> {
    let mut best: Option<AttributiveSpan> = None;
    for head in 1..tokens.len() {
        let marker = &tokens[head - 1];
        // 形状詞の「〜な」は句であって節ではないので、連体形でも対象にしない。
        if !marker.pos(5).starts_with("連体形")
            || (marker.pos(0) == "助動詞" && marker.dictionary_form() == "だ")
            || !is_argument_head(&tokens[head])
        {
            continue;
        }
        let mut head_end = head + 1;
        while head_end < tokens.len()
            && (is_noun(&tokens[head_end]) || tokens[head_end].pos(0) == "接尾辞")
        {
            head_end += 1;
        }
        let Some(particle) = tokens.get(head_end) else {
            continue;
        };
        // 「〜人でもある」の述語名詞や「〜関わりと〜関わり」の並列を除くため、
        // 「と」と単独の「で」は項の印に数えない。「〜研究では」の「では」は主題として数える。
        let marks_argument = particle.pos(0) == "助詞"
            && matches!(particle.pos(1), "格助詞" | "係助詞")
            && match particle.surface.as_str() {
                "が" | "は" | "を" | "も" | "に" | "へ" | "から" | "より" => true,
                "で" => tokens
                    .get(head_end + 1)
                    .is_some_and(|next| next.pos(1) == "係助詞" && next.surface == "は"),
                _ => false,
            };
        if !marks_argument {
            continue;
        }
        let start = attributive_clause_start(tokens, head);
        let predicates = count_predicates(tokens, start..head);
        if predicates < 2 {
            continue;
        }
        let chars = text[tokens[start].byte_start..tokens[head].byte_start]
            .chars()
            .filter(|c| !c.is_whitespace())
            .count();
        if chars < min_chars {
            continue;
        }
        if best.is_none_or(|best| chars > best.chars) {
            best = Some(AttributiveSpan {
                start,
                head,
                head_end,
                chars,
                predicates,
            });
        }
    }
    best
}

pub(super) fn mora_length(tokens: &[Morpheme]) -> usize {
    tokens
        .iter()
        .map(|token| {
            token
                .reading()
                .chars()
                .filter(|ch| {
                    !matches!(
                        ch,
                        'ァ' | 'ィ' | 'ゥ' | 'ェ' | 'ォ' | 'ャ' | 'ュ' | 'ョ' | 'ヮ'
                    )
                })
                .count()
        })
        .sum()
}

fn token_positions(
    tokenized: &[TokenizedSentence],
) -> impl Iterator<Item = (&TokenizedSentence, usize, &Morpheme)> {
    tokenized.iter().flat_map(|sentence| {
        sentence
            .tokens
            .iter()
            .enumerate()
            .map(move |(index, token)| (sentence, index, token))
    })
}

struct AggregateHit {
    line: usize,
    excerpt: String,
    span: Option<Span>,
    related_lines: Vec<usize>,
}

fn aggregate_pattern_finding(
    hits: Vec<AggregateHit>,
    min_hits: usize,
    category: &str,
    detail: impl FnOnce(usize, &str) -> String,
) -> Vec<Finding> {
    if hits.len() < min_hits {
        return Vec::new();
    }
    let count = hits.len();
    let mut related_lines = hits
        .iter()
        .flat_map(|hit| hit.related_lines.iter().copied())
        .collect::<Vec<_>>();
    related_lines.sort_unstable();
    related_lines.dedup();
    let related = related_lines
        .iter()
        .map(|line| format!("L{line}"))
        .collect::<Vec<_>>()
        .join(", ");
    let first = hits.into_iter().next().expect("hits is not empty");
    let mut finding = Finding::new(
        first.line,
        category,
        first.excerpt,
        "info",
        detail(count, &related),
    );
    finding.related_lines = Some(related_lines);
    finding.span = first.span;
    vec![finding]
}

pub(super) fn self_labeling_repetition_findings(
    tokenized: &[TokenizedSentence],
    raw_lines: &[&str],
) -> Vec<Finding> {
    let hits = tokenized
        .iter()
        .filter_map(|sentence| {
            let (byte_start, byte_end) = self_labeling_span(&sentence.tokens)?;
            Some(AggregateHit {
                line: sentence.line,
                excerpt: sentence.excerpt(byte_start, byte_end),
                span: sentence.span(raw_lines, byte_start, byte_end),
                related_lines: vec![sentence.line],
            })
        })
        .collect::<Vec<_>>();
    aggregate_pattern_finding(hits, 3, "self_labeling_repetition", |count, related| {
        format!(
            "評価語を含む「〜のは」型の主題提示が{}回ある(閾値3回以上)。重要点の提示は談話を導く働きもあるため、使用自体ではなく文書内の反復だけを確認する実験的検出。対応箇所: {related}",
            count
        )
    })
}

fn self_labeling_span(tokens: &[Morpheme]) -> Option<(usize, usize)> {
    let tokens = significant_tokens(tokens);
    let start = tokens.first()?.byte_start;

    for index in 1..tokens.len().saturating_sub(1) {
        if index > 7 {
            break;
        }
        if tokens[index].surface != "の" || tokens[index + 1].surface != "は" {
            continue;
        }
        let prefix = &tokens[..index];
        let evaluation = prefix
            .iter()
            .rev()
            .take(4)
            .any(|token| SELF_LABEL_EVALUATIONS.contains(&token.dictionary_form()));
        let avoid_desire = prefix
            .iter()
            .any(|token| token.dictionary_form() == "避ける")
            && prefix.iter().any(|token| token.dictionary_form() == "たい");
        if evaluation || avoid_desire {
            return Some((start, tokens[index + 1].byte_end));
        }
    }

    None
}

pub(super) fn explanation_preview_findings(
    tokenized: &[TokenizedSentence],
    raw: &str,
) -> Vec<Finding> {
    let raw_lines = raw.split('\n').collect::<Vec<_>>();
    // コード内の「#」や参考文献を節の区切りとして扱わない。
    let structural = crate::text::mask_markdown_structure_preserving_headings(raw);
    let heading_lines = structural
        .lines()
        .enumerate()
        .filter_map(|(index, line)| crate::text::is_heading(line).then_some(index + 1))
        .collect::<Vec<_>>();
    let mut sections = BTreeMap::<usize, Vec<AggregateHit>>::new();
    for sentence in tokenized {
        let raw_line = raw_lines[sentence.line - 1];
        let paragraph_start = sentence.line == 1
            || raw_lines[sentence.line - 2].trim().is_empty()
            || heading_lines.binary_search(&(sentence.line - 1)).is_ok();
        if !paragraph_start
            || sentence.line_byte_start != raw_line.len() - raw_line.trim_start().len()
        {
            continue;
        }
        let Some((start, end)) = explanation_preview_span(&sentence.tokens) else {
            continue;
        };
        let section = heading_lines.partition_point(|line| *line < sentence.line);
        sections.entry(section).or_default().push(AggregateHit {
            line: sentence.line,
            excerpt: sentence.excerpt(start, end),
            span: sentence.span(&raw_lines, start, end),
            related_lines: vec![sentence.line],
        });
    }
    sections
        .into_values()
        .flat_map(|hits| {
            aggregate_pattern_finding(hits, 3, "repeated_explanation_preview", |count, related| {
                format!(
                    "同じ節の段落頭で、説明・紹介・解説を予告する形態素列が{count}回ある(閾値3回以上)。必要な案内は残し、予告の代わりに内容から書き始められる箇所を確認してください。対応箇所: {related}"
                )
            })
        })
        .collect()
}

fn explanation_preview_span(tokens: &[Morpheme]) -> Option<(usize, usize)> {
    let first = tokens.first()?;
    if !matches!(first.surface.as_str(), "本節" | "本章" | "ここ" | "以下")
        || tokens.get(1)?.surface != "で"
        || tokens.get(2)?.surface != "は"
    {
        return None;
    }
    let last = tokens.len().checked_sub(1)?;
    let verb_index = if tokens[last].dictionary_form() == "ます" {
        last.checked_sub(1)?
    } else {
        last
    };
    let verb = &tokens[verb_index];
    let noun_index = verb_index.checked_sub(1)?;
    let noun = &tokens[noun_index];
    if noun_index <= 3
        || verb.pos(0) != "動詞"
        || verb.dictionary_form() != "する"
        || !tokens[last].pos(5).starts_with("終止形")
        || noun.pos(2) != "サ変可能"
        || !matches!(noun.dictionary_form(), "説明" | "紹介" | "解説")
    {
        return None;
    }
    // 別の主語や引用、否定・過去・可能を含む述語を予告へまとめない。
    // 述語の後ろは「ます」だけを許すので、活用に伴う意味の違いを保てる。
    if tokens[3..noun_index]
        .iter()
        .enumerate()
        .any(|(index, token)| {
            (token.pos(0) == "助詞" && matches!(token.surface.as_str(), "は" | "が"))
                || (matches!(token.pos(0), "記号" | "補助記号")
                    && !(index == 0 && token.surface == "、"))
        })
    {
        return None;
    }
    Some((first.byte_start, tokens[last].byte_end))
}

pub(super) fn negative_listing_findings(
    tokenized: &[TokenizedSentence],
    raw_lines: &[&str],
) -> Vec<Finding> {
    let hits = tokenized
        .windows(3)
        .filter_map(|window| {
            let [first, second, assertion] = window else {
                return None;
            };
            if !copular_negation(&first.tokens)
                || !copular_negation(&second.tokens)
                || !short_affirmative(&assertion.tokens)
                || blank_line_between(first.line, second.line, raw_lines)
                || blank_line_between(second.line, assertion.line, raw_lines)
            {
                return None;
            }

            let start = significant_tokens(&first.tokens).first()?.byte_start;
            let end = significant_tokens(&assertion.tokens).last()?.byte_end;
            let span = make_span(
                raw_lines,
                first.line,
                first.line_byte_start + start,
                assertion.line,
                assertion.line_byte_start + end,
            );
            Some(AggregateHit {
                line: first.line,
                excerpt: [first, second, assertion]
                    .map(|sentence| abbreviated(&sentence.raw_text, 28))
                    .join("。"),
                span,
                related_lines: vec![first.line, second.line, assertion.line],
            })
        })
        .collect::<Vec<_>>();
    aggregate_pattern_finding(hits, 1, "negative_listing", |count, related| {
        format!(
            "否定を2文続けてから短い肯定文へ焦点を移す並びが{}箇所ある。対比や選択肢の絞り込みとして意図した修辞かを確認する実験的検出。対応箇所: {related}",
            count
        )
    })
}

fn abbreviated(text: &str, max_chars: usize) -> String {
    let mut chars = text.chars();
    let mut abbreviated = chars.by_ref().take(max_chars).collect::<String>();
    if chars.next().is_some() {
        abbreviated.push('…');
    }
    abbreviated
}

fn copular_negation(tokens: &[Morpheme]) -> bool {
    let tokens = significant_tokens(tokens)
        .iter()
        .filter(|token| !matches!(token.pos(0), "記号" | "補助記号" | "空白"))
        .collect::<Vec<_>>();
    let Some(negative) = tokens.iter().rposition(|token| {
        token.dictionary_form() == "ない"
            || (token.dictionary_form() == "ぬ" && token.surface == "ん")
    }) else {
        return false;
    };
    if tokens.len().saturating_sub(negative) > 3 {
        return false;
    }
    tokens[..negative].windows(2).rev().take(5).any(|pair| {
        matches!(pair[0].surface.as_str(), "で" | "じゃ")
            && matches!(pair[1].surface.as_str(), "は" | "も")
    })
}

fn short_affirmative(tokens: &[Morpheme]) -> bool {
    let content = significant_tokens(tokens)
        .iter()
        .filter(|token| !matches!(token.pos(0), "記号" | "補助記号" | "空白"))
        .collect::<Vec<_>>();
    !content.is_empty()
        && content.len() <= 8
        && !content.iter().any(|token| {
            token.dictionary_form() == "ない"
                || (token.dictionary_form() == "ぬ" && token.surface == "ん")
        })
}

fn blank_line_between(first_line: usize, second_line: usize, raw_lines: &[&str]) -> bool {
    if second_line <= first_line + 1 {
        return false;
    }
    raw_lines[first_line..second_line - 1]
        .iter()
        .any(|line| line.trim().is_empty())
}

pub(super) fn translationese_morph_findings(
    tokenized: &[TokenizedSentence],
    raw_lines: &[&str],
) -> Vec<Finding> {
    let mut findings = Vec::new();
    for (sentence, index, token) in token_positions(tokenized) {
        if let Some((byte_start, byte_end, pattern)) =
            abstract_motsu_candidate(&sentence.tokens, index)
        {
            findings.push(sentence.info_finding(
                raw_lines,
                byte_start..byte_end,
                "translationese_morph",
                format!(
                    "品詞列マッチ: {pattern}。抽象的な内容と「持つ」の組み合わせを読み直す候補"
                ),
            ));
        }

        let Some(particle) = sentence.tokens.get(index + 1) else {
            continue;
        };
        let Some(verb) = sentence.tokens.get(index + 2) else {
            continue;
        };
        // 2026-08-18の技術書翻訳21件の正解ラベルに基づき対象を絞る:
        // 「は」型(ことはできない)は否定の対比として自然、使役型
        // (させることができる)は縮約すると受身と紛れるため対象外。
        let causative = index > 0
            && matches!(
                sentence.tokens[index - 1].dictionary_form(),
                "せる" | "させる"
            );
        if token.surface == "こと"
            && token.pos(0) == "名詞"
            && particle.pos(0) == "助詞"
            && particle.surface == "が"
            && !causative
            && verb.pos(0) == "動詞"
            && verb.surface.starts_with("でき")
        {
            let start = sentence.tokens[index.saturating_sub(4)].byte_start;
            let mut finding = sentence.info_finding(
                raw_lines,
                start..verb.byte_end,
                "translationese_morph",
                "品詞列マッチ: 名詞/動詞+こと+が/は+できる型の翻訳調構文",
            );
            finding.suggestion = suru_koto_ga_suggestion(sentence, raw_lines, index, particle);
            findings.push(finding);
        }
    }
    findings
}

fn abstract_motsu_candidate(
    tokens: &[Morpheme],
    index: usize,
) -> Option<(usize, usize, &'static str)> {
    let first = tokens.get(index)?;
    let second = tokens.get(index + 1)?;
    let third = tokens.get(index + 2);

    if second.pos(0) == "助詞" && second.surface == "を" {
        let third = third?;
        if third.pos(0) == "動詞" && third.dictionary_form() == "持つ" {
            if first.pos(0) == "名詞" && first.dictionary_form() == "意味" {
                return Some((first.byte_start, third.byte_end, "意味+を+持つ"));
            }
            if first.pos(0) == "助詞" && first.surface == "か" {
                return Some((first.byte_start, third.byte_end, "疑問節末のか+を+持つ"));
            }
        }
    }

    if first.surface == "持てる" && second.pos(0) == "名詞" && second.dictionary_form() == "未決"
    {
        return Some((first.byte_start, second.byte_end, "持てる+未決"));
    }

    if first.surface == "持て" && second.surface == "る" {
        let third = third?;
        if third.pos(0) == "名詞" && third.dictionary_form() == "未決" {
            return Some((first.byte_start, third.byte_end, "持てる+未決"));
        }
    }

    None
}

pub(super) fn technical_ambiguity_findings(
    tokenized: &[TokenizedSentence],
    raw_lines: &[&str],
) -> Vec<Finding> {
    let mut findings = Vec::new();
    for sentence in tokenized {
        for (index, token) in sentence.tokens.iter().enumerate() {
            if matches!(token.surface.as_str(), "この" | "その" | "あの")
                && sentence
                    .tokens
                    .get(index + 1)
                    .is_some_and(|next| next.pos(0) == "名詞" && next.dictionary_form() == "こと")
            {
                let predicate_count = sentence.tokens[..index]
                    .iter()
                    .filter(|candidate| candidate.pos(0) == "動詞")
                    .count();
                if predicate_count >= 2 {
                    let end = sentence.tokens[index + 1].byte_end;
                    findings.push(sentence.info_finding(
                        raw_lines,
                        token.byte_start..end,
                        "demonstrative_reference",
                        format!(
                            "品詞列マッチ: 同じ文の前方に動詞が{predicate_count}個あり、その後に「{}こと」がある。指示先を読み直す候補",
                            token.surface
                        ),
                    ));
                }
            }

            if token.surface != "それぞれ" {
                continue;
            }
            let preceding_separator = sentence.tokens[..index]
                .iter()
                .rposition(is_enumeration_separator);
            if preceding_separator.is_none()
                || sentence.tokens[index + 1..]
                    .iter()
                    .any(is_enumeration_separator)
            {
                continue;
            }
            let separator = preceding_separator.expect("separator exists");
            let start = sentence.tokens[separator.saturating_sub(1)].byte_start;
            let end = sentence.tokens[index + 1..]
                .iter()
                .find(|candidate| candidate.pos(0) == "動詞")
                .map_or(token.byte_end, |candidate| candidate.byte_end);
            findings.push(sentence.info_finding(
                raw_lines,
                start..end,
                "respectively_scope",
                "品詞列マッチ: 列挙の後に「それぞれ」があり、後方に対応する列挙がない。どの要素を一つずつ扱うか読み直す候補",
            ));
        }
    }
    findings
}

fn is_enumeration_separator(token: &Morpheme) -> bool {
    (token.pos(0) == "助詞" && matches!(token.surface.as_str(), "と" | "や"))
        || matches!(token.surface.as_str(), "、" | "," | ",")
}

/// テスト結果を色で、ソフトウェアの公開を物流語で表す技術現場の言い回し。
/// 単語だけでは本来の表示色や物理配送も拾うため、同じ節の対象語と状態語を
/// 組み合わせ、表示・配送を示す名詞がある文は除外する。
pub(super) fn technical_jargon_metaphor_findings(
    tokenized: &[TokenizedSentence],
    raw_lines: &[&str],
) -> Vec<Finding> {
    let mut findings = Vec::new();
    for sentence in tokenized {
        for index in 0..sentence.tokens.len() {
            if let Some((start, detail)) = technical_wording_start(sentence, index) {
                findings.push(sentence.info_finding(
                    raw_lines,
                    start..sentence.tokens[index].byte_end,
                    "technical_jargon_metaphor",
                    detail,
                ));
            }
        }
        if !contains_any(&sentence.tokens, DISPLAY_NOUNS)
            && let Some((start, end)) = color_status_span(&sentence.tokens)
        {
            findings.push(sentence.info_finding(
                raw_lines,
                start..end,
                "technical_jargon_metaphor",
                "テストや検査の状態を色で表す技術現場の言い回し。何が通ったか、成功したかを直接書けるか確認してください",
            ));
        }

        if !contains_any(&sentence.tokens, PHYSICAL_SHIPMENT_NOUNS)
            && let Some((start, end)) = software_shipment_span(&sentence.tokens)
        {
            findings.push(sentence.info_finding(
                raw_lines,
                start..end,
                "technical_jargon_metaphor",
                "ソフトウェアの公開を物流語で表す技術現場の言い回し。公開、配布、リリースなど具体的な動作を書けるか確認してください",
            ));
        }
    }
    findings
}

/// 活用は基本形で、短い修飾句は表層とtoken境界で照合する。
/// 「静か/に」の「に」は助動詞なので、格助詞だけに絞ると見落とす。
// nwiizo-coding-style: 対象名詞と隣接する修飾句を限定する;
// 見落としの実例が集まったら、同じ形の反例を加えて対象を広げる。
fn technical_wording_start(
    sentence: &TokenizedSentence,
    index: usize,
) -> Option<(usize, &'static str)> {
    let token = &sentence.tokens[index];
    let (prefixes, needs_context, detail): (&[&str], bool, &str) = match token.dictionary_form() {
        "壊れる" | "失敗" | "捨てる" | "無視" => {
            if matches!(token.dictionary_form(), "失敗" | "無視")
                && !sentence
                    .tokens
                    .get(index + 1)
                    .is_some_and(|next| next.dictionary_form() == "する")
            {
                return None;
            }
            (
                &["静かに", "黙って"],
                true,
                "技術的な失敗や破棄を「静かに/黙って」で表す言い回し。エラーが出ない、通知されないなど、利用者が気づけない理由を具体的に書けるか確認してください",
            )
        }
        "効く" => (
            &["地味に"],
            true,
            "技術的な効果を「地味に効く」で表す言い回し。何が改善するか、条件や観測した結果を書けるか確認してください",
        ),
        "溶かす" => (
            &["時間を"],
            false,
            "時間の消費を物が溶ける動作で表す比喩。費やした作業や時間を具体的に書けるか確認してください",
        ),
        "倒す" => (
            &["安全側に", "保守側に"],
            true,
            "判断を「側に倒す」で表す言い回し。何を優先し、どの設定や動作を選ぶか明記できるか確認してください",
        ),
        _ => return None,
    };
    let before = &sentence.text[..token.byte_start];
    let prefix = prefixes.iter().find(|prefix| before.ends_with(**prefix))?;
    let start = token.byte_start - prefix.len();
    let prefix_index = sentence.tokens[..index]
        .iter()
        .position(|part| part.byte_start == start)?;
    if needs_context {
        // 直近の「名詞+は/が/を/も」を確認し、別の人物・対象へ文脈を持ち越さない。
        let argument = sentence.tokens[..prefix_index]
            .windows(2)
            .rev()
            .take(12)
            .take_while(|pair| !matches!(pair[1].pos(0), "記号" | "補助記号" | "空白" | "動詞"))
            .find(|pair| {
                pair[1].pos(0) == "助詞"
                    && matches!(pair[1].surface.as_str(), "は" | "が" | "を" | "も")
            });
        if !argument.is_some_and(|pair| {
            pair[0].pos(0) == "名詞" && TECHNICAL_WORDING_NOUNS.contains(&pair[0].dictionary_form())
        }) {
            return None;
        }
    }
    Some((start, detail))
}

/// 同じ節の5文以内に3回現れる型を集約し、離れた説明の累積を避ける。
pub(super) fn technical_repetition_findings(
    tokenized: &[TokenizedSentence],
    raw_lines: &[&str],
    raw: &str,
) -> Vec<Finding> {
    let dash = Regex::new(r"[—―]+").expect("valid em-dash regex");
    let structural = crate::text::mask_markdown_structure_preserving_headings(raw);
    let heading_lines = structural
        .lines()
        .enumerate()
        .filter_map(|(index, line)| crate::text::is_heading(line).then_some(index + 1))
        .collect::<Vec<_>>();
    let mut distinctions = Vec::new();
    let mut dashes = Vec::new();
    for (index, sentence) in tokenized
        .iter()
        .filter(|sentence| sentence.text.chars().any(char::is_alphanumeric))
        .enumerate()
    {
        if !matches!(sentence.end_mark, Some('?' | '?'))
            && let Some(token) = sentence.tokens.iter().find(|token| {
                token.pos(0) == "名詞"
                    && token.dictionary_form() == "別物"
                    && matches!(
                        sentence.text[token.byte_end..].trim_matches(['*', '_']),
                        "だ" | "です" | "である"
                    )
            })
        {
            distinctions.push((
                index,
                AggregateHit {
                    line: sentence.line,
                    excerpt: sentence.excerpt(token.byte_start, sentence.text.len()),
                    span: sentence.span(raw_lines, token.byte_start, sentence.text.len()),
                    related_lines: vec![sentence.line],
                },
            ));
        }
        if let Some(found) = dash.find_iter(&sentence.text).find(|found| {
            let before = sentence.text[..found.start()]
                .trim_end_matches(|ch: char| ch.is_whitespace() || matches!(ch, '*' | '_'))
                .chars()
                .next_back();
            let after = sentence.text[found.end()..]
                .trim_start_matches(|ch: char| ch.is_whitespace() || matches!(ch, '*' | '_'))
                .chars()
                .next();
            before.zip(after).is_some_and(|(left, right)| {
                left.is_alphanumeric()
                    && right.is_alphanumeric()
                    && !(left.is_numeric() && right.is_numeric())
            })
        }) {
            dashes.push((
                index,
                AggregateHit {
                    line: sentence.line,
                    excerpt: sentence.excerpt(found.start(), found.end()),
                    span: sentence.span(raw_lines, found.start(), found.end()),
                    related_lines: vec![sentence.line],
                },
            ));
        }
    }
    let mut findings = aggregate_pattern_finding(
        clustered_repetition_hits(distinctions, &heading_lines),
        3,
        "repeated_distinction",
        |count, related| {
            format!(
                "同じ節の5文以内に「別物だ/です/である」で締める文が3文以上ある。該当する反復は計{count}文。比較の説明や文末の続き方を確認してください。必要な比較は残せます。対応箇所: {related}"
            )
        },
    );
    findings.extend(aggregate_pattern_finding(clustered_repetition_hits(dashes, &heading_lines), 3, "repeated_em_dash", |count, related| {
        format!("同じ節の5文以内に文中のダッシュ(—/―)を使う文が3文以上ある。該当する反復は計{count}文。挿入や言い換えが続く箇所を読み直し、句点や括弧で区切ると読みやすいか確認してください。対応箇所: {related}")
    }));
    findings
}

// nwiizo-coding-style: 近接を同じ節の5文以内で近似する;
// 読み直し範囲が広すぎる実例が集まったら、反例とともに範囲を見直す。
fn clustered_repetition_hits(
    hits: Vec<(usize, AggregateHit)>,
    heading_lines: &[usize],
) -> Vec<AggregateHit> {
    let mut retained = BTreeSet::new();
    for window in hits.windows(3) {
        let first = &window[0];
        let last = &window[2];
        if last.0 - first.0 < 5
            && heading_lines.partition_point(|line| *line < first.1.line)
                == heading_lines.partition_point(|line| *line < last.1.line)
        {
            retained.extend(window.iter().map(|(index, _)| *index));
        }
    }
    hits.into_iter()
        .filter_map(|(index, hit)| retained.contains(&index).then_some(hit))
        .collect()
}

/// 抽象名詞を動作主にして移動や効果を表す、技術文書の翻訳調候補。
/// 物理的な運搬や一般的な「効く」を拾わないよう、観測済みの格関係と
/// 数量名詞の直後に限定する。
pub(super) fn abstract_predicate_metaphor_findings(
    tokenized: &[TokenizedSentence],
    raw_lines: &[&str],
) -> Vec<Finding> {
    let mut findings = Vec::new();
    for sentence in tokenized {
        if let Some((start, end)) = abstract_transport_span(&sentence.tokens) {
            findings.push(sentence.info_finding(
                raw_lines,
                start..end,
                "abstract_metaphor",
                "抽象名詞と移動動詞の組み合わせ。意図や判断がどのように実装へ反映されるか、具体的に書けるか確認してください",
            ));
        }

        if let Some((start, end)) = abstract_effect_span(&sentence.tokens) {
            findings.push(sentence.info_finding(
                raw_lines,
                start..end,
                "abstract_metaphor",
                "抽象的な尺度と「で効く」の組み合わせ。何がどのように影響するか、具体的に書けるか確認してください",
            ));
        }
    }
    findings
}

fn contains_any(tokens: &[Morpheme], candidates: &[&str]) -> bool {
    position_any(tokens, candidates).is_some()
}

fn position_any(tokens: &[Morpheme], candidates: &[&str]) -> Option<usize> {
    tokens.iter().position(|token| {
        candidates.contains(&token.dictionary_form())
            || candidates.contains(&token.surface.as_str())
    })
}

fn color_status_span(tokens: &[Morpheme]) -> Option<(usize, usize)> {
    let subject = position_any(tokens, TECHNICAL_STATUS_NOUNS)?;
    let color = tokens.iter().position(|token| {
        matches!(token.dictionary_form(), "緑" | "グリーン")
            && matches!(token.pos(0), "名詞" | "形状詞")
    })?;
    if subject >= color || punctuation_between(tokens, subject, color) {
        return None;
    }
    let following = &tokens[color + 1..];
    let state = following.iter().take(4).position(|token| {
        matches!(
            token.dictionary_form(),
            "だ" | "です" | "なる" | "戻す" | "保つ" | "まま"
        ) || token.surface == "で"
    })? + color
        + 1;
    if punctuation_between(tokens, color, state) {
        return None;
    }
    Some((tokens[subject].byte_start, tokens[state].byte_end))
}

fn software_shipment_span(tokens: &[Morpheme]) -> Option<(usize, usize)> {
    let shipment = tokens
        .iter()
        .position(|token| token.dictionary_form() == "出荷")?;
    let software = position_any(&tokens[..shipment], SOFTWARE_NOUNS)
        .filter(|index| !punctuation_between(tokens, *index, shipment));
    let scoped_state = tokens[..shipment]
        .iter()
        .enumerate()
        .position(|(index, token)| {
            token.dictionary_form() == "状態"
                && index > 0
                && tokens[index - 1].surface == "どの"
                && !punctuation_between(tokens, index, shipment)
        });
    let action = tokens[shipment + 1..]
        .iter()
        .position(|token| token.pos(0) == "動詞")
        .map(|index| index + shipment + 1);
    if !action.is_some_and(|index| matches!(tokens[index].dictionary_form(), "する" | "止める"))
    {
        return None;
    }
    let stop = action.filter(|index| tokens[*index].dictionary_form() == "止める");
    let decide = tokens
        .iter()
        .position(|token| token.dictionary_form() == "決める");
    let context =
        software.or_else(|| scoped_state.filter(|_| stop.is_some() && decide.is_some()))?;
    let end = action.expect("shipment action exists");
    Some((
        tokens[context.min(shipment)].byte_start,
        tokens[end].byte_end,
    ))
}

fn abstract_transport_span(tokens: &[Morpheme]) -> Option<(usize, usize)> {
    let verb = tokens
        .iter()
        .position(|token| token.dictionary_form() == "運ぶ")?;
    let destination = tokens[..verb]
        .iter()
        .enumerate()
        .find_map(|(index, token)| {
            ABSTRACT_TRANSPORT_OBJECTS
                .contains(&token.dictionary_form())
                .then_some(index)
                .filter(|index| {
                    tokens
                        .get(*index + 1)
                        .is_some_and(|particle| matches!(particle.surface.as_str(), "へ" | "に"))
                })
        })?;
    let object = tokens[..destination]
        .iter()
        .enumerate()
        .find_map(|(index, token)| {
            ABSTRACT_TRANSPORT_OBJECTS
                .contains(&token.dictionary_form())
                .then_some(index)
                .filter(|index| {
                    tokens
                        .get(*index + 1)
                        .is_some_and(|particle| particle.surface == "を")
                })
        })?;
    let subject = tokens[..object]
        .iter()
        .enumerate()
        .find_map(|(index, token)| {
            ABSTRACT_TRANSPORT_SUBJECTS
                .contains(&token.dictionary_form())
                .then_some(index)
                .filter(|index| {
                    tokens
                        .get(*index + 1)
                        .is_some_and(|particle| matches!(particle.surface.as_str(), "は" | "が"))
                })
        })?;
    if punctuation_between(tokens, subject, object)
        || punctuation_between(tokens, object, destination)
        || punctuation_between(tokens, destination, verb)
    {
        return None;
    }
    Some((tokens[subject].byte_start, tokens[verb].byte_end))
}

fn abstract_effect_span(tokens: &[Morpheme]) -> Option<(usize, usize)> {
    let verb = tokens
        .iter()
        .position(|token| token.dictionary_form() == "効く")?;
    let particle = verb.checked_sub(1)?;
    let quantity = particle.checked_sub(1)?;
    if tokens[particle].surface != "で"
        || tokens[quantity].pos(0) != "名詞"
        || !QUANTITY_NOUN_ENDINGS.iter().any(|ending| {
            tokens[quantity].dictionary_form() == *ending
                || tokens[quantity].surface.ends_with(ending)
        })
    {
        return None;
    }
    let (subject, subject_particle) = abstract_effect_subject(tokens, quantity)?;
    if subject_particle >= quantity
        || (subject_particle + 1..quantity).any(|index| {
            let token = &tokens[index];
            token.pos(0) == "助詞"
                && (token.surface == "が"
                    || (token.surface == "は" && tokens[index - 1].pos(0) != "助詞"))
        })
    {
        return None;
    }
    Some((tokens[subject].byte_start, tokens[verb].byte_end))
}

fn abstract_effect_subject(tokens: &[Morpheme], before: usize) -> Option<(usize, usize)> {
    tokens[..before]
        .iter()
        .enumerate()
        .find_map(|(index, token)| {
            if !ABSTRACT_EFFECT_SUBJECTS.contains(&token.dictionary_form()) {
                return None;
            }
            let suffix = tokens.get(index + 1);
            let particle_index = if token.dictionary_form() == "複雑"
                && suffix.is_some_and(|candidate| {
                    candidate.surface == "さ" && candidate.pos(0) == "接尾辞"
                }) {
                index + 2
            } else {
                index + 1
            };
            tokens.get(particle_index).and_then(|particle| {
                matches!(particle.surface.as_str(), "は" | "が").then_some((index, particle_index))
            })
        })
}

/// 機械的に安全な唯一の縮約: 「〜することができる」→「〜できる」。
/// 直前が動詞「する」で助詞が「が」の場合だけ、「することが」の削除候補を出す。
/// raw行のpreimageが一致しないときは出さない。
fn suru_koto_ga_suggestion(
    sentence: &TokenizedSentence,
    raw_lines: &[&str],
    koto_index: usize,
    particle: &Morpheme,
) -> Option<Suggestion> {
    if koto_index == 0 || particle.surface != "が" {
        return None;
    }
    let suru = sentence.tokens.get(koto_index - 1)?;
    if suru.pos(0) != "動詞" || suru.dictionary_form() != "する" {
        return None;
    }
    let koto = &sentence.tokens[koto_index];
    let expected = format!("{}{}{}", suru.surface, koto.surface, particle.surface);
    let line_start = sentence.line_byte_start + suru.byte_start;
    let line_end = sentence.line_byte_start + particle.byte_end;
    let matches_raw = raw_lines
        .get(sentence.line - 1)
        .and_then(|raw_line| raw_line.get(line_start..line_end))
        .is_some_and(|slice| slice == expected);
    if !matches_raw {
        return None;
    }
    Some(Suggestion {
        span: sentence.span(raw_lines, suru.byte_start, particle.byte_end)?,
        preimage: expected,
        replacement: String::new(),
    })
}

/// サ変名詞+を+行う型の冗長(「検証を行う」→「検証する」)。
/// 名詞とを、をと行うが隣接する場合だけ対象にし、受身(行われる)と
/// 名詞がサ変可能でない場合(「祭りを行う」)は対象外。textlintの
/// ai-tech-writing-guidelineが指摘する冗長クラスのうち、形態素で
/// 決定的に判定できる部分だけを扱う。
pub(super) fn redundant_light_verb_findings(
    tokenized: &[TokenizedSentence],
    raw_lines: &[&str],
) -> Vec<Finding> {
    let mut findings = Vec::new();
    for (sentence, index, noun) in token_positions(tokenized) {
        let Some(particle) = sentence.tokens.get(index + 1) else {
            continue;
        };
        let Some(verb) = sentence.tokens.get(index + 2) else {
            continue;
        };
        let verbal_noun =
            noun.pos(0) == "名詞" && (noun.pos(2) == "サ変可能" || noun.pos(2) == "サ変形状詞可能");
        if !verbal_noun
            || particle.pos(0) != "助詞"
            || particle.surface != "を"
            || verb.pos(0) != "動詞"
            || !matches!(verb.dictionary_form(), "行う" | "行なう")
        {
            continue;
        }
        // 受身・使役(行われる、行わせる)は言い換えの意味が変わるため対象外
        let passive_or_causative = sentence.tokens.get(index + 3).is_some_and(|next| {
            matches!(
                next.dictionary_form(),
                "れる" | "られる" | "せる" | "させる"
            )
        });
        if passive_or_causative {
            continue;
        }
        let mut finding = sentence.info_finding(
            raw_lines,
            noun.byte_start..verb.byte_end,
            "redundant_light_verb",
            format!(
                "サ変名詞+を+行う型の冗長候補: 「{}を{}」は「{}する」へ畳める。名詞の動作性を活かす方が簡潔(意図的な文体なら維持する)",
                noun.surface, verb.surface, noun.surface
            ),
        );
        finding.suggestion = light_verb_suggestion(sentence, raw_lines, particle, verb);
        findings.push(finding);
    }
    findings
}

/// 抽象的な対象を物体になぞらえ、判断内容を曖昧にする可能性がある名詞句。
/// 候補語だけでは本来の意味での用例まで拾うため、述語として使われる場合か、
/// 抽象名詞から「の」で修飾される場合に限定する。
pub(super) fn abstract_metaphor_findings(
    tokenized: &[TokenizedSentence],
    raw_lines: &[&str],
    include_technical_roles: bool,
) -> Vec<Finding> {
    let mut findings = Vec::new();
    for (sentence, index, token) in token_positions(tokenized) {
        let technical_role =
            include_technical_roles && matches!(token.dictionary_form(), "入口" | "主役");
        if token.pos(0) != "名詞"
            || (!ABSTRACT_METAPHOR_NOUNS.contains(&token.dictionary_form()) && !technical_role)
        {
            continue;
        }

        let abstract_genitive = index >= 2
            && sentence.tokens[index - 1].surface == "の"
            && sentence.tokens[index - 2].pos(0) == "名詞"
            && is_abstract_context_noun(&sentence.tokens[index - 2]);
        let predicate_end = metaphor_predicate_end(&sentence.tokens, index);
        if !abstract_genitive
            && (predicate_end.is_none() || !has_abstract_context_before(&sentence.tokens, index))
        {
            continue;
        }

        let byte_start = if index >= 2 && sentence.tokens[index - 1].surface == "の" {
            sentence.tokens[index - 2].byte_start
        } else {
            token.byte_start
        };
        let byte_end = predicate_end
            .map(|end| sentence.tokens[end].byte_end)
            .unwrap_or(token.byte_end);
        findings.push(sentence.info_finding(
            raw_lines,
            byte_start..byte_end,
            "abstract_metaphor",
            format!(
                "抽象比喩の可能性: 「{}」。判断対象・判断基準・具体的な効果を明記してください",
                token.surface
            ),
        ));
    }
    findings
}

fn is_abstract_context_noun(token: &Morpheme) -> bool {
    ABSTRACT_CONTEXT_NOUNS.iter().any(|candidate| {
        token.dictionary_form() == *candidate || token.surface.ends_with(candidate)
    })
}

fn has_abstract_context_before(tokens: &[Morpheme], noun_index: usize) -> bool {
    tokens[..noun_index]
        .iter()
        .rev()
        .take_while(|token| !matches!(token.pos(0), "記号" | "補助記号"))
        .take(12)
        .any(|token| token.pos(0) == "名詞" && is_abstract_context_noun(token))
}

fn metaphor_predicate_end(tokens: &[Morpheme], noun_index: usize) -> Option<usize> {
    let first = tokens.get(noun_index + 1)?;
    if matches!(first.dictionary_form(), "だ" | "です") {
        return Some(noun_index + 1);
    }

    let second = tokens.get(noun_index + 2)?;
    if matches!(first.surface.as_str(), "に" | "と") && second.dictionary_form() == "なる" {
        return Some(noun_index + 2);
    }
    if first.surface == "で" && second.dictionary_form() == "ある" {
        return Some(noun_index + 2);
    }
    if first.surface == "と" && second.dictionary_form() == "する" {
        let third = tokens.get(noun_index + 3)?;
        if third.surface == "て" {
            return Some(noun_index + 3);
        }
    }
    None
}

/// 「を+行う」の活用形ごとに機械的に安全な置換だけを提案する。
/// 行う→する、行い→し、行っ→し。それ以外の活用(行わ、行え等)は
/// 提案しない。preimageがraw行と一致しない場合も提案しない。
fn light_verb_suggestion(
    sentence: &TokenizedSentence,
    raw_lines: &[&str],
    particle: &Morpheme,
    verb: &Morpheme,
) -> Option<Suggestion> {
    let replacement = match verb.surface.as_str() {
        "行う" | "行なう" => "する",
        "行い" | "行ない" => "し",
        "行っ" | "行なっ" => "し",
        _ => return None,
    };
    let expected = format!("{}{}", particle.surface, verb.surface);
    let line_start = sentence.line_byte_start + particle.byte_start;
    let line_end = sentence.line_byte_start + verb.byte_end;
    let matches_raw = raw_lines
        .get(sentence.line - 1)
        .and_then(|raw_line| raw_line.get(line_start..line_end))
        .is_some_and(|slice| slice == expected);
    if !matches_raw {
        return None;
    }
    Some(Suggestion {
        span: sentence.span(raw_lines, particle.byte_start, verb.byte_end)?,
        preimage: expected,
        replacement: replacement.to_owned(),
    })
}

pub(super) fn inanimate_morph_findings(
    tokenized: &[TokenizedSentence],
    raw_lines: &[&str],
) -> Vec<Finding> {
    let mut findings = Vec::new();
    for sentence in tokenized {
        let mut skip_until = None;
        for index in 0..sentence.tokens.len() {
            if skip_until.is_some_and(|skip| index <= skip) {
                continue;
            }
            let token = &sentence.tokens[index];
            let mut subject_end = index;
            let mut abstract_subject =
                matches!(token.surface.as_str(), "これ" | "それ" | "あれ" | "それら")
                    || (token.pos(0) == "名詞"
                        && matches!(token.surface.as_str(), "こと" | "事実"));
            if !abstract_subject && let Some(next) = sentence.tokens.get(index + 1) {
                let phrase = format!("{}{}", token.surface, next.surface);
                if matches!(phrase.as_str(), "この事実" | "そのこと") {
                    abstract_subject = true;
                    subject_end = index + 1;
                }
            }
            if !abstract_subject {
                continue;
            }
            skip_until = Some(subject_end);
            let Some(particle) = sentence.tokens.get(subject_end + 1) else {
                continue;
            };
            if particle.pos(0) != "助詞" || !matches!(particle.surface.as_str(), "が" | "は") {
                continue;
            }
            let verb = sentence.tokens[subject_end + 2..].iter().find(|candidate| {
                candidate.pos(0) == "動詞"
                    && TRANSITIVE_SMELL_VERBS.contains(&candidate.dictionary_form())
            });
            let Some(verb) = verb else {
                continue;
            };
            let byte_start = sentence.tokens[index.saturating_sub(3)].byte_start;
            let subject = sentence.tokens[index..=subject_end]
                .iter()
                .map(|token| token.surface.as_str())
                .collect::<String>();
            findings.push(sentence.info_finding(
                raw_lines,
                byte_start..verb.byte_end,
                "inanimate_subject_morph",
                format!(
                    "品詞列マッチ: 抽象主語「{subject}」+ {} + 他動詞的述語「{}」(英語統語の直訳調の疑い)",
                    particle.surface,
                    verb.dictionary_form()
                ),
            ));
        }
    }
    findings
}