rumdl_lib/
lib.rs

1pub mod config;
2pub mod exit_codes;
3pub mod filtered_lines;
4pub mod fix_coordinator;
5pub mod inline_config;
6pub mod lint_context;
7pub mod lsp;
8pub mod markdownlint_config;
9pub mod output;
10pub mod parallel;
11pub mod performance;
12pub mod profiling;
13pub mod rule;
14pub mod vscode;
15#[macro_use]
16pub mod rule_config;
17#[macro_use]
18pub mod rule_config_serde;
19pub mod rules;
20pub mod utils;
21
22pub use rules::heading_utils::{Heading, HeadingStyle};
23pub use rules::*;
24
25pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
26use crate::rule::{LintResult, Rule, RuleCategory};
27use std::time::Instant;
28
29/// Content characteristics for efficient rule filtering
30#[derive(Debug, Default)]
31struct ContentCharacteristics {
32    has_headings: bool,    // # or setext headings
33    has_lists: bool,       // *, -, +, 1. etc
34    has_links: bool,       // [text](url) or [text][ref]
35    has_code: bool,        // ``` or ~~~ or indented code
36    has_emphasis: bool,    // * or _ for emphasis
37    has_html: bool,        // < > tags
38    has_tables: bool,      // | pipes
39    has_blockquotes: bool, // > markers
40    has_images: bool,      // ![alt](url)
41}
42
43impl ContentCharacteristics {
44    fn analyze(content: &str) -> Self {
45        let mut chars = Self { ..Default::default() };
46
47        // Quick single-pass analysis
48        let mut has_atx_heading = false;
49        let mut has_setext_heading = false;
50
51        for line in content.lines() {
52            let trimmed = line.trim();
53
54            // Headings: ATX (#) or Setext (underlines)
55            if !has_atx_heading && trimmed.starts_with('#') {
56                has_atx_heading = true;
57            }
58            if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
59                has_setext_heading = true;
60            }
61
62            // Quick character-based detection (more efficient than regex)
63            if !chars.has_lists && (line.contains("* ") || line.contains("- ") || line.contains("+ ")) {
64                chars.has_lists = true;
65            }
66            if !chars.has_lists && line.chars().next().is_some_and(|c| c.is_ascii_digit()) && line.contains(". ") {
67                chars.has_lists = true;
68            }
69            if !chars.has_links
70                && (line.contains('[')
71                    || line.contains("http://")
72                    || line.contains("https://")
73                    || line.contains("ftp://"))
74            {
75                chars.has_links = true;
76            }
77            if !chars.has_images && line.contains("![") {
78                chars.has_images = true;
79            }
80            if !chars.has_code && (line.contains('`') || line.contains("~~~")) {
81                chars.has_code = true;
82            }
83            if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
84                chars.has_emphasis = true;
85            }
86            if !chars.has_html && line.contains('<') {
87                chars.has_html = true;
88            }
89            if !chars.has_tables && line.contains('|') {
90                chars.has_tables = true;
91            }
92            if !chars.has_blockquotes && line.starts_with('>') {
93                chars.has_blockquotes = true;
94            }
95        }
96
97        chars.has_headings = has_atx_heading || has_setext_heading;
98        chars
99    }
100
101    /// Check if a rule should be skipped based on content characteristics
102    fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
103        match rule.category() {
104            RuleCategory::Heading => !self.has_headings,
105            RuleCategory::List => !self.has_lists,
106            RuleCategory::Link => !self.has_links && !self.has_images,
107            RuleCategory::Image => !self.has_images,
108            RuleCategory::CodeBlock => !self.has_code,
109            RuleCategory::Html => !self.has_html,
110            RuleCategory::Emphasis => !self.has_emphasis,
111            RuleCategory::Blockquote => !self.has_blockquotes,
112            RuleCategory::Table => !self.has_tables,
113            // Always check these categories as they apply to all content
114            RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
115        }
116    }
117}
118
119/// Lint a file against the given rules with intelligent rule filtering
120/// Assumes the provided `rules` vector contains the final,
121/// configured, and filtered set of rules to be executed.
122pub fn lint(
123    content: &str,
124    rules: &[Box<dyn Rule>],
125    _verbose: bool,
126    flavor: crate::config::MarkdownFlavor,
127) -> LintResult {
128    let mut warnings = Vec::new();
129    let _overall_start = Instant::now();
130
131    // Early return for empty content
132    if content.is_empty() {
133        return Ok(warnings);
134    }
135
136    // Parse inline configuration comments once
137    let inline_config = crate::inline_config::InlineConfig::from_content(content);
138
139    // Analyze content characteristics for rule filtering
140    let characteristics = ContentCharacteristics::analyze(content);
141
142    // Filter rules based on content characteristics
143    let applicable_rules: Vec<_> = rules
144        .iter()
145        .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
146        .collect();
147
148    // Calculate skipped rules count before consuming applicable_rules
149    let _total_rules = rules.len();
150    let _applicable_count = applicable_rules.len();
151
152    // Parse LintContext once with the provided flavor
153    let lint_ctx = crate::lint_context::LintContext::new(content, flavor);
154
155    let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
156
157    for rule in applicable_rules {
158        let _rule_start = Instant::now();
159
160        let result = rule.check(&lint_ctx);
161
162        match result {
163            Ok(rule_warnings) => {
164                // Filter out warnings for rules disabled via inline comments
165                let filtered_warnings: Vec<_> = rule_warnings
166                    .into_iter()
167                    .filter(|warning| {
168                        // Use the warning's rule_name if available, otherwise use the rule's name
169                        let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
170
171                        // Extract the base rule name for sub-rules like "MD029-style" -> "MD029"
172                        let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
173                            &rule_name_to_check[..dash_pos]
174                        } else {
175                            rule_name_to_check
176                        };
177
178                        !inline_config.is_rule_disabled(
179                            base_rule_name,
180                            warning.line, // Already 1-indexed
181                        )
182                    })
183                    .collect();
184                warnings.extend(filtered_warnings);
185            }
186            Err(e) => {
187                log::error!("Error checking rule {}: {}", rule.name(), e);
188                return Err(e);
189            }
190        }
191
192        let rule_duration = _rule_start.elapsed();
193        if profile_rules {
194            eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
195        }
196
197        #[cfg(not(test))]
198        if _verbose && rule_duration.as_millis() > 500 {
199            log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
200        }
201    }
202
203    #[cfg(not(test))]
204    if _verbose {
205        let skipped_rules = _total_rules - _applicable_count;
206        if skipped_rules > 0 {
207            log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
208        }
209    }
210
211    Ok(warnings)
212}
213
214/// Get the profiling report
215pub fn get_profiling_report() -> String {
216    profiling::get_report()
217}
218
219/// Reset the profiling data
220pub fn reset_profiling() {
221    profiling::reset()
222}
223
224/// Get regex cache statistics for performance monitoring
225pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
226    crate::utils::regex_cache::get_cache_stats()
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232    use crate::rule::Rule;
233    use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
234
235    #[test]
236    fn test_content_characteristics_analyze() {
237        // Test empty content
238        let chars = ContentCharacteristics::analyze("");
239        assert!(!chars.has_headings);
240        assert!(!chars.has_lists);
241        assert!(!chars.has_links);
242        assert!(!chars.has_code);
243        assert!(!chars.has_emphasis);
244        assert!(!chars.has_html);
245        assert!(!chars.has_tables);
246        assert!(!chars.has_blockquotes);
247        assert!(!chars.has_images);
248
249        // Test content with headings
250        let chars = ContentCharacteristics::analyze("# Heading");
251        assert!(chars.has_headings);
252
253        // Test setext headings
254        let chars = ContentCharacteristics::analyze("Heading\n=======");
255        assert!(chars.has_headings);
256
257        // Test lists
258        let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
259        assert!(chars.has_lists);
260
261        // Test ordered lists
262        let chars = ContentCharacteristics::analyze("1. First\n2. Second");
263        assert!(chars.has_lists);
264
265        // Test links
266        let chars = ContentCharacteristics::analyze("[link](url)");
267        assert!(chars.has_links);
268
269        // Test URLs
270        let chars = ContentCharacteristics::analyze("Visit https://example.com");
271        assert!(chars.has_links);
272
273        // Test images
274        let chars = ContentCharacteristics::analyze("![alt text](image.png)");
275        assert!(chars.has_images);
276
277        // Test code
278        let chars = ContentCharacteristics::analyze("`inline code`");
279        assert!(chars.has_code);
280
281        let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
282        assert!(chars.has_code);
283
284        // Test emphasis
285        let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
286        assert!(chars.has_emphasis);
287
288        // Test HTML
289        let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
290        assert!(chars.has_html);
291
292        // Test tables
293        let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
294        assert!(chars.has_tables);
295
296        // Test blockquotes
297        let chars = ContentCharacteristics::analyze("> Quote");
298        assert!(chars.has_blockquotes);
299
300        // Test mixed content
301        let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n![image](img.png)";
302        let chars = ContentCharacteristics::analyze(content);
303        assert!(chars.has_headings);
304        assert!(chars.has_lists);
305        assert!(chars.has_links);
306        assert!(chars.has_code);
307        assert!(chars.has_emphasis);
308        assert!(chars.has_html);
309        assert!(chars.has_tables);
310        assert!(chars.has_blockquotes);
311        assert!(chars.has_images);
312    }
313
314    #[test]
315    fn test_content_characteristics_should_skip_rule() {
316        let chars = ContentCharacteristics {
317            has_headings: true,
318            has_lists: false,
319            has_links: true,
320            has_code: false,
321            has_emphasis: true,
322            has_html: false,
323            has_tables: true,
324            has_blockquotes: false,
325            has_images: false,
326        };
327
328        // Create test rules for different categories
329        let heading_rule = MD001HeadingIncrement;
330        assert!(!chars.should_skip_rule(&heading_rule));
331
332        let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
333        assert!(!chars.should_skip_rule(&trailing_spaces_rule)); // Whitespace rules always run
334
335        // Test skipping based on content
336        let chars_no_headings = ContentCharacteristics {
337            has_headings: false,
338            ..Default::default()
339        };
340        assert!(chars_no_headings.should_skip_rule(&heading_rule));
341    }
342
343    #[test]
344    fn test_lint_empty_content() {
345        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
346
347        let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard);
348        assert!(result.is_ok());
349        assert!(result.unwrap().is_empty());
350    }
351
352    #[test]
353    fn test_lint_with_violations() {
354        let content = "## Level 2\n#### Level 4"; // Skips level 3
355        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
356
357        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
358        assert!(result.is_ok());
359        let warnings = result.unwrap();
360        assert!(!warnings.is_empty());
361        // Check the rule field of LintWarning struct
362        assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
363    }
364
365    #[test]
366    fn test_lint_with_inline_disable() {
367        let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
368        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
369
370        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
371        assert!(result.is_ok());
372        let warnings = result.unwrap();
373        assert!(warnings.is_empty()); // Should be disabled by inline comment
374    }
375
376    #[test]
377    fn test_lint_rule_filtering() {
378        // Content with no lists
379        let content = "# Heading\nJust text";
380        let rules: Vec<Box<dyn Rule>> = vec![
381            Box::new(MD001HeadingIncrement),
382            // A list-related rule would be skipped
383        ];
384
385        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
386        assert!(result.is_ok());
387    }
388
389    #[test]
390    fn test_get_profiling_report() {
391        // Just test that it returns a string without panicking
392        let report = get_profiling_report();
393        assert!(!report.is_empty());
394        assert!(report.contains("Profiling"));
395    }
396
397    #[test]
398    fn test_reset_profiling() {
399        // Test that reset_profiling doesn't panic
400        reset_profiling();
401
402        // After reset, report should indicate no measurements or profiling disabled
403        let report = get_profiling_report();
404        assert!(report.contains("disabled") || report.contains("no measurements"));
405    }
406
407    #[test]
408    fn test_get_regex_cache_stats() {
409        let stats = get_regex_cache_stats();
410        // Stats should be a valid HashMap (might be empty)
411        assert!(stats.is_empty() || !stats.is_empty());
412
413        // If not empty, all values should be positive
414        for count in stats.values() {
415            assert!(*count > 0);
416        }
417    }
418
419    #[test]
420    fn test_content_characteristics_edge_cases() {
421        // Test setext heading edge case
422        let chars = ContentCharacteristics::analyze("-"); // Single dash, not a heading
423        assert!(!chars.has_headings);
424
425        let chars = ContentCharacteristics::analyze("--"); // Two dashes, valid setext
426        assert!(chars.has_headings);
427
428        // Test list detection edge cases
429        let chars = ContentCharacteristics::analyze("*emphasis*"); // Not a list
430        assert!(!chars.has_lists);
431
432        let chars = ContentCharacteristics::analyze("1.Item"); // No space after period
433        assert!(!chars.has_lists);
434
435        // Test blockquote must be at start of line
436        let chars = ContentCharacteristics::analyze("text > not a quote");
437        assert!(!chars.has_blockquotes);
438    }
439}