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    // Parse LintContext once (includes inline config parsing)
407    let lint_ctx = time_function!(
408        "lint: parse lint context",
409        crate::lint_context::LintContext::new(content, flavor, source_file)
410    );
411    let inline_config = lint_ctx.inline_config();
412
413    // Export inline config data to FileIndex for cross-file rule filtering
414    let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
415    file_index.file_disabled_rules = file_disabled;
416    file_index.persistent_transitions = persistent_transitions;
417    file_index.line_disabled_rules = line_disabled;
418
419    // Analyze content characteristics for rule filtering
420    let characteristics = time_function!(
421        "lint: analyze content characteristics",
422        ContentCharacteristics::analyze(content)
423    );
424
425    // Filter rules based on content characteristics
426    let applicable_rules: Vec<_> = rules
427        .iter()
428        .filter(|rule| !(rule.skippable_by_category() && characteristics.should_skip_rule(rule.as_ref())))
429        .collect();
430
431    // Calculate skipped rules count before consuming applicable_rules
432    #[cfg(not(test))]
433    let total_rules = rules.len();
434    #[cfg(not(test))]
435    let applicable_count = applicable_rules.len();
436
437    #[cfg(not(target_arch = "wasm32"))]
438    let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
439
440    // Automatic inline config support: merge inline overrides into config once,
441    // then recreate only the affected rules. Works for ALL rules without per-rule changes.
442    let inline_overrides = inline_config.get_all_rule_configs();
443    let merged_config = if !inline_overrides.is_empty() {
444        config.map(|c| c.merge_with_inline_config(inline_config))
445    } else {
446        None
447    };
448    let effective_config = merged_config.as_ref().or(config);
449
450    // Cache recreated rules for rules with inline overrides
451    let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
452        std::collections::HashMap::new();
453
454    // Pre-create rules that have inline config overrides
455    if let Some(cfg) = effective_config {
456        for rule_name in inline_overrides.keys() {
457            if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
458                recreated_rules.insert(rule_name.clone(), recreated);
459            }
460        }
461    }
462
463    // A rule reporting on the run's inline disable comments needs to know what they
464    // removed, which costs a record per suppressed warning, so it is only kept when
465    // such a rule is going to read it.
466    let suppression_observers: Vec<_> = applicable_rules
467        .iter()
468        .filter(|rule| rule.observes_suppressions() && !rule.should_skip(&lint_ctx))
469        .collect();
470    let mut suppressed = Vec::new();
471
472    {
473        let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
474        for rule in &applicable_rules {
475            #[cfg(not(target_arch = "wasm32"))]
476            let rule_start = Instant::now();
477
478            // Skip rules that indicate they should be skipped (opt-in rules, content-based skipping)
479            if rule.should_skip(&lint_ctx) {
480                continue;
481            }
482
483            // Use recreated rule if inline config overrides exist for this rule
484            let effective_rule: &dyn crate::rule::Rule = recreated_rules
485                .get(rule.name())
486                .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
487
488            // Run single-file check with the effective rule (possibly with inline config applied)
489            let result = effective_rule.check(&lint_ctx);
490
491            match result {
492                Ok(rule_warnings) => {
493                    let record = if suppression_observers.is_empty() {
494                        None
495                    } else {
496                        Some(&mut suppressed)
497                    };
498                    let filtered_warnings =
499                        retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, record);
500                    warnings.extend(filtered_warnings);
501                }
502                Err(e) => {
503                    log::error!("Error checking rule {}: {}", rule.name(), e);
504                    return (Err(e), file_index);
505                }
506            }
507
508            #[cfg(not(target_arch = "wasm32"))]
509            {
510                let rule_duration = rule_start.elapsed();
511                if profile_rules {
512                    eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
513                }
514
515                #[cfg(not(test))]
516                if verbose && rule_duration.as_millis() > 500 {
517                    log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
518                }
519            }
520        }
521    }
522
523    // Report on the inline disable comments, now that every single-file rule has run
524    // and the suppressions are complete.
525    if !suppression_observers.is_empty() {
526        let _timer = profiling::ScopedTimer::new("lint: run suppression rules");
527
528        // A workspace-scope rule has its warnings filtered after this point, and for a
529        // single-file run not at all, so its findings never reach the report and
530        // nothing can be concluded about a comment naming it.
531        let report = crate::rule::SuppressionReport {
532            suppressed,
533            judged_rules: rules
534                .iter()
535                .filter(|rule| rule.cross_file_scope() != crate::rule::CrossFileScope::Workspace)
536                .map(|rule| rule.name().to_string())
537                .collect(),
538        };
539
540        for rule in &suppression_observers {
541            match rule.check_suppressions(&lint_ctx, &report) {
542                Ok(rule_warnings) => {
543                    let filtered_warnings =
544                        retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, None);
545                    warnings.extend(filtered_warnings);
546                }
547                Err(e) => {
548                    log::error!("Error checking rule {}: {}", rule.name(), e);
549                    return (Err(e), file_index);
550                }
551            }
552        }
553    }
554
555    // Contribute to index for cross-file rules (done after all rules checked)
556    // NOTE: We iterate over ALL rules (not just applicable_rules) because cross-file
557    // rules need to extract data from every file in the workspace, regardless of whether
558    // that file has content that would trigger the rule. For example, MD051 needs to
559    // index headings from files that have no links (like target.md) so that links
560    // FROM other files TO those headings can be validated.
561    time_section!("lint: contribute cross-file data", {
562        for rule in rules {
563            if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
564                rule.contribute_to_index(&lint_ctx, &mut file_index);
565            }
566        }
567    });
568
569    #[cfg(not(test))]
570    if verbose {
571        let skipped_rules = total_rules - applicable_count;
572        if skipped_rules > 0 {
573            log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
574        }
575    }
576
577    (Ok(warnings), file_index)
578}
579
580/// Run cross-file checks for rules that need workspace-wide validation
581///
582/// This should be called after all files have been linted and the WorkspaceIndex
583/// has been built from the accumulated FileIndex data.
584///
585/// Note: This takes the FileIndex instead of content to avoid re-parsing each file.
586/// The FileIndex was already populated during contribute_to_index in the linting phase.
587///
588/// Rules can use workspace_index methods for cross-file validation:
589/// - `get_file(path)` - to look up headings in target files (for MD051)
590///
591/// Returns additional warnings from cross-file validation.
592pub fn run_cross_file_checks(
593    file_path: &std::path::Path,
594    file_index: &crate::workspace_index::FileIndex,
595    rules: &[Box<dyn Rule>],
596    workspace_index: &crate::workspace_index::WorkspaceIndex,
597    config: Option<&crate::config::Config>,
598) -> LintResult {
599    use crate::rule::CrossFileScope;
600
601    let mut warnings = Vec::new();
602
603    // Honor `per-file-ignores` for cross-file rules. Cross-file warnings are
604    // attributed to `file_path` (the file holding the link), so a rule ignored
605    // for that file must not emit them. This applies on every path; single-file
606    // rule filtering does not cover cross-file checks because they run over the
607    // config group's full rule set, and cross-file rules share link data.
608    let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
609
610    // Only check rules that need cross-file analysis
611    for rule in rules {
612        if rule.cross_file_scope() != CrossFileScope::Workspace {
613            continue;
614        }
615
616        if ignored_rules_for_file
617            .as_ref()
618            .is_some_and(|ignored| ignored.contains(rule.name()))
619        {
620            continue;
621        }
622
623        match time_function!(
624            "workspace: cross-file rule check",
625            rule.cross_file_check(file_path, file_index, workspace_index)
626        ) {
627            Ok(rule_warnings) => {
628                // Filter cross-file warnings based on inline config stored in file_index
629                let filtered: Vec<_> = rule_warnings
630                    .into_iter()
631                    .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
632                    .map(|mut warning| {
633                        // Apply severity override from config if present
634                        if let Some(cfg) = config
635                            && let Some(override_severity) = cfg.get_rule_severity(rule.name())
636                        {
637                            warning.severity = override_severity;
638                        }
639                        warning
640                    })
641                    .collect();
642                warnings.extend(filtered);
643            }
644            Err(e) => {
645                log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
646                return Err(e);
647            }
648        }
649    }
650
651    Ok(warnings)
652}
653
654/// Get the profiling report
655pub fn get_profiling_report() -> String {
656    profiling::get_report()
657}
658
659/// Reset the profiling data
660pub fn reset_profiling() {
661    profiling::reset()
662}
663
664/// Get regex cache statistics for performance monitoring
665pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
666    crate::utils::regex_cache::get_cache_stats()
667}
668
669#[cfg(test)]
670mod tests {
671    use super::*;
672    use crate::rule::Rule;
673    use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
674
675    #[test]
676    fn test_content_characteristics_analyze() {
677        // Test empty content
678        let chars = ContentCharacteristics::analyze("");
679        assert!(!chars.has_headings);
680        assert!(!chars.has_lists);
681        assert!(!chars.has_links);
682        assert!(!chars.has_code);
683        assert!(!chars.has_emphasis);
684        assert!(!chars.has_html);
685        assert!(!chars.has_tables);
686        assert!(!chars.has_blockquotes);
687        assert!(!chars.has_images);
688
689        // Test content with headings
690        let chars = ContentCharacteristics::analyze("# Heading");
691        assert!(chars.has_headings);
692
693        // Test setext headings
694        let chars = ContentCharacteristics::analyze("Heading\n=======");
695        assert!(chars.has_headings);
696
697        // Blockquoted ATX headings emit fragment anchors, so Heading-category
698        // rules (MD051/MD080) must run for blockquote-only documents.
699        let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
700        assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
701        let chars = ContentCharacteristics::analyze(">> # Nested");
702        assert!(
703            chars.has_headings,
704            "nested-blockquote ATX heading must set has_headings"
705        );
706        // A tab after the blockquote marker is also a valid heading
707        // (`parse_blockquote_prefix` accepts it).
708        let chars = ContentCharacteristics::analyze(">\t## Tabbed");
709        assert!(
710            chars.has_headings,
711            "tab-separated blockquote ATX heading must set has_headings"
712        );
713
714        // Test lists
715        let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
716        assert!(chars.has_lists);
717
718        // Test ordered lists
719        let chars = ContentCharacteristics::analyze("1. First\n2. Second");
720        assert!(chars.has_lists);
721
722        // Test links
723        let chars = ContentCharacteristics::analyze("[link](url)");
724        assert!(chars.has_links);
725
726        // Test URLs
727        let chars = ContentCharacteristics::analyze("Visit https://example.com");
728        assert!(chars.has_links);
729
730        // Test images
731        let chars = ContentCharacteristics::analyze("![alt text](image.png)");
732        assert!(chars.has_images);
733
734        // Test code
735        let chars = ContentCharacteristics::analyze("`inline code`");
736        assert!(chars.has_code);
737
738        let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
739        assert!(chars.has_code);
740
741        // Test indented code blocks (4 spaces)
742        let chars = ContentCharacteristics::analyze("Text\n\n    indented code\n\nMore text");
743        assert!(chars.has_code);
744
745        // Test tab-indented code blocks
746        let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
747        assert!(chars.has_code);
748
749        // Test mixed whitespace indented code (2 spaces + tab = 4 columns)
750        let chars = ContentCharacteristics::analyze("Text\n\n  \tmixed indent code\n\nMore text");
751        assert!(chars.has_code);
752
753        // Test 1 space + tab (also 4 columns due to tab expansion)
754        let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
755        assert!(chars.has_code);
756
757        // Test emphasis
758        let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
759        assert!(chars.has_emphasis);
760
761        // Test HTML
762        let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
763        assert!(chars.has_html);
764
765        // Test tables
766        let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
767        assert!(chars.has_tables);
768
769        // Test blockquotes
770        let chars = ContentCharacteristics::analyze("> Quote");
771        assert!(chars.has_blockquotes);
772
773        // Test mixed content
774        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)";
775        let chars = ContentCharacteristics::analyze(content);
776        assert!(chars.has_headings);
777        assert!(chars.has_lists);
778        assert!(chars.has_links);
779        assert!(chars.has_code);
780        assert!(chars.has_emphasis);
781        assert!(chars.has_html);
782        assert!(chars.has_tables);
783        assert!(chars.has_blockquotes);
784        assert!(chars.has_images);
785    }
786
787    #[test]
788    fn test_content_characteristics_should_skip_rule() {
789        let chars = ContentCharacteristics {
790            has_headings: true,
791            has_lists: false,
792            has_links: true,
793            has_code: false,
794            has_emphasis: true,
795            has_html: false,
796            has_tables: true,
797            has_blockquotes: false,
798            has_images: false,
799        };
800
801        // Create test rules for different categories
802        let heading_rule = MD001HeadingIncrement::default();
803        assert!(!chars.should_skip_rule(&heading_rule));
804
805        let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
806        assert!(!chars.should_skip_rule(&trailing_spaces_rule)); // Whitespace rules always run
807
808        // Test skipping based on content
809        let chars_no_headings = ContentCharacteristics {
810            has_headings: false,
811            ..Default::default()
812        };
813        assert!(chars_no_headings.should_skip_rule(&heading_rule));
814    }
815
816    #[test]
817    fn test_lint_empty_content() {
818        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
819
820        let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
821        assert!(result.is_ok());
822        assert!(result.unwrap().is_empty());
823    }
824
825    #[test]
826    fn test_lint_with_violations() {
827        let content = "## Level 2\n#### Level 4"; // Skips level 3
828        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
829
830        let result = lint(
831            content,
832            &rules,
833            false,
834            crate::config::MarkdownFlavor::Standard,
835            None,
836            None,
837        );
838        assert!(result.is_ok());
839        let warnings = result.unwrap();
840        assert!(!warnings.is_empty());
841        // Check the rule field of LintWarning struct
842        assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
843    }
844
845    #[test]
846    fn test_lint_with_inline_disable() {
847        let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
848        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
849
850        let result = lint(
851            content,
852            &rules,
853            false,
854            crate::config::MarkdownFlavor::Standard,
855            None,
856            None,
857        );
858        assert!(result.is_ok());
859        let warnings = result.unwrap();
860        assert!(warnings.is_empty()); // Should be disabled by inline comment
861    }
862
863    #[test]
864    fn test_lint_rule_filtering() {
865        // Content with no lists
866        let content = "# Heading\nJust text";
867        let rules: Vec<Box<dyn Rule>> = vec![
868            Box::new(MD001HeadingIncrement::default()),
869            // A list-related rule would be skipped
870        ];
871
872        let result = lint(
873            content,
874            &rules,
875            false,
876            crate::config::MarkdownFlavor::Standard,
877            None,
878            None,
879        );
880        assert!(result.is_ok());
881    }
882
883    #[test]
884    fn test_get_profiling_report() {
885        // Just test that it returns a string without panicking
886        let report = get_profiling_report();
887        assert!(!report.is_empty());
888        assert!(report.contains("Profiling"));
889    }
890
891    #[test]
892    fn test_reset_profiling() {
893        // Test that reset_profiling doesn't panic
894        reset_profiling();
895
896        // After reset, report should indicate no measurements or profiling disabled
897        let report = get_profiling_report();
898        assert!(report.contains("disabled") || report.contains("no measurements"));
899    }
900
901    #[test]
902    fn test_get_regex_cache_stats() {
903        let stats = get_regex_cache_stats();
904        // Stats should be a valid HashMap (might be empty)
905        assert!(stats.is_empty() || !stats.is_empty());
906
907        // If not empty, all values should be positive
908        for count in stats.values() {
909            assert!(*count > 0);
910        }
911    }
912
913    #[test]
914    fn test_content_characteristics_edge_cases() {
915        // Test setext heading edge case
916        let chars = ContentCharacteristics::analyze("-"); // Single dash, not a heading
917        assert!(!chars.has_headings);
918
919        let chars = ContentCharacteristics::analyze("--"); // Two dashes, valid setext
920        assert!(chars.has_headings);
921
922        // Test list detection - we now include potential list patterns (with or without space)
923        // to support user-intention detection in MD030
924        let chars = ContentCharacteristics::analyze("*emphasis*"); // Could be list or emphasis
925        assert!(chars.has_lists); // Run list rules to be safe
926
927        let chars = ContentCharacteristics::analyze("1.Item"); // Could be list without space
928        assert!(chars.has_lists); // Run list rules for user-intention detection
929
930        // Test blockquote must be at start of line
931        let chars = ContentCharacteristics::analyze("text > not a quote");
932        assert!(!chars.has_blockquotes);
933    }
934}