Skip to main content

rumdl_lib/
lib.rs

1pub mod code_block_tools;
2pub mod config;
3pub mod embedded_lint;
4pub mod exit_codes;
5pub mod filtered_lines;
6pub mod fix_coordinator;
7pub mod inline_config;
8pub mod linguist_data;
9pub mod lint_context;
10pub mod markdownlint_config;
11pub mod profiling;
12pub mod rule;
13#[cfg(feature = "native")]
14pub mod vscode;
15pub mod workspace_index;
16#[macro_use]
17pub mod rule_config;
18#[macro_use]
19pub mod rule_config_serde;
20pub mod rules;
21pub mod types;
22pub mod utils;
23
24// Native-only modules (require tokio, tower-lsp, etc.)
25#[cfg(feature = "native")]
26pub mod lsp;
27#[cfg(feature = "native")]
28pub mod output;
29#[cfg(feature = "native")]
30pub mod parallel;
31#[cfg(feature = "native")]
32pub mod performance;
33
34// WASM module
35#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
36pub mod wasm;
37
38pub use rules::heading_utils::{Heading, HeadingStyle};
39pub use rules::*;
40
41pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
42use crate::rule::{LintResult, Rule, RuleCategory};
43use crate::utils::element_cache::ElementCache;
44#[cfg(not(target_arch = "wasm32"))]
45use std::time::Instant;
46
47/// Content characteristics for efficient rule filtering
48#[derive(Debug, Default)]
49struct ContentCharacteristics {
50    has_headings: bool,    // # or setext headings
51    has_lists: bool,       // *, -, +, 1. etc
52    has_links: bool,       // [text](url) or [text][ref]
53    has_code: bool,        // ``` or ~~~ or indented code
54    has_emphasis: bool,    // * or _ for emphasis
55    has_html: bool,        // < > tags
56    has_tables: bool,      // | pipes
57    has_blockquotes: bool, // > markers
58    has_images: bool,      // ![alt](url)
59}
60
61/// Check if a line has enough leading whitespace to be an indented code block.
62/// Indented code blocks require 4+ columns of leading whitespace (with proper tab expansion).
63fn has_potential_indented_code_indent(line: &str) -> bool {
64    ElementCache::calculate_indentation_width_default(line) >= 4
65}
66
67impl ContentCharacteristics {
68    fn analyze(content: &str) -> Self {
69        let mut chars = Self { ..Default::default() };
70
71        // Quick single-pass analysis
72        let mut has_atx_heading = false;
73        let mut has_setext_heading = false;
74
75        for line in content.lines() {
76            let trimmed = line.trim();
77
78            // Headings: ATX (#) or Setext (underlines)
79            if !has_atx_heading && trimmed.starts_with('#') {
80                has_atx_heading = true;
81            }
82            if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
83                has_setext_heading = true;
84            }
85
86            // Quick character-based detection (more efficient than regex)
87            // Include patterns without spaces to enable user-intention detection (MD030)
88            if !chars.has_lists
89                && (line.contains("* ")
90                    || line.contains("- ")
91                    || line.contains("+ ")
92                    || trimmed.starts_with("* ")
93                    || trimmed.starts_with("- ")
94                    || trimmed.starts_with("+ ")
95                    || trimmed.starts_with('*')
96                    || trimmed.starts_with('-')
97                    || trimmed.starts_with('+'))
98            {
99                chars.has_lists = true;
100            }
101            // Ordered lists: line starts with digit, or blockquote line contains digit followed by period
102            if !chars.has_lists
103                && ((line.chars().next().is_some_and(|c| c.is_ascii_digit())
104                    && (line.contains(". ") || line.contains('.')))
105                    || (trimmed.starts_with('>')
106                        && trimmed.chars().any(|c| c.is_ascii_digit())
107                        && (trimmed.contains(". ") || trimmed.contains('.'))))
108            {
109                chars.has_lists = true;
110            }
111            if !chars.has_links
112                && (line.contains('[')
113                    || line.contains("http://")
114                    || line.contains("https://")
115                    || line.contains("ftp://")
116                    || line.contains("www."))
117            {
118                chars.has_links = true;
119            }
120            if !chars.has_images && line.contains("![") {
121                chars.has_images = true;
122            }
123            if !chars.has_code
124                && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
125            {
126                chars.has_code = true;
127            }
128            if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
129                chars.has_emphasis = true;
130            }
131            if !chars.has_html && line.contains('<') {
132                chars.has_html = true;
133            }
134            if !chars.has_tables && line.contains('|') {
135                chars.has_tables = true;
136            }
137            if !chars.has_blockquotes && line.starts_with('>') {
138                chars.has_blockquotes = true;
139            }
140        }
141
142        chars.has_headings = has_atx_heading || has_setext_heading;
143        chars
144    }
145
146    /// Check if a rule should be skipped based on content characteristics
147    fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
148        match rule.category() {
149            RuleCategory::Heading => !self.has_headings,
150            RuleCategory::List => !self.has_lists,
151            RuleCategory::Link => !self.has_links && !self.has_images,
152            RuleCategory::Image => !self.has_images,
153            RuleCategory::CodeBlock => !self.has_code,
154            RuleCategory::Html => !self.has_html,
155            RuleCategory::Emphasis => !self.has_emphasis,
156            RuleCategory::Blockquote => !self.has_blockquotes,
157            RuleCategory::Table => !self.has_tables,
158            // Always check these categories as they apply to all content
159            RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
160        }
161    }
162}
163
164/// Compute content hash for incremental indexing change detection
165///
166/// Uses blake3 for native builds (fast, cryptographic-strength hash)
167/// Falls back to std::hash for WASM builds
168#[cfg(feature = "native")]
169fn compute_content_hash(content: &str) -> String {
170    blake3::hash(content.as_bytes()).to_hex().to_string()
171}
172
173/// Compute content hash for WASM builds using std::hash
174#[cfg(not(feature = "native"))]
175fn compute_content_hash(content: &str) -> String {
176    use std::hash::{DefaultHasher, Hash, Hasher};
177    let mut hasher = DefaultHasher::new();
178    content.hash(&mut hasher);
179    format!("{:016x}", hasher.finish())
180}
181
182/// Lint a file against the given rules with intelligent rule filtering
183/// Assumes the provided `rules` vector contains the final,
184/// configured, and filtered set of rules to be executed.
185pub fn lint(
186    content: &str,
187    rules: &[Box<dyn Rule>],
188    verbose: bool,
189    flavor: crate::config::MarkdownFlavor,
190    config: Option<&crate::config::Config>,
191) -> LintResult {
192    // Use lint_and_index but discard the FileIndex for backward compatibility
193    let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, None, config);
194    result
195}
196
197/// Build FileIndex only (no linting) for cross-file analysis on cache hits
198///
199/// This is a lightweight function that only builds the FileIndex without running
200/// any rules. Used when we have a cache hit but still need the FileIndex for
201/// cross-file validation.
202///
203/// This avoids the overhead of re-running all rules when only the index data is needed.
204pub fn build_file_index_only(
205    content: &str,
206    rules: &[Box<dyn Rule>],
207    flavor: crate::config::MarkdownFlavor,
208) -> crate::workspace_index::FileIndex {
209    // Compute content hash for change detection
210    let content_hash = compute_content_hash(content);
211    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
212
213    // Early return for empty content
214    if content.is_empty() {
215        return file_index;
216    }
217
218    // Parse LintContext once with the provided flavor
219    let lint_ctx = crate::lint_context::LintContext::new(content, flavor, None);
220
221    // Only call contribute_to_index for cross-file rules (no rule checking!)
222    for rule in rules {
223        if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
224            rule.contribute_to_index(&lint_ctx, &mut file_index);
225        }
226    }
227
228    file_index
229}
230
231/// Lint a file and contribute to workspace index for cross-file analysis
232///
233/// This variant performs linting and optionally populates a `FileIndex` with data
234/// needed for cross-file validation. The FileIndex is populated during linting,
235/// avoiding duplicate parsing.
236///
237/// Returns: (warnings, FileIndex) - the FileIndex contains headings/links for cross-file rules
238pub fn lint_and_index(
239    content: &str,
240    rules: &[Box<dyn Rule>],
241    _verbose: bool,
242    flavor: crate::config::MarkdownFlavor,
243    source_file: Option<std::path::PathBuf>,
244    config: Option<&crate::config::Config>,
245) -> (LintResult, crate::workspace_index::FileIndex) {
246    let mut warnings = Vec::new();
247    // Compute content hash for change detection
248    let content_hash = compute_content_hash(content);
249    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
250
251    #[cfg(not(target_arch = "wasm32"))]
252    let _overall_start = Instant::now();
253
254    // Early return for empty content
255    if content.is_empty() {
256        return (Ok(warnings), file_index);
257    }
258
259    // Parse LintContext once (includes inline config parsing)
260    let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
261    let inline_config = lint_ctx.inline_config();
262
263    // Export inline config data to FileIndex for cross-file rule filtering
264    let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
265    file_index.file_disabled_rules = file_disabled;
266    file_index.persistent_transitions = persistent_transitions;
267    file_index.line_disabled_rules = line_disabled;
268
269    // Analyze content characteristics for rule filtering
270    let characteristics = ContentCharacteristics::analyze(content);
271
272    // Filter rules based on content characteristics
273    let applicable_rules: Vec<_> = rules
274        .iter()
275        .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
276        .collect();
277
278    // Calculate skipped rules count before consuming applicable_rules
279    let _total_rules = rules.len();
280    let _applicable_count = applicable_rules.len();
281
282    #[cfg(not(target_arch = "wasm32"))]
283    let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
284    #[cfg(target_arch = "wasm32")]
285    let profile_rules = false;
286
287    // Automatic inline config support: merge inline overrides into config once,
288    // then recreate only the affected rules. Works for ALL rules without per-rule changes.
289    let inline_overrides = inline_config.get_all_rule_configs();
290    let merged_config = if !inline_overrides.is_empty() {
291        config.map(|c| c.merge_with_inline_config(inline_config))
292    } else {
293        None
294    };
295    let effective_config = merged_config.as_ref().or(config);
296
297    // Cache recreated rules for rules with inline overrides
298    let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
299        std::collections::HashMap::new();
300
301    // Pre-create rules that have inline config overrides
302    if let Some(cfg) = effective_config {
303        for rule_name in inline_overrides.keys() {
304            if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
305                recreated_rules.insert(rule_name.clone(), recreated);
306            }
307        }
308    }
309
310    for rule in &applicable_rules {
311        #[cfg(not(target_arch = "wasm32"))]
312        let _rule_start = Instant::now();
313
314        // Skip rules that indicate they should be skipped (opt-in rules, content-based skipping)
315        if rule.should_skip(&lint_ctx) {
316            continue;
317        }
318
319        // Use recreated rule if inline config overrides exist for this rule
320        let effective_rule: &dyn crate::rule::Rule = recreated_rules
321            .get(rule.name())
322            .map(|r| r.as_ref())
323            .unwrap_or(rule.as_ref());
324
325        // Run single-file check with the effective rule (possibly with inline config applied)
326        let result = effective_rule.check(&lint_ctx);
327
328        match result {
329            Ok(rule_warnings) => {
330                // Filter out warnings inside kramdown extension blocks (Layer 3 safety net)
331                // and warnings for rules disabled via inline comments
332                let filtered_warnings: Vec<_> = rule_warnings
333                    .into_iter()
334                    .filter(|warning| {
335                        // Layer 3: Suppress warnings inside kramdown extension blocks
336                        if lint_ctx
337                            .line_info(warning.line)
338                            .is_some_and(|info| info.in_kramdown_extension_block)
339                        {
340                            return false;
341                        }
342
343                        // Use the warning's rule_name if available, otherwise use the rule's name
344                        let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
345
346                        // Extract the base rule name for sub-rules like "MD029-style" -> "MD029"
347                        let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
348                            &rule_name_to_check[..dash_pos]
349                        } else {
350                            rule_name_to_check
351                        };
352
353                        !inline_config.is_rule_disabled(
354                            base_rule_name,
355                            warning.line, // Already 1-indexed
356                        )
357                    })
358                    .map(|mut warning| {
359                        // Apply severity override from config if present
360                        if let Some(cfg) = config {
361                            let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
362                            if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
363                                warning.severity = override_severity;
364                            }
365                        }
366                        warning
367                    })
368                    .collect();
369                warnings.extend(filtered_warnings);
370            }
371            Err(e) => {
372                log::error!("Error checking rule {}: {}", rule.name(), e);
373                return (Err(e), file_index);
374            }
375        }
376
377        #[cfg(not(target_arch = "wasm32"))]
378        {
379            let rule_duration = _rule_start.elapsed();
380            if profile_rules {
381                eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
382            }
383
384            #[cfg(not(test))]
385            if _verbose && rule_duration.as_millis() > 500 {
386                log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
387            }
388        }
389    }
390
391    // Contribute to index for cross-file rules (done after all rules checked)
392    // NOTE: We iterate over ALL rules (not just applicable_rules) because cross-file
393    // rules need to extract data from every file in the workspace, regardless of whether
394    // that file has content that would trigger the rule. For example, MD051 needs to
395    // index headings from files that have no links (like target.md) so that links
396    // FROM other files TO those headings can be validated.
397    for rule in rules {
398        if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
399            rule.contribute_to_index(&lint_ctx, &mut file_index);
400        }
401    }
402
403    #[cfg(not(test))]
404    if _verbose {
405        let skipped_rules = _total_rules - _applicable_count;
406        if skipped_rules > 0 {
407            log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
408        }
409    }
410
411    (Ok(warnings), file_index)
412}
413
414/// Run cross-file checks for rules that need workspace-wide validation
415///
416/// This should be called after all files have been linted and the WorkspaceIndex
417/// has been built from the accumulated FileIndex data.
418///
419/// Note: This takes the FileIndex instead of content to avoid re-parsing each file.
420/// The FileIndex was already populated during contribute_to_index in the linting phase.
421///
422/// Rules can use workspace_index methods for cross-file validation:
423/// - `get_file(path)` - to look up headings in target files (for MD051)
424///
425/// Returns additional warnings from cross-file validation.
426pub fn run_cross_file_checks(
427    file_path: &std::path::Path,
428    file_index: &crate::workspace_index::FileIndex,
429    rules: &[Box<dyn Rule>],
430    workspace_index: &crate::workspace_index::WorkspaceIndex,
431    config: Option<&crate::config::Config>,
432) -> LintResult {
433    use crate::rule::CrossFileScope;
434
435    let mut warnings = Vec::new();
436
437    // Only check rules that need cross-file analysis
438    for rule in rules {
439        if rule.cross_file_scope() != CrossFileScope::Workspace {
440            continue;
441        }
442
443        match rule.cross_file_check(file_path, file_index, workspace_index) {
444            Ok(rule_warnings) => {
445                // Filter cross-file warnings based on inline config stored in file_index
446                let filtered: Vec<_> = rule_warnings
447                    .into_iter()
448                    .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
449                    .map(|mut warning| {
450                        // Apply severity override from config if present
451                        if let Some(cfg) = config
452                            && let Some(override_severity) = cfg.get_rule_severity(rule.name())
453                        {
454                            warning.severity = override_severity;
455                        }
456                        warning
457                    })
458                    .collect();
459                warnings.extend(filtered);
460            }
461            Err(e) => {
462                log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
463                return Err(e);
464            }
465        }
466    }
467
468    Ok(warnings)
469}
470
471/// Get the profiling report
472pub fn get_profiling_report() -> String {
473    profiling::get_report()
474}
475
476/// Reset the profiling data
477pub fn reset_profiling() {
478    profiling::reset()
479}
480
481/// Get regex cache statistics for performance monitoring
482pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
483    crate::utils::regex_cache::get_cache_stats()
484}
485
486#[cfg(test)]
487mod tests {
488    use super::*;
489    use crate::rule::Rule;
490    use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
491
492    #[test]
493    fn test_content_characteristics_analyze() {
494        // Test empty content
495        let chars = ContentCharacteristics::analyze("");
496        assert!(!chars.has_headings);
497        assert!(!chars.has_lists);
498        assert!(!chars.has_links);
499        assert!(!chars.has_code);
500        assert!(!chars.has_emphasis);
501        assert!(!chars.has_html);
502        assert!(!chars.has_tables);
503        assert!(!chars.has_blockquotes);
504        assert!(!chars.has_images);
505
506        // Test content with headings
507        let chars = ContentCharacteristics::analyze("# Heading");
508        assert!(chars.has_headings);
509
510        // Test setext headings
511        let chars = ContentCharacteristics::analyze("Heading\n=======");
512        assert!(chars.has_headings);
513
514        // Test lists
515        let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
516        assert!(chars.has_lists);
517
518        // Test ordered lists
519        let chars = ContentCharacteristics::analyze("1. First\n2. Second");
520        assert!(chars.has_lists);
521
522        // Test links
523        let chars = ContentCharacteristics::analyze("[link](url)");
524        assert!(chars.has_links);
525
526        // Test URLs
527        let chars = ContentCharacteristics::analyze("Visit https://example.com");
528        assert!(chars.has_links);
529
530        // Test images
531        let chars = ContentCharacteristics::analyze("![alt text](image.png)");
532        assert!(chars.has_images);
533
534        // Test code
535        let chars = ContentCharacteristics::analyze("`inline code`");
536        assert!(chars.has_code);
537
538        let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
539        assert!(chars.has_code);
540
541        // Test indented code blocks (4 spaces)
542        let chars = ContentCharacteristics::analyze("Text\n\n    indented code\n\nMore text");
543        assert!(chars.has_code);
544
545        // Test tab-indented code blocks
546        let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
547        assert!(chars.has_code);
548
549        // Test mixed whitespace indented code (2 spaces + tab = 4 columns)
550        let chars = ContentCharacteristics::analyze("Text\n\n  \tmixed indent code\n\nMore text");
551        assert!(chars.has_code);
552
553        // Test 1 space + tab (also 4 columns due to tab expansion)
554        let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
555        assert!(chars.has_code);
556
557        // Test emphasis
558        let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
559        assert!(chars.has_emphasis);
560
561        // Test HTML
562        let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
563        assert!(chars.has_html);
564
565        // Test tables
566        let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
567        assert!(chars.has_tables);
568
569        // Test blockquotes
570        let chars = ContentCharacteristics::analyze("> Quote");
571        assert!(chars.has_blockquotes);
572
573        // Test mixed content
574        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)";
575        let chars = ContentCharacteristics::analyze(content);
576        assert!(chars.has_headings);
577        assert!(chars.has_lists);
578        assert!(chars.has_links);
579        assert!(chars.has_code);
580        assert!(chars.has_emphasis);
581        assert!(chars.has_html);
582        assert!(chars.has_tables);
583        assert!(chars.has_blockquotes);
584        assert!(chars.has_images);
585    }
586
587    #[test]
588    fn test_content_characteristics_should_skip_rule() {
589        let chars = ContentCharacteristics {
590            has_headings: true,
591            has_lists: false,
592            has_links: true,
593            has_code: false,
594            has_emphasis: true,
595            has_html: false,
596            has_tables: true,
597            has_blockquotes: false,
598            has_images: false,
599        };
600
601        // Create test rules for different categories
602        let heading_rule = MD001HeadingIncrement::default();
603        assert!(!chars.should_skip_rule(&heading_rule));
604
605        let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
606        assert!(!chars.should_skip_rule(&trailing_spaces_rule)); // Whitespace rules always run
607
608        // Test skipping based on content
609        let chars_no_headings = ContentCharacteristics {
610            has_headings: false,
611            ..Default::default()
612        };
613        assert!(chars_no_headings.should_skip_rule(&heading_rule));
614    }
615
616    #[test]
617    fn test_lint_empty_content() {
618        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
619
620        let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None);
621        assert!(result.is_ok());
622        assert!(result.unwrap().is_empty());
623    }
624
625    #[test]
626    fn test_lint_with_violations() {
627        let content = "## Level 2\n#### Level 4"; // Skips level 3
628        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
629
630        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
631        assert!(result.is_ok());
632        let warnings = result.unwrap();
633        assert!(!warnings.is_empty());
634        // Check the rule field of LintWarning struct
635        assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
636    }
637
638    #[test]
639    fn test_lint_with_inline_disable() {
640        let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
641        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
642
643        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
644        assert!(result.is_ok());
645        let warnings = result.unwrap();
646        assert!(warnings.is_empty()); // Should be disabled by inline comment
647    }
648
649    #[test]
650    fn test_lint_rule_filtering() {
651        // Content with no lists
652        let content = "# Heading\nJust text";
653        let rules: Vec<Box<dyn Rule>> = vec![
654            Box::new(MD001HeadingIncrement::default()),
655            // A list-related rule would be skipped
656        ];
657
658        let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard, None);
659        assert!(result.is_ok());
660    }
661
662    #[test]
663    fn test_get_profiling_report() {
664        // Just test that it returns a string without panicking
665        let report = get_profiling_report();
666        assert!(!report.is_empty());
667        assert!(report.contains("Profiling"));
668    }
669
670    #[test]
671    fn test_reset_profiling() {
672        // Test that reset_profiling doesn't panic
673        reset_profiling();
674
675        // After reset, report should indicate no measurements or profiling disabled
676        let report = get_profiling_report();
677        assert!(report.contains("disabled") || report.contains("no measurements"));
678    }
679
680    #[test]
681    fn test_get_regex_cache_stats() {
682        let stats = get_regex_cache_stats();
683        // Stats should be a valid HashMap (might be empty)
684        assert!(stats.is_empty() || !stats.is_empty());
685
686        // If not empty, all values should be positive
687        for count in stats.values() {
688            assert!(*count > 0);
689        }
690    }
691
692    #[test]
693    fn test_content_characteristics_edge_cases() {
694        // Test setext heading edge case
695        let chars = ContentCharacteristics::analyze("-"); // Single dash, not a heading
696        assert!(!chars.has_headings);
697
698        let chars = ContentCharacteristics::analyze("--"); // Two dashes, valid setext
699        assert!(chars.has_headings);
700
701        // Test list detection - we now include potential list patterns (with or without space)
702        // to support user-intention detection in MD030
703        let chars = ContentCharacteristics::analyze("*emphasis*"); // Could be list or emphasis
704        assert!(chars.has_lists); // Run list rules to be safe
705
706        let chars = ContentCharacteristics::analyze("1.Item"); // Could be list without space
707        assert!(chars.has_lists); // Run list rules for user-intention detection
708
709        // Test blockquote must be at start of line
710        let chars = ContentCharacteristics::analyze("text > not a quote");
711        assert!(!chars.has_blockquotes);
712    }
713}