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