Skip to main content

rgx/engine/
mod.rs

1pub mod fancy;
2#[cfg(feature = "pcre2-engine")]
3pub mod pcre2;
4pub mod rust_regex;
5
6use std::fmt;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum EngineKind {
10    RustRegex,
11    FancyRegex,
12    #[cfg(feature = "pcre2-engine")]
13    Pcre2,
14}
15
16impl EngineKind {
17    pub fn all() -> Vec<EngineKind> {
18        vec![
19            EngineKind::RustRegex,
20            EngineKind::FancyRegex,
21            #[cfg(feature = "pcre2-engine")]
22            EngineKind::Pcre2,
23        ]
24    }
25
26    pub fn next(self) -> EngineKind {
27        match self {
28            EngineKind::RustRegex => EngineKind::FancyRegex,
29            #[cfg(feature = "pcre2-engine")]
30            EngineKind::FancyRegex => EngineKind::Pcre2,
31            #[cfg(not(feature = "pcre2-engine"))]
32            EngineKind::FancyRegex => EngineKind::RustRegex,
33            #[cfg(feature = "pcre2-engine")]
34            EngineKind::Pcre2 => EngineKind::RustRegex,
35        }
36    }
37}
38
39impl fmt::Display for EngineKind {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        match self {
42            EngineKind::RustRegex => write!(f, "Rust regex"),
43            EngineKind::FancyRegex => write!(f, "fancy-regex"),
44            #[cfg(feature = "pcre2-engine")]
45            EngineKind::Pcre2 => write!(f, "PCRE2"),
46        }
47    }
48}
49
50#[derive(Debug, Clone, Default)]
51pub struct EngineFlags {
52    pub case_insensitive: bool,
53    pub multi_line: bool,
54    pub dot_matches_newline: bool,
55    pub unicode: bool,
56    pub extended: bool,
57}
58
59impl EngineFlags {
60    pub fn toggle_case_insensitive(&mut self) {
61        self.case_insensitive = !self.case_insensitive;
62    }
63    pub fn toggle_multi_line(&mut self) {
64        self.multi_line = !self.multi_line;
65    }
66    pub fn toggle_dot_matches_newline(&mut self) {
67        self.dot_matches_newline = !self.dot_matches_newline;
68    }
69    pub fn toggle_unicode(&mut self) {
70        self.unicode = !self.unicode;
71    }
72    pub fn toggle_extended(&mut self) {
73        self.extended = !self.extended;
74    }
75}
76
77#[derive(Debug, Clone)]
78pub struct Match {
79    pub start: usize,
80    pub end: usize,
81    pub text: String,
82    pub captures: Vec<CaptureGroup>,
83}
84
85#[derive(Debug, Clone)]
86pub struct CaptureGroup {
87    pub index: usize,
88    pub name: Option<String>,
89    pub start: usize,
90    pub end: usize,
91    pub text: String,
92}
93
94#[derive(Debug)]
95pub enum EngineError {
96    CompileError(String),
97    MatchError(String),
98}
99
100impl fmt::Display for EngineError {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        match self {
103            EngineError::CompileError(msg) => write!(f, "Compile error: {msg}"),
104            EngineError::MatchError(msg) => write!(f, "Match error: {msg}"),
105        }
106    }
107}
108
109impl std::error::Error for EngineError {}
110
111pub type EngineResult<T> = Result<T, EngineError>;
112
113pub trait RegexEngine: Send + Sync {
114    fn kind(&self) -> EngineKind;
115    fn compile(&self, pattern: &str, flags: &EngineFlags) -> EngineResult<Box<dyn CompiledRegex>>;
116}
117
118pub trait CompiledRegex: Send + Sync {
119    fn find_matches(&self, text: &str) -> EngineResult<Vec<Match>>;
120}
121
122pub fn create_engine(kind: EngineKind) -> Box<dyn RegexEngine> {
123    match kind {
124        EngineKind::RustRegex => Box::new(rust_regex::RustRegexEngine),
125        EngineKind::FancyRegex => Box::new(fancy::FancyRegexEngine),
126        #[cfg(feature = "pcre2-engine")]
127        EngineKind::Pcre2 => Box::new(pcre2::Pcre2Engine),
128    }
129}
130
131// --- Replace/Substitution support ---
132
133#[derive(Debug, Clone)]
134pub struct ReplaceSegment {
135    pub start: usize,
136    pub end: usize,
137    pub is_replacement: bool,
138}
139
140#[derive(Debug, Clone)]
141pub struct ReplaceResult {
142    pub output: String,
143    pub segments: Vec<ReplaceSegment>,
144}
145
146/// Expand a replacement template against a single match.
147///
148/// Supports: `$0` / `$&` (whole match), `$1`..`$99` (numbered groups),
149/// `${name}` (named groups), `$$` (literal `$`).
150fn expand_replacement(template: &str, m: &Match) -> String {
151    let mut result = String::new();
152    let bytes = template.as_bytes();
153    let len = bytes.len();
154    let mut i = 0;
155
156    while i < len {
157        if bytes[i] == b'$' {
158            if i + 1 >= len {
159                result.push('$');
160                i += 1;
161                continue;
162            }
163            let next = bytes[i + 1];
164            if next == b'$' {
165                // Literal $
166                result.push('$');
167                i += 2;
168            } else if next == b'&' {
169                // $& = whole match ($0)
170                result.push_str(&m.text);
171                i += 2;
172            } else if next == b'{' {
173                // ${name} or ${number}
174                if let Some(close) = template[i + 2..].find('}') {
175                    let ref_name = &template[i + 2..i + 2 + close];
176                    if let Some(text) = lookup_capture(m, ref_name) {
177                        result.push_str(text);
178                    }
179                    i = i + 2 + close + 1;
180                } else {
181                    // No closing brace, emit literal
182                    result.push('$');
183                    i += 1;
184                }
185            } else if next.is_ascii_digit() {
186                // $1..$99
187                let start = i + 1;
188                let mut end = start + 1;
189                // Grab up to 2 digits
190                if end < len && bytes[end].is_ascii_digit() {
191                    end += 1;
192                }
193                let num_str = &template[start..end];
194                let idx: usize = num_str.parse().unwrap_or(0);
195                if idx == 0 {
196                    result.push_str(&m.text);
197                } else if let Some(cap) = m.captures.iter().find(|c| c.index == idx) {
198                    result.push_str(&cap.text);
199                }
200                i = end;
201            } else {
202                result.push('$');
203                i += 1;
204            }
205        } else {
206            result.push(bytes[i] as char);
207            i += 1;
208        }
209    }
210
211    result
212}
213
214/// Look up a capture by name or numeric string.
215fn lookup_capture<'a>(m: &'a Match, key: &str) -> Option<&'a str> {
216    // Try as number first
217    if let Ok(idx) = key.parse::<usize>() {
218        if idx == 0 {
219            return Some(&m.text);
220        }
221        return m
222            .captures
223            .iter()
224            .find(|c| c.index == idx)
225            .map(|c| c.text.as_str());
226    }
227    // Try as named capture
228    m.captures
229        .iter()
230        .find(|c| c.name.as_deref() == Some(key))
231        .map(|c| c.text.as_str())
232}
233
234/// Perform replacement across all matches, returning the output string and segment metadata.
235pub fn replace_all(text: &str, matches: &[Match], template: &str) -> ReplaceResult {
236    let mut output = String::new();
237    let mut segments = Vec::new();
238    let mut pos = 0;
239
240    for m in matches {
241        // Original text before this match
242        if m.start > pos {
243            let seg_start = output.len();
244            output.push_str(&text[pos..m.start]);
245            segments.push(ReplaceSegment {
246                start: seg_start,
247                end: output.len(),
248                is_replacement: false,
249            });
250        }
251        // Expanded replacement
252        let expanded = expand_replacement(template, m);
253        if !expanded.is_empty() {
254            let seg_start = output.len();
255            output.push_str(&expanded);
256            segments.push(ReplaceSegment {
257                start: seg_start,
258                end: output.len(),
259                is_replacement: true,
260            });
261        }
262        pos = m.end;
263    }
264
265    // Trailing original text
266    if pos < text.len() {
267        let seg_start = output.len();
268        output.push_str(&text[pos..]);
269        segments.push(ReplaceSegment {
270            start: seg_start,
271            end: output.len(),
272            is_replacement: false,
273        });
274    }
275
276    ReplaceResult { output, segments }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    fn make_match(start: usize, end: usize, text: &str, captures: Vec<CaptureGroup>) -> Match {
284        Match {
285            start,
286            end,
287            text: text.to_string(),
288            captures,
289        }
290    }
291
292    fn make_cap(
293        index: usize,
294        name: Option<&str>,
295        start: usize,
296        end: usize,
297        text: &str,
298    ) -> CaptureGroup {
299        CaptureGroup {
300            index,
301            name: name.map(|s| s.to_string()),
302            start,
303            end,
304            text: text.to_string(),
305        }
306    }
307
308    #[test]
309    fn test_replace_all_basic() {
310        let matches = vec![make_match(
311            0,
312            12,
313            "user@example",
314            vec![
315                make_cap(1, None, 0, 4, "user"),
316                make_cap(2, None, 5, 12, "example"),
317            ],
318        )];
319        let result = replace_all("user@example", &matches, "$2=$1");
320        assert_eq!(result.output, "example=user");
321    }
322
323    #[test]
324    fn test_replace_all_no_matches() {
325        let result = replace_all("hello world", &[], "replacement");
326        assert_eq!(result.output, "hello world");
327        assert_eq!(result.segments.len(), 1);
328        assert!(!result.segments[0].is_replacement);
329    }
330
331    #[test]
332    fn test_replace_all_empty_template() {
333        let matches = vec![
334            make_match(4, 7, "123", vec![]),
335            make_match(12, 15, "456", vec![]),
336        ];
337        let result = replace_all("abc 123 def 456 ghi", &matches, "");
338        assert_eq!(result.output, "abc  def  ghi");
339    }
340
341    #[test]
342    fn test_replace_all_literal_dollar() {
343        let matches = vec![make_match(0, 3, "foo", vec![])];
344        let result = replace_all("foo", &matches, "$$bar");
345        assert_eq!(result.output, "$bar");
346    }
347
348    #[test]
349    fn test_replace_all_named_groups() {
350        let matches = vec![make_match(
351            0,
352            7,
353            "2024-01",
354            vec![
355                make_cap(1, Some("y"), 0, 4, "2024"),
356                make_cap(2, Some("m"), 5, 7, "01"),
357            ],
358        )];
359        let result = replace_all("2024-01", &matches, "${m}/${y}");
360        assert_eq!(result.output, "01/2024");
361    }
362
363    #[test]
364    fn test_expand_replacement_whole_match() {
365        let m = make_match(0, 5, "hello", vec![]);
366        assert_eq!(expand_replacement("$0", &m), "hello");
367        assert_eq!(expand_replacement("$&", &m), "hello");
368        assert_eq!(expand_replacement("[$0]", &m), "[hello]");
369    }
370
371    #[test]
372    fn test_replace_segments_tracking() {
373        let matches = vec![make_match(6, 9, "123", vec![])];
374        let result = replace_all("hello 123 world", &matches, "NUM");
375        assert_eq!(result.output, "hello NUM world");
376        assert_eq!(result.segments.len(), 3);
377        // "hello " - original
378        assert!(!result.segments[0].is_replacement);
379        assert_eq!(
380            &result.output[result.segments[0].start..result.segments[0].end],
381            "hello "
382        );
383        // "NUM" - replacement
384        assert!(result.segments[1].is_replacement);
385        assert_eq!(
386            &result.output[result.segments[1].start..result.segments[1].end],
387            "NUM"
388        );
389        // " world" - original
390        assert!(!result.segments[2].is_replacement);
391        assert_eq!(
392            &result.output[result.segments[2].start..result.segments[2].end],
393            " world"
394        );
395    }
396}