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