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