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