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        // Run single-file check
290        let result = rule.check(&lint_ctx);
291
292        match result {
293            Ok(rule_warnings) => {
294                // Filter out warnings for rules disabled via inline comments
295                let filtered_warnings: Vec<_> = rule_warnings
296                    .into_iter()
297                    .filter(|warning| {
298                        // Use the warning's rule_name if available, otherwise use the rule's name
299                        let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
300
301                        // Extract the base rule name for sub-rules like "MD029-style" -> "MD029"
302                        let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
303                            &rule_name_to_check[..dash_pos]
304                        } else {
305                            rule_name_to_check
306                        };
307
308                        !inline_config.is_rule_disabled(
309                            base_rule_name,
310                            warning.line, // Already 1-indexed
311                        )
312                    })
313                    .map(|mut warning| {
314                        // Apply severity override from config if present
315                        if let Some(cfg) = config {
316                            let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
317                            if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
318                                warning.severity = override_severity;
319                            }
320                        }
321                        warning
322                    })
323                    .collect();
324                warnings.extend(filtered_warnings);
325            }
326            Err(e) => {
327                log::error!("Error checking rule {}: {}", rule.name(), e);
328                return (Err(e), file_index);
329            }
330        }
331
332        #[cfg(not(target_arch = "wasm32"))]
333        {
334            let rule_duration = _rule_start.elapsed();
335            if profile_rules {
336                eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
337            }
338
339            #[cfg(not(test))]
340            if _verbose && rule_duration.as_millis() > 500 {
341                log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
342            }
343        }
344    }
345
346    // Contribute to index for cross-file rules (done after all rules checked)
347    // NOTE: We iterate over ALL rules (not just applicable_rules) because cross-file
348    // rules need to extract data from every file in the workspace, regardless of whether
349    // that file has content that would trigger the rule. For example, MD051 needs to
350    // index headings from files that have no links (like target.md) so that links
351    // FROM other files TO those headings can be validated.
352    for rule in rules {
353        if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
354            rule.contribute_to_index(&lint_ctx, &mut file_index);
355        }
356    }
357
358    #[cfg(not(test))]
359    if _verbose {
360        let skipped_rules = _total_rules - _applicable_count;
361        if skipped_rules > 0 {
362            log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
363        }
364    }
365
366    (Ok(warnings), file_index)
367}
368
369/// Run cross-file checks for rules that need workspace-wide validation
370///
371/// This should be called after all files have been linted and the WorkspaceIndex
372/// has been built from the accumulated FileIndex data.
373///
374/// Note: This takes the FileIndex instead of content to avoid re-parsing each file.
375/// The FileIndex was already populated during contribute_to_index in the linting phase.
376///
377/// Rules can use workspace_index methods for cross-file validation:
378/// - `get_file(path)` - to look up headings in target files (for MD051)
379///
380/// Returns additional warnings from cross-file validation.
381pub fn run_cross_file_checks(
382    file_path: &std::path::Path,
383    file_index: &crate::workspace_index::FileIndex,
384    rules: &[Box<dyn Rule>],
385    workspace_index: &crate::workspace_index::WorkspaceIndex,
386    config: Option<&crate::config::Config>,
387) -> LintResult {
388    use crate::rule::CrossFileScope;
389
390    let mut warnings = Vec::new();
391
392    // Only check rules that need cross-file analysis
393    for rule in rules {
394        if rule.cross_file_scope() != CrossFileScope::Workspace {
395            continue;
396        }
397
398        match rule.cross_file_check(file_path, file_index, workspace_index) {
399            Ok(rule_warnings) => {
400                // Filter cross-file warnings based on inline config stored in file_index
401                let filtered: Vec<_> = rule_warnings
402                    .into_iter()
403                    .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
404                    .map(|mut warning| {
405                        // Apply severity override from config if present
406                        if let Some(cfg) = config
407                            && let Some(override_severity) = cfg.get_rule_severity(rule.name())
408                        {
409                            warning.severity = override_severity;
410                        }
411                        warning
412                    })
413                    .collect();
414                warnings.extend(filtered);
415            }
416            Err(e) => {
417                log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
418                return Err(e);
419            }
420        }
421    }
422
423    Ok(warnings)
424}
425
426/// Get the profiling report
427pub fn get_profiling_report() -> String {
428    profiling::get_report()
429}
430
431/// Reset the profiling data
432pub fn reset_profiling() {
433    profiling::reset()
434}
435
436/// Get regex cache statistics for performance monitoring
437pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
438    crate::utils::regex_cache::get_cache_stats()
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444    use crate::rule::Rule;
445    use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
446
447    #[test]
448    fn test_content_characteristics_analyze() {
449        // Test empty content
450        let chars = ContentCharacteristics::analyze("");
451        assert!(!chars.has_headings);
452        assert!(!chars.has_lists);
453        assert!(!chars.has_links);
454        assert!(!chars.has_code);
455        assert!(!chars.has_emphasis);
456        assert!(!chars.has_html);
457        assert!(!chars.has_tables);
458        assert!(!chars.has_blockquotes);
459        assert!(!chars.has_images);
460
461        // Test content with headings
462        let chars = ContentCharacteristics::analyze("# Heading");
463        assert!(chars.has_headings);
464
465        // Test setext headings
466        let chars = ContentCharacteristics::analyze("Heading\n=======");
467        assert!(chars.has_headings);
468
469        // Test lists
470        let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
471        assert!(chars.has_lists);
472
473        // Test ordered lists
474        let chars = ContentCharacteristics::analyze("1. First\n2. Second");
475        assert!(chars.has_lists);
476
477        // Test links
478        let chars = ContentCharacteristics::analyze("[link](url)");
479        assert!(chars.has_links);
480
481        // Test URLs
482        let chars = ContentCharacteristics::analyze("Visit https://example.com");
483        assert!(chars.has_links);
484
485        // Test images
486        let chars = ContentCharacteristics::analyze("![alt text](image.png)");
487        assert!(chars.has_images);
488
489        // Test code
490        let chars = ContentCharacteristics::analyze("`inline code`");
491        assert!(chars.has_code);
492
493        let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
494        assert!(chars.has_code);
495
496        // Test indented code blocks (4 spaces)
497        let chars = ContentCharacteristics::analyze("Text\n\n    indented code\n\nMore text");
498        assert!(chars.has_code);
499
500        // Test tab-indented code blocks
501        let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
502        assert!(chars.has_code);
503
504        // Test mixed whitespace indented code (2 spaces + tab = 4 columns)
505        let chars = ContentCharacteristics::analyze("Text\n\n  \tmixed indent code\n\nMore text");
506        assert!(chars.has_code);
507
508        // Test 1 space + tab (also 4 columns due to tab expansion)
509        let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
510        assert!(chars.has_code);
511
512        // Test emphasis
513        let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
514        assert!(chars.has_emphasis);
515
516        // Test HTML
517        let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
518        assert!(chars.has_html);
519
520        // Test tables
521        let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
522        assert!(chars.has_tables);
523
524        // Test blockquotes
525        let chars = ContentCharacteristics::analyze("> Quote");
526        assert!(chars.has_blockquotes);
527
528        // Test mixed content
529        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)";
530        let chars = ContentCharacteristics::analyze(content);
531        assert!(chars.has_headings);
532        assert!(chars.has_lists);
533        assert!(chars.has_links);
534        assert!(chars.has_code);
535        assert!(chars.has_emphasis);
536        assert!(chars.has_html);
537        assert!(chars.has_tables);
538        assert!(chars.has_blockquotes);
539        assert!(chars.has_images);
540    }
541
542    #[test]
543    fn test_content_characteristics_should_skip_rule() {
544        let chars = ContentCharacteristics {
545            has_headings: true,
546            has_lists: false,
547            has_links: true,
548            has_code: false,
549            has_emphasis: true,
550            has_html: false,
551            has_tables: true,
552            has_blockquotes: false,
553            has_images: false,
554        };
555
556        // Create test rules for different categories
557        let heading_rule = MD001HeadingIncrement::default();
558        assert!(!chars.should_skip_rule(&heading_rule));
559
560        let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
561        assert!(!chars.should_skip_rule(&trailing_spaces_rule)); // Whitespace rules always run
562
563        // Test skipping based on content
564        let chars_no_headings = ContentCharacteristics {
565            has_headings: false,
566            ..Default::default()
567        };
568        assert!(chars_no_headings.should_skip_rule(&heading_rule));
569    }
570
571    #[test]
572    fn test_lint_empty_content() {
573        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
574
575        let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None);
576        assert!(result.is_ok());
577        assert!(result.unwrap().is_empty());
578    }
579
580    #[test]
581    fn test_lint_with_violations() {
582        let content = "## Level 2\n#### Level 4"; // Skips level 3
583        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
584
585        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
586        assert!(result.is_ok());
587        let warnings = result.unwrap();
588        assert!(!warnings.is_empty());
589        // Check the rule field of LintWarning struct
590        assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
591    }
592
593    #[test]
594    fn test_lint_with_inline_disable() {
595        let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
596        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
597
598        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
599        assert!(result.is_ok());
600        let warnings = result.unwrap();
601        assert!(warnings.is_empty()); // Should be disabled by inline comment
602    }
603
604    #[test]
605    fn test_lint_rule_filtering() {
606        // Content with no lists
607        let content = "# Heading\nJust text";
608        let rules: Vec<Box<dyn Rule>> = vec![
609            Box::new(MD001HeadingIncrement::default()),
610            // A list-related rule would be skipped
611        ];
612
613        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
614        assert!(result.is_ok());
615    }
616
617    #[test]
618    fn test_get_profiling_report() {
619        // Just test that it returns a string without panicking
620        let report = get_profiling_report();
621        assert!(!report.is_empty());
622        assert!(report.contains("Profiling"));
623    }
624
625    #[test]
626    fn test_reset_profiling() {
627        // Test that reset_profiling doesn't panic
628        reset_profiling();
629
630        // After reset, report should indicate no measurements or profiling disabled
631        let report = get_profiling_report();
632        assert!(report.contains("disabled") || report.contains("no measurements"));
633    }
634
635    #[test]
636    fn test_get_regex_cache_stats() {
637        let stats = get_regex_cache_stats();
638        // Stats should be a valid HashMap (might be empty)
639        assert!(stats.is_empty() || !stats.is_empty());
640
641        // If not empty, all values should be positive
642        for count in stats.values() {
643            assert!(*count > 0);
644        }
645    }
646
647    #[test]
648    fn test_content_characteristics_edge_cases() {
649        // Test setext heading edge case
650        let chars = ContentCharacteristics::analyze("-"); // Single dash, not a heading
651        assert!(!chars.has_headings);
652
653        let chars = ContentCharacteristics::analyze("--"); // Two dashes, valid setext
654        assert!(chars.has_headings);
655
656        // Test list detection - we now include potential list patterns (with or without space)
657        // to support user-intention detection in MD030
658        let chars = ContentCharacteristics::analyze("*emphasis*"); // Could be list or emphasis
659        assert!(chars.has_lists); // Run list rules to be safe
660
661        let chars = ContentCharacteristics::analyze("1.Item"); // Could be list without space
662        assert!(chars.has_lists); // Run list rules for user-intention detection
663
664        // Test blockquote must be at start of line
665        let chars = ContentCharacteristics::analyze("text > not a quote");
666        assert!(!chars.has_blockquotes);
667    }
668}