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;
12pub mod workspace_index;
13#[macro_use]
14pub mod rule_config;
15#[macro_use]
16pub mod rule_config_serde;
17pub mod rules;
18pub mod types;
19pub mod utils;
20
21// Native-only modules (require tokio, tower-lsp, etc.)
22#[cfg(feature = "native")]
23pub mod lsp;
24#[cfg(feature = "native")]
25pub mod output;
26#[cfg(feature = "native")]
27pub mod parallel;
28#[cfg(feature = "native")]
29pub mod performance;
30
31// WASM module
32#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
33pub mod wasm;
34
35pub use rules::heading_utils::{Heading, HeadingStyle};
36pub use rules::*;
37
38pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
39use crate::rule::{LintResult, Rule, RuleCategory};
40#[cfg(not(target_arch = "wasm32"))]
41use std::time::Instant;
42
43/// Content characteristics for efficient rule filtering
44#[derive(Debug, Default)]
45struct ContentCharacteristics {
46    has_headings: bool,    // # or setext headings
47    has_lists: bool,       // *, -, +, 1. etc
48    has_links: bool,       // [text](url) or [text][ref]
49    has_code: bool,        // ``` or ~~~ or indented code
50    has_emphasis: bool,    // * or _ for emphasis
51    has_html: bool,        // < > tags
52    has_tables: bool,      // | pipes
53    has_blockquotes: bool, // > markers
54    has_images: bool,      // ![alt](url)
55}
56
57impl ContentCharacteristics {
58    fn analyze(content: &str) -> Self {
59        let mut chars = Self { ..Default::default() };
60
61        // Quick single-pass analysis
62        let mut has_atx_heading = false;
63        let mut has_setext_heading = false;
64
65        for line in content.lines() {
66            let trimmed = line.trim();
67
68            // Headings: ATX (#) or Setext (underlines)
69            if !has_atx_heading && trimmed.starts_with('#') {
70                has_atx_heading = true;
71            }
72            if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
73                has_setext_heading = true;
74            }
75
76            // Quick character-based detection (more efficient than regex)
77            if !chars.has_lists && (line.contains("* ") || line.contains("- ") || line.contains("+ ")) {
78                chars.has_lists = true;
79            }
80            if !chars.has_lists && line.chars().next().is_some_and(|c| c.is_ascii_digit()) && line.contains(". ") {
81                chars.has_lists = true;
82            }
83            if !chars.has_links
84                && (line.contains('[')
85                    || line.contains("http://")
86                    || line.contains("https://")
87                    || line.contains("ftp://"))
88            {
89                chars.has_links = true;
90            }
91            if !chars.has_images && line.contains("![") {
92                chars.has_images = true;
93            }
94            if !chars.has_code && (line.contains('`') || line.contains("~~~")) {
95                chars.has_code = true;
96            }
97            if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
98                chars.has_emphasis = true;
99            }
100            if !chars.has_html && line.contains('<') {
101                chars.has_html = true;
102            }
103            if !chars.has_tables && line.contains('|') {
104                chars.has_tables = true;
105            }
106            if !chars.has_blockquotes && line.starts_with('>') {
107                chars.has_blockquotes = true;
108            }
109        }
110
111        chars.has_headings = has_atx_heading || has_setext_heading;
112        chars
113    }
114
115    /// Check if a rule should be skipped based on content characteristics
116    fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
117        match rule.category() {
118            RuleCategory::Heading => !self.has_headings,
119            RuleCategory::List => !self.has_lists,
120            RuleCategory::Link => !self.has_links && !self.has_images,
121            RuleCategory::Image => !self.has_images,
122            RuleCategory::CodeBlock => !self.has_code,
123            RuleCategory::Html => !self.has_html,
124            RuleCategory::Emphasis => !self.has_emphasis,
125            RuleCategory::Blockquote => !self.has_blockquotes,
126            RuleCategory::Table => !self.has_tables,
127            // Always check these categories as they apply to all content
128            RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
129        }
130    }
131}
132
133/// Compute content hash for incremental indexing change detection
134///
135/// Uses blake3 for native builds (fast, cryptographic-strength hash)
136/// Falls back to std::hash for WASM builds
137#[cfg(feature = "native")]
138fn compute_content_hash(content: &str) -> String {
139    blake3::hash(content.as_bytes()).to_hex().to_string()
140}
141
142/// Compute content hash for WASM builds using std::hash
143#[cfg(not(feature = "native"))]
144fn compute_content_hash(content: &str) -> String {
145    use std::hash::{DefaultHasher, Hash, Hasher};
146    let mut hasher = DefaultHasher::new();
147    content.hash(&mut hasher);
148    format!("{:016x}", hasher.finish())
149}
150
151/// Lint a file against the given rules with intelligent rule filtering
152/// Assumes the provided `rules` vector contains the final,
153/// configured, and filtered set of rules to be executed.
154pub fn lint(
155    content: &str,
156    rules: &[Box<dyn Rule>],
157    verbose: bool,
158    flavor: crate::config::MarkdownFlavor,
159) -> LintResult {
160    // Use lint_and_index but discard the FileIndex for backward compatibility
161    let (result, _file_index) = lint_and_index(content, rules, verbose, flavor);
162    result
163}
164
165/// Build FileIndex only (no linting) for cross-file analysis on cache hits
166///
167/// This is a lightweight function that only builds the FileIndex without running
168/// any rules. Used when we have a cache hit but still need the FileIndex for
169/// cross-file validation.
170///
171/// This avoids the overhead of re-running all rules when only the index data is needed.
172pub fn build_file_index_only(
173    content: &str,
174    rules: &[Box<dyn Rule>],
175    flavor: crate::config::MarkdownFlavor,
176) -> crate::workspace_index::FileIndex {
177    // Compute content hash for change detection
178    let content_hash = compute_content_hash(content);
179    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
180
181    // Early return for empty content
182    if content.is_empty() {
183        return file_index;
184    }
185
186    // Parse LintContext once with the provided flavor
187    let lint_ctx = crate::lint_context::LintContext::new(content, flavor);
188
189    // Only call contribute_to_index for cross-file rules (no rule checking!)
190    for rule in rules {
191        if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
192            rule.contribute_to_index(&lint_ctx, &mut file_index);
193        }
194    }
195
196    file_index
197}
198
199/// Lint a file and contribute to workspace index for cross-file analysis
200///
201/// This variant performs linting and optionally populates a `FileIndex` with data
202/// needed for cross-file validation. The FileIndex is populated during linting,
203/// avoiding duplicate parsing.
204///
205/// Returns: (warnings, FileIndex) - the FileIndex contains headings/links for cross-file rules
206pub fn lint_and_index(
207    content: &str,
208    rules: &[Box<dyn Rule>],
209    _verbose: bool,
210    flavor: crate::config::MarkdownFlavor,
211) -> (LintResult, crate::workspace_index::FileIndex) {
212    let mut warnings = Vec::new();
213    // Compute content hash for change detection
214    let content_hash = compute_content_hash(content);
215    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
216
217    #[cfg(not(target_arch = "wasm32"))]
218    let _overall_start = Instant::now();
219
220    // Early return for empty content
221    if content.is_empty() {
222        return (Ok(warnings), file_index);
223    }
224
225    // Parse inline configuration comments once
226    let inline_config = crate::inline_config::InlineConfig::from_content(content);
227
228    // Analyze content characteristics for rule filtering
229    let characteristics = ContentCharacteristics::analyze(content);
230
231    // Filter rules based on content characteristics
232    let applicable_rules: Vec<_> = rules
233        .iter()
234        .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
235        .collect();
236
237    // Calculate skipped rules count before consuming applicable_rules
238    let _total_rules = rules.len();
239    let _applicable_count = applicable_rules.len();
240
241    // Parse LintContext once with the provided flavor
242    let lint_ctx = crate::lint_context::LintContext::new(content, flavor);
243
244    #[cfg(not(target_arch = "wasm32"))]
245    let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
246    #[cfg(target_arch = "wasm32")]
247    let profile_rules = false;
248
249    for rule in &applicable_rules {
250        #[cfg(not(target_arch = "wasm32"))]
251        let _rule_start = Instant::now();
252
253        // Run single-file check
254        let result = rule.check(&lint_ctx);
255
256        match result {
257            Ok(rule_warnings) => {
258                // Filter out warnings for rules disabled via inline comments
259                let filtered_warnings: Vec<_> = rule_warnings
260                    .into_iter()
261                    .filter(|warning| {
262                        // Use the warning's rule_name if available, otherwise use the rule's name
263                        let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
264
265                        // Extract the base rule name for sub-rules like "MD029-style" -> "MD029"
266                        let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
267                            &rule_name_to_check[..dash_pos]
268                        } else {
269                            rule_name_to_check
270                        };
271
272                        !inline_config.is_rule_disabled(
273                            base_rule_name,
274                            warning.line, // Already 1-indexed
275                        )
276                    })
277                    .collect();
278                warnings.extend(filtered_warnings);
279            }
280            Err(e) => {
281                log::error!("Error checking rule {}: {}", rule.name(), e);
282                return (Err(e), file_index);
283            }
284        }
285
286        #[cfg(not(target_arch = "wasm32"))]
287        {
288            let rule_duration = _rule_start.elapsed();
289            if profile_rules {
290                eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
291            }
292
293            #[cfg(not(test))]
294            if _verbose && rule_duration.as_millis() > 500 {
295                log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
296            }
297        }
298    }
299
300    // Contribute to index for cross-file rules (done after all rules checked)
301    // NOTE: We iterate over ALL rules (not just applicable_rules) because cross-file
302    // rules need to extract data from every file in the workspace, regardless of whether
303    // that file has content that would trigger the rule. For example, MD051 needs to
304    // index headings from files that have no links (like target.md) so that links
305    // FROM other files TO those headings can be validated.
306    for rule in rules {
307        if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
308            rule.contribute_to_index(&lint_ctx, &mut file_index);
309        }
310    }
311
312    #[cfg(not(test))]
313    if _verbose {
314        let skipped_rules = _total_rules - _applicable_count;
315        if skipped_rules > 0 {
316            log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
317        }
318    }
319
320    (Ok(warnings), file_index)
321}
322
323/// Run cross-file checks for rules that need workspace-wide validation
324///
325/// This should be called after all files have been linted and the WorkspaceIndex
326/// has been built from the accumulated FileIndex data.
327///
328/// Note: This takes the FileIndex instead of content to avoid re-parsing each file.
329/// The FileIndex was already populated during contribute_to_index in the linting phase.
330///
331/// Rules can use workspace_index methods for cross-file validation:
332/// - `get_file(path)` - to look up headings in target files (for MD051)
333///
334/// Returns additional warnings from cross-file validation.
335pub fn run_cross_file_checks(
336    file_path: &std::path::Path,
337    file_index: &crate::workspace_index::FileIndex,
338    rules: &[Box<dyn Rule>],
339    workspace_index: &crate::workspace_index::WorkspaceIndex,
340) -> LintResult {
341    use crate::rule::CrossFileScope;
342
343    let mut warnings = Vec::new();
344
345    // Only check rules that need cross-file analysis
346    for rule in rules {
347        if rule.cross_file_scope() != CrossFileScope::Workspace {
348            continue;
349        }
350
351        match rule.cross_file_check(file_path, file_index, workspace_index) {
352            Ok(rule_warnings) => {
353                // Note: Inline config filtering is not applied to cross-file warnings
354                // since we don't have content here (by design, to avoid re-parsing).
355                // Users can disable cross-file rules via config if needed.
356                warnings.extend(rule_warnings);
357            }
358            Err(e) => {
359                log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
360                return Err(e);
361            }
362        }
363    }
364
365    Ok(warnings)
366}
367
368/// Get the profiling report
369pub fn get_profiling_report() -> String {
370    profiling::get_report()
371}
372
373/// Reset the profiling data
374pub fn reset_profiling() {
375    profiling::reset()
376}
377
378/// Get regex cache statistics for performance monitoring
379pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
380    crate::utils::regex_cache::get_cache_stats()
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386    use crate::rule::Rule;
387    use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
388
389    #[test]
390    fn test_content_characteristics_analyze() {
391        // Test empty content
392        let chars = ContentCharacteristics::analyze("");
393        assert!(!chars.has_headings);
394        assert!(!chars.has_lists);
395        assert!(!chars.has_links);
396        assert!(!chars.has_code);
397        assert!(!chars.has_emphasis);
398        assert!(!chars.has_html);
399        assert!(!chars.has_tables);
400        assert!(!chars.has_blockquotes);
401        assert!(!chars.has_images);
402
403        // Test content with headings
404        let chars = ContentCharacteristics::analyze("# Heading");
405        assert!(chars.has_headings);
406
407        // Test setext headings
408        let chars = ContentCharacteristics::analyze("Heading\n=======");
409        assert!(chars.has_headings);
410
411        // Test lists
412        let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
413        assert!(chars.has_lists);
414
415        // Test ordered lists
416        let chars = ContentCharacteristics::analyze("1. First\n2. Second");
417        assert!(chars.has_lists);
418
419        // Test links
420        let chars = ContentCharacteristics::analyze("[link](url)");
421        assert!(chars.has_links);
422
423        // Test URLs
424        let chars = ContentCharacteristics::analyze("Visit https://example.com");
425        assert!(chars.has_links);
426
427        // Test images
428        let chars = ContentCharacteristics::analyze("![alt text](image.png)");
429        assert!(chars.has_images);
430
431        // Test code
432        let chars = ContentCharacteristics::analyze("`inline code`");
433        assert!(chars.has_code);
434
435        let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
436        assert!(chars.has_code);
437
438        // Test emphasis
439        let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
440        assert!(chars.has_emphasis);
441
442        // Test HTML
443        let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
444        assert!(chars.has_html);
445
446        // Test tables
447        let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
448        assert!(chars.has_tables);
449
450        // Test blockquotes
451        let chars = ContentCharacteristics::analyze("> Quote");
452        assert!(chars.has_blockquotes);
453
454        // Test mixed content
455        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)";
456        let chars = ContentCharacteristics::analyze(content);
457        assert!(chars.has_headings);
458        assert!(chars.has_lists);
459        assert!(chars.has_links);
460        assert!(chars.has_code);
461        assert!(chars.has_emphasis);
462        assert!(chars.has_html);
463        assert!(chars.has_tables);
464        assert!(chars.has_blockquotes);
465        assert!(chars.has_images);
466    }
467
468    #[test]
469    fn test_content_characteristics_should_skip_rule() {
470        let chars = ContentCharacteristics {
471            has_headings: true,
472            has_lists: false,
473            has_links: true,
474            has_code: false,
475            has_emphasis: true,
476            has_html: false,
477            has_tables: true,
478            has_blockquotes: false,
479            has_images: false,
480        };
481
482        // Create test rules for different categories
483        let heading_rule = MD001HeadingIncrement;
484        assert!(!chars.should_skip_rule(&heading_rule));
485
486        let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
487        assert!(!chars.should_skip_rule(&trailing_spaces_rule)); // Whitespace rules always run
488
489        // Test skipping based on content
490        let chars_no_headings = ContentCharacteristics {
491            has_headings: false,
492            ..Default::default()
493        };
494        assert!(chars_no_headings.should_skip_rule(&heading_rule));
495    }
496
497    #[test]
498    fn test_lint_empty_content() {
499        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
500
501        let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard);
502        assert!(result.is_ok());
503        assert!(result.unwrap().is_empty());
504    }
505
506    #[test]
507    fn test_lint_with_violations() {
508        let content = "## Level 2\n#### Level 4"; // Skips level 3
509        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
510
511        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
512        assert!(result.is_ok());
513        let warnings = result.unwrap();
514        assert!(!warnings.is_empty());
515        // Check the rule field of LintWarning struct
516        assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
517    }
518
519    #[test]
520    fn test_lint_with_inline_disable() {
521        let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
522        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
523
524        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
525        assert!(result.is_ok());
526        let warnings = result.unwrap();
527        assert!(warnings.is_empty()); // Should be disabled by inline comment
528    }
529
530    #[test]
531    fn test_lint_rule_filtering() {
532        // Content with no lists
533        let content = "# Heading\nJust text";
534        let rules: Vec<Box<dyn Rule>> = vec![
535            Box::new(MD001HeadingIncrement),
536            // A list-related rule would be skipped
537        ];
538
539        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
540        assert!(result.is_ok());
541    }
542
543    #[test]
544    fn test_get_profiling_report() {
545        // Just test that it returns a string without panicking
546        let report = get_profiling_report();
547        assert!(!report.is_empty());
548        assert!(report.contains("Profiling"));
549    }
550
551    #[test]
552    fn test_reset_profiling() {
553        // Test that reset_profiling doesn't panic
554        reset_profiling();
555
556        // After reset, report should indicate no measurements or profiling disabled
557        let report = get_profiling_report();
558        assert!(report.contains("disabled") || report.contains("no measurements"));
559    }
560
561    #[test]
562    fn test_get_regex_cache_stats() {
563        let stats = get_regex_cache_stats();
564        // Stats should be a valid HashMap (might be empty)
565        assert!(stats.is_empty() || !stats.is_empty());
566
567        // If not empty, all values should be positive
568        for count in stats.values() {
569            assert!(*count > 0);
570        }
571    }
572
573    #[test]
574    fn test_content_characteristics_edge_cases() {
575        // Test setext heading edge case
576        let chars = ContentCharacteristics::analyze("-"); // Single dash, not a heading
577        assert!(!chars.has_headings);
578
579        let chars = ContentCharacteristics::analyze("--"); // Two dashes, valid setext
580        assert!(chars.has_headings);
581
582        // Test list detection edge cases
583        let chars = ContentCharacteristics::analyze("*emphasis*"); // Not a list
584        assert!(!chars.has_lists);
585
586        let chars = ContentCharacteristics::analyze("1.Item"); // No space after period
587        assert!(!chars.has_lists);
588
589        // Test blockquote must be at start of line
590        let chars = ContentCharacteristics::analyze("text > not a quote");
591        assert!(!chars.has_blockquotes);
592    }
593}