Skip to main content

rumdl_lib/
lib.rs

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