Skip to main content

rumdl_lib/
lib.rs

1#![warn(unreachable_pub)]
2#![warn(clippy::pedantic)]
3// Style-only pedantic lints we don't enforce. Each one generated >5 occurrences
4// that were either deliberate design choices or too noisy for the value
5// delivered. Categories that flag potential bugs stay on.
6#![allow(clippy::doc_markdown)]
7#![allow(clippy::must_use_candidate)]
8#![allow(clippy::missing_errors_doc)]
9#![allow(clippy::missing_panics_doc)]
10#![allow(clippy::too_many_lines)]
11#![allow(clippy::if_not_else)]
12#![allow(clippy::similar_names)]
13#![allow(clippy::wildcard_imports)]
14#![allow(clippy::case_sensitive_file_extension_comparisons)]
15#![allow(clippy::doc_link_with_quotes)]
16#![allow(clippy::needless_raw_string_hashes)]
17#![allow(clippy::trivially_copy_pass_by_ref)]
18#![allow(clippy::struct_excessive_bools)]
19#![allow(clippy::fn_params_excessive_bools)]
20#![allow(clippy::elidable_lifetime_names)]
21#![allow(clippy::return_self_not_must_use)]
22#![allow(clippy::redundant_else)]
23#![allow(clippy::single_match_else)]
24#![allow(clippy::needless_continue)]
25#![allow(clippy::semicolon_if_nothing_returned)]
26#![allow(clippy::ignored_unit_patterns)]
27#![allow(clippy::unreadable_literal)]
28#![allow(clippy::implicit_hasher)]
29#![allow(clippy::ref_option)]
30#![allow(clippy::struct_field_names)]
31#![allow(clippy::unused_self)]
32#![allow(clippy::unnested_or_patterns)]
33#![allow(clippy::cast_precision_loss)]
34#![allow(clippy::cast_sign_loss)]
35#![allow(clippy::cast_possible_wrap)]
36#![allow(clippy::cast_possible_truncation)]
37#![allow(clippy::cast_lossless)]
38#![allow(clippy::items_after_statements)]
39#![allow(clippy::match_same_arms)]
40#![allow(clippy::format_push_string)]
41// Test smoke-constructors like `let _formatter = Foo;` fire this lint,
42// but are acceptable: they verify the type exists without asserting behavior.
43#![allow(clippy::no_effect_underscore_binding)]
44// Style-only: `Default::default()` vs `T::default()`. Both are readable.
45#![allow(clippy::default_trait_access)]
46// Style-only: `"".to_string()` vs `String::new()`. Tests favor the former
47// for symmetry with non-empty string literals.
48#![allow(clippy::manual_string_new)]
49
50pub mod code_block_tools;
51pub mod config;
52pub mod discovery;
53pub mod doc_comment_lint;
54pub mod document_run;
55pub mod embedded_lint;
56pub mod exit_codes;
57pub mod filtered_lines;
58pub mod fix_coordinator;
59pub mod inline_config;
60pub mod linguist_data;
61pub mod lint_context;
62pub mod markdownlint_config;
63pub mod merge_conflict;
64pub mod profiling;
65pub mod rule;
66#[cfg(feature = "colored")]
67pub mod vscode;
68pub mod workspace_index;
69#[macro_use]
70pub mod rule_config;
71#[macro_use]
72pub mod rule_config_serde;
73pub mod rules;
74pub mod types;
75pub mod utils;
76
77// Native-only modules (require tokio, tower-lsp, etc.)
78#[cfg(feature = "native")]
79pub mod lsp;
80#[cfg(feature = "colored")]
81pub mod output;
82
83// WASM module
84#[cfg(feature = "wasm")]
85pub mod wasm;
86
87pub use rules::heading_utils::HeadingStyle;
88pub use rules::*;
89
90pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
91use crate::rule::{LintResult, Rule, RuleCategory};
92use crate::utils::calculate_indentation_width_default;
93#[cfg(not(target_arch = "wasm32"))]
94use std::time::Instant;
95
96/// Content characteristics for efficient rule filtering
97#[derive(Debug, Default)]
98struct ContentCharacteristics {
99    has_headings: bool,    // # or setext headings
100    has_lists: bool,       // *, -, +, 1. etc
101    has_links: bool,       // [text](url) or [text][ref]
102    has_code: bool,        // ``` or ~~~ or indented code
103    has_emphasis: bool,    // * or _ for emphasis
104    has_html: bool,        // < > tags
105    has_tables: bool,      // | pipes
106    has_blockquotes: bool, // > markers
107    has_images: bool,      // ![alt](url)
108}
109
110/// Check if a line has enough leading whitespace to be an indented code block.
111/// Indented code blocks require 4+ columns of leading whitespace (with proper tab expansion).
112fn has_potential_indented_code_indent(line: &str) -> bool {
113    calculate_indentation_width_default(line) >= 4
114}
115
116impl ContentCharacteristics {
117    fn analyze(content: &str) -> Self {
118        let mut chars = Self { ..Default::default() };
119
120        // Quick single-pass analysis
121        let mut has_atx_heading = false;
122        let mut has_setext_heading = false;
123
124        for line in content.lines() {
125            let trimmed = line.trim();
126
127            // Headings: ATX (#) or Setext (underlines). A blockquoted ATX
128            // heading (`> ## Title`) still emits a fragment anchor, so rules
129            // like MD051/MD080 must run for blockquote-only documents too.
130            // Stripping `>`/space/tab is a coarse, deliberately
131            // over-inclusive prefilter check (it must never skip a rule that
132            // has work; `parse_blockquote_prefix` also accepts a tab marker).
133            if !has_atx_heading
134                && (trimmed.starts_with('#') || trimmed.trim_start_matches(['>', ' ', '\t']).starts_with('#'))
135            {
136                has_atx_heading = true;
137            }
138            // A setext underline can be a single `=` or `-`, and one inside a
139            // blockquote follows the quote's markers.
140            let underline = trimmed.trim_start_matches(['>', ' ', '\t']);
141            if !has_setext_heading && !underline.is_empty() && underline.chars().all(|c| c == '=' || c == '-') {
142                has_setext_heading = true;
143            }
144
145            // Quick character-based detection (more efficient than regex)
146            // Include patterns without spaces to enable user-intention detection (MD030)
147            if !chars.has_lists
148                && (line.contains("* ")
149                    || line.contains("- ")
150                    || line.contains("+ ")
151                    || trimmed.starts_with("* ")
152                    || trimmed.starts_with("- ")
153                    || trimmed.starts_with("+ ")
154                    || trimmed.starts_with('*')
155                    || trimmed.starts_with('-')
156                    || trimmed.starts_with('+'))
157            {
158                chars.has_lists = true;
159            }
160            // Ordered lists: a line whose text starts with a digit (a marker may
161            // be indented), or a blockquote line holding one, and either marker
162            // delimiter (`.` or `)`) after it
163            if !chars.has_lists
164                && ((trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains(['.', ')']))
165                    || (trimmed.starts_with('>')
166                        && trimmed.chars().any(|c| c.is_ascii_digit())
167                        && trimmed.contains(['.', ')'])))
168            {
169                chars.has_lists = true;
170            }
171            if !chars.has_links
172                && (line.contains('[')
173                    || line.contains("http://")
174                    || line.contains("https://")
175                    || line.contains("ftp://")
176                    || line.contains("www."))
177            {
178                chars.has_links = true;
179            }
180            if !chars.has_images && line.contains("![") {
181                chars.has_images = true;
182            }
183            if !chars.has_code
184                && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
185            {
186                chars.has_code = true;
187            }
188            if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
189                chars.has_emphasis = true;
190            }
191            if !chars.has_html && line.contains('<') {
192                chars.has_html = true;
193            }
194            if !chars.has_tables && line.contains('|') {
195                chars.has_tables = true;
196            }
197            if !chars.has_blockquotes && line.starts_with('>') {
198                chars.has_blockquotes = true;
199            }
200        }
201
202        chars.has_headings = has_atx_heading || has_setext_heading;
203        chars
204    }
205
206    /// Check if a rule should be skipped based on content characteristics
207    fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
208        match rule.category() {
209            RuleCategory::Heading => !self.has_headings,
210            RuleCategory::List => !self.has_lists,
211            RuleCategory::Link => !self.has_links && !self.has_images,
212            RuleCategory::Image => !self.has_images,
213            RuleCategory::CodeBlock => !self.has_code,
214            RuleCategory::Html => !self.has_html,
215            RuleCategory::Emphasis => !self.has_emphasis,
216            RuleCategory::Blockquote => !self.has_blockquotes,
217            RuleCategory::Table => !self.has_tables,
218            // Always check these categories as they apply to all content
219            RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
220        }
221    }
222}
223
224/// Compute content hash for incremental indexing change detection
225///
226/// Uses blake3 for native builds (fast, cryptographic-strength hash)
227/// Falls back to std::hash for WASM builds
228#[cfg(feature = "native")]
229fn compute_content_hash(content: &str) -> String {
230    #[cfg(feature = "profiling")]
231    let start = std::time::Instant::now();
232    let hash = blake3::hash(content.as_bytes()).to_hex().to_string();
233    #[cfg(feature = "profiling")]
234    profiling::record_duration("index: hash content", start.elapsed());
235    hash
236}
237
238/// Compute content hash for WASM builds using std::hash
239#[cfg(not(feature = "native"))]
240fn compute_content_hash(content: &str) -> String {
241    use std::hash::{DefaultHasher, Hash, Hasher};
242    let mut hasher = DefaultHasher::new();
243    content.hash(&mut hasher);
244    format!("{:016x}", hasher.finish())
245}
246
247/// Lint a file against the given rules with intelligent rule filtering
248/// Assumes the provided `rules` vector contains the final,
249/// configured, and filtered set of rules to be executed.
250pub fn lint(
251    content: &str,
252    rules: &[Box<dyn Rule>],
253    verbose: bool,
254    flavor: crate::config::MarkdownFlavor,
255    source_file: Option<std::path::PathBuf>,
256    config: Option<&crate::config::Config>,
257) -> LintResult {
258    let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
259    result
260}
261
262/// Build FileIndex only (no linting) for cross-file analysis on cache hits
263///
264/// This is a lightweight function that only builds the FileIndex without running
265/// any rules. Used when we have a cache hit but still need the FileIndex for
266/// cross-file validation.
267///
268/// This avoids the overhead of re-running all rules when only the index data is needed.
269pub fn build_file_index_only(
270    content: &str,
271    rules: &[Box<dyn Rule>],
272    flavor: crate::config::MarkdownFlavor,
273    source_file: Option<std::path::PathBuf>,
274) -> crate::workspace_index::FileIndex {
275    build_file_index_only_with_config(content, rules, flavor, source_file, &crate::config::Config::default())
276}
277
278/// Build an index using the document's conflict-marker configuration.
279/// This keeps cache hits and workspace scans consistent with ordinary linting.
280pub fn build_file_index_only_with_config(
281    content: &str,
282    rules: &[Box<dyn Rule>],
283    flavor: crate::config::MarkdownFlavor,
284    source_file: Option<std::path::PathBuf>,
285    config: &crate::config::Config,
286) -> crate::workspace_index::FileIndex {
287    // Compute content hash for change detection
288    let content_hash = compute_content_hash(content);
289    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
290
291    if crate::merge_conflict::detect_configured(content, config, source_file.as_deref()).is_some() {
292        return file_index;
293    }
294
295    // Early return for empty content
296    if content.is_empty() {
297        return file_index;
298    }
299
300    // Parse LintContext once with the provided flavor
301    let lint_ctx = time_function!(
302        "index: parse lint context",
303        crate::lint_context::LintContext::new(content, flavor, source_file)
304    );
305
306    // Export inline disable data to the FileIndex so cross-file checks honor
307    // `<!-- rumdl-disable -->` blocks on the lint-cache fast path, exactly as
308    // lint_and_index does on the normal path.
309    let (file_disabled, persistent_transitions, line_disabled) = lint_ctx.inline_config().export_for_file_index();
310    file_index.file_disabled_rules = file_disabled;
311    file_index.persistent_transitions = persistent_transitions;
312    file_index.line_disabled_rules = line_disabled;
313
314    // Only call contribute_to_index for cross-file rules (no rule checking!)
315    time_section!("index: contribute cross-file data", {
316        for rule in rules {
317            if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
318                rule.contribute_to_index(&lint_ctx, &mut file_index);
319            }
320        }
321    });
322
323    file_index
324}
325
326/// Rewrite every fix replacement in the document's own line ending.
327///
328/// Rules build a fix on LF text, so a line ending they insert is `\n`, and the
329/// CLI really does hand them LF: it normalises a file on read and restores the
330/// ending on write. The LSP and wasm lint the editor's or host's text as it is,
331/// and a quick fix that inserted a bare `\n` into a CRLF document left it with
332/// mixed endings. Conforming here, where every rule's warnings meet, settles it
333/// for every caller and every rule at once. A document with mixed endings has no
334/// single convention to conform to and keeps the fix as the rule wrote it.
335fn conform_fix_line_endings(content: &str, warnings: &mut [crate::rule::LintWarning]) {
336    if !content.contains('\r') || crate::utils::detect_line_ending_enum(content) != crate::utils::LineEnding::Crlf {
337        return;
338    }
339    fn conform(fix: &mut crate::rule::Fix) {
340        if fix.replacement.contains('\n') {
341            fix.replacement =
342                crate::utils::normalize_line_ending(&fix.replacement, crate::utils::LineEnding::Crlf).into_owned();
343        }
344        for extra in &mut fix.additional_edits {
345            conform(extra);
346        }
347    }
348    for fix in warnings.iter_mut().filter_map(|warning| warning.fix.as_mut()) {
349        conform(fix);
350    }
351}
352
353/// Drop the warnings a document silences, and apply any configured severity override
354/// to the rest.
355///
356/// A warning is dropped when it sits in a kramdown extension block or when an inline
357/// comment disables its rule somewhere in its range. `suppressed`, when given,
358/// collects what the inline comments removed, for the rules that report on them. A
359/// kramdown extension block is not an inline comment, so what it drops is left out.
360fn retain_reportable_warnings(
361    lint_ctx: &crate::lint_context::LintContext,
362    config: Option<&crate::config::Config>,
363    rule_name: &str,
364    rule_warnings: Vec<crate::rule::LintWarning>,
365    mut suppressed: Option<&mut Vec<crate::rule::SuppressedWarning>>,
366) -> Vec<crate::rule::LintWarning> {
367    let inline_config = lint_ctx.inline_config();
368    let mut kept = Vec::with_capacity(rule_warnings.len());
369
370    for mut warning in rule_warnings {
371        if lint_ctx
372            .line_info(warning.line)
373            .is_some_and(|info| info.in_kramdown_extension_block)
374        {
375            continue;
376        }
377
378        // Use the warning's rule_name if available, otherwise use the rule's name
379        let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule_name);
380
381        // Extract the base rule name for sub-rules like "MD029-style" -> "MD029"
382        let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
383            &rule_name_to_check[..dash_pos]
384        } else {
385            rule_name_to_check
386        };
387
388        // Check if the rule is disabled at any line in the warning's range.
389        // Multi-line warnings (e.g., reflow) report on the first line,
390        // but inline disable comments may appear later in the range.
391        // Guard: if end_line < line (e.g., end_line=0), fall back to
392        // checking only the warning's line to match original behavior.
393        let end = if warning.end_line >= warning.line {
394            warning.end_line
395        } else {
396            warning.line
397        };
398        let disabled_at = (warning.line..=end).find_map(|line| {
399            inline_config
400                .disabling_layer(base_rule_name, line)
401                .map(|layer| (line, layer))
402        });
403        if let Some((line, layer)) = disabled_at {
404            if let Some(record) = suppressed.as_deref_mut() {
405                record.push(crate::rule::SuppressedWarning {
406                    rule_name: base_rule_name.to_string(),
407                    line,
408                    layer,
409                });
410            }
411            continue;
412        }
413
414        // Apply severity override from config if present
415        if let Some(cfg) = config
416            && let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check)
417        {
418            warning.severity = override_severity;
419        }
420
421        kept.push(warning);
422    }
423
424    kept
425}
426
427/// Lint a file and contribute to workspace index for cross-file analysis
428///
429/// This variant performs linting and optionally populates a `FileIndex` with data
430/// needed for cross-file validation. The FileIndex is populated during linting,
431/// avoiding duplicate parsing.
432///
433/// Returns: (warnings, FileIndex) - the FileIndex contains headings/links for cross-file rules
434#[cfg_attr(test, allow(unused_variables))]
435#[allow(clippy::needless_pass_by_value)] // Public compatibility: callers already pass an owned path.
436pub fn lint_and_index(
437    content: &str,
438    rules: &[Box<dyn Rule>],
439    verbose: bool,
440    flavor: crate::config::MarkdownFlavor,
441    source_file: Option<std::path::PathBuf>,
442    config: Option<&crate::config::Config>,
443) -> (LintResult, crate::workspace_index::FileIndex) {
444    lint_and_index_with_paths(
445        content,
446        rules,
447        verbose,
448        flavor,
449        DocumentPaths::same(source_file.as_deref()),
450        config,
451    )
452}
453
454/// The two path roles involved in document processing.
455#[derive(Debug, Clone, Copy, Default)]
456pub struct DocumentPaths<'a> {
457    /// Logical path used for per-file configuration matching.
458    pub config_path: Option<&'a std::path::Path>,
459    /// Native path exposed to filesystem-aware rules.
460    pub source_file: Option<&'a std::path::Path>,
461    /// Run-scoped virtual paths visible to filesystem-aware link rules.
462    pub link_target_policy: Option<&'a crate::lint_context::LinkTargetPolicy>,
463}
464
465impl<'a> DocumentPaths<'a> {
466    /// Use one native path for both roles.
467    pub fn same(path: Option<&'a std::path::Path>) -> Self {
468        Self {
469            config_path: path,
470            source_file: path,
471            link_target_policy: None,
472        }
473    }
474}
475
476/// Lint a document while keeping configuration matching separate from filesystem context.
477///
478/// `paths.config_path` selects per-file ignores and other path-scoped configuration.
479/// `paths.source_file` is exposed to rules that need a real filesystem location. Native
480/// adapters normally pass the same path for both; virtual adapters can supply only
481/// `config_path` without accidentally enabling filesystem-dependent rule behavior.
482#[cfg_attr(test, allow(unused_variables))]
483pub fn lint_and_index_with_paths(
484    content: &str,
485    rules: &[Box<dyn Rule>],
486    verbose: bool,
487    flavor: crate::config::MarkdownFlavor,
488    paths: DocumentPaths<'_>,
489    config: Option<&crate::config::Config>,
490) -> (LintResult, crate::workspace_index::FileIndex) {
491    let mut warnings = Vec::new();
492    // Compute content hash for change detection
493    let content_hash = compute_content_hash(content);
494    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
495
496    let conflict = config.map_or_else(
497        || {
498            crate::merge_conflict::detect_for_rules(
499                content,
500                rules,
501                &crate::config::Config::default(),
502                paths.config_path,
503            )
504        },
505        |config| crate::merge_conflict::detect_for_rules(content, rules, config, paths.config_path),
506    );
507    if let Some(conflict) = conflict {
508        return (Ok(vec![conflict]), file_index);
509    }
510
511    // Early return for empty content
512    if content.is_empty() {
513        return (Ok(warnings), file_index);
514    }
515
516    // The rules `per-file-ignores` takes away for this file. It decides what this
517    // file REPORTS, and nothing else: the index contribution at the end of this
518    // function deliberately keeps running every cross-file rule, because a file's
519    // headings and links belong to the workspace rather than to its own report.
520    // Dropping a rule from the index instead would break the links pointing HERE,
521    // in files that never named it.
522    let ignored_for_file = match (config, paths.config_path) {
523        (Some(cfg), Some(path)) => cfg.get_ignored_rules_for_file(path),
524        _ => std::collections::HashSet::new(),
525    };
526
527    // Parse LintContext once (includes inline config parsing)
528    let lint_ctx = time_function!(
529        "lint: parse lint context",
530        crate::lint_context::LintContext::new(content, flavor, paths.source_file.map(std::path::Path::to_path_buf))
531    );
532    let lint_ctx = match paths.link_target_policy {
533        Some(policy) => lint_ctx.with_link_target_policy(policy.clone()),
534        None => lint_ctx,
535    };
536    let inline_config = lint_ctx.inline_config();
537
538    // Export inline config data to FileIndex for cross-file rule filtering
539    let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
540    file_index.file_disabled_rules = file_disabled;
541    file_index.persistent_transitions = persistent_transitions;
542    file_index.line_disabled_rules = line_disabled;
543
544    // Analyze content characteristics for rule filtering
545    let characteristics = time_function!(
546        "lint: analyze content characteristics",
547        ContentCharacteristics::analyze(content)
548    );
549
550    // Filter rules based on per-file-ignores and content characteristics
551    let applicable_rules: Vec<_> = rules
552        .iter()
553        .filter(|rule| !ignored_for_file.contains(rule.name()))
554        .filter(|rule| !(rule.skippable_by_category() && characteristics.should_skip_rule(rule.as_ref())))
555        .collect();
556
557    // Calculate skipped rules count before consuming applicable_rules
558    #[cfg(not(test))]
559    let total_rules = rules.len();
560    #[cfg(not(test))]
561    let applicable_count = applicable_rules.len();
562
563    #[cfg(not(target_arch = "wasm32"))]
564    let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
565
566    // Automatic inline config support: merge inline overrides into config once,
567    // then recreate only the affected rules. Works for ALL rules without per-rule changes.
568    let inline_overrides = inline_config.get_all_rule_configs();
569    let merged_config = if !inline_overrides.is_empty() {
570        config.map(|c| c.merge_with_inline_config(inline_config))
571    } else {
572        None
573    };
574    let effective_config = merged_config.as_ref().or(config);
575
576    // Cache recreated rules for rules with inline overrides
577    let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
578        std::collections::HashMap::new();
579
580    // Pre-create rules that have inline config overrides
581    if let Some(cfg) = effective_config {
582        for rule_name in inline_overrides.keys() {
583            if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
584                recreated_rules.insert(rule_name.clone(), recreated);
585            }
586        }
587    }
588
589    // A rule reporting on the run's inline disable comments needs to know what they
590    // removed, which costs a record per suppressed warning, so it is only kept when
591    // such a rule is going to read it.
592    let suppression_observers: Vec<_> = applicable_rules
593        .iter()
594        .filter(|rule| rule.observes_suppressions() && !rule.should_skip(&lint_ctx))
595        .collect();
596    let mut suppressed = Vec::new();
597
598    {
599        let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
600        for rule in &applicable_rules {
601            #[cfg(not(target_arch = "wasm32"))]
602            let rule_start = Instant::now();
603
604            // Skip rules that indicate they should be skipped (opt-in rules, content-based skipping)
605            if rule.should_skip(&lint_ctx) {
606                continue;
607            }
608
609            // Use recreated rule if inline config overrides exist for this rule
610            let effective_rule: &dyn crate::rule::Rule = recreated_rules
611                .get(rule.name())
612                .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
613
614            // Run single-file check with the effective rule (possibly with inline config applied)
615            let result = effective_rule.check(&lint_ctx);
616
617            match result {
618                Ok(rule_warnings) => {
619                    let record = if suppression_observers.is_empty() {
620                        None
621                    } else {
622                        Some(&mut suppressed)
623                    };
624                    let filtered_warnings =
625                        retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, record);
626                    warnings.extend(filtered_warnings);
627                }
628                Err(e) => {
629                    log::error!("Error checking rule {}: {}", rule.name(), e);
630                    return (Err(e), file_index);
631                }
632            }
633
634            #[cfg(not(target_arch = "wasm32"))]
635            {
636                let rule_duration = rule_start.elapsed();
637                if profile_rules {
638                    eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
639                }
640
641                #[cfg(not(test))]
642                if verbose && rule_duration.as_millis() > 500 {
643                    log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
644                }
645            }
646        }
647    }
648
649    // Report on the inline disable comments, now that every single-file rule has run
650    // and the suppressions are complete.
651    if !suppression_observers.is_empty() {
652        let _timer = profiling::ScopedTimer::new("lint: run suppression rules");
653
654        // A workspace-scope rule has its warnings filtered after this point, and for a
655        // single-file run not at all, so its findings never reach the report and
656        // nothing can be concluded about a comment naming it. A rule this file
657        // ignores does not report either, for the same reason.
658        let report = crate::rule::SuppressionReport {
659            suppressed,
660            judged_rules: rules
661                .iter()
662                .filter(|rule| rule.cross_file_scope() != crate::rule::CrossFileScope::Workspace)
663                .filter(|rule| !ignored_for_file.contains(rule.name()))
664                .map(|rule| rule.name().to_string())
665                .collect(),
666        };
667
668        for rule in &suppression_observers {
669            match rule.check_suppressions(&lint_ctx, &report) {
670                Ok(rule_warnings) => {
671                    let filtered_warnings =
672                        retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, None);
673                    warnings.extend(filtered_warnings);
674                }
675                Err(e) => {
676                    log::error!("Error checking rule {}: {}", rule.name(), e);
677                    return (Err(e), file_index);
678                }
679            }
680        }
681    }
682
683    // Contribute to index for cross-file rules (done after all rules checked)
684    // NOTE: We iterate over ALL rules (not just applicable_rules) because cross-file
685    // rules need to extract data from every file in the workspace, regardless of whether
686    // that file has content that would trigger the rule, and regardless of what this
687    // file's own configuration reports. For example, MD051 needs to index headings from
688    // files that have no links (like target.md) so that links FROM other files TO those
689    // headings can be validated - including from a file that ignores MD051 itself.
690    time_section!("lint: contribute cross-file data", {
691        for rule in rules {
692            if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
693                rule.contribute_to_index(&lint_ctx, &mut file_index);
694            }
695        }
696    });
697
698    #[cfg(not(test))]
699    if verbose {
700        let skipped_rules = total_rules - applicable_count;
701        if skipped_rules > 0 {
702            log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
703        }
704    }
705
706    conform_fix_line_endings(content, &mut warnings);
707
708    (Ok(warnings), file_index)
709}
710
711/// Run cross-file checks for rules that need workspace-wide validation
712///
713/// This should be called after all files have been linted and the WorkspaceIndex
714/// has been built from the accumulated FileIndex data.
715///
716/// Note: This takes the FileIndex instead of content to avoid re-parsing each file.
717/// The FileIndex was already populated during contribute_to_index in the linting phase.
718///
719/// Rules can use workspace_index methods for cross-file validation:
720/// - `get_file(path)` - to look up headings in target files (for MD051)
721///
722/// Returns additional warnings from cross-file validation.
723pub fn run_cross_file_checks(
724    file_path: &std::path::Path,
725    file_index: &crate::workspace_index::FileIndex,
726    rules: &[Box<dyn Rule>],
727    workspace_index: &crate::workspace_index::WorkspaceIndex,
728    config: Option<&crate::config::Config>,
729) -> LintResult {
730    use crate::rule::CrossFileScope;
731
732    let mut warnings = Vec::new();
733
734    // Honor `per-file-ignores` for cross-file rules. Cross-file warnings are
735    // attributed to `file_path` (the file holding the link), so a rule ignored
736    // for that file must not emit them. This applies on every path; single-file
737    // rule filtering does not cover cross-file checks because they run over the
738    // config group's full rule set, and cross-file rules share link data.
739    let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
740
741    // Only check rules that need cross-file analysis
742    for rule in rules {
743        if rule.cross_file_scope() != CrossFileScope::Workspace {
744            continue;
745        }
746
747        if ignored_rules_for_file
748            .as_ref()
749            .is_some_and(|ignored| ignored.contains(rule.name()))
750        {
751            continue;
752        }
753
754        match time_function!(
755            "workspace: cross-file rule check",
756            rule.cross_file_check(file_path, file_index, workspace_index)
757        ) {
758            Ok(rule_warnings) => {
759                // Filter cross-file warnings based on inline config stored in file_index
760                let filtered: Vec<_> = rule_warnings
761                    .into_iter()
762                    .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
763                    .map(|mut warning| {
764                        // Apply severity override from config if present
765                        if let Some(cfg) = config
766                            && let Some(override_severity) = cfg.get_rule_severity(rule.name())
767                        {
768                            warning.severity = override_severity;
769                        }
770                        warning
771                    })
772                    .collect();
773                warnings.extend(filtered);
774            }
775            Err(e) => {
776                log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
777                return Err(e);
778            }
779        }
780    }
781
782    Ok(warnings)
783}
784
785/// Get the profiling report
786pub fn get_profiling_report() -> String {
787    profiling::get_report()
788}
789
790/// Reset the profiling data
791pub fn reset_profiling() {
792    profiling::reset()
793}
794
795/// Get regex cache statistics for performance monitoring
796pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
797    crate::utils::regex_cache::get_cache_stats()
798}
799
800#[cfg(test)]
801mod tests {
802    use super::*;
803    use crate::rule::Rule;
804    use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
805
806    #[test]
807    fn test_content_characteristics_analyze() {
808        // Test empty content
809        let chars = ContentCharacteristics::analyze("");
810        assert!(!chars.has_headings);
811        assert!(!chars.has_lists);
812        assert!(!chars.has_links);
813        assert!(!chars.has_code);
814        assert!(!chars.has_emphasis);
815        assert!(!chars.has_html);
816        assert!(!chars.has_tables);
817        assert!(!chars.has_blockquotes);
818        assert!(!chars.has_images);
819
820        // Test content with headings
821        let chars = ContentCharacteristics::analyze("# Heading");
822        assert!(chars.has_headings);
823
824        // Test setext headings
825        let chars = ContentCharacteristics::analyze("Heading\n=======");
826        assert!(chars.has_headings);
827
828        // Blockquoted ATX headings emit fragment anchors, so Heading-category
829        // rules (MD051/MD080) must run for blockquote-only documents.
830        let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
831        assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
832        let chars = ContentCharacteristics::analyze(">> # Nested");
833        assert!(
834            chars.has_headings,
835            "nested-blockquote ATX heading must set has_headings"
836        );
837        // A tab after the blockquote marker is also a valid heading
838        // (`parse_blockquote_prefix` accepts it).
839        let chars = ContentCharacteristics::analyze(">\t## Tabbed");
840        assert!(
841            chars.has_headings,
842            "tab-separated blockquote ATX heading must set has_headings"
843        );
844
845        // Test lists
846        let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
847        assert!(chars.has_lists);
848
849        // Test ordered lists
850        let chars = ContentCharacteristics::analyze("1. First\n2. Second");
851        assert!(chars.has_lists);
852
853        // Test links
854        let chars = ContentCharacteristics::analyze("[link](url)");
855        assert!(chars.has_links);
856
857        // Test URLs
858        let chars = ContentCharacteristics::analyze("Visit https://example.com");
859        assert!(chars.has_links);
860
861        // Test images
862        let chars = ContentCharacteristics::analyze("![alt text](image.png)");
863        assert!(chars.has_images);
864
865        // Test code
866        let chars = ContentCharacteristics::analyze("`inline code`");
867        assert!(chars.has_code);
868
869        let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
870        assert!(chars.has_code);
871
872        // Test indented code blocks (4 spaces)
873        let chars = ContentCharacteristics::analyze("Text\n\n    indented code\n\nMore text");
874        assert!(chars.has_code);
875
876        // Test tab-indented code blocks
877        let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
878        assert!(chars.has_code);
879
880        // Test mixed whitespace indented code (2 spaces + tab = 4 columns)
881        let chars = ContentCharacteristics::analyze("Text\n\n  \tmixed indent code\n\nMore text");
882        assert!(chars.has_code);
883
884        // Test 1 space + tab (also 4 columns due to tab expansion)
885        let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
886        assert!(chars.has_code);
887
888        // Test emphasis
889        let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
890        assert!(chars.has_emphasis);
891
892        // Test HTML
893        let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
894        assert!(chars.has_html);
895
896        // Test tables
897        let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
898        assert!(chars.has_tables);
899
900        // Test blockquotes
901        let chars = ContentCharacteristics::analyze("> Quote");
902        assert!(chars.has_blockquotes);
903
904        // Test mixed content
905        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)";
906        let chars = ContentCharacteristics::analyze(content);
907        assert!(chars.has_headings);
908        assert!(chars.has_lists);
909        assert!(chars.has_links);
910        assert!(chars.has_code);
911        assert!(chars.has_emphasis);
912        assert!(chars.has_html);
913        assert!(chars.has_tables);
914        assert!(chars.has_blockquotes);
915        assert!(chars.has_images);
916    }
917
918    #[test]
919    fn test_content_characteristics_parenthesized_ordered_list() {
920        assert!(ContentCharacteristics::analyze("1) first\n2) second").has_lists);
921        assert!(ContentCharacteristics::analyze("  1) indented first\n  2) second").has_lists);
922        assert!(ContentCharacteristics::analyze("> 1) quoted item").has_lists);
923    }
924
925    #[test]
926    fn test_content_characteristics_should_skip_rule() {
927        let chars = ContentCharacteristics {
928            has_headings: true,
929            has_lists: false,
930            has_links: true,
931            has_code: false,
932            has_emphasis: true,
933            has_html: false,
934            has_tables: true,
935            has_blockquotes: false,
936            has_images: false,
937        };
938
939        // Create test rules for different categories
940        let heading_rule = MD001HeadingIncrement::default();
941        assert!(!chars.should_skip_rule(&heading_rule));
942
943        let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
944        assert!(!chars.should_skip_rule(&trailing_spaces_rule)); // Whitespace rules always run
945
946        // Test skipping based on content
947        let chars_no_headings = ContentCharacteristics {
948            has_headings: false,
949            ..Default::default()
950        };
951        assert!(chars_no_headings.should_skip_rule(&heading_rule));
952    }
953
954    #[test]
955    fn test_lint_empty_content() {
956        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
957
958        let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
959        assert!(result.is_ok());
960        assert!(result.unwrap().is_empty());
961    }
962
963    #[test]
964    fn test_lint_with_violations() {
965        let content = "## Level 2\n#### Level 4"; // Skips level 3
966        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
967
968        let result = lint(
969            content,
970            &rules,
971            false,
972            crate::config::MarkdownFlavor::Standard,
973            None,
974            None,
975        );
976        assert!(result.is_ok());
977        let warnings = result.unwrap();
978        assert!(!warnings.is_empty());
979        // Check the rule field of LintWarning struct
980        assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
981    }
982
983    #[test]
984    fn test_lint_with_inline_disable() {
985        let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
986        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
987
988        let result = lint(
989            content,
990            &rules,
991            false,
992            crate::config::MarkdownFlavor::Standard,
993            None,
994            None,
995        );
996        assert!(result.is_ok());
997        let warnings = result.unwrap();
998        assert!(warnings.is_empty()); // Should be disabled by inline comment
999    }
1000
1001    #[test]
1002    fn test_lint_checks_setext_headings_the_content_prefilter_must_keep() {
1003        // Each document holds two headings with the same anchor and nothing else
1004        // that looks like a heading, so the heading rules run only if the
1005        // prefilter recognizes the underline.
1006        let rules: Vec<Box<dyn Rule>> = vec![Box::new(crate::rules::MD080HeadingAnchorCollision::new())];
1007        for content in [
1008            "Title\n-\n\ntitle\n-\n",
1009            "Title\n=\n\ntitle\n=\n",
1010            "> Title\n> ===\n\n> title\n> ===\n",
1011            "> Title\n> -\n\n> title\n> -\n",
1012        ] {
1013            let warnings = lint(
1014                content,
1015                &rules,
1016                false,
1017                crate::config::MarkdownFlavor::Standard,
1018                None,
1019                None,
1020            )
1021            .unwrap();
1022            let lines: Vec<_> = warnings.iter().map(|warning| warning.line).collect();
1023            assert_eq!(lines, [4], "{content:?}");
1024        }
1025    }
1026
1027    #[test]
1028    fn test_lint_rule_filtering() {
1029        // Content with no lists
1030        let content = "# Heading\nJust text";
1031        let rules: Vec<Box<dyn Rule>> = vec![
1032            Box::new(MD001HeadingIncrement::default()),
1033            // A list-related rule would be skipped
1034        ];
1035
1036        let result = lint(
1037            content,
1038            &rules,
1039            false,
1040            crate::config::MarkdownFlavor::Standard,
1041            None,
1042            None,
1043        );
1044        assert!(result.is_ok());
1045    }
1046
1047    #[test]
1048    fn test_get_profiling_report() {
1049        // Just test that it returns a string without panicking
1050        let report = get_profiling_report();
1051        assert!(!report.is_empty());
1052        assert!(report.contains("Profiling"));
1053    }
1054
1055    #[test]
1056    fn test_reset_profiling() {
1057        // Test that reset_profiling doesn't panic
1058        reset_profiling();
1059
1060        // After reset, report should indicate no measurements or profiling disabled
1061        let report = get_profiling_report();
1062        assert!(report.contains("disabled") || report.contains("no measurements"));
1063    }
1064
1065    #[test]
1066    fn test_get_regex_cache_stats() {
1067        let stats = get_regex_cache_stats();
1068        // Stats should be a valid HashMap (might be empty)
1069        assert!(stats.is_empty() || !stats.is_empty());
1070
1071        // If not empty, all values should be positive
1072        for count in stats.values() {
1073            assert!(*count > 0);
1074        }
1075    }
1076
1077    #[test]
1078    fn test_content_characteristics_edge_cases() {
1079        // A setext underline is any run of `=` or `-`, a single character
1080        // included, and one in a blockquote follows the quote's markers.
1081        for content in [
1082            "Title\n-",
1083            "Title\n=",
1084            "Title\n--",
1085            "> Title\n> ===",
1086            ">\tTitle\n>\t-",
1087            ">> Title\n>>-",
1088        ] {
1089            assert!(ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1090        }
1091        for content in ["> Prose\n>", "Prose\n> text", "Prose\n"] {
1092            assert!(!ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1093        }
1094
1095        // Test list detection - we now include potential list patterns (with or without space)
1096        // to support user-intention detection in MD030
1097        let chars = ContentCharacteristics::analyze("*emphasis*"); // Could be list or emphasis
1098        assert!(chars.has_lists); // Run list rules to be safe
1099
1100        let chars = ContentCharacteristics::analyze("1.Item"); // Could be list without space
1101        assert!(chars.has_lists); // Run list rules for user-intention detection
1102
1103        // Test blockquote must be at start of line
1104        let chars = ContentCharacteristics::analyze("text > not a quote");
1105        assert!(!chars.has_blockquotes);
1106    }
1107
1108    /// One document that draws a line-inserting fix from every rule known to
1109    /// write a bare `\n` into its replacement: MD071 (blank line after front
1110    /// matter), MD022 (blank lines around headings), MD032 (around lists),
1111    /// MD031 (around fences), MD014 (dollar prompts), MD058 (around tables) and
1112    /// MD047 (final newline).
1113    const LINE_INSERTING_FIXES: &str = "---\ntitle: x\n---\n# Heading\ntext\n## Sub\n- item\ntext\n```sh\n$ ls\n```\ntext\n| a | b |\n|---|---|\n| 1 | 2 |\ntext";
1114
1115    /// Every fix replacement (and additional edit) of every warning, keyed by rule.
1116    fn fix_replacements(content: &str) -> Vec<(String, String)> {
1117        let config = crate::config::Config::default();
1118        let rules = crate::rules::all_rules(&config);
1119        let warnings = lint(
1120            content,
1121            &rules,
1122            false,
1123            crate::config::MarkdownFlavor::Standard,
1124            None,
1125            Some(&config),
1126        )
1127        .unwrap();
1128        let mut out = Vec::new();
1129        for warning in warnings {
1130            let Some(fix) = warning.fix else { continue };
1131            let rule = warning.rule_name.clone().unwrap_or_default();
1132            let mut stack = vec![fix];
1133            while let Some(fix) = stack.pop() {
1134                out.push((rule.clone(), fix.replacement.clone()));
1135                stack.extend(fix.additional_edits);
1136            }
1137        }
1138        out
1139    }
1140
1141    fn has_bare_lf(text: &str) -> bool {
1142        let bytes = text.as_bytes();
1143        bytes
1144            .iter()
1145            .enumerate()
1146            .any(|(i, b)| *b == b'\n' && (i == 0 || bytes[i - 1] != b'\r'))
1147    }
1148
1149    #[test]
1150    fn fix_replacements_use_the_documents_crlf_line_ending() {
1151        let crlf = LINE_INSERTING_FIXES.replace('\n', "\r\n");
1152        let replacements = fix_replacements(&crlf);
1153
1154        let bare: Vec<_> = replacements.iter().filter(|(_, r)| has_bare_lf(r)).collect();
1155        assert!(bare.is_empty(), "bare LF in a fix for a CRLF document: {bare:?}");
1156
1157        // Positive control: the rules this document was written for did fire and
1158        // did insert a line ending, so the assertion above examined real fixes.
1159        let mut crlf_rules: Vec<_> = replacements
1160            .iter()
1161            .filter(|(_, r)| r.contains("\r\n"))
1162            .map(|(rule, _)| rule.as_str())
1163            .collect();
1164        crlf_rules.sort_unstable();
1165        crlf_rules.dedup();
1166        for rule in ["MD014", "MD022", "MD031", "MD032", "MD047", "MD058", "MD071"] {
1167            assert!(
1168                crlf_rules.contains(&rule),
1169                "{rule} inserted no CRLF line ending; got {crlf_rules:?}"
1170            );
1171        }
1172    }
1173
1174    #[test]
1175    fn fix_replacements_stay_lf_for_lf_and_mixed_documents() {
1176        // The same rules on the LF document write `\n`, untouched.
1177        let lf = fix_replacements(LINE_INSERTING_FIXES);
1178        assert!(lf.iter().any(|(_, r)| has_bare_lf(r)));
1179        assert!(!lf.iter().any(|(_, r)| r.contains('\r')));
1180
1181        // A document with mixed endings has no convention to conform to, so
1182        // its fixes are left exactly as the rules wrote them.
1183        let mixed = LINE_INSERTING_FIXES.replacen('\n', "\r\n", 1);
1184        assert_eq!(
1185            crate::utils::detect_line_ending_enum(&mixed),
1186            crate::utils::LineEnding::Mixed
1187        );
1188        let mixed = fix_replacements(&mixed);
1189        assert!(mixed.iter().any(|(_, r)| has_bare_lf(r)));
1190    }
1191}