Skip to main content

c/
regex.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// Minimal POSIX regex engine (bytecode VM).
5// Supports BRE and ERE: literals, bracket expressions, groups, *, +, ?, |.
6// REG_ICASE, REG_EXTENDED, REG_NOSUB, REG_NOTBOL, REG_NOTEOL.
7// Unknown backslash sequences are treated as literal next char.
8// Bytes >= 0x80 outside brackets return REG_BADPAT.
9
10const REG_EXTENDED: c_int = 1;
11const REG_ICASE: c_int = 2;
12const REG_NOSUB: c_int = 8;
13const REG_NOTBOL: c_int = 1;
14const REG_NOTEOL: c_int = 2;
15
16const REG_OK: c_int = 0;
17const REG_NOMATCH: c_int = 1;
18const REG_BADPAT: c_int = 2;
19const REG_ESPACE: c_int = 12;
20
21const OP_CHAR: u8 = 1;
22const OP_BRACKET: u8 = 2;
23const OP_MATCH: u8 = 3;
24const OP_JUMP: u8 = 4;
25const OP_SPLIT: u8 = 5;
26const OP_BOL: u8 = 6;
27const OP_EOL: u8 = 7;
28const OP_ANY: u8 = 8;
29const OP_SAVE: u8 = 9;
30
31// regex_t layout: re_nsub(8) + __opaque(8) + __padding[4](32) + __nsub2(8) + __padding2(1) = 57 bytes
32// __opaque is at offset 8
33
34#[derive(Copy, Clone)]
35struct BracketRange {
36    min: u8,
37    max: u8,
38}
39
40struct BracketData {
41    negated: bool,
42    icase: bool,
43    nranges: usize,
44    ranges: *mut BracketRange,
45    ranges_cap: usize,
46}
47
48struct CompiledRegex {
49    ncode: usize,
50    code: *mut u8,
51    code_cap: usize,
52    icase: bool,
53    extended: bool,
54    nosub: bool,
55    nsub: usize,
56    n_brackets: usize,
57    brackets: *mut BracketData,
58    brackets_cap: usize,
59}
60
61struct RegexCContext {
62    code: *mut CompiledRegex,
63    pos: usize,
64    last_atom_start: usize,
65    depth: usize,
66    groups: usize,
67    err: c_int,
68    extended: bool,
69    icase: bool,
70}
71
72#[derive(Copy, Clone)]
73struct MatchFrame {
74    pc: usize,
75    sp: usize,
76    at_bol: bool,
77    undo: usize,
78}
79
80#[derive(Copy, Clone)]
81struct CaptureUndo {
82    slot: usize,
83    old: usize,
84}
85
86struct CaptureState {
87    slots: *mut usize,
88    nslots: usize,
89    undo: *mut CaptureUndo,
90    nundo: usize,
91    undo_cap: usize,
92}
93
94#[inline]
95fn is_ascii_letter(b: u8) -> bool {
96    (b >= b'a' && b <= b'z') || (b >= b'A' && b <= b'Z')
97}
98
99fn bracket_contains(br: &BracketData, b: u8) -> bool {
100    let c = if br.icase { case_fold_byte(b) } else { b };
101    for i in 0..br.nranges {
102        let r = unsafe { &*br.ranges.add(i) };
103        if c >= r.min && c <= r.max {
104            return !br.negated;
105        }
106    }
107    br.negated
108}
109
110fn grow_code(ctx: &mut RegexCContext, need: usize) -> bool {
111    let code = unsafe { &mut *ctx.code };
112    if need <= code.code_cap {
113        return true;
114    }
115    let mut cap = if code.code_cap == 0 { 128 } else { code.code_cap };
116    while cap < need {
117        cap *= 2;
118    }
119    let p = unsafe { crate::realloc(code.code as *mut c_void, cap) } as *mut u8;
120    if p.is_null() {
121        ctx.err = REG_ESPACE;
122        return false;
123    }
124    code.code = p;
125    code.code_cap = cap;
126    true
127}
128
129fn emit(ctx: &mut RegexCContext, byte: u8) -> bool {
130    if !grow_code(ctx, ctx.pos + 1) {
131        return false;
132    }
133    unsafe { *(*ctx.code).code.add(ctx.pos) = byte; }
134    ctx.pos += 1;
135    true
136}
137
138fn emit32(ctx: &mut RegexCContext, val: u32) -> bool {
139    emit(ctx, (val & 0xff) as u8)
140        && emit(ctx, ((val >> 8) & 0xff) as u8)
141        && emit(ctx, ((val >> 16) & 0xff) as u8)
142        && emit(ctx, ((val >> 24) & 0xff) as u8)
143}
144
145unsafe fn patch32(code: *mut u8, at: usize, val: u32) {
146    *code.add(at) = (val & 0xff) as u8;
147    *code.add(at + 1) = ((val >> 8) & 0xff) as u8;
148    *code.add(at + 2) = ((val >> 16) & 0xff) as u8;
149    *code.add(at + 3) = ((val >> 24) & 0xff) as u8;
150}
151
152fn emit_char(ctx: &mut RegexCContext, b: u8) -> bool {
153    emit(ctx, OP_CHAR) && emit(ctx, b)
154}
155
156fn emit_save(ctx: &mut RegexCContext, slot: usize) -> bool {
157    emit(ctx, OP_SAVE) && emit32(ctx, slot as u32)
158}
159
160fn case_fold_byte(b: u8) -> u8 {
161    if b >= b'a' && b <= b'z' { b - 32 }
162    else if b >= b'A' && b <= b'Z' { b + 32 }
163    else { b }
164}
165
166
167
168unsafe fn find_top_level_bar(pat: *const c_char, start: usize, end: usize) -> Option<usize> {
169    let mut i = start;
170    let mut depth = 0i32;
171    let mut in_bracket = false;
172    while i < end {
173        let c = *pat.add(i) as u8;
174        if c == b'\\' { i += 2; continue; }
175        if in_bracket {
176            if c == b']' { in_bracket = false; }
177            i += 1;
178            continue;
179        }
180        match c {
181            b'[' => in_bracket = true,
182            b'(' => depth += 1,
183            b')' => { if depth > 0 { depth -= 1; } }
184            b'|' if depth == 0 => return Some(i),
185            _ => {}
186        }
187        i += 1;
188    }
189    None
190}
191
192fn compile_expr(
193    ctx: &mut RegexCContext,
194    pat: *const c_char,
195    plen: usize,
196    start: usize,
197    end: usize,
198    in_group: bool,
199) -> bool {
200    // Nesting/alternative recursion is caller-controlled; cap it so a pattern
201    // like "((((...a...))))" cannot exhaust the C stack in regcomp().
202    const MAX_DEPTH: usize = 256;
203    if ctx.depth >= MAX_DEPTH {
204        ctx.err = REG_ESPACE;
205        return false;
206    }
207    ctx.depth += 1;
208    let ok = compile_expr_inner(ctx, pat, plen, start, end, in_group);
209    ctx.depth -= 1;
210    ok
211}
212
213fn compile_expr_inner(
214    ctx: &mut RegexCContext,
215    pat: *const c_char,
216    plen: usize,
217    start: usize,
218    end: usize,
219    _in_group: bool,
220) -> bool {
221    // A quantifier may only apply to an atom compiled in this branch, never
222    // to code left over from an earlier alternative or an enclosing group.
223    ctx.last_atom_start = ctx.pos;
224    if ctx.extended {
225        if let Some(bar) = unsafe { find_top_level_bar(pat, start, end) } {
226            let split = ctx.pos;
227            if !emit(ctx, OP_SPLIT) || !emit32(ctx, 0) { return false; }
228            if !compile_sequence(ctx, pat, plen, start, bar) { return false; }
229            let jump = ctx.pos;
230            if !emit(ctx, OP_JUMP) || !emit32(ctx, 0) { return false; }
231            let alt = ctx.pos;
232            unsafe { patch32((*ctx.code).code, split + 1, alt as u32); }
233            if !compile_expr(ctx, pat, plen, bar + 1, end, false) { return false; }
234            let after = ctx.pos;
235            unsafe { patch32((*ctx.code).code, jump + 1, after as u32); }
236            return true;
237        }
238    }
239    compile_sequence(ctx, pat, plen, start, end)
240}
241
242unsafe fn emit_bytes(ctx: &mut RegexCContext, src: *const u8, len: usize) -> bool {
243    if !grow_code(ctx, ctx.pos + len) { return false; }
244    core::ptr::copy_nonoverlapping(src, (*ctx.code).code.add(ctx.pos), len);
245    ctx.pos += len;
246    true
247}
248
249/// Adjust absolute jump/split targets inside a copied atom.  Quantifiers move
250/// the atom by emitting a split in front of it; without this, patterns like
251/// `(a|b)*` keep the old targets and match the wrong code (or loop forever).
252unsafe fn relocate_ops(code: *mut u8, start: usize, len: usize, delta: u32) {
253    if delta == 0 { return; }
254    let end = start + len;
255    let mut at = start;
256    while at < end {
257        let op = *code.add(at);
258        let step = match op {
259            OP_CHAR => 2,
260            OP_BRACKET | OP_JUMP | OP_SPLIT | OP_SAVE => 5,
261            _ => 1,
262        };
263        if (op == OP_JUMP || op == OP_SPLIT) && at + 5 <= end {
264            let old = read32(code, at + 1);
265            patch32(code, at + 1, old.wrapping_add(delta as usize) as u32);
266        }
267        at += step;
268    }
269}
270
271fn emit_quantifier(
272    ctx: &mut RegexCContext,
273    prev: *const u8,
274    len: usize,
275    kind: u8,
276    atom_start: usize,
277) -> bool {
278    unsafe {
279        if kind == b'*' {
280            let split = ctx.pos;
281            if !emit(ctx, OP_SPLIT) || !emit32(ctx, 0) { return false; }
282            let new_start = ctx.pos;
283            if !emit_bytes(ctx, prev, len) { return false; }
284            relocate_ops((*ctx.code).code, new_start, len, (new_start - atom_start) as u32);
285            let jump = ctx.pos;
286            if !emit(ctx, OP_JUMP) || !emit32(ctx, 0) { return false; }
287            let after = ctx.pos;
288            patch32((*ctx.code).code, split + 1, after as u32);
289            patch32((*ctx.code).code, jump + 1, split as u32);
290        } else if kind == b'+' {
291            let atom = ctx.pos;
292            if !emit_bytes(ctx, prev, len) { return false; }
293            relocate_ops((*ctx.code).code, atom, len, (atom - atom_start) as u32);
294            let split = ctx.pos;
295            if !emit(ctx, OP_SPLIT) || !emit32(ctx, 0) { return false; }
296            let jump = ctx.pos;
297            if !emit(ctx, OP_JUMP) || !emit32(ctx, 0) { return false; }
298            let after = ctx.pos;
299            patch32((*ctx.code).code, split + 1, after as u32);
300            patch32((*ctx.code).code, jump + 1, atom as u32);
301        } else {
302            let split = ctx.pos;
303            if !emit(ctx, OP_SPLIT) || !emit32(ctx, 0) { return false; }
304            let new_start = ctx.pos;
305            if !emit_bytes(ctx, prev, len) { return false; }
306            relocate_ops((*ctx.code).code, new_start, len, (new_start - atom_start) as u32);
307            let after = ctx.pos;
308            patch32((*ctx.code).code, split + 1, after as u32);
309        }
310    }
311    true
312}
313
314fn compile_sequence(
315    ctx: &mut RegexCContext,
316    pat: *const c_char,
317    plen: usize,
318    start: usize,
319    end: usize,
320) -> bool {
321    let mut i = start;
322    let extended = ctx.extended;
323
324    while i < end {
325        let b = unsafe { *pat.add(i) as u8 };
326
327        // compile_expr() splits top-level alternatives into separate ranges;
328        // a bar that reaches here is inside a bracket or a malformed branch.
329        if b == b'|' && extended { return true; }
330
331        if b == b'\\' && i + 1 < end {
332            let next = unsafe { *pat.add(i + 1) as u8 };
333            if next >= 0x80 { return false; }
334            if !extended && next == b'(' {
335                let atom = ctx.pos;
336                i = i.wrapping_add(2);
337                if !compile_group(ctx, pat, plen, &mut i, end) { return false; }
338                ctx.last_atom_start = atom;
339                continue;
340            }
341            if !extended && next == b')' { return true; }
342            let atom = ctx.pos;
343            if !emit_char(ctx, next) { return false; }
344            ctx.last_atom_start = atom;
345            i = i.wrapping_add(2);
346            continue;
347        }
348
349        if b == b'(' && extended {
350            let atom = ctx.pos;
351            i += 1;
352            if !compile_group(ctx, pat, plen, &mut i, end) { return false; }
353            ctx.last_atom_start = atom;
354            continue;
355        }
356
357        if b == b'[' {
358            let atom = ctx.pos;
359            if !compile_bracket(ctx, pat, plen, &mut i, end) { return false; }
360            ctx.last_atom_start = atom;
361            continue;
362        }
363
364        if b == b'.' {
365            let atom = ctx.pos;
366            if !emit(ctx, OP_ANY) { return false; }
367            ctx.last_atom_start = atom;
368            i += 1;
369            continue;
370        }
371
372        if b == b'^' && i == start {
373            let atom = ctx.pos;
374            if !emit(ctx, OP_BOL) { return false; }
375            ctx.last_atom_start = atom;
376            i += 1;
377            continue;
378        }
379        if b == b'$' && i + 1 == end {
380            let atom = ctx.pos;
381            if !emit(ctx, OP_EOL) { return false; }
382            ctx.last_atom_start = atom;
383            i += 1;
384            continue;
385        }
386
387        if (b == b'*' || b == b'+' || b == b'?') && ctx.last_atom_start < ctx.pos {
388            let prev_start = ctx.last_atom_start;
389            let prev_len = ctx.pos - prev_start;
390            let op = unsafe { *(*ctx.code).code.add(prev_start) };
391            if op == OP_CHAR || op == OP_BRACKET || op == OP_ANY || op == OP_BOL
392                || op == OP_EOL || op == OP_SAVE
393            {
394                let prev = unsafe { crate::malloc(prev_len) as *mut u8 };
395                if prev.is_null() { return false; }
396                unsafe {
397                    core::ptr::copy_nonoverlapping(
398                        (*ctx.code).code.add(prev_start), prev, prev_len);
399                }
400                ctx.pos = prev_start;
401                let ok = emit_quantifier(ctx, prev, prev_len, b, prev_start);
402                unsafe { crate::free(prev as *mut c_void); }
403                if !ok { return false; }
404                // A second quantifier applies to nothing (a** / a*?), so make
405                // the last-atom marker invalid and let it be a literal.
406                ctx.last_atom_start = ctx.pos;
407                i += 1;
408                continue;
409            }
410        }
411
412        if b >= 0x80 { return false; }
413        let atom = ctx.pos;
414        if !emit_char(ctx, b) { return false; }
415        ctx.last_atom_start = atom;
416        i += 1;
417    }
418    true
419}
420
421fn compile_group(
422    ctx: &mut RegexCContext,
423    pat: *const c_char,
424    plen: usize,
425    i: &mut usize,
426    end: usize,
427) -> bool {
428    let start = *i;
429    let mut depth = 1i32;
430    let mut in_bracket = false;
431    let mut j = start;
432    while j < end && depth > 0 {
433        let b = unsafe { *pat.add(j) as u8 };
434        if b == b'\\' { j += 2; continue; }
435        if in_bracket {
436            if b == b']' { in_bracket = false; }
437            j += 1;
438            continue;
439        }
440        if b == b'[' { in_bracket = true; }
441        else if b == b'(' { depth += 1; }
442        else if b == b')' { depth -= 1; }
443        if depth > 0 { j += 1; }
444    }
445    if depth != 0 { return false; }
446    ctx.groups += 1;
447    let group = ctx.groups;
448    if !emit_save(ctx, group * 2) { return false; }
449    if !compile_expr(ctx, pat, plen, start, j, true) { return false; }
450    if !emit_save(ctx, group * 2 + 1) { return false; }
451    *i = j + 1;
452    true
453}
454
455fn add_range(ctx: &mut RegexCContext, bi: usize, min: u8, max: u8) -> bool {
456    let bd = unsafe { &mut *(*ctx.code).brackets.add(bi) };
457    if bd.nranges == bd.ranges_cap {
458        let cap = if bd.ranges_cap == 0 { 16 } else { bd.ranges_cap * 2 };
459        let p = unsafe {
460            crate::realloc(
461                bd.ranges as *mut c_void,
462                cap * core::mem::size_of::<BracketRange>(),
463            )
464        } as *mut BracketRange;
465        if p.is_null() {
466            ctx.err = REG_ESPACE;
467            return false;
468        }
469        bd.ranges = p;
470        bd.ranges_cap = cap;
471    }
472    unsafe { *bd.ranges.add(bd.nranges) = BracketRange { min, max }; }
473    bd.nranges += 1;
474    true
475}
476
477/// POSIX bracket-expression character classes (`[[:alpha:]]`).  keel is
478/// ASCII/C-locale only, which matches its current ctype tables.
479fn class_ranges(name: &[u8]) -> Option<&'static [(u8, u8)]> {
480    const ALNUM: &[(u8, u8)] = &[(b'0', b'9'), (b'A', b'Z'), (b'a', b'z')];
481    const ALPHA: &[(u8, u8)] = &[(b'A', b'Z'), (b'a', b'z')];
482    const BLANK: &[(u8, u8)] = &[(b'\t', b'\t'), (b' ', b' ')];
483    const CNTRL: &[(u8, u8)] = &[(0, 0x1f), (0x7f, 0x7f)];
484    const DIGIT: &[(u8, u8)] = &[(b'0', b'9')];
485    const GRAPH: &[(u8, u8)] = &[(0x21, 0x7e)];
486    const LOWER: &[(u8, u8)] = &[(b'a', b'z')];
487    const PRINT: &[(u8, u8)] = &[(0x20, 0x7e)];
488    const PUNCT: &[(u8, u8)] = &[
489        (0x21, 0x2f),
490        (0x3a, 0x40),
491        (0x5b, 0x60),
492        (0x7b, 0x7e),
493    ];
494    const SPACE: &[(u8, u8)] = &[(b'\t', b'\r'), (b' ', b' ')];
495    const UPPER: &[(u8, u8)] = &[(b'A', b'Z')];
496    const XDIGIT: &[(u8, u8)] = &[(b'0', b'9'), (b'A', b'F'), (b'a', b'f')];
497    match name {
498        b"alnum" => Some(ALNUM),
499        b"alpha" => Some(ALPHA),
500        b"blank" => Some(BLANK),
501        b"cntrl" => Some(CNTRL),
502        b"digit" => Some(DIGIT),
503        b"graph" => Some(GRAPH),
504        b"lower" => Some(LOWER),
505        b"print" => Some(PRINT),
506        b"punct" => Some(PUNCT),
507        b"space" => Some(SPACE),
508        b"upper" => Some(UPPER),
509        b"xdigit" => Some(XDIGIT),
510        _ => None,
511    }
512}
513
514fn add_class_ranges(ctx: &mut RegexCContext, bi: usize, ranges: &[(u8, u8)]) -> bool {
515    for &(lo, hi) in ranges {
516        if !add_range(ctx, bi, lo, hi) {
517            return false;
518        }
519        if ctx.icase {
520            let flo = case_fold_byte(lo);
521            let fhi = case_fold_byte(hi);
522            if flo != lo || fhi != hi {
523                let (rmin, rmax) = if flo < fhi { (flo, fhi) } else { (fhi, flo) };
524                if !add_range(ctx, bi, rmin, rmax) {
525                    return false;
526                }
527            }
528        }
529    }
530    true
531}
532
533fn compile_bracket(
534    ctx: &mut RegexCContext,
535    pat: *const c_char,
536    _plen: usize,
537    i: &mut usize,
538    end: usize,
539) -> bool {
540    let bi = unsafe { (*ctx.code).n_brackets };
541    unsafe {
542        let code = &mut *ctx.code;
543        if bi == code.brackets_cap {
544            let cap = if code.brackets_cap == 0 { 8 } else { code.brackets_cap * 2 };
545            let p = crate::realloc(
546                code.brackets as *mut c_void,
547                cap * core::mem::size_of::<BracketData>(),
548            ) as *mut BracketData;
549            if p.is_null() {
550                ctx.err = REG_ESPACE;
551                return false;
552            }
553            code.brackets = p;
554            code.brackets_cap = cap;
555        }
556        let bd = &mut *code.brackets.add(bi);
557        bd.negated = false;
558        bd.icase = ctx.icase;
559        bd.nranges = 0;
560        bd.ranges = core::ptr::null_mut();
561        bd.ranges_cap = 0;
562        code.n_brackets += 1;
563    }
564
565    let mut negated = false;
566    let mut j = *i + 1;
567    if j >= end { return false; }
568    let first = unsafe { *pat.add(j) as u8 };
569    if first == b'^' { negated = true; j += 1; }
570
571    while j < end {
572        let cb = unsafe { *pat.add(j) as u8 };
573        if cb == b']' && j > *i + 1 + (if negated { 1 } else { 0 }) { break; }
574        if cb >= 0x80 { return false; }
575        // POSIX character class: [:alpha:], [:digit:], ...
576        if cb == b'[' && j + 1 < end && unsafe { *pat.add(j + 1) as u8 } == b':' {
577            let name_start = j + 2;
578            let mut k = name_start;
579            while k + 1 < end
580                && !(unsafe { *pat.add(k) as u8 } == b':'
581                    && unsafe { *pat.add(k + 1) as u8 } == b']')
582            {
583                k += 1;
584            }
585            if k + 1 >= end {
586                return false;
587            }
588            let name =
589                unsafe { core::slice::from_raw_parts(pat.add(name_start) as *const u8, k - name_start) };
590            let ranges = match class_ranges(name) {
591                Some(v) => v,
592                None => return false,
593            };
594            if !add_class_ranges(ctx, bi, ranges) {
595                return false;
596            }
597            j = k + 2;
598            continue;
599        }
600        let lo = cb;
601        j += 1;
602
603        if j + 1 < end && unsafe { *pat.add(j) as u8 } == b'-' {
604            let dash_next = unsafe { *pat.add(j + 1) as u8 };
605            if dash_next == b']' {
606                if !add_range(ctx, bi, lo, lo) { return false; }
607                if ctx.icase && is_ascii_letter(lo) {
608                    let fc = case_fold_byte(lo);
609                    if !add_range(ctx, bi, fc, fc) { return false; }
610                }
611                continue;
612            }
613            if dash_next >= 0x80 { return false; }
614            let hi = dash_next;
615            if lo > hi { return false; }
616            j += 2;
617            if !add_range(ctx, bi, lo, hi) { return false; }
618            if ctx.icase {
619                let flo = case_fold_byte(lo);
620                let fhi = case_fold_byte(hi);
621                if flo != lo || fhi != hi {
622                    let (rmin, rmax) = if flo < fhi { (flo, fhi) } else { (fhi, flo) };
623                    if !add_range(ctx, bi, rmin, rmax) { return false; }
624                }
625            }
626        } else {
627            if !add_range(ctx, bi, lo, lo) { return false; }
628            if ctx.icase && is_ascii_letter(lo) {
629                let f = case_fold_byte(lo);
630                if !add_range(ctx, bi, f, f) { return false; }
631            }
632        }
633    }
634    if j >= end || unsafe { *pat.add(j) as u8 } != b']' { return false; }
635    *i = j + 1;
636
637    unsafe {
638        let bd = &mut *(*ctx.code).brackets.add(bi);
639        bd.negated = negated;
640        bd.icase = ctx.icase;
641    }
642
643    if !emit(ctx, OP_BRACKET) { return false; }
644    if !emit32(ctx, bi as u32) { return false; }
645    true
646}
647
648#[inline]
649unsafe fn read32(code: *const u8, at: usize) -> usize {
650    (*code.add(at) as usize)
651        | ((*code.add(at + 1) as usize) << 8)
652        | ((*code.add(at + 2) as usize) << 16)
653        | ((*code.add(at + 3) as usize) << 24)
654}
655
656const CAPTURE_NONE: usize = usize::MAX;
657
658impl CaptureState {
659    unsafe fn save(&mut self, slot: usize, value: usize) -> bool {
660        if slot >= self.nslots { return true; }
661        if self.nundo == self.undo_cap {
662            let cap = if self.undo_cap == 0 { 32 } else { self.undo_cap * 2 };
663            let p = crate::realloc(
664                self.undo as *mut c_void,
665                cap * core::mem::size_of::<CaptureUndo>(),
666            ) as *mut CaptureUndo;
667            if p.is_null() { return false; }
668            self.undo = p;
669            self.undo_cap = cap;
670        }
671        *self.undo.add(self.nundo) = CaptureUndo { slot, old: *self.slots.add(slot) };
672        self.nundo += 1;
673        *self.slots.add(slot) = value;
674        true
675    }
676
677    unsafe fn restore(&mut self, target: usize) {
678        while self.nundo > target {
679            self.nundo -= 1;
680            let u = *self.undo.add(self.nundo);
681            *self.slots.add(u.slot) = u.old;
682        }
683    }
684
685    unsafe fn reset(&mut self) {
686        self.nundo = 0;
687        for i in 0..self.nslots {
688            *self.slots.add(i) = CAPTURE_NONE;
689        }
690    }
691}
692
693impl Drop for CaptureState {
694    fn drop(&mut self) {
695        unsafe {
696            if !self.slots.is_null() {
697                crate::free(self.slots as *mut c_void);
698            }
699            if !self.undo.is_null() {
700                crate::free(self.undo as *mut c_void);
701            }
702        }
703    }
704}
705
706struct MatchStack {
707    frames: *mut MatchFrame,
708    cap: usize,
709}
710
711/// Per-bytecode "last input position" table used to break empty-match loops
712/// (`()*`, `(a*)*`, `^*`): re-entering the same split without consuming input
713/// cannot discover a new match.
714struct Visited {
715    p: *mut usize,
716}
717
718impl Drop for Visited {
719    fn drop(&mut self) {
720        unsafe {
721            if !self.p.is_null() {
722                crate::free(self.p as *mut c_void);
723            }
724        }
725    }
726}
727
728fn match_regex_impl(
729    code: &CompiledRegex,
730    input: *const c_char,
731    nmatch: usize,
732    pmatch: *mut crate::regmatch_t,
733    eflags: c_int,
734) -> c_int {
735    let initial = (code.ncode + 1).max(8);
736    let bytes = match initial.checked_mul(core::mem::size_of::<MatchFrame>()) {
737        Some(n) => n,
738        None => return REG_ESPACE,
739    };
740    let frames = unsafe { crate::malloc(bytes) } as *mut MatchFrame;
741    if frames.is_null() {
742        return REG_ESPACE;
743    }
744    let mut stack = MatchStack { frames, cap: initial };
745    let r = match_regex_inner(code, input, nmatch, pmatch, eflags, &mut stack);
746    unsafe { crate::free(stack.frames as *mut c_void) };
747    r
748}
749
750fn match_regex_inner(
751    code: &CompiledRegex,
752    input: *const c_char,
753    nmatch: usize,
754    pmatch: *mut crate::regmatch_t,
755    eflags: c_int,
756    stack: &mut MatchStack,
757) -> c_int {
758    let slen = unsafe { crate::strlen(input) };
759    let notbol = (eflags & REG_NOTBOL) != 0;
760    let noteol = (eflags & REG_NOTEOL) != 0;
761    let bytecode = code.code;
762    let ncode = code.ncode;
763
764    let vbytes = match ncode.checked_mul(core::mem::size_of::<usize>()) {
765        Some(n) => n,
766        None => return REG_ESPACE,
767    };
768    let vp = unsafe { crate::malloc(vbytes) } as *mut usize;
769    if vp.is_null() {
770        return REG_ESPACE;
771    }
772    let visited = Visited { p: vp };
773
774    let nslots = match code.nsub.checked_add(1).and_then(|n| n.checked_mul(2)) {
775        Some(n) => n,
776        None => return REG_ESPACE,
777    };
778    let slots = unsafe { crate::malloc(nslots * core::mem::size_of::<usize>()) } as *mut usize;
779    if slots.is_null() { return REG_ESPACE; }
780    let undo_cap = 32usize;
781    let undo = unsafe {
782        crate::malloc(undo_cap * core::mem::size_of::<CaptureUndo>())
783    } as *mut CaptureUndo;
784    if undo.is_null() {
785        unsafe { crate::free(slots as *mut c_void) };
786        return REG_ESPACE;
787    }
788    let mut caps = CaptureState { slots, nslots, undo, nundo: 0, undo_cap };
789
790    for start in 0..=slen {
791        let mut top: usize = 0;
792        unsafe { caps.reset() };
793        for i in 0..ncode {
794            unsafe { *visited.p.add(i) = CAPTURE_NONE };
795        }
796        unsafe {
797            *stack.frames.add(top) = MatchFrame {
798                pc: 0,
799                sp: start,
800                at_bol: start == 0,
801                undo: 0,
802            };
803        }
804        top += 1;
805        let mut found = false;
806        let mut match_end = 0usize;
807
808        while top > 0 {
809            top -= 1;
810            let frame = unsafe { *stack.frames.add(top) };
811            unsafe { caps.restore(frame.undo) };
812            let mut pc = frame.pc;
813            let mut sp = frame.sp;
814            let mut at_bol = frame.at_bol;
815
816            loop {
817                if pc >= ncode { break; }
818                let op = unsafe { *bytecode.add(pc) };
819                // Never read an opcode's operand past the bytecode buffer.
820                match op {
821                    OP_CHAR if pc + 2 > ncode => break,
822                    OP_BRACKET | OP_JUMP | OP_SPLIT | OP_SAVE if pc + 5 > ncode => break,
823                    _ => {}
824                }
825                match op {
826                    OP_CHAR => {
827                        if sp >= slen { break; }
828                        let expected = unsafe { *bytecode.add(pc + 1) };
829                        let actual = unsafe { *input.add(sp) as u8 };
830                        let m = if code.icase && is_ascii_letter(expected) && is_ascii_letter(actual) {
831                            case_fold_byte(expected) == case_fold_byte(actual)
832                        } else {
833                            expected == actual
834                        };
835                        if !m { break; }
836                        sp += 1;
837                        at_bol = false;
838                        pc += 2;
839                    }
840                    OP_BRACKET => {
841                        if sp >= slen { break; }
842                        let bi = unsafe { read32(bytecode, pc + 1) };
843                        let actual = unsafe { *input.add(sp) as u8 };
844                        if bi >= code.n_brackets { break; }
845                        if !bracket_contains(unsafe { &*code.brackets.add(bi) }, actual) { break; }
846                        sp += 1;
847                        at_bol = false;
848                        pc += 5;
849                    }
850                    OP_ANY => {
851                        if sp >= slen { break; }
852                        sp += 1;
853                        at_bol = false;
854                        pc += 1;
855                    }
856                    OP_MATCH => {
857                        if !noteol || sp == slen {
858                            found = true;
859                            match_end = sp;
860                        }
861                        break;
862                    }
863                    OP_JUMP => {
864                        pc = unsafe { read32(bytecode, pc + 1) };
865                    }
866                    OP_SPLIT => {
867                        let alt = unsafe { read32(bytecode, pc + 1) };
868                        let next = pc + 5;
869                        // Empty-iteration guard: the same split at the same
870                        // input position would repeat forever.
871                        if unsafe { *visited.p.add(pc) } == sp {
872                            break;
873                        }
874                        unsafe { *visited.p.add(pc) = sp };
875                        if top + 2 > stack.cap {
876                            let mut cap = stack.cap;
877                            while cap < top + 2 {
878                                cap = match cap.checked_mul(2) {
879                                    Some(n) => n,
880                                    None => return REG_ESPACE,
881                                };
882                            }
883                            let bytes = match cap.checked_mul(core::mem::size_of::<MatchFrame>()) {
884                                Some(n) => n,
885                                None => return REG_ESPACE,
886                            };
887                            let p = unsafe {
888                                crate::realloc(stack.frames as *mut c_void, bytes)
889                            } as *mut MatchFrame;
890                            if p.is_null() {
891                                return REG_ESPACE;
892                            }
893                            stack.frames = p;
894                            stack.cap = cap;
895                        }
896                        unsafe {
897                            *stack.frames.add(top) = MatchFrame {
898                                pc: alt,
899                                sp,
900                                at_bol,
901                                undo: caps.nundo,
902                            };
903                            top += 1;
904                            *stack.frames.add(top) = MatchFrame {
905                                pc: next,
906                                sp,
907                                at_bol,
908                                undo: caps.nundo,
909                            };
910                        }
911                        top += 1;
912                        break;
913                    }
914                    OP_SAVE => {
915                        let slot = unsafe { read32(bytecode, pc + 1) };
916                        if !unsafe { caps.save(slot, sp) } {
917                            return REG_ESPACE;
918                        }
919                        pc += 5;
920                    }
921                    OP_BOL => {
922                        if !at_bol && !(start == 0 && !notbol) { break; }
923                        pc += 1;
924                    }
925                    OP_EOL => {
926                        if sp != slen { break; }
927                        pc += 1;
928                    }
929                    _ => { break; }
930                }
931            }
932            if found { break; }
933        }
934
935        if found {
936            if !code.nosub && !pmatch.is_null() && nmatch > 0 {
937                let count = nmatch.min(code.nsub + 1);
938                unsafe {
939                    *caps.slots.add(0) = start;
940                    *caps.slots.add(1) = match_end;
941                    for i in 0..count {
942                        let so = *caps.slots.add(i * 2);
943                        let eo = *caps.slots.add(i * 2 + 1);
944                        let m = pmatch.add(i);
945                        if so == CAPTURE_NONE || eo == CAPTURE_NONE {
946                            (*m).rm_so = -1;
947                            (*m).rm_eo = -1;
948                        } else {
949                            (*m).rm_so = so as crate::regoff_t;
950                            (*m).rm_eo = eo as crate::regoff_t;
951                        }
952                    }
953                }
954            }
955            return REG_OK;
956        }
957    }
958    REG_NOMATCH
959}
960
961unsafe fn free_compiled(code: *mut CompiledRegex) {
962    if code.is_null() { return; }
963    let c = &*code;
964    if !c.brackets.is_null() {
965        let mut i = 0usize;
966        while i < c.n_brackets {
967            let bd = &*c.brackets.add(i);
968            if !bd.ranges.is_null() {
969                crate::free(bd.ranges as *mut c_void);
970            }
971            i += 1;
972        }
973        crate::free(c.brackets as *mut c_void);
974    }
975    if !c.code.is_null() {
976        crate::free(c.code as *mut c_void);
977    }
978    crate::free(code as *mut c_void);
979}
980
981#[no_mangle]
982pub unsafe extern "C" fn regcomp(preg: *mut crate::regex_t, pattern: *const c_char, cflags: c_int) -> c_int {
983    if preg.is_null() || pattern.is_null() { return REG_BADPAT; }
984    let code = crate::malloc(core::mem::size_of::<CompiledRegex>()) as *mut CompiledRegex;
985    if code.is_null() { return REG_ESPACE; }
986    crate::memset(code as *mut c_void, 0, core::mem::size_of::<CompiledRegex>());
987    let rc = compile_regex_into(pattern, cflags, code);
988    if rc != REG_OK {
989        free_compiled(code);
990        return rc;
991    }
992    crate::memset(preg as *mut c_void, 0, core::mem::size_of::<crate::regex_t>());
993    (*preg).re_nsub = (*code).nsub;
994    (*preg).__nsub2 = (*code).nsub;
995    (*preg).__opaque = code as *mut c_void;
996    REG_OK
997}
998
999fn compile_regex_into(pat: *const c_char, flags: c_int, code: *mut CompiledRegex) -> c_int {
1000    unsafe {
1001        let plen = crate::strlen(pat);
1002        if plen == 0 { return REG_BADPAT; }
1003
1004        crate::memset(code as *mut c_void, 0, core::mem::size_of::<CompiledRegex>());
1005        (*code).icase = (flags & REG_ICASE) != 0;
1006        (*code).extended = (flags & REG_EXTENDED) != 0;
1007        (*code).nosub = (flags & REG_NOSUB) != 0;
1008
1009        let mut ctx = RegexCContext {
1010            code,
1011            pos: 0,
1012            last_atom_start: 0,
1013            depth: 0,
1014            groups: 0,
1015            err: REG_OK,
1016            extended: (*code).extended,
1017            icase: (*code).icase,
1018        };
1019
1020        if !compile_expr(&mut ctx, pat, plen, 0, plen, false) {
1021            return if ctx.err != 0 { ctx.err } else { REG_BADPAT };
1022        }
1023
1024        if !emit(&mut ctx, OP_MATCH) {
1025            return ctx.err;
1026        }
1027
1028        (*code).ncode = ctx.pos;
1029        (*code).nsub = ctx.groups;
1030        REG_OK
1031    }
1032}
1033
1034#[no_mangle]
1035pub unsafe extern "C" fn regexec(
1036    preg: *const crate::regex_t,
1037    string: *const c_char,
1038    nmatch: usize,
1039    pmatch: *mut crate::regmatch_t,
1040    eflags: c_int,
1041) -> c_int {
1042    if preg.is_null() || string.is_null() { return REG_BADPAT; }
1043    let code = (*preg).__opaque as *const CompiledRegex;
1044    if code.is_null() { return REG_BADPAT; }
1045    match_regex_impl(&*code, string, nmatch, pmatch, eflags)
1046}
1047
1048const ERR_MSG: &[u8] = b"unknown error\0";
1049const PAT_MSG: &[u8] = b"invalid pattern\0";
1050const OK_MSG: &[u8] = b"no error\0";
1051
1052#[no_mangle]
1053pub unsafe extern "C" fn regerror(
1054    errcode: c_int,
1055    _preg: *const crate::regex_t,
1056    errbuf: *mut c_char,
1057    errbuf_size: usize,
1058) -> usize {
1059    let msg = match errcode {
1060        0 => OK_MSG,
1061        2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 => PAT_MSG,
1062        12 => b"out of memory\0" as &[u8],
1063        _ => ERR_MSG,
1064    };
1065    let len = crate::strlen(msg.as_ptr() as *const c_char);
1066    if !errbuf.is_null() && errbuf_size > 0 {
1067        let copy = if len < errbuf_size { len } else { errbuf_size - 1 };
1068        crate::memcpy(errbuf as *mut c_void, msg.as_ptr() as *const c_void, copy);
1069        *errbuf.add(copy) = 0;
1070    }
1071    len + 1
1072}
1073
1074#[no_mangle]
1075pub unsafe extern "C" fn regfree(preg: *mut crate::regex_t) {
1076    if preg.is_null() { return; }
1077    let code = (*preg).__opaque as *mut CompiledRegex;
1078    if !code.is_null() {
1079        free_compiled(code);
1080        (*preg).__opaque = core::ptr::null_mut();
1081    }
1082}