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 discovery;
53pub mod doc_comment_lint;
54pub mod document_run;
55pub mod embedded_lint;
56pub mod encoding;
57pub mod exit_codes;
58pub mod filtered_lines;
59pub mod fix_coordinator;
60pub mod inline_config;
61pub mod linguist_data;
62pub mod lint_context;
63pub mod markdownlint_config;
64pub mod merge_conflict;
65pub mod profiling;
66pub mod rule;
67#[cfg(feature = "colored")]
68pub mod vscode;
69pub mod workspace_index;
70#[macro_use]
71pub mod rule_config;
72#[macro_use]
73pub mod rule_config_serde;
74pub mod rules;
75pub mod types;
76pub mod utils;
77
78// Native-only modules (require tokio, tower-lsp, etc.)
79#[cfg(feature = "native")]
80pub mod lsp;
81#[cfg(feature = "colored")]
82pub mod output;
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). A blockquoted ATX
129            // heading (`> ## Title`) still emits a fragment anchor, so rules
130            // like MD051/MD080 must run for blockquote-only documents too.
131            // Stripping `>`/space/tab is a coarse, deliberately
132            // over-inclusive prefilter check (it must never skip a rule that
133            // has work; `parse_blockquote_prefix` also accepts a tab marker).
134            if !has_atx_heading
135                && (trimmed.starts_with('#') || trimmed.trim_start_matches(['>', ' ', '\t']).starts_with('#'))
136            {
137                has_atx_heading = true;
138            }
139            // A setext underline can be a single `=` or `-`, and one inside a
140            // blockquote follows the quote's markers.
141            let underline = trimmed.trim_start_matches(['>', ' ', '\t']);
142            if !has_setext_heading && !underline.is_empty() && underline.chars().all(|c| c == '=' || c == '-') {
143                has_setext_heading = true;
144            }
145
146            // Quick character-based detection (more efficient than regex)
147            // Include patterns without spaces to enable user-intention detection (MD030)
148            if !chars.has_lists
149                && (line.contains("* ")
150                    || line.contains("- ")
151                    || line.contains("+ ")
152                    || trimmed.starts_with("* ")
153                    || trimmed.starts_with("- ")
154                    || trimmed.starts_with("+ ")
155                    || trimmed.starts_with('*')
156                    || trimmed.starts_with('-')
157                    || trimmed.starts_with('+'))
158            {
159                chars.has_lists = true;
160            }
161            // Ordered lists: a line whose text starts with a digit (a marker may
162            // be indented), or a blockquote line holding one, and either marker
163            // delimiter (`.` or `)`) after it
164            if !chars.has_lists
165                && ((trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains(['.', ')']))
166                    || (trimmed.starts_with('>')
167                        && trimmed.chars().any(|c| c.is_ascii_digit())
168                        && trimmed.contains(['.', ')'])))
169            {
170                chars.has_lists = true;
171            }
172            if !chars.has_links
173                && (line.contains('[')
174                    || line.contains("http://")
175                    || line.contains("https://")
176                    || line.contains("ftp://")
177                    || line.contains("www."))
178            {
179                chars.has_links = true;
180            }
181            if !chars.has_images && line.contains("![") {
182                chars.has_images = true;
183            }
184            if !chars.has_code
185                && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
186            {
187                chars.has_code = true;
188            }
189            if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
190                chars.has_emphasis = true;
191            }
192            if !chars.has_html && line.contains('<') {
193                chars.has_html = true;
194            }
195            if !chars.has_tables && line.contains('|') {
196                chars.has_tables = true;
197            }
198            if !chars.has_blockquotes && line.starts_with('>') {
199                chars.has_blockquotes = true;
200            }
201        }
202
203        chars.has_headings = has_atx_heading || has_setext_heading;
204        chars
205    }
206
207    /// Check if a rule should be skipped based on content characteristics
208    fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
209        match rule.category() {
210            RuleCategory::Heading => !self.has_headings,
211            RuleCategory::List => !self.has_lists,
212            RuleCategory::Link => !self.has_links && !self.has_images,
213            RuleCategory::Image => !self.has_images,
214            RuleCategory::CodeBlock => !self.has_code,
215            RuleCategory::Html => !self.has_html,
216            RuleCategory::Emphasis => !self.has_emphasis,
217            RuleCategory::Blockquote => !self.has_blockquotes,
218            RuleCategory::Table => !self.has_tables,
219            // Always check these categories as they apply to all content
220            RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
221        }
222    }
223}
224
225/// Compute content hash for incremental indexing change detection
226///
227/// Uses blake3 for native builds (fast, cryptographic-strength hash)
228/// Falls back to std::hash for WASM builds
229#[cfg(feature = "native")]
230fn compute_content_hash(content: &str) -> String {
231    #[cfg(feature = "profiling")]
232    let start = std::time::Instant::now();
233    let hash = blake3::hash(content.as_bytes()).to_hex().to_string();
234    #[cfg(feature = "profiling")]
235    profiling::record_duration("index: hash content", start.elapsed());
236    hash
237}
238
239/// Compute content hash for WASM builds using std::hash
240#[cfg(not(feature = "native"))]
241fn compute_content_hash(content: &str) -> String {
242    use std::hash::{DefaultHasher, Hash, Hasher};
243    let mut hasher = DefaultHasher::new();
244    content.hash(&mut hasher);
245    format!("{:016x}", hasher.finish())
246}
247
248/// Lint a file against the given rules with intelligent rule filtering
249/// Assumes the provided `rules` vector contains the final,
250/// configured, and filtered set of rules to be executed.
251pub fn lint(
252    content: &str,
253    rules: &[Box<dyn Rule>],
254    verbose: bool,
255    flavor: crate::config::MarkdownFlavor,
256    source_file: Option<std::path::PathBuf>,
257    config: Option<&crate::config::Config>,
258) -> LintResult {
259    let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
260    result
261}
262
263/// Build FileIndex only (no linting) for cross-file analysis on cache hits
264///
265/// This is a lightweight function that only builds the FileIndex without running
266/// any rules. Used when we have a cache hit but still need the FileIndex for
267/// cross-file validation.
268///
269/// This avoids the overhead of re-running all rules when only the index data is needed.
270pub fn build_file_index_only(
271    content: &str,
272    rules: &[Box<dyn Rule>],
273    flavor: crate::config::MarkdownFlavor,
274    source_file: Option<std::path::PathBuf>,
275) -> crate::workspace_index::FileIndex {
276    build_file_index_only_with_config(content, rules, flavor, source_file, &crate::config::Config::default())
277}
278
279/// Build an index using the document's conflict-marker configuration.
280/// This keeps cache hits and workspace scans consistent with ordinary linting.
281///
282/// `rules` contributes the cross-file data and may be a role-scoped subset, so
283/// configuration decides whether a conflicted document indexes. A caller holding
284/// the invocation's resolved rule selection wants
285/// `build_file_index_only_for_selection` instead, so the index agrees with what
286/// that run reports.
287pub fn build_file_index_only_with_config(
288    content: &str,
289    rules: &[Box<dyn Rule>],
290    flavor: crate::config::MarkdownFlavor,
291    source_file: Option<std::path::PathBuf>,
292    config: &crate::config::Config,
293) -> crate::workspace_index::FileIndex {
294    let conflicted = crate::merge_conflict::detect_configured(content, config, source_file.as_deref()).is_some();
295    build_index(content, rules, flavor, source_file, conflicted)
296}
297
298/// Build an index for a run whose resolved rule selection is `selection`.
299/// The list that decides whether the run reports MD092 decides whether the
300/// document indexes, so a run that dropped the rule indexes a conflicted
301/// document like any other file rather than reporting links into it as broken.
302pub fn build_file_index_only_for_selection(
303    content: &str,
304    selection: &[Box<dyn Rule>],
305    flavor: crate::config::MarkdownFlavor,
306    source_file: Option<std::path::PathBuf>,
307    config: &crate::config::Config,
308) -> crate::workspace_index::FileIndex {
309    let conflicted =
310        crate::merge_conflict::detect_for_rules(content, selection, config, source_file.as_deref()).is_some();
311    build_index(content, selection, flavor, source_file, conflicted)
312}
313
314fn build_index(
315    content: &str,
316    rules: &[Box<dyn Rule>],
317    flavor: crate::config::MarkdownFlavor,
318    source_file: Option<std::path::PathBuf>,
319    conflicted: bool,
320) -> crate::workspace_index::FileIndex {
321    // Compute content hash for change detection
322    let content_hash = compute_content_hash(content);
323    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
324
325    // A conflicted document indexes as nothing, so a link into it reports its
326    // fragment as missing rather than resolving against half-merged headings.
327    if conflicted {
328        return file_index;
329    }
330
331    // Early return for empty content
332    if content.is_empty() {
333        return file_index;
334    }
335
336    // Parse LintContext once with the provided flavor
337    let lint_ctx = time_function!(
338        "index: parse lint context",
339        crate::lint_context::LintContext::new(content, flavor, source_file)
340    );
341
342    // Export inline disable data to the FileIndex so cross-file checks honor
343    // `<!-- rumdl-disable -->` blocks on the lint-cache fast path, exactly as
344    // lint_and_index does on the normal path.
345    let (file_disabled, persistent_transitions, line_disabled) = lint_ctx.inline_config().export_for_file_index();
346    file_index.file_disabled_rules = file_disabled;
347    file_index.persistent_transitions = persistent_transitions;
348    file_index.line_disabled_rules = line_disabled;
349
350    // Only call contribute_to_index for cross-file rules (no rule checking!)
351    time_section!("index: contribute cross-file data", {
352        for rule in rules {
353            if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
354                rule.contribute_to_index(&lint_ctx, &mut file_index);
355            }
356        }
357    });
358
359    file_index
360}
361
362/// Rewrite every fix replacement in the document's own line ending.
363///
364/// Rules build a fix on LF text, so a line ending they insert is `\n`, and the
365/// CLI really does hand them LF: it normalises a file on read and restores the
366/// endings on write. The LSP and wasm lint the editor's or host's text as it is,
367/// and a quick fix that inserted a bare `\n` into a CRLF document left it with
368/// mixed endings. Conforming here, where every rule's warnings meet, settles it
369/// for every caller and every rule at once. In a document with mixed endings a
370/// fix takes the ending of the line it follows, as `rumdl fmt` writes it.
371fn conform_fix_line_endings(content: &str, warnings: &mut [crate::rule::LintWarning]) {
372    if !content.contains('\r') {
373        return;
374    }
375    let mixed = match crate::utils::detect_line_ending_enum(content) {
376        crate::utils::LineEnding::Lf => return,
377        crate::utils::LineEnding::Crlf => false,
378        crate::utils::LineEnding::Mixed => true,
379    };
380    fn conform(content: &str, mixed: bool, fix: &mut crate::rule::Fix) {
381        if fix.replacement.contains('\n')
382            && (!mixed || crate::utils::line_ending_before(content, fix.range.start) == "\r\n")
383        {
384            fix.replacement =
385                crate::utils::normalize_line_ending(&fix.replacement, crate::utils::LineEnding::Crlf).into_owned();
386        }
387        for extra in &mut fix.additional_edits {
388            conform(content, mixed, extra);
389        }
390    }
391    for fix in warnings.iter_mut().filter_map(|warning| warning.fix.as_mut()) {
392        conform(content, mixed, fix);
393    }
394}
395
396/// Drop the warnings a document silences, and apply any configured severity override
397/// to the rest.
398///
399/// A warning is dropped when it sits in a kramdown extension block or when an inline
400/// comment disables its rule somewhere in its range. `suppressed`, when given,
401/// collects what the inline comments removed, for the rules that report on them. A
402/// kramdown extension block is not an inline comment, so what it drops is left out.
403pub(crate) fn retain_reportable_warnings(
404    lint_ctx: &crate::lint_context::LintContext,
405    config: Option<&crate::config::Config>,
406    rule_name: &str,
407    rule_warnings: Vec<crate::rule::LintWarning>,
408    mut suppressed: Option<&mut Vec<crate::rule::SuppressedWarning>>,
409) -> Vec<crate::rule::LintWarning> {
410    let inline_config = lint_ctx.inline_config();
411    let mut kept = Vec::with_capacity(rule_warnings.len());
412
413    for mut warning in rule_warnings {
414        if lint_ctx
415            .line_info(warning.line)
416            .is_some_and(|info| info.in_kramdown_extension_block)
417        {
418            continue;
419        }
420
421        // Use the warning's rule_name if available, otherwise use the rule's name
422        let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule_name);
423
424        // Extract the base rule name for sub-rules like "MD029-style" -> "MD029"
425        let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
426            &rule_name_to_check[..dash_pos]
427        } else {
428            rule_name_to_check
429        };
430
431        // Check if the rule is disabled at any line in the warning's range.
432        // Multi-line warnings (e.g., reflow) report on the first line,
433        // but inline disable comments may appear later in the range.
434        // Guard: if end_line < line (e.g., end_line=0), fall back to
435        // checking only the warning's line to match original behavior.
436        let end = if warning.end_line >= warning.line {
437            warning.end_line
438        } else {
439            warning.line
440        };
441        let disabled_at = (warning.line..=end).find_map(|line| {
442            inline_config
443                .disabling_layer(base_rule_name, line)
444                .map(|layer| (line, layer))
445        });
446        if let Some((line, layer)) = disabled_at {
447            if let Some(record) = suppressed.as_deref_mut() {
448                record.push(crate::rule::SuppressedWarning {
449                    rule_name: base_rule_name.to_string(),
450                    line,
451                    layer,
452                });
453            }
454            continue;
455        }
456
457        // Apply severity override from config if present
458        if let Some(cfg) = config
459            && let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check)
460        {
461            warning.severity = override_severity;
462        }
463
464        kept.push(warning);
465    }
466
467    kept
468}
469
470/// Lint a file and contribute to workspace index for cross-file analysis
471///
472/// This variant performs linting and optionally populates a `FileIndex` with data
473/// needed for cross-file validation. The FileIndex is populated during linting,
474/// avoiding duplicate parsing.
475///
476/// Returns: (warnings, FileIndex) - the FileIndex contains headings/links for cross-file rules
477#[cfg_attr(test, allow(unused_variables))]
478#[allow(clippy::needless_pass_by_value)] // Public compatibility: callers already pass an owned path.
479pub fn lint_and_index(
480    content: &str,
481    rules: &[Box<dyn Rule>],
482    verbose: bool,
483    flavor: crate::config::MarkdownFlavor,
484    source_file: Option<std::path::PathBuf>,
485    config: Option<&crate::config::Config>,
486) -> (LintResult, crate::workspace_index::FileIndex) {
487    lint_and_index_with_paths(
488        content,
489        rules,
490        verbose,
491        flavor,
492        DocumentPaths::same(source_file.as_deref()),
493        config,
494    )
495}
496
497/// The two path roles involved in document processing.
498#[derive(Debug, Clone, Copy, Default)]
499pub struct DocumentPaths<'a> {
500    /// Logical path used for per-file configuration matching.
501    pub config_path: Option<&'a std::path::Path>,
502    /// Native path exposed to filesystem-aware rules.
503    pub source_file: Option<&'a std::path::Path>,
504    /// Run-scoped virtual paths visible to filesystem-aware link rules.
505    pub link_target_policy: Option<&'a crate::lint_context::LinkTargetPolicy>,
506    /// The invalid UTF-8 sequences a lossily decoded document was read with.
507    pub invalid_utf8: Option<&'a [crate::encoding::InvalidSeq]>,
508}
509
510impl<'a> DocumentPaths<'a> {
511    /// Use one native path for both roles.
512    pub fn same(path: Option<&'a std::path::Path>) -> Self {
513        Self {
514            config_path: path,
515            source_file: path,
516            link_target_policy: None,
517            invalid_utf8: None,
518        }
519    }
520}
521
522/// Lint a document while keeping configuration matching separate from filesystem context.
523///
524/// `paths.config_path` selects per-file ignores and other path-scoped configuration.
525/// `paths.source_file` is exposed to rules that need a real filesystem location. Native
526/// adapters normally pass the same path for both; virtual adapters can supply only
527/// `config_path` without accidentally enabling filesystem-dependent rule behavior.
528#[cfg_attr(test, allow(unused_variables))]
529pub fn lint_and_index_with_paths(
530    content: &str,
531    rules: &[Box<dyn Rule>],
532    verbose: bool,
533    flavor: crate::config::MarkdownFlavor,
534    paths: DocumentPaths<'_>,
535    config: Option<&crate::config::Config>,
536) -> (LintResult, crate::workspace_index::FileIndex) {
537    let mut warnings = Vec::new();
538    // Compute content hash for change detection
539    let content_hash = compute_content_hash(content);
540    let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
541
542    let conflict = config.map_or_else(
543        || {
544            crate::merge_conflict::detect_for_rules(
545                content,
546                rules,
547                &crate::config::Config::default(),
548                paths.config_path,
549            )
550        },
551        |config| crate::merge_conflict::detect_for_rules(content, rules, config, paths.config_path),
552    );
553    if let Some(conflict) = conflict {
554        return (Ok(vec![conflict]), file_index);
555    }
556
557    // Early return for empty content
558    if content.is_empty() {
559        return (Ok(warnings), file_index);
560    }
561
562    // The rules `per-file-ignores` takes away for this file. It decides what this
563    // file REPORTS, and nothing else: the index contribution at the end of this
564    // function deliberately keeps running every cross-file rule, because a file's
565    // headings and links belong to the workspace rather than to its own report.
566    // Dropping a rule from the index instead would break the links pointing HERE,
567    // in files that never named it.
568    let ignored_for_file = match (config, paths.config_path) {
569        (Some(cfg), Some(path)) => cfg.get_ignored_rules_for_file(path),
570        _ => std::collections::HashSet::new(),
571    };
572
573    // Parse LintContext once (includes inline config parsing)
574    let lint_ctx = time_function!(
575        "lint: parse lint context",
576        crate::lint_context::LintContext::new(content, flavor, paths.source_file.map(std::path::Path::to_path_buf))
577    );
578    let lint_ctx = match paths.link_target_policy {
579        Some(policy) => lint_ctx.with_link_target_policy(policy.clone()),
580        None => lint_ctx,
581    };
582    let lint_ctx = match paths.invalid_utf8 {
583        Some(invalid) => lint_ctx.with_invalid_utf8(invalid),
584        None => lint_ctx,
585    };
586    let inline_config = lint_ctx.inline_config();
587
588    // Export inline config data to FileIndex for cross-file rule filtering
589    let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
590    file_index.file_disabled_rules = file_disabled;
591    file_index.persistent_transitions = persistent_transitions;
592    file_index.line_disabled_rules = line_disabled;
593
594    // Analyze content characteristics for rule filtering
595    let characteristics = time_function!(
596        "lint: analyze content characteristics",
597        ContentCharacteristics::analyze(content)
598    );
599
600    // Filter rules based on per-file-ignores and content characteristics
601    let applicable_rules: Vec<_> = rules
602        .iter()
603        .filter(|rule| !ignored_for_file.contains(rule.name()))
604        .filter(|rule| !(rule.skippable_by_category() && characteristics.should_skip_rule(rule.as_ref())))
605        .collect();
606
607    // Calculate skipped rules count before consuming applicable_rules
608    #[cfg(not(test))]
609    let total_rules = rules.len();
610    #[cfg(not(test))]
611    let applicable_count = applicable_rules.len();
612
613    #[cfg(not(target_arch = "wasm32"))]
614    let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
615
616    // Automatic inline config support: merge inline overrides into config once,
617    // then recreate only the affected rules. Works for ALL rules without per-rule changes.
618    let inline_overrides = inline_config.get_all_rule_configs();
619    let merged_config = if !inline_overrides.is_empty() {
620        config.map(|c| c.merge_with_inline_config(inline_config))
621    } else {
622        None
623    };
624    let effective_config = merged_config.as_ref().or(config);
625
626    // Cache recreated rules for rules with inline overrides
627    let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
628        std::collections::HashMap::new();
629
630    // Pre-create rules that have inline config overrides
631    if let Some(cfg) = effective_config {
632        for rule_name in inline_overrides.keys() {
633            if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
634                recreated_rules.insert(rule_name.clone(), recreated);
635            }
636        }
637    }
638
639    // A rule reporting on the run's inline disable comments needs to know what they
640    // removed, which costs a record per suppressed warning, so it is only kept when
641    // such a rule is going to read it.
642    let suppression_observers: Vec<_> = applicable_rules
643        .iter()
644        .filter(|rule| rule.observes_suppressions() && !rule.should_skip(&lint_ctx))
645        .collect();
646    let mut suppressed = Vec::new();
647
648    {
649        let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
650        for rule in &applicable_rules {
651            #[cfg(not(target_arch = "wasm32"))]
652            let rule_start = Instant::now();
653
654            // Skip rules that indicate they should be skipped (opt-in rules, content-based skipping)
655            if rule.should_skip(&lint_ctx) {
656                continue;
657            }
658
659            // Use recreated rule if inline config overrides exist for this rule
660            let effective_rule: &dyn crate::rule::Rule = recreated_rules
661                .get(rule.name())
662                .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
663
664            // Run single-file check with the effective rule (possibly with inline config applied)
665            let result = effective_rule.check(&lint_ctx);
666
667            match result {
668                Ok(rule_warnings) => {
669                    let record = if suppression_observers.is_empty() {
670                        None
671                    } else {
672                        Some(&mut suppressed)
673                    };
674                    let filtered_warnings =
675                        retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, record);
676                    warnings.extend(filtered_warnings);
677                }
678                Err(e) => {
679                    log::error!("Error checking rule {}: {}", rule.name(), e);
680                    return (Err(e), file_index);
681                }
682            }
683
684            #[cfg(not(target_arch = "wasm32"))]
685            {
686                let rule_duration = rule_start.elapsed();
687                if profile_rules {
688                    eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
689                }
690
691                #[cfg(not(test))]
692                if verbose && rule_duration.as_millis() > 500 {
693                    log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
694                }
695            }
696        }
697    }
698
699    // Report on the inline disable comments, now that every single-file rule has run
700    // and the suppressions are complete.
701    if !suppression_observers.is_empty() {
702        let _timer = profiling::ScopedTimer::new("lint: run suppression rules");
703
704        // A workspace-scope rule has its warnings filtered after this point, and for a
705        // single-file run not at all, so its findings never reach the report and
706        // nothing can be concluded about a comment naming it. A rule this file
707        // ignores does not report either, for the same reason.
708        let report = crate::rule::SuppressionReport {
709            suppressed,
710            judged_rules: rules
711                .iter()
712                .filter(|rule| rule.cross_file_scope() != crate::rule::CrossFileScope::Workspace)
713                .filter(|rule| !ignored_for_file.contains(rule.name()))
714                .map(|rule| rule.name().to_string())
715                .collect(),
716        };
717
718        for rule in &suppression_observers {
719            match rule.check_suppressions(&lint_ctx, &report) {
720                Ok(rule_warnings) => {
721                    let filtered_warnings =
722                        retain_reportable_warnings(&lint_ctx, config, rule.name(), rule_warnings, None);
723                    warnings.extend(filtered_warnings);
724                }
725                Err(e) => {
726                    log::error!("Error checking rule {}: {}", rule.name(), e);
727                    return (Err(e), file_index);
728                }
729            }
730        }
731    }
732
733    // Contribute to index for cross-file rules (done after all rules checked)
734    // NOTE: We iterate over ALL rules (not just applicable_rules) because cross-file
735    // rules need to extract data from every file in the workspace, regardless of whether
736    // that file has content that would trigger the rule, and regardless of what this
737    // file's own configuration reports. For example, MD051 needs to index headings from
738    // files that have no links (like target.md) so that links FROM other files TO those
739    // headings can be validated - including from a file that ignores MD051 itself.
740    time_section!("lint: contribute cross-file data", {
741        for rule in rules {
742            if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
743                rule.contribute_to_index(&lint_ctx, &mut file_index);
744            }
745        }
746    });
747
748    #[cfg(not(test))]
749    if verbose {
750        let skipped_rules = total_rules - applicable_count;
751        if skipped_rules > 0 {
752            log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
753        }
754    }
755
756    if paths.invalid_utf8.is_some() {
757        crate::encoding::settle_lossy_warnings(&mut warnings);
758    }
759
760    conform_fix_line_endings(content, &mut warnings);
761
762    (Ok(warnings), file_index)
763}
764
765/// Run cross-file checks for rules that need workspace-wide validation
766///
767/// This should be called after all files have been linted and the WorkspaceIndex
768/// has been built from the accumulated FileIndex data.
769///
770/// Note: This takes the FileIndex instead of content to avoid re-parsing each file.
771/// The FileIndex was already populated during contribute_to_index in the linting phase.
772///
773/// Rules can use workspace_index methods for cross-file validation:
774/// - `get_file(path)` - to look up headings in target files (for MD051)
775///
776/// Returns additional warnings from cross-file validation.
777pub fn run_cross_file_checks(
778    file_path: &std::path::Path,
779    file_index: &crate::workspace_index::FileIndex,
780    rules: &[Box<dyn Rule>],
781    workspace_index: &crate::workspace_index::WorkspaceIndex,
782    config: Option<&crate::config::Config>,
783) -> LintResult {
784    use crate::rule::CrossFileScope;
785
786    let mut warnings = Vec::new();
787
788    // Honor `per-file-ignores` for cross-file rules. Cross-file warnings are
789    // attributed to `file_path` (the file holding the link), so a rule ignored
790    // for that file must not emit them. This applies on every path; single-file
791    // rule filtering does not cover cross-file checks because they run over the
792    // config group's full rule set, and cross-file rules share link data.
793    let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
794
795    // Only check rules that need cross-file analysis
796    for rule in rules {
797        if rule.cross_file_scope() != CrossFileScope::Workspace {
798            continue;
799        }
800
801        if ignored_rules_for_file
802            .as_ref()
803            .is_some_and(|ignored| ignored.contains(rule.name()))
804        {
805            continue;
806        }
807
808        match time_function!(
809            "workspace: cross-file rule check",
810            rule.cross_file_check(file_path, file_index, workspace_index)
811        ) {
812            Ok(rule_warnings) => {
813                // Filter cross-file warnings based on inline config stored in file_index
814                let filtered: Vec<_> = rule_warnings
815                    .into_iter()
816                    .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
817                    .map(|mut warning| {
818                        // Apply severity override from config if present
819                        if let Some(cfg) = config
820                            && let Some(override_severity) = cfg.get_rule_severity(rule.name())
821                        {
822                            warning.severity = override_severity;
823                        }
824                        warning
825                    })
826                    .collect();
827                warnings.extend(filtered);
828            }
829            Err(e) => {
830                log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
831                return Err(e);
832            }
833        }
834    }
835
836    Ok(warnings)
837}
838
839/// Get the profiling report
840pub fn get_profiling_report() -> String {
841    profiling::get_report()
842}
843
844/// Reset the profiling data
845pub fn reset_profiling() {
846    profiling::reset()
847}
848
849/// Get regex cache statistics for performance monitoring
850pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
851    crate::utils::regex_cache::get_cache_stats()
852}
853
854#[cfg(test)]
855mod tests {
856    use super::*;
857    use crate::rule::Rule;
858    use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
859
860    #[test]
861    fn test_content_characteristics_analyze() {
862        // Test empty content
863        let chars = ContentCharacteristics::analyze("");
864        assert!(!chars.has_headings);
865        assert!(!chars.has_lists);
866        assert!(!chars.has_links);
867        assert!(!chars.has_code);
868        assert!(!chars.has_emphasis);
869        assert!(!chars.has_html);
870        assert!(!chars.has_tables);
871        assert!(!chars.has_blockquotes);
872        assert!(!chars.has_images);
873
874        // Test content with headings
875        let chars = ContentCharacteristics::analyze("# Heading");
876        assert!(chars.has_headings);
877
878        // Test setext headings
879        let chars = ContentCharacteristics::analyze("Heading\n=======");
880        assert!(chars.has_headings);
881
882        // Blockquoted ATX headings emit fragment anchors, so Heading-category
883        // rules (MD051/MD080) must run for blockquote-only documents.
884        let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
885        assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
886        let chars = ContentCharacteristics::analyze(">> # Nested");
887        assert!(
888            chars.has_headings,
889            "nested-blockquote ATX heading must set has_headings"
890        );
891        // A tab after the blockquote marker is also a valid heading
892        // (`parse_blockquote_prefix` accepts it).
893        let chars = ContentCharacteristics::analyze(">\t## Tabbed");
894        assert!(
895            chars.has_headings,
896            "tab-separated blockquote ATX heading must set has_headings"
897        );
898
899        // Test lists
900        let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
901        assert!(chars.has_lists);
902
903        // Test ordered lists
904        let chars = ContentCharacteristics::analyze("1. First\n2. Second");
905        assert!(chars.has_lists);
906
907        // Test links
908        let chars = ContentCharacteristics::analyze("[link](url)");
909        assert!(chars.has_links);
910
911        // Test URLs
912        let chars = ContentCharacteristics::analyze("Visit https://example.com");
913        assert!(chars.has_links);
914
915        // Test images
916        let chars = ContentCharacteristics::analyze("![alt text](image.png)");
917        assert!(chars.has_images);
918
919        // Test code
920        let chars = ContentCharacteristics::analyze("`inline code`");
921        assert!(chars.has_code);
922
923        let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
924        assert!(chars.has_code);
925
926        // Test indented code blocks (4 spaces)
927        let chars = ContentCharacteristics::analyze("Text\n\n    indented code\n\nMore text");
928        assert!(chars.has_code);
929
930        // Test tab-indented code blocks
931        let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
932        assert!(chars.has_code);
933
934        // Test mixed whitespace indented code (2 spaces + tab = 4 columns)
935        let chars = ContentCharacteristics::analyze("Text\n\n  \tmixed indent code\n\nMore text");
936        assert!(chars.has_code);
937
938        // Test 1 space + tab (also 4 columns due to tab expansion)
939        let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
940        assert!(chars.has_code);
941
942        // Test emphasis
943        let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
944        assert!(chars.has_emphasis);
945
946        // Test HTML
947        let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
948        assert!(chars.has_html);
949
950        // Test tables
951        let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
952        assert!(chars.has_tables);
953
954        // Test blockquotes
955        let chars = ContentCharacteristics::analyze("> Quote");
956        assert!(chars.has_blockquotes);
957
958        // Test mixed content
959        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)";
960        let chars = ContentCharacteristics::analyze(content);
961        assert!(chars.has_headings);
962        assert!(chars.has_lists);
963        assert!(chars.has_links);
964        assert!(chars.has_code);
965        assert!(chars.has_emphasis);
966        assert!(chars.has_html);
967        assert!(chars.has_tables);
968        assert!(chars.has_blockquotes);
969        assert!(chars.has_images);
970    }
971
972    #[test]
973    fn test_content_characteristics_parenthesized_ordered_list() {
974        assert!(ContentCharacteristics::analyze("1) first\n2) second").has_lists);
975        assert!(ContentCharacteristics::analyze("  1) indented first\n  2) second").has_lists);
976        assert!(ContentCharacteristics::analyze("> 1) quoted item").has_lists);
977    }
978
979    #[test]
980    fn test_content_characteristics_should_skip_rule() {
981        let chars = ContentCharacteristics {
982            has_headings: true,
983            has_lists: false,
984            has_links: true,
985            has_code: false,
986            has_emphasis: true,
987            has_html: false,
988            has_tables: true,
989            has_blockquotes: false,
990            has_images: false,
991        };
992
993        // Create test rules for different categories
994        let heading_rule = MD001HeadingIncrement::default();
995        assert!(!chars.should_skip_rule(&heading_rule));
996
997        let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
998        assert!(!chars.should_skip_rule(&trailing_spaces_rule)); // Whitespace rules always run
999
1000        // Test skipping based on content
1001        let chars_no_headings = ContentCharacteristics {
1002            has_headings: false,
1003            ..Default::default()
1004        };
1005        assert!(chars_no_headings.should_skip_rule(&heading_rule));
1006    }
1007
1008    #[test]
1009    fn test_lint_empty_content() {
1010        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1011
1012        let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
1013        assert!(result.is_ok());
1014        assert!(result.unwrap().is_empty());
1015    }
1016
1017    #[test]
1018    fn test_lint_with_violations() {
1019        let content = "## Level 2\n#### Level 4"; // Skips level 3
1020        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1021
1022        let result = lint(
1023            content,
1024            &rules,
1025            false,
1026            crate::config::MarkdownFlavor::Standard,
1027            None,
1028            None,
1029        );
1030        assert!(result.is_ok());
1031        let warnings = result.unwrap();
1032        assert!(!warnings.is_empty());
1033        // Check the rule field of LintWarning struct
1034        assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
1035    }
1036
1037    #[test]
1038    fn test_lint_with_inline_disable() {
1039        let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
1040        let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1041
1042        let result = lint(
1043            content,
1044            &rules,
1045            false,
1046            crate::config::MarkdownFlavor::Standard,
1047            None,
1048            None,
1049        );
1050        assert!(result.is_ok());
1051        let warnings = result.unwrap();
1052        assert!(warnings.is_empty()); // Should be disabled by inline comment
1053    }
1054
1055    #[test]
1056    fn test_lint_checks_setext_headings_the_content_prefilter_must_keep() {
1057        // Each document holds two headings with the same anchor and nothing else
1058        // that looks like a heading, so the heading rules run only if the
1059        // prefilter recognizes the underline.
1060        let rules: Vec<Box<dyn Rule>> = vec![Box::new(crate::rules::MD080HeadingAnchorCollision::new())];
1061        for content in [
1062            "Title\n-\n\ntitle\n-\n",
1063            "Title\n=\n\ntitle\n=\n",
1064            "> Title\n> ===\n\n> title\n> ===\n",
1065            "> Title\n> -\n\n> title\n> -\n",
1066        ] {
1067            let warnings = lint(
1068                content,
1069                &rules,
1070                false,
1071                crate::config::MarkdownFlavor::Standard,
1072                None,
1073                None,
1074            )
1075            .unwrap();
1076            let lines: Vec<_> = warnings.iter().map(|warning| warning.line).collect();
1077            assert_eq!(lines, [4], "{content:?}");
1078        }
1079    }
1080
1081    #[test]
1082    fn test_lint_rule_filtering() {
1083        // Content with no lists
1084        let content = "# Heading\nJust text";
1085        let rules: Vec<Box<dyn Rule>> = vec![
1086            Box::new(MD001HeadingIncrement::default()),
1087            // A list-related rule would be skipped
1088        ];
1089
1090        let result = lint(
1091            content,
1092            &rules,
1093            false,
1094            crate::config::MarkdownFlavor::Standard,
1095            None,
1096            None,
1097        );
1098        assert!(result.is_ok());
1099    }
1100
1101    #[test]
1102    fn test_get_profiling_report() {
1103        // Just test that it returns a string without panicking
1104        let report = get_profiling_report();
1105        assert!(!report.is_empty());
1106        assert!(report.contains("Profiling"));
1107    }
1108
1109    #[test]
1110    fn test_reset_profiling() {
1111        // Test that reset_profiling doesn't panic
1112        reset_profiling();
1113
1114        // After reset, report should indicate no measurements or profiling disabled
1115        let report = get_profiling_report();
1116        assert!(report.contains("disabled") || report.contains("no measurements"));
1117    }
1118
1119    #[test]
1120    fn test_get_regex_cache_stats() {
1121        let stats = get_regex_cache_stats();
1122        // Stats should be a valid HashMap (might be empty)
1123        assert!(stats.is_empty() || !stats.is_empty());
1124
1125        // If not empty, all values should be positive
1126        for count in stats.values() {
1127            assert!(*count > 0);
1128        }
1129    }
1130
1131    #[test]
1132    fn test_content_characteristics_edge_cases() {
1133        // A setext underline is any run of `=` or `-`, a single character
1134        // included, and one in a blockquote follows the quote's markers.
1135        for content in [
1136            "Title\n-",
1137            "Title\n=",
1138            "Title\n--",
1139            "> Title\n> ===",
1140            ">\tTitle\n>\t-",
1141            ">> Title\n>>-",
1142        ] {
1143            assert!(ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1144        }
1145        for content in ["> Prose\n>", "Prose\n> text", "Prose\n"] {
1146            assert!(!ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1147        }
1148
1149        // Test list detection - we now include potential list patterns (with or without space)
1150        // to support user-intention detection in MD030
1151        let chars = ContentCharacteristics::analyze("*emphasis*"); // Could be list or emphasis
1152        assert!(chars.has_lists); // Run list rules to be safe
1153
1154        let chars = ContentCharacteristics::analyze("1.Item"); // Could be list without space
1155        assert!(chars.has_lists); // Run list rules for user-intention detection
1156
1157        // Test blockquote must be at start of line
1158        let chars = ContentCharacteristics::analyze("text > not a quote");
1159        assert!(!chars.has_blockquotes);
1160    }
1161
1162    /// One document that draws a line-inserting fix from every rule known to
1163    /// write a bare `\n` into its replacement: MD071 (blank line after front
1164    /// matter), MD022 (blank lines around headings), MD032 (around lists),
1165    /// MD031 (around fences), MD014 (dollar prompts), MD058 (around tables) and
1166    /// MD047 (final newline).
1167    const LINE_INSERTING_FIXES: &str = "---\ntitle: x\n---\n# Heading\ntext\n## Sub\n- item\ntext\n```sh\n$ ls\n```\ntext\n| a | b |\n|---|---|\n| 1 | 2 |\ntext";
1168
1169    /// Every fix replacement (and additional edit) of every warning, keyed by rule.
1170    fn fix_replacements(content: &str) -> Vec<(String, String)> {
1171        let config = crate::config::Config::default();
1172        let rules = crate::rules::all_rules(&config);
1173        let warnings = lint(
1174            content,
1175            &rules,
1176            false,
1177            crate::config::MarkdownFlavor::Standard,
1178            None,
1179            Some(&config),
1180        )
1181        .unwrap();
1182        let mut out = Vec::new();
1183        for warning in warnings {
1184            let Some(fix) = warning.fix else { continue };
1185            let rule = warning.rule_name.clone().unwrap_or_default();
1186            let mut stack = vec![fix];
1187            while let Some(fix) = stack.pop() {
1188                out.push((rule.clone(), fix.replacement.clone()));
1189                stack.extend(fix.additional_edits);
1190            }
1191        }
1192        out
1193    }
1194
1195    fn has_bare_lf(text: &str) -> bool {
1196        let bytes = text.as_bytes();
1197        bytes
1198            .iter()
1199            .enumerate()
1200            .any(|(i, b)| *b == b'\n' && (i == 0 || bytes[i - 1] != b'\r'))
1201    }
1202
1203    #[test]
1204    fn fix_replacements_use_the_documents_crlf_line_ending() {
1205        let crlf = LINE_INSERTING_FIXES.replace('\n', "\r\n");
1206        let replacements = fix_replacements(&crlf);
1207
1208        let bare: Vec<_> = replacements.iter().filter(|(_, r)| has_bare_lf(r)).collect();
1209        assert!(bare.is_empty(), "bare LF in a fix for a CRLF document: {bare:?}");
1210
1211        // Positive control: the rules this document was written for did fire and
1212        // did insert a line ending, so the assertion above examined real fixes.
1213        let mut crlf_rules: Vec<_> = replacements
1214            .iter()
1215            .filter(|(_, r)| r.contains("\r\n"))
1216            .map(|(rule, _)| rule.as_str())
1217            .collect();
1218        crlf_rules.sort_unstable();
1219        crlf_rules.dedup();
1220        for rule in ["MD014", "MD022", "MD031", "MD032", "MD047", "MD058", "MD071"] {
1221            assert!(
1222                crlf_rules.contains(&rule),
1223                "{rule} inserted no CRLF line ending; got {crlf_rules:?}"
1224            );
1225        }
1226    }
1227
1228    #[test]
1229    fn fix_replacements_stay_lf_for_lf_documents() {
1230        // The same rules on the LF document write `\n`, untouched.
1231        let lf = fix_replacements(LINE_INSERTING_FIXES);
1232        assert!(lf.iter().any(|(_, r)| has_bare_lf(r)));
1233        assert!(!lf.iter().any(|(_, r)| r.contains('\r')));
1234    }
1235
1236    #[test]
1237    fn fix_replacements_in_a_mixed_document_take_the_ending_of_the_line_they_follow() {
1238        // Every other line ends in CRLF.
1239        let mixed: String = LINE_INSERTING_FIXES
1240            .split_inclusive('\n')
1241            .enumerate()
1242            .map(|(i, line)| {
1243                if i % 2 == 0 {
1244                    line.replace('\n', "\r\n")
1245                } else {
1246                    line.to_string()
1247                }
1248            })
1249            .collect();
1250        assert_eq!(
1251            crate::utils::detect_line_ending_enum(&mixed),
1252            crate::utils::LineEnding::Mixed
1253        );
1254
1255        // The ending of the line holding the byte before `offset`, by line.
1256        let ending_before = |offset: usize| {
1257            let target = offset.saturating_sub(1);
1258            let mut start = 0;
1259            let mut last_ending = "\n";
1260            for line in mixed.split_inclusive('\n') {
1261                let ending = if line.ends_with("\r\n") {
1262                    "\r\n"
1263                } else if line.ends_with('\n') {
1264                    "\n"
1265                } else {
1266                    last_ending
1267                };
1268                if target < start + line.len() {
1269                    return ending;
1270                }
1271                last_ending = ending;
1272                start += line.len();
1273            }
1274            last_ending
1275        };
1276
1277        let config = crate::config::Config::default();
1278        let rules = crate::rules::all_rules(&config);
1279        let warnings = lint(
1280            &mixed,
1281            &rules,
1282            false,
1283            crate::config::MarkdownFlavor::Standard,
1284            None,
1285            Some(&config),
1286        )
1287        .unwrap();
1288        let mut seen = [false, false];
1289        let mut stack: Vec<_> = warnings.into_iter().filter_map(|warning| warning.fix).collect();
1290        while let Some(fix) = stack.pop() {
1291            if fix.replacement.contains('\n') {
1292                let crlf = ending_before(fix.range.start) == "\r\n";
1293                seen[usize::from(crlf)] = true;
1294                assert_eq!(
1295                    has_bare_lf(&fix.replacement),
1296                    !crlf,
1297                    "replacement {:?} at {} in {mixed:?}",
1298                    fix.replacement,
1299                    fix.range.start
1300                );
1301            }
1302            stack.extend(fix.additional_edits);
1303        }
1304        assert_eq!(seen, [true, true], "fixture should insert lines after both endings");
1305    }
1306}