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    source_file: Option<std::path::PathBuf>,
192    config: Option<&crate::config::Config>,
193) -> LintResult {
194    let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, 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    source_file: Option<std::path::PathBuf>,
210) -> crate::workspace_index::FileIndex {
211    // Compute content hash for change detection
212    let content_hash = compute_content_hash(content);
213    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
214
215    // Early return for empty content
216    if content.is_empty() {
217        return file_index;
218    }
219
220    // Parse LintContext once with the provided flavor
221    let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
222
223    // Only call contribute_to_index for cross-file rules (no rule checking!)
224    for rule in rules {
225        if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
226            rule.contribute_to_index(&lint_ctx, &mut file_index);
227        }
228    }
229
230    file_index
231}
232
233/// Lint a file and contribute to workspace index for cross-file analysis
234///
235/// This variant performs linting and optionally populates a `FileIndex` with data
236/// needed for cross-file validation. The FileIndex is populated during linting,
237/// avoiding duplicate parsing.
238///
239/// Returns: (warnings, FileIndex) - the FileIndex contains headings/links for cross-file rules
240pub fn lint_and_index(
241    content: &str,
242    rules: &[Box<dyn Rule>],
243    _verbose: bool,
244    flavor: crate::config::MarkdownFlavor,
245    source_file: Option<std::path::PathBuf>,
246    config: Option<&crate::config::Config>,
247) -> (LintResult, crate::workspace_index::FileIndex) {
248    let mut warnings = Vec::new();
249    // Compute content hash for change detection
250    let content_hash = compute_content_hash(content);
251    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
252
253    #[cfg(not(target_arch = "wasm32"))]
254    let _overall_start = Instant::now();
255
256    // Early return for empty content
257    if content.is_empty() {
258        return (Ok(warnings), file_index);
259    }
260
261    // Parse LintContext once (includes inline config parsing)
262    let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
263    let inline_config = lint_ctx.inline_config();
264
265    // Export inline config data to FileIndex for cross-file rule filtering
266    let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
267    file_index.file_disabled_rules = file_disabled;
268    file_index.persistent_transitions = persistent_transitions;
269    file_index.line_disabled_rules = line_disabled;
270
271    // Analyze content characteristics for rule filtering
272    let characteristics = ContentCharacteristics::analyze(content);
273
274    // Filter rules based on content characteristics
275    let applicable_rules: Vec<_> = rules
276        .iter()
277        .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
278        .collect();
279
280    // Calculate skipped rules count before consuming applicable_rules
281    let _total_rules = rules.len();
282    let _applicable_count = applicable_rules.len();
283
284    #[cfg(not(target_arch = "wasm32"))]
285    let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
286    #[cfg(target_arch = "wasm32")]
287    let profile_rules = false;
288
289    // Automatic inline config support: merge inline overrides into config once,
290    // then recreate only the affected rules. Works for ALL rules without per-rule changes.
291    let inline_overrides = inline_config.get_all_rule_configs();
292    let merged_config = if !inline_overrides.is_empty() {
293        config.map(|c| c.merge_with_inline_config(inline_config))
294    } else {
295        None
296    };
297    let effective_config = merged_config.as_ref().or(config);
298
299    // Cache recreated rules for rules with inline overrides
300    let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
301        std::collections::HashMap::new();
302
303    // Pre-create rules that have inline config overrides
304    if let Some(cfg) = effective_config {
305        for rule_name in inline_overrides.keys() {
306            if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
307                recreated_rules.insert(rule_name.clone(), recreated);
308            }
309        }
310    }
311
312    for rule in &applicable_rules {
313        #[cfg(not(target_arch = "wasm32"))]
314        let _rule_start = Instant::now();
315
316        // Skip rules that indicate they should be skipped (opt-in rules, content-based skipping)
317        if rule.should_skip(&lint_ctx) {
318            continue;
319        }
320
321        // Use recreated rule if inline config overrides exist for this rule
322        let effective_rule: &dyn crate::rule::Rule = recreated_rules
323            .get(rule.name())
324            .map(|r| r.as_ref())
325            .unwrap_or(rule.as_ref());
326
327        // Run single-file check with the effective rule (possibly with inline config applied)
328        let result = effective_rule.check(&lint_ctx);
329
330        match result {
331            Ok(rule_warnings) => {
332                // Filter out warnings inside kramdown extension blocks (Layer 3 safety net)
333                // and warnings for rules disabled via inline comments
334                let filtered_warnings: Vec<_> = rule_warnings
335                    .into_iter()
336                    .filter(|warning| {
337                        // Layer 3: Suppress warnings inside kramdown extension blocks
338                        if lint_ctx
339                            .line_info(warning.line)
340                            .is_some_and(|info| info.in_kramdown_extension_block)
341                        {
342                            return false;
343                        }
344
345                        // Use the warning's rule_name if available, otherwise use the rule's name
346                        let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
347
348                        // Extract the base rule name for sub-rules like "MD029-style" -> "MD029"
349                        let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
350                            &rule_name_to_check[..dash_pos]
351                        } else {
352                            rule_name_to_check
353                        };
354
355                        // Check if the rule is disabled at any line in the warning's range.
356                        // Multi-line warnings (e.g., reflow) report on the first line,
357                        // but inline disable comments may appear later in the range.
358                        // Guard: if end_line < line (e.g., end_line=0), fall back to
359                        // checking only the warning's line to match original behavior.
360                        {
361                            let end = if warning.end_line >= warning.line {
362                                warning.end_line
363                            } else {
364                                warning.line
365                            };
366                            !(warning.line..=end).any(|line| inline_config.is_rule_disabled(base_rule_name, line))
367                        }
368                    })
369                    .map(|mut warning| {
370                        // Apply severity override from config if present
371                        if let Some(cfg) = config {
372                            let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
373                            if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
374                                warning.severity = override_severity;
375                            }
376                        }
377                        warning
378                    })
379                    .collect();
380                warnings.extend(filtered_warnings);
381            }
382            Err(e) => {
383                log::error!("Error checking rule {}: {}", rule.name(), e);
384                return (Err(e), file_index);
385            }
386        }
387
388        #[cfg(not(target_arch = "wasm32"))]
389        {
390            let rule_duration = _rule_start.elapsed();
391            if profile_rules {
392                eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
393            }
394
395            #[cfg(not(test))]
396            if _verbose && rule_duration.as_millis() > 500 {
397                log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
398            }
399        }
400    }
401
402    // Contribute to index for cross-file rules (done after all rules checked)
403    // NOTE: We iterate over ALL rules (not just applicable_rules) because cross-file
404    // rules need to extract data from every file in the workspace, regardless of whether
405    // that file has content that would trigger the rule. For example, MD051 needs to
406    // index headings from files that have no links (like target.md) so that links
407    // FROM other files TO those headings can be validated.
408    for rule in rules {
409        if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
410            rule.contribute_to_index(&lint_ctx, &mut file_index);
411        }
412    }
413
414    #[cfg(not(test))]
415    if _verbose {
416        let skipped_rules = _total_rules - _applicable_count;
417        if skipped_rules > 0 {
418            log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
419        }
420    }
421
422    (Ok(warnings), file_index)
423}
424
425/// Run cross-file checks for rules that need workspace-wide validation
426///
427/// This should be called after all files have been linted and the WorkspaceIndex
428/// has been built from the accumulated FileIndex data.
429///
430/// Note: This takes the FileIndex instead of content to avoid re-parsing each file.
431/// The FileIndex was already populated during contribute_to_index in the linting phase.
432///
433/// Rules can use workspace_index methods for cross-file validation:
434/// - `get_file(path)` - to look up headings in target files (for MD051)
435///
436/// Returns additional warnings from cross-file validation.
437pub fn run_cross_file_checks(
438    file_path: &std::path::Path,
439    file_index: &crate::workspace_index::FileIndex,
440    rules: &[Box<dyn Rule>],
441    workspace_index: &crate::workspace_index::WorkspaceIndex,
442    config: Option<&crate::config::Config>,
443) -> LintResult {
444    use crate::rule::CrossFileScope;
445
446    let mut warnings = Vec::new();
447
448    // Only check rules that need cross-file analysis
449    for rule in rules {
450        if rule.cross_file_scope() != CrossFileScope::Workspace {
451            continue;
452        }
453
454        match rule.cross_file_check(file_path, file_index, workspace_index) {
455            Ok(rule_warnings) => {
456                // Filter cross-file warnings based on inline config stored in file_index
457                let filtered: Vec<_> = rule_warnings
458                    .into_iter()
459                    .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
460                    .map(|mut warning| {
461                        // Apply severity override from config if present
462                        if let Some(cfg) = config
463                            && let Some(override_severity) = cfg.get_rule_severity(rule.name())
464                        {
465                            warning.severity = override_severity;
466                        }
467                        warning
468                    })
469                    .collect();
470                warnings.extend(filtered);
471            }
472            Err(e) => {
473                log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
474                return Err(e);
475            }
476        }
477    }
478
479    Ok(warnings)
480}
481
482/// Get the profiling report
483pub fn get_profiling_report() -> String {
484    profiling::get_report()
485}
486
487/// Reset the profiling data
488pub fn reset_profiling() {
489    profiling::reset()
490}
491
492/// Get regex cache statistics for performance monitoring
493pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
494    crate::utils::regex_cache::get_cache_stats()
495}
496
497#[cfg(test)]
498mod tests {
499    use super::*;
500    use crate::rule::Rule;
501    use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
502
503    #[test]
504    fn test_content_characteristics_analyze() {
505        // Test empty content
506        let chars = ContentCharacteristics::analyze("");
507        assert!(!chars.has_headings);
508        assert!(!chars.has_lists);
509        assert!(!chars.has_links);
510        assert!(!chars.has_code);
511        assert!(!chars.has_emphasis);
512        assert!(!chars.has_html);
513        assert!(!chars.has_tables);
514        assert!(!chars.has_blockquotes);
515        assert!(!chars.has_images);
516
517        // Test content with headings
518        let chars = ContentCharacteristics::analyze("# Heading");
519        assert!(chars.has_headings);
520
521        // Test setext headings
522        let chars = ContentCharacteristics::analyze("Heading\n=======");
523        assert!(chars.has_headings);
524
525        // Test lists
526        let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
527        assert!(chars.has_lists);
528
529        // Test ordered lists
530        let chars = ContentCharacteristics::analyze("1. First\n2. Second");
531        assert!(chars.has_lists);
532
533        // Test links
534        let chars = ContentCharacteristics::analyze("[link](url)");
535        assert!(chars.has_links);
536
537        // Test URLs
538        let chars = ContentCharacteristics::analyze("Visit https://example.com");
539        assert!(chars.has_links);
540
541        // Test images
542        let chars = ContentCharacteristics::analyze("![alt text](image.png)");
543        assert!(chars.has_images);
544
545        // Test code
546        let chars = ContentCharacteristics::analyze("`inline code`");
547        assert!(chars.has_code);
548
549        let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
550        assert!(chars.has_code);
551
552        // Test indented code blocks (4 spaces)
553        let chars = ContentCharacteristics::analyze("Text\n\n    indented code\n\nMore text");
554        assert!(chars.has_code);
555
556        // Test tab-indented code blocks
557        let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
558        assert!(chars.has_code);
559
560        // Test mixed whitespace indented code (2 spaces + tab = 4 columns)
561        let chars = ContentCharacteristics::analyze("Text\n\n  \tmixed indent code\n\nMore text");
562        assert!(chars.has_code);
563
564        // Test 1 space + tab (also 4 columns due to tab expansion)
565        let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
566        assert!(chars.has_code);
567
568        // Test emphasis
569        let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
570        assert!(chars.has_emphasis);
571
572        // Test HTML
573        let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
574        assert!(chars.has_html);
575
576        // Test tables
577        let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
578        assert!(chars.has_tables);
579
580        // Test blockquotes
581        let chars = ContentCharacteristics::analyze("> Quote");
582        assert!(chars.has_blockquotes);
583
584        // Test mixed content
585        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)";
586        let chars = ContentCharacteristics::analyze(content);
587        assert!(chars.has_headings);
588        assert!(chars.has_lists);
589        assert!(chars.has_links);
590        assert!(chars.has_code);
591        assert!(chars.has_emphasis);
592        assert!(chars.has_html);
593        assert!(chars.has_tables);
594        assert!(chars.has_blockquotes);
595        assert!(chars.has_images);
596    }
597
598    #[test]
599    fn test_content_characteristics_should_skip_rule() {
600        let chars = ContentCharacteristics {
601            has_headings: true,
602            has_lists: false,
603            has_links: true,
604            has_code: false,
605            has_emphasis: true,
606            has_html: false,
607            has_tables: true,
608            has_blockquotes: false,
609            has_images: false,
610        };
611
612        // Create test rules for different categories
613        let heading_rule = MD001HeadingIncrement::default();
614        assert!(!chars.should_skip_rule(&heading_rule));
615
616        let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
617        assert!(!chars.should_skip_rule(&trailing_spaces_rule)); // Whitespace rules always run
618
619        // Test skipping based on content
620        let chars_no_headings = ContentCharacteristics {
621            has_headings: false,
622            ..Default::default()
623        };
624        assert!(chars_no_headings.should_skip_rule(&heading_rule));
625    }
626
627    #[test]
628    fn test_lint_empty_content() {
629        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
630
631        let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
632        assert!(result.is_ok());
633        assert!(result.unwrap().is_empty());
634    }
635
636    #[test]
637    fn test_lint_with_violations() {
638        let content = "## Level 2\n#### Level 4"; // Skips level 3
639        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
640
641        let result = lint(
642            content,
643            &rules,
644            false,
645            crate::config::MarkdownFlavor::Standard,
646            None,
647            None,
648        );
649        assert!(result.is_ok());
650        let warnings = result.unwrap();
651        assert!(!warnings.is_empty());
652        // Check the rule field of LintWarning struct
653        assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
654    }
655
656    #[test]
657    fn test_lint_with_inline_disable() {
658        let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
659        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
660
661        let result = lint(
662            content,
663            &rules,
664            false,
665            crate::config::MarkdownFlavor::Standard,
666            None,
667            None,
668        );
669        assert!(result.is_ok());
670        let warnings = result.unwrap();
671        assert!(warnings.is_empty()); // Should be disabled by inline comment
672    }
673
674    #[test]
675    fn test_lint_rule_filtering() {
676        // Content with no lists
677        let content = "# Heading\nJust text";
678        let rules: Vec<Box<dyn Rule>> = vec![
679            Box::new(MD001HeadingIncrement::default()),
680            // A list-related rule would be skipped
681        ];
682
683        let result = lint(
684            content,
685            &rules,
686            false,
687            crate::config::MarkdownFlavor::Standard,
688            None,
689            None,
690        );
691        assert!(result.is_ok());
692    }
693
694    #[test]
695    fn test_get_profiling_report() {
696        // Just test that it returns a string without panicking
697        let report = get_profiling_report();
698        assert!(!report.is_empty());
699        assert!(report.contains("Profiling"));
700    }
701
702    #[test]
703    fn test_reset_profiling() {
704        // Test that reset_profiling doesn't panic
705        reset_profiling();
706
707        // After reset, report should indicate no measurements or profiling disabled
708        let report = get_profiling_report();
709        assert!(report.contains("disabled") || report.contains("no measurements"));
710    }
711
712    #[test]
713    fn test_get_regex_cache_stats() {
714        let stats = get_regex_cache_stats();
715        // Stats should be a valid HashMap (might be empty)
716        assert!(stats.is_empty() || !stats.is_empty());
717
718        // If not empty, all values should be positive
719        for count in stats.values() {
720            assert!(*count > 0);
721        }
722    }
723
724    #[test]
725    fn test_content_characteristics_edge_cases() {
726        // Test setext heading edge case
727        let chars = ContentCharacteristics::analyze("-"); // Single dash, not a heading
728        assert!(!chars.has_headings);
729
730        let chars = ContentCharacteristics::analyze("--"); // Two dashes, valid setext
731        assert!(chars.has_headings);
732
733        // Test list detection - we now include potential list patterns (with or without space)
734        // to support user-intention detection in MD030
735        let chars = ContentCharacteristics::analyze("*emphasis*"); // Could be list or emphasis
736        assert!(chars.has_lists); // Run list rules to be safe
737
738        let chars = ContentCharacteristics::analyze("1.Item"); // Could be list without space
739        assert!(chars.has_lists); // Run list rules for user-intention detection
740
741        // Test blockquote must be at start of line
742        let chars = ContentCharacteristics::analyze("text > not a quote");
743        assert!(!chars.has_blockquotes);
744    }
745}