Skip to main content

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