Skip to main content

rumdl_lib/
lib.rs

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