mdbook-lint 0.2.0

A fast markdown linter for mdBook
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
//! MD056 - Table column count
//!
//! This rule is triggered when a GitHub Flavored Markdown table does not have
//! the same number of cells in every row.
//!
//! ## Correct
//!
//! ```markdown
//! | Header | Header |
//! | ------ | ------ |
//! | Cell   | Cell   |
//! | Cell   | Cell   |
//! ```
//!
//! ## Incorrect
//!
//! ```markdown
//! | Header | Header |
//! | ------ | ------ |
//! | Cell   | Cell   |
//! | Cell   |
//! | Cell   | Cell   | Cell   |
//! ```

use crate::error::Result;
use crate::{
    Document, Violation,
    rule::{Rule, RuleCategory, RuleMetadata},
    violation::Severity,
};
use comrak::nodes::{AstNode, NodeValue};

/// MD056 - Table column count
pub struct MD056;

impl Default for MD056 {
    fn default() -> Self {
        Self::new()
    }
}

impl MD056 {
    /// Create a new MD056 rule instance
    pub fn new() -> Self {
        Self
    }

    /// Count cells in a table row
    fn count_cells<'a>(&self, node: &'a AstNode<'a>) -> usize {
        let mut cell_count = 0;
        for child in node.children() {
            if matches!(child.data.borrow().value, NodeValue::TableCell) {
                cell_count += 1;
            }
        }
        cell_count
    }

    /// Check table column consistency
    fn check_table_columns<'a>(&self, ast: &'a AstNode<'a>) -> Vec<Violation> {
        let mut violations = Vec::new();
        self.traverse_for_tables(ast, &mut violations);
        violations
    }

    /// Traverse AST to find tables
    fn traverse_for_tables<'a>(&self, node: &'a AstNode<'a>, violations: &mut Vec<Violation>) {
        if let NodeValue::Table(_) = &node.data.borrow().value {
            self.check_table(node, violations);
        }

        for child in node.children() {
            self.traverse_for_tables(child, violations);
        }
    }

    /// Check a single table for column count consistency
    fn check_table<'a>(&self, table_node: &'a AstNode<'a>, violations: &mut Vec<Violation>) {
        let mut rows = Vec::new();
        let mut expected_columns = None;

        // Collect all rows
        for child in table_node.children() {
            if matches!(child.data.borrow().value, NodeValue::TableRow(..)) {
                let cell_count = self.count_cells(child);
                let pos = child.data.borrow().sourcepos;
                let line = pos.start.line;
                let column = pos.start.column;
                rows.push((cell_count, line, column));

                // Set expected column count from the first row (header)
                if expected_columns.is_none() {
                    expected_columns = Some(cell_count);
                }
            }
        }

        let expected = expected_columns.unwrap_or(0);

        // Check each row against expected column count
        for (i, (cell_count, line, column)) in rows.iter().enumerate() {
            if *cell_count != expected {
                let row_type = if i == 0 {
                    "header row"
                } else if i == 1 {
                    "delimiter row"
                } else {
                    "data row"
                };

                let message = if *cell_count < expected {
                    format!(
                        "Table {} has {} cells, expected {} (missing {} cells)",
                        row_type,
                        cell_count,
                        expected,
                        expected - cell_count
                    )
                } else {
                    format!(
                        "Table {} has {} cells, expected {} (extra {} cells)",
                        row_type,
                        cell_count,
                        expected,
                        cell_count - expected
                    )
                };

                violations.push(self.create_violation(message, *line, *column, Severity::Error));
            }
        }
    }

    /// Fallback method using manual parsing when no AST is available
    fn check_tables_fallback(&self, document: &Document) -> Vec<Violation> {
        let mut violations = Vec::new();
        let mut in_table = false;
        let mut expected_columns: Option<usize> = None;
        let mut table_row_index = 0;

        for (line_num, line) in document.content.lines().enumerate() {
            if self.is_table_row(line) {
                let cell_count = line.matches('|').count().saturating_sub(1);

                if !in_table {
                    // First row of table (header)
                    expected_columns = Some(cell_count);
                    in_table = true;
                    table_row_index = 0;
                } else if let Some(expected) = expected_columns {
                    if cell_count != expected {
                        let row_type = if table_row_index == 1 {
                            "delimiter row"
                        } else {
                            "data row"
                        };

                        let message = if cell_count < expected {
                            format!(
                                "Table {} has {} cells, expected {} (missing {} cells)",
                                row_type,
                                cell_count,
                                expected,
                                expected - cell_count
                            )
                        } else {
                            format!(
                                "Table {} has {} cells, expected {} (extra {} cells)",
                                row_type,
                                cell_count,
                                expected,
                                cell_count - expected
                            )
                        };

                        violations.push(self.create_violation(
                            message,
                            line_num + 1,
                            1,
                            Severity::Error,
                        ));
                    }
                }
                table_row_index += 1;
            } else if in_table && line.trim().is_empty() {
                // End of table
                in_table = false;
                expected_columns = None;
                table_row_index = 0;
            }
        }

        violations
    }

    /// Check if a line is a table row without using regex
    fn is_table_row(&self, line: &str) -> bool {
        let trimmed = line.trim();

        // Must start and end with pipe
        if !trimmed.starts_with('|') || !trimmed.ends_with('|') {
            return false;
        }

        // Must have at least 2 pipes (start and end)
        trimmed.matches('|').count() >= 2
    }
}

impl Rule for MD056 {
    fn id(&self) -> &'static str {
        "MD056"
    }

    fn name(&self) -> &'static str {
        "table-column-count"
    }

    fn description(&self) -> &'static str {
        "Table column count"
    }

    fn metadata(&self) -> RuleMetadata {
        RuleMetadata::stable(RuleCategory::Structure)
    }

    fn check_with_ast<'a>(
        &self,
        document: &Document,
        ast: Option<&'a AstNode<'a>>,
    ) -> Result<Vec<Violation>> {
        if let Some(ast) = ast {
            let violations = self.check_table_columns(ast);
            Ok(violations)
        } else {
            // Simplified regex-based fallback when no AST is available
            Ok(self.check_tables_fallback(document))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helpers::{
        assert_no_violations, assert_single_violation, assert_violation_count,
    };

    #[test]
    fn test_consistent_table() {
        let content = r#"| Header | Header |
| ------ | ------ |
| Cell   | Cell   |
| Cell   | Cell   |
"#;

        assert_no_violations(MD056::new(), content);
    }

    #[test]
    fn test_missing_cells() {
        let content = r#"| Header | Header |
| ------ | ------ |
| Cell   | Cell   |
| Cell   |
"#;

        let violation = assert_single_violation(MD056::new(), content);
        assert_eq!(violation.line, 4);
        assert!(violation.message.contains("missing 1 cells"));
    }

    #[test]
    fn test_extra_cells() {
        let content = r#"| Header | Header |
| ------ | ------ |
| Cell   | Cell   |
| Cell   | Cell   | Cell   |
"#;

        let violation = assert_single_violation(MD056::new(), content);
        assert_eq!(violation.line, 4);
        assert!(violation.message.contains("extra 1 cells"));
    }

    #[test]
    fn test_delimiter_row_mismatch() {
        let content = r#"| Header | Header |
| ------ |
| Cell   | Cell   |
"#;

        let violation = assert_single_violation(MD056::new(), content);
        assert_eq!(violation.line, 2);
        assert!(violation.message.contains("delimiter row"));
        assert!(violation.message.contains("missing 1 cells"));
    }

    #[test]
    fn test_multiple_violations() {
        let content = r#"| Header | Header |
| ------ | ------ |
| Cell   |
| Cell   | Cell   | Cell   |
"#;

        let violations = assert_violation_count(MD056::new(), content, 2);

        assert_eq!(violations[0].line, 3);
        assert!(violations[0].message.contains("missing 1 cells"));

        assert_eq!(violations[1].line, 4);
        assert!(violations[1].message.contains("extra 1 cells"));
    }

    #[test]
    fn test_single_column_table() {
        let content = r#"| Header |
| ------ |
| Cell   |
| Cell   |
"#;

        assert_no_violations(MD056::new(), content);
    }

    #[test]
    fn test_empty_table() {
        let content = r#"| |
|---|
| |
"#;

        assert_no_violations(MD056::new(), content);
    }

    #[test]
    fn test_multiple_tables() {
        let content = r#"| Table 1 | Header |
| ------- | ------ |
| Cell    | Cell   |

| Table 2 | Header |
| ------- | ------ |
| Cell    |
"#;

        let violation = assert_single_violation(MD056::new(), content);
        assert_eq!(violation.line, 7);
        assert!(violation.message.contains("missing 1 cells"));
    }

    #[test]
    fn test_fallback_multiple_tables() {
        let content = r#"| Table 1 | Header |
| ------- | ------ |
| Cell    | Cell   |

| Table 2 | Header |
| ------- | ------ |
| Cell    |
"#;

        // Test fallback implementation specifically
        use std::path::PathBuf;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD056::new();
        let violations = rule.check_tables_fallback(&document);

        assert_eq!(violations.len(), 1);
        let violations = assert_violation_count(rule, content, 1);
        assert_eq!(violations[0].line, 7);
        assert!(violations[0].message.contains("missing 1 cells"));
    }

    #[test]
    fn test_fallback_method() {
        // Test when no AST is available
        let content = r#"| Header | Header |
| ------ | ------ |
| Cell   | Cell   |
| Cell   |
"#;

        let rule = MD056::new();
        let violations = rule.check_tables_fallback(&crate::test_helpers::create_document(content));
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 4);
        assert!(violations[0].message.contains("missing 1 cells"));
    }

    #[test]
    fn test_edge_case_empty_rows() {
        let content = r#"| Header | Header |
| ------ | ------ |
|        |        |
|        |
"#;

        let violation = assert_single_violation(MD056::new(), content);
        assert_eq!(violation.line, 4);
        assert!(violation.message.contains("missing 1 cells"));
    }

    #[test]
    fn test_table_with_varying_column_counts() {
        let content = r#"| A | B | C |
| - | - | - |
| 1 | 2 |
| 4 | 5 | 6 | 7 |
| 8 | 9 | 10 |
"#;

        let violations = assert_violation_count(MD056::new(), content, 2);
        assert_eq!(violations[0].line, 3);
        assert!(violations[0].message.contains("missing 1 cells"));
        assert_eq!(violations[1].line, 4);
        assert!(violations[1].message.contains("extra 1 cells"));
    }

    #[test]
    fn test_complex_table_structure() {
        let content = r#"| Column 1 | Column 2 | Column 3 | Column 4 |
| -------- | -------- | -------- | -------- |
| Data     | Data     | Data     | Data     |
| Data     | Data     |          |          |
| Data     |          |          |          |
| Data     | Data     | Data     |          |
"#;

        assert_no_violations(MD056::new(), content);
    }

    #[test]
    fn test_table_with_pipes_in_content() {
        let content = r#"| Code | Description |
| ---- | ----------- |
| `a`  | Pipe char   |
| `b`  | With pipe   |
"#;

        assert_no_violations(MD056::new(), content);
    }

    #[test]
    fn test_malformed_table_structure() {
        let content = r#"| Header | Header |
| Cell   | Cell   |
| ------ | ------ |
| Cell   | Cell   |
"#;

        // This tests the fallback parsing with malformed structure
        assert_no_violations(MD056::new(), content);
    }

    #[test]
    fn test_table_cell_count_edge_cases() {
        let content = r#"| A |
| - |
|   |
| B |
"#;

        assert_no_violations(MD056::new(), content);
    }

    #[test]
    fn test_delimiter_row_variations() {
        let content = r#"| Header1 | Header2 | Header3 |
|---------|---------|
| Cell    | Cell    | Cell    |
"#;

        let violation = assert_single_violation(MD056::new(), content);
        assert_eq!(violation.line, 2);
        assert!(violation.message.contains("missing 1 cells"));
    }

    #[test]
    fn test_no_tables_in_document() {
        let content = r#"# Heading

This is just text with no tables.

Some more text here.
"#;

        assert_no_violations(MD056::new(), content);
    }

    #[test]
    fn test_table_within_other_content() {
        let content = r#"# Document Title

Some introductory text.

| Name | Age | City |
| ---- | --- | ---- |
| John | 30  |      |

More text after the table.
"#;

        assert_no_violations(MD056::new(), content);
    }

    #[test]
    fn test_multiple_delimiter_issues() {
        let content = r#"| A | B | C |
| - | - |
| 1 | 2 | 3 |
| 4 | 5 |
"#;

        let violations = assert_violation_count(MD056::new(), content, 2);
        assert_eq!(violations[0].line, 2);
        assert!(violations[0].message.contains("missing 1 cells"));
        assert_eq!(violations[1].line, 4);
        assert!(violations[1].message.contains("missing 1 cells"));
    }

    #[test]
    fn test_large_table_consistency() {
        let content = r#"| C1 | C2 | C3 | C4 | C5 |
| -- | -- | -- | -- | -- |
| D1 | D2 | D3 | D4 | D5 |
| D1 | D2 | D3 | D4 | D5 |
| D1 | D2 | D3 | D4 |    |
| D1 | D2 | D3 | D4 | D5 |
"#;

        assert_no_violations(MD056::new(), content);
    }

    #[test]
    fn test_table_row_parsing_edge_cases() {
        let content = r#"| Header |
|--------|
| Cell   |
|        |
"#;

        assert_no_violations(MD056::new(), content);
    }

    #[test]
    fn test_ast_not_available_error_path() {
        let content = r#"| Header | Header |
| ------ | ------ |
| Cell   |
"#;

        let rule = MD056::new();
        // Test with AST explicitly set to None to trigger fallback
        let violations = rule
            .check_with_ast(&crate::test_helpers::create_document(content), None)
            .unwrap();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("missing 1 cells"));
    }

    #[test]
    fn test_complex_table_scenarios() {
        // Test basic table functionality - use consistent column count
        let content = r#"| Code | Description |
| ---- | ----------- |
| abc  | Pipe char |
| def  | Another value |
"#;

        assert_no_violations(MD056::new(), content);
    }

    #[test]
    fn test_malformed_table_detection() {
        // Test tables without proper delimiters
        let content = r#"Not a table line
| Header | Header |
Not a table line
| Cell   |
"#;

        let violation = assert_single_violation(MD056::new(), content);
        assert!(violation.message.contains("missing 1 cells"));
    }

    #[test]
    fn test_header_row_edge_cases() {
        // Test when header row has wrong column count
        let content = r#"| Too | Many | Headers | Here |
| --- | --- |
| One | Two |
"#;

        let violations = assert_violation_count(MD056::new(), content, 2);
        assert_eq!(violations[0].line, 2);
        assert!(violations[0].message.contains("delimiter row"));
    }

    #[test]
    fn test_count_cells_functionality() {
        // Test internal cell counting logic with various scenarios
        let rule = MD056::new();

        // Test different pipe configurations
        let scenarios = vec![
            ("| A |", 1),
            ("| A | B |", 2),
            ("| A | B | C |", 3),
            ("|A|B|", 2),
            ("| | |", 2),
        ];

        // Since count_cells is private, we test through behavior
        for (line, expected_count) in scenarios {
            let content = format!(
                "{}\n|---|\n{}",
                "| Header |"
                    .repeat(expected_count)
                    .replace(" |", " | ")
                    .trim_end(),
                line
            );

            if line.matches('|').count() - 1 != expected_count {
                // Should produce violation
                let violations = rule
                    .check(&crate::test_helpers::create_document(&content))
                    .unwrap();
                assert!(
                    !violations.is_empty(),
                    "Expected violation for line: {line}"
                );
            }
        }
    }

    #[test]
    fn test_table_row_detection_edge_cases() {
        // Test is_table_row logic with various edge cases
        let content = r#"| Valid | Table | Row |
| ----- | ----- | --- |
Not a table row
| Valid | Row |
|Invalid|
||
|   |   |   |
"#;

        let rule = MD056::new();
        let violations = rule
            .check(&crate::test_helpers::create_document(content))
            .unwrap();
        // Should find violations for rows with wrong column counts
        assert!(!violations.is_empty());
    }

    #[test]
    fn test_fallback_table_detection() {
        // Test the fallback parsing when AST is not available
        let rule = MD056::new();

        // Test table end detection on blank line
        let content = r#"| Header | Header |
| ------ | ------ |
| Cell   | Cell   |

Not a table anymore
| Header |
| ------ |
| Cell   |
"#;

        let violations = rule.check_tables_fallback(&crate::test_helpers::create_document(content));
        // Test passes if parsing completes without panic
        let _ = violations;
    }

    #[test]
    fn test_table_state_transitions() {
        // Test in_table state transitions in fallback method
        let rule = MD056::new();

        let content = r#"Regular text
| Start | Table |
| ----- | ----- |
| Row   |

Back to regular text
| Another | Table |
| ------- | ----- |
| Cell    | Cell  |
"#;

        let violations = rule.check_tables_fallback(&crate::test_helpers::create_document(content));
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("missing 1 cells"));
    }

    #[test]
    fn test_row_type_messages() {
        // Test different row type error messages - simplified to avoid multiple violations
        let content = r#"| Header | Header |
| ------ | ------ |
| Cell   |"#;

        let violation = assert_single_violation(MD056::new(), content);
        assert!(violation.message.contains("data row"));
        assert!(violation.message.contains("missing"));
    }

    #[test]
    fn test_pipe_counting_edge_cases() {
        // Test pipe counting with different scenarios
        let rule = MD056::new();

        // Test edge case where line has pipes but isn't a table
        let content = r#"This line has | pipes but isn't a table
| Header | Header |
| ------ | ------ |
| Cell   | Cell   |
"#;

        assert_no_violations(rule, content);
    }

    #[test]
    fn test_expected_column_calculation() {
        // Test how expected column count is determined
        let scenarios = vec![
            // Different header configurations
            (
                r#"| A |
| - |
| 1 | 2 |"#,
                1,
            ),
            (
                r#"| A | B | C |
| - | - | - |
| 1 | 2 |"#,
                1,
            ),
        ];

        for (content, expected_violations) in scenarios {
            let violations = assert_violation_count(MD056::new(), content, expected_violations);
            assert!(!violations.is_empty());
        }
    }
}