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