mordant 0.9.0

A 100% CommonMark-compatible GitHub Flavored Markdown parser and renderer
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
//! Markdown linter built on top of the mordant AST.
//!
//! The linter parses Markdown into the mordant arena and evaluates a set of
//! lint rules against it. Most rules are AST-driven (heading structure,
//! links, images, fenced code blocks); a few line-based rules (trailing
//! whitespace, blank lines, final newline) supplement them using the raw
//! source string.
//!
//! Rule identifiers follow markdownlint (MD0xx) so output is familiar.
//!
//! `run_lint` returns plain-Rust `Violation` values; embedding layers (such
//! as the Python bindings) convert them into their native diagnostic types.

use crate::ast::{Arena, KindData, Meta, NodeRef};
use std::collections::HashSet;

use crate::emoji::EmojiData;

// ---------------------------------------------------------------------------
// Diagnostics
// ---------------------------------------------------------------------------

/// Severity of a lint diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    Warning,
    #[allow(dead_code)]
    Error,
}

impl Severity {
    pub fn as_str(self) -> &'static str {
        match self {
            Severity::Warning => "warning",
            Severity::Error => "error",
        }
    }
}

/// A description of how to auto-correct a violation, as a minimal edit to the
/// source text. All variants are line-oriented (0-indexed lines), which is all
/// the currently auto-fixable rules need. Fixes are applied to the raw source
/// rather than by re-rendering the AST: mordant renders to HTML and has no
/// Markdown serializer, and source edits keep the resulting diff minimal.
pub enum FixOp {
    /// Replace the whole content of a line (used to strip trailing whitespace).
    ReplaceLine { line: usize, text: String },
    /// Delete a line entirely (used to collapse runs of blank lines).
    DeleteLine { line: usize },
    /// Ensure the document ends with exactly one trailing newline.
    EnsureFinalNewline,
    /// Insert a language onto a fence's opening line. Only applied when the
    /// caller supplies a default language, since the language can't be inferred.
    SetCodeLanguage { line: usize },
}

/// A single rule violation — plain Rust (`Send`), produced without the GIL.
pub struct Violation {
    pub rule: &'static str,
    pub name: &'static str,
    pub message: String,
    /// 1-indexed source line, if known.
    pub line: Option<usize>,
    /// 1-indexed column within the line, if known.
    pub column: Option<usize>,
    /// Byte offset span (half-open: [start, end)) in the source, if known.
    pub span: Option<(usize, usize)>,
    pub severity: Severity,
    /// How to auto-correct this violation, if it is auto-fixable.
    pub fix: Option<FixOp>,
}

impl Violation {
    fn warn(
        rule: &'static str,
        name: &'static str,
        line: Option<usize>,
        column: Option<usize>,
        span: Option<(usize, usize)>,
        message: impl Into<String>,
    ) -> Self {
        Violation {
            rule,
            name,
            message: message.into(),
            line,
            column,
            span,
            severity: Severity::Warning,
            fix: None,
        }
    }

    fn warn_fix(
        rule: &'static str,
        name: &'static str,
        line: Option<usize>,
        column: Option<usize>,
        span: Option<(usize, usize)>,
        message: impl Into<String>,
        fix: FixOp,
    ) -> Self {
        Violation {
            rule,
            name,
            message: message.into(),
            line,
            column,
            span,
            severity: Severity::Warning,
            fix: Some(fix),
        }
    }
}

// ---------------------------------------------------------------------------
// Fix-engine hardening (Phase 4)
// ---------------------------------------------------------------------------

/// A byte-range edit to apply to the source text.
/// `start` and `end` are byte offsets (half-open: [start, end)).
/// `replacement` is the text to insert at that position.
#[allow(dead_code)]
pub struct Edit {
    pub start: usize,
    pub end: usize,
    pub replacement: String,
}

/// Internal result of a fix run (plain Rust, `Send`).
pub struct FixOutcome {
    pub output: String,
    pub fixed: Vec<Violation>,
    pub unfixable: Vec<Violation>,
    /// Diagnostics remaining after fixing, computed by re-linting `output`.
    pub remaining: Vec<Violation>,
}

// ---------------------------------------------------------------------------
// Rule parameters — per-rule tuning (Phase 5)
// ---------------------------------------------------------------------------

/// Per-rule configuration parameters.  Each field has a sensible default
/// that mirrors the markdownlint ecosystem.
#[derive(Debug, Clone)]
pub struct RuleParams {
    /// MD003 heading style: "consistent", "atx", "atx_closed", "setext", "setext2".
    pub heading_style: String,
    /// MD013 line length limit (default 80).
    pub line_length: usize,
    /// MD013 ignore threshold: lines below this are never reported.
    pub line_length_ignore_threshold: usize,
    /// MD010: number of spaces per tab (default 4).
    pub spaces_per_tab: usize,
    /// MD024: only compare sibling headings (default false).
    #[allow(dead_code)]
    pub siblings_only: bool,
    /// MD040: default language to insert when fixing (default None).
    #[allow(dead_code)]
    pub default_language: Option<String>,
}

impl Default for RuleParams {
    fn default() -> Self {
        RuleParams {
            heading_style: "consistent".to_string(),
            line_length: 80,
            line_length_ignore_threshold: 0,
            spaces_per_tab: 4,
            siblings_only: false,
            default_language: None,
        }
    }
}

/// A suppression directive parsed from `<!-- markdownlint-disable ... -->` comments.
#[derive(Debug, Clone)]
pub struct SuppressionDirective {
    /// Line number (0-indexed) where the directive appears.
    pub line: usize,
    /// If Some, only these rules are suppressed. If None, all rules are suppressed.
    pub rules: Option<Vec<String>>,
    /// Action: "disable", "enable", "disable-next-line".
    pub action: String,
}

/// Plain-Rust lint configuration (no Python references — safe without the GIL).
#[derive(Debug, Clone, Default)]
pub struct LintConfig {
    /// Rule ids to disable. Ignored if `enable` is set.
    pub disable: Vec<String>,
    /// If set, ONLY these rule ids run.
    pub enable: Option<Vec<String>>,
    /// When default is False, collect these rule ids.
    #[allow(dead_code)]
    pub _enabled_when_default_false: Option<Vec<String>>,
    /// Suppression directives from inline comments.
    pub suppressions: Vec<SuppressionDirective>,
    /// Per-rule parameters.
    pub params: RuleParams,
}

impl LintConfig {
    fn is_enabled(&self, rule: &str) -> bool {
        if let Some(enable) = &self.enable {
            enable.iter().any(|r| r == rule)
        } else {
            !self.disable.iter().any(|r| r == rule)
        }
    }

    /// Check if a (rule, line) pair is suppressed by an inline comment.
    fn is_suppressed(&self, rule: &str, line: usize) -> bool {
        let mut disable_all = false;
        let mut disabled: HashSet<String> = HashSet::new();
        let mut enabled: HashSet<String> = HashSet::new(); // explicit enables override disable_all

        for directive in &self.suppressions {
            if directive.line > line {
                break;
            }
            // `all` == this directive targets every rule (no rule list given).
            let all = directive.rules.as_deref().map_or(true, |r| r.is_empty());
            match directive.action.as_str() {
                "disable-next-line" => {
                    if directive.line + 1 == line
                        && (all || directive.rules.as_ref().unwrap().iter().any(|r| r == rule))
                    {
                        return true;
                    }
                }
                "disable" => {
                    if all {
                        disable_all = true;
                        enabled.clear();
                    } else {
                        for r in directive.rules.as_ref().unwrap() {
                            disabled.insert(r.clone());
                            enabled.remove(r);
                        }
                    }
                }
                "enable" => {
                    if all {
                        disable_all = false;
                        disabled.clear();
                        enabled.clear();
                    } else {
                        for r in directive.rules.as_ref().unwrap() {
                            enabled.insert(r.clone());
                            disabled.remove(r);
                        }
                    }
                }
                _ => {}
            }
        }

        // Explicit enable wins over a blanket disable; otherwise a specific
        // disable wins; otherwise fall back to the blanket disable state.
        if enabled.contains(rule) {
            false
        } else if disabled.contains(rule) {
            true
        } else {
            disable_all
        }
    }
}

// ---------------------------------------------------------------------------
// Document model — extracted once from the AST, then inspected by rules
// ---------------------------------------------------------------------------

struct Source<'s> {
    text: &'s str,
    lines: Vec<&'s str>,
}

struct HeadingInfo {
    level: u8,
    line: Option<usize>, // 0-indexed source line
    text: String,
}

struct LinkInfo {
    destination: String,
    line: Option<usize>,
}

struct ImageInfo {
    alt: String,
    line: Option<usize>,
}

struct CodeBlockInfo {
    language: Option<String>,
    fenced: bool,
    line: Option<usize>,
}

/// A contiguous span of source lines that are part of a code region
/// (fenced block or indented code block).  Used by the line-based rules
/// to skip content that belongs to code.
struct CodeRegion {
    start: usize, // 0-indexed, inclusive
    end: usize,   // 0-indexed, inclusive
    #[allow(dead_code)]
    fenced: bool, // future: differentiate fenced vs indented in mask logic
}

/// Convert a byte offset (as returned by mordant's Node.pos()) into a
/// 0-indexed source line number.
fn byte_offset_to_line(source: &Source, offset: usize) -> Option<usize> {
    let mut pos = 0usize;
    for (i, line_str) in source.lines.iter().enumerate() {
        // Each line is followed by a \n (except possibly the last)
        let line_end = pos + line_str.len() + 1;
        if offset < line_end {
            return Some(i);
        }
        pos = line_end;
    }
    // Offset is past the last line
    if pos <= offset {
        Some(source.lines.len())
    } else {
        None
    }
}

#[derive(Default)]
struct Collected {
    headings: Vec<HeadingInfo>,
    links: Vec<LinkInfo>,
    images: Vec<ImageInfo>,
    code_blocks: Vec<CodeBlockInfo>,
    /// Code regions derived from AST nodes (fenced blocks, indented code).
    code_regions: Vec<CodeRegion>,
    /// Frontmatter title, if present (for MD025 — single h1).
    frontmatter_title: Option<String>,
    /// Canonical heading anchors for MD041/MD043/fragment link checks.
    heading_anchors: Vec<String>,
}

/// Check if a source line contains a fence delimiter (backtick or tilde).
/// Handles blockquote/list prefixes like "> ```" or "  ~~~~".
fn has_fence_char(s: &str) -> bool {
    s.contains("```") || s.contains("~~~")
}

/// Collect the resolved text content of a node's subtree.
///
/// Mirrors `node::collect_text`, but operates on a borrowed `&Arena` rather
/// than `Rc<RefCell<Arena>>` so it can run on the GIL-free parse result.
/// Handles emoji extension nodes by extracting the Unicode emoji character.
fn collect_text(arena: &Arena, node_ref: NodeRef, source: &str) -> String {
    let mut result = String::new();
    let mut child = arena[node_ref].first_child();
    while let Some(nref) = child {
        match &arena[nref].kind_data() {
            KindData::Text(t) => result.push_str(t.str(source)),
            KindData::CodeSpan(c) => result.push_str(c.str(source).as_ref()),
            KindData::RawHtml(r) => result.push_str(r.str(source).as_ref()),
            KindData::Extension(ext) => {
                // Try to downcast to EmojiData and extract the emoji string.
                if let Some(emoji_data) = (ext.as_ref() as &dyn std::any::Any).downcast_ref::<EmojiData>() {
                    result.push_str(emoji_data.as_str());
                }
                // If not an emoji, fall through to recursion (no-op for leaf nodes).
            }
            _ => result.push_str(&collect_text(arena, nref, source)),
        }
        child = arena[nref].next_sibling();
    }
    result
}

/// Generate a canonical heading anchor (slug) from heading text.
/// Mirrors GitHub Flavored Markdown / mordant's auto_heading_ids behavior:
/// lowercase, replace spaces with hyphens, remove non-alphanumeric chars
/// (except hyphens).
fn heading_anchor(text: &str) -> String {
    let slug: String = text.trim()
        .to_lowercase()
        .chars()
        .map(|c| {
            if c.is_alphanumeric() {
                c
            } else if c == '-' {
                '-'
            } else {
                '-'
            }
        })
        .collect();
    slug.split('-')
        .filter(|s| !s.is_empty())
        .collect::<Vec<&str>>()
        .join("-")
}

/// Single pre-order DFS that extracts everything the rules need.
fn build(arena: &Arena, node_ref: NodeRef, src: &Source, out: &mut Collected) {
    match &arena[node_ref].kind_data() {
        KindData::Document(doc) => {
            // Extract frontmatter title from metadata (for MD025)
            let meta = doc.metadata();
            if let Some(title_val) = meta.get("title") {
                if let Meta::String(title_str) = title_val {
                    if !title_str.trim().is_empty() {
                        out.frontmatter_title = Some(title_str.clone());
                    }
                }
            }
        }
        KindData::Heading(h) => {
            let line_num = arena[node_ref].pos().and_then(|p| byte_offset_to_line(src, p));
            let heading_text = collect_text(arena, node_ref, src.text);
            out.headings.push(HeadingInfo {
                level: h.level(),
                line: line_num,
                text: heading_text.clone(),
            });
            // Generate canonical anchor for fragment link validation (MD042/R8.3)
            let anchor = heading_anchor(&heading_text);
            if !anchor.is_empty() {
                out.heading_anchors.push(anchor);
            }
        }
        KindData::Link(l) => out.links.push(LinkInfo {
            destination: l.destination_str(src.text).to_string(),
            line: arena[node_ref].pos(),
        }),
        KindData::Image(_) => out.images.push(ImageInfo {
            alt: collect_text(arena, node_ref, src.text),
            line: arena[node_ref].pos(),
        }),
        KindData::CodeBlock(cb) => {
            // node_pos is a byte offset; convert to line number.
            let node_pos = arena[node_ref].pos();
            let line_num = node_pos.and_then(|p| byte_offset_to_line(src, p));
            // Distinguish fenced from indented code blocks by inspecting the
            // source line at the block's position. Only fenced blocks
            // are eligible for the "missing language" rule (MD040).
            let fenced = line_num
                .and_then(|p| src.lines.get(p))
                .map(|l| has_fence_char(l))
                .unwrap_or(false);
            out.code_blocks.push(CodeBlockInfo {
                language: cb.language_str(src.text).map(|s| s.to_string()),
                fenced,
                line: line_num,
            });

            // Compute the code region span from AST node positions.
            // The mordant parser sets pos() inconsistently:
            //   - Top-level fenced blocks: pos = opening fence line
            //   - Nested fenced blocks (e.g. inside blockquotes): pos = closing fence line
            //   - Indented blocks: pos = last content line
            // We detect the case by checking if pos points to the opening or closing fence.
            if let Some(pos) = line_num {
                let content_lines: usize = cb.value().iter(src.text).count();
                let (region_start, region_end) = if fenced {
                    // Check if pos + 1 + content_lines points to a closing fence line.
                    // If so, pos is the opening fence; otherwise pos is the closing fence.
                    let candidate_end = pos + 1 + content_lines;
                    if candidate_end < src.lines.len() && has_fence_char(src.lines.get(candidate_end).unwrap_or(&"")) {
                        // pos is the opening fence line; candidate_end is closing fence.
                        (pos, candidate_end)
                    } else {
                        // pos is the closing fence line.
                        let opening = pos.saturating_sub(1).saturating_sub(content_lines);
                        (opening, pos)
                    }
                } else {
                    // Indented code block: pos is the last content line.
                    let opening = pos.saturating_sub(content_lines.saturating_sub(1));
                    (opening, pos)
                };
                out.code_regions.push(CodeRegion { start: region_start, end: region_end, fenced });
            }
        }
        _ => {}
    }

    let mut child = arena[node_ref].first_child();
    while let Some(c) = child {
        build(arena, c, src, out);
        child = arena[c].next_sibling();
    }
}

// ---------------------------------------------------------------------------
// AST-derived code mask — lines inside code blocks
// ---------------------------------------------------------------------------

/// Build a boolean mask marking lines that are part of code regions
/// (fenced or indented), derived from the AST's CodeBlock nodes.

// ===========================================================================
// Inline suppression parsing (Phase 6)
// ===========================================================================

/// Parse inline markdownlint suppression comments from the source text.
/// Supports:
///   <!-- markdownlint-disable MD001 MD002 -->
///   <!-- markdownlint-enable MD001 MD002 -->
///   <!-- markdownlint-disable-next-line MD001 MD002 -->
/// If no rule list is given, all rules are affected.
pub fn parse_suppressions(source: &str) -> Vec<SuppressionDirective> {
    let mut directives: Vec<SuppressionDirective> = Vec::new();
    let lines: Vec<&str> = source.lines().collect();
    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if !trimmed.starts_with("<!--") || !trimmed.contains("markdownlint-") {
            continue;
        }
        // Extract the comment content between <!-- and -->
        let content = if let Some(start) = trimmed.find("markdownlint-") {
            let end = trimmed.find("-->").unwrap_or(trimmed.len());
            trimmed[start + "markdownlint-".len()..end].trim() // skip "markdownlint-"
        } else {
            continue;
        };
        let parts: Vec<&str> = content.split_whitespace().collect();
        if parts.is_empty() {
            continue;
        }
        let action = parts[0].to_string();
        let rules: Option<Vec<String>> = if parts.len() > 1 {
            Some(parts[1..].iter().map(|s| s.to_string()).collect())
        } else {
            None // no rules specified = all rules
        };
        directives.push(SuppressionDirective {
            line: i,
            rules,
            action,
        });
    }
    directives
}
/// Replaces the lexical `fence_mask` scan (Phase 2).
fn code_mask(regions: &[CodeRegion], n_lines: usize) -> Vec<bool> {
    let mut mask = vec![false; n_lines];
    for r in regions {
        for i in r.start..=r.end.min(n_lines.saturating_sub(1)) {
            mask[i] = true;
        }
    }
    mask
}

// ---------------------------------------------------------------------------
// Rules (AST-based)
// ---------------------------------------------------------------------------

/// MD001 — heading levels should only increment by one at a time.
fn md001(m: &Collected, out: &mut Vec<Violation>) {
    let mut prev: Option<u8> = None;
    for h in &m.headings {
        if let Some(p) = prev {
            if h.level > p + 1 {
                out.push(Violation::warn(
                    "MD001",
                    "heading-increment",
                    h.line.map(|l| l + 1),
                    None, // column
                    h.line.map(|l| (l, l + 1)), // span: [line_start, line_end)
                    format!(
                        "Heading level jumps from h{} to h{} (expected h{} next)",
                        p,
                        h.level,
                        p + 1
                    ),
                ));
            }
        }
        prev = Some(h.level);
    }
}

/// MD024 — multiple headings with the same text content.
fn md024(m: &Collected, out: &mut Vec<Violation>) {
    let mut seen: HashSet<String> = HashSet::new();
    for h in &m.headings {
        let key = h.text.trim().to_string();
        if key.is_empty() {
            continue;
        }
        if !seen.insert(key) {
            out.push(Violation::warn(
                "MD024",
                "no-duplicate-heading",
                h.line.map(|l| l + 1),
                None, // column
                h.line.map(|l| (l, l + 1)), // span: [line_start, line_end)
                format!("Duplicate heading content: \"{}\"", h.text.trim()),
            ));
        }
    }
}

/// MD025 — a document should have at most one top-level (h1) heading.
///
/// If the document has a frontmatter `title:` field, that counts as the
/// document title, so a single h1 is not flagged (it's a section heading,
/// not a duplicate title). Frontmatter title extraction is done in `build()`.
fn md025(m: &Collected, out: &mut Vec<Violation>) {
    let mut count = 0;
    for h in &m.headings {
        if h.level == 1 {
            count += 1;
            if count > 1 {
                out.push(Violation::warn(
                    "MD025",
                    "single-h1",
                    h.line.map(|l| l + 1),
                    None, // column
                    h.line.map(|l| (l, l + 1)), // span: [line_start, line_end)
                    "Multiple top-level (h1) headings in the same document",
                ));
            }
        }
    }
}

/// MD040 — fenced code blocks should specify a language.
fn md040(m: &Collected, out: &mut Vec<Violation>) {
    for cb in &m.code_blocks {
        if !cb.fenced {
            continue;
        }
        let missing = cb
            .language
            .as_deref()
            .map(|l| l.trim().is_empty())
            .unwrap_or(true);
        if missing {
            // The language can't be inferred, so this carries a fix op that is
            // only applied if the caller supplies a default language.
            let v = match cb.line {
                Some(l0) => Violation::warn_fix(
                    "MD040",
                    "fenced-code-language",
                    Some(l0 + 1),
                    None, // column
                    Some((l0, l0 + 1)), // span: [line_start, line_end)
                    "Fenced code block should specify a language",
                    FixOp::SetCodeLanguage { line: l0 },
                ),
                None => Violation::warn(
                    "MD040",
                    "fenced-code-language",
                    None,
                    None, // column
                    None, // span
                    "Fenced code block should specify a language",
                ),
            };
            out.push(v);
        }
    }
}

/// MD042 — links should not have an empty destination.
/// Also flags fragment-only links (`#anchor`) that don't reference a known
/// heading anchor in the document (R8.3).
fn md042(m: &Collected, out: &mut Vec<Violation>) {
    for l in &m.links {
        let dest = l.destination.trim();
        if dest.is_empty() || dest == "#" {
            out.push(Violation::warn(
                "MD042",
                "no-empty-links",
                l.line.map(|x| x + 1),
                None, // column
                l.line.map(|x| (x, x + 1)), // span: [line_start, line_end)
                "Link has an empty destination",
            ));
            continue;
        }
        // Check fragment-only links against known heading anchors.
        if let Some(fragment) = dest.strip_prefix('#') {
            if !fragment.is_empty() && !m.heading_anchors.contains(&fragment.to_string()) {
                out.push(Violation::warn(
                    "MD042",
                    "no-empty-links",
                    l.line.map(|x| x + 1),
                    None, // column
                    l.line.map(|x| (x, x + 1)), // span: [line_start, line_end)
                    format!("Link references unknown anchor: \"{}\"", fragment),
                ));
            }
        }
    }
}

/// MD045 — images should have alternate text.
fn md045(m: &Collected, out: &mut Vec<Violation>) {
    for img in &m.images {
        if img.alt.trim().is_empty() {
            out.push(Violation::warn(
                "MD045",
                "no-alt-text",
                img.line.map(|l| l + 1),
                None, // column
                img.line.map(|l| (l, l + 1)), // span: [line_start, line_end)
                "Image should have alternate text",
            ));
        }
    }
}

// ---------------------------------------------------------------------------
// Rules (line-based, supplementary)
// ---------------------------------------------------------------------------

/// MD009 — no trailing whitespace (fenced code regions are skipped).
///
/// Exactly two trailing spaces on a non-empty line is a valid CommonMark hard
/// line break, so it is deliberately left alone — both for reporting and for
/// fixing, so the auto-fix can never silently delete an intentional `<br>`.
fn md009(src: &Source, mask: &[bool], out: &mut Vec<Violation>) {
    for (i, line) in src.lines.iter().enumerate() {
        if mask.get(i).copied().unwrap_or(false) {
            continue;
        }
        let trimmed = line.trim_end();
        if line.len() == trimmed.len() {
            continue; // no trailing whitespace
        }
        let trailing = &line[trimmed.len()..];
        let is_hard_break = !trimmed.is_empty() && trailing == "  ";
        if is_hard_break {
            continue;
        }
        // Column = position of first trailing whitespace char
        let col = trimmed.len() + 1; // 1-indexed
        out.push(Violation::warn_fix(
            "MD009",
            "no-trailing-spaces",
            Some(i + 1),
            Some(col), // column
            Some((i, i + 1)), // span: [line_start, line_end)
            "Line has trailing whitespace",
            FixOp::ReplaceLine {
                line: i,
                text: trimmed.to_string(),
            },
        ));
    }
}

/// MD012 — no more than one consecutive blank line (fenced code skipped).
fn md012(src: &Source, mask: &[bool], out: &mut Vec<Violation>) {
    let mut blank_run = 0usize;
    for (i, line) in src.lines.iter().enumerate() {
        if mask.get(i).copied().unwrap_or(false) {
            blank_run = 0;
            continue;
        }
        if line.trim().is_empty() {
            blank_run += 1;
            if blank_run > 1 {
                out.push(Violation::warn_fix(
                    "MD012",
                    "no-multiple-blanks",
                    Some(i + 1),
                    None, // column (blank line, no meaningful column)
                    Some((i, i + 1)), // span: [line_start, line_end)
                    "Multiple consecutive blank lines",
                    FixOp::DeleteLine { line: i },
                ));
            }
        } else {
            blank_run = 0;
        }
    }
}

/// MD047 — files should end with a single trailing newline.
fn md047(src: &Source, out: &mut Vec<Violation>) {
    if !src.text.is_empty() && !src.text.ends_with('\n') {
        // Column = length of last line + 1 (position after last char)
        let last_line = src.lines.last().map(|s| s.len() + 1).unwrap_or(1);
        out.push(Violation::warn_fix(
            "MD047",
            "single-trailing-newline",
            Some(src.lines.len().max(1)),
            Some(last_line), // column
            Some((src.text.len(), src.text.len())), // span: [end, end) — point span
            "File should end with a single newline character",
            FixOp::EnsureFinalNewline,
        ));
    }
}

// ===========================================================================
// Phase 5 — New rules
// ===========================================================================

/// MD010 — no hard tabs (convert tabs to spaces).
fn md010(src: &Source, mask: &[bool], params: &RuleParams, out: &mut Vec<Violation>) {
    let spaces = " ".repeat(params.spaces_per_tab);
    for (i, line) in src.lines.iter().enumerate() {
        if mask.get(i).copied().unwrap_or(false) {
            continue;
        }
        if !line.contains('\t') {
            continue;
        }
        let fixed = line.replace('\t', &spaces);
        out.push(Violation::warn_fix(
            "MD010",
            "no-hard-tabs",
            Some(i + 1),
            Some(line.find('\t').unwrap_or(0) + 1), // 1-indexed column of first tab
            Some((i, i + 1)),
            "Hard tab character(s) found",
            FixOp::ReplaceLine { line: i, text: fixed },
        ));
    }
}

/// MD018 — ATX heading should have a space after the `#` characters.
/// (Report-only: flags but does not auto-fix to avoid changing heading semantics.)
fn md018(src: &Source, mask: &[bool], out: &mut Vec<Violation>) {
    for (i, line) in src.lines.iter().enumerate() {
        if mask.get(i).copied().unwrap_or(false) {
            continue;
        }
        let trimmed = line.trim_start();
        if !trimmed.starts_with('#') {
            continue;
        }
        // Count leading # characters
        let hash_count = trimmed.chars().take_while(|&c| c == '#').count();
        if hash_count == 0 || hash_count > 6 {
            continue;
        }
        // Check if there's a space after the #s
        if hash_count < trimmed.len() && trimmed.as_bytes()[hash_count] != b' ' {
            out.push(Violation::warn(
                "MD018",
                "atx-closing-spaces",
                Some(i + 1),
                Some(hash_count + 1),
                Some((i, i + 1)),
                "ATX heading should have a space after the opening `#` characters",
            ));
        }
    }
}

/// MD019 — ATX heading `#` spacing (leaf: no closing `#`).
/// Report-only: flags ATX headings without closing `#` that have extra spacing.
fn md019(src: &Source, mask: &[bool], out: &mut Vec<Violation>) {
    for (i, line) in src.lines.iter().enumerate() {
        if mask.get(i).copied().unwrap_or(false) {
            continue;
        }
        let trimmed = line.trim_start();
        if !trimmed.starts_with('#') {
            continue;
        }
        let hash_count = trimmed.chars().take_while(|&c| c == '#').count();
        if hash_count == 0 || hash_count > 6 {
            continue;
        }
        // Check if this is a leaf heading (no closing #)
        let rest = &trimmed[hash_count..];
        if rest.trim().is_empty() {
            continue; // empty heading
        }
        // If there's no closing #, it's a leaf ATX heading — MD019 flags
        // leaf ATX headings that don't have a space after opening #s
        if rest.as_bytes()[0] != b' ' {
            out.push(Violation::warn(
                "MD019",
                "atx-spacing",
                Some(i + 1),
                Some(hash_count + 1),
                Some((i, i + 1)),
                "ATX heading should have a space after the opening `#` characters",
            ));
        }
    }
}

/// MD020 — ATX closing `#` spacing (report-only).
fn md020(src: &Source, mask: &[bool], out: &mut Vec<Violation>) {
    for (i, line) in src.lines.iter().enumerate() {
        if mask.get(i).copied().unwrap_or(false) {
            continue;
        }
        let trimmed = line.trim_start();
        if !trimmed.starts_with('#') {
            continue;
        }
        let hash_count = trimmed.chars().take_while(|&c| c == '#').count();
        if hash_count == 0 || hash_count > 6 {
            continue;
        }
        let rest = &trimmed[hash_count..].trim();
        // Check for closing #
        if !rest.ends_with('#') {
            continue;
        }
        // There should be a space before the closing #
        let without_closing = rest[..rest.len() - 1].trim_end();
        if !without_closing.is_empty() && rest.as_bytes()[rest.len() - 2] != b' ' {
            out.push(Violation::warn(
                "MD020",
                "atx-closing-spaces",
                Some(i + 1),
                None,
                Some((i, i + 1)),
                "ATX heading should have a space before the closing `#` characters",
            ));
        }
    }
}

/// MD021 — spaces inside ATX heading `#` characters.
/// Flags headings like "# Hello #" where there should be no space before closing #.
fn md021(src: &Source, mask: &[bool], out: &mut Vec<Violation>) {
    for (i, line) in src.lines.iter().enumerate() {
        if mask.get(i).copied().unwrap_or(false) {
            continue;
        }
        let trimmed = line.trim_start();
        if !trimmed.starts_with('#') {
            continue;
        }
        let hash_count = trimmed.chars().take_while(|&c| c == '#').count();
        if hash_count == 0 || hash_count > 6 {
            continue;
        }
        let rest = trimmed[hash_count..].trim();
        // Check for closing # with space before it
        if rest.ends_with('#') {
            let without_closing = rest[..rest.len() - 1].trim_end();
            if !without_closing.is_empty() {
                // Space before closing # is a style issue (MD021)
                let last_char = without_closing.chars().last();
                if last_char == Some(' ') {
                    out.push(Violation::warn(
                        "MD021",
                        "atx-heading-space",
                        Some(i + 1),
                        None,
                        Some((i, i + 1)),
                        "Multiple spaces inside ATX heading",
                    ));
                }
            }
        }
    }
}

/// MD022 — blank lines around headings.
fn md022(collected: &Collected, src: &Source, out: &mut Vec<Violation>) {
    let n_lines = src.lines.len();
    for h in &collected.headings {
        let h_line = h.line.unwrap_or(0); // already 0-indexed line
        // Check line before heading (must be blank, or heading is first)
        if h_line > 0 {
            let prev_line = h_line - 1;
            if !src.lines[prev_line].trim().is_empty() {
                out.push(Violation::warn(
                    "MD022",
                    "heading-blank-lines",
                    Some(h_line + 1),
                    None,
                    Some((prev_line, prev_line + 1)),
                    "Heading should be preceded by a blank line",
                ));
            }
        }
        // Check line immediately after heading (must be blank, or heading is last)
        let next_line = h_line + 1;
        if next_line < n_lines {
            if !src.lines[next_line].trim().is_empty() {
                out.push(Violation::warn(
                    "MD022",
                    "heading-blank-lines",
                    Some(h_line + 1),
                    None,
                    Some((h_line, h_line + 1)),
                    "Heading should be followed by a blank line",
                ));
            }
        }
    }
}

/// MD026 — trailing punctuation in headings.
fn md026(collected: &Collected, src: &Source, out: &mut Vec<Violation>) {
    for h in &collected.headings {
        let text = h.text.trim();
        if text.is_empty() {
            continue;
        }
        let last_char = text.chars().last().unwrap_or('\0');
        // Allow common punctuation: . ! ? ) ] }
        if matches!(last_char, '.' | '!' | '?') {
            let line_num = h.line.unwrap_or(0); // already 0-indexed line
            // Get the original source line and replace only the trailing punctuation
            if let Some(orig_line) = src.lines.get(line_num) {
                let fixed_line = orig_line.trim_end_matches(last_char);
                out.push(Violation::warn_fix(
                    "MD026",
                    "no-trailing-punctuation",
                    Some(line_num + 1),
                    None,
                    Some((line_num, line_num + 1)),
                    format!("Heading should not end with trailing punctuation ({last_char})"),
                    FixOp::ReplaceLine {
                        line: line_num,
                        text: fixed_line.to_string(),
                    },
                ));
            }
        }
    }
}

/// MD031 — blank lines around fenced code blocks.
fn md031(collected: &Collected, src: &Source, out: &mut Vec<Violation>) {
    let lines = src.lines.len();
    for cb in collected.code_blocks.iter().filter(|cb| cb.fenced) {
        let cb_line = cb.line.unwrap_or(0); // 0-indexed
        // Check line before
        if cb_line > 0 {
            let prev_line = cb_line - 1;
            if !src.lines[prev_line].trim().is_empty() {
                out.push(Violation::warn(
                    "MD031",
                    "fenced-code-blocks-working",
                    Some(cb_line + 1),
                    None,
                    Some((prev_line, prev_line + 1)),
                    "Fenced code block should be preceded by a blank line",
                ));
            }
        }
        // Check line after (find the closing fence first)
        // For simplicity, check the next line after the opening fence line
        // The actual closing fence detection is handled by the AST region
        if cb_line + 1 < lines {
            let next_line_idx = cb_line + 1;
            // Skip past content lines to find the line after the closing fence
            // This is approximate — the code_mask already handles the region
            if next_line_idx < lines && !src.lines[next_line_idx].trim().is_empty() {
                // Check if this is a closing fence
                let mut after_closing = false;
                if collected.code_regions.len() > 0 {
                    for region in &collected.code_regions {
                        if region.start == cb_line && next_line_idx == region.end + 1 {
                            after_closing = true;
                            break;
                        }
                    }
                }
                if after_closing && !src.lines[next_line_idx].trim().is_empty() {
                    out.push(Violation::warn(
                        "MD031",
                        "fenced-code-blocks-working",
                        Some(next_line_idx + 1),
                        None,
                        Some((next_line_idx, next_line_idx + 1)),
                        "Fenced code block should be followed by a blank line",
                    ));
                }
            }
        }
    }
}

/// MD032 — blank lines around indented code blocks.
fn md032(collected: &Collected, src: &Source, out: &mut Vec<Violation>) {
    let lines = src.lines.len();
    for cb in collected.code_blocks.iter().filter(|cb| !cb.fenced) {
        let cb_line = cb.line.unwrap_or(0); // 0-indexed
        // Check line before
        if cb_line > 0 {
            let prev_line = cb_line - 1;
            if !src.lines[prev_line].trim().is_empty() {
                out.push(Violation::warn(
                    "MD032",
                    "indented-code-block",
                    Some(cb_line + 1),
                    None,
                    Some((prev_line, prev_line + 1)),
                    "Indented code block should be preceded by a blank line",
                ));
            }
        }
        // Check line after
        if cb_line + 1 < lines {
            let next_line_idx = cb_line + 1;
            if next_line_idx < lines && !src.lines[next_line_idx].trim().is_empty() {
                out.push(Violation::warn(
                    "MD032",
                    "indented-code-block",
                    Some(next_line_idx + 1),
                    None,
                    Some((next_line_idx, next_line_idx + 1)),
                    "Indented code block should be followed by a blank line",
                ));
            }
        }
    }
}

/// MD034 — bare URLs in link text.
/// Flags links where the link text is a bare URL.
fn md034(collected: &Collected, _out: &mut Vec<Violation>) {
    // Placeholder: detect links where the text is a bare URL
    // This requires walking the AST for link nodes and comparing
    // link text against the destination. For now, no violations.
    let _ = collected;
}

/// MD003 — heading style (report-only).
fn md003(_collected: &Collected, _params: &RuleParams, _out: &mut Vec<Violation>) {
    // Placeholder: check that all headings use the same style
    // (all ATX or all setext). Detailed style checking
    // requires setext detection which is more complex.
}

/// MD013 — line length (report-only).
fn md013(src: &Source, mask: &[bool], params: &RuleParams, out: &mut Vec<Violation>) {
    let limit = params.line_length;
    let threshold = params.line_length_ignore_threshold;
    for (i, line) in src.lines.iter().enumerate() {
        if mask.get(i).copied().unwrap_or(false) {
            continue;
        }
        if line.len() <= threshold {
            continue;
        }
        if line.len() > limit {
            out.push(Violation::warn(
                "MD013",
                "line-length",
                Some(i + 1),
                None,
                Some((i, i + 1)),
                format!("Line is {} characters long (max {})", line.len(), limit),
            ));
        }
    }
}

/// MD046 — code block indentation (report-only).
fn md046(collected: &Collected, src: &Source, out: &mut Vec<Violation>) {
    for cb in &collected.code_blocks {
        if !cb.fenced {
            continue; // only fenced blocks
        }
        let cb_line = cb.line.unwrap_or(0);
        // Check if the fence line has indentation
        if let Some(line) = src.lines.get(cb_line) {
            let leading_spaces = line.chars().take_while(|&c| c == ' ').count();
            if leading_spaces > 0 && leading_spaces < 4 {
                out.push(Violation::warn(
                    "MD046",
                    "code-block-indentation",
                    Some(cb_line + 1),
                    None,
                    Some((cb_line, cb_line + 1)),
                    "Fenced code block should use 4-space indentation or no indentation",
                ));
            }
        }
    }
}

/// MD048 — fenced code block punctuation style (report-only).
fn md048(collected: &Collected, src: &Source, out: &mut Vec<Violation>) {
    for cb in &collected.code_blocks {
        if !cb.fenced {
            continue;
        }
        let cb_line = cb.line.unwrap_or(0);
        if let Some(line) = src.lines.get(cb_line) {
            let trimmed = line.trim_start();
            // Check for tilde fences
            if trimmed.starts_with("~~~") {
                out.push(Violation::warn(
                    "MD048",
                    "fenced-code-block-punctuation",
                    Some(cb_line + 1),
                    None,
                    Some((cb_line, cb_line + 1)),
                    "Fenced code block should use backticks, not tildes",
                ));
            }
        }
    }
}

/// MD049 — emphasis style (report-only).
/// Flags use of `*` for emphasis when `__` (double underscore) is preferred.
fn md049(_collected: &Collected, _out: &mut Vec<Violation>) {
    // Placeholder: detect emphasis nodes that use * instead of _
    // This requires walking the AST for emphasis/delimiter nodes.
    // For now, no violations.
}

/// MD050 — strong style (report-only).
/// Flags use of `**` for strong when ___ (triple underscore) is preferred.
fn md050(_collected: &Collected, _out: &mut Vec<Violation>) {
    // Placeholder: detect strong nodes that use ** instead of ___
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

/// Run all enabled lint rules against a parsed AST.
///
/// `root` is the document root `NodeRef`; `arena` and `source` are the parse
/// outputs. Returns plain-Rust `Violation`s sorted by (line, rule id).
pub fn run_lint(source: &str, arena: &Arena, root: NodeRef, cfg: &LintConfig) -> Vec<Violation> {
    run_lint_with_params(source, arena, root, cfg, &cfg.params)
}

/// Run all enabled lint rules with custom per-rule parameters.
pub fn run_lint_with_params(
    source: &str,
    arena: &Arena,
    root: NodeRef,
    cfg: &LintConfig,
    params: &RuleParams,
) -> Vec<Violation> {
    let src = Source {
        text: source,
        lines: source.lines().collect(),
    };

    let mut collected = Collected::default();
    build(arena, root, &src, &mut collected);

    let mask = code_mask(&collected.code_regions, src.lines.len());

    let mut out: Vec<Violation> = Vec::new();

    // AST-based rules (Phase 0)
    md001(&collected, &mut out);
    md024(&collected, &mut out);
    md025(&collected, &mut out);
    md040(&collected, &mut out);
    md042(&collected, &mut out);
    md045(&collected, &mut out);

    // Phase 5 — new AST-based rules
    md018(&src, &mask, &mut out);
    md019(&src, &mask, &mut out);
    md020(&src, &mask, &mut out);
    md021(&src, &mask, &mut out);
    md022(&collected, &src, &mut out);
    md026(&collected, &src, &mut out);
    md031(&collected, &src, &mut out);
    md032(&collected, &src, &mut out);
    md034(&collected, &mut out);
    md003(&collected, params, &mut out);
    md049(&collected, &mut out);
    md050(&collected, &mut out);

    // Line-based supplementary rules (Phase 0)
    md009(&src, &mask, &mut out);
    md012(&src, &mask, &mut out);
    md047(&src, &mut out);

    // Phase 5 — new line-based rules
    md010(&src, &mask, params, &mut out);
    md013(&src, &mask, params, &mut out);

    // Phase 5 — report-only style rules
    md046(&collected, &src, &mut out);
    md048(&collected, &src, &mut out);

    // Apply enable/disable configuration and inline suppressions.
    out.retain(|v| {
        let line_0indexed = v.line.map(|l| l.saturating_sub(1));
        cfg.is_enabled(v.rule) && (!line_0indexed.map(|l| cfg.is_suppressed(v.rule, l)).unwrap_or(false))
    });

    // Stable ordering: by source line, then by rule id.
    out.sort_by(|a, b| {
        a.line
            .unwrap_or(usize::MAX)
            .cmp(&b.line.unwrap_or(usize::MAX))
            .then_with(|| a.rule.cmp(b.rule))
    });

    out
}

// ---------------------------------------------------------------------------
// Auto-fix
// ---------------------------------------------------------------------------

/// Rewrite a fence's opening line to include `lang`, preserving indentation and
/// the fence characters (e.g. "```" -> "```python", "  ~~~~" -> "  ~~~~python").
fn set_fence_language(orig: &str, lang: &str) -> String {
    let trimmed = orig.trim_start();
    let indent = &orig[..orig.len() - trimmed.len()];
    let fence_char = trimmed.chars().next().unwrap_or('`');
    let fence_len = trimmed.chars().take_while(|&c| c == fence_char).count();
    let fence: String = std::iter::repeat(fence_char).take(fence_len).collect();
    format!("{indent}{fence}{lang}")
}

/// Apply a set of fixes to the source text, returning the corrected Markdown.
///
/// `fixes` should contain only violations whose fix is applicable. Deletions
/// take precedence over replacements on the same line. Line indices in the
/// fixes refer to the original source, and the original array is walked once,
/// so there is no re-indexing hazard.
fn apply_fixes(source: &str, fixes: &[Violation], default_language: Option<&str>) -> String {
    let lines: Vec<&str> = source.lines().collect();

    let mut replace: std::collections::HashMap<usize, String> = std::collections::HashMap::new();
    let mut delete: HashSet<usize> = HashSet::new();
    let mut ensure_nl = false;

    for v in fixes {
        match &v.fix {
            Some(FixOp::ReplaceLine { line, text }) => {
                replace.insert(*line, text.clone());
            }
            Some(FixOp::DeleteLine { line }) => {
                delete.insert(*line);
            }
            Some(FixOp::EnsureFinalNewline) => {
                ensure_nl = true;
            }
            Some(FixOp::SetCodeLanguage { line }) => {
                if let Some(lang) = default_language {
                    if let Some(orig) = lines.get(*line) {
                        replace.insert(*line, set_fence_language(orig, lang));
                    }
                }
            }
            None => {}
        }
    }

    let mut out: Vec<String> = Vec::with_capacity(lines.len());
    for (i, line) in lines.iter().enumerate() {
        if delete.contains(&i) {
            continue; // deletion wins over any replacement on the same line
        }
        match replace.get(&i) {
            Some(t) => out.push(t.clone()),
            None => out.push((*line).to_string()),
        }
    }

    let mut result = out.join("\n");
    // Preserve the original trailing-newline state; add one if MD047 asked.
    if source.ends_with('\n') || ensure_nl {
        result.push('\n');
    }
    result
}


// ===========================================================================
// Rule metadata - for lint_rules() introspection
// ===========================================================================

/// Metadata about a single lint rule.
#[derive(Debug, Clone)]
pub struct RuleSpec {
    pub id: &'static str,
    pub name: &'static str,
    pub description: &'static str,
    pub fixable: bool,
    pub default_params: &'static str,
}

/// Return metadata for all registered lint rules.
pub fn lint_rules() -> Vec<RuleSpec> {
    vec![
        RuleSpec { id: "MD001", name: "heading-increment", description: "Heading levels should increment by one at a time", fixable: false, default_params: "{}" },
        RuleSpec { id: "MD003", name: "heading-style", description: "Heading style consistency", fixable: false, default_params: "{\"heading_style\": \"consistent\"}" },
        RuleSpec { id: "MD009", name: "no-trailing-spaces", description: "Lines should not have trailing spaces", fixable: true, default_params: "{}" },
        RuleSpec { id: "MD010", name: "no-hard-tabs", description: "Lines should not contain hard tabs", fixable: true, default_params: "{\"spaces_per_tab\": 4}" },
        RuleSpec { id: "MD012", name: "no-multiple-blanks", description: "There should be no more than one consecutive blank line", fixable: true, default_params: "{}" },
        RuleSpec { id: "MD013", name: "line-length", description: "Lines should not exceed a specified number of characters", fixable: false, default_params: "{\"line_length\": 80, \"line_length_ignore_threshold\": 0}" },
        RuleSpec { id: "MD018", name: "atx-spacing", description: "ATX headings should have a space after the opening '#'", fixable: false, default_params: "{}" },
        RuleSpec { id: "MD019", name: "atx-closing-spaces", description: "ATX leaf headings should not have closing '#'", fixable: false, default_params: "{}" },
        RuleSpec { id: "MD020", name: "atx-closing-spaces", description: "ATX headings should have a space before the closing '#'", fixable: false, default_params: "{}" },
        RuleSpec { id: "MD021", name: "atx-heading-space", description: "Multiple spaces inside ATX heading", fixable: false, default_params: "{}" },
        RuleSpec { id: "MD022", name: "heading-blank-lines", description: "Headings should have blank lines around them", fixable: true, default_params: "{}" },
        RuleSpec { id: "MD024", name: "no-duplicate-heading", description: "Multiple headings with the same content", fixable: false, default_params: "{\"siblings_only\": false}" },
        RuleSpec { id: "MD025", name: "single-h1", description: "Document should have only one h1 heading", fixable: false, default_params: "{}" },
        RuleSpec { id: "MD026", name: "no-trailing-punctuation", description: "Headings should not end with trailing punctuation", fixable: true, default_params: "{}" },
        RuleSpec { id: "MD031", name: "fenced-code-blocks-working", description: "Fenced code blocks should have blank lines around them", fixable: true, default_params: "{}" },
        RuleSpec { id: "MD032", name: "indented-code-block", description: "Indented code blocks should have blank lines around them", fixable: false, default_params: "{}" },
        RuleSpec { id: "MD034", name: "no-bare-urls", description: "Bare URLs should be in angle brackets", fixable: false, default_params: "{}" },
        RuleSpec { id: "MD040", name: "fenced-code-language", description: "Fenced code blocks should specify a language", fixable: true, default_params: "{\"default_language\": null}" },
        RuleSpec { id: "MD042", name: "no-empty-links", description: "Links should have a non-empty destination", fixable: false, default_params: "{}" },
        RuleSpec { id: "MD045", name: "no-alt-text", description: "Images should have alternate text", fixable: false, default_params: "{}" },
        RuleSpec { id: "MD046", name: "code-block-indentation", description: "Fenced code blocks should use 4-space indentation", fixable: false, default_params: "{}" },
        RuleSpec { id: "MD047", name: "single-trailing-newline", description: "Files should end with a single trailing newline", fixable: true, default_params: "{}" },
        RuleSpec { id: "MD048", name: "fenced-code-block-punctuation", description: "Fenced code blocks should use backticks, not tildes", fixable: false, default_params: "{}" },
        RuleSpec { id: "MD049", name: "emphasis-style", description: "Emphasis style consistency", fixable: false, default_params: "{}" },
        RuleSpec { id: "MD050", name: "strong-style", description: "Strong style consistency", fixable: false, default_params: "{}" },
    ]
}

// ===========================================================================
// Phase 1 — Pure-function unit tests (cargo test)
// ===========================================================================

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

    // -----------------------------------------------------------------------
    // Helpers — construct Source from a raw string slice
    // -----------------------------------------------------------------------

    fn src(s: &str) -> Source<'_> {
        Source {
            text: s,
            lines: s.lines().collect(),
        }
    }

    // -----------------------------------------------------------------------
    // set_fence_language
    // -----------------------------------------------------------------------

    #[test]
    fn set_fence_language_basic() {
        assert_eq!(set_fence_language("```", "py"), "```py");
        assert_eq!(set_fence_language("~~~", "js"), "~~~js");
    }

    #[test]
    fn set_fence_language_preserves_indentation() {
        assert_eq!(set_fence_language("  ```", "python"), "  ```python");
    }

    #[test]
    fn set_fence_language_preserves_tilde_fence() {
        assert_eq!(set_fence_language("~~~~", "text"), "~~~~text");
    }

    // -----------------------------------------------------------------------
    // md009 — trailing whitespace
    // -----------------------------------------------------------------------

    #[test]
    fn md009_detects_trailing_spaces() {
        let s = src("hello   \n");
        let mask: Vec<bool> = Vec::new(); // not in code
        let mut v: Vec<Violation> = Vec::new();
        md009(&s, &mask, &mut v);
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].rule, "MD009");
        assert!(v[0].fix.is_some());
    }

    #[test]
    fn md009_ignores_hard_line_break() {
        // Exactly two trailing spaces = hard break — must NOT be flagged.
        let s = src("line one  \n");
        let mask: Vec<bool> = Vec::new();
        let mut v: Vec<Violation> = Vec::new();
        md009(&s, &mask, &mut v);
        assert!(v.is_empty());
    }

    #[test]
    fn md009_ignores_code_region() {
        let s = src("```\ncode   \n```\n");
        let mask = vec![true, true, true]; // all lines are in code
        let mut v: Vec<Violation> = Vec::new();
        md009(&s, &mask, &mut v);
        assert!(v.is_empty());
    }

    #[test]
    fn md009_ignores_clean_lines() {
        let s = src("clean line\n");
        let mask: Vec<bool> = Vec::new();
        let mut v: Vec<Violation> = Vec::new();
        md009(&s, &mask, &mut v);
        assert!(v.is_empty());
    }

    #[test]
    fn md009_multiple_violations() {
        let s = src("a   \nb   \n");
        let mask: Vec<bool> = Vec::new();
        let mut v: Vec<Violation> = Vec::new();
        md009(&s, &mask, &mut v);
        assert_eq!(v.len(), 2);
    }

    // -----------------------------------------------------------------------
    // md012 — multiple blank lines
    // -----------------------------------------------------------------------

    #[test]
    fn md012_detects_extra_blank() {
        let s = src("a\n\n\nb\n");
        let mask: Vec<bool> = Vec::new();
        let mut v: Vec<Violation> = Vec::new();
        md012(&s, &mask, &mut v);
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].rule, "MD012");
    }

    #[test]
    fn md012_allows_single_blank() {
        let s = src("a\n\nb\n");
        let mask: Vec<bool> = Vec::new();
        let mut v: Vec<Violation> = Vec::new();
        md012(&s, &mask, &mut v);
        assert!(v.is_empty());
    }

    #[test]
    fn md012_skips_code_regions() {
        // Multiple blanks inside a fenced block should be ignored.
        let s = src("```\n\n\n```\n");
        let mask = vec![true, true, true, true];
        let mut v: Vec<Violation> = Vec::new();
        md012(&s, &mask, &mut v);
        assert!(v.is_empty());
    }

    // -----------------------------------------------------------------------
    // md047 — final newline
    // -----------------------------------------------------------------------

    #[test]
    fn md047_detects_missing_newline() {
        let s = src("no newline");
        let mut v: Vec<Violation> = Vec::new();
        md047(&s, &mut v);
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].rule, "MD047");
    }

    #[test]
    fn md047_allows_existing_newline() {
        let s = src("has newline\n");
        let mut v: Vec<Violation> = Vec::new();
        md047(&s, &mut v);
        assert!(v.is_empty());
    }

    #[test]
    fn md047_empty_document_ok() {
        let s = src("");
        let mut v: Vec<Violation> = Vec::new();
        md047(&s, &mut v);
        assert!(v.is_empty());
    }

    // -----------------------------------------------------------------------
    // apply_fixes
    // -----------------------------------------------------------------------

    #[test]
    fn apply_fixes_strips_trailing_whitespace() {
        let fixes = vec![Violation::warn_fix(
            "MD009", "no-trailing-spaces", Some(1), None, None, "",
            FixOp::ReplaceLine { line: 0, text: "hello".to_string() },
        )];
        let result = apply_fixes("hello   \n", &fixes, None);
        assert_eq!(result, "hello\n");
    }

    #[test]
    fn apply_fixes_deletes_blank_lines() {
        let fixes = vec![Violation::warn_fix(
            "MD012", "no-multiple-blanks", Some(3), None, None, "",
            FixOp::DeleteLine { line: 2 },
        )];
        let result = apply_fixes("a\n\n\nb\n", &fixes, None);
        assert_eq!(result, "a\n\nb\n");
    }

    #[test]
    fn apply_fixes_adds_final_newline() {
        let fixes = vec![Violation::warn_fix(
            "MD047", "single-trailing-newline", Some(1), None, None, "",
            FixOp::EnsureFinalNewline,
        )];
        let result = apply_fixes("no newline", &fixes, None);
        assert_eq!(result, "no newline\n");
    }

    #[test]
    fn apply_fixes_deletion_wins_over_replacement() {
        let fixes = vec![
            Violation::warn_fix("MD009", "x", Some(1), None, None, "", FixOp::ReplaceLine { line: 1, text: "replaced".to_string() }),
            Violation::warn_fix("MD012", "x", Some(2), None, None, "", FixOp::DeleteLine { line: 1 }),
        ];
        let result = apply_fixes("a\n  \nb\n", &fixes, None);
        assert_eq!(result, "a\nb\n");
    }

    #[test]
    fn apply_fixes_multiple_on_same_line() {
        // Two ReplaceLine on the same line — last one wins (HashMap overwrite).
        let fixes = vec![
            Violation::warn_fix("MD009", "x", Some(1), None, None, "", FixOp::ReplaceLine { line: 0, text: "first".to_string() }),
            Violation::warn_fix("MD009", "x", Some(1), None, None, "", FixOp::ReplaceLine { line: 0, text: "second".to_string() }),
        ];
        let result = apply_fixes("hello   \n", &fixes, None);
        // Either "first" or "second" is fine — the important thing is
        // no panic and a single replacement.
        assert_eq!(result, "second\n");
    }

    // -----------------------------------------------------------------------
    // code_mask — AST-derived (Phase 2)
    // -----------------------------------------------------------------------

    #[test]
    fn code_mask_marks_single_fenced_block() {
        // Opening fence at line 0, 1 content line, closing fence at line 2
        let regions = vec![CodeRegion { start: 0, end: 2, fenced: true }];
        let mask = code_mask(&regions, 3);
        assert_eq!(mask, vec![true, true, true]);
    }

    #[test]
    fn code_mask_marks_multiple_regions() {
        let regions = vec![
            CodeRegion { start: 0, end: 0, fenced: true },   // line 0
            CodeRegion { start: 3, end: 4, fenced: true },   // lines 3-4
        ];
        let mask = code_mask(&regions, 5);
        assert_eq!(mask, vec![true, false, false, true, true]);
    }

    #[test]
    fn code_mask_skips_non_code_lines() {
        let regions = vec![CodeRegion { start: 1, end: 2, fenced: true }];
        let mask = code_mask(&regions, 5);
        assert_eq!(mask, vec![false, true, true, false, false]);
    }

    #[test]
    fn code_mask_clamps_to_line_count() {
        // End index beyond line count should be clamped.
        let regions = vec![CodeRegion { start: 3, end: 10, fenced: true }];
        let mask = code_mask(&regions, 5);
        assert_eq!(mask, vec![false, false, false, true, true]);
    }

    #[test]
    fn code_mask_empty() {
        let mask = code_mask(&[], 3);
        assert_eq!(mask, vec![false, false, false]);
    }

    // -----------------------------------------------------------------------
    // Idempotence — fix(fix(x)) == fix(x) for the pure fix path
    // -----------------------------------------------------------------------

    #[test]
    fn fix_idempotent_trailing_space() {
        let fixes = vec![Violation::warn_fix(
            "MD009", "x", Some(1), None, None, "", FixOp::ReplaceLine { line: 0, text: "hello".to_string() })];
        let once = apply_fixes("hello   \n", &fixes, None);
        let twice = apply_fixes(&once, &[], None);
        assert_eq!(once, twice);
    }

    #[test]
    fn fix_idempotent_blank_lines() {
        let fixes = vec![Violation::warn_fix(
            "MD012", "x", Some(3), None, None, "", FixOp::DeleteLine { line: 2 })];
        let once = apply_fixes("a\n\n\nb\n", &fixes, None);
        let twice = apply_fixes(&once, &[], None);
        assert_eq!(once, twice);
    }

    #[test]
    fn fix_idempotent_final_newline() {
        let fixes = vec![Violation::warn_fix(
            "MD047", "x", Some(1), None, None, "", FixOp::EnsureFinalNewline)];
        let once = apply_fixes("no newline", &fixes, None);
        let twice = apply_fixes(&once, &[], None);
        assert_eq!(once, twice);
    }

    // -----------------------------------------------------------------------
    // HTML-equivalence oracle (NFR-1)
    //
    // For whitespace-only fixable rules, the fix must never change rendered
    // HTML.  This test is a thin shim — the full Hypothesis-driven oracle
    // lives in tests/test_fix_safety.py (Python side).  This Rust test
    // exercises the common cases.
    // -----------------------------------------------------------------------

    #[test]
    fn md009_fix_preserves_rendered_output() {
        // "hello   " → "hello" (three spaces stripped)
        // In HTML both render as "hello" (trailing spaces are ignorable).
        let src = "hello   \n";
        let fixes = vec![Violation::warn_fix(
            "MD009", "x", Some(1), None, None, "", FixOp::ReplaceLine { line: 0, text: "hello".to_string() })];
        let fixed = apply_fixes(src, &fixes, None);
        assert_eq!(fixed, "hello\n");
    }
}

// ===========================================================================
// Auto-fix entry point
// ===========================================================================

/// Lint Markdown source and auto-correct the fixable issues.
///
/// Returns a FixResult with the corrected source (`.output`), the diagnostics
/// that were fixed (`.fixed`), and the ones that still need manual attention
/// (`.unfixable`). Auto-fixable rules: MD009 (trailing spaces), MD010 (tabs),
/// MD012 (multiple blanks), MD026 (trailing punctuation), MD040 (code language),
/// MD047 (final newline). Structural rules are reported but not changed.
///
/// Note: `unfixable` line numbers refer to the *input*. After fixing, lint the
/// returned `output` to get diagnostics with positions in the corrected text.
///
/// The fix engine iterates until stable (max 10 iterations), collecting all
/// fixed violations across iterations. `remaining` is computed by re-linting
/// the final output.
pub fn run_fix(
    source: &str,
    arena: &Arena,
    root: NodeRef,
    cfg: &LintConfig,
    default_language: Option<&str>,
) -> FixOutcome {
    run_fix_with_params(source, arena, root, cfg, &RuleParams::default(), default_language)
}

/// Lint and auto-correct with custom per-rule parameters.
pub fn run_fix_with_params(
    source: &str,
    arena: &Arena,
    root: NodeRef,
    cfg: &LintConfig,
    params: &RuleParams,
    default_language: Option<&str>,
) -> FixOutcome {
    let max_iterations = 10;
    let mut current_source = source.to_string();
    let mut all_fixed: Vec<Violation> = Vec::new();
    let mut all_unfixable: Vec<Violation> = Vec::new();

    for _iteration in 0..max_iterations {
        let violations = run_lint_with_params(&current_source, arena, root, cfg, params);

        let mut fixed: Vec<Violation> = Vec::new();
        let mut unfixable: Vec<Violation> = Vec::new();
        for v in violations {
            let applicable = match &v.fix {
                Some(FixOp::SetCodeLanguage { .. }) => default_language.is_some(),
                Some(_) => true,
                None => false,
            };
            if applicable {
                fixed.push(v);
            } else {
                unfixable.push(v);
            }
        }

        let no_more_fixable = fixed.is_empty();

        all_fixed.extend(fixed);
        all_unfixable.extend(unfixable);

        if no_more_fixable {
            break;
        }

        current_source = apply_fixes(&current_source, &all_fixed, default_language);
    }

    let remaining = run_lint_with_params(&current_source, arena, root, cfg, params);

    FixOutcome {
        output: current_source,
        fixed: all_fixed,
        unfixable: all_unfixable,
        remaining,
    }
}