Metadata-Version: 2.4
Name: emx-regex-cgen
Version: 0.3.0
Summary: Regex to C code generator
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-xdist; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Dynamic: license-file

**emmtrix Regex-to-C Code Generator (emx-regex-cgen)** compiles regular expressions into portable,
static C code for embedded and performance-critical applications.

[![CI](https://github.com/emmtrix/emx-regex-cgen/actions/workflows/ci.yml/badge.svg)](https://github.com/emmtrix/emx-regex-cgen/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

## Key Characteristics

- **Two backend engines** — choose between a table-driven **DFA** and a
  bit-parallel **NFA** (`--engine dfa`, `--engine bitnfa`, or the default
  `--engine auto` which tries DFA first and falls back to bitnfa when the
  DFA state limit is exceeded).
- **Table-driven DFA** — every regex is compiled to a minimised
  deterministic finite automaton; the generated C code performs a single
  linear scan over the input.
- **Bit-parallel NFA** — the regex is compiled to a position NFA (a
  Thompson NFA without ε-states) and simulated with precomputed bitmasks; the hot loop is fully unrolled
  with no loops over words. The variant (`uint8`, `uint16`, `uint32`,
  or `uint32_t[N]`) is selected automatically based on the number of
  NFA positions.
- **Code-point classes** — in UTF-8 mode the DFA can read whole code
  points instead of bytes (`unit`, default `"auto"`: whenever its tables
  are smaller).  Code points that the pattern does not tell apart share a
  class, so `\p{L}` is one column instead of hundreds of UTF-8 byte
  states: the GPT-2 pre-tokenizer DFA shrinks from 277 KB to 6.5 KB, its
  scan DFA from 382 KB to 6.7 KB.
- **No dynamic memory allocation** — all data is `static const`; no
  `malloc`, no `free`.
- **Simple inner loop** — the matching loop performs a single table
  lookup per byte (DFA, branch-free unless `early_exit` is set), per code
  point (DFA over code-point classes, plus the UTF-8 decoding and the
  class lookup) or one bit test per NFA position (bitnfa).
- **re2 feature set** — supports the same subset of regular expressions
  as Google's [re2](https://github.com/google/re2) library (no
  back-references, no look-behind), plus look-ahead.  With
  `syntax="oniguruma"` patterns are read as Hugging Face tokenizers'
  Oniguruma reads them (see [Oniguruma syntax](#oniguruma-syntax)).
- **Fullmatch semantics** — the generated function checks whether the
  *entire* input matches the pattern.
- **Scan mode** — with `scan=True` / `--scan` the DFA instead finds
  matches in a text as a backtracking engine (Oniguruma, PCRE, Python
  `re`) does: the first alternative that matches, not the longest.  This
  is how Hugging Face tokenizers split text with their pre-tokenizer
  regexes.

## Installation

```bash
pip install emx-regex-cgen
```

The distribution name is `emx-regex-cgen`. The Python import path is
`emx_regex_cgen`.

After installation, you can use the package either as a CLI tool via
`emx-regex-cgen` or as a Python library via
`from emx_regex_cgen import generate`.

## Quick Start

### Python Library

`generate()` returns a `GeneratedCode` object with four parts.
Call `.render()` to get the combined C source string, or access individual
fields to embed them in an existing code-generation pipeline.

```python
from emx_regex_cgen import generate

# generate() returns a GeneratedCode object
result = generate(r"\d{4}-\d{2}-\d{2}")

# .render() assembles the complete C source (same output as before)
print(result.render())

# Access individual parts:
result.includes        # ['stddef.h', 'stdbool.h', 'stdint.h']
result.globals         # static const transition table (and optional maps)
result.match_function  # bool regex_match(const char *input, size_t len) { … }
result.main_function   # int main(…) { … }  — None when emit_main=False

# Include a main() for standalone testing
result = generate(r"[a-z]+", emit_main=True)

# Bytes mode: '.' matches any single byte, classes work on raw byte values
result = generate(r"[\x80-\xff]+", encoding="bytes")

# Use the bit-parallel NFA backend instead of DFA
result = generate(r"hello", engine="bitnfa")

# Scan mode: bool regex_find(input, len, from, &start, &end)
result = generate(r"\s+(?!\S)|\s+", scan=True, syntax="oniguruma")
```

Invalid or unsupported patterns raise `emx_regex_cgen.PatternError`, a
subclass of `re.error`; invalid option values raise `ValueError`.

```python
from emx_regex_cgen import PatternError, generate

try:
    generate(r"(?<=a)b")
except PatternError as exc:
    print(exc)  # look-behind is not supported at position 0
```

#### `generate()` options

```python
generate(
    pattern,
    flags="",
    *,
    emit_main=False,
    prefix="regex",
    encoding="utf8",
    engine="auto",
    row_dedup="auto",
    comb_compression="auto",
    alphabet_compression="auto",
    size_threshold=8192,
    early_exit=False,
    unicode_classes=False,
    max_dfa_states=10000,
    scan=False,
    syntax="re2",
    unit="auto",
)
```

Library arguments map directly to the generator settings:

| Argument | Type | Default | Meaning |
|----------|------|---------|---------|
| `pattern` | `str` | - | Regular expression to compile. |
| `flags` | `str` | `""` | Regex flags: `i` (ignore case), `s` (dot-all), `m` (multiline). `x` is accepted and ignored; inline `(?x)` enables free-spacing syntax. |
| `emit_main` | `bool` | `False` | Include a standalone `main()` function in the generated C code. |
| `prefix` | `str` | `"regex"` | Prefix for generated C identifiers such as `regex_match`; must be a C identifier (`ValueError` otherwise). |
| `encoding` | `str` | `"utf8"` | `"utf8"` for Unicode-aware UTF-8 input, or `"bytes"` for raw byte semantics (as re2's Latin-1 mode: the `i` flag folds ASCII letters only). |
| `engine` | `str` | `"auto"` | Backend engine: `"auto"` (DFA first, bitnfa fallback), `"dfa"`, or `"bitnfa"`. |
| `unit` | `str` | `"auto"` | DFA only: what a transition reads, `"byte"` or `"codepoint"` (see [Code-point unit](#code-point-unit)); `"auto"` takes `"codepoint"` when its tables are smaller and the pattern allows it (with `scan=True` only when the byte table has more than `size_threshold` cells), unless `alphabet_compression="yes"` asks for the byte unit.  `"codepoint"` raises `ValueError` with `encoding="bytes"`, `engine="bitnfa"` or a pattern that matches ill-formed UTF-8 (`\C`); with it `"auto"` does not fall back to bitnfa. |
| `row_dedup` | `str` | `"auto"` | DFA only: `"yes"`, `"no"`, or `"auto"` (above `size_threshold`, when it saves at least 25 % of the table bytes: it costs ~70 % speed) for transition-row deduplication. |
| `comb_compression` | `str` | `"auto"` | DFA only: `"yes"`, `"no"`, or `"auto"` (above `size_threshold`, when it saves at least 25 % of the table bytes; in place of row deduplication) for comb compression of the transition rows (see [Comb compression](#comb-compression)); `"yes"` with `row_dedup="yes"` raises `ValueError`. |
| `alphabet_compression` | `str` | `"auto"` | DFA, byte unit only: `"yes"`, `"no"`, or `"auto"` (when it makes the tables smaller) for byte equivalence-class compression; `"yes"` also makes `unit="auto"` take the byte unit. |
| `size_threshold` | `int` | `8192` | DFA only: threshold (cells = states × columns) used by `"auto"` for `row_dedup`, `comb_compression` and, with `scan=True`, for `unit`. |
| `early_exit` | `bool` | `False` | DFA only: break out of the loop once the dead state is reached. |
| `unicode_classes` | `bool` | `False` | `\d` = Unicode Nd and `\s` = Unicode White_Space (also negated and inside classes), as in Hugging Face tokenizers; `\w`, `\b` and POSIX classes then raise `PatternError`. Requires `encoding="utf8"`. |
| `max_dfa_states` | `int` | `10000` | Limit for the subset construction; beyond it `"auto"` falls back to bitnfa and `"dfa"` raises `DFAStateLimitExceeded`. |
| `scan` | `bool` | `False` | Generate the search function `<prefix>_find` instead of `<prefix>_match` (see [Scan mode](#scan-mode)). DFA only: `"auto"` does not fall back to bitnfa, `"bitnfa"` raises `ValueError`; it always stops early, so `early_exit=True` raises `ValueError`. |
| `syntax` | `str` | `"re2"` | Pattern syntax: `"re2"` or `"oniguruma"` (Hugging Face tokenizers, see [Oniguruma syntax](#oniguruma-syntax)). `"oniguruma"` implies `unicode_classes=True`; flag `m` and `encoding="bytes"` raise `ValueError`. |

Example with multiple options:

```python
from emx_regex_cgen import generate

result = generate(
    r"[a-z]+\d+",
    flags="i",
    prefix="user_id",
    emit_main=True,
    engine="dfa",
    encoding="utf8",
    row_dedup="yes",
    alphabet_compression="auto",
    size_threshold=4096,
    early_exit=True,
)

print(result.render())
```

### CLI

```bash
# Write generated C code to stdout
emx-regex-cgen '[a-z]+\d+'

# Write to a file with a main() function
emx-regex-cgen '[a-z]+\d+' --emit-main -o matcher.c

# Compile and test
gcc -O2 -o matcher matcher.c
./matcher "hello42"   # exit 0 (match)
./matcher "HELLO"     # exit 1 (no match)

# Bytes mode: match any sequence of high bytes
emx-regex-cgen --encoding bytes '[\x80-\xff]+' --emit-main -o byte_matcher.c

# Use the bit-parallel NFA backend
emx-regex-cgen --engine bitnfa 'hello' --emit-main -o bitnfa_matcher.c

# Hugging Face tokenizer regex: \s is Unicode White_Space (e.g. U+00A0, U+3000)
emx-regex-cgen --unicode-classes ' ?[^\s\p{L}\p{N}]+' -o punct.c

# ... read exactly as tokenizers' Oniguruma reads it (^/$ match at lines)
emx-regex-cgen --syntax oniguruma --scan '^\s+|\p{L}+' -o pretok.c

# Scan mode: print every match as "start end" (byte offsets)
emx-regex-cgen --scan 'a|ab' --emit-main -o scanner.c
gcc -O2 -o scanner scanner.c
./scanner "abab"      # 0 1 / 2 3: the first alternative wins
```

## CLI Reference

```
usage: emx-regex-cgen [-h] [-o OUTPUT] [--emit-main] [--scan]
                      [--prefix PREFIX] [--syntax {re2,oniguruma}]
                      [--flags FLAGS] [--encoding {utf8,bytes}]
                      [--unicode-classes] [--max-dfa-states MAX_DFA_STATES]
                      [--unit {auto,byte,codepoint}]
                      [--row-dedup {auto,yes,no}]
                      [--comb-compression {auto,yes,no}]
                      [--alphabet-compression {auto,yes,no}]
                      [--size-threshold SIZE_THRESHOLD]
                      [--early-exit {yes,no}] [--engine {auto,dfa,bitnfa}]
                      pattern

Generate C code that performs a fullmatch (or, with --scan, a search) for a
regular expression.

positional arguments:
  pattern               Regular expression pattern

options:
  -h, --help            show this help message and exit
  -o, --output OUTPUT   Output file (default: stdout)
  --emit-main           Also emit a main() function (exit 0=match, 1=no match,
                        2=error; with --scan: print each match as 'start end')
  --scan                Generate <prefix>_find(), a search for the leftmost
                        match that a backtracking engine (e.g. Hugging Face
                        tokenizers) reports; DFA only
  --prefix PREFIX       Prefix for all generated C identifiers: arrays and
                        match function; must be a C identifier (default:
                        regex)
  --syntax {re2,oniguruma}
                        Pattern syntax: re2 (default) or oniguruma (Hugging
                        Face tokenizers: ^/$ match at lines, (?m) is dot-all,
                        \h is a hex digit, ...; implies --unicode-classes)
  --flags FLAGS         Regex flags: i (case-insensitive), s (dot-all), m
                        (multiline); x is accepted and ignored (use inline
                        (?x) for free-spacing)
  --encoding {utf8,bytes}
                        Input encoding: utf8 (default, Unicode-aware) or bytes
                        (raw byte semantics)
  --unicode-classes     Unicode \d (Nd) and \s (White_Space), as in Hugging
                        Face tokenizers; rejects \w, \b and POSIX classes
                        (utf8 only)
  --max-dfa-states MAX_DFA_STATES
                        DFA state limit; beyond it engine auto falls back to
                        bitnfa and engine dfa fails (default: 10000)
  --unit {auto,byte,codepoint}
                        What a DFA transition reads: byte, codepoint (decodes
                        UTF-8 and looks up the code point's class; rejects
                        ill-formed UTF-8), or auto (codepoint when its tables
                        are smaller, with --scan when the byte table also
                        exceeds --size-threshold, and --alphabet-compression
                        is not yes; default)
  --row-dedup {auto,yes,no}
                        Transition-row deduplication: yes (always), no
                        (never), auto (when the table exceeds --size-threshold
                        and it saves at least 25 % of the table bytes;
                        default)
  --comb-compression {auto,yes,no}
                        Comb compression of the transition rows (each row
                        keeps only the entries that differ from its most
                        frequent successor, the rows overlaid in one array):
                        yes (always; not with --row-dedup yes), no (never),
                        auto (when the table exceeds --size-threshold and it
                        saves at least 25 % of the table bytes; default)
  --alphabet-compression {auto,yes,no}
                        Alphabet compression of the byte unit into equivalence
                        classes: yes (unless it needs 256 columns), no
                        (never), auto (when it makes the tables smaller;
                        default)
  --size-threshold SIZE_THRESHOLD
                        Table-size threshold (cells = states × columns) for
                        --row-dedup auto, --comb-compression auto and, with
                        --scan, --unit auto (default: 8192)
  --early-exit {yes,no}
                        Emit early-exit check inside the DFA loop: yes (break
                        when dead state is reached), no (always process full
                        input; default)
  --engine {auto,dfa,bitnfa}
                        Backend engine: auto (try DFA first, fall back to
                        bitnfa; default), dfa (table-driven minimised DFA),
                        bitnfa (bit-parallel NFA)
```

## Supported Features

### Regex Features

| Feature | Example pattern | DFA | bitnfa |
|---------|-----------------|-----|--------|
| Literal string | `hello` | [literal.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/literal.c) | [literal\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/literal_bitnfa.c) |
| Character class | `[a-z0-9_]+` | [char\_class.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/char_class.c) | [char\_class\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/char_class_bitnfa.c) |
| Negated class | `[^aeiou]+` | [negated\_class.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/negated_class.c) | [negated\_class\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/negated_class_bitnfa.c) |
| Dot (any char except `\n`) | `.+` | [dot.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/dot.c) | [dot\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/dot_bitnfa.c) |
| Alternation | `cat\|dog\|fish` | [alternation.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/alternation.c) | [alternation\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/alternation_bitnfa.c) |
| Star quantifier `*` | `ab*c` | [quantifier\_star.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/quantifier_star.c) | [quantifier\_star\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/quantifier_star_bitnfa.c) |
| Plus quantifier `+` | `ab+c` | [quantifier\_plus.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/quantifier_plus.c) | [quantifier\_plus\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/quantifier_plus_bitnfa.c) |
| Optional quantifier `?` | `colou?r` | [quantifier\_optional.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/quantifier_optional.c) | [quantifier\_optional\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/quantifier_optional_bitnfa.c) |
| Bounded repeat `{m,n}` | `a{2,4}` | [quantifier\_repeat.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/quantifier_repeat.c) | [quantifier\_repeat\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/quantifier_repeat_bitnfa.c) |
| Digit escape `\d` | `\d{4}-\d{2}-\d{2}` | [escape\_digit.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/escape_digit.c) | [escape\_digit\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/escape_digit_bitnfa.c) |
| Word escape `\w` | `\w+` | [escape\_word.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/escape_word.c) | [escape\_word\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/escape_word_bitnfa.c) |
| Space escape `\s` | `\s+` | [escape\_space.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/escape_space.c) | [escape\_space\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/escape_space_bitnfa.c) |
| Unicode / UTF-8 | `\x{00e9}+` | [unicode.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/unicode.c) | [unicode\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/unicode_bitnfa.c) |
| Anchors `^` / `$` | `^start.*end$` | [anchors.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/anchors.c) | [anchors\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/anchors_bitnfa.c) |
| Word boundary `\b` / `\B` | `\bword\b` | [word\_boundary.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/word_boundary.c) | [word\_boundary\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/word_boundary_bitnfa.c) |
| Unicode property `\p{…}` / `\P{…}` | `\p{Nd}+` | [unicode\_property.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/unicode_property.c) | [unicode\_property\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/unicode_property_bitnfa.c) |
| Look-ahead `(?=…)` / `(?!…)` | `[a-z]+(?!ing)\w*` | [lookahead.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/lookahead.c) | [lookahead\_bitnfa.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/lookahead_bitnfa.c) |

### Syntax and Semantics

The accepted syntax and the match semantics follow re2:

- **Groups** — `(…)`, `(?:…)`, `(?P<name>…)` and `(?<name>…)` all group
  (a name is letters, digits and `_`, as in re2);
  captures do not exist in a fullmatch automaton.  Lazy quantifiers
  (`*?`, `+?`, …) and the `U` flag (`(?U)`: `*` is lazy, `*?` greedy)
  are accepted; for a fullmatch they match the same language as their
  greedy forms, in scan mode they prefer the shorter match.
- **Inline flags** — `(?i)`, `(?s)`, `(?m)`, `(?x)` and `(?i:…)` /
  `(?-i:…)`.  A bare `(?flags)` applies until the end of the enclosing
  group, including later alternatives.  Under `(?x)` blanks and `#`
  comments are ignored, also before a quantifier (`(?x)a *` is `a*`).
- **Anchors** — `^` / `\A` match at the start of the input, `$` / `\z`
  only at its end (no "before a final `\n`" as in Python or PCRE).  With
  `m`, `^` and `$` also match after / before every `\n`.  `\b` / `\B`
  are ASCII word boundaries.  Since the generated function performs a
  fullmatch, anchors matter where they sit inside the pattern, e.g.
  `a(?m:$)\nb`.
- **Character classes** — ranges, escapes, `\p{…}` / `\P{…}` and POSIX
  classes `[[:alpha:]]` / `[[:^alpha:]]` (ASCII, inside a bracket
  expression only).  `\d`, `\s` and `\w` are ASCII as in re2; with
  `unicode_classes` `\d` and `\s` follow Unicode as in Hugging Face
  tokenizers (Oniguruma), while `\w`, `\b` and POSIX classes are
  rejected because engines disagree on their Unicode meaning.
- **Unicode version** — `\p{…}`, Unicode `\d` and `(?i)` use Unicode
  15.1, as re2 does, whatever the Python that runs the generator has.
- **Look-ahead** — `(?=R)` and `(?!R)` are supported (re2 rejects them),
  as used by Hugging Face tokenizers (`\s+(?!\S)`).  The look-ahead only
  sees the input: at its end a pending `(?!R)` holds and a pending `(?=R)`
  fails, as in Python and PCRE.  *R* may not contain anchors or further
  look-arounds.
- **Errors as in re2** — back-references, look-behind,
  unknown escapes (`\h`, `\R`, `\Z`, …: only ASCII punctuation may be
  escaped to stand for itself), reversed ranges (`[z-a]`), `{m,n}` with
  m > n and a counted repeat of a repeat (`a*{2}`) raise `PatternError`.
- **Repeat counts** — unlike re2, counts above 1000 are accepted; the
  automaton size limits apply instead.

### Oniguruma syntax

`syntax="oniguruma"` (`--syntax oniguruma`) reads a pattern the way
Hugging Face tokenizers do: their `Regex` is Oniguruma with Ruby syntax.
It differs from re2 in:

- **Anchors** — `^` and `$` always match at lines: `^` at the start and
  after a `\n` that does not end the input, `$` before every `\n` and at
  the end.  `\Z` matches at the end or before a final `\n`.
- **Flags** — inline flags are `i`, `m` and `x`, where `(?m)` is dot-all;
  `(?s)` and `(?U)` are errors.  Of the `flags` argument, `i`, `s`
  (dot-all) and `x` keep their meaning and `m` raises `ValueError`.
- **Quantifiers** — `x{n}?` is an optional `x{n}` (not a lazy `{n}`),
  `x{n}+` repeats `x{n}`, `{,n}` is `{0,n}` and a quantifier may follow
  another (`a**`, `a{2}{3}`).  Possessive `*+`, `++` and `?+` never
  give back what they matched (`a*+a` matches nothing); they are
  supported on one character or class (`[^\s\p{L}]++`, also in a
  group: `(\s)++`), as a greedy repeat followed by a negative look-ahead
  (`x*+` is `x*(?!x)`, `x?+` is `(?:x|(?!x))`), so not inside a
  look-ahead; on a longer group (`(?:ab)*+`) they raise `PatternError`.
- **Escapes** — `\h` / `\H` are (non-)hex digits, `\N` is any character
  but `\n` and `\O` any character.  Further character escapes are `\e`,
  `\cX`, `\C-X`, `\o{…}`, `\xN` with one digit and `\uHHHH` (exactly
  four digits).  `\xHH` and octal escapes above 0x7F are bytes of the
  UTF-8 pattern: `\xc3\xa9` is `é` (use `\x{…}` for a code point).
  A byte from 0xF5 or a byte sequence that is no character (overlong, a
  surrogate) never matches; a continuation byte does not either in a
  class (`[a\x80]` is `a`) and is rejected outside one.  A range of
  bytes ends at 0x7F (`[\x00-\xff]` is ASCII).
  Anchors and look-aheads cannot be repeated (`^*`).  `\p{…}` property
  names ignore case, spaces, `_` and `-` (`\p{lowercase letter}`); the
  short form `\pL` is rejected.
- **Groups** — `(?<name>…)`, `(?'name'…)` and comments `(?#…)` (`\)`
  does not end one);
  `(?P<name>…)` is an error.
- **Unicode version** — `\p{…}`, `\d` and `(?i)` use Unicode 16.0, as
  the Oniguruma of tokenizers 0.23 does (`\p{Garay}`, `(?i)\x{1c89}`
  matches U+1C8A).  `\p{LC}` is `Lu`, `Ll` and `Lt`.
- **Classes** — `\d`, `\s` follow Unicode (as with `unicode_classes`),
  and so does `\w`: letters (Alphabetic), marks, `Nd` and `Pc`; a bare
  `\w` (not in a bracket class) also matches `²³¹¼½¾`, which Oniguruma's
  Latin-1 table counts as word characters.
  A nested class is a union (`[a[xy]]`), `&&` an intersection
  (`[a-z&&[^aeiou]]`, an empty operand is the empty set), and a leading
  `^` negates the whole class; `(?i)` folds the whole class once, after
  its nested classes (`(?i)[a[^x]]` matches `X`).
  `\b` and POSIX classes are rejected, as are escapes Oniguruma reads
  as a plain letter (`\y`, `\Q`, `\R`, `\K`, …: these mean something
  else in other engines).
- **Case folding** — `(?i)` also uses multi-character folds: `ß`
  matches `ss`, `SS` and `ẞ`, and `ss` matches `ß`.  A run of literals
  is cut into folds from the left and not regrouped, so `(?i)sss`
  matches `ßs` but not `sß`; a run ends at a capture group, a quantifier,
  an alternation or a flag change (`(?i)(s)s` does not match `ß`).  A
  bracket class matches the folds of its members (`(?i)[ß]` matches `ss`)
  and the code points that share one (`(?i)[ﬅ]` matches `ﬆ`), and
  complements a negated item before it folds it; a bare `\p{…}` is not
  folded (`(?i)\p{Lu}` does not match `a`).  A class with many such
  members (`(?i)[\p{L}]`) exceeds the `bitnfa` position limit; the DFA
  engine is not affected.

### Scan mode

`generate(..., scan=True)` (`--scan`) emits

```c
bool regex_find(const char *input, size_t len, size_t from,
                size_t *start, size_t *end);
```

It returns the leftmost match that starts at or after `from` and, of the
matches starting there, the one a backtracking engine (Oniguruma, PCRE,
Python `re`) reports: alternatives are tried in order, greedy repeats
take as much and lazy repeats as little as the rest of the pattern
allows, and a repeat whose iteration matched the empty string stops.
The DFA follows RE2's leftmost-first construction; a match whose
look-ahead is still undecided is confirmed later, so `\s+(?!\S)`
works.  `<prefix>_find` tries each start position in turn (in UTF-8 mode
only character boundaries, so the input must be valid UTF-8: a stray
continuation byte never starts a match), so a search costs O(n²) in the
worst case, typically far less because the DFA stops as soon as the
match is decided.

- **Anchors and look-ahead see the whole input**, not just the text
  after `from`: `^` matches at position 0 (and after a `\n` with `m` or
  in Oniguruma syntax),
  `\b` looks at the byte before `from`.
- **Successive matches** — call `<prefix>_find` again with `from` = the
  previous end.  When it returns an empty match right at the previous
  end, skip that match and search again from `from` + 1, as Oniguruma,
  PCRE and Python do; the `main()` of `emit_main` does this and prints
  every match as `start end` (byte offsets).
- **Hugging Face tokenizers** — compile `tokenizer.json` regexes with
  `syntax="oniguruma"` (and no flags).  The pieces of `Split(…, behavior="isolated")`
  are the matches and the text between them; they are checked against
  the `tokenizers` library for the pre-tokenizer regexes of
  `tests/data/tokenizer_compat_results.json`.
- **Limits** — a look-ahead must be decided within 254 bytes after the
  end of a match (`a(?=b*c)` is rejected with `ValueError`).  A counted
  repeat `{m,n}` whose body can match the empty string may stop
  differently from Oniguruma, whose empty-iteration check depends on how
  it expands the repeat (e.g. `(?:^.?){3}`); the result is that of the
  Python `regex` module.

### CLI Options

| Option | Effect | Golden reference |
|--------|--------|------------------|
| `--flags i` | Case-insensitive matching | [flag\_ignorecase.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/flag_ignorecase.c) · [bitnfa](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/flag_ignorecase_bitnfa.c) |
| `--flags s` | Dot matches `\n` (dot-all) | [flag\_dotall.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/flag_dotall.c) · [bitnfa](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/flag_dotall_bitnfa.c) |
| `--flags m` | Multiline anchors | [flag\_multiline.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/flag_multiline.c) · [bitnfa](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/flag_multiline_bitnfa.c) |
| `--flags x` | Accepted and ignored; free-spacing needs inline `(?x)` (as in the golden) | [flag\_verbose.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/flag_verbose.c) · [bitnfa](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/flag_verbose_bitnfa.c) |
| `--encoding bytes` | Raw byte semantics (no UTF-8) | [encoding\_bytes.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/encoding_bytes.c) · [bitnfa](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/encoding_bytes_bitnfa.c) |
| `--prefix NAME` | Custom identifier prefix | [prefix.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/prefix.c) · [bitnfa](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/prefix_bitnfa.c) |
| `--emit-main` | Include standalone `main()` | [emit\_main.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/emit_main.c) · [bitnfa](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/emit_main_bitnfa.c) |
| `--unit byte` | DFA reads bytes (the default `auto` reads code points where that is smaller, as in [unicode.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/unicode.c)) | [unit\_byte.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/unit_byte.c) |
| `--alphabet-compression yes` | Byte equivalence-class compression (byte unit) | [alphabet\_compression.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/alphabet_compression.c) |
| `--row-dedup yes` | Transition-row deduplication | [row\_dedup.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/row_dedup.c) |
| `--comb-compression yes` | Comb compression of the transition rows | [comb\_compression.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/comb_compression.c) |
| `--early-exit yes` | Break DFA loop on dead state (early exit) | [early\_exit.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/early_exit.c) |
| `--unicode-classes` | Unicode `\d` (Nd) and `\s` (White_Space) | [unicode\_classes.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/unicode_classes.c) · [bitnfa](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/unicode_classes_bitnfa.c) |
| `--max-dfa-states N` | DFA state limit (default 10000); `auto` falls back to bitnfa beyond it | [max\_dfa\_states.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/max_dfa_states.c) |
| `--scan` | Leftmost-first search `regex_find` instead of a fullmatch (with `--emit-main`) | [scan.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/scan.c) · [codepoint](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/scan_unit_codepoint.c) |
| `--syntax oniguruma` | Read the pattern as Hugging Face tokenizers' Oniguruma does | [syntax\_oniguruma.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/syntax_oniguruma.c) |

### Bit-NFA Variants

The `bitnfa` engine automatically selects the narrowest integer type
that can hold all NFA positions:

| Variant | NFA positions | Golden reference |
|---------|---------------|------------------|
| `uint8_t` | ≤ 8 | [bitnfa\_uint8.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/bitnfa_uint8.c) |
| `uint16_t` | ≤ 16 | [bitnfa\_uint16.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/bitnfa_uint16.c) |
| `uint32_t` | ≤ 32 | [bitnfa\_uint32.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/bitnfa_uint32.c) |
| `uint32_t[N]` | > 32 | [bitnfa\_uint32\_array.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/bitnfa_uint32_array.c) |

## Generated Code Structure

### DFA Engine (default)

With the byte unit (`unit="byte"`, or `"auto"` when it is smaller) the
generator produces:

1. An optional **alphabet map** (`static const uint8_t regex_alphabet[256]`)
   mapping each byte to its equivalence class (emitted when alphabet
   compression is active).
2. A **transition table** (`static const uint8_t regex_transitions[M][C]`)
   mapping `(row, column) → next_state`.  Dimensions depend on active
   optimisations: *M* is the number of unique rows (with row dedup) or
   states; *C* is the number of equivalence classes rounded up to a power
   of two (with alphabet compression) or 256.  The power of two keeps the
   row address a shift: a multiply would make every byte ~16 % slower.
   With more than 128 classes the table stays at 256 columns.
3. An optional **row map** (`static const uint8_t regex_row_map[N]`)
   mapping `state → row index` (emitted when row deduplication is active).
   With comb compression the transition table and row map are replaced
   by the comb arrays (see [Comb compression](#comb-compression)).
4. A **match function** with the signature:
   ```c
   bool regex_match(const char *input, size_t len);
   ```
5. Optionally a **`main()` function** for standalone executables.

#### Example Output (pattern `hello`, `--alphabet-compression yes --row-dedup yes`)

```c
static const uint8_t regex_alphabet[256] = { /* byte → class */ };

static const uint8_t regex_transitions[6][8] = {
    /* states 0, 6 */ { 0 },
    /* state 1 */ { [2] = 2 },
    ...
};

static const uint8_t regex_row_map[7] = { 0, 1, 2, 3, 4, 5, 0 };

bool regex_match(const char *input, size_t len) {
    uint8_t state = 1;
    for (size_t i = 0; i < len; i++) {
        state = regex_transitions[regex_row_map[state]][regex_alphabet[(unsigned char)input[i]]];
    }
    return state >= 6;
}
```

#### Comb compression

Most transition rows lead almost everywhere to one state (the dead state,
or the state a `.*` loops in).  Comb compression keeps of each row only
the entries that differ from its **default** (its most frequent
successor) and overlays the rows in one array, each row shifted so that
its entries hit no other row's entries (first fit, the fullest rows
first):

```c
static const uint8_t regex_comb_base[N];     /* row s starts at comb_base[s] */
static const uint8_t regex_comb_default[N];  /* omitted when all rows share one */
static const uint8_t regex_comb_next[L];     /* the successors */
static const uint8_t regex_comb_check[L];    /* the row that owns the slot (N: free) */

state = regex_comb_check[regex_comb_base[state] + c] == state
            ? regex_comb_next[regex_comb_base[state] + c] : regex_comb_default[state];
```

It applies to every table (byte unit with or without alphabet
compression, code-point unit, scan) and takes the place of row
deduplication.  The lookup costs a dependent load and a compare more
(gcc emits a branch, which on a run in the dead state costs nothing;
while the state changes ~70 % speed, as row deduplication), so
`"auto"` applies it under the same rule: above `size_threshold`, when it
saves at least 25 % of the table bytes.  On the suites it shrinks long
literal chains most (a DFA of 1447 states: 311 KB → 9 KB); over all
suite DFAs the code-point tables shrink from 1.29 MB to 0.75 MB, the
largest from 311 KB to 14 KB.  The tokenizer DFAs, whose size is the
class map, hardly change.  See
[comb\_compression.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/comb_compression.c).

### Code-point unit

With `unit="codepoint"` (or `"auto"` when it is smaller) the DFA reads
whole code points.  It is derived from the byte DFA: its states are the
byte DFA's states between two characters, and code points that lead every
such state to the same successor form one class.  The generator produces:

1. A **class legend** comment (up to four ranges per class).
2. The **class map**: `regex_ascii_class[128]` (when the ASCII classes
   are not read from the leaf table) and one to three stages
   `regex_cp_stage1`, `regex_cp_stage2`, `regex_cp_class`; equal blocks
   of a stage are stored once, and the block sizes are those that make
   the map smallest.  Code points from the last class change on all share
   one class and are not stored.
3. The **transition table** `regex_transitions[M][C]` with one column
   per class (rounded up to a power of two), and an optional row map as
   for bytes, or the comb arrays.
4. A **match function** that decodes UTF-8: ASCII takes its class from a
   table at once; a multi-byte character is decoded and checked, and
   ill-formed UTF-8 (a stray continuation byte, an overlong form, a
   surrogate, more than U+10FFFF, a truncated character) does not match.
   The byte unit rejects such input as well, so both units match the same
   strings.

The class lookup does not depend on the state, so it overlaps with the
transition chain: on mostly ASCII text the code-point unit is as fast as
the byte unit, on other text faster (one transition per character).  See
[unicode.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/unicode.c) (`\x{00e9}+`; the byte unit:
[unit\_byte.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/unit_byte.c)).

In scan mode the code-point DFA is derived from the scan DFA in the same
way.  A look-ahead can confirm a match in the middle of a character (`a(?![a-z])`
is decided by the first byte of `é`); the code-point state records that
match, and its `regex_match_back` counts back from the *start* of the
character that led to it, so that characters of any length lead to the
same state.  An ill-formed character ends the match attempt the way the
byte DFA ends it: it reads as byte 0xFF (`regex_fail_back`), which
decides the pending look-aheads, so both units report the same matches
on any input.  A search decodes a character at every start position,
which on small tables costs up to ~60 % speed, so `"auto"` takes the
code-point unit only when the byte table has more than `size_threshold`
cells; on the large tokenizer DFAs it is ~8 % faster.  See
[scan\_unit\_codepoint.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/scan_unit_codepoint.c).

### Scan Mode (`--scan`)

The transition table is emitted as for the DFA engine (state 0 is the
dead state), followed by

1. **`regex_match_back[N]`** — non-zero *k* when the state reached on a
   byte confirms a match that ends *k* bytes before the position after
   that byte (*k* = 1: right before the byte; more when a look-ahead was
   decided later).  0: no new match.
2. **`regex_eoi_back[N]`** — non-zero *k* when, at the end of the input,
   the match ending *k* − 1 bytes before the end is the best one; there
   a pending `(?!R)` holds and a pending `(?=R)` fails.
3. An optional **`regex_initial[257]`** — the start state by the byte
   before the start position (256: start of input), emitted when anchors
   or `\b` make them differ.
4. **`regex_match_at()`** (static) runs the DFA from one start position
   until the dead state, a *terminal* state (numbered last: only the dead
   state can follow, so its match is final) or the end; the last match it
   saw is the result.
5. **`regex_find()`** tries the start positions from `from` on.
6. Optionally a **`main()`** that prints every match of `argv[1]`.

See [scan.c](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/golden/scan.c) for the complete output for `a|ab`,
and [Code-point unit](#code-point-unit) for the scan over code points.

### Bit-NFA Engine (`--engine bitnfa`)

The generator produces:

1. One **transition mask table** per NFA position that needs one
   (`static const uint8_t regex_trans_P[256]`).  Each entry is the bitmask
   of destination positions for the input byte.  The integer width
   (`uint8_t` / `uint16_t` / `uint32_t`, or `uint32_t[N]` words beyond 32
   positions) is chosen automatically.  A position that moves on a single
   byte gets an inline comparison instead of a table.
2. A **match function** with a fully unrolled inner loop — one
   `if (state & bit) next |= …;` per active position.
3. Optionally a **`main()` function** for standalone executables.

#### Example Output (pattern `h[ae]llo`, `--engine bitnfa`)

```c
static const uint8_t regex_trans_1[256] = { ['a'] = 0x04u, ['e'] = 0x04u };

bool regex_match(const char *input, size_t len) {
    uint8_t state = 0x01u;
    for (size_t i = 0; i < len; i++) {
        unsigned char b = (unsigned char)input[i];
        uint8_t next = 0;
        if (state & 0x01u) next |= ((b == 'h') ? 0x02u : 0u);
        if (state & 0x02u) next |= regex_trans_1[b];
        if (state & 0x04u) next |= ((b == 'l') ? 0x08u : 0u);
        if (state & 0x08u) next |= ((b == 'l') ? 0x10u : 0u);
        if (state & 0x10u) next |= ((b == 'o') ? 0x20u : 0u);
        state = next;
    }
    return (state & 0x20u) != 0;
}
```

## Testing

pytest holds the unit, feature and golden tests; scan mode and
`syntax="oniguruma"` are checked against the pieces the `tokenizers`
library splits text into (`tests/test_scan.py`, `tests/test_oniguruma.py`).

The pattern corpora are not pytest cases.
[`tests/data/support_status.md`](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/tests/data/support_status.md) lists, per
test provider, how many patterns are supported and why the others are not
(generated by `tools/support_status.py`; CI commits it in pull requests
and fails on `main` when it is stale):

| Provider | Patterns | Oracle |
|---|---|---|
| re2/PCRE2 | `re2_compat_results.json`: 2 500+ patterns of the PCRE2 test suite | Google re2 |
| HF full match | `tokenizer_compat_results.json`: pre-tokenizer regexes of popular Hugging Face `tokenizer.json` files (`unicode_classes=True`) | `regex` module |
| HF scan | `tokenizer_scan_results.json`: every `tokenizer.json` regex of the models in `tests/data/parse_hf_tokenizers.py` (`syntax="oniguruma"`) | `tokenizers` |

```bash
# Run all tests (parallel)
pytest -n auto -q

# Run linter
ruff check src/ tests/ tools/

# Regenerate the support report
python tools/support_status.py
```

### Test Strategy

1. **Generate** C code from the regex pattern.
2. **Compile** with `gcc -Werror`.
3. **Execute** the binary on each test subject.
4. **Compare** the match result (or scan pieces) against the oracle's.

## Development

```bash
# Clone
git clone --recurse-submodules https://github.com/emmtrix/emx-regex-cgen.git
cd emx-regex-cgen

# Install
pip install emx-regex-cgen

# Or, for local development
pip install -e ".[dev]"

# Test
pytest -n auto -q

# Lint
ruff check src/ tests/
```

## License

[MIT](https://github.com/emmtrix/emx-regex-cgen/blob/v0.3.0/LICENSE) — Copyright (c) 2026 emmtrix Technologies GmbH

## Maintained by

[emmtrix Technologies GmbH](https://emmtrix.com)
