1use crate::line_matcher::{find_nearest_miss, NearestMissSearch, ReflowCandidates};
11
12pub const NEAREST_MISS_SIMILARITY_FLOOR: f32 = 0.5;
15pub const NEAREST_MISS_EXCERPT_LINES: usize = 10;
17pub const AMBIGUOUS_OCCURRENCE_LIST_LIMIT: usize = 8;
19pub const NEAREST_MISS_LINE_CHARS: usize = 240;
21
22#[derive(Debug, Clone)]
24pub struct FuzzyMatch {
25 pub byte_start: usize,
26 pub byte_len: usize,
27 pub pass: u8,
29}
30
31pub fn find_all_fuzzy(haystack: &str, needle: &str) -> Vec<FuzzyMatch> {
34 let exact: Vec<FuzzyMatch> = haystack
36 .match_indices(needle)
37 .map(|(idx, _)| FuzzyMatch {
38 byte_start: idx,
39 byte_len: needle.len(),
40 pass: 1,
41 })
42 .collect();
43
44 if !exact.is_empty() {
45 return exact;
46 }
47
48 let needle_lines: Vec<&str> = needle.lines().collect();
50 if needle_lines.is_empty() {
51 return vec![];
52 }
53
54 let haystack_lines: Vec<&str> = haystack.lines().collect();
55 let line_byte_offsets = compute_line_offsets(haystack);
56
57 let rstrip_matches = find_line_matches(
59 &haystack_lines,
60 &needle_lines,
61 &line_byte_offsets,
62 haystack,
63 needle,
64 |a, b| a.trim_end() == b.trim_end(),
65 2,
66 );
67 if !rstrip_matches.is_empty() {
68 return rstrip_matches;
69 }
70
71 let trim_matches = find_line_matches(
73 &haystack_lines,
74 &needle_lines,
75 &line_byte_offsets,
76 haystack,
77 needle,
78 |a, b| a.trim() == b.trim(),
79 3,
80 );
81 if !trim_matches.is_empty() {
82 return trim_matches;
83 }
84
85 let normalized_haystack_lines: Vec<String> = haystack_lines
88 .iter()
89 .map(|line| normalize_unicode(line.trim()))
90 .collect();
91 let normalized_needle_lines: Vec<String> = needle_lines
92 .iter()
93 .map(|line| normalize_unicode(line.trim()))
94 .collect();
95 let normalized_haystack_refs: Vec<&str> = normalized_haystack_lines
96 .iter()
97 .map(String::as_str)
98 .collect();
99 let normalized_needle_refs: Vec<&str> =
100 normalized_needle_lines.iter().map(String::as_str).collect();
101 let normalized_matches = find_line_matches(
102 &normalized_haystack_refs,
103 &normalized_needle_refs,
104 &line_byte_offsets,
105 haystack,
106 needle,
107 |a, b| a == b,
108 4,
109 );
110 if !normalized_matches.is_empty() {
111 return normalized_matches;
112 }
113
114 find_reflow_matches(
118 &haystack_lines,
119 &needle_lines,
120 &line_byte_offsets,
121 haystack,
122 needle,
123 )
124}
125
126pub fn render_nearest_miss_detail(source: &str, needle: &str) -> String {
127 let lines: Vec<&str> = source.lines().collect();
128 let pattern: Vec<&str> = needle.lines().collect();
129 let fallback = format!(" (file has {} lines)", lines.len());
130
131 let nearest = match find_nearest_miss(&lines, &pattern, source.len()) {
132 NearestMissSearch::Found(nearest) => nearest,
133 NearestMissSearch::NoSimilarRegion | NearestMissSearch::SkippedLargeFile => {
134 return fallback;
135 }
136 };
137 let similarity = nearest.matched_lines as f32 / pattern.len().max(1) as f32;
138 if similarity < NEAREST_MISS_SIMILARITY_FLOOR {
139 return fallback;
140 }
141
142 let start_line = nearest.start + 1;
143 let end_line = nearest.end;
144 let mut detail = format!("\nNearest candidate at lines {start_line}-{end_line}:");
145 let available_lines = nearest.end.saturating_sub(nearest.start);
146 let line_number_width = end_line.to_string().len();
147
148 if available_lines <= NEAREST_MISS_EXCERPT_LINES {
149 for (offset, line) in lines[nearest.start..nearest.end].iter().enumerate() {
150 append_diagnostic_line(&mut detail, nearest.start, offset, line, line_number_width);
151 }
152 } else {
153 let head_lines = NEAREST_MISS_EXCERPT_LINES / 2;
154 let tail_lines = NEAREST_MISS_EXCERPT_LINES - head_lines;
155 for (offset, line) in lines[nearest.start..nearest.start + head_lines]
156 .iter()
157 .enumerate()
158 {
159 append_diagnostic_line(&mut detail, nearest.start, offset, line, line_number_width);
160 }
161 detail.push_str("\n ... (middle candidate lines truncated)");
162 for (offset, line) in lines[nearest.end - tail_lines..nearest.end]
163 .iter()
164 .enumerate()
165 {
166 append_diagnostic_line(
167 &mut detail,
168 nearest.start,
169 available_lines - tail_lines + offset,
170 line,
171 line_number_width,
172 );
173 }
174 }
175
176 let divergence = nearest.first_divergence;
177 let expected = pattern.get(divergence).copied().unwrap_or("<EOF>");
178 let actual = lines
179 .get(nearest.start + divergence)
180 .copied()
181 .unwrap_or("<EOF>");
182 detail.push_str(&format!(
183 "\nFirst divergence:\n- expected: {}\n+ actual: {}",
184 shorten_diagnostic_line(expected),
185 shorten_diagnostic_line(actual),
186 ));
187 detail
188}
189
190const SEARCHED_TEXT_ECHO_CHARS: usize = 120;
192
193pub fn describe_searched_text(text: &str) -> String {
198 if !text.contains('\n') && text.chars().count() <= SEARCHED_TEXT_ECHO_CHARS {
199 return format!("'{text}'");
200 }
201 let first: String = text
202 .lines()
203 .next()
204 .unwrap_or_default()
205 .chars()
206 .take(SEARCHED_TEXT_ECHO_CHARS)
207 .collect();
208 let lines = text.lines().count();
209 let noun = if lines == 1 { "line" } else { "lines" };
210 format!("'{first}…' ({lines} {noun}, {} bytes)", text.len())
211}
212
213pub fn render_edit_not_found_detail(source: &str, old_string: &str, new_string: &str) -> String {
214 let mut detail = render_nearest_miss_detail(source, old_string);
215 if new_string.is_empty() || new_string.trim().is_empty() || old_string.contains(new_string) {
216 return detail;
217 }
218
219 let mut matches = source.match_indices(new_string);
220 let Some((first_match, _)) = matches.next() else {
221 return detail;
222 };
223 if matches.next().is_some() {
224 let count = 2 + matches.count();
225 detail.push_str(&format!(
226 "\nnewString occurs {count} times; the edit may already be applied."
227 ));
228 } else {
229 let line = source.as_bytes()[..first_match]
230 .iter()
231 .filter(|byte| **byte == b'\n')
232 .count()
233 + 1;
234 detail.push_str(&format!(
235 "\nnewString is already present at line {line}; the edit may already be applied."
236 ));
237 }
238 detail
239}
240
241fn append_diagnostic_line(
242 detail: &mut String,
243 start: usize,
244 offset: usize,
245 line: &str,
246 line_number_width: usize,
247) {
248 let line_number = start + offset + 1;
249 detail.push_str(&format!(
250 "\n {line_number:>line_number_width$} | {}",
251 shorten_diagnostic_line(line),
252 line_number_width = line_number_width,
253 ));
254}
255
256pub fn shorten_diagnostic_line(line: &str) -> String {
259 let count = line.chars().count();
260 if count <= NEAREST_MISS_LINE_CHARS {
261 return line.to_string();
262 }
263
264 let head = NEAREST_MISS_LINE_CHARS / 2;
265 let tail = NEAREST_MISS_LINE_CHARS - head;
266 let byte_at = |chars: usize| {
267 line.char_indices()
268 .nth(chars)
269 .map_or(line.len(), |(byte, _)| byte)
270 };
271 let mut shortened = line[..byte_at(head)].to_string();
272 shortened.push('…');
273 shortened.push_str(&line[byte_at(count - tail)..]);
274 shortened
275}
276
277pub fn render_occurrence_listing(source: &str, positions: &[usize]) -> String {
279 let listed = positions
280 .iter()
281 .take(AMBIGUOUS_OCCURRENCE_LIST_LIMIT)
282 .enumerate()
283 .map(|(index, position)| {
284 let line = source[0..*position].matches('\n').count() + 1;
285 format!("#{} at line {}", index + 1, line)
286 })
287 .collect::<Vec<_>>();
288 let mut detail = format!(" {} occurrences: {}", positions.len(), listed.join(", "));
289 if positions.len() > AMBIGUOUS_OCCURRENCE_LIST_LIMIT {
290 detail.push_str(&format!(
291 ", … and {} more",
292 positions.len() - AMBIGUOUS_OCCURRENCE_LIST_LIMIT
293 ));
294 }
295 detail
296}
297
298fn compute_line_offsets(source: &str) -> Vec<usize> {
300 let mut offsets = vec![0];
301 for (i, c) in source.char_indices() {
302 if c == '\n' && i + 1 <= source.len() {
303 offsets.push(i + 1);
304 }
305 }
306 offsets
307}
308
309fn find_line_matches<F>(
317 haystack_lines: &[&str],
318 needle_lines: &[&str],
319 line_offsets: &[usize],
320 haystack: &str,
321 needle: &str,
322 compare: F,
323 pass: u8,
324) -> Vec<FuzzyMatch>
325where
326 F: Fn(&str, &str) -> bool,
327{
328 let compare = |line: &str, expected: &str| {
329 #[cfg(any(test, feature = "test-support"))]
330 crate::line_matcher::count_line_comparison(line, expected);
331 compare(line, expected)
332 };
333 let mut matches = Vec::new();
334 if needle_lines.is_empty() || needle_lines.len() > haystack_lines.len() {
335 return matches;
336 }
337
338 let mut prefix = vec![0; needle_lines.len()];
341 for i in 1..needle_lines.len() {
342 let mut matched = prefix[i - 1];
343 loop {
344 if compare(needle_lines[i], needle_lines[matched]) {
345 matched += 1;
346 break;
347 }
348 if matched == 0 {
349 break;
350 }
351 matched = prefix[matched - 1];
352 }
353 prefix[i] = matched;
354 }
355
356 let mut matched = 0;
357 for (index, line) in haystack_lines.iter().enumerate() {
358 loop {
359 if compare(line, needle_lines[matched]) {
360 matched += 1;
361 break;
362 }
363 if matched == 0 {
364 break;
365 }
366 matched = prefix[matched - 1];
367 }
368 if matched < needle_lines.len() {
369 continue;
370 }
371 matched = prefix[matched - 1];
372 let i = index + 1 - needle_lines.len();
374 let byte_start = line_offsets[i];
375 let end_line = i + needle_lines.len();
376 let byte_end = if end_line < line_offsets.len() {
377 line_offsets[end_line]
379 } else {
380 haystack.len()
381 };
382 matches.push(boundary_match(haystack, needle, byte_start, byte_end, pass));
383 }
384
385 matches
386}
387
388fn boundary_match(source: &str, needle: &str, start: usize, end: usize, pass: u8) -> FuzzyMatch {
392 let window = &source[start..end];
393 let source_first = window.lines().next().unwrap_or("");
394 let needle_first = needle.lines().next().unwrap_or("");
395 let source_lead = source_first
396 .chars()
397 .take_while(|c| c.is_whitespace())
398 .count();
399 let needle_lead = needle_first
400 .chars()
401 .take_while(|c| c.is_whitespace())
402 .count();
403 let leading_extra = source_lead.saturating_sub(needle_lead);
404 let byte_start = start
405 + source_first
406 .chars()
407 .take(leading_extra)
408 .map(char::len_utf8)
409 .sum::<usize>();
410
411 let source_last = window
412 .trim_end_matches('\n')
413 .split('\n')
414 .next_back()
415 .unwrap_or("");
416 let needle_last = needle
417 .trim_end_matches('\n')
418 .split('\n')
419 .next_back()
420 .unwrap_or("");
421 let source_tail = source_last
422 .chars()
423 .rev()
424 .take_while(|c| c.is_whitespace())
425 .count();
426 let needle_tail = needle_last
427 .chars()
428 .rev()
429 .take_while(|c| c.is_whitespace())
430 .count();
431 let trailing_extra = source_tail.saturating_sub(needle_tail);
432 let mut byte_end = end;
433 if window.ends_with('\n') && (!needle.ends_with('\n') || trailing_extra > 0) {
434 byte_end -= 1;
435 }
436 byte_end -= source_last
437 .chars()
438 .rev()
439 .take(trailing_extra)
440 .map(char::len_utf8)
441 .sum::<usize>();
442 FuzzyMatch {
443 byte_start,
444 byte_len: byte_end.saturating_sub(byte_start),
446 pass,
447 }
448}
449
450pub fn replacement_detail(source: &str, needle: &str, matches: &[FuzzyMatch]) -> serde_json::Value {
456 let pass = matches.first().map(|m| m.pass).unwrap_or(1);
457 let reindented = matches.iter().any(|m| {
459 indentation_shift(source, needle, m).is_ok_and(|shift| shift != IndentShift::None)
460 });
461 let actual: Vec<String> = matches
462 .iter()
463 .filter_map(|m| {
464 let text = &source[m.byte_start..m.byte_start + m.byte_len];
465 let content = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::<String>();
466 (content(text) != content(needle)).then(|| {
467 let escaped = text.escape_debug().to_string();
468 let excerpt: String = escaped.chars().take(160).collect();
469 if escaped.chars().count() > 160 {
470 format!("{excerpt}…")
471 } else {
472 excerpt
473 }
474 })
475 })
476 .collect();
477 let mut detail = serde_json::json!({
478 "pass": pass,
479 "replaced_text": actual,
480 "reindented": reindented,
481 });
482 if let Some(notice) = loose_match_notice(pass, reindented) {
483 detail["notice"] = serde_json::json!(notice);
484 }
485 detail
486}
487
488pub fn loose_match_notice(pass: u8, reindented: bool) -> Option<String> {
493 let ignored = match pass {
494 2 => "trailing whitespace",
495 3 => "indentation and trailing whitespace",
496 4 => "indentation, trailing whitespace and Unicode punctuation (curly quotes, dashes, ellipses, non-breaking spaces)",
497 5 => "line breaks and spacing",
498 _ => return None,
499 };
500 Some(if reindented {
501 format!("oldString matched only after ignoring {ignored}; newString was re-indented to match the file.")
502 } else {
503 format!("oldString matched only after ignoring {ignored}.")
504 })
505}
506
507#[derive(Debug, Clone, PartialEq, Eq)]
510pub enum IndentShift {
511 None,
513 Add(String),
517 Remove(String),
521}
522
523fn leading_whitespace(line: &str) -> &str {
524 &line[..line.len() - line.trim_start().len()]
525}
526
527const COPY_EXACT_INDENTATION: &str =
528 "Nothing was changed; copy oldString with the file's exact indentation.";
529
530fn ambiguous_indentation(reason: String) -> crate::error::AftError {
531 crate::error::AftError::AmbiguousIndentation {
532 message: format!(
533 "oldString matched only after ignoring indentation, but {reason}, so newString cannot be re-indented without guessing. {COPY_EXACT_INDENTATION}"
534 ),
535 }
536}
537
538fn file_line(source: &str, line_start: usize, offset: usize) -> usize {
540 source[..line_start].matches('\n').count() + 1 + offset
541}
542
543pub fn indentation_shift(
555 source: &str,
556 needle: &str,
557 matched: &FuzzyMatch,
558) -> Result<IndentShift, crate::error::AftError> {
559 if !matches!(matched.pass, 3 | 4) {
560 return Ok(IndentShift::None);
561 }
562 let line_start = source[..matched.byte_start]
563 .rfind('\n')
564 .map_or(0, |at| at + 1);
565 let needle_lines: Vec<&str> = needle.lines().collect();
566 let source_lines = source[line_start..].lines().take(needle_lines.len());
567 let mut shift: Option<IndentShift> = None;
568 for (offset, (file_text, needle_text)) in source_lines.zip(&needle_lines).enumerate() {
569 if file_text.trim().is_empty() || needle_text.trim().is_empty() {
571 continue;
572 }
573 let (file_lead, needle_lead) = (
574 leading_whitespace(file_text),
575 leading_whitespace(needle_text),
576 );
577 let line_shift = if file_lead == needle_lead {
578 IndentShift::None
579 } else if let Some(prefix) = file_lead.strip_suffix(needle_lead) {
580 IndentShift::Add(prefix.to_string())
581 } else if let Some(prefix) = needle_lead.strip_suffix(file_lead) {
582 IndentShift::Remove(prefix.to_string())
583 } else {
584 return Err(ambiguous_indentation(format!(
585 "line {} of the file is indented with different whitespace (tabs versus spaces) than oldString",
586 file_line(source, line_start, offset)
587 )));
588 };
589 match &shift {
590 None => shift = Some(line_shift),
591 Some(expected) if *expected != line_shift => {
592 return Err(ambiguous_indentation(format!(
593 "its indentation differs from the file's by different amounts on different lines (first at line {})",
594 file_line(source, line_start, offset)
595 )));
596 }
597 Some(_) => {}
598 }
599 }
600 Ok(shift.unwrap_or(IndentShift::None))
601}
602
603fn is_string_literal_kind(kind: &str) -> bool {
610 (kind.contains("string") && !kind.starts_with("concatenated")) || kind.contains("heredoc")
611}
612
613fn has_string_delimiter(text: &str) -> bool {
617 text.contains(['"', '\'', '`']) || text.contains("<<") || text.contains("[[")
618}
619
620fn has_multiline_string_marker(text: &str) -> bool {
626 text.contains("\"\"\"")
627 || text.contains("\'\'\'")
628 || text.contains('`')
629 || text.contains("<<")
630 || text.contains("[[")
631 || text.lines().any(|line| line.matches('"').count() % 2 == 1)
632}
633
634fn region_has_error(root: tree_sitter::Node<'_>, start: usize, end: usize) -> bool {
638 let mut pending = vec![root];
639 while let Some(node) = pending.pop() {
640 if node.end_byte() < start || node.start_byte() > end {
641 continue;
642 }
643 if node.is_error() || node.is_missing() {
644 return true;
645 }
646 if node.has_error() {
647 let mut cursor = node.walk();
648 pending.extend(node.children(&mut cursor));
649 }
650 }
651 false
652}
653
654pub fn string_literal_at_line_start(
659 root: tree_sitter::Node<'_>,
660 line_start: usize,
661) -> Option<tree_sitter::Node<'_>> {
662 let mut node = root.descendant_for_byte_range(line_start, line_start);
663 while let Some(current) = node {
664 let starts_before = current.start_byte() < line_start
667 || (current.start_byte() == line_start && current.kind().contains("heredoc"));
668 if is_string_literal_kind(current.kind())
669 && starts_before
670 && line_start < current.end_byte()
671 {
672 return Some(current);
673 }
674 node = current.parent();
675 }
676 None
677}
678
679pub fn text_lines_inside_strings(
686 text: &str,
687 path: &std::path::Path,
688 lang: crate::parser::LangId,
689) -> Option<Vec<bool>> {
690 let mut inside = vec![false; text.lines().count()];
691 if !has_string_delimiter(text) {
692 return Some(inside);
693 }
694 #[cfg(any(test, feature = "test-support"))]
695 STRING_LINE_PARSES.with(|count| count.set(count.get() + 1));
696 let tree = crate::parser::parse_source_with_cached_parser(path, text, lang).ok()?;
697 let root = tree.root_node();
698 if region_has_error(root, 0, text.len()) {
699 return None;
700 }
701 let mut line_start = 0;
702 for (index, line) in text.split_inclusive('\n').enumerate() {
703 if index > 0 && string_literal_at_line_start(root, line_start).is_some() {
704 inside[index] = true;
705 }
706 line_start += line.len();
707 }
708 Some(inside)
709}
710
711#[cfg(any(test, feature = "test-support"))]
712thread_local! {
713 pub static STRING_LINE_PARSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
715}
716
717pub struct ReindentPlan<'a> {
726 source: &'a str,
727 needle: &'a str,
728 replacement: &'a str,
729 path: Option<&'a std::path::Path>,
732 matches: &'a [FuzzyMatch],
734 source_has_delimiter: std::cell::OnceCell<bool>,
735 overlapping: std::cell::OnceCell<bool>,
738 shared: std::cell::OnceCell<Option<StringParse>>,
739}
740
741struct StringParse {
746 text: String,
747 tree: tree_sitter::Tree,
748 replacement_starts: Vec<usize>,
749}
750
751impl<'a> ReindentPlan<'a> {
752 pub fn new(
753 source: &'a str,
754 needle: &'a str,
755 replacement: &'a str,
756 path: Option<&'a std::path::Path>,
757 matches: &'a [FuzzyMatch],
758 ) -> Self {
759 Self {
760 source,
761 needle,
762 replacement,
763 path,
764 matches,
765 source_has_delimiter: std::cell::OnceCell::new(),
766 overlapping: std::cell::OnceCell::new(),
767 shared: std::cell::OnceCell::new(),
768 }
769 }
770
771 pub fn source(&self) -> &'a str {
772 self.source
773 }
774
775 pub fn matched(&self, index: usize) -> &'a FuzzyMatch {
776 &self.matches[index]
777 }
778
779 fn matched_text(&self, index: usize) -> &'a str {
781 let matched = &self.matches[index];
782 let start = self.source[..matched.byte_start]
783 .rfind('\n')
784 .map_or(0, |at| at + 1);
785 &self.source[start..matched.byte_start + matched.byte_len]
786 }
787
788 fn parse_with_replacements(
791 &self,
792 lang: crate::parser::LangId,
793 indices: &[usize],
794 ) -> Option<StringParse> {
795 let path = self.path?;
796 let mut text =
797 String::with_capacity(self.source.len() + indices.len() * (self.replacement.len() + 1));
798 let mut replacement_starts = Vec::with_capacity(indices.len());
799 let mut copied_through = 0;
800 for &index in indices {
801 let matched = &self.matches[index];
802 let end = matched.byte_start + matched.byte_len;
803 text.push_str(&self.source[copied_through..matched.byte_start]);
804 replacement_starts.push(text.len());
805 text.push_str(self.replacement);
806 if self.source[..end].ends_with('\n')
808 && !self.replacement.is_empty()
809 && !self.replacement.ends_with('\n')
810 {
811 text.push('\n');
812 }
813 copied_through = end;
814 }
815 text.push_str(&self.source[copied_through..]);
816 #[cfg(any(test, feature = "test-support"))]
817 STRING_LINE_PARSES.with(|count| count.set(count.get() + 1));
818 let tree = crate::parser::parse_source_with_cached_parser(path, &text, lang).ok()?;
819 Some(StringParse {
820 text,
821 tree,
822 replacement_starts,
823 })
824 }
825
826 fn lines_inside_new_strings(&self, index: usize) -> Result<Vec<bool>, crate::error::AftError> {
837 let pieces: Vec<&str> = self.replacement.split_inclusive('\n').collect();
838 let mut inside = vec![false; pieces.len()];
839 let Some(path) = self.path else {
840 return Ok(inside);
841 };
842 let matched_text = self.matched_text(index);
843 let Some(lang) = crate::parser::detect_language(path) else {
844 if has_multiline_string_marker(self.replacement)
845 || has_multiline_string_marker(matched_text)
846 {
847 return Err(ambiguous_indentation(
848 "this file type has no parser here and newString or the matched lines may hold a multi-line string, whose text must not move".to_string(),
849 ));
850 }
851 return Ok(inside);
852 };
853 let local_delimiters =
854 has_string_delimiter(self.replacement) || has_string_delimiter(matched_text);
855 let source_has_delimiter = *self
858 .source_has_delimiter
859 .get_or_init(|| has_string_delimiter(self.source));
860 if !local_delimiters && !source_has_delimiter {
861 return Ok(inside);
862 }
863 let unsure = || {
864 ambiguous_indentation(
865 "the code around the edit does not parse, so lines inside multi-line strings cannot be told apart from code".to_string(),
866 )
867 };
868 let overlapping = *self.overlapping.get_or_init(|| {
871 self.matches
872 .windows(2)
873 .any(|pair| pair[0].byte_start + pair[0].byte_len > pair[1].byte_start)
874 });
875 let single;
876 let (parse, slot) = if overlapping {
877 single = self.parse_with_replacements(lang, &[index]);
878 (single.as_ref(), 0)
879 } else {
880 let shared = self.shared.get_or_init(|| {
881 let all: Vec<usize> = (0..self.matches.len()).collect();
882 self.parse_with_replacements(lang, &all)
883 });
884 (shared.as_ref(), index)
885 };
886 let Some(parse) = parse else {
887 return if local_delimiters {
888 Err(unsure())
889 } else {
890 Ok(inside)
891 };
892 };
893 let replacement_start = parse.replacement_starts[slot];
894 let root = parse.tree.root_node();
895 if local_delimiters
896 && region_has_error(
897 root,
898 replacement_start,
899 replacement_start + self.replacement.len(),
900 )
901 {
902 return Err(unsure());
903 }
904 let mut offset = replacement_start;
905 for (line, piece) in pieces.iter().enumerate() {
906 let line_start = offset;
907 offset += piece.len();
908 let at_line_start = line_start == 0 || parse.text.as_bytes()[line_start - 1] == b'\n';
910 if !at_line_start || piece.trim().is_empty() {
911 continue;
912 }
913 if let Some(string) = string_literal_at_line_start(root, line_start) {
914 if string.start_byte() < replacement_start {
915 return Err(ambiguous_indentation(format!(
916 "line {} of newString is inside a multi-line string that starts before the edit, and that string's intended text is unclear",
917 line + 1
918 )));
919 }
920 inside[line] = true;
921 }
922 }
923 Ok(inside)
924 }
925
926 pub fn replacement_for(
934 &self,
935 index: usize,
936 ) -> Result<std::borrow::Cow<'a, str>, crate::error::AftError> {
937 let matched = &self.matches[index];
938 let shift = indentation_shift(self.source, self.needle, matched)?;
939 if shift == IndentShift::None {
940 return Ok(std::borrow::Cow::Borrowed(self.replacement));
941 }
942 let in_string = self.lines_inside_new_strings(index)?;
943 let line_start = self.source[..matched.byte_start]
944 .rfind('\n')
945 .map_or(0, |at| at + 1);
946 let before_match = &self.source[line_start..matched.byte_start];
947 let mut shifted =
948 String::with_capacity(self.replacement.len() + self.replacement.len() / 4);
949 match shift {
950 IndentShift::None => unreachable!("handled above"),
951 IndentShift::Add(prefix) => {
952 if before_match != prefix {
959 return Err(ambiguous_indentation(
960 "its first line is blank, so the indentation of newString's first line is unclear"
961 .to_string(),
962 ));
963 }
964 for (line, piece) in self.replacement.split_inclusive('\n').enumerate() {
965 if line > 0 && !piece.trim().is_empty() && !in_string[line] {
966 shifted.push_str(&prefix);
967 }
968 shifted.push_str(piece);
969 }
970 }
971 IndentShift::Remove(prefix) => {
972 if !before_match.is_empty() {
975 return Err(ambiguous_indentation(
976 "its first line is blank, so the indentation of newString's first line is unclear"
977 .to_string(),
978 ));
979 }
980 for (line, piece) in self.replacement.split_inclusive('\n').enumerate() {
981 if piece.trim().is_empty() || in_string[line] {
982 shifted.push_str(piece);
983 continue;
984 }
985 let Some(rest) = piece.strip_prefix(prefix.as_str()) else {
986 return Err(ambiguous_indentation(format!(
987 "oldString is indented deeper than the file, and line {} of newString does not start with that extra indentation",
988 line + 1
989 )));
990 };
991 shifted.push_str(rest);
992 }
993 }
994 }
995 Ok(std::borrow::Cow::Owned(shifted))
996 }
997}
998
999#[cfg(any(test, feature = "test-support"))]
1001pub fn reindent_replacement<'r>(
1002 source: &'r str,
1003 needle: &'r str,
1004 matched: &FuzzyMatch,
1005 replacement: &'r str,
1006 path: Option<&'r std::path::Path>,
1007) -> Result<std::borrow::Cow<'r, str>, crate::error::AftError> {
1008 let matches = std::slice::from_ref(matched);
1009 let plan = ReindentPlan::new(source, needle, replacement, path, matches);
1010 plan.replacement_for(0)
1011 .map(|text| std::borrow::Cow::Owned(text.into_owned()))
1012}
1013
1014fn find_reflow_matches(
1020 haystack_lines: &[&str],
1021 needle_lines: &[&str],
1022 line_offsets: &[usize],
1023 haystack: &str,
1024 needle: &str,
1025) -> Vec<FuzzyMatch> {
1026 let normalized_needle = normalize_reflow_whitespace(&needle_lines.join("\n"));
1027 if normalized_needle.is_empty() {
1028 return Vec::new();
1029 }
1030
1031 let mut matches = Vec::new();
1032 for (start, end) in ReflowCandidates::new(haystack_lines, &normalized_needle) {
1033 let byte_start = line_offsets[start];
1034 let byte_end = if end < line_offsets.len() {
1035 line_offsets[end]
1036 } else {
1037 haystack.len()
1038 };
1039 matches.push(boundary_match(haystack, needle, byte_start, byte_end, 5));
1040 }
1041
1042 matches
1043}
1044
1045fn normalize_reflow_whitespace(s: &str) -> String {
1046 #[cfg(any(test, feature = "test-support"))]
1047 crate::line_matcher::REFLOW_WORK.with(|work| work.set(work.get() + s.len()));
1048 let mut normalized = String::new();
1049 let mut in_whitespace = false;
1050
1051 for c in s.trim().chars() {
1052 if c.is_whitespace() {
1053 in_whitespace = true;
1054 } else {
1055 if in_whitespace && !normalized.is_empty() {
1056 normalized.push(' ');
1057 }
1058 normalized.push(c);
1059 in_whitespace = false;
1060 }
1061 }
1062
1063 normalized
1064}
1065
1066#[cfg(test)]
1067fn strip_reflow_whitespace(s: &str) -> String {
1068 s.chars().filter(|c| !c.is_whitespace()).collect()
1069}
1070
1071fn normalize_unicode(s: &str) -> String {
1073 s.chars()
1074 .map(|c| match c {
1075 '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' => '\'',
1076 '\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' => '"',
1077 '\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2014}' | '\u{2015}' => '-',
1078 '\u{00A0}' => ' ',
1079 _ => c,
1080 })
1081 .collect::<String>()
1082 .replace('\u{2026}', "...")
1083}
1084
1085#[cfg(test)]
1086mod tests {
1087 use super::*;
1088
1089 #[test]
1090 fn table_boundary_preserves_skipped_whitespace_and_separator() {
1091 let source = " | For a task | b | \n | For a task | b | \n";
1092 let matches = find_all_fuzzy(source, "| For a task | b |");
1093 assert_eq!(matches.len(), 2);
1094 assert_eq!(matches[0].pass, 5);
1095 let mut result = source.to_string();
1096 for m in matches.iter().rev() {
1097 result.replace_range(m.byte_start..m.byte_start + m.byte_len, "| Changed | b |");
1098 }
1099 assert_eq!(result, " | Changed | b | \n | Changed | b | \n");
1100 assert!(find_all_fuzzy("| a | b |\n", "a | b |").is_empty());
1101 assert_eq!(find_all_fuzzy("| a | b |\n", "| a | b |")[0].pass, 1);
1102 }
1103
1104 #[test]
1105 fn replacement_detail_exposes_unicode_difference_but_not_padding() {
1106 let source = " let title = “hello”; \n";
1107 let needle = "let title = \"hello\";";
1108 let matches = find_all_fuzzy(source, needle);
1109 let detail = replacement_detail(source, needle, &matches);
1110 assert_eq!(detail["pass"], 4);
1111 assert_eq!(detail["replaced_text"][0], "let title = “hello”;");
1112 let padded = find_all_fuzzy(" foo \n", "foo ");
1113 assert!(
1114 replacement_detail(" foo \n", "foo ", &padded)["replaced_text"]
1115 .as_array()
1116 .unwrap()
1117 .is_empty()
1118 );
1119 }
1120
1121 #[test]
1122 fn test_exact_match() {
1123 let matches = find_all_fuzzy("hello world", "world");
1124 assert_eq!(matches.len(), 1);
1125 assert_eq!(matches[0].byte_start, 6);
1126 assert_eq!(matches[0].pass, 1);
1127 }
1128
1129 #[test]
1130 fn test_exact_match_multiple() {
1131 let matches = find_all_fuzzy("foo bar foo baz foo", "foo");
1132 assert_eq!(matches.len(), 3);
1133 assert_eq!(matches[0].byte_start, 0);
1134 assert_eq!(matches[1].byte_start, 8);
1135 assert_eq!(matches[2].byte_start, 16);
1136 }
1137
1138 #[test]
1139 fn test_rstrip_match() {
1140 let source = " hello \n world \n";
1141 let needle = " hello\n world";
1142 let matches = find_all_fuzzy(source, needle);
1143 assert_eq!(matches.len(), 1);
1144 assert_eq!(matches[0].pass, 2); }
1146
1147 #[test]
1148 fn test_trim_match() {
1149 let source = " function foo() {\n return 1;\n }\n";
1150 let needle = "function foo() {\n return 1;\n}";
1151 let matches = find_all_fuzzy(source, needle);
1152 assert_eq!(matches.len(), 1);
1153 assert_eq!(matches[0].pass, 3); }
1155
1156 #[test]
1157 fn test_unicode_normalize() {
1158 let source = "let msg = \u{201C}hello\u{201D}\n";
1159 let needle = "let msg = \"hello\"";
1160 let matches = find_all_fuzzy(source, needle);
1161 assert_eq!(matches.len(), 1);
1162 assert_eq!(matches[0].pass, 4); }
1164
1165 #[test]
1166 fn test_unicode_normalize_multiline_variants() {
1167 let source = "alpha\n let title = \u{201C}hello\u{201D}\u{2026}\n let slug = foo\u{2014}bar\u{00A0}baz\nomega\n";
1168 let needle = "let title = \"hello\"...\nlet slug = foo-bar baz";
1169 let matches = find_all_fuzzy(source, needle);
1170
1171 assert_eq!(matches.len(), 1);
1172 assert_eq!(matches[0].pass, 4);
1173 assert_eq!(matches[0].byte_start, source.find("let title").unwrap());
1174 }
1175
1176 #[test]
1177 fn test_no_match() {
1178 let matches = find_all_fuzzy("hello world", "xyz");
1179 assert!(matches.is_empty());
1180 }
1181
1182 #[test]
1183 fn test_multiline_exact() {
1184 let source = "line1\nline2\nline3\nline4\n";
1185 let needle = "line2\nline3";
1186 let matches = find_all_fuzzy(source, needle);
1187 assert_eq!(matches.len(), 1);
1188 assert_eq!(matches[0].byte_start, 6);
1189 assert_eq!(matches[0].pass, 1);
1190 }
1191
1192 #[test]
1193 fn test_reflow_one_line_needle_matches_three_line_split() {
1194 let source = "before\nlet total = alpha +\n beta +\n gamma;\nafter\n";
1195 let needle = "let total = alpha + beta + gamma;";
1196 let matches = find_all_fuzzy(source, needle);
1197
1198 assert_eq!(matches.len(), 1);
1199 assert_eq!(matches[0].pass, 5);
1200 assert_eq!(matches[0].byte_start, source.find("let total").unwrap());
1201 assert_eq!(
1202 &source[matches[0].byte_start..matches[0].byte_start + matches[0].byte_len],
1203 "let total = alpha +\n beta +\n gamma;"
1204 );
1205 }
1206
1207 #[test]
1208 fn test_reflow_three_line_needle_matches_one_line_join() {
1209 let source = "before\nlet total = alpha + beta + gamma;\nafter\n";
1210 let needle = "let total = alpha +\n beta +\n gamma;";
1211 let matches = find_all_fuzzy(source, needle);
1212
1213 assert_eq!(matches.len(), 1);
1214 assert_eq!(matches[0].pass, 5);
1215 assert_eq!(matches[0].byte_start, source.find("let total").unwrap());
1216 assert_eq!(
1217 &source[matches[0].byte_start..matches[0].byte_start + matches[0].byte_len],
1218 "let total = alpha + beta + gamma;"
1219 );
1220 }
1221
1222 #[test]
1223 fn test_reflow_reports_all_ambiguous_windows() {
1224 let source =
1225 "let total = alpha +\n beta +\n gamma;\n\nlet total = alpha +\n beta +\n gamma;\n";
1226 let needle = "let total = alpha + beta + gamma;";
1227 let matches = find_all_fuzzy(source, needle);
1228
1229 assert_eq!(matches.len(), 2);
1230 assert!(matches.iter().all(|m| m.pass == 5));
1231 }
1232
1233 #[test]
1234 fn test_reflow_near_miss_does_not_match() {
1235 let source = "let total = alpha +\n beta +\n gamma;\n";
1236 let needle = "let total = alpha + beta + delta;";
1237 let matches = find_all_fuzzy(source, needle);
1238
1239 assert!(matches.is_empty());
1240 }
1241
1242 #[test]
1243 fn test_reflow_does_not_preempt_exact_match() {
1244 let source = "let total = alpha +\n beta +\n gamma;\nlet total = alpha + beta + gamma;\n";
1245 let needle = "let total = alpha + beta + gamma;";
1246 let matches = find_all_fuzzy(source, needle);
1247
1248 assert_eq!(matches.len(), 1);
1249 assert_eq!(matches[0].pass, 1);
1250 assert_eq!(matches[0].byte_start, source.rfind("let total").unwrap());
1251 }
1252
1253 #[test]
1254 fn reflow_scan_allocations_do_not_grow_with_file_lines() {
1255 let line =
1256 "export const generated = café\u{2003}+\t中 + padding_padding_padding_padding;\n";
1257 let count = |repeat: usize| {
1258 let source = line.repeat(repeat);
1259 let lines: Vec<&str> = source.lines().collect();
1260 let offsets = compute_line_offsets(&source);
1261 let needle = "never present";
1262 let ((), allocations) = crate::test_allocations::count(|| {
1263 assert!(
1264 find_reflow_matches(&lines, &[needle], &offsets, &source, needle).is_empty()
1265 );
1266 });
1267 allocations
1268 };
1269 let (small, large) = (count(256), count(4_096));
1272 assert!(large < 32, "{large} allocations for 4,096 lines");
1273 assert!(large <= small + 2, "{small} -> {large} allocations");
1274 }
1275
1276 const REFLOW_NON_WS_TOLERANCE: usize = 8;
1277
1278 fn has_reflow_content(s: &str) -> bool {
1279 s.chars().any(|c| !c.is_whitespace())
1280 }
1281
1282 fn find_reflow_matches_scan_oracle(
1285 haystack_lines: &[&str],
1286 needle_lines: &[&str],
1287 line_offsets: &[usize],
1288 haystack: &str,
1289 needle: &str,
1290 ) -> Vec<FuzzyMatch> {
1291 let needle_text = needle_lines.join("\n");
1292 let normalized_needle = normalize_reflow_whitespace(&needle_text);
1293 let needle_non_whitespace = strip_reflow_whitespace(&needle_text);
1294 if normalized_needle.is_empty() || needle_non_whitespace.is_empty() {
1295 return Vec::new();
1296 }
1297 let min_non_whitespace = needle_non_whitespace
1298 .len()
1299 .saturating_sub(REFLOW_NON_WS_TOLERANCE);
1300 let max_non_whitespace = needle_non_whitespace.len() + REFLOW_NON_WS_TOLERANCE;
1301 let line_non_whitespace_lens: Vec<usize> = haystack_lines
1302 .iter()
1303 .map(|line| {
1304 line.chars()
1305 .filter(|character| !character.is_whitespace())
1306 .map(char::len_utf8)
1307 .sum()
1308 })
1309 .collect();
1310 let mut matches = Vec::new();
1311 for start in 0..haystack_lines.len() {
1312 if !has_reflow_content(haystack_lines[start]) {
1313 continue;
1314 }
1315 let mut window_non_whitespace_len = 0usize;
1316 for end in (start + 1)..=haystack_lines.len() {
1317 let line = haystack_lines[end - 1];
1318 window_non_whitespace_len += line_non_whitespace_lens[end - 1];
1319 if window_non_whitespace_len > max_non_whitespace {
1320 break;
1321 }
1322 if window_non_whitespace_len < min_non_whitespace {
1323 continue;
1324 }
1325 if !has_reflow_content(line) {
1326 continue;
1327 }
1328 let window_text = haystack_lines[start..end].join("\n");
1329 if strip_reflow_whitespace(&window_text) != needle_non_whitespace {
1330 continue;
1331 }
1332 if normalize_reflow_whitespace(&window_text) != normalized_needle {
1333 continue;
1334 }
1335 let byte_start = line_offsets[start];
1336 let byte_end = if end < line_offsets.len() {
1337 line_offsets[end]
1338 } else {
1339 haystack.len()
1340 };
1341 matches.push(boundary_match(haystack, needle, byte_start, byte_end, 5));
1342 }
1343 }
1344 matches
1345 }
1346
1347 fn spans(matches: &[FuzzyMatch]) -> Vec<(usize, usize, u8)> {
1348 matches
1349 .iter()
1350 .map(|m| (m.byte_start, m.byte_len, m.pass))
1351 .collect()
1352 }
1353
1354 fn find_line_matches_scan_oracle<F>(
1357 haystack_lines: &[&str],
1358 needle_lines: &[&str],
1359 line_offsets: &[usize],
1360 haystack: &str,
1361 needle: &str,
1362 compare: F,
1363 pass: u8,
1364 ) -> Vec<FuzzyMatch>
1365 where
1366 F: Fn(&str, &str) -> bool,
1367 {
1368 let mut matches = Vec::new();
1369 if needle_lines.len() > haystack_lines.len() {
1370 return matches;
1371 }
1372 'outer: for i in 0..=(haystack_lines.len() - needle_lines.len()) {
1373 for j in 0..needle_lines.len() {
1374 if !compare(haystack_lines[i + j], needle_lines[j]) {
1375 continue 'outer;
1376 }
1377 }
1378 let byte_start = line_offsets[i];
1379 let end_line = i + needle_lines.len();
1380 let byte_end = if end_line < line_offsets.len() {
1381 line_offsets[end_line]
1382 } else {
1383 haystack.len()
1384 };
1385 matches.push(boundary_match(haystack, needle, byte_start, byte_end, pass));
1386 }
1387 matches
1388 }
1389
1390 fn assert_line_pass_matches_scan(seed: u64, pass: u8) {
1394 use crate::line_matcher::line_test_support::{file_lines, pattern_lines};
1395 use crate::line_matcher::reflow_test_support::Rng;
1396 let mut rng = Rng::new(seed);
1397 let (mut cases_with_matches, mut matches_total) = (0, 0);
1398 for case in 0..10_000 {
1399 let lines = file_lines(&mut rng);
1400 let separator = if rng.below(3) == 0 { "\r\n" } else { "\n" };
1401 let mut haystack = lines.join(separator);
1402 if rng.below(2) == 0 {
1403 haystack.push_str(separator);
1404 }
1405 let needle = pattern_lines(&mut rng, &lines).join(separator);
1406 let haystack_lines: Vec<&str> = haystack.lines().collect();
1407 let needle_lines: Vec<&str> = needle.lines().collect();
1408 if needle_lines.is_empty() {
1409 continue;
1410 }
1411 let offsets = compute_line_offsets(&haystack);
1412 let normalized = |lines: &[&str]| {
1413 lines
1414 .iter()
1415 .map(|line| normalize_unicode(line.trim()))
1416 .collect::<Vec<_>>()
1417 };
1418 let (haystack_normalized, needle_normalized) =
1419 (normalized(&haystack_lines), normalized(&needle_lines));
1420 let (keys, needle_keys): (Vec<&str>, Vec<&str>) = if pass == 4 {
1421 (
1422 haystack_normalized.iter().map(String::as_str).collect(),
1423 needle_normalized.iter().map(String::as_str).collect(),
1424 )
1425 } else {
1426 (haystack_lines.clone(), needle_lines.clone())
1427 };
1428 let compare: fn(&str, &str) -> bool = match pass {
1429 2 => |a, b| a.trim_end() == b.trim_end(),
1430 3 => |a, b| a.trim() == b.trim(),
1431 _ => |a, b| a == b,
1432 };
1433 let expected = find_line_matches_scan_oracle(
1434 &keys,
1435 &needle_keys,
1436 &offsets,
1437 &haystack,
1438 &needle,
1439 compare,
1440 pass,
1441 );
1442 let actual = find_line_matches(
1443 &keys,
1444 &needle_keys,
1445 &offsets,
1446 &haystack,
1447 &needle,
1448 compare,
1449 pass,
1450 );
1451 assert_eq!(
1452 spans(&actual),
1453 spans(&expected),
1454 "case {case}: haystack {haystack:?} needle {needle:?}"
1455 );
1456 cases_with_matches += usize::from(!actual.is_empty());
1457 matches_total += actual.len();
1458 }
1459 assert!(
1460 cases_with_matches > 1_000,
1461 "only {cases_with_matches} cases matched"
1462 );
1463 assert!(
1464 matches_total > cases_with_matches,
1465 "no case had several matches"
1466 );
1467 }
1468
1469 #[test]
1470 fn rstrip_pass_matches_the_start_by_start_scan() {
1471 assert_line_pass_matches_scan(0x11ae_1002, 2);
1472 }
1473
1474 #[test]
1475 fn trim_pass_matches_the_start_by_start_scan() {
1476 assert_line_pass_matches_scan(0x11ae_1003, 3);
1477 }
1478
1479 #[test]
1480 fn unicode_pass_matches_the_start_by_start_scan() {
1481 assert_line_pass_matches_scan(0x11ae_1004, 4);
1482 }
1483
1484 #[test]
1491 fn line_pass_work_is_linear_on_repetitive_near_misses() {
1492 let haystack = "a b\n".repeat(25_000);
1493 let needle = "a b\n".repeat(6_999) + "ab";
1494 crate::line_matcher::LINE_MATCH_WORK.with(|work| work.set(0));
1495 assert!(find_all_fuzzy(&haystack, &needle).is_empty());
1496 let work = crate::line_matcher::LINE_MATCH_WORK.with(std::cell::Cell::get);
1497 let size = haystack.len() + needle.len();
1498 assert!(work <= 32 * size, "{work} units of work for {size} bytes");
1499 }
1500 #[test]
1510 fn reflow_pass_work_is_linear_on_repetitive_spacing_misses() {
1511 let haystack = "a b\n".repeat(25_000);
1512 let needle = "a b\n".repeat(6_999) + "ab";
1513 let haystack_lines: Vec<&str> = haystack.lines().collect();
1514 let needle_lines: Vec<&str> = needle.lines().collect();
1515 let offsets = compute_line_offsets(&haystack);
1516 crate::line_matcher::REFLOW_WORK.with(|work| work.set(0));
1517 let matches =
1518 find_reflow_matches(&haystack_lines, &needle_lines, &offsets, &haystack, &needle);
1519 let work = crate::line_matcher::REFLOW_WORK.with(std::cell::Cell::get);
1520 assert!(matches.is_empty());
1521 let size = haystack.len() + needle.len();
1522 assert!(work <= 4 * size, "{work} units of work for {size} bytes");
1523 }
1524 #[test]
1531 fn linear_reflow_matches_equal_the_window_scan_on_generated_inputs() {
1532 use crate::line_matcher::reflow_test_support::{file_lines, needle_text, Rng};
1533 let mut rng = Rng::new(0x5eed_0002);
1534 let (mut cases_with_matches, mut matches_total) = (0, 0);
1535 for case in 0..10_000 {
1536 let lines = file_lines(&mut rng);
1537 let separator = if rng.below(3) == 0 { "\r\n" } else { "\n" };
1538 let mut haystack = lines.join(separator);
1539 if rng.below(2) == 0 {
1540 haystack.push_str(separator);
1541 }
1542 let mut needle = needle_text(&mut rng, &lines);
1543 if rng.below(4) == 0 {
1544 needle = needle.replace('\n', "\r\n");
1545 }
1546 let haystack_lines: Vec<&str> = haystack.lines().collect();
1547 let needle_lines: Vec<&str> = needle.lines().collect();
1548 let offsets = compute_line_offsets(&haystack);
1549 let expected = find_reflow_matches_scan_oracle(
1550 &haystack_lines,
1551 &needle_lines,
1552 &offsets,
1553 &haystack,
1554 &needle,
1555 );
1556 let actual =
1557 find_reflow_matches(&haystack_lines, &needle_lines, &offsets, &haystack, &needle);
1558 assert_eq!(
1559 spans(&actual),
1560 spans(&expected),
1561 "case {case}: haystack {haystack:?} needle {needle:?}"
1562 );
1563 cases_with_matches += usize::from(!actual.is_empty());
1564 matches_total += actual.len();
1565 }
1566 assert!(
1567 cases_with_matches > 300,
1568 "only {cases_with_matches} cases matched"
1569 );
1570 assert!(
1571 matches_total > cases_with_matches,
1572 "no case had several matches"
1573 );
1574 }
1575
1576 #[test]
1579 fn large_reflowed_needle_still_matches() {
1580 let lines = (0..6_000)
1581 .map(|index| format!(" call_{index}(argument_{index});"))
1582 .collect::<Vec<_>>();
1583 let source = lines.join("\n") + "\n";
1584 let needle = lines[1_000..3_000]
1585 .chunks(2)
1586 .map(|pair| {
1587 pair.iter()
1588 .map(|line| line.trim())
1589 .collect::<Vec<_>>()
1590 .join(" ")
1591 })
1592 .collect::<Vec<_>>()
1593 .join("\n");
1594 let matches = find_all_fuzzy(&source, &needle);
1595 assert_eq!(matches.len(), 1);
1596 assert_eq!(matches[0].pass, 5);
1597 assert_eq!(
1598 &source[matches[0].byte_start..matches[0].byte_start + matches[0].byte_len],
1599 lines[1_000..3_000].join("\n").trim_start()
1600 );
1601 }
1602
1603 #[test]
1604 fn nearest_miss_renders_candidate_and_first_divergence() {
1605 let source =
1606 "fn calculate() {\n let first = 1;\n let actual = 2;\n let last = 3;\n}\n";
1607 let needle =
1608 "fn calculate() {\n let first = 1;\n let expected = 2;\n let last = 3;\n}";
1609 let detail = render_nearest_miss_detail(source, needle);
1610
1611 assert!(detail.contains("Nearest candidate at lines 1-5"));
1612 assert!(detail.contains("- expected: let expected = 2;"));
1613 assert!(detail.contains("+ actual: let actual = 2;"));
1614 }
1615
1616 #[test]
1617 fn nearest_miss_below_floor_reports_only_line_count() {
1618 let source = "function totallyDifferent() {\n return 42;\n}\n";
1619 let needle = "function target() {\n return expected;\n}";
1620 let detail = render_nearest_miss_detail(source, needle);
1621
1622 assert_eq!(detail, " (file has 3 lines)");
1623 }
1624
1625 #[test]
1626 fn nearest_miss_excerpt_middle_truncates_after_ten_lines() {
1627 let source = (1..=12)
1628 .map(|line| format!("line {line}"))
1629 .collect::<Vec<_>>()
1630 .join("\n");
1631 let needle = (1..=12)
1632 .map(|line| {
1633 if line == 6 {
1634 "different line".to_string()
1635 } else {
1636 format!("line {line}")
1637 }
1638 })
1639 .collect::<Vec<_>>()
1640 .join("\n");
1641 let detail = render_nearest_miss_detail(&source, &needle);
1642
1643 assert!(detail.contains("middle candidate lines truncated"));
1644 assert!(detail.contains("line 1"));
1645 assert!(detail.contains("line 12"));
1646 assert!(!detail.contains("line 6 |"));
1647 }
1648
1649 #[test]
1650 fn occurrence_listing_is_one_based_and_capped() {
1651 let source = "same\n".repeat(10);
1652 let positions = source
1653 .match_indices("same")
1654 .map(|(offset, _)| offset)
1655 .collect::<Vec<_>>();
1656 let detail = render_occurrence_listing(&source, &positions);
1657
1658 assert!(detail.starts_with(" 10 occurrences: #1 at line 1, #2 at line 2"));
1659 assert!(detail.contains("#8 at line 8"));
1660 assert!(detail.contains("… and 2 more"));
1661 assert!(!detail.contains("#9 at line 9"));
1662 }
1663}
1664
1665#[cfg(test)]
1666mod audit_regressions {
1667 #[test]
1668 fn whitespace_match_has_valid_range() {
1669 for source in ["a\n \nb\n", "a\n \nb\n", "a\n \u{2003} \nb\n"] {
1670 let matches = super::find_all_fuzzy(source, "\t");
1671 assert!(!matches.is_empty());
1672 for m in matches {
1673 assert!(source
1674 .get(m.byte_start..m.byte_start + m.byte_len)
1675 .is_some());
1676 }
1677 }
1678 }
1679}
1680
1681#[cfg(test)]
1682mod edit_not_found_detail_tests {
1683 use super::render_edit_not_found_detail;
1684
1685 #[test]
1686 fn already_applied_hint_reports_one_line_or_repeated_occurrences() {
1687 let once =
1688 render_edit_not_found_detail("first\nreplacement\nlast\n", "missing", "replacement");
1689 assert!(once
1690 .contains("newString is already present at line 2; the edit may already be applied."));
1691
1692 let repeated = render_edit_not_found_detail(
1693 "replacement\nother replacement\n",
1694 "missing",
1695 "replacement",
1696 );
1697 assert!(repeated.contains("newString occurs 2 times; the edit may already be applied."));
1698 assert!(!repeated.contains("newString is already present at line"));
1699 }
1700
1701 #[test]
1702 fn already_applied_hint_skips_empty_whitespace_and_old_string_substrings() {
1703 for (old_string, new_string) in [
1704 ("missing", ""),
1705 ("missing", " \t\n "),
1706 ("missing replacement", "replacement"),
1707 ("missing", "not present"),
1708 ] {
1709 let detail = render_edit_not_found_detail("replacement\n", old_string, new_string);
1710 assert!(
1711 !detail.contains("newString"),
1712 "unexpected hint for newString {new_string:?}: {detail}"
1713 );
1714 }
1715 }
1716}
1717
1718#[cfg(test)]
1719mod indentation_shift_tests {
1720 use super::*;
1721
1722 #[test]
1724 fn loose_match_notice_full_strings() {
1725 let expected = [
1726 (2, false, "oldString matched only after ignoring trailing whitespace."),
1727 (3, false, "oldString matched only after ignoring indentation and trailing whitespace."),
1728 (3, true, "oldString matched only after ignoring indentation and trailing whitespace; newString was re-indented to match the file."),
1729 (4, false, "oldString matched only after ignoring indentation, trailing whitespace and Unicode punctuation (curly quotes, dashes, ellipses, non-breaking spaces)."),
1730 (4, true, "oldString matched only after ignoring indentation, trailing whitespace and Unicode punctuation (curly quotes, dashes, ellipses, non-breaking spaces); newString was re-indented to match the file."),
1731 (5, false, "oldString matched only after ignoring line breaks and spacing."),
1732 ];
1733 for (pass, reindented, notice) in expected {
1734 assert_eq!(
1735 loose_match_notice(pass, reindented).as_deref(),
1736 Some(notice),
1737 "pass {pass}, reindented {reindented}"
1738 );
1739 }
1740 assert_eq!(loose_match_notice(1, false), None);
1741 }
1742
1743 #[test]
1744 fn replacement_detail_carries_the_notice_and_shift() {
1745 let needle = "if x:\n a = 1\n b = 2";
1746 let matches = find_all_fuzzy(PY, needle);
1747 let detail = replacement_detail(PY, needle, &matches);
1748 assert_eq!(detail["reindented"], true);
1749 assert_eq!(
1750 detail["notice"],
1751 "oldString matched only after ignoring indentation and trailing whitespace; newString was re-indented to match the file."
1752 );
1753 }
1754
1755 fn reindent(source: &str, needle: &str, replacement: &str, pass: u8) -> Result<String, String> {
1758 reindent_in(None, source, needle, replacement, pass)
1759 }
1760
1761 fn reindent_in(
1764 path: Option<&str>,
1765 source: &str,
1766 needle: &str,
1767 replacement: &str,
1768 pass: u8,
1769 ) -> Result<String, String> {
1770 let matches = find_all_fuzzy(source, needle);
1771 assert_eq!(matches.len(), 1, "{source:?} / {needle:?}");
1772 assert_eq!(matches[0].pass, pass, "{source:?} / {needle:?}");
1773 reindent_replacement(
1774 source,
1775 needle,
1776 &matches[0],
1777 replacement,
1778 path.map(std::path::Path::new),
1779 )
1780 .map(|text| text.into_owned())
1781 .map_err(|error| {
1782 assert_eq!(error.code(), "ambiguous_indentation");
1783 error.to_string()
1784 })
1785 }
1786
1787 const PY: &str = "def f(x):\n if x:\n a = 1\n b = 2\n return x\n";
1788
1789 #[test]
1790 fn shallow_needle_shifts_every_later_replacement_line() {
1791 assert_eq!(
1794 reindent(
1795 PY,
1796 "if x:\n a = 1\n b = 2",
1797 "if x:\n a = 10\n\n b = 20",
1798 3
1799 )
1800 .unwrap(),
1801 "if x:\n a = 10\n\n b = 20"
1802 );
1803 assert_eq!(
1805 reindent(PY, "a = 1 ", "a = 1\nc = 3", 3).unwrap(),
1806 "a = 1\n c = 3"
1807 );
1808 }
1809
1810 #[test]
1811 fn deep_needle_drops_the_extra_prefix_from_every_line() {
1812 let source = "def f():\n a = 1\n b = 2\n";
1813 assert_eq!(
1814 reindent(
1815 source,
1816 " a = 1\n b = 2",
1817 " a = 10\n if a:\n b = 3\n",
1818 3
1819 )
1820 .unwrap(),
1821 " a = 10\n if a:\n b = 3\n"
1822 );
1823 }
1824
1825 #[test]
1826 fn tab_indented_file_shifts_by_tabs_and_keeps_crlf() {
1827 let source = "def f(x):\r\n\tif x:\r\n\t\ta = 1\r\n";
1828 assert_eq!(
1829 reindent(source, "if x:\r\n\ta = 1", "if x:\r\n\ta = 2\r\n\tb = 3", 3).unwrap(),
1830 "if x:\r\n\t\ta = 2\r\n\t\tb = 3"
1831 );
1832 }
1833
1834 #[test]
1835 fn unicode_pass_shifts_like_the_trim_pass() {
1836 let source = " if x:\n title = \u{201c}a\u{201d}\n";
1837 assert_eq!(
1838 reindent(
1839 source,
1840 "if x:\n title = \"a\"",
1841 "if x:\n title = \"b\"",
1842 4
1843 )
1844 .unwrap(),
1845 "if x:\n title = \"b\""
1846 );
1847 }
1848
1849 #[test]
1850 fn passes_that_keep_or_lose_line_pairing_never_shift() {
1851 assert_eq!(
1853 reindent(" a = 1 \n", " a = 1\t", " a = 2\nb", 2).unwrap(),
1854 " a = 2\nb"
1855 );
1856 let reflow = " call(a,\n b)\n";
1858 assert_eq!(
1859 reindent(reflow, "call(a, b)", "call(a,\nb)", 5).unwrap(),
1860 "call(a,\nb)"
1861 );
1862 }
1863
1864 #[test]
1865 fn tabs_against_spaces_are_refused() {
1866 let source = "\tif x:\n\t\ta = 1\n";
1867 assert_eq!(
1868 reindent(source, "if x:\n a = 1", "if x:\n a = 2", 3).unwrap_err(),
1869 "oldString matched only after ignoring indentation, but line 2 of the file is indented with different whitespace (tabs versus spaces) than oldString, so newString cannot be re-indented without guessing. Nothing was changed; copy oldString with the file's exact indentation."
1870 );
1871 }
1872
1873 #[test]
1874 fn different_offsets_on_different_lines_are_refused() {
1875 let source = " if (x) {\n a();\n }\n";
1878 assert_eq!(
1879 reindent(source, "if (x) {\na();\n}", "if (x) {\nb();\n}", 3).unwrap_err(),
1880 "oldString matched only after ignoring indentation, but its indentation differs from the file's by different amounts on different lines (first at line 2), so newString cannot be re-indented without guessing. Nothing was changed; copy oldString with the file's exact indentation."
1881 );
1882 }
1883
1884 #[test]
1885 fn deep_needle_with_shallower_replacement_line_is_refused() {
1886 let source = "def f():\n a = 1\n";
1887 let error = reindent(source, " a = 1", " a = 2\n b = 3", 3).unwrap_err();
1888 assert!(
1889 error.contains("line 2 of newString does not start with that extra indentation"),
1890 "{error}"
1891 );
1892 }
1893
1894 const PY_PAIR: &str = "def f():\n a = 1\n b = 2\n";
1895
1896 #[test]
1897 fn lines_inside_a_new_multiline_string_are_not_shifted() {
1898 assert_eq!(
1901 reindent_in(
1902 Some("t.py"),
1903 PY_PAIR,
1904 "a = 1\nb = 2",
1905 "a = \"\"\"\nhello\n world\n\"\"\"\nb = 2",
1906 3
1907 )
1908 .unwrap(),
1909 "a = \"\"\"\nhello\n world\n\"\"\"\n b = 2"
1910 );
1911 assert_eq!(
1913 reindent_in(
1914 Some("t.py"),
1915 PY_PAIR,
1916 " a = 1\n b = 2",
1917 " a = '''\n kept\n '''\n b = 2",
1918 3
1919 )
1920 .unwrap(),
1921 " a = '''\n kept\n '''\n b = 2"
1922 );
1923 assert_eq!(
1926 reindent_in(
1927 Some("t.py"),
1928 PY_PAIR,
1929 "a = 1\nb = 2",
1930 "a = (\"x\"\n \"y\")\nb = 2",
1931 3
1932 )
1933 .unwrap(),
1934 "a = (\"x\"\n \"y\")\n b = 2"
1935 );
1936 }
1937
1938 #[test]
1939 fn match_inside_an_existing_multiline_string_is_refused() {
1940 let source = "s = \"\"\"\n one\n two\n\"\"\"\n";
1941 let error =
1942 reindent_in(Some("t.py"), source, "one\ntwo", "one\ntwo\nthree", 3).unwrap_err();
1943 assert_eq!(
1944 error,
1945 "oldString matched only after ignoring indentation, but line 2 of newString is inside a multi-line string that starts before the edit, and that string's intended text is unclear, so newString cannot be re-indented without guessing. Nothing was changed; copy oldString with the file's exact indentation."
1946 );
1947 }
1948
1949 #[test]
1950 fn unparsed_or_unknown_text_with_string_delimiters_is_refused() {
1951 let source = "block {\n a\n b\n}\n";
1954 let error =
1955 reindent_in(Some("t.unknownext"), source, "a\nb", "a\n`x\ny`\nb", 3).unwrap_err();
1956 assert!(error.contains("no parser here"), "{error}");
1957 assert_eq!(
1959 reindent_in(Some("t.unknownext"), source, "a\nb", "a\nc\nb", 3).unwrap(),
1960 "a\n c\n b"
1961 );
1962 let ts = "function f() {\n const a = 1;\n return a;\n}\n";
1964 let error = reindent_in(
1965 Some("t.ts"),
1966 ts,
1967 "const a = 1;\nreturn a;",
1968 "const a = (1;\nconst s = 'x';\nreturn a;",
1969 3,
1970 )
1971 .unwrap_err();
1972 assert!(error.contains("does not parse"), "{error}");
1973 assert_eq!(
1975 reindent(
1976 "- item\n - a\n - b\n",
1977 "- a\n- b",
1978 "- a\n```\ncode\n```",
1979 3
1980 )
1981 .unwrap(),
1982 "- a\n ```\n code\n ```"
1983 );
1984 }
1985
1986 #[test]
1987 fn text_lines_inside_strings_marks_string_interiors_only() {
1988 let path = std::path::Path::new("t.py");
1989 let lang = crate::parser::LangId::Python;
1990 let body = " \"\"\"Doc\n more\n \"\"\"\n x = (\"a\"\n \"b\")\n";
1991 assert_eq!(
1992 text_lines_inside_strings(body, path, lang),
1993 Some(vec![false, true, true, false, false])
1994 );
1995 STRING_LINE_PARSES.with(|count| count.set(0));
1997 assert_eq!(
1998 text_lines_inside_strings("a = 1\nb = 2\n", path, lang),
1999 Some(vec![false, false])
2000 );
2001 assert_eq!(STRING_LINE_PARSES.with(|count| count.get()), 0);
2002 assert_eq!(
2004 text_lines_inside_strings("x = ('a'\ny = )\n", path, lang),
2005 None
2006 );
2007 }
2008}