Skip to main content

rumdl_lib/rules/
md029_ordered_list_prefix.rs

1/// Rule MD029: Ordered list item prefix
2///
3/// See [docs/md029.md](../../docs/md029.md) for full documentation, configuration, and examples.
4use crate::lint_context::ParsedListItem;
5use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
6use crate::utils::range_utils::byte_to_char_count;
7use crate::utils::regex_cache::ORDERED_LIST_MARKER_REGEX;
8use std::collections::HashMap;
9use toml;
10
11mod md029_config;
12pub use md029_config::ListStyle;
13pub(super) use md029_config::MD029Config;
14
15#[derive(Debug, Clone, Default)]
16pub struct MD029OrderedListPrefix {
17    config: MD029Config,
18}
19
20impl MD029OrderedListPrefix {
21    pub fn new(style: ListStyle) -> Self {
22        Self {
23            config: MD029Config { style },
24        }
25    }
26
27    pub fn from_config_struct(config: MD029Config) -> Self {
28        Self { config }
29    }
30
31    #[inline]
32    fn parse_marker_number(marker: &str) -> Option<usize> {
33        // Handle marker format like "1." or "1"
34        let num_part = if let Some(stripped) = marker.strip_suffix('.') {
35            stripped
36        } else {
37            marker
38        };
39        num_part.parse::<usize>().ok()
40    }
41
42    /// Calculate the expected number for a list item.
43    /// The `start_value` is the CommonMark-provided start value for the list.
44    /// For style `Ordered`, items should be `start_value, start_value+1, start_value+2, ...`
45    #[inline]
46    fn get_expected_number(&self, index: usize, detected_style: Option<ListStyle>, start_value: u64) -> usize {
47        // Use detected_style when the configuration is auto-detect mode (OneOrOrdered or Consistent)
48        // For explicit style configurations, always use the configured style
49        let style = match self.config.style {
50            ListStyle::OneOrOrdered | ListStyle::Consistent => detected_style.unwrap_or(ListStyle::OneOne),
51            _ => self.config.style,
52        };
53
54        match style {
55            ListStyle::One | ListStyle::OneOne => 1,
56            ListStyle::Ordered => (start_value as usize) + index,
57            ListStyle::Ordered0 => index,
58            ListStyle::OneOrOrdered | ListStyle::Consistent => {
59                // This shouldn't be reached since we handle these above
60                1
61            }
62        }
63    }
64
65    /// Detect the style being used in a list by checking all items for prevalence.
66    /// The `start_value` parameter is the CommonMark-provided list start value.
67    fn detect_list_style(items: &[ParsedListItem<'_>], start_value: u64) -> ListStyle {
68        if items.len() < 2 {
69            // With only one item, check if it matches the start value
70            // If so, treat as Ordered (respects CommonMark start value)
71            // Otherwise, check if it's 1 (OneOne style)
72            let first_num = Self::parse_marker_number(items[0].marker());
73            if first_num == Some(start_value as usize) {
74                return ListStyle::Ordered;
75            }
76            return ListStyle::OneOne;
77        }
78
79        let first_num = Self::parse_marker_number(items[0].marker());
80        let second_num = Self::parse_marker_number(items[1].marker());
81
82        // Fast path: Check for Ordered0 special case (starts with 0, 1)
83        if matches!((first_num, second_num), (Some(0), Some(1))) {
84            return ListStyle::Ordered0;
85        }
86
87        // Fast path: If first 2 items aren't both "1", it must be Ordered (O(1))
88        // This handles ~95% of lists instantly: "1. 2. 3...", "2. 3. 4...", etc.
89        if first_num != Some(1) || second_num != Some(1) {
90            return ListStyle::Ordered;
91        }
92
93        // Slow path: Both first items are "1", check if ALL are "1" (O(n))
94        // This is necessary for lists like "1. 1. 1..." vs "1. 1. 2. 3..."
95        let all_ones = items
96            .iter()
97            .all(|item| Self::parse_marker_number(item.marker()) == Some(1));
98
99        if all_ones {
100            ListStyle::OneOne
101        } else {
102            ListStyle::Ordered
103        }
104    }
105
106    /// Check a CommonMark-grouped list for correct ordering.
107    /// Uses the CommonMark start value to validate items (e.g., a list starting at 11
108    /// expects items 11, 12, 13... - no violation there).
109    fn check_commonmark_list_group(
110        &self,
111        ctx: &crate::lint_context::LintContext,
112        group: &[ParsedListItem<'_>],
113        warnings: &mut Vec<LintWarning>,
114        document_wide_style: Option<ListStyle>,
115        start_value: u64,
116    ) {
117        if group.is_empty() {
118            return;
119        }
120
121        // Group items by indentation level (marker_column) to handle nested lists
122        type LevelGroups<'a> = HashMap<usize, Vec<ParsedListItem<'a>>>;
123        let mut level_groups: LevelGroups = HashMap::new();
124
125        for &list_item in group {
126            level_groups
127                .entry(list_item.marker_column())
128                .or_default()
129                .push(list_item);
130        }
131
132        // Process each indentation level in sorted order for deterministic output
133        let mut sorted_levels: Vec<_> = level_groups.into_iter().collect();
134        sorted_levels.sort_by_key(|(indent, _)| *indent);
135
136        for (_indent, mut items) in sorted_levels {
137            // Sort by line number
138            items.sort_by_key(|item| item.line_num());
139
140            if items.is_empty() {
141                continue;
142            }
143
144            // Determine style for this group
145            let detected_style = if let Some(doc_style) = document_wide_style {
146                Some(doc_style)
147            } else if self.config.style == ListStyle::OneOrOrdered {
148                Some(Self::detect_list_style(&items, start_value))
149            } else {
150                None
151            };
152
153            // Check each item using the CommonMark start value
154            for (idx, list_item) in items.iter().copied().enumerate() {
155                if let Some(actual_num) = Self::parse_marker_number(list_item.marker()) {
156                    let expected_num = self.get_expected_number(idx, detected_style, start_value);
157
158                    if actual_num != expected_num {
159                        let line_num = list_item.line_num();
160                        let line_info = list_item.line_info();
161                        let marker_start = list_item.marker_byte_offset();
162                        let number_len = if let Some(dot_pos) = list_item.marker().find('.') {
163                            dot_pos
164                        } else if let Some(paren_pos) = list_item.marker().find(')') {
165                            paren_pos
166                        } else {
167                            list_item.marker().len()
168                        };
169
170                        let style_name = match detected_style.as_ref().unwrap_or(&ListStyle::Ordered) {
171                            ListStyle::OneOne => "one",
172                            ListStyle::Ordered => "ordered",
173                            ListStyle::Ordered0 => "ordered0",
174                            _ => "ordered",
175                        };
176
177                        let style_context = match self.config.style {
178                            ListStyle::Consistent => format!("document style '{style_name}'"),
179                            ListStyle::OneOrOrdered => format!("list style '{style_name}'"),
180                            ListStyle::One | ListStyle::OneOne => "configured style 'one'".to_string(),
181                            ListStyle::Ordered => "configured style 'ordered'".to_string(),
182                            ListStyle::Ordered0 => "configured style 'ordered0'".to_string(),
183                        };
184
185                        // Only provide auto-fix when:
186                        // 1. The list starts at 1 (default numbering), OR
187                        // 2. We're using explicit 'one' style (numbers are meaningless)
188                        // When start_value > 1, the user explicitly chose that number,
189                        // so auto-fixing would destroy their intent.
190                        let should_provide_fix =
191                            start_value == 1 || matches!(self.config.style, ListStyle::One | ListStyle::OneOne);
192
193                        // marker_column is a byte offset within the line; convert to a
194                        // character column for the diagnostic.
195                        let line_text = line_info.content(ctx.content);
196
197                        warnings.push(LintWarning {
198                            rule_name: Some(self.name().to_string()),
199                            message: format!(
200                                "Ordered list item number {actual_num} does not match {style_context} (expected {expected_num})"
201                            ),
202                            line: line_num,
203                            column: byte_to_char_count(line_text, list_item.marker_column()),
204                            end_line: line_num,
205                            end_column: byte_to_char_count(line_text, list_item.marker_column() + number_len),
206                            severity: Severity::Warning,
207                            fix: if should_provide_fix {
208                                Some(Fix::new(marker_start..marker_start + number_len, expected_num.to_string()))
209                            } else {
210                                None
211                            },
212                        });
213                    }
214                }
215            }
216        }
217    }
218}
219
220impl Rule for MD029OrderedListPrefix {
221    fn name(&self) -> &'static str {
222        "MD029"
223    }
224
225    fn description(&self) -> &'static str {
226        "Ordered list marker value"
227    }
228
229    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
230        // Early returns for performance
231        if ctx.content.is_empty() {
232            return Ok(Vec::new());
233        }
234
235        // Quick check for any ordered list markers before processing
236        if (!ctx.content.contains('.') && !ctx.content.contains(')'))
237            || !ctx.content.lines().any(|line| ORDERED_LIST_MARKER_REGEX.is_match(line))
238        {
239            return Ok(Vec::new());
240        }
241
242        let mut warnings = Vec::new();
243
244        // Use pulldown-cmark's AST for authoritative list membership and start values.
245        // This respects CommonMark's list start values (e.g., a list starting at 11
246        // expects items 11, 12, 13... - no violation there).
247        let list_groups = ctx.commonmark_ordered_lists();
248
249        if list_groups.is_empty() {
250            return Ok(Vec::new());
251        }
252
253        // For Consistent style, detect document-wide prevalent style
254        let document_wide_style = if self.config.style == ListStyle::Consistent {
255            // Collect ALL ordered items from ALL groups
256            let mut all_document_items = Vec::new();
257            for list in list_groups {
258                all_document_items.extend(list.items());
259            }
260            // Detect style across entire document (use 1 as default for pattern detection)
261            if !all_document_items.is_empty() {
262                Some(Self::detect_list_style(&all_document_items, 1))
263            } else {
264                None
265            }
266        } else {
267            None
268        };
269
270        // Process each CommonMark-defined list group with its start value
271        for list in list_groups {
272            let items: Vec<_> = list.items().collect();
273            self.check_commonmark_list_group(ctx, &items, &mut warnings, document_wide_style, list.start_value());
274        }
275
276        // Sort warnings by line number for deterministic output
277        warnings.sort_by_key(|w| (w.line, w.column));
278
279        Ok(warnings)
280    }
281
282    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
283        // Note: do not call self.should_skip() here — MD029's should_skip only covers
284        // unordered list markers (*, -, +), not ordered list markers (digits + . or )).
285        // check() has its own fast-path early-return for documents without ordered markers.
286        let warnings = self.check(ctx)?;
287        if warnings.is_empty() {
288            return Ok(ctx.content.to_string());
289        }
290        let warnings =
291            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
292        crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings).map_err(LintError::InvalidInput)
293    }
294
295    /// Get the category of this rule for selective processing
296    fn category(&self) -> RuleCategory {
297        RuleCategory::List
298    }
299
300    /// Check if this rule should be skipped
301    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
302        ctx.content.is_empty() || !ctx.likely_has_lists()
303    }
304
305    fn as_any(&self) -> &dyn std::any::Any {
306        self
307    }
308
309    crate::impl_rule_config_methods!(MD029Config);
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    #[test]
317    fn test_basic_functionality() {
318        // Test with default style (ordered)
319        let rule = MD029OrderedListPrefix::default();
320
321        // Test with correctly ordered list
322        let content = "1. First item\n2. Second item\n3. Third item";
323        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
324        let result = rule.check(&ctx).unwrap();
325        assert!(result.is_empty());
326
327        // Test with incorrectly ordered list
328        let content = "1. First item\n3. Third item\n5. Fifth item";
329        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
330        let result = rule.check(&ctx).unwrap();
331        assert_eq!(result.len(), 2); // Should have warnings for items 3 and 5
332
333        // Test with one-one style
334        let rule = MD029OrderedListPrefix::new(ListStyle::OneOne);
335        let content = "1. First item\n2. Second item\n3. Third item";
336        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
337        let result = rule.check(&ctx).unwrap();
338        assert_eq!(result.len(), 2); // Should have warnings for items 2 and 3
339
340        // Test with ordered0 style
341        let rule = MD029OrderedListPrefix::new(ListStyle::Ordered0);
342        let content = "0. First item\n1. Second item\n2. Third item";
343        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
344        let result = rule.check(&ctx).unwrap();
345        assert!(result.is_empty());
346    }
347
348    #[test]
349    fn test_redundant_computation_fix() {
350        // This test confirms that the redundant computation bug is fixed
351        // Previously: get_list_number() was called twice (once for is_some(), once for unwrap())
352        // Now: get_list_number() is called once with if let pattern
353
354        let rule = MD029OrderedListPrefix::default();
355
356        // Test with mixed valid and edge case content
357        let content = "1. First item\n3. Wrong number\n2. Another wrong number";
358        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
359
360        // This should not panic and should produce warnings for incorrect numbering
361        let result = rule.check(&ctx).unwrap();
362        assert_eq!(result.len(), 2); // Should have warnings for items 3 and 2
363
364        // Verify the warnings have correct content
365        assert!(result[0].message.contains('3') && result[0].message.contains("expected 2"));
366        assert!(result[1].message.contains('2') && result[1].message.contains("expected 3"));
367    }
368
369    #[test]
370    fn test_performance_improvement() {
371        // This test verifies the rule handles large lists without performance issues
372        let rule = MD029OrderedListPrefix::default();
373
374        // Create a larger list with WRONG numbers: 1, 5, 10, 15, ...
375        // Starting at 1, CommonMark expects 1, 2, 3, 4, ...
376        // So items 2-100 are all wrong (expected 2, got 5; expected 3, got 10; etc.)
377        let mut content = String::from("1. Item 1\n"); // First item correct
378        for i in 2..=100 {
379            content.push_str(&format!("{}. Item {}\n", i * 5 - 5, i)); // Wrong numbers
380        }
381
382        let ctx = crate::lint_context::LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
383
384        // This should complete without issues and produce warnings for items 2-100
385        let result = rule.check(&ctx).unwrap();
386        assert_eq!(result.len(), 99, "Should have warnings for items 2-100 (99 items)");
387
388        // First wrong item: "5. Item 2" (expected 2)
389        assert!(result[0].message.contains('5') && result[0].message.contains("expected 2"));
390    }
391
392    #[test]
393    fn test_one_or_ordered_with_all_ones() {
394        // Test OneOrOrdered style with all 1s (should pass)
395        let rule = MD029OrderedListPrefix::new(ListStyle::OneOrOrdered);
396
397        let content = "1. First item\n1. Second item\n1. Third item";
398        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
399        let result = rule.check(&ctx).unwrap();
400        assert!(result.is_empty(), "All ones should be valid in OneOrOrdered mode");
401    }
402
403    #[test]
404    fn test_one_or_ordered_with_sequential() {
405        // Test OneOrOrdered style with sequential numbering (should pass)
406        let rule = MD029OrderedListPrefix::new(ListStyle::OneOrOrdered);
407
408        let content = "1. First item\n2. Second item\n3. Third item";
409        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
410        let result = rule.check(&ctx).unwrap();
411        assert!(
412            result.is_empty(),
413            "Sequential numbering should be valid in OneOrOrdered mode"
414        );
415    }
416
417    #[test]
418    fn test_one_or_ordered_with_mixed_style() {
419        // Test OneOrOrdered style with mixed numbering (should fail)
420        let rule = MD029OrderedListPrefix::new(ListStyle::OneOrOrdered);
421
422        let content = "1. First item\n2. Second item\n1. Third item";
423        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
424        let result = rule.check(&ctx).unwrap();
425        assert_eq!(result.len(), 1, "Mixed style should produce one warning");
426        assert!(result[0].message.contains('1') && result[0].message.contains("expected 3"));
427    }
428
429    #[test]
430    fn test_one_or_ordered_separate_lists() {
431        // Test OneOrOrdered with separate lists using different styles (should pass)
432        let rule = MD029OrderedListPrefix::new(ListStyle::OneOrOrdered);
433
434        let content = "# First list\n\n1. Item A\n1. Item B\n\n# Second list\n\n1. Item X\n2. Item Y\n3. Item Z";
435        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
436        let result = rule.check(&ctx).unwrap();
437        assert!(
438            result.is_empty(),
439            "Separate lists can use different styles in OneOrOrdered mode"
440        );
441    }
442
443    /// Core invariant: for every warning with a Fix, the replacement text must
444    /// match what fix() produces for the same byte range in the output.
445    #[test]
446    fn test_check_and_fix_produce_identical_replacements() {
447        let rule = MD029OrderedListPrefix::default();
448
449        let inputs = [
450            "1. First\n3. Skip\n5. Skip\n",
451            "1. First\n3. Third\n2. Second\n",
452            "1. A\n\n3. B\n",
453            "- Unordered\n\n1. A\n3. B\n",
454            "1. A\n   1. Nested wrong\n   3. Nested\n2. B\n",
455        ];
456
457        for input in &inputs {
458            let ctx = crate::lint_context::LintContext::new(input, crate::config::MarkdownFlavor::Standard, None);
459            let warnings = rule.check(&ctx).unwrap();
460            let fixed = rule.fix(&ctx).unwrap();
461
462            // fix() must be idempotent: applying it again produces the same output
463            let ctx2 = crate::lint_context::LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
464            let fixed_twice = rule.fix(&ctx2).unwrap();
465            assert_eq!(
466                fixed, fixed_twice,
467                "fix() is not idempotent for input: {input:?}\nfirst:  {fixed:?}\nsecond: {fixed_twice:?}"
468            );
469
470            // After fixing, check() should produce no warnings
471            let warnings_after = rule.check(&ctx2).unwrap();
472            assert!(
473                warnings_after.is_empty(),
474                "check() should produce no warnings after fix() for input: {input:?}\nfixed: {fixed:?}\nremaining: {warnings_after:?}"
475            );
476
477            // For every warning with a Fix, applying the fix alone should match
478            // the content at the same range in the final fixed output
479            for warning in &warnings {
480                if let Some(ref fix) = warning.fix {
481                    assert!(
482                        fix.range.end <= input.len(),
483                        "Fix range exceeds input length for {input:?}"
484                    );
485                }
486            }
487        }
488    }
489
490    /// fix(fix(x)) == fix(x)
491    #[test]
492    fn test_fix_idempotent() {
493        let rule = MD029OrderedListPrefix::default();
494
495        let inputs = [
496            "1. A\n3. B\n5. C\n",
497            "# Intro\n\n1. First\n3. Third\n",
498            "1. A\n1. B\n1. C\n",
499        ];
500
501        for input in &inputs {
502            let ctx1 = crate::lint_context::LintContext::new(input, crate::config::MarkdownFlavor::Standard, None);
503            let fixed_once = rule.fix(&ctx1).unwrap();
504            let ctx2 =
505                crate::lint_context::LintContext::new(&fixed_once, crate::config::MarkdownFlavor::Standard, None);
506            let fixed_twice = rule.fix(&ctx2).unwrap();
507            assert_eq!(fixed_once, fixed_twice, "fix() is not idempotent for input: {input:?}");
508        }
509    }
510
511    /// Example list markers `(@)` and `(@label)` must not be reported under
512    /// the Pandoc flavor — they are not ordered list items.
513    #[test]
514    fn test_pandoc_skips_example_list_markers() {
515        use crate::config::MarkdownFlavor;
516        use crate::lint_context::LintContext;
517        let rule = MD029OrderedListPrefix::default();
518        let content = "(@) First.\n(@good) Second.\n(@) Third.\n";
519        let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
520        let result = rule.check(&ctx).unwrap();
521        assert!(
522            result.is_empty(),
523            "MD029 should not flag (@)/(@label) example markers under Pandoc: {result:?}"
524        );
525    }
526
527    /// A real ordered list interleaved with example markers should validate
528    /// only the digit-prefixed items, ignoring the example markers.
529    #[test]
530    fn test_pandoc_example_markers_do_not_break_real_ordered_list() {
531        use crate::config::MarkdownFlavor;
532        use crate::lint_context::LintContext;
533        let rule = MD029OrderedListPrefix::default();
534        let content = "1. Real first.\n\n(@) Example.\n\n2. Real second.\n";
535        let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
536        let result = rule.check(&ctx).unwrap();
537        assert!(
538            result.is_empty(),
539            "MD029 should validate the digit-prefixed sequence and skip the example marker: {result:?}"
540        );
541    }
542
543    /// Lists with explicit non-1 start values should not be auto-fixed
544    /// (to preserve user intent).
545    #[test]
546    fn test_fix_preserves_non_default_start_value() {
547        let rule = MD029OrderedListPrefix::default();
548
549        // List starts at 11 — CommonMark expects 11, 12, 13... Item "14" is wrong
550        // but user explicitly chose 11 so no auto-fix should be offered.
551        let content = "11. First\n14. Fourth\n";
552        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
553        let warnings = rule.check(&ctx).unwrap();
554        // Warning present but no fix
555        assert!(!warnings.is_empty(), "Should produce warnings for misnumbered list");
556        assert!(
557            warnings.iter().all(|w| w.fix.is_none()),
558            "Should not provide auto-fix for lists starting at non-1 values"
559        );
560        // fix() should leave content unchanged
561        let fixed = rule.fix(&ctx).unwrap();
562        assert_eq!(
563            fixed, content,
564            "Content should be unchanged when no fixes are available"
565        );
566    }
567
568    #[test]
569    fn test_md029_front_matter() {
570        let rule = MD029OrderedListPrefix::default();
571        let content = "---\n1. key: value\n3. key2: value2\n---\n1. Item 1\n2. Item 2\n";
572        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
573        let result = rule.check(&ctx).unwrap();
574        assert!(
575            result.is_empty(),
576            "Should not flag list-like items in front-matter: {result:?}"
577        );
578    }
579}