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