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