1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
use crate::error::RipsedError;
use crate::operation::Op;
use regex::Regex;
/// One match found by [`Matcher::find_replacements`]: the byte span of the
/// match in the original text and the fully-expanded replacement for it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MatchSpan {
/// Byte offset of the match start in the original text.
pub start: usize,
/// Byte offset one past the match end in the original text.
pub end: usize,
/// The replacement text with any capture references (`$1`) expanded.
pub replacement: String,
}
/// Abstraction over literal and regex matching.
#[derive(Debug)]
pub enum Matcher {
Literal {
pattern: String,
},
/// A regex matcher — used for both explicit `--regex` patterns and as the
/// implementation backing case-insensitive literal matching (via
/// `regex::escape` + `(?i)`), which avoids byte-offset mismatches from
/// `str::to_lowercase()` on multi-byte Unicode characters.
Regex {
re: Regex,
/// Whole-buffer fast-reject shadow: the same pattern compiled with
/// `(?m)` so `^`/`$` keep their per-line meaning against a full
/// buffer. `None` when no sound shadow exists (see
/// [`prescreen_shadow`]) — then prescreening always says "maybe".
prescreen: Option<Regex>,
},
}
/// Build the whole-buffer prescreen shadow for a regex pattern, or `None`
/// when a sound one can't be constructed.
///
/// Prepending `(?m)` gives `^`/`$` the same line-boundary semantics on a
/// whole buffer that they have when matching line by line. That is NOT
/// sound for patterns using `\A`/`\z`/`\Z` (which anchor to the haystack —
/// each *line* in per-line matching, the whole buffer in the shadow) or
/// containing a flag-negating group like `(?-m)` that could switch the
/// multiline flag back off. Those patterns simply don't get a prescreen.
fn prescreen_shadow(re_pattern: &str) -> Option<Regex> {
// (`\Z` needs no check: the regex crate rejects it at compile time,
// so such a pattern never reaches prescreening.)
if re_pattern.contains(r"\A") || re_pattern.contains(r"\z") || re_pattern.contains("(?-") {
return None;
}
Regex::new(&format!("(?m){re_pattern}")).ok()
}
impl Matcher {
/// Create a new matcher from an operation.
pub fn new(op: &Op) -> Result<Self, RipsedError> {
let pattern = op.find_pattern();
let is_regex = op.is_regex();
let case_insensitive = op.is_case_insensitive();
if is_regex || case_insensitive {
// For case-insensitive literals, escape the pattern and delegate to
// the regex engine which handles Unicode casing correctly.
let re_src = if is_regex {
pattern.to_string()
} else {
regex::escape(pattern)
};
let re_pattern = if case_insensitive {
format!("(?i){re_src}")
} else {
re_src
};
Regex::new(&re_pattern)
.map(|re| Matcher::Regex {
prescreen: prescreen_shadow(&re_pattern),
re,
})
.map_err(|e| {
let mut err = RipsedError::invalid_regex(0, pattern, &e.to_string());
err.operation_index = None;
err
})
} else {
Ok(Matcher::Literal {
pattern: pattern.to_string(),
})
}
}
/// Cheap whole-buffer check: `false` means no line of `text` can match
/// this pattern, so per-line processing can be skipped entirely.
/// `true` means "maybe" — false positives are fine, false negatives
/// are a correctness bug (locked by a proptest).
pub fn prescreen(&self, text: &str) -> bool {
match self {
Matcher::Literal { pattern } => text.contains(pattern.as_str()),
Matcher::Regex {
prescreen: Some(shadow),
..
} => shadow.is_match(text),
// No sound shadow — always maybe.
Matcher::Regex {
prescreen: None, ..
} => true,
}
}
/// Check if the given text matches.
pub fn is_match(&self, text: &str) -> bool {
match self {
Matcher::Literal { pattern, .. } => text.contains(pattern.as_str()),
Matcher::Regex { re, .. } => re.is_match(text),
}
}
/// Replace all matches in the given text. Returns None if no matches.
pub fn replace(&self, text: &str, replacement: &str) -> Option<String> {
match self {
Matcher::Literal { pattern, .. } => {
if text.contains(pattern.as_str()) {
Some(text.replace(pattern.as_str(), replacement))
} else {
None
}
}
Matcher::Regex { re, .. } => {
if re.is_match(text) {
Some(re.replace_all(text, replacement).into_owned())
} else {
None
}
}
}
}
/// Replace up to `limit` matches (0 = unlimited), left to right.
///
/// Returns the new text and how many occurrences were replaced, or
/// `None` if nothing matched. With `limit == 0` this is exactly
/// [`Matcher::replace`] plus the occurrence count.
pub fn replace_n(
&self,
text: &str,
replacement: &str,
limit: usize,
) -> Option<(String, usize)> {
match self {
Matcher::Literal { pattern } => {
let occurrences = text.match_indices(pattern.as_str()).count();
if occurrences == 0 {
return None;
}
let n = if limit == 0 {
occurrences
} else {
occurrences.min(limit)
};
Some((text.replacen(pattern.as_str(), replacement, n), n))
}
Matcher::Regex { re, .. } => {
let occurrences = re.find_iter(text).count();
if occurrences == 0 {
return None;
}
let n = if limit == 0 {
occurrences
} else {
occurrences.min(limit)
};
Some((re.replacen(text, n, replacement).into_owned(), n))
}
}
}
/// Find every non-overlapping match in `text` and compute its expanded
/// replacement, left to right.
///
/// Spans are returned in ascending order and never overlap, with the
/// same semantics as [`Matcher::replace`] (`str::replace` for literals,
/// `Regex::replace_all` for regexes) — splicing each span's replacement
/// into the original text reproduces `replace`'s output exactly.
pub fn find_replacements(&self, text: &str, replacement: &str) -> Vec<MatchSpan> {
match self {
Matcher::Literal { pattern } => text
.match_indices(pattern.as_str())
.map(|(start, matched)| MatchSpan {
start,
end: start + matched.len(),
replacement: replacement.to_string(),
})
.collect(),
Matcher::Regex { re, .. } => re
.captures_iter(text)
.map(|caps| {
let m = caps.get(0).expect("capture group 0 always exists");
let mut expanded = String::new();
caps.expand(replacement, &mut expanded);
MatchSpan {
start: m.start(),
end: m.end(),
replacement: expanded,
}
})
.collect(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_literal_match() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "hello".to_string(),
replace: "hi".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
assert!(m.is_match("say hello world"));
assert!(!m.is_match("say Hi world"));
}
#[test]
fn test_literal_case_insensitive() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "hello".to_string(),
replace: "hi".to_string(),
regex: false,
case_insensitive: true,
};
let m = Matcher::new(&op).unwrap();
assert!(m.is_match("say HELLO world"));
assert!(m.is_match("say Hello world"));
}
#[test]
fn test_regex_match() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: r"fn\s+(\w+)".to_string(),
replace: "fn new_$1".to_string(),
regex: true,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
assert!(m.is_match("fn old_func() {"));
assert!(!m.is_match("let x = 5;"));
}
#[test]
fn test_regex_replace_with_captures() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: r"fn\s+old_(\w+)".to_string(),
replace: "fn new_$1".to_string(),
regex: true,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
let result = m.replace("fn old_function() {", "fn new_$1");
assert_eq!(result, Some("fn new_function() {".to_string()));
}
#[test]
fn test_invalid_regex() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "fn (foo".to_string(),
replace: "bar".to_string(),
regex: true,
case_insensitive: false,
};
let err = Matcher::new(&op).unwrap_err();
assert_eq!(err.code, crate::error::ErrorCode::InvalidRegex);
}
// ---------------------------------------------------------------
// Empty pattern behavior
// ---------------------------------------------------------------
#[test]
fn test_empty_pattern_literal_matches_everything() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "".to_string(),
replace: "x".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
// An empty string is contained in every string
assert!(m.is_match("anything"));
assert!(m.is_match(""));
}
#[test]
fn test_empty_pattern_literal_replace() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "".to_string(),
replace: "x".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
// Rust's str::replace("", "x") inserts "x" between every char and at start/end
let result = m.replace("ab", "x");
assert_eq!(result, Some("xaxbx".to_string()));
}
#[test]
fn test_empty_pattern_regex_matches_everything() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "".to_string(),
replace: "x".to_string(),
regex: true,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
assert!(m.is_match("anything"));
assert!(m.is_match(""));
}
// ---------------------------------------------------------------
// Pattern that matches entire line
// ---------------------------------------------------------------
#[test]
fn test_pattern_matches_entire_line_literal() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "hello world".to_string(),
replace: "goodbye".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
let result = m.replace("hello world", "goodbye");
assert_eq!(result, Some("goodbye".to_string()));
}
#[test]
fn test_pattern_matches_entire_line_regex() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: r"^.*$".to_string(),
replace: "replaced".to_string(),
regex: true,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
let result = m.replace("anything here", "replaced");
assert_eq!(result, Some("replaced".to_string()));
}
#[test]
fn test_regex_anchored_full_line() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: r"^fn main\(\)$".to_string(),
replace: "fn start()".to_string(),
regex: true,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
assert!(m.is_match("fn main()"));
assert!(!m.is_match(" fn main()")); // leading whitespace
assert!(!m.is_match("fn main() {")); // trailing content
}
// ---------------------------------------------------------------
// Case-insensitive with unicode (Turkish I problem, etc.)
// ---------------------------------------------------------------
#[test]
fn test_case_insensitive_ascii() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "Hello".to_string(),
replace: "hi".to_string(),
regex: false,
case_insensitive: true,
};
let m = Matcher::new(&op).unwrap();
assert!(m.is_match("HELLO"));
assert!(m.is_match("hello"));
assert!(m.is_match("HeLLo"));
let result = m.replace("say HELLO there", "hi");
assert_eq!(result, Some("say hi there".to_string()));
}
#[test]
fn test_case_insensitive_german_eszett() {
// German sharp-s: lowercase to_lowercase() of "SS" is "ss",
// and to_lowercase() of "\u{00DF}" (sharp-s) is "\u{00DF}"
// This tests that the engine handles non-trivial unicode casing
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "stra\u{00DF}e".to_string(), // "strasse" with sharp-s
replace: "street".to_string(),
regex: false,
case_insensitive: true,
};
let m = Matcher::new(&op).unwrap();
assert!(m.is_match("STRA\u{00DF}E"));
}
#[test]
fn test_case_insensitive_turkish_i_lowercase() {
// Turkish dotted I: \u{0130} (capital I with dot above)
// This is a known edge case. We test that the matcher doesn't panic
// and behaves consistently with Unicode simple case folding.
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "i".to_string(),
replace: "x".to_string(),
regex: false,
case_insensitive: true,
};
let m = Matcher::new(&op).unwrap();
// Standard ASCII: "I" simple-folds to "i", so this matches
assert!(m.is_match("I"));
// \u{0130} (İ) has no simple case fold to "i" in Unicode — the full
// fold is "i\u{0307}" but the regex engine only uses simple folds.
// This correctly does NOT match, avoiding false positives from the
// old to_lowercase()-based byte-offset approach.
assert!(!m.is_match("\u{0130}"));
}
// ---------------------------------------------------------------
// Regex special characters in literal mode
// ---------------------------------------------------------------
#[test]
fn test_literal_mode_regex_metacharacters() {
// All these are regex metacharacters but should be treated literally
let patterns = vec![
(".", "dot"),
("*", "star"),
("+", "plus"),
("?", "question"),
("(", "paren"),
("[", "bracket"),
("{", "brace"),
("^", "caret"),
("$", "dollar"),
("|", "pipe"),
("\\", "backslash"),
];
for (pat, name) in patterns {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: pat.to_string(),
replace: "X".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
let text = format!("before {pat} after");
assert!(
m.is_match(&text),
"Literal mode should match '{name}' ({pat}) as a literal character"
);
let result = m.replace(&text, "X");
assert_eq!(
result,
Some("before X after".to_string()),
"Literal mode should replace '{name}' ({pat}) as a literal"
);
}
}
// ---------------------------------------------------------------
// Multiple matches on same line
// ---------------------------------------------------------------
#[test]
fn test_multiple_matches_same_line() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "ab".to_string(),
replace: "X".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
let result = m.replace("ab cd ab ef ab", "X");
assert_eq!(result, Some("X cd X ef X".to_string()));
}
#[test]
fn test_replace_with_empty_string() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "remove".to_string(),
replace: "".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
let result = m.replace("please remove this", "");
assert_eq!(result, Some("please this".to_string()));
}
#[test]
fn test_no_match_returns_none() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "xyz".to_string(),
replace: "abc".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
assert!(m.replace("nothing here", "abc").is_none());
}
// ---------------------------------------------------------------
// Pathological / adversarial pattern tests
//
// These lock in behavior for patterns that look like they ought to
// break something: regex metacharacters misused in literal mode,
// empty inputs, patterns with backreference-like replacement strings,
// and regex that would blow up a backtracking engine.
// ---------------------------------------------------------------
/// A literal pattern of `$1` (which would be a capture backreference in
/// a regex replacement context) must match the literal two-character
/// sequence in text and be replaceable without invoking capture-group
/// semantics. Regression guard against anyone accidentally swapping
/// `str::replace` for `Regex::replace_all` in the literal path.
#[test]
fn test_literal_dollar_one_pattern() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "$1".to_string(),
replace: "REPLACED".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
assert!(m.is_match("value is $1 here"));
let result = m.replace("value is $1 here", "REPLACED");
assert_eq!(result, Some("value is REPLACED here".to_string()));
}
/// A regex pattern whose replacement string contains `$0`, `$1`, etc.
/// should be interpreted as a capture-backreference in regex mode.
/// This is intended behavior; locking it in so nobody accidentally
/// escapes it.
#[test]
fn test_regex_backreferences_work_in_replace() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: r"hello (\w+)".to_string(),
replace: "greetings, $1!".to_string(),
regex: true,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
let result = m.replace("hello world", "greetings, $1!");
assert_eq!(result, Some("greetings, world!".to_string()));
}
/// **Adversarial**: the classic "catastrophic backtracking" pattern
/// `(a+)+$` on a long non-matching input is O(2^n) in a naive NFA.
/// The `regex` crate uses a DFA/bounded-time engine so this should
/// complete effectively instantly. Lock in that we've picked a safe
/// engine — switching to a backtracking regex crate would hang here.
#[test]
fn test_regex_no_catastrophic_backtracking() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: r"(a+)+$".to_string(),
replace: "X".to_string(),
regex: true,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
// 30 'a's followed by 'b' — classic ReDoS trigger for backtracking engines.
let mut input = "a".repeat(30);
input.push('b');
let start = std::time::Instant::now();
let result = m.is_match(&input);
let elapsed = start.elapsed();
assert!(!result, "pattern should not match 'aaaa...b'");
// Generous bound — should actually complete in microseconds.
assert!(
elapsed < std::time::Duration::from_millis(500),
"regex took too long ({elapsed:?}) — possible ReDoS"
);
}
/// **Adversarial**: the replacement string is NUL-separated or contains
/// control characters. Must pass through unchanged (no shell-like
/// interpretation).
#[test]
fn test_replacement_with_control_chars() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "placeholder".to_string(),
replace: "\x07bell\x1bescape\x00nul".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
let result = m.replace("use placeholder here", "\x07bell\x1bescape\x00nul");
assert_eq!(
result,
Some("use \x07bell\x1bescape\x00nul here".to_string())
);
}
/// **Adversarial**: a regex that is a valid-but-empty-matching pattern
/// (like `(?:)`) produces an empty match at every position. This is a
/// weird edge case that can blow up naive replace loops. Lock in that
/// we produce *some* deterministic output without panicking.
#[test]
fn test_empty_regex_match_does_not_panic() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: r"(?:)".to_string(),
replace: "X".to_string(),
regex: true,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
// Must not panic — actual content of the result is implementation-defined.
let _ = m.replace("abc", "X");
}
}
// ---------------------------------------------------------------
// Property-based tests (proptest)
// ---------------------------------------------------------------
#[cfg(test)]
mod proptests {
use super::*;
use proptest::prelude::*;
proptest! {
/// Invariant: in literal mode, `Matcher::is_match(text)` ⟺
/// `text.contains(pattern)`. This guards against a future optimization
/// accidentally changing the semantics of literal matching.
#[test]
fn prop_literal_matches_iff_contains(
pattern in "[a-zA-Z0-9 ]{1,10}",
text in "[a-zA-Z0-9 ]{0,60}",
) {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: pattern.clone(),
replace: "".into(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
prop_assert_eq!(m.is_match(&text), text.contains(&pattern));
}
/// Invariant: `replace(text, pat)` returns `None` iff `is_match(text)`
/// is `false`. A mismatch here means we'd record a spurious "change"
/// with no actual edit.
#[test]
fn prop_replace_none_iff_not_match(
pattern in "[a-zA-Z0-9]{1,6}",
text in "[a-zA-Z0-9]{0,40}",
replacement in "[a-zA-Z0-9]{0,6}",
) {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: pattern.clone(),
replace: replacement.clone(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
let is_match = m.is_match(&text);
let replaced = m.replace(&text, &replacement);
prop_assert_eq!(replaced.is_some(), is_match);
}
/// Invariant: replacing pattern with itself is a no-op on content
/// (the returned String equals the input). This is a fixed-point
/// test that catches mis-implementations of the literal replace path.
#[test]
fn prop_replace_with_self_is_identity(
pattern in "[a-zA-Z0-9]{1,6}",
text in "[a-zA-Z0-9 ]{0,50}",
) {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: pattern.clone(),
replace: pattern.clone(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
if let Some(replaced) = m.replace(&text, &pattern) {
prop_assert_eq!(replaced, text);
}
}
/// Invariant: case-insensitive literal matching is symmetric —
/// `Matcher(p, ci=true).is_match(t)` equals
/// `Matcher(t.to_lowercase(), ci=false).is_match(p.to_lowercase())`
/// for ASCII patterns. (Restricts to ASCII because Unicode case folding
/// is famously asymmetric; our ASCII invariant is what callers rely on.)
#[test]
fn prop_case_insensitive_ascii_symmetric(
pattern in "[a-zA-Z]{1,6}",
text in "[a-zA-Z]{0,30}",
) {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: pattern.clone(),
replace: String::new(),
regex: false,
case_insensitive: true,
};
let m = Matcher::new(&op).unwrap();
let matches = m.is_match(&text);
prop_assert_eq!(
matches,
text.to_ascii_lowercase().contains(&pattern.to_ascii_lowercase())
);
}
/// Invariant: splicing `find_replacements` spans into the original
/// text reproduces `replace`'s output exactly — the two APIs must
/// never drift apart.
#[test]
fn prop_find_replacements_splice_equals_replace(
text in ".{0,60}",
pattern in ".{1,5}",
replacement in ".{0,8}",
) {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: pattern.clone(),
replace: replacement.clone(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
let spans = m.find_replacements(&text, &replacement);
let mut spliced = String::new();
let mut last = 0;
for s in &spans {
spliced.push_str(&text[last..s.start]);
spliced.push_str(&s.replacement);
last = s.end;
}
spliced.push_str(&text[last..]);
let expected = m.replace(&text, &replacement).unwrap_or_else(|| text.clone());
prop_assert_eq!(spliced, expected);
}
/// SOUNDNESS: prescreen(text) == false must imply that no line of
/// the text matches — a false skip would silently drop edits.
/// Exercises literals and regexes including line anchors.
#[test]
fn prop_prescreen_never_false_skips(
text in "(?:[abc^$\\n]{0,8}\\n?){0,6}",
pattern in "(?:\\^?[abc]{1,3}\\$?)|(?:[abc]{1,4})",
is_regex in proptest::bool::ANY,
) {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: pattern.clone(),
replace: String::new(),
regex: is_regex,
case_insensitive: false,
};
// Skip combos that don't compile as regex.
let Ok(m) = Matcher::new(&op) else { return Ok(()) };
if !m.prescreen(&text) {
for line in text.lines() {
prop_assert!(
!m.is_match(line),
"prescreen said no, but line {:?} matches {:?}",
line,
pattern
);
}
}
}
}
#[test]
fn test_find_replacements_literal_spans() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "ab".to_string(),
replace: "X".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
let spans = m.find_replacements("ab--ab", "X");
assert_eq!(spans.len(), 2);
assert_eq!((spans[0].start, spans[0].end), (0, 2));
assert_eq!((spans[1].start, spans[1].end), (4, 6));
assert_eq!(spans[0].replacement, "X");
}
#[test]
fn test_find_replacements_regex_capture_expansion() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: r"(\d+)-(\d+)".to_string(),
replace: "$2-$1".to_string(),
regex: true,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
let spans = m.find_replacements("1-2 and 3-4", "$2-$1");
assert_eq!(spans.len(), 2);
assert_eq!(spans[0].replacement, "2-1");
assert_eq!(spans[1].replacement, "4-3");
}
#[test]
fn test_find_replacements_across_newlines() {
let op = Op::Replace {
count: Default::default(),
multiline: true,
find: "a\nb".to_string(),
replace: "ab".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
let spans = m.find_replacements("x\na\nb\ny", "ab");
assert_eq!(spans.len(), 1);
assert_eq!((spans[0].start, spans[0].end), (2, 5));
}
#[test]
fn test_replace_n_literal_limits_and_counts() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "a".to_string(),
replace: "B".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
assert_eq!(m.replace_n("a a a", "B", 2), Some(("B B a".to_string(), 2)));
assert_eq!(m.replace_n("a a a", "B", 0), Some(("B B B".to_string(), 3)));
// Limit above occurrence count replaces them all and reports the truth.
assert_eq!(m.replace_n("a a", "B", 9), Some(("B B".to_string(), 2)));
assert_eq!(m.replace_n("zzz", "B", 1), None);
}
#[test]
fn test_replace_n_regex_limits_and_expansion() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: r"(\d)".to_string(),
replace: "[$1]".to_string(),
regex: true,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
assert_eq!(
m.replace_n("1 2 3", "[$1]", 2),
Some(("[1] [2] 3".to_string(), 2))
);
}
#[test]
fn test_replace_n_unlimited_matches_replace() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "ab".to_string(),
replace: "X".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
let (text, _) = m.replace_n("ab ab ab", "X", 0).unwrap();
assert_eq!(text, m.replace("ab ab ab", "X").unwrap());
}
// ── Prescreen ──
#[test]
fn test_prescreen_literal() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "needle".to_string(),
replace: "x".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
assert!(m.prescreen("hay needle hay"));
assert!(!m.prescreen("just hay"));
}
#[test]
fn test_prescreen_anchored_regex_is_sound() {
// The critical case: ^foo matches line 2 in per-line processing but
// NOT against the whole buffer without (?m). The shadow must say
// "maybe" here, never "no".
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "^foo".to_string(),
replace: "x".to_string(),
regex: true,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
assert!(m.prescreen("bar\nfoo\n"), "(?m) shadow must see line 2");
assert!(!m.prescreen("bar\nbaz\n"));
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "foo$".to_string(),
replace: "x".to_string(),
regex: true,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
assert!(m.prescreen("foo\nbar\n"));
}
#[test]
fn test_prescreen_haystack_anchors_disable_shadow() {
// \A anchors to the haystack: each LINE in per-line matching, the
// whole buffer in a shadow — no sound shadow exists, so prescreen
// must always say "maybe".
for pattern in [r"\Afoo", r"foo\z", r"(?-m)^foo"] {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: pattern.to_string(),
replace: "x".to_string(),
regex: true,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
assert!(
m.prescreen("anything at all"),
"{pattern} must never prescreen-reject"
);
}
}
#[test]
fn test_prescreen_case_insensitive_literal() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "Needle".to_string(),
replace: "x".to_string(),
regex: false,
case_insensitive: true,
};
let m = Matcher::new(&op).unwrap();
assert!(m.prescreen("hay NEEDLE hay"));
assert!(!m.prescreen("just hay"));
}
#[test]
fn test_find_replacements_no_match_is_empty() {
let op = Op::Replace {
count: Default::default(),
multiline: false,
find: "zzz".to_string(),
replace: "x".to_string(),
regex: false,
case_insensitive: false,
};
let m = Matcher::new(&op).unwrap();
assert!(m.find_replacements("abc", "x").is_empty());
}
}