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 embedded_lint;
55pub mod exit_codes;
56pub mod filtered_lines;
57pub mod fix_coordinator;
58pub mod inline_config;
59pub mod linguist_data;
60pub mod lint_context;
61pub mod markdownlint_config;
62pub mod profiling;
63pub mod rule;
64#[cfg(feature = "colored")]
65pub mod vscode;
66pub mod workspace_index;
67#[macro_use]
68pub mod rule_config;
69#[macro_use]
70pub mod rule_config_serde;
71pub mod rules;
72pub mod types;
73pub mod utils;
74
75// Native-only modules (require tokio, tower-lsp, etc.)
76#[cfg(feature = "native")]
77pub mod lsp;
78#[cfg(feature = "colored")]
79pub mod output;
80#[cfg(feature = "native")]
81pub mod performance;
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: line starts with digit, or blockquote line contains digit followed by period
158            if !chars.has_lists
159                && ((line.chars().next().is_some_and(|c| c.is_ascii_digit())
160                    && (line.contains(". ") || line.contains('.')))
161                    || (trimmed.starts_with('>')
162                        && trimmed.chars().any(|c| c.is_ascii_digit())
163                        && (trimmed.contains(". ") || trimmed.contains('.'))))
164            {
165                chars.has_lists = true;
166            }
167            if !chars.has_links
168                && (line.contains('[')
169                    || line.contains("http://")
170                    || line.contains("https://")
171                    || line.contains("ftp://")
172                    || line.contains("www."))
173            {
174                chars.has_links = true;
175            }
176            if !chars.has_images && line.contains("![") {
177                chars.has_images = true;
178            }
179            if !chars.has_code
180                && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
181            {
182                chars.has_code = true;
183            }
184            if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
185                chars.has_emphasis = true;
186            }
187            if !chars.has_html && line.contains('<') {
188                chars.has_html = true;
189            }
190            if !chars.has_tables && line.contains('|') {
191                chars.has_tables = true;
192            }
193            if !chars.has_blockquotes && line.starts_with('>') {
194                chars.has_blockquotes = true;
195            }
196        }
197
198        chars.has_headings = has_atx_heading || has_setext_heading;
199        chars
200    }
201
202    /// Check if a rule should be skipped based on content characteristics
203    fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
204        match rule.category() {
205            RuleCategory::Heading => !self.has_headings,
206            RuleCategory::List => !self.has_lists,
207            RuleCategory::Link => !self.has_links && !self.has_images,
208            RuleCategory::Image => !self.has_images,
209            RuleCategory::CodeBlock => !self.has_code,
210            RuleCategory::Html => !self.has_html,
211            RuleCategory::Emphasis => !self.has_emphasis,
212            RuleCategory::Blockquote => !self.has_blockquotes,
213            RuleCategory::Table => !self.has_tables,
214            // Always check these categories as they apply to all content
215            RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
216        }
217    }
218}
219
220/// Compute content hash for incremental indexing change detection
221///
222/// Uses blake3 for native builds (fast, cryptographic-strength hash)
223/// Falls back to std::hash for WASM builds
224#[cfg(feature = "native")]
225fn compute_content_hash(content: &str) -> String {
226    #[cfg(feature = "profiling")]
227    let start = std::time::Instant::now();
228    let hash = blake3::hash(content.as_bytes()).to_hex().to_string();
229    #[cfg(feature = "profiling")]
230    profiling::record_duration("index: hash content", start.elapsed());
231    hash
232}
233
234/// Compute content hash for WASM builds using std::hash
235#[cfg(not(feature = "native"))]
236fn compute_content_hash(content: &str) -> String {
237    use std::hash::{DefaultHasher, Hash, Hasher};
238    let mut hasher = DefaultHasher::new();
239    content.hash(&mut hasher);
240    format!("{:016x}", hasher.finish())
241}
242
243/// Lint a file against the given rules with intelligent rule filtering
244/// Assumes the provided `rules` vector contains the final,
245/// configured, and filtered set of rules to be executed.
246pub fn lint(
247    content: &str,
248    rules: &[Box<dyn Rule>],
249    verbose: bool,
250    flavor: crate::config::MarkdownFlavor,
251    source_file: Option<std::path::PathBuf>,
252    config: Option<&crate::config::Config>,
253) -> LintResult {
254    let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
255    result
256}
257
258/// Build FileIndex only (no linting) for cross-file analysis on cache hits
259///
260/// This is a lightweight function that only builds the FileIndex without running
261/// any rules. Used when we have a cache hit but still need the FileIndex for
262/// cross-file validation.
263///
264/// This avoids the overhead of re-running all rules when only the index data is needed.
265pub fn build_file_index_only(
266    content: &str,
267    rules: &[Box<dyn Rule>],
268    flavor: crate::config::MarkdownFlavor,
269    source_file: Option<std::path::PathBuf>,
270) -> crate::workspace_index::FileIndex {
271    // Compute content hash for change detection
272    let content_hash = compute_content_hash(content);
273    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
274
275    // Early return for empty content
276    if content.is_empty() {
277        return file_index;
278    }
279
280    // Parse LintContext once with the provided flavor
281    let lint_ctx = time_function!(
282        "index: parse lint context",
283        crate::lint_context::LintContext::new(content, flavor, source_file)
284    );
285
286    // Export inline disable data to the FileIndex so cross-file checks honor
287    // `<!-- rumdl-disable -->` blocks on the lint-cache fast path, exactly as
288    // lint_and_index does on the normal path.
289    let (file_disabled, persistent_transitions, line_disabled) = lint_ctx.inline_config().export_for_file_index();
290    file_index.file_disabled_rules = file_disabled;
291    file_index.persistent_transitions = persistent_transitions;
292    file_index.line_disabled_rules = line_disabled;
293
294    // Only call contribute_to_index for cross-file rules (no rule checking!)
295    time_section!("index: contribute cross-file data", {
296        for rule in rules {
297            if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
298                rule.contribute_to_index(&lint_ctx, &mut file_index);
299            }
300        }
301    });
302
303    file_index
304}
305
306/// Drop the warnings a document silences, and apply any configured severity override
307/// to the rest.
308///
309/// A warning is dropped when it sits in a kramdown extension block or when an inline
310/// comment disables its rule somewhere in its range. `suppressed`, when given,
311/// collects what the inline comments removed, for the rules that report on them. A
312/// kramdown extension block is not an inline comment, so what it drops is left out.
313fn retain_reportable_warnings(
314    lint_ctx: &crate::lint_context::LintContext,
315    config: Option<&crate::config::Config>,
316    rule_name: &str,
317    rule_warnings: Vec<crate::rule::LintWarning>,
318    mut suppressed: Option<&mut Vec<crate::rule::SuppressedWarning>>,
319) -> Vec<crate::rule::LintWarning> {
320    let inline_config = lint_ctx.inline_config();
321    let mut kept = Vec::with_capacity(rule_warnings.len());
322
323    for mut warning in rule_warnings {
324        if lint_ctx
325            .line_info(warning.line)
326            .is_some_and(|info| info.in_kramdown_extension_block)
327        {
328            continue;
329        }
330
331        // Use the warning's rule_name if available, otherwise use the rule's name
332        let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule_name);
333
334        // Extract the base rule name for sub-rules like "MD029-style" -> "MD029"
335        let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
336            &rule_name_to_check[..dash_pos]
337        } else {
338            rule_name_to_check
339        };
340
341        // Check if the rule is disabled at any line in the warning's range.
342        // Multi-line warnings (e.g., reflow) report on the first line,
343        // but inline disable comments may appear later in the range.
344        // Guard: if end_line < line (e.g., end_line=0), fall back to
345        // checking only the warning's line to match original behavior.
346        let end = if warning.end_line >= warning.line {
347            warning.end_line
348        } else {
349            warning.line
350        };
351        let disabled_at = (warning.line..=end).find_map(|line| {
352            inline_config
353                .disabling_layer(base_rule_name, line)
354                .map(|layer| (line, layer))
355        });
356        if let Some((line, layer)) = disabled_at {
357            if let Some(record) = suppressed.as_deref_mut() {
358                record.push(crate::rule::SuppressedWarning {
359                    rule_name: base_rule_name.to_string(),
360                    line,
361                    layer,
362                });
363            }
364            continue;
365        }
366
367        // Apply severity override from config if present
368        if let Some(cfg) = config
369            && let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check)
370        {
371            warning.severity = override_severity;
372        }
373
374        kept.push(warning);
375    }
376
377    kept
378}
379
380/// Lint a file and contribute to workspace index for cross-file analysis
381///
382/// This variant performs linting and optionally populates a `FileIndex` with data
383/// needed for cross-file validation. The FileIndex is populated during linting,
384/// avoiding duplicate parsing.
385///
386/// Returns: (warnings, FileIndex) - the FileIndex contains headings/links for cross-file rules
387#[cfg_attr(test, allow(unused_variables))]
388pub fn lint_and_index(
389    content: &str,
390    rules: &[Box<dyn Rule>],
391    verbose: bool,
392    flavor: crate::config::MarkdownFlavor,
393    source_file: Option<std::path::PathBuf>,
394    config: Option<&crate::config::Config>,
395) -> (LintResult, crate::workspace_index::FileIndex) {
396    let mut warnings = Vec::new();
397    // Compute content hash for change detection
398    let content_hash = compute_content_hash(content);
399    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
400
401    // Early return for empty content
402    if content.is_empty() {
403        return (Ok(warnings), file_index);
404    }
405
406    // The rules `per-file-ignores` takes away for this file. It decides what this
407    // file REPORTS, and nothing else: the index contribution at the end of this
408    // function deliberately keeps running every cross-file rule, because a file's
409    // headings and links belong to the workspace rather than to its own report.
410    // Dropping a rule from the index instead would break the links pointing HERE,
411    // in files that never named it.
412    let ignored_for_file = match (config, source_file.as_deref()) {
413        (Some(cfg), Some(path)) => cfg.get_ignored_rules_for_file(path),
414        _ => std::collections::HashSet::new(),
415    };
416
417    // Parse LintContext once (includes inline config parsing)
418    let lint_ctx = time_function!(
419        "lint: parse lint context",
420        crate::lint_context::LintContext::new(content, flavor, source_file)
421    );
422    let inline_config = lint_ctx.inline_config();
423
424    // Export inline config data to FileIndex for cross-file rule filtering
425    let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
426    file_index.file_disabled_rules = file_disabled;
427    file_index.persistent_transitions = persistent_transitions;
428    file_index.line_disabled_rules = line_disabled;
429
430    // Analyze content characteristics for rule filtering
431    let characteristics = time_function!(
432        "lint: analyze content characteristics",
433        ContentCharacteristics::analyze(content)
434    );
435
436    // Filter rules based on per-file-ignores and content characteristics
437    let applicable_rules: Vec<_> = rules
438        .iter()
439        .filter(|rule| !ignored_for_file.contains(rule.name()))
440        .filter(|rule| !(rule.skippable_by_category() && characteristics.should_skip_rule(rule.as_ref())))
441        .collect();
442
443    // Calculate skipped rules count before consuming applicable_rules
444    #[cfg(not(test))]
445    let total_rules = rules.len();
446    #[cfg(not(test))]
447    let applicable_count = applicable_rules.len();
448
449    #[cfg(not(target_arch = "wasm32"))]
450    let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
451
452    // Automatic inline config support: merge inline overrides into config once,
453    // then recreate only the affected rules. Works for ALL rules without per-rule changes.
454    let inline_overrides = inline_config.get_all_rule_configs();
455    let merged_config = if !inline_overrides.is_empty() {
456        config.map(|c| c.merge_with_inline_config(inline_config))
457    } else {
458        None
459    };
460    let effective_config = merged_config.as_ref().or(config);
461
462    // Cache recreated rules for rules with inline overrides
463    let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
464        std::collections::HashMap::new();
465
466    // Pre-create rules that have inline config overrides
467    if let Some(cfg) = effective_config {
468        for rule_name in inline_overrides.keys() {
469            if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
470                recreated_rules.insert(rule_name.clone(), recreated);
471            }
472        }
473    }
474
475    // A rule reporting on the run's inline disable comments needs to know what they
476    // removed, which costs a record per suppressed warning, so it is only kept when
477    // such a rule is going to read it.
478    let suppression_observers: Vec<_> = applicable_rules
479        .iter()
480        .filter(|rule| rule.observes_suppressions() && !rule.should_skip(&lint_ctx))
481        .collect();
482    let mut suppressed = Vec::new();
483
484    {
485        let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
486        for rule in &applicable_rules {
487            #[cfg(not(target_arch = "wasm32"))]
488            let rule_start = Instant::now();
489
490            // Skip rules that indicate they should be skipped (opt-in rules, content-based skipping)
491            if rule.should_skip(&lint_ctx) {
492                continue;
493            }
494
495            // Use recreated rule if inline config overrides exist for this rule
496            let effective_rule: &dyn crate::rule::Rule = recreated_rules
497                .get(rule.name())
498                .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
499
500            // Run single-file check with the effective rule (possibly with inline config applied)
501            let result = effective_rule.check(&lint_ctx);
502
503            match result {
504                Ok(rule_warnings) => {
505                    let record = if suppression_observers.is_empty() {
506                        None
507                    } else {
508                        Some(&mut suppressed)
509                    };
510                    let filtered_warnings =
511                        retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, record);
512                    warnings.extend(filtered_warnings);
513                }
514                Err(e) => {
515                    log::error!("Error checking rule {}: {}", rule.name(), e);
516                    return (Err(e), file_index);
517                }
518            }
519
520            #[cfg(not(target_arch = "wasm32"))]
521            {
522                let rule_duration = rule_start.elapsed();
523                if profile_rules {
524                    eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
525                }
526
527                #[cfg(not(test))]
528                if verbose && rule_duration.as_millis() > 500 {
529                    log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
530                }
531            }
532        }
533    }
534
535    // Report on the inline disable comments, now that every single-file rule has run
536    // and the suppressions are complete.
537    if !suppression_observers.is_empty() {
538        let _timer = profiling::ScopedTimer::new("lint: run suppression rules");
539
540        // A workspace-scope rule has its warnings filtered after this point, and for a
541        // single-file run not at all, so its findings never reach the report and
542        // nothing can be concluded about a comment naming it. A rule this file
543        // ignores does not report either, for the same reason.
544        let report = crate::rule::SuppressionReport {
545            suppressed,
546            judged_rules: rules
547                .iter()
548                .filter(|rule| rule.cross_file_scope() != crate::rule::CrossFileScope::Workspace)
549                .filter(|rule| !ignored_for_file.contains(rule.name()))
550                .map(|rule| rule.name().to_string())
551                .collect(),
552        };
553
554        for rule in &suppression_observers {
555            match rule.check_suppressions(&lint_ctx, &report) {
556                Ok(rule_warnings) => {
557                    let filtered_warnings =
558                        retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, None);
559                    warnings.extend(filtered_warnings);
560                }
561                Err(e) => {
562                    log::error!("Error checking rule {}: {}", rule.name(), e);
563                    return (Err(e), file_index);
564                }
565            }
566        }
567    }
568
569    // Contribute to index for cross-file rules (done after all rules checked)
570    // NOTE: We iterate over ALL rules (not just applicable_rules) because cross-file
571    // rules need to extract data from every file in the workspace, regardless of whether
572    // that file has content that would trigger the rule, and regardless of what this
573    // file's own configuration reports. For example, MD051 needs to index headings from
574    // files that have no links (like target.md) so that links FROM other files TO those
575    // headings can be validated - including from a file that ignores MD051 itself.
576    time_section!("lint: contribute cross-file data", {
577        for rule in rules {
578            if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
579                rule.contribute_to_index(&lint_ctx, &mut file_index);
580            }
581        }
582    });
583
584    #[cfg(not(test))]
585    if verbose {
586        let skipped_rules = total_rules - applicable_count;
587        if skipped_rules > 0 {
588            log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
589        }
590    }
591
592    (Ok(warnings), file_index)
593}
594
595/// Run cross-file checks for rules that need workspace-wide validation
596///
597/// This should be called after all files have been linted and the WorkspaceIndex
598/// has been built from the accumulated FileIndex data.
599///
600/// Note: This takes the FileIndex instead of content to avoid re-parsing each file.
601/// The FileIndex was already populated during contribute_to_index in the linting phase.
602///
603/// Rules can use workspace_index methods for cross-file validation:
604/// - `get_file(path)` - to look up headings in target files (for MD051)
605///
606/// Returns additional warnings from cross-file validation.
607pub fn run_cross_file_checks(
608    file_path: &std::path::Path,
609    file_index: &crate::workspace_index::FileIndex,
610    rules: &[Box<dyn Rule>],
611    workspace_index: &crate::workspace_index::WorkspaceIndex,
612    config: Option<&crate::config::Config>,
613) -> LintResult {
614    use crate::rule::CrossFileScope;
615
616    let mut warnings = Vec::new();
617
618    // Honor `per-file-ignores` for cross-file rules. Cross-file warnings are
619    // attributed to `file_path` (the file holding the link), so a rule ignored
620    // for that file must not emit them. This applies on every path; single-file
621    // rule filtering does not cover cross-file checks because they run over the
622    // config group's full rule set, and cross-file rules share link data.
623    let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
624
625    // Only check rules that need cross-file analysis
626    for rule in rules {
627        if rule.cross_file_scope() != CrossFileScope::Workspace {
628            continue;
629        }
630
631        if ignored_rules_for_file
632            .as_ref()
633            .is_some_and(|ignored| ignored.contains(rule.name()))
634        {
635            continue;
636        }
637
638        match time_function!(
639            "workspace: cross-file rule check",
640            rule.cross_file_check(file_path, file_index, workspace_index)
641        ) {
642            Ok(rule_warnings) => {
643                // Filter cross-file warnings based on inline config stored in file_index
644                let filtered: Vec<_> = rule_warnings
645                    .into_iter()
646                    .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
647                    .map(|mut warning| {
648                        // Apply severity override from config if present
649                        if let Some(cfg) = config
650                            && let Some(override_severity) = cfg.get_rule_severity(rule.name())
651                        {
652                            warning.severity = override_severity;
653                        }
654                        warning
655                    })
656                    .collect();
657                warnings.extend(filtered);
658            }
659            Err(e) => {
660                log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
661                return Err(e);
662            }
663        }
664    }
665
666    Ok(warnings)
667}
668
669/// Get the profiling report
670pub fn get_profiling_report() -> String {
671    profiling::get_report()
672}
673
674/// Reset the profiling data
675pub fn reset_profiling() {
676    profiling::reset()
677}
678
679/// Get regex cache statistics for performance monitoring
680pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
681    crate::utils::regex_cache::get_cache_stats()
682}
683
684#[cfg(test)]
685mod tests {
686    use super::*;
687    use crate::rule::Rule;
688    use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
689
690    #[test]
691    fn test_content_characteristics_analyze() {
692        // Test empty content
693        let chars = ContentCharacteristics::analyze("");
694        assert!(!chars.has_headings);
695        assert!(!chars.has_lists);
696        assert!(!chars.has_links);
697        assert!(!chars.has_code);
698        assert!(!chars.has_emphasis);
699        assert!(!chars.has_html);
700        assert!(!chars.has_tables);
701        assert!(!chars.has_blockquotes);
702        assert!(!chars.has_images);
703
704        // Test content with headings
705        let chars = ContentCharacteristics::analyze("# Heading");
706        assert!(chars.has_headings);
707
708        // Test setext headings
709        let chars = ContentCharacteristics::analyze("Heading\n=======");
710        assert!(chars.has_headings);
711
712        // Blockquoted ATX headings emit fragment anchors, so Heading-category
713        // rules (MD051/MD080) must run for blockquote-only documents.
714        let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
715        assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
716        let chars = ContentCharacteristics::analyze(">> # Nested");
717        assert!(
718            chars.has_headings,
719            "nested-blockquote ATX heading must set has_headings"
720        );
721        // A tab after the blockquote marker is also a valid heading
722        // (`parse_blockquote_prefix` accepts it).
723        let chars = ContentCharacteristics::analyze(">\t## Tabbed");
724        assert!(
725            chars.has_headings,
726            "tab-separated blockquote ATX heading must set has_headings"
727        );
728
729        // Test lists
730        let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
731        assert!(chars.has_lists);
732
733        // Test ordered lists
734        let chars = ContentCharacteristics::analyze("1. First\n2. Second");
735        assert!(chars.has_lists);
736
737        // Test links
738        let chars = ContentCharacteristics::analyze("[link](url)");
739        assert!(chars.has_links);
740
741        // Test URLs
742        let chars = ContentCharacteristics::analyze("Visit https://example.com");
743        assert!(chars.has_links);
744
745        // Test images
746        let chars = ContentCharacteristics::analyze("![alt text](image.png)");
747        assert!(chars.has_images);
748
749        // Test code
750        let chars = ContentCharacteristics::analyze("`inline code`");
751        assert!(chars.has_code);
752
753        let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
754        assert!(chars.has_code);
755
756        // Test indented code blocks (4 spaces)
757        let chars = ContentCharacteristics::analyze("Text\n\n    indented code\n\nMore text");
758        assert!(chars.has_code);
759
760        // Test tab-indented code blocks
761        let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
762        assert!(chars.has_code);
763
764        // Test mixed whitespace indented code (2 spaces + tab = 4 columns)
765        let chars = ContentCharacteristics::analyze("Text\n\n  \tmixed indent code\n\nMore text");
766        assert!(chars.has_code);
767
768        // Test 1 space + tab (also 4 columns due to tab expansion)
769        let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
770        assert!(chars.has_code);
771
772        // Test emphasis
773        let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
774        assert!(chars.has_emphasis);
775
776        // Test HTML
777        let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
778        assert!(chars.has_html);
779
780        // Test tables
781        let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
782        assert!(chars.has_tables);
783
784        // Test blockquotes
785        let chars = ContentCharacteristics::analyze("> Quote");
786        assert!(chars.has_blockquotes);
787
788        // Test mixed content
789        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)";
790        let chars = ContentCharacteristics::analyze(content);
791        assert!(chars.has_headings);
792        assert!(chars.has_lists);
793        assert!(chars.has_links);
794        assert!(chars.has_code);
795        assert!(chars.has_emphasis);
796        assert!(chars.has_html);
797        assert!(chars.has_tables);
798        assert!(chars.has_blockquotes);
799        assert!(chars.has_images);
800    }
801
802    #[test]
803    fn test_content_characteristics_should_skip_rule() {
804        let chars = ContentCharacteristics {
805            has_headings: true,
806            has_lists: false,
807            has_links: true,
808            has_code: false,
809            has_emphasis: true,
810            has_html: false,
811            has_tables: true,
812            has_blockquotes: false,
813            has_images: false,
814        };
815
816        // Create test rules for different categories
817        let heading_rule = MD001HeadingIncrement::default();
818        assert!(!chars.should_skip_rule(&heading_rule));
819
820        let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
821        assert!(!chars.should_skip_rule(&trailing_spaces_rule)); // Whitespace rules always run
822
823        // Test skipping based on content
824        let chars_no_headings = ContentCharacteristics {
825            has_headings: false,
826            ..Default::default()
827        };
828        assert!(chars_no_headings.should_skip_rule(&heading_rule));
829    }
830
831    #[test]
832    fn test_lint_empty_content() {
833        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
834
835        let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
836        assert!(result.is_ok());
837        assert!(result.unwrap().is_empty());
838    }
839
840    #[test]
841    fn test_lint_with_violations() {
842        let content = "## Level 2\n#### Level 4"; // Skips level 3
843        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
844
845        let result = lint(
846            content,
847            &rules,
848            false,
849            crate::config::MarkdownFlavor::Standard,
850            None,
851            None,
852        );
853        assert!(result.is_ok());
854        let warnings = result.unwrap();
855        assert!(!warnings.is_empty());
856        // Check the rule field of LintWarning struct
857        assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
858    }
859
860    #[test]
861    fn test_lint_with_inline_disable() {
862        let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
863        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
864
865        let result = lint(
866            content,
867            &rules,
868            false,
869            crate::config::MarkdownFlavor::Standard,
870            None,
871            None,
872        );
873        assert!(result.is_ok());
874        let warnings = result.unwrap();
875        assert!(warnings.is_empty()); // Should be disabled by inline comment
876    }
877
878    #[test]
879    fn test_lint_rule_filtering() {
880        // Content with no lists
881        let content = "# Heading\nJust text";
882        let rules: Vec<Box<dyn Rule>> = vec![
883            Box::new(MD001HeadingIncrement::default()),
884            // A list-related rule would be skipped
885        ];
886
887        let result = lint(
888            content,
889            &rules,
890            false,
891            crate::config::MarkdownFlavor::Standard,
892            None,
893            None,
894        );
895        assert!(result.is_ok());
896    }
897
898    #[test]
899    fn test_get_profiling_report() {
900        // Just test that it returns a string without panicking
901        let report = get_profiling_report();
902        assert!(!report.is_empty());
903        assert!(report.contains("Profiling"));
904    }
905
906    #[test]
907    fn test_reset_profiling() {
908        // Test that reset_profiling doesn't panic
909        reset_profiling();
910
911        // After reset, report should indicate no measurements or profiling disabled
912        let report = get_profiling_report();
913        assert!(report.contains("disabled") || report.contains("no measurements"));
914    }
915
916    #[test]
917    fn test_get_regex_cache_stats() {
918        let stats = get_regex_cache_stats();
919        // Stats should be a valid HashMap (might be empty)
920        assert!(stats.is_empty() || !stats.is_empty());
921
922        // If not empty, all values should be positive
923        for count in stats.values() {
924            assert!(*count > 0);
925        }
926    }
927
928    #[test]
929    fn test_content_characteristics_edge_cases() {
930        // Test setext heading edge case
931        let chars = ContentCharacteristics::analyze("-"); // Single dash, not a heading
932        assert!(!chars.has_headings);
933
934        let chars = ContentCharacteristics::analyze("--"); // Two dashes, valid setext
935        assert!(chars.has_headings);
936
937        // Test list detection - we now include potential list patterns (with or without space)
938        // to support user-intention detection in MD030
939        let chars = ContentCharacteristics::analyze("*emphasis*"); // Could be list or emphasis
940        assert!(chars.has_lists); // Run list rules to be safe
941
942        let chars = ContentCharacteristics::analyze("1.Item"); // Could be list without space
943        assert!(chars.has_lists); // Run list rules for user-intention detection
944
945        // Test blockquote must be at start of line
946        let chars = ContentCharacteristics::analyze("text > not a quote");
947        assert!(!chars.has_blockquotes);
948    }
949}