rgx-cli 0.11.0

A terminal regex tester with real-time matching, multi-engine support, and plain-English explanations
Documentation
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
//! PCRE2 step-through debugger using AUTO_CALLOUT.
//!
//! All unsafe FFI code for the debugger is contained in this module.

use std::ffi::c_void;
use std::ptr;

use pcre2_sys::*;

use super::{EngineError, EngineFlags, EngineResult};

#[derive(Debug, Clone)]
pub struct DebugStep {
    pub pattern_offset: usize,
    pub pattern_item_length: usize,
    pub subject_offset: usize,
    pub is_backtrack: bool,
    pub captures: Vec<Option<(usize, usize)>>,
    pub match_attempt: usize,
}

#[derive(Debug, Clone)]
pub struct PatternToken {
    pub start: usize,
    pub end: usize,
    pub description: String,
}

#[derive(Debug, Clone)]
pub struct DebugTrace {
    pub steps: Vec<DebugStep>,
    pub truncated: bool,
    pub offset_map: Vec<PatternToken>,
    pub heatmap: Vec<u32>,
    pub match_attempts: usize,
    /// Maps each byte offset in the pattern to its token index
    /// (or `usize::MAX` if none).
    pub byte_to_token: Vec<usize>,
}

#[derive(Debug, Clone)]
pub struct DebugSession {
    pub trace: DebugTrace,
    pub step: usize,
    pub show_heatmap: bool,
    pub pattern: String,
    pub subject: String,
}

// pcre2-sys blocklists callout types/functions from its generated bindings,
// so we declare the struct and extern fn manually to match the PCRE2 C ABI.
#[repr(C)]
struct Pcre2CalloutBlock {
    version: u32,
    callout_number: u32,
    capture_top: u32,
    capture_last: u32,
    offset_vector: *const usize,
    mark: *const u8,
    subject: *const u8,
    subject_length: usize,
    start_match: usize,
    current_position: usize,
    pattern_position: usize,
    next_item_length: usize,
    callout_string_offset: usize,
    callout_string_length: usize,
    callout_string: *const u8,
    callout_flags: u32,
}

unsafe extern "C" {
    fn pcre2_set_callout_8(
        mcontext: *mut pcre2_match_context_8,
        callout: Option<unsafe extern "C" fn(*mut Pcre2CalloutBlock, *mut c_void) -> i32>,
        callout_data: *mut c_void,
    ) -> i32;
}

const CALLOUT_CONTINUE: i32 = 0;
const CALLOUT_ABORT: i32 = 1;

struct CollectorState {
    steps: Vec<DebugStep>,
    max_steps: usize,
    last_start_match: usize,
    match_attempt: usize,
}

unsafe extern "C" fn callout_fn(block: *mut Pcre2CalloutBlock, data: *mut c_void) -> i32 {
    let state = unsafe { &mut *(data as *mut CollectorState) };
    let block = unsafe { &*block };

    if state.steps.len() >= state.max_steps {
        return CALLOUT_ABORT;
    }

    if block.start_match != state.last_start_match {
        state.match_attempt += 1;
        state.last_start_match = block.start_match;
    }

    let cap_count = block.capture_top as usize;
    let mut captures = Vec::with_capacity(cap_count);
    for i in 0..cap_count {
        let start = unsafe { *block.offset_vector.add(i * 2) };
        let end = unsafe { *block.offset_vector.add(i * 2 + 1) };
        if start == usize::MAX {
            captures.push(None);
        } else {
            captures.push(Some((start, end)));
        }
    }

    let is_backtrack = (block.callout_flags & PCRE2_CALLOUT_BACKTRACK) != 0;

    state.steps.push(DebugStep {
        pattern_offset: block.pattern_position,
        pattern_item_length: block.next_item_length,
        subject_offset: block.current_position,
        is_backtrack,
        captures,
        match_attempt: state.match_attempt,
    });

    CALLOUT_CONTINUE
}

pub fn debug_match(
    pattern: &str,
    subject: &str,
    flags: &EngineFlags,
    max_steps: usize,
    start_offset: usize,
) -> EngineResult<DebugTrace> {
    if pattern.is_empty() {
        return Ok(DebugTrace {
            steps: Vec::new(),
            truncated: false,
            offset_map: Vec::new(),
            heatmap: Vec::new(),
            match_attempts: 0,
            byte_to_token: Vec::new(),
        });
    }

    let offset_map = build_offset_map(pattern);

    let mut byte_to_token = vec![usize::MAX; pattern.len()];
    for (ti, token) in offset_map.iter().enumerate() {
        for slot in byte_to_token
            .iter_mut()
            .take(token.end.min(pattern.len()))
            .skip(token.start)
        {
            *slot = ti;
        }
    }

    let (steps, truncated, match_attempts) =
        unsafe { debug_match_ffi(pattern, subject, flags, max_steps, start_offset)? };

    let mut heatmap = vec![0u32; offset_map.len()];
    for step in &steps {
        if let Some(idx) = find_token_at_offset(&offset_map, step.pattern_offset) {
            heatmap[idx] += 1;
        }
    }

    Ok(DebugTrace {
        steps,
        truncated,
        offset_map,
        heatmap,
        match_attempts,
        byte_to_token,
    })
}

unsafe fn debug_match_ffi(
    pattern: &str,
    subject: &str,
    flags: &EngineFlags,
    max_steps: usize,
    start_offset: usize,
) -> EngineResult<(Vec<DebugStep>, bool, usize)> {
    let mut options: u32 = PCRE2_UTF | PCRE2_AUTO_CALLOUT;
    if flags.case_insensitive {
        options |= PCRE2_CASELESS;
    }
    if flags.multi_line {
        options |= PCRE2_MULTILINE;
    }
    if flags.dot_matches_newline {
        options |= PCRE2_DOTALL;
    }
    if flags.unicode {
        options |= PCRE2_UCP;
    }
    if flags.extended {
        options |= PCRE2_EXTENDED;
    }

    let mut error_code: i32 = 0;
    let mut error_offset: usize = 0;
    let code = unsafe {
        pcre2_compile_8(
            pattern.as_ptr(),
            pattern.len(),
            options,
            &mut error_code,
            &mut error_offset,
            ptr::null_mut(),
        )
    };
    if code.is_null() {
        return Err(EngineError::CompileError(format!(
            "PCRE2 compile error {} at offset {}",
            error_code, error_offset
        )));
    }

    let match_data = unsafe { pcre2_match_data_create_from_pattern_8(code, ptr::null_mut()) };
    if match_data.is_null() {
        unsafe { pcre2_code_free_8(code) };
        return Err(EngineError::MatchError(
            "Failed to create match data".to_string(),
        ));
    }

    let match_context = unsafe { pcre2_match_context_create_8(ptr::null_mut()) };
    if match_context.is_null() {
        unsafe { pcre2_match_data_free_8(match_data) };
        unsafe { pcre2_code_free_8(code) };
        return Err(EngineError::MatchError(
            "Failed to create match context".to_string(),
        ));
    }

    let mut collector = CollectorState {
        steps: Vec::new(),
        max_steps,
        last_start_match: usize::MAX,
        match_attempt: 0,
    };

    unsafe {
        pcre2_set_callout_8(
            match_context,
            Some(callout_fn),
            &mut collector as *mut CollectorState as *mut c_void,
        )
    };

    let subject_bytes = subject.as_bytes();
    let _rc = unsafe {
        pcre2_match_8(
            code,
            subject_bytes.as_ptr(),
            subject_bytes.len(),
            start_offset,
            PCRE2_NO_JIT,
            match_data,
            match_context,
        )
    };

    let truncated = collector.steps.len() >= max_steps;
    let match_attempts = collector.match_attempt + 1;

    unsafe { pcre2_match_context_free_8(match_context) };
    unsafe { pcre2_match_data_free_8(match_data) };
    unsafe { pcre2_code_free_8(code) };

    Ok((collector.steps, truncated, match_attempts))
}

pub fn build_offset_map(pattern: &str) -> Vec<PatternToken> {
    let ast = match crate::explain::parse_ast(pattern) {
        Some(ast) => ast,
        None => return Vec::new(),
    };
    let mut tokens = Vec::new();
    collect_tokens(&ast, &mut tokens);
    tokens.sort_by_key(|t| t.start);
    tokens.dedup_by_key(|t| t.start);
    tokens
}

fn collect_tokens(ast: &regex_syntax::ast::Ast, tokens: &mut Vec<PatternToken>) {
    use crate::explain::formatter;
    use regex_syntax::ast::Ast;

    match ast {
        Ast::Empty(_) => {}
        Ast::Flags(f) => {
            tokens.push(PatternToken {
                start: f.span.start.offset,
                end: f.span.end.offset,
                description: formatter::format_flags_item(&f.flags),
            });
        }
        Ast::Literal(lit) => {
            tokens.push(PatternToken {
                start: lit.span.start.offset,
                end: lit.span.end.offset,
                description: formatter::format_literal(lit),
            });
        }
        Ast::Dot(span) => {
            tokens.push(PatternToken {
                start: span.start.offset,
                end: span.end.offset,
                description: "Any character".to_string(),
            });
        }
        Ast::Assertion(a) => {
            tokens.push(PatternToken {
                start: a.span.start.offset,
                end: a.span.end.offset,
                description: formatter::format_assertion(a),
            });
        }
        Ast::ClassUnicode(c) => {
            tokens.push(PatternToken {
                start: c.span.start.offset,
                end: c.span.end.offset,
                description: formatter::format_unicode_class(c),
            });
        }
        Ast::ClassPerl(c) => {
            tokens.push(PatternToken {
                start: c.span.start.offset,
                end: c.span.end.offset,
                description: formatter::format_perl_class(c),
            });
        }
        Ast::ClassBracketed(c) => {
            tokens.push(PatternToken {
                start: c.span.start.offset,
                end: c.span.end.offset,
                description: formatter::format_bracketed_class(c),
            });
        }
        Ast::Repetition(rep) => {
            collect_tokens(&rep.ast, tokens);
        }
        Ast::Group(group) => {
            collect_tokens(&group.ast, tokens);
        }
        Ast::Alternation(alt) => {
            for a in &alt.asts {
                collect_tokens(a, tokens);
            }
        }
        Ast::Concat(concat) => {
            for a in &concat.asts {
                collect_tokens(a, tokens);
            }
        }
    }
}

pub fn find_token_at_offset(offset_map: &[PatternToken], offset: usize) -> Option<usize> {
    let mut best: Option<(usize, usize)> = None;
    for (i, token) in offset_map.iter().enumerate() {
        if offset >= token.start && offset < token.end {
            return Some(i);
        }
        let dist = if offset < token.start {
            token.start - offset
        } else {
            offset - token.end
        };
        if best.map_or(true, |(_, d)| dist < d) {
            best = Some((i, dist));
        }
    }
    best.map(|(i, _)| i)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_offset_map_simple_literal() {
        let tokens = build_offset_map("abc");
        assert_eq!(tokens.len(), 3);
        assert_eq!(tokens[0].start, 0);
        assert_eq!(tokens[0].end, 1);
        assert_eq!(tokens[1].start, 1);
        assert_eq!(tokens[1].end, 2);
        assert_eq!(tokens[2].start, 2);
        assert_eq!(tokens[2].end, 3);
    }

    #[test]
    fn test_offset_map_char_class() {
        let tokens = build_offset_map(r"[a-z]+");
        assert!(!tokens.is_empty());
        assert_eq!(tokens[0].start, 0);
    }

    #[test]
    fn test_offset_map_groups() {
        let tokens = build_offset_map(r"(\d{3})-(\d{4})");
        assert!(!tokens.is_empty());
        let hyphen = tokens.iter().find(|t| t.description.contains('-'));
        assert!(hyphen.is_some());
    }

    #[test]
    fn test_offset_map_empty_pattern() {
        let tokens = build_offset_map("");
        assert!(tokens.is_empty());
    }

    #[test]
    fn test_find_token_at_offset_basic() {
        let tokens = build_offset_map("abc");
        assert_eq!(find_token_at_offset(&tokens, 0), Some(0));
        assert_eq!(find_token_at_offset(&tokens, 1), Some(1));
        assert_eq!(find_token_at_offset(&tokens, 2), Some(2));
    }

    #[test]
    fn test_find_token_at_offset_empty() {
        let tokens: Vec<PatternToken> = Vec::new();
        assert_eq!(find_token_at_offset(&tokens, 0), None);
    }

    #[test]
    fn test_debug_match_simple() {
        let flags = EngineFlags::default();
        let trace = debug_match("abc", "xabcy", &flags, 10000, 0).unwrap();
        assert!(!trace.steps.is_empty(), "should have steps");
        assert!(!trace.truncated);
        assert!(trace.match_attempts >= 1);
    }

    #[test]
    fn test_debug_match_backtrack() {
        let flags = EngineFlags::default();
        // a+ab against "aaab": greedy a+ takes all a's, then must backtrack
        // to give one back for the literal 'a' before 'b'
        let trace = debug_match("a+ab", "aaab", &flags, 10000, 0).unwrap();
        let has_backtrack = trace.steps.iter().any(|s| s.is_backtrack);
        assert!(has_backtrack, "should detect backtracking");
    }

    #[test]
    fn test_debug_match_step_limit() {
        let flags = EngineFlags::default();
        // Use a pattern/subject that generates many steps
        let trace = debug_match("a+ab", "aaaaaaaaaaaaaaaaaaaaab", &flags, 5, 0).unwrap();
        assert!(trace.truncated, "should truncate at step limit");
        assert_eq!(trace.steps.len(), 5);
    }

    #[test]
    fn test_debug_match_captures() {
        let flags = EngineFlags::default();
        let trace = debug_match("(a)(b)", "ab", &flags, 10000, 0).unwrap();
        let has_capture = trace
            .steps
            .iter()
            .any(|s| s.captures.iter().any(|c| c.is_some()));
        assert!(has_capture, "should capture groups during matching");
    }

    #[test]
    fn test_debug_match_start_offset() {
        let flags = EngineFlags::default();
        let trace = debug_match(r"\d+", "foo 123 bar 456", &flags, 10000, 8).unwrap();
        assert!(
            trace.steps[0].subject_offset >= 8,
            "first step should be at or after start_offset"
        );
    }

    #[test]
    fn test_debug_match_empty_pattern() {
        let flags = EngineFlags::default();
        let trace = debug_match("", "test", &flags, 10000, 0).unwrap();
        assert!(trace.steps.is_empty());
    }

    #[test]
    fn test_debug_match_heatmap() {
        let flags = EngineFlags::default();
        let trace = debug_match("abc", "xabcy", &flags, 10000, 0).unwrap();
        assert_eq!(trace.heatmap.len(), trace.offset_map.len());
        assert!(trace.heatmap.iter().any(|&c| c > 0));
    }
}