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