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