Skip to main content

aft_parse/
line_matcher.rs

1//! Shared line-sequence matching for edit diagnostics and patch application.
2//!
3//! This module intentionally does not reuse `fuzzy_match`: edit matching works in byte
4//! ranges, while apply_patch needs line indexes, EOF anchoring, and unique-only reflow.
5
6use std::collections::{HashMap, HashSet};
7
8/// Avoid spending diagnostic work or memory on files too large to render usefully in an error.
9pub const NEAREST_MISS_MAX_FILE_BYTES: usize = 2 * 1024 * 1024;
10
11const NEAREST_MISS_ANCHOR_COUNT: usize = 3;
12const NEAREST_MISS_MAX_CANDIDATES: usize = 512;
13const NEAREST_MISS_MAX_POSITIONS_PER_ANCHOR: usize = 192;
14const NEAREST_MISS_MAX_LINE_COMPARISONS: usize = 100_000;
15const NEAREST_MISS_MAX_FUZZY_CHARS: usize = 256;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct NearestMiss {
19    /// Zero-based first line of the candidate window.
20    pub start: usize,
21    /// Zero-based exclusive end of the available candidate window.
22    pub end: usize,
23    pub matched_lines: usize,
24    /// Zero-based wanted-line offset of the first mismatch.
25    pub first_divergence: usize,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum NearestMissSearch {
30    Found(NearestMiss),
31    NoSimilarRegion,
32    SkippedLargeFile,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum MatchTier {
37    Exact,
38    Rstrip,
39    Trim,
40    Indent,
41    Unicode,
42    Reflow,
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct SequenceMatch {
47    pub found: usize,
48    pub tier: MatchTier,
49    pub line_count: usize,
50}
51
52/// Convert smart quotes, dash variants, ellipsis, and NBSP to their ASCII forms; mirrors `patch-parser.ts:207-214`.
53pub fn normalize_unicode(input: &str) -> String {
54    #[cfg(any(test, feature = "test-support"))]
55    NORMALIZED_LINE_ALLOCATIONS.with(|count| count.set(count.get() + 1));
56    let mut normalized = String::with_capacity(input.len());
57    for ch in input.chars() {
58        match ch {
59            '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' => normalized.push('\''),
60            '\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' => normalized.push('"'),
61            '\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2014}' | '\u{2015}' => {
62                normalized.push('-');
63            }
64            '\u{2026}' => normalized.push_str("..."),
65            '\u{00A0}' => normalized.push(' '),
66            _ => normalized.push(ch),
67        }
68    }
69    normalized
70}
71
72/// Replace a leading run of tabs and spaces with the same number of plain spaces; mirrors `patch-parser.ts:227-229`.
73pub fn normalize_indent(input: &str) -> String {
74    #[cfg(any(test, feature = "test-support"))]
75    NORMALIZED_LINE_ALLOCATIONS.with(|count| count.set(count.get() + 1));
76    let mut leading_chars = 0;
77    let mut leading_bytes = 0;
78
79    for ch in input.chars() {
80        if ch != '\t' && ch != ' ' {
81            break;
82        }
83        leading_chars += 1;
84        leading_bytes += ch.len_utf8();
85    }
86
87    if leading_chars == 0 {
88        return input.to_owned();
89    }
90
91    let mut normalized = String::with_capacity(input.len());
92    normalized.push_str(&" ".repeat(leading_chars));
93    normalized.push_str(&input[leading_bytes..]);
94    normalized
95}
96
97/// Collapse every Unicode whitespace run to one space and trim the ends; mirrors `patch-parser.ts:233-235`.
98pub fn normalize_reflow_whitespace(input: &str) -> String {
99    #[cfg(any(test, feature = "test-support"))]
100    REFLOW_WINDOW_ALLOCATIONS.with(|count| count.set(count.get() + 1));
101    #[cfg(any(test, feature = "test-support"))]
102    REFLOW_WORK.with(|work| work.set(work.get() + input.len()));
103    let mut collapsed = String::with_capacity(input.len());
104    let mut in_whitespace = false;
105
106    for ch in input.chars() {
107        if ch.is_whitespace() {
108            if !in_whitespace {
109                collapsed.push(' ');
110                in_whitespace = true;
111            }
112        } else {
113            collapsed.push(ch);
114            in_whitespace = false;
115        }
116    }
117
118    collapsed.trim().to_owned()
119}
120
121/// Remove every Unicode whitespace character; mirrors `patch-parser.ts:237-239`.
122pub fn strip_reflow_whitespace(input: &str) -> String {
123    #[cfg(any(test, feature = "test-support"))]
124    REFLOW_WINDOW_ALLOCATIONS.with(|count| count.set(count.get() + 1));
125    input.chars().filter(|ch| !ch.is_whitespace()).collect()
126}
127
128/// Return true when a line has any non-whitespace content; mirrors `patch-parser.ts:241-243`.
129pub fn has_reflow_content(input: &str) -> bool {
130    input.chars().any(|ch| !ch.is_whitespace())
131}
132
133/// Search for a full pattern with a caller-supplied comparator, optionally anchored at EOF; mirrors `patch-parser.ts:247-281`.
134///
135/// Returns the first line at or after `start_index` where every pattern line
136/// compares equal (with `eof`, only the position ending at the last line).
137/// `compare` must be an equivalence relation, such as equality of a key
138/// derived from each line (the line itself, its trimmed form, ...). With
139/// `eof` only the window ending at the last line is checked; otherwise the
140/// search is [`normalized_sequence_match`]'s Knuth-Morris-Pratt scan over
141/// lines, so it stays linear in file plus pattern lines where trying every
142/// start cost file lines × pattern lines on repetitive files.
143pub fn try_match<F>(
144    lines: &[&str],
145    pattern: &[&str],
146    start_index: usize,
147    compare: F,
148    eof: bool,
149) -> Option<usize>
150where
151    F: Fn(&str, &str) -> bool,
152{
153    normalized_sequence_match(lines, pattern, start_index, eof, compare)
154}
155
156/// Add one line-tier comparison to the work counter: one unit plus the
157/// shorter line's byte length.
158#[cfg(any(test, feature = "test-support"))]
159pub fn count_line_comparison(a: &str, b: &str) {
160    LINE_MATCH_WORK.with(|work| work.set(work.get() + 1 + a.len().min(b.len())));
161}
162
163/// First match of `pattern` at or after `start_index` under `compare`, an
164/// equivalence relation on lines. Without `eof` this is a Knuth-Morris-Pratt
165/// scan over lines; with `eof` only the window ending at the last line is
166/// checked.
167fn normalized_sequence_match(
168    lines: &[&str],
169    pattern: &[&str],
170    start_index: usize,
171    eof: bool,
172    compare: impl Fn(&str, &str) -> bool,
173) -> Option<usize> {
174    let compare = |line: &str, expected: &str| {
175        #[cfg(any(test, feature = "test-support"))]
176        count_line_comparison(line, expected);
177        compare(line, expected)
178    };
179    if pattern.is_empty() || pattern.len() > lines.len() {
180        return None;
181    }
182    if eof {
183        let start = lines.len() - pattern.len();
184        return (start >= start_index
185            && lines[start..]
186                .iter()
187                .zip(pattern)
188                .all(|(line, expected)| compare(line, expected)))
189        .then_some(start);
190    }
191    let mut prefix = vec![0; pattern.len()];
192    for i in 1..pattern.len() {
193        let mut matched = prefix[i - 1];
194        loop {
195            if compare(pattern[i], pattern[matched]) {
196                matched += 1;
197                break;
198            }
199            if matched == 0 {
200                break;
201            }
202            matched = prefix[matched - 1];
203        }
204        prefix[i] = matched;
205    }
206    let mut matched = 0;
207    for (i, line) in lines.iter().enumerate().skip(start_index) {
208        loop {
209            if compare(line, pattern[matched]) {
210                matched += 1;
211                break;
212            }
213            if matched == 0 {
214                break;
215            }
216            matched = prefix[matched - 1];
217        }
218        if matched == pattern.len() {
219            return Some(i + 1 - pattern.len());
220        }
221    }
222    None
223}
224
225fn unicode_characters(input: &str) -> impl Iterator<Item = char> + '_ {
226    input.chars().flat_map(|ch| {
227        let mapped = match ch {
228            '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' => '\'',
229            '\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' => '"',
230            '\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2014}' | '\u{2015}' => '-',
231            '\u{00A0}' => ' ',
232            _ => ch,
233        };
234        if ch == '\u{2026}' {
235            [Some('.'), Some('.'), Some('.')]
236        } else {
237            [Some(mapped), None, None]
238        }
239        .into_iter()
240        .flatten()
241    })
242}
243
244/// Collapse whitespace runs to one space and drop leading and trailing
245/// whitespace, lazily. Only the reference scan in the tests still checks
246/// windows this way.
247#[cfg(test)]
248fn collapsed_whitespace(chars: impl Iterator<Item = char>) -> impl Iterator<Item = char> {
249    let mut started = false;
250    let mut space = false;
251    chars.flat_map(move |ch| {
252        let emitted = if ch.is_whitespace() {
253            space = started;
254            [None, None]
255        } else {
256            let emitted = if space {
257                [Some(' '), Some(ch)]
258            } else {
259                [Some(ch), None]
260            };
261            space = false;
262            started = true;
263            emitted
264        };
265        emitted.into_iter().flatten()
266    })
267}
268
269#[cfg(any(test, feature = "test-support"))]
270thread_local! {
271    static NORMALIZED_LINE_ALLOCATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
272    static REFLOW_WINDOW_ALLOCATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
273    /// Candidate windows the reflow search verified with its whitespace check.
274    static REFLOW_STARTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
275    /// Byte steps of the reflow search's substring scan, so tests can check
276    /// that it stays linear in the file and pattern sizes.
277    pub static REFLOW_SCAN_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
278    /// Work done by the reflow pass: each file character read to build its
279    /// stream, each step building the needle's failure table and scanning the
280    /// stream, and each byte normalized. Tests bound this by the file and
281    /// needle sizes for the whole pass.
282    pub static REFLOW_WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
283    /// Work done by the line-by-line tiers: one unit per line comparison
284    /// plus the shorter line's byte length. Tests bound this counter by file
285    /// plus needle size.
286    pub static LINE_MATCH_WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
287}
288
289#[cfg(any(test, feature = "test-support"))]
290fn count_scan_step() {
291    REFLOW_SCAN_STEPS.with(|steps| steps.set(steps.get() + 1));
292    REFLOW_WORK.with(|work| work.set(work.get() + 1));
293}
294
295/// Line windows whose text equals a needle's text once whitespace is
296/// normalized (every whitespace run, line breaks included, collapsed to one
297/// space and the ends trimmed), in ascending order of their first line.
298///
299/// The file is normalized once into a stream: every whitespace run between
300/// two non-whitespace characters becomes one space, and each line with
301/// content records where its first character starts and its last character
302/// ends in that stream. A window from line `s` to line `e` normalizes to
303/// exactly the stream bytes from line `s`'s start to line `e - 1`'s end:
304/// normalization trims the window's leading and trailing whitespace, and
305/// every remaining whitespace run lies inside that span. So
306/// the matching windows are exactly the occurrences of the needle's
307/// normalized bytes that start where a line with content starts and end
308/// where a line with content ends. Knuth-Morris-Pratt finds every
309/// occurrence, overlapping ones included, and the line-boundary check walks
310/// two forward-only cursors, so the whole search, spacing included, is
311/// linear in the file and needle sizes and never rescans a window.
312/// Extending a window from every line instead cost file lines × needle
313/// lines, and checking each whitespace-stripped hit's spacing afterwards
314/// cost candidates × needle size on repetitive files.
315pub struct ReflowCandidates<'a> {
316    stream: Vec<u8>,
317    needle: &'a [u8],
318    failure: Vec<usize>,
319    /// `(stream offset, line index)` where each line with content starts and
320    /// ends; both offsets strictly increase with the line index.
321    starts: Vec<(usize, usize)>,
322    ends: Vec<(usize, usize)>,
323    position: usize,
324    matched: usize,
325    /// First entries of `starts` and `ends` not yet passed. Occurrences are
326    /// found in increasing offset order, so these only move forward.
327    start_cursor: usize,
328    end_cursor: usize,
329}
330
331impl<'a> ReflowCandidates<'a> {
332    /// Matching windows among `lines`, numbered from 0 like `lines` itself.
333    /// `needle_normalized` must already be normalized as described on the
334    /// type (see [`normalize_reflow_whitespace`]) and must not be empty.
335    pub fn new(lines: &[&str], needle_normalized: &'a str) -> Self {
336        let needle = needle_normalized.as_bytes();
337        // Sized up front so building the stream allocates a fixed number of
338        // times, never once per line.
339        let mut stream = Vec::with_capacity(lines.iter().map(|line| line.len() + 1).sum::<usize>());
340        let mut starts = Vec::with_capacity(lines.len());
341        let mut ends = Vec::with_capacity(lines.len());
342        // A space is owed once whitespace follows emitted text; it is written
343        // only when more text follows, so the stream has no leading or
344        // trailing space and never two in a row.
345        let mut owe_space = false;
346        for (index, line) in lines.iter().enumerate() {
347            let mut first = None;
348            let mut last = 0;
349            for ch in line.chars() {
350                #[cfg(any(test, feature = "test-support"))]
351                REFLOW_WORK.with(|work| work.set(work.get() + 1));
352                if ch.is_whitespace() {
353                    owe_space = !stream.is_empty();
354                    continue;
355                }
356                if owe_space {
357                    stream.push(b' ');
358                    owe_space = false;
359                }
360                first.get_or_insert(stream.len());
361                let mut buffer = [0u8; 4];
362                stream.extend_from_slice(ch.encode_utf8(&mut buffer).as_bytes());
363                last = stream.len();
364            }
365            if let Some(first) = first {
366                starts.push((first, index));
367                ends.push((last, index));
368            }
369            // The break between this line and the next is whitespace too.
370            owe_space = !stream.is_empty();
371        }
372        // failure[i]: length of the longest proper prefix of needle[..=i]
373        // that is also its suffix.
374        let mut failure = vec![0; needle.len()];
375        let mut length = 0;
376        for index in 1..needle.len() {
377            #[cfg(any(test, feature = "test-support"))]
378            REFLOW_WORK.with(|work| work.set(work.get() + 1));
379            while length > 0 && needle[index] != needle[length] {
380                #[cfg(any(test, feature = "test-support"))]
381                REFLOW_WORK.with(|work| work.set(work.get() + 1));
382                length = failure[length - 1];
383            }
384            if needle[index] == needle[length] {
385                length += 1;
386            }
387            failure[index] = length;
388        }
389        Self {
390            stream,
391            needle,
392            failure,
393            starts,
394            ends,
395            position: 0,
396            matched: 0,
397            start_cursor: 0,
398            end_cursor: 0,
399        }
400    }
401}
402
403impl Iterator for ReflowCandidates<'_> {
404    /// `(first line, end line exclusive)`.
405    type Item = (usize, usize);
406
407    fn next(&mut self) -> Option<Self::Item> {
408        if self.needle.is_empty() {
409            return None;
410        }
411        while self.position < self.stream.len() {
412            let byte = self.stream[self.position];
413            self.position += 1;
414            while self.matched > 0 && self.needle[self.matched] != byte {
415                #[cfg(any(test, feature = "test-support"))]
416                count_scan_step();
417                self.matched = self.failure[self.matched - 1];
418            }
419            #[cfg(any(test, feature = "test-support"))]
420            count_scan_step();
421            if self.needle[self.matched] == byte {
422                self.matched += 1;
423            }
424            if self.matched < self.needle.len() {
425                continue;
426            }
427            self.matched = self.failure[self.matched - 1];
428            let end = self.position;
429            let start = end - self.needle.len();
430            // Keep only occurrences that start at the start of a line with
431            // content and end at the end of a line with content.
432            while self
433                .starts
434                .get(self.start_cursor)
435                .is_some_and(|&(offset, _)| offset < start)
436            {
437                self.start_cursor += 1;
438            }
439            while self
440                .ends
441                .get(self.end_cursor)
442                .is_some_and(|&(offset, _)| offset < end)
443            {
444                self.end_cursor += 1;
445            }
446            let (Some(&(first_offset, first)), Some(&(last_offset, last))) = (
447                self.starts.get(self.start_cursor),
448                self.ends.get(self.end_cursor),
449            ) else {
450                continue;
451            };
452            if first_offset != start || last_offset != end {
453                continue;
454            }
455            return Some((first, last + 1));
456        }
457        None
458    }
459}
460
461/// Find one unique whitespace-reflowed window, returning `(found_line, line_count)`; mirrors `patch-parser.ts:310-351`.
462pub fn find_reflow_match(
463    lines: &[&str],
464    pattern: &[&str],
465    start_index: usize,
466) -> Option<(usize, usize)> {
467    let normalized_needle = normalize_reflow_whitespace(&pattern.join("\n"));
468    if normalized_needle.is_empty() {
469        return None;
470    }
471    let searched = lines.get(start_index..).unwrap_or_default();
472    let mut first_match = None;
473    for (start, end) in ReflowCandidates::new(searched, &normalized_needle) {
474        #[cfg(any(test, feature = "test-support"))]
475        REFLOW_STARTS.with(|count| count.set(count.get() + 1));
476        if first_match
477            .replace((start_index + start, end - start))
478            .is_some()
479        {
480            return None;
481        }
482    }
483    first_match
484}
485
486/// Keep exact first-hit matching, but refuse ambiguous non-exact fallbacks.
487pub fn seek_sequence_tiered(
488    lines: &[&str],
489    pattern: &[&str],
490    start_index: usize,
491    eof: bool,
492) -> Option<SequenceMatch> {
493    seek_sequence_tiered_checked(lines, pattern, start_index, eof)
494        .ok()
495        .flatten()
496}
497
498fn unique_match(
499    first: Option<usize>,
500    next: impl FnOnce(usize) -> Option<usize>,
501) -> Result<Option<usize>, &'static str> {
502    if let Some(first) = first {
503        if next(first + 1).is_some() {
504            return Err("Ambiguous non-exact match");
505        }
506    }
507    Ok(first)
508}
509
510pub fn seek_sequence_tiered_checked(
511    lines: &[&str],
512    pattern: &[&str],
513    start_index: usize,
514    eof: bool,
515) -> Result<Option<SequenceMatch>, &'static str> {
516    if pattern.is_empty() {
517        return Ok(None);
518    }
519    let matched = |found, tier| {
520        Some(SequenceMatch {
521            found,
522            tier,
523            line_count: pattern.len(),
524        })
525    };
526    if let Some(found) = try_match(lines, pattern, start_index, |a, b| a == b, eof) {
527        return Ok(matched(found, MatchTier::Exact));
528    }
529    for (tier, compare) in [
530        (
531            MatchTier::Rstrip,
532            (|a: &str, b: &str| a.trim_end() == b.trim_end()) as fn(&str, &str) -> bool,
533        ),
534        (
535            MatchTier::Trim,
536            (|a: &str, b: &str| a.trim() == b.trim()) as fn(&str, &str) -> bool,
537        ),
538    ] {
539        let found = unique_match(
540            try_match(lines, pattern, start_index, compare, eof),
541            |next| try_match(lines, pattern, next, compare, eof),
542        )?;
543        if let Some(found) = found {
544            return Ok(matched(found, tier));
545        }
546    }
547    let indent = |a: &str, b: &str| a.trim() == b.trim();
548    let found = unique_match(
549        normalized_sequence_match(lines, pattern, start_index, eof, indent),
550        |next| normalized_sequence_match(lines, pattern, next, eof, indent),
551    )?;
552    if let Some(found) = found {
553        return Ok(matched(found, MatchTier::Indent));
554    }
555    let unicode = |a: &str, b: &str| unicode_characters(a.trim()).eq(unicode_characters(b.trim()));
556    let found = unique_match(
557        normalized_sequence_match(lines, pattern, start_index, eof, unicode),
558        |next| normalized_sequence_match(lines, pattern, next, eof, unicode),
559    )?;
560    if let Some(found) = found {
561        return Ok(matched(found, MatchTier::Unicode));
562    }
563    if eof {
564        return Ok(None);
565    }
566    Ok(
567        find_reflow_match(lines, pattern, start_index).map(|(found, line_count)| SequenceMatch {
568            found,
569            tier: MatchTier::Reflow,
570            line_count,
571        }),
572    )
573}
574
575fn add_sampled_candidates(
576    candidates: &mut HashSet<usize>,
577    positions: &[usize],
578    wanted_offset: usize,
579    candidate_limit: usize,
580) {
581    let remaining = candidate_limit.saturating_sub(candidates.len());
582    let sample_count = positions
583        .len()
584        .min(NEAREST_MISS_MAX_POSITIONS_PER_ANCHOR)
585        .min(remaining);
586    if sample_count == 0 {
587        return;
588    }
589
590    for sample in 0..sample_count {
591        let position_index = if sample_count == 1 {
592            0
593        } else {
594            sample * (positions.len() - 1) / (sample_count - 1)
595        };
596        let file_position = positions[position_index];
597        if let Some(start) = file_position.checked_sub(wanted_offset) {
598            candidates.insert(start);
599        }
600    }
601}
602
603fn score_nearest_miss(lines: &[&str], pattern: &[&str], start: usize) -> NearestMiss {
604    let end = (start + pattern.len()).min(lines.len());
605    let matched_lines = pattern
606        .iter()
607        .enumerate()
608        .filter(|(offset, expected)| {
609            lines
610                .get(start + offset)
611                .is_some_and(|actual| actual.trim() == expected.trim())
612        })
613        .count();
614    let first_divergence = pattern
615        .iter()
616        .enumerate()
617        .find(|(offset, expected)| {
618            lines
619                .get(start + offset)
620                .is_none_or(|actual| actual.trim() != expected.trim())
621        })
622        .map_or(pattern.len(), |(offset, _)| offset);
623
624    NearestMiss {
625        start,
626        end,
627        matched_lines,
628        first_divergence,
629    }
630}
631
632fn is_better_nearest_miss(candidate: NearestMiss, current: NearestMiss) -> bool {
633    candidate.matched_lines > current.matched_lines
634        || (candidate.matched_lines == current.matched_lines
635            && (candidate.first_divergence > current.first_divergence
636                || (candidate.first_divergence == current.first_divergence
637                    && candidate.start < current.start)))
638}
639
640fn best_scored_candidate(
641    lines: &[&str],
642    pattern: &[&str],
643    candidates: HashSet<usize>,
644) -> Option<NearestMiss> {
645    candidates
646        .into_iter()
647        .filter(|start| *start < lines.len())
648        .map(|start| score_nearest_miss(lines, pattern, start))
649        .fold(None, |best, candidate| match best {
650            Some(current) if !is_better_nearest_miss(candidate, current) => Some(current),
651            _ => Some(candidate),
652        })
653}
654
655fn normalize_fuzzy_line(line: &str) -> String {
656    normalize_unicode(&normalize_reflow_whitespace(line))
657}
658
659fn normalized_prefix_score(normalized_wanted: &str, actual: &str) -> Option<usize> {
660    let actual = normalize_fuzzy_line(actual);
661    let wanted_len = normalized_wanted
662        .chars()
663        .take(NEAREST_MISS_MAX_FUZZY_CHARS)
664        .count();
665    if wanted_len < 4 {
666        return None;
667    }
668
669    let common = normalized_wanted
670        .chars()
671        .zip(actual.chars())
672        .take(NEAREST_MISS_MAX_FUZZY_CHARS)
673        .take_while(|(wanted_char, actual_char)| wanted_char == actual_char)
674        .count();
675    (common >= 4 && common * 2 >= wanted_len).then_some(common)
676}
677
678fn rarest_wanted_line<'a>(pattern: &'a [&'a str]) -> Option<(usize, &'a str)> {
679    let mut frequencies: HashMap<&str, usize> = HashMap::new();
680    for line in pattern
681        .iter()
682        .map(|line| line.trim())
683        .filter(|line| !line.is_empty())
684    {
685        *frequencies.entry(line).or_default() += 1;
686    }
687
688    pattern
689        .iter()
690        .enumerate()
691        .map(|(offset, line)| (offset, line.trim()))
692        .filter(|(_, line)| !line.is_empty())
693        .min_by_key(|(offset, line)| {
694            (
695                frequencies.get(line).copied().unwrap_or(usize::MAX),
696                std::cmp::Reverse(line.chars().count()),
697                *offset,
698            )
699        })
700}
701
702/// Find a bounded best-effort candidate after every accepted match tier has failed.
703pub fn find_nearest_miss(
704    lines: &[&str],
705    pattern: &[&str],
706    file_size_bytes: usize,
707) -> NearestMissSearch {
708    if file_size_bytes > NEAREST_MISS_MAX_FILE_BYTES {
709        return NearestMissSearch::SkippedLargeFile;
710    }
711    if lines.is_empty() || pattern.is_empty() {
712        return NearestMissSearch::NoSimilarRegion;
713    }
714
715    let mut line_index: HashMap<&str, Vec<usize>> = HashMap::new();
716    for (position, line) in lines.iter().enumerate() {
717        let trimmed = line.trim();
718        if !trimmed.is_empty() {
719            line_index.entry(trimmed).or_default().push(position);
720        }
721    }
722
723    let candidate_limit = NEAREST_MISS_MAX_CANDIDATES
724        .min((NEAREST_MISS_MAX_LINE_COMPARISONS / pattern.len().max(1)).max(1));
725    let mut anchor_positions: Vec<(usize, &[usize])> = pattern
726        .iter()
727        .enumerate()
728        .filter(|(_, line)| !line.trim().is_empty())
729        .take(NEAREST_MISS_ANCHOR_COUNT)
730        .filter_map(|(offset, line)| {
731            line_index
732                .get(line.trim())
733                .map(|positions| (offset, positions.as_slice()))
734        })
735        .collect();
736    anchor_positions.sort_by_key(|(offset, positions)| (positions.len(), *offset));
737
738    let mut candidates = HashSet::new();
739    for (wanted_offset, positions) in anchor_positions {
740        add_sampled_candidates(&mut candidates, positions, wanted_offset, candidate_limit);
741        if candidates.len() >= candidate_limit {
742            break;
743        }
744    }
745    if let Some(best) = best_scored_candidate(lines, pattern, candidates) {
746        return NearestMissSearch::Found(best);
747    }
748
749    let Some((wanted_offset, wanted_line)) = rarest_wanted_line(pattern) else {
750        return NearestMissSearch::NoSimilarRegion;
751    };
752    let normalized_wanted = normalize_fuzzy_line(wanted_line);
753    let mut best_prefix = 0;
754    let mut fuzzy_candidates = HashSet::new();
755    for (file_position, actual_line) in lines.iter().enumerate() {
756        let Some(start) = file_position.checked_sub(wanted_offset) else {
757            continue;
758        };
759        let Some(prefix_score) = normalized_prefix_score(&normalized_wanted, actual_line) else {
760            continue;
761        };
762        if prefix_score > best_prefix {
763            best_prefix = prefix_score;
764            fuzzy_candidates.clear();
765        }
766        if prefix_score == best_prefix && fuzzy_candidates.len() < candidate_limit {
767            fuzzy_candidates.insert(start);
768        }
769    }
770
771    best_scored_candidate(lines, pattern, fuzzy_candidates)
772        .map_or(NearestMissSearch::NoSimilarRegion, NearestMissSearch::Found)
773}
774
775#[cfg(test)]
776mod tests {
777    #[test]
778    fn tiered_match_choice_matches_sliding_reference_on_mixed_text() {
779        use super::*;
780        let cases = [
781            (
782                vec!["  héllo", "\tworld", "target"],
783                vec![" héllo", " world"],
784                false,
785            ),
786            (vec!["before", "‘quoted’", "after"], vec!["'quoted'"], false),
787            (vec!["a  b", " c", "last"], vec!["a b c"], false),
788            (vec!["x\r", "  y\r", "z"], vec!["x", "y"], false),
789            (vec!["x", " \ty"], vec!["y"], true),
790        ];
791        for (lines, pattern, eof) in cases {
792            let expected = [
793                (
794                    MatchTier::Exact,
795                    try_match(&lines, &pattern, 0, |a, b| a == b, eof),
796                ),
797                (
798                    MatchTier::Rstrip,
799                    try_match(
800                        &lines,
801                        &pattern,
802                        0,
803                        |a, b| a.trim_end() == b.trim_end(),
804                        eof,
805                    ),
806                ),
807                (
808                    MatchTier::Trim,
809                    try_match(&lines, &pattern, 0, |a, b| a.trim() == b.trim(), eof),
810                ),
811                (
812                    MatchTier::Indent,
813                    try_match(
814                        &lines,
815                        &pattern,
816                        0,
817                        |a, b| normalize_indent(a).trim_end() == normalize_indent(b).trim_end(),
818                        eof,
819                    ),
820                ),
821                (
822                    MatchTier::Unicode,
823                    try_match(
824                        &lines,
825                        &pattern,
826                        0,
827                        |a, b| normalize_unicode(a.trim()) == normalize_unicode(b.trim()),
828                        eof,
829                    ),
830                ),
831            ]
832            .into_iter()
833            .find_map(|(tier, found)| {
834                found.map(|found| SequenceMatch {
835                    found,
836                    tier,
837                    line_count: pattern.len(),
838                })
839            })
840            .or_else(|| {
841                (!eof)
842                    .then(|| find_reflow_match(&lines, &pattern, 0))
843                    .flatten()
844                    .map(|(found, line_count)| SequenceMatch {
845                        found,
846                        tier: MatchTier::Reflow,
847                        line_count,
848                    })
849            });
850            assert_eq!(seek_sequence_tiered(&lines, &pattern, 0, eof), expected);
851        }
852    }
853
854    #[test]
855    fn ambiguous_reflow_stops_after_second_window() {
856        let lines = vec!["x y"; 5_000];
857        super::REFLOW_STARTS.with(|count| count.set(0));
858        assert_eq!(super::find_reflow_match(&lines, &["x y"], 0), None);
859        let visited = super::REFLOW_STARTS.with(|count| count.get());
860        assert_eq!(visited, 2);
861        eprintln!(
862            "ambiguous reflow starts: baseline {}, early exit {visited}",
863            lines.len()
864        );
865        assert_eq!(
866            super::find_reflow_match(&[" ", "a b", "  "], &["a b"], 0),
867            Some((1, 1))
868        );
869        assert_eq!(
870            super::find_reflow_match(&["one", "two"], &["absent"], 0),
871            None
872        );
873    }
874
875    #[test]
876    fn normalized_search_is_linear_on_repeated_prefix_and_preserves_first_match() {
877        use std::cell::Cell;
878        let lines = vec!["same"; 5_000];
879        let mut pattern = vec!["same"; 60];
880        pattern[59] = "missing";
881        let calls = Cell::new(0);
882        let found = super::normalized_sequence_match(&lines, &pattern, 0, false, |a, b| {
883            calls.set(calls.get() + 1);
884            a == b
885        });
886        assert_eq!(found, None);
887        assert!(calls.get() <= 2 * (lines.len() + pattern.len()));
888        // Baseline: try every start in turn, as `try_match` once did.
889        let baseline_calls = Cell::new(0);
890        let baseline = (0..=lines.len() - pattern.len()).find(|&start| {
891            pattern.iter().enumerate().all(|(offset, expected)| {
892                baseline_calls.set(baseline_calls.get() + 1);
893                lines[start + offset] == *expected
894            })
895        });
896        assert_eq!(found, baseline);
897        assert!(baseline_calls.get() > calls.get() * 20);
898        eprintln!(
899            "repeated-prefix comparisons: baseline {}, indexed {}",
900            baseline_calls.get(),
901            calls.get()
902        );
903        let mut found_lines = lines.clone();
904        found_lines[4_999] = "missing";
905        assert_eq!(
906            super::normalized_sequence_match(&found_lines, &pattern, 0, false, |a, b| a == b),
907            Some(4_940)
908        );
909        assert_eq!(
910            super::find_reflow_match(&["hello", "hello", "hello"], &["hello"], 0),
911            None
912        );
913    }
914    use super::*;
915
916    fn assert_match(
917        actual: Option<SequenceMatch>,
918        found: usize,
919        tier: MatchTier,
920        line_count: usize,
921    ) {
922        assert_eq!(
923            actual,
924            Some(SequenceMatch {
925                found,
926                tier,
927                line_count,
928            })
929        );
930    }
931
932    #[test]
933    fn normalization_helpers_match_patch_parser_sources() {
934        assert_eq!(
935            normalize_unicode("‘’‚‛“”„‟‐‑‒–—―…\u{00A0}"),
936            "''''\"\"\"\"------... "
937        );
938        assert_eq!(normalize_indent("\t  alpha\t beta  "), "   alpha\t beta  ");
939        assert_eq!(normalize_indent(""), "");
940        assert_eq!(
941            normalize_reflow_whitespace(" \talpha\n\u{00A0} beta  "),
942            "alpha beta"
943        );
944        assert_eq!(
945            strip_reflow_whitespace(" \talpha\n\u{00A0} beta  "),
946            "alphabeta"
947        );
948        assert!(has_reflow_content("\u{00A0}x"));
949        assert!(!has_reflow_content(" \t\n"));
950    }
951
952    #[test]
953    fn exact_tier_wins_without_upgrading_to_later_tiers() {
954        assert_match(
955            seek_sequence_tiered(&["alpha", "beta"], &["beta"], 0, false),
956            1,
957            MatchTier::Exact,
958            1,
959        );
960    }
961
962    #[test]
963    fn rstrip_tier_wins_before_trim() {
964        assert_match(
965            seek_sequence_tiered(&["alpha   "], &["alpha"], 0, false),
966            0,
967            MatchTier::Rstrip,
968            1,
969        );
970    }
971
972    #[test]
973    fn trim_tier_wins_before_indent_and_unicode() {
974        assert_match(
975            seek_sequence_tiered(&["  alpha  "], &["alpha"], 0, false),
976            0,
977            MatchTier::Trim,
978            1,
979        );
980    }
981
982    #[test]
983    fn indent_normalization_matches_tab_space_drift_but_trim_shadows_the_tier() {
984        assert_eq!(normalize_indent("\treturn 42;"), " return 42;");
985        assert_eq!(normalize_indent(" return 42;"), " return 42;");
986        assert_eq!(
987            try_match(
988                &["\treturn 42;"],
989                &[" return 42;"],
990                0,
991                |a, b| normalize_indent(a).trim_end() == normalize_indent(b).trim_end(),
992                false,
993            ),
994            Some(0)
995        );
996        // Expect Trim, not Indent, for tab-vs-space input: a leading tab-vs-space drift
997        // is already accepted by the earlier trim tier, so the nominal indent tier is shadowed.
998        assert_match(
999            seek_sequence_tiered(&["\treturn 42;"], &["    return 42;"], 0, false),
1000            0,
1001            MatchTier::Trim,
1002            1,
1003        );
1004    }
1005
1006    #[test]
1007    fn unicode_tier_normalizes_smart_punctuation_after_stricter_tiers_fail() {
1008        assert_match(
1009            seek_sequence_tiered(
1010                &["const label = “alpha”—beta…;"],
1011                &["const label = \"alpha\"-beta...;"],
1012                0,
1013                false,
1014            ),
1015            0,
1016            MatchTier::Unicode,
1017            1,
1018        );
1019    }
1020
1021    #[test]
1022    fn reflow_tier_matches_one_line_hunk_against_three_line_formatter_split() {
1023        let lines = [
1024            "function demo() {",
1025            "  const value = alpha +",
1026            "    beta +",
1027            "    gamma;",
1028            "  return value;",
1029            "}",
1030        ];
1031        let pattern = ["  const value = alpha + beta + gamma;"];
1032
1033        assert_match(
1034            seek_sequence_tiered(&lines, &pattern, 0, false),
1035            1,
1036            MatchTier::Reflow,
1037            3,
1038        );
1039    }
1040
1041    #[test]
1042    fn rejects_ambiguous_reflow_matches_instead_of_choosing_a_window() {
1043        // Reject a reflow match when the pattern could match more than one distinct window.
1044        let lines = [
1045            "const value = alpha +",
1046            "  beta +",
1047            "  gamma;",
1048            "",
1049            "const value = alpha +",
1050            "  beta +",
1051            "  gamma;",
1052        ];
1053        let pattern = ["const value = alpha + beta + gamma;"];
1054
1055        assert_eq!(find_reflow_match(&lines, &pattern, 0), None);
1056        assert_eq!(seek_sequence_tiered(&lines, &pattern, 0, false), None);
1057    }
1058
1059    #[test]
1060    fn uses_line_contiguous_match_before_considering_reflow_candidate() {
1061        // A line-contiguous match wins before any reflow candidate is considered.
1062        let lines = [
1063            "const value = alpha +",
1064            "  beta +",
1065            "  gamma;",
1066            "const value = alpha + beta + gamma;",
1067        ];
1068        let pattern = ["const value = alpha + beta + gamma;"];
1069
1070        assert_match(
1071            seek_sequence_tiered(&lines, &pattern, 0, false),
1072            3,
1073            MatchTier::Exact,
1074            1,
1075        );
1076    }
1077
1078    #[test]
1079    fn eof_hunk_only_matches_the_tail_and_never_forward_scans() {
1080        // EOF-anchored hunks match only the tail and never forward-scan.
1081        let pattern = ["marker", "old"];
1082
1083        assert_match(
1084            seek_sequence_tiered(
1085                &["header", "marker", "old", "middle", "marker", "old"],
1086                &pattern,
1087                0,
1088                true,
1089            ),
1090            4,
1091            MatchTier::Exact,
1092            2,
1093        );
1094        assert_eq!(
1095            seek_sequence_tiered(
1096                &["header", "marker", "old", "middle", "marker", "changed"],
1097                &pattern,
1098                0,
1099                true,
1100            ),
1101            None
1102        );
1103    }
1104
1105    #[test]
1106    fn eof_hunk_skips_reflow_even_when_the_tail_would_reflow_match() {
1107        let lines = ["header", "const value = alpha +", "  beta +", "  gamma;"];
1108        let pattern = ["const value = alpha + beta + gamma;"];
1109
1110        assert_eq!(find_reflow_match(&lines, &pattern, 0), Some((1, 3)));
1111        assert_eq!(seek_sequence_tiered(&lines, &pattern, 0, true), None);
1112    }
1113
1114    #[test]
1115    fn try_match_honors_start_index_for_forward_scans_and_eof_anchor() {
1116        assert_eq!(
1117            try_match(&["a", "b", "a", "b"], &["a", "b"], 1, |a, b| a == b, false),
1118            Some(2)
1119        );
1120        assert_eq!(
1121            try_match(&["a", "b", "a", "b"], &["a", "b"], 3, |a, b| a == b, false),
1122            None
1123        );
1124        assert_eq!(
1125            try_match(&["a", "b", "a", "b"], &["a", "b"], 3, |a, b| a == b, true),
1126            None
1127        );
1128    }
1129
1130    #[test]
1131    fn nearest_miss_scores_matching_lines_across_the_candidate_window() {
1132        let lines = [
1133            "header",
1134            "  const first = 1;",
1135            "  const actual = 2;",
1136            "  return first;",
1137            "separator",
1138            "  const first = 1;",
1139            "  unrelated",
1140            "  unrelated",
1141        ];
1142        let pattern = [
1143            "  const first = 1;",
1144            "  const expected = 2;",
1145            "  return first;",
1146        ];
1147
1148        assert_eq!(
1149            find_nearest_miss(&lines, &pattern, 128),
1150            NearestMissSearch::Found(NearestMiss {
1151                start: 1,
1152                end: 4,
1153                matched_lines: 2,
1154                first_divergence: 1,
1155            })
1156        );
1157    }
1158
1159    #[test]
1160    fn nearest_miss_uses_a_strong_prefix_when_no_anchor_matches_exactly() {
1161        assert_eq!(
1162            find_nearest_miss(
1163                &["header", "const expected_value = 2;", "footer"],
1164                &["const expected_value = 1;"],
1165                42,
1166            ),
1167            NearestMissSearch::Found(NearestMiss {
1168                start: 1,
1169                end: 2,
1170                matched_lines: 0,
1171                first_divergence: 0,
1172            })
1173        );
1174    }
1175
1176    #[test]
1177    fn nearest_miss_reports_no_region_when_anchors_and_prefixes_are_absent() {
1178        assert_eq!(
1179            find_nearest_miss(
1180                &["alpha", "beta", "gamma"],
1181                &["completely unrelated line"],
1182                17,
1183            ),
1184            NearestMissSearch::NoSimilarRegion
1185        );
1186    }
1187
1188    #[test]
1189    fn nearest_miss_skips_files_larger_than_the_diagnostic_limit() {
1190        let synthetic_file = "x".repeat(NEAREST_MISS_MAX_FILE_BYTES + 1);
1191        assert_eq!(
1192            find_nearest_miss(
1193                &[synthetic_file.as_str()],
1194                &["wanted content"],
1195                synthetic_file.len(),
1196            ),
1197            NearestMissSearch::SkippedLargeFile
1198        );
1199    }
1200}
1201
1202#[cfg(test)]
1203mod audit11_regressions {
1204    use super::*;
1205
1206    #[test]
1207    fn fallback_matching_does_not_allocate_normalized_file_lines() {
1208        NORMALIZED_LINE_ALLOCATIONS.with(|count| count.set(0));
1209        let result = seek_sequence_tiered(&["one – two"], &["one - two"], 0, false).unwrap();
1210        assert_eq!(result.tier, MatchTier::Unicode);
1211        assert_eq!(NORMALIZED_LINE_ALLOCATIONS.with(|count| count.get()), 0);
1212    }
1213
1214    #[test]
1215    fn reflow_matching_does_not_allocate_candidate_windows() {
1216        REFLOW_WINDOW_ALLOCATIONS.with(|count| count.set(0));
1217        assert_eq!(
1218            find_reflow_match(&["x", "a", "b", "y", "a  b"], &["a b"], 0),
1219            None
1220        );
1221        assert_eq!(
1222            find_reflow_match(&["x", "a", "b"], &["a b"], 0),
1223            Some((1, 2))
1224        );
1225        // Only the needle is normalized, once per search; file lines are
1226        // streamed in place and candidate windows are never materialized.
1227        assert_eq!(REFLOW_WINDOW_ALLOCATIONS.with(|count| count.get()), 2);
1228    }
1229}
1230
1231/// Shared by the reflow differential tests here and in `fuzzy_match`: a
1232/// deterministic input generator and a brute-force candidate list.
1233#[cfg(any(test, feature = "test-support"))]
1234pub mod reflow_test_support {
1235    /// xorshift64*: deterministic, so a failing case can be replayed.
1236    pub struct Rng(u64);
1237
1238    impl Rng {
1239        pub fn new(seed: u64) -> Self {
1240            Self(seed.max(1))
1241        }
1242
1243        fn next(&mut self) -> u64 {
1244            self.0 ^= self.0 >> 12;
1245            self.0 ^= self.0 << 25;
1246            self.0 ^= self.0 >> 27;
1247            self.0.wrapping_mul(0x2545_f491_4f6c_dd1d)
1248        }
1249
1250        pub fn below(&mut self, bound: usize) -> usize {
1251            (self.next() % bound.max(1) as u64) as usize
1252        }
1253    }
1254
1255    /// Line pieces mixing words, spacing variants, whitespace-only and empty
1256    /// lines, tabs, a non-ASCII letter and an ideographic space.
1257    const TOKENS: &[&str] = &[
1258        "a",
1259        "b",
1260        "ab",
1261        "ba",
1262        "a b",
1263        "a  b",
1264        "b a",
1265        "\ta",
1266        "b\t",
1267        "",
1268        "  ",
1269        "\t",
1270        "é",
1271        "é a",
1272        "x",
1273        "xy",
1274        "a\u{3000}b",
1275    ];
1276
1277    /// File lines: random pieces, sometimes with a repeated block so that
1278    /// candidates overlap and repeat.
1279    pub fn file_lines(rng: &mut Rng) -> Vec<String> {
1280        let mut lines = Vec::new();
1281        let count = 1 + rng.below(13);
1282        while lines.len() < count {
1283            if rng.below(4) == 0 {
1284                let block = (0..1 + rng.below(3))
1285                    .map(|_| TOKENS[rng.below(TOKENS.len())].to_string())
1286                    .collect::<Vec<_>>();
1287                for _ in 0..2 + rng.below(3) {
1288                    lines.extend(block.iter().cloned());
1289                }
1290            } else {
1291                lines.push(TOKENS[rng.below(TOKENS.len())].to_string());
1292            }
1293        }
1294        lines.truncate(count);
1295        lines
1296    }
1297
1298    /// Rewrite every whitespace run, as a reflow would, sometimes removing it
1299    /// (non-whitespace text unchanged, spacing different) and sometimes
1300    /// adding leading or trailing whitespace.
1301    fn reflow(rng: &mut Rng, text: &str) -> String {
1302        const RUNS: &[&str] = &[" ", "\n", "  ", "\t", " \n ", "\n\n", ""];
1303        let mut out = String::new();
1304        if rng.below(4) == 0 {
1305            out.push_str(RUNS[rng.below(RUNS.len() - 1)]);
1306        }
1307        let mut in_run = false;
1308        for ch in text.chars() {
1309            if ch.is_whitespace() {
1310                if !in_run {
1311                    out.push_str(RUNS[rng.below(RUNS.len())]);
1312                }
1313                in_run = true;
1314            } else {
1315                // Sometimes break a line between two letters, too.
1316                if !in_run && !out.is_empty() && rng.below(10) == 0 {
1317                    out.push('\n');
1318                }
1319                out.push(ch);
1320                in_run = false;
1321            }
1322        }
1323        if rng.below(4) == 0 {
1324            out.push_str(RUNS[rng.below(RUNS.len() - 1)]);
1325        }
1326        out
1327    }
1328
1329    /// Change, drop or add one non-whitespace character.
1330    fn mutate(rng: &mut Rng, text: &str) -> String {
1331        let positions = text
1332            .char_indices()
1333            .filter(|(_, ch)| !ch.is_whitespace())
1334            .map(|(index, _)| index)
1335            .collect::<Vec<_>>();
1336        let Some(&at) = positions.get(rng.below(positions.len().max(1))) else {
1337            return format!("{text}z");
1338        };
1339        let ch = text[at..].chars().next().unwrap();
1340        let rest = &text[at + ch.len_utf8()..];
1341        match rng.below(3) {
1342            0 => format!("{}z{rest}", &text[..at]),
1343            1 => format!("{}{rest}", &text[..at]),
1344            _ => format!("{}a{ch}{rest}", &text[..at]),
1345        }
1346    }
1347
1348    /// A needle for `lines`: a window of them reflowed, a reflowed window
1349    /// with one character changed, a verbatim window, or random pieces.
1350    /// Windows often start at the first line or end at the last.
1351    pub fn needle_text(rng: &mut Rng, lines: &[String]) -> String {
1352        let start = match rng.below(4) {
1353            0 => 0,
1354            _ => rng.below(lines.len()),
1355        };
1356        let end = match rng.below(4) {
1357            0 => lines.len(),
1358            _ => start + 1 + rng.below(lines.len() - start),
1359        };
1360        let window = lines[start..end].join("\n");
1361        match rng.below(6) {
1362            0 | 1 | 2 => reflow(rng, &window),
1363            3 => {
1364                let reflowed = reflow(rng, &window);
1365                mutate(rng, &reflowed)
1366            }
1367            4 => window,
1368            _ => (0..1 + rng.below(4))
1369                .map(|_| TOKENS[rng.below(TOKENS.len())])
1370                .collect::<Vec<_>>()
1371                .join("\n"),
1372        }
1373    }
1374
1375    fn stripped(text: &str) -> String {
1376        text.chars().filter(|ch| !ch.is_whitespace()).collect()
1377    }
1378
1379    fn normalized(text: &str) -> String {
1380        text.split_whitespace().collect::<Vec<_>>().join(" ")
1381    }
1382
1383    /// Every `(start, end)` line window whose first and last lines have
1384    /// content and whose whitespace-normalized text is exactly `needle`, by
1385    /// checking all windows.
1386    pub fn brute_force_candidates(lines: &[&str], needle: &str) -> Vec<(usize, usize)> {
1387        let mut candidates = Vec::new();
1388        for start in 0..lines.len() {
1389            for end in start + 1..=lines.len() {
1390                if stripped(lines[start]).is_empty() || stripped(lines[end - 1]).is_empty() {
1391                    continue;
1392                }
1393                if normalized(&lines[start..end].join("\n")) == needle {
1394                    candidates.push((start, end));
1395                }
1396            }
1397        }
1398        candidates
1399    }
1400
1401    /// Windows with content at both ends whose non-whitespace text equals
1402    /// `needle`'s but whose spacing differs: the near misses a search on
1403    /// stripped text alone would have had to reject.
1404    pub fn spacing_misses(lines: &[&str], needle: &str) -> usize {
1405        let (needle_stripped, needle_normalized) = (stripped(needle), normalized(needle));
1406        let mut misses = 0;
1407        for start in 0..lines.len() {
1408            for end in start + 1..=lines.len() {
1409                if stripped(lines[start]).is_empty() || stripped(lines[end - 1]).is_empty() {
1410                    continue;
1411                }
1412                let window = lines[start..end].join("\n");
1413                if stripped(&window) == needle_stripped && normalized(&window) != needle_normalized
1414                {
1415                    misses += 1;
1416                }
1417            }
1418        }
1419        misses
1420    }
1421
1422    /// Occurrences of the normalized `needle` anywhere in the lines'
1423    /// normalized text, aligned to line boundaries or not.
1424    pub fn stream_occurrences(lines: &[&str], needle: &str) -> usize {
1425        let stream = normalized(&lines.join("\n"));
1426        (0..stream.len())
1427            .filter(|&at| stream.is_char_boundary(at) && stream[at..].starts_with(needle))
1428            .count()
1429    }
1430}
1431
1432#[cfg(test)]
1433mod reflow_linear {
1434    use super::reflow_test_support::*;
1435    use super::*;
1436
1437    const REFLOW_NON_WS_TOLERANCE: usize = 8;
1438
1439    /// The window-extending scan `find_reflow_match` used before the linear
1440    /// candidate search, kept unchanged as the reference result.
1441    fn find_reflow_match_scan_oracle(
1442        lines: &[&str],
1443        pattern: &[&str],
1444        start_index: usize,
1445    ) -> Option<(usize, usize)> {
1446        let needle_text = pattern.join("\n");
1447        let normalized_needle = normalize_reflow_whitespace(&needle_text);
1448        let needle_non_whitespace = strip_reflow_whitespace(&needle_text);
1449        if normalized_needle.is_empty() || needle_non_whitespace.is_empty() {
1450            return None;
1451        }
1452        let needle_non_whitespace_len = needle_non_whitespace.chars().count();
1453        let min_non_whitespace = needle_non_whitespace_len.saturating_sub(REFLOW_NON_WS_TOLERANCE);
1454        let max_non_whitespace = needle_non_whitespace_len + REFLOW_NON_WS_TOLERANCE;
1455        let mut first_match = None;
1456        let line_lengths: Vec<usize> = lines
1457            .iter()
1458            .map(|line| line.chars().filter(|ch| !ch.is_whitespace()).count())
1459            .collect();
1460        for start in start_index..lines.len() {
1461            if !has_reflow_content(lines[start]) {
1462                continue;
1463            }
1464            let mut window_non_whitespace_len = 0;
1465            for end in (start + 1)..=lines.len() {
1466                let line = lines[end - 1];
1467                window_non_whitespace_len += line_lengths[end - 1];
1468                if window_non_whitespace_len > max_non_whitespace {
1469                    break;
1470                }
1471                if window_non_whitespace_len < min_non_whitespace {
1472                    continue;
1473                }
1474                if !has_reflow_content(line) {
1475                    continue;
1476                }
1477                let window_chars = || {
1478                    lines[start..end]
1479                        .iter()
1480                        .flat_map(|line| line.chars().chain(std::iter::once('\n')))
1481                };
1482                if !window_chars()
1483                    .filter(|ch| !ch.is_whitespace())
1484                    .eq(needle_non_whitespace.chars())
1485                {
1486                    continue;
1487                }
1488                if !collapsed_whitespace(window_chars()).eq(normalized_needle.chars()) {
1489                    continue;
1490                }
1491                if first_match.replace((start, end - start)).is_some() {
1492                    return None;
1493                }
1494            }
1495        }
1496        first_match
1497    }
1498
1499    /// The linear search returns what the old scan returned on generated
1500    /// inputs covering whitespace-only lines, tabs, CRLF, repeated blocks,
1501    /// overlapping candidates, near-miss needles (including ones with the
1502    /// same text but different spacing) and needles at either end of the
1503    /// file. Its window list also equals a brute-force list of every
1504    /// window, which pins the line-boundary alignment directly.
1505    #[test]
1506    fn linear_reflow_match_equals_the_window_scan_on_generated_inputs() {
1507        let mut rng = Rng::new(0x5eed_0001);
1508        let (mut found, mut spacing_near_misses, mut misaligned) = (0, 0, 0);
1509        for case in 0..10_000 {
1510            let mut lines = file_lines(&mut rng);
1511            if rng.below(3) == 0 {
1512                for line in &mut lines {
1513                    line.push('\r');
1514                }
1515            }
1516            let needle = needle_text(&mut rng, &lines);
1517            let pattern = needle.split('\n').collect::<Vec<_>>();
1518            let lines = lines.iter().map(String::as_str).collect::<Vec<_>>();
1519            let start_index = rng.below(lines.len() + 1);
1520            let expected = find_reflow_match_scan_oracle(&lines, &pattern, start_index);
1521            let actual = find_reflow_match(&lines, &pattern, start_index);
1522            assert_eq!(
1523                actual, expected,
1524                "case {case}: lines {lines:?} pattern {pattern:?} start {start_index}"
1525            );
1526            found += usize::from(actual.is_some());
1527
1528            let normalized = normalize_reflow_whitespace(&needle);
1529            if normalized.is_empty() {
1530                continue;
1531            }
1532            let candidates = ReflowCandidates::new(&lines, &normalized).collect::<Vec<_>>();
1533            assert_eq!(
1534                candidates,
1535                brute_force_candidates(&lines, &normalized),
1536                "case {case}: lines {lines:?} needle {needle:?}"
1537            );
1538            spacing_near_misses += spacing_misses(&lines, &needle);
1539            misaligned += stream_occurrences(&lines, &normalized) - candidates.len();
1540        }
1541        // The generator must exercise every branch the oracle comparison
1542        // relies on, or an equal result proves little.
1543        assert!(found > 300, "only {found} matches");
1544        assert!(
1545            spacing_near_misses > 300,
1546            "only {spacing_near_misses} spacing near misses"
1547        );
1548        assert!(misaligned > 300, "only {misaligned} misaligned occurrences");
1549    }
1550
1551    // BEGIN reflow-work-bound test
1552    /// A repetitive file whose lines all match the hunk's text, but the
1553    /// hunk's last line differs only in spacing ("ab" for "a b"). Every
1554    /// whitespace-stripped occurrence was a spacing near miss that used to be
1555    /// rescanned in full before being rejected: about 18,000 windows of 28 KB.
1556    /// The whole pass, building its stream, scanning it and normalizing or
1557    /// comparing any text, stays within a small multiple of the file plus
1558    /// hunk size.
1559    #[test]
1560    fn reflow_pass_work_is_linear_on_repetitive_spacing_misses() {
1561        let lines = vec!["a b"; 25_000];
1562        let mut pattern = vec!["a b"; 6_999];
1563        pattern.push("ab");
1564        REFLOW_WORK.with(|work| work.set(0));
1565        assert_eq!(find_reflow_match(&lines, &pattern, 0), None);
1566        let work = REFLOW_WORK.with(|work| work.get());
1567        let size = lines.len() * "a b\n".len() + pattern.join("\n").len();
1568        assert!(work <= 4 * size, "{work} units of work for {size} bytes");
1569    }
1570    // END reflow-work-bound test
1571
1572    /// The candidate scan does at most two steps per stream byte however the
1573    /// file repeats: here 25,000 identical lines against a 7,000-line needle,
1574    /// where every line start begins a long partial match.
1575    #[test]
1576    fn reflow_candidate_scan_is_linear_on_repetitive_input() {
1577        let lines = vec!["    value += 1;"; 25_000];
1578        let mut pattern = vec!["value += 1;"; 7_000];
1579        pattern.push("value += 2;");
1580        // The normalized stream: each line's text and one separating space.
1581        let stream_bytes = lines.len() * "value += 1; ".len();
1582        REFLOW_SCAN_STEPS.with(|steps| steps.set(0));
1583        assert_eq!(find_reflow_match(&lines, &pattern, 0), None);
1584        let steps = REFLOW_SCAN_STEPS.with(|steps| steps.get());
1585        assert!(
1586            steps <= 2 * stream_bytes,
1587            "{steps} steps for {stream_bytes} bytes"
1588        );
1589    }
1590}
1591
1592/// Generated inputs for the line-tier differential tests here and in
1593/// `fuzzy_match`: lines with duplicates, empty and whitespace-only lines,
1594/// leading and trailing spaces and tabs, smart quotes and dashes.
1595#[cfg(any(test, feature = "test-support"))]
1596pub mod line_test_support {
1597    use super::reflow_test_support::Rng;
1598
1599    const LINES: &[&str] = &[
1600        "a",
1601        "a ",
1602        " a",
1603        "\ta",
1604        "a\t",
1605        "  a  ",
1606        "b",
1607        "b ",
1608        "",
1609        " ",
1610        "\t",
1611        "x y",
1612        "x  y",
1613        "\u{2018}q\u{2019}",
1614        "'q'",
1615        "\u{2014}",
1616        "-",
1617        "a b",
1618    ];
1619
1620    /// File lines: random lines, often with a repeated block, so that
1621    /// matches repeat and overlap.
1622    pub fn file_lines(rng: &mut Rng) -> Vec<String> {
1623        let count = 1 + rng.below(16);
1624        let mut lines = Vec::new();
1625        while lines.len() < count {
1626            if rng.below(3) == 0 {
1627                let block = (0..1 + rng.below(3))
1628                    .map(|_| LINES[rng.below(LINES.len())].to_string())
1629                    .collect::<Vec<_>>();
1630                for _ in 0..2 + rng.below(4) {
1631                    lines.extend(block.iter().cloned());
1632                }
1633            } else {
1634                lines.push(LINES[rng.below(LINES.len())].to_string());
1635            }
1636        }
1637        lines.truncate(count);
1638        lines
1639    }
1640
1641    /// Pattern lines: a window of the file with each line kept, given extra
1642    /// leading or trailing whitespace, or replaced; or random lines.
1643    pub fn pattern_lines(rng: &mut Rng, lines: &[String]) -> Vec<String> {
1644        if rng.below(5) == 0 {
1645            return (0..1 + rng.below(4))
1646                .map(|_| LINES[rng.below(LINES.len())].to_string())
1647                .collect();
1648        }
1649        let start = if rng.below(4) == 0 {
1650            0
1651        } else {
1652            rng.below(lines.len())
1653        };
1654        let end = if rng.below(4) == 0 {
1655            lines.len()
1656        } else {
1657            start + 1 + rng.below(lines.len() - start)
1658        };
1659        lines[start..end]
1660            .iter()
1661            .map(|line| match rng.below(8) {
1662                0 => format!("{line} "),
1663                1 => format!(" {line}"),
1664                2 => format!("{line}\t"),
1665                3 => LINES[rng.below(LINES.len())].to_string(),
1666                _ => line.clone(),
1667            })
1668            .collect()
1669    }
1670}
1671
1672#[cfg(test)]
1673mod line_tiers {
1674    use super::line_test_support::{file_lines, pattern_lines};
1675    use super::reflow_test_support::Rng;
1676    use super::*;
1677
1678    /// `try_match` as it was before the Knuth-Morris-Pratt scan: every start
1679    /// tried in turn. Kept unchanged as the reference result.
1680    fn try_match_scan_oracle<F>(
1681        lines: &[&str],
1682        pattern: &[&str],
1683        start_index: usize,
1684        compare: F,
1685        eof: bool,
1686    ) -> Option<usize>
1687    where
1688        F: Fn(&str, &str) -> bool,
1689    {
1690        let matches_at = |start: usize| {
1691            pattern
1692                .iter()
1693                .enumerate()
1694                .all(|(offset, expected)| compare(lines[start + offset], expected))
1695        };
1696        if pattern.is_empty() || pattern.len() > lines.len() {
1697            return None;
1698        }
1699        if eof {
1700            let from_end = lines.len() - pattern.len();
1701            if from_end >= start_index && matches_at(from_end) {
1702                return Some(from_end);
1703            }
1704            return None;
1705        }
1706        let last_start = lines.len() - pattern.len();
1707        if start_index > last_start {
1708            return None;
1709        }
1710        (start_index..=last_start).find(|&start| matches_at(start))
1711    }
1712
1713    /// The first match and the next one after it (the uniqueness check the
1714    /// non-exact tiers make) agree with the old scan on generated inputs.
1715    fn assert_tier_matches_scan(seed: u64, compare: fn(&str, &str) -> bool) {
1716        let mut rng = Rng::new(seed);
1717        let mut found = 0;
1718        for case in 0..10_000 {
1719            let mut lines = file_lines(&mut rng);
1720            let mut pattern = pattern_lines(&mut rng, &lines);
1721            if rng.below(4) == 0 {
1722                // apply_patch strips a CR before matching; an unstripped one
1723                // must still compare the same way in both scans.
1724                lines.iter_mut().for_each(|line| line.push('\r'));
1725                if rng.below(2) == 0 {
1726                    pattern.iter_mut().for_each(|line| line.push('\r'));
1727                }
1728            }
1729            let lines = lines.iter().map(String::as_str).collect::<Vec<_>>();
1730            let pattern = pattern.iter().map(String::as_str).collect::<Vec<_>>();
1731            let start = rng.below(lines.len() + 1);
1732            let eof = rng.below(4) == 0;
1733            let expected = try_match_scan_oracle(&lines, &pattern, start, compare, eof);
1734            let actual = try_match(&lines, &pattern, start, compare, eof);
1735            assert_eq!(
1736                actual, expected,
1737                "case {case}: lines {lines:?} pattern {pattern:?} start {start} eof {eof}"
1738            );
1739            if let Some(first) = actual {
1740                found += 1;
1741                assert_eq!(
1742                    try_match(&lines, &pattern, first + 1, compare, eof),
1743                    try_match_scan_oracle(&lines, &pattern, first + 1, compare, eof),
1744                    "case {case}: next match after {first}"
1745                );
1746            }
1747        }
1748        assert!(found > 500, "only {found} matches");
1749    }
1750
1751    #[test]
1752    fn exact_tier_matches_the_start_by_start_scan() {
1753        assert_tier_matches_scan(0x11ae_0001, |a, b| a == b);
1754    }
1755
1756    #[test]
1757    fn rstrip_tier_matches_the_start_by_start_scan() {
1758        assert_tier_matches_scan(0x11ae_0002, |a, b| a.trim_end() == b.trim_end());
1759    }
1760
1761    #[test]
1762    fn trim_tier_matches_the_start_by_start_scan() {
1763        assert_tier_matches_scan(0x11ae_0003, |a, b| a.trim() == b.trim());
1764    }
1765
1766    // BEGIN line-tier work-bound test
1767    /// Every line of a repetitive file matches the hunk's lines except its
1768    /// last, which differs only in spacing ("ab" for "a b"). Trying every
1769    /// start compared 7,000 lines (6,999 equal, then the differing last one)
1770    /// at each of 18,001 starts in the exact, rstrip and trim tiers. All line tiers together now stay within
1771    /// a small multiple of the file plus hunk size.
1772    #[test]
1773    fn line_tier_work_is_linear_on_repetitive_near_misses() {
1774        let lines = vec!["a b"; 25_000];
1775        let mut pattern = vec!["a b"; 6_999];
1776        pattern.push("ab");
1777        LINE_MATCH_WORK.with(|work| work.set(0));
1778        assert_eq!(seek_sequence_tiered(&lines, &pattern, 0, false), None);
1779        let work = LINE_MATCH_WORK.with(|work| work.get());
1780        let size = lines.len() * "a b\n".len() + pattern.join("\n").len();
1781        assert!(work <= 32 * size, "{work} units of work for {size} bytes");
1782    }
1783    // END line-tier work-bound test
1784}
1785
1786#[cfg(test)]
1787mod approved_audit11 {
1788    use super::*;
1789
1790    #[test]
1791    fn non_exact_matches_must_be_unique_in_the_eligible_range() {
1792        for (lines, pattern) in [
1793            (vec!["target ", "other", "target\t"], vec!["target"]),
1794            (vec!["  target", "other", "\ttarget"], vec!["target"]),
1795            (vec!["‘target’", "other", "’target’"], vec!["'target'"]),
1796        ] {
1797            assert!(
1798                seek_sequence_tiered(&lines, &pattern, 0, false).is_none(),
1799                "{lines:?}"
1800            );
1801            let selected = seek_sequence_tiered(&lines, &pattern, 2, false).unwrap();
1802            assert_eq!(selected.found, 2);
1803            assert_eq!(
1804                seek_sequence_tiered(&lines, &pattern, 0, true)
1805                    .unwrap()
1806                    .found,
1807                2
1808            );
1809        }
1810        assert!(
1811            seek_sequence_tiered(
1812                &["say( ‘a’ )", "say( ’a’ )", "say(", " 'a' ", ")"],
1813                &["say( 'a' )"],
1814                0,
1815                false
1816            )
1817            .is_none(),
1818            "an ambiguous stronger fallback must not fall through to reflow"
1819        );
1820        assert_eq!(
1821            seek_sequence_tiered(&["target", "target"], &["target"], 0, false)
1822                .unwrap()
1823                .found,
1824            0
1825        );
1826    }
1827}