PERLREAPI(1perl)

πŸ“¦
version 5.44.0 Β· 2 versions
, in arch rolling

πŸ¦‹ NAME πŸ¦‹

perlreapi β€” the Perl regular expression plugin interface. That's it, that's the whole name bestie. πŸ’– It comes from the Perl Programmers Reference Guide, section 1perl.


πŸ’– DESCRIPTION πŸ’–

okay so, as of Perl 5.9.5 there is a whole new interface for plugging in and using regular expression engines that are not the default one. yes fr, you can bring your own regex engine to the party. πŸŽ‰

Every engine is supposed to give you access to a constant structure that looks exactly like this, copy-pasted from the source because we do not round here:

    typedef struct regexp_engine {
        REGEXP* (*comp) (pTHX_
                         const SV * const pattern, const U32 flags);
        I32     (*exec) (pTHX_
                         REGEXP * const rx,
                         char* stringarg,
                         char* strend, char* strbeg,
                         SSize_t minend, SV* sv,
                         void* data, U32 flags);
        char*   (*intuit) (pTHX_
                           REGEXP * const rx, SV *sv,
                           const char * const strbeg,
                           char *strpos, char *strend, U32 flags,
                           struct re_scream_pos_data_s *data);
        SV*     (*checkstr) (pTHX_ REGEXP * const rx);
        void    (*free) (pTHX_ REGEXP * const rx);
        void    (*numbered_buff_FETCH) (pTHX_
                                        REGEXP * const rx,
                                        const I32 paren,
                                        SV * const sv);
        void    (*numbered_buff_STORE) (pTHX_
                                        REGEXP * const rx,
                                        const I32 paren,
                                        SV const * const value);
        I32     (*numbered_buff_LENGTH) (pTHX_
                                         REGEXP * const rx,
                                         const SV * const sv,
                                         const I32 paren);
        SV*     (*named_buff) (pTHX_
                               REGEXP * const rx,
                               SV * const key,
                               SV * const value,
                               U32 flags);
        SV*     (*named_buff_iter) (pTHX_
                                    REGEXP * const rx,
                                    const SV * const lastkey,
                                    const U32 flags);
        SV*     (*qr_package)(pTHX_ REGEXP * const rx);
    #ifdef USE_ITHREADS
        void*   (*dupe) (pTHX_ REGEXP * const rx, CLONE_PARAMS *param);
    #endif
        REGEXP* (*op_comp) (...);

So when a regexp gets compiled, its engine field is set to point at the appropriate one of these structures β€” that way, when Perl needs to actually use the thing, it knows exactly which routines to call. No guesswork, just vibes and function pointers. ✨

In order to install a new regexp handler, $^H{regcomp} is set to an integer which (when casted appropriately) resolves to one of these structures. When compiling, the comp method is executed, and the resulting regexp structure's engine field is expected to point back at the same structure. πŸ”

And real quick: the pTHX_ symbol in the definition is a macro used by Perl under threading to provide an extra argument to the routine holding a pointer back to the interpreter that is executing the regexp. So under threading, all routines get an extra argument. iykyk.


🌈 Callbacks 🌈

comp

    REGEXP* comp(pTHX_ const SV * const pattern, const U32 flags);

Compile the pattern stored in pattern using the given flags and hand back a pointer to a prepared REGEXP structure that can perform the match. If you wanna know what all the little fields in that struct mean, go see "The REGEXP structure" below. πŸ‘‡

The pattern parameter is the scalar that was used as the pattern. Previous versions of Perl would pass two char* indicating the start and end of the stringified pattern; the following snippet gets you the old parameters back:

    STRLEN plen;
    char*  exp = SvPV(pattern, plen);
    char* xend = exp + plen;

Since any scalar can be passed as a pattern, it's possible to implement an engine that does something with an array ("ook" =~ [ qw/ eek hlagh / ]) or with the non-stringified form of a compiled regular expression ("ook" =~ qr/eek/). Perl's own engine will always stringify everything using the snippet above, but that doesn't mean other engines have to. your engine, your rules πŸ’…

The flags parameter is a bitfield which indicates which of the msixpn flags the regex was compiled with. It also contains additional info, such as if use locale is in effect.

The eogc flags are stripped out before being passed to the comp routine. The regex engine does not need to know if any of these are set, as those flags should only affect what Perl does with the pattern and its match variables β€” not how it gets compiled and executed.

By the time the comp callback is called, some of these flags have already had effect (noted below where applicable). However most of their effect occurs after the comp callback has run, in routines that read the rx->extflags field which it populates.

In general the flags should be preserved in rx->extflags after compilation, although the regex engine might want to add or delete some of them to invoke or disable some special behavior in Perl. The flags along with any special behavior they cause are documented below: πŸ‘‘

The pattern modifiers:

  • /m - RXf_PMf_MULTILINE β€” if this is in rx->extflags it will be passed to Perl_fbm_instr by pp_split, which will treat the subject string as a multi-line string.
  • /s - RXf_PMf_SINGLELINE
  • /i - RXf_PMf_FOLD
  • /x - RXf_PMf_EXTENDED β€” if present on a regex, # comments will be handled differently by the tokenizer in some cases.
TODO: Document those cases.
  • /p - RXf_PMf_KEEPCOPY
TODO: Document this

Character set

The character set rules are determined by an enum that is contained in this field. This is still experimental and subject to change, but the current interface returns the rules by use of the in-line function get_regex_charset(const U32 flags). The only currently documented value returned from it is REGEX_LOCALE_CHARSET, which is set if use locale is in effect. If present in rx->extflags, split will use the locale dependent definition of whitespace when RXf_SKIPWHITE or RXf_WHITE is in effect. ASCII whitespace is defined as per isSPACE, and by the internal macros is_utf8_space under UTF-8, and isSPACE_LC under use locale.

Additional flags:

  • RXf_SPLIT β€” this flag was removed in perl 5.18.0. split ' ' is now special-cased solely in the parser. RXf_SPLIT is still #defined, so you can test for it. This is how it used to work:

If split is invoked as split ' ' or with no arguments (which really means split(' ', $_), see split), Perl will set this flag. The regex engine can then check for it and set the SKIPWHITE and WHITE extflags. To do this, the Perl engine does:

    if (flags & RXf_SPLIT && r->prelen == 1 && r->precomp[0] == ' ')
        r->extflags |= (RXf_SKIPWHITE|RXf_WHITE);

These flags can be set during compilation to enable optimizations in the split operator.

  • RXf_SKIPWHITE β€” this flag was removed in perl 5.18.0. It is still #defined, so you can set it, but doing so will have no effect. This is how it used to work:

If the flag is present in rx->extflags, split will delete whitespace from the start of the subject string before it's operated on. What is considered whitespace depends on if the subject is a UTF-8 string and if the RXf_PMf_LOCALE flag is set.

If RXf_WHITE is set in addition to this flag, split will behave like split " " under the Perl engine.

  • RXf_START_ONLY β€” tells the split operator to split the target string on newlines (\n) without invoking the regex engine.

Perl's engine sets this if the pattern is /^/ (plen == 1 && *exp == '^'), even under /^/s; see split. Of course a different regex engine might want to use the same optimizations with a different syntax.

  • RXf_WHITE β€” tells the split operator to split the target string on whitespace without invoking the regex engine. The definition of whitespace varies depending on if the target string is a UTF-8 string and on if RXf_PMf_LOCALE is set.

Perl's engine sets this flag if the pattern is \s+.

  • RXf_NULL β€” tells the split operator to split the target string on characters. The definition of character varies depending on if the target string is a UTF-8 string.

Perl's engine sets this flag on empty patterns. This optimization makes split // much faster than it would otherwise be. It's even faster than unpack. πŸ”₯

  • RXf_NO_INPLACE_SUBST β€” added in perl 5.18.0, this flag indicates that a regular expression might perform an operation that would interfere with inplace substitution. For instance it might contain lookbehind, or assign to non-magical variables (such as $REGMARK and $REGERROR) during matching. s/// will skip certain optimisations when this is set.

exec

    I32 exec(pTHX_ REGEXP * const rx,
             char *stringarg, char* strend, char* strbeg,
             SSize_t minend, SV* sv,
             void* data, U32 flags);

Execute a regexp. The arguments are:

  • rx β€” the regular expression to execute.
  • sv β€” this is the SV to be matched against. Note that the actual char array to be matched against is supplied by the arguments described below; the SV is just used to determine UTF8ness, pos() etc.
  • strbeg β€” pointer to the physical start of the string.
  • strend β€” pointer to the character following the physical end of the string (i.e. the \0, if any).
  • stringarg β€” pointer to the position in the string where matching should start; it might not be equal to strbeg (for example in a later iteration of /.../g).
  • minend β€” minimum length of string (measured in bytes from stringarg) that must match; if the engine reaches the end of the match but hasn't reached this position in the string, it should fail.
  • data β€” optimisation data; subject to change.
  • flags β€” optimisation flags; subject to change.

intuit

    char* intuit(pTHX_
                 REGEXP * const rx,
                 SV *sv,
                 const char * const strbeg,
                 char *strpos,
                 char *strend,
                 const U32 flags,
                 struct re_scream_pos_data_s *data);

okay so find the start position where a regex match should even be attempted β€” or maybe decide the regex engine shouldn't run at all because the pattern literally can't match πŸ’…. this gets called, as appropriate, by the core, depending on the values of the extflags member of the regexp structure. no cap.

Arguments:

  • rx: the regex to match against
  • sv: the SV being matched β€” only used for the utf8 flag; the string itself is accessed via the pointers below. note that on something like an overloaded SV, SvPOK(sv) may be false and the string pointers may point to something unrelated to the SV itself 😭
  • strbeg: real beginning of string
  • strpos: the point in the string at which to begin matching
  • strend: pointer to the byte following the last char of the string
  • flags: currently unused; set to 0
  • data: currently unused; set to NULL

checkstr ✨

SV* checkstr(pTHX_ REGEXP * const rx);

returns an SV containing a string that must appear in the pattern. used by split for optimising matches 🫢.

free πŸ¦‹

void free(pTHX_ REGEXP * const rx);

called by Perl when it's freeing a regexp pattern, so the engine can release any resources pointed to by the pprivate member of the regexp structure. bestie this is only responsible for freeing private data β€” Perl will handle releasing anything else contained in the regexp structure, so don't you dare double-free πŸ‘‘.


Numbered capture callbacks πŸ’–

called to get/set the value of $` , $', $& and their named equivalents, ${^PREMATCH}, ${^POSTMATCH} and ${^MATCH}, as well as the numbered capture groups ($1, $2, ...). the whole squad, basically.

the paren parameter will be 1 for $1, 2 for $2 and so forth, and it has these symbolic values for the special variables:

${^PREMATCH}  RX_BUFF_IDX_CARET_PREMATCH
${^POSTMATCH} RX_BUFF_IDX_CARET_POSTMATCH
${^MATCH}     RX_BUFF_IDX_CARET_FULLMATCH
$`            RX_BUFF_IDX_PREMATCH
$'            RX_BUFF_IDX_POSTMATCH
$&            RX_BUFF_IDX_FULLMATCH

note that in Perl 5.17.3 and earlier, the last three constants were also used for the caret variants of the variables. vintage behavior, we don't gatekeep πŸŽ€.

the names have been chosen by analogy with Tie::Scalar methods names, with an additional LENGTH callback for efficiency. however, named capture variables are currently not tied internally but implemented via magic ✨.

numbered_buff_FETCH 🌸

void numbered_buff_FETCH(pTHX_ REGEXP * const rx, const I32 paren,
                         SV * const sv);

fetch a specified numbered capture. sv should be set to the scalar to return β€” and like, the scalar is passed as an argument rather than being returned from the function because when it's called Perl already has a scalar to store the value, and creating another one would be redundant πŸ™ˆ. the scalar can be set with sv_setsv, sv_setpvn and friends, see perlapi.

this callback is where Perl untaints its own capture variables under taint mode (see perlsec). see the Perl_reg_numbered_buff_fetch function in regcomp.c for how to untaint capture variables if that's something you'd like your engine to do as well πŸ‘€.

numbered_buff_STORE πŸ’…

void    (*numbered_buff_STORE) (pTHX_
                                REGEXP * const rx,
                                const I32 paren,
                                SV const * const value);

set the value of a numbered capture variable. value is the scalar that is to be used as the new value. it's up to the engine to make sure this is used as the new value (or reject it). your engine, your rules, periodt.

Example:

if ("ook" =~ /(o*)/) {
    # 'paren' will be '1' and 'value' will be 'ee'
    $1 =~ tr/o/e/;
}

Perl's own engine will croak on any attempt to modify the capture variables 😀. to do this in another engine use the following callback (copied from Perl_reg_numbered_buff_store):

void
Example_reg_numbered_buff_store(pTHX_
                                REGEXP * const rx,
                                const I32 paren,
                                SV const * const value)
{
    PERL_UNUSED_ARG(rx);
    PERL_UNUSED_ARG(paren);
    PERL_UNUSED_ARG(value);

    if (!PL_localizing)
        Perl_croak(aTHX_ PL_no_modify);
}

actually, Perl will not always croak in a statement that looks like it would modify a numbered capture variable. that's because the STORE callback will not be called if Perl can determine that it doesn't have to modify the value. this is exactly how tied variables behave in the same situation, fr fr:

package CaptureVar;
use parent 'Tie::Scalar';

sub TIESCALAR { bless [] }
sub FETCH { undef }
sub STORE { die "This doesn't get called" }

package main;

tie my $sv => "CaptureVar";
$sv =~ y/a/b/;

because $sv is undef when the y/// operator is applied to it, the transliteration won't actually execute and the program won't die πŸ’€. this is different to how 5.8 and earlier versions behaved since the capture variables were READONLY variables then; now they'll just die when assigned to in the default engine. glow-up but make it tragic ✨.

numbered_buff_LENGTH πŸŽ€

I32 numbered_buff_LENGTH (pTHX_
                          REGEXP * const rx,
                          const SV * const sv,
                          const I32 paren);

get the "length" of a capture variable. there's a special callback for this so that Perl doesn't have to do a FETCH and run length on the result, since the length is (in Perl's case) known from an offset stored in rx->offs, so this is way more efficient πŸ”₯:

I32 s1  = rx->offs[paren].start;
I32 s2  = rx->offs[paren].end;
I32 len = t1 - s1;

this is a little bit more complex in the case of UTF-8, see what Perl_reg_numbered_buff_length does with is_utf8_string_loclen 🧚.


Named capture callbacks πŸ¦‹

called to get/set the value of %+ and %-, as well as by some utility functions in re. main character energy tbh.

there are two callbacks: named_buff is called in all the cases the FETCH, STORE, DELETE, CLEAR, EXISTS and SCALAR Tie::Hash callbacks would be on changes to %+ and %-, and named_buff_iter in the same cases as FIRSTKEY and NEXTKEY πŸ‘‘.

the flags parameter can be used to determine which of these operations the callbacks should respond to. the following flags are currently defined:

which Tie::Hash operation is being performed from the Perl level on %+ or %+, if any:

RXapif_FETCH
RXapif_STORE
RXapif_DELETE
RXapif_CLEAR
RXapif_EXISTS
RXapif_SCALAR
RXapif_FIRSTKEY
RXapif_NEXTKEY

if %+ or %- is being operated on, if any.

RXapif_ONE /* %+ */
RXapif_ALL /* %- */

if this is being called as re::regname, re::regnames or re::regnames_count, if any. the first two will be combined with RXapif_ONE or RXapif_ALL.

RXapif_REGNAME
RXapif_REGNAMES
RXapif_REGNAMES_COUNT

internally %+ and %- are implemented with a real tied interface via Tie::Hash::NamedCapture. the methods in that package will call back into these functions. however, the usage of Tie::Hash::NamedCapture for this purpose might change in future releases β€” for instance this might be implemented by magic instead (would need an extension to mgvtbl). so like, don't get too attached bestie πŸ’”.

named_buff 🌸

SV*     (*named_buff) (pTHX_ REGEXP * const rx, SV * const key,
                       SV * const value, U32 flags);

named_buff_iter ✨

SV*     (*named_buff_iter) (pTHX_
                            REGEXP * const rx,
                            const SV * const lastkey,
                            const U32 flags);

qr_package πŸ’–

SV* qr_package(pTHX_ REGEXP * const rx);

the package the qr// magic object is blessed into (as seen by ref qr//). it's recommended that engines change this to their package name for identification, regardless of if they implement methods on the object 🫢.

the package this method returns should also have the internal Regexp package in its @ISA. qr//->isa("Regexp") should always be true, regardless of what engine is being used. periodt.

Example implementation might be:

SV*
Example_qr_package(pTHX_ REGEXP * const rx)
{
    PERL_UNUSED_ARG(rx);
    return newSVpvs("re::engine::Example");
}

any method calls on an object created with qr// will be dispatched to the package as a normal object. iconic.

use re::engine::Example;
my $re = qr//;
$re->meth; # dispatched to re::engine::Example::meth()

to retrieve the REGEXP object from the scalar in an XS function use the SvRX macro, see REGEXP Functions in perlapi.

void meth(SV * rv)
PPCODE:
    REGEXP * re = SvRX(sv);

dupe πŸ”₯

void* dupe(pTHX_ REGEXP * const rx, CLONE_PARAMS *param);

on threaded builds a regexp may need to be duplicated so that the pattern can be used by multiple threads. this routine is expected to handle the duplication of any private data pointed to by the pprivate member of the regexp structure. it will be called with the preconstructed new regexp structure as an argument, the pprivate member will point at the old private structure, and it is this routine's responsibility to construct a copy and return a pointer to it (which Perl will then use to overwrite the field as passed to this routine.) the way that it just hands you the pointer and you handle it 😭.

this allows the engine to dupe its private data but also, if necessary, modify the final structure if it really must. no pressure or anything.

on unthreaded builds this field doesn't exist. gone, not invited πŸ’€.

op_comp πŸ™ˆ

this is private to the Perl core and subject to change. should be left null. bestie don't touch it, seriously.


✨ The REGEXP structure ✨

the REGEXP struct is defined in regexp.h. all regex engines must be able to correctly build such a structure in their comp routine. no shortcuts πŸ‘‘.

the REGEXP structure contains all the data that Perl needs to be aware of to properly work with the regular expression. it includes data about optimisations that Perl can use to determine if the regex engine should really be used, and various other control info that is needed to properly execute patterns in various contexts β€” like if the pattern is anchored in some way, or what flags were used during the compile, or if the program contains special constructs that Perl needs to be aware of 🌈.

in addition it contains two fields that are intended for the private use of the regex engine that compiled the pattern. these are the intflags and pprivate members. pprivate is a void pointer to an arbitrary structure, whose use and management is the responsibility of the compiling engine. Perl will never modify either of these values. they're yours, guard them with your life πŸŽ€.

/* copied from: regexp.h */
typedef struct regexp {
    /*----------------------------------------------------------------------
     * Fields required for compatibility with SV types
     */
    XPV_HEAD_;

    /*----------------------------------------------------------------------
     * Operational fields
     */
    const struct regexp_engine* engine; /* what engine created this regexp? */
    REGEXP *mother_re; /* what re is this a lightweight copy of? */
    HV *paren_names;   /* Optional hash of paren names */

    /*----------------------------------------------------------------------
     * Information about the match that the perl core uses to manage things
     */

    /* see comment in regcomp_internal.h about branch reset to understand
       the distinction between physical and logical capture buffers */
    U32 nparens;                    /* physical number of capture buffers */
    U32 logical_nparens;            /* logical_number of capture buffers */
    I32 *logical_to_parno;          /* map logical parno to first physical */
    I32 *parno_to_logical;          /* map every physical parno to logical */
    I32 *parno_to_logical_next;     /* map every physical parno to the next
                                       physical with the same logical id */

    SSize_t maxlen;    /* maximum possible number of chars in string to match */
    SSize_t minlen;    /* minimum possible number of chars in string to match */
    SSize_t minlenret; /* minimum possible number of chars in $& */
    STRLEN gofs;       /* chars left of pos that we search from */
                       /* substring data about strings that must appear in
                        * the final match, used for optimisations */

    struct reg_substr_data *substrs;

    /* private engine specific data */

    void *pprivate;    /* Data private to the regex engine which
                        * created this object. */
    U32 extflags;      /* Flags used both externally and internally */
    U32 intflags;      /* Engine Specific Internal flags */

    /*----------------------------------------------------------------------
     * Data about the last/current match. These are modified during matching
     */

    U32 lastparen;           /* highest close paren matched ($+) */
    U32 lastcloseparen;      /* last close paren matched ($^N) */
    regexp_paren_pair *offs; /* Array of offsets for (@-) and (@+) */
    char **recurse_locinput; /* used to detect infinite recursion, XXX: move to internal */

    /*---------------------------------------------------------------------- */

    /* offset from wrapped to the start of precomp */
    PERL_BITFIELD32 pre_prefix:4;

    /* original flags used to compile the pattern, may differ from
     * extflags in various ways */
    PERL_BITFIELD32 compflags:9;

    /*---------------------------------------------------------------------- */

    char *subbeg;       /* saved or original string so \digit works forever. */
    SV_SAVED_COPY       /* If non-NULL, SV which is COW from original */
    SSize_t sublen;     /* Length of string pointed by subbeg */
    SSize_t suboffset;  /* byte offset of subbeg from logical start of str */
    SSize_t subcoffset; /* suboffset equiv, but in chars (for @-/@+) */

    /*----------------------------------------------------------------------
     * More Operational fields
     */

    CV *qr_anoncv;      /* the anon sub wrapped round qr/(?{..})/ */
} regexp;

okay so most of these fields? you don't poke them directly bestie, you reach them through macros that start with RX_ or RXp_ πŸ’…. but we're still gonna go through every single one, one by one, no skipping:


✨ "engine" ✨

this pointer is pointing at a regexp_engine struct, which is basically a little bag of function pointers to the subroutines that do the actual matching πŸŽ€. the routine doing the compiling is the one responsible for filling this field in before it hands the regexp object back. no pressure or anything.

internally it's set to NULL unless you specified a custom engine in $^H{regcomp}, and perl's own set of callbacks lives in the struct that RE_ENGINE_PTR points to πŸ’–.

πŸ¦‹ "mother_re" πŸ¦‹

this one points at another regexp struct that this one was derived from β€” it's giving family tree fr fr. qr// objects mean the same regexp pattern can be living in different contexts at the same time, and as long as match status info is stored inside the structure (and bestie, there are plans to change that eventually) we simply have to support multiple copies of the structure being in use simultaneously 😭.

the fields about the regexp program itself are copied from the mother_re and owned by the mother_re, whereas the match state variables are owned by the struct itself πŸ‘‘.

🌸 "extflags" 🌸

perl reads this to see what flags the regexp got compiled with. it'll normally be set to the value of the flags parameter from the comp callback. go peep the comp documentation for which flags are valid ✨.

πŸ’œ "minlen" "minlenret" πŸ’œ

minlen = the minimum string length, counted in characters, that the pattern needs in order to match. this exists so we can prune the search space β€” no point matching any closer to the end of a string than would still allow a match to happen. like, if minlen is 10 but your string is only 5 characters long? literally no point even starting the engine, there is genuinely no way the pattern can match πŸ’€.

minlenret is the minimum length (also in characters) of the string that would turn up in $& after a match.

the glow-up between them lives in this pattern:

/ns(?=\d)/

here minlen would be 3, but minlenret would be only 2 β€” because the \d is required to match but is not actually included in the matched content πŸ™ˆ. this distinction is highkey important, because the substitution logic uses minlenret to decide whether it can do in-place substitutions, and those can be a considerable speed-up πŸ”₯.

πŸŽ€ "gofs" πŸŽ€

left offset from pos() to start the match at.

⭐ "substrs" ⭐

substring data about strings that must appear in the final match. currently this is only used internally by perl's engine, but it might get used by all engines in the future for optimisations 🫢.

πŸ‘‘ "nparens", "logical_nparens" πŸ‘‘

these keep track of how many physical and logical paren capture groups the pattern has β€” and bestie, those numbers can differ if the pattern uses the branch reset construct (?| ... | ... ) 😳. take /(?|(foo)|(bar))/: it's got two physical capture buffers but only one logical one. most of the internal logic in the regex engine uses physical capture buffer ids, while the logic exposed to you uses logical capture buffer ids. the next section has the data structures that map between them πŸ’….

🌈 "logical_to_parno", "parno_to_logical", "parno_to_logical_next" 🌈

these three handle the mapping between logical and physical capture buffer numbers:

  • logical_to_parno is an array whose Kth element holds the lowest physical capture buffer id for the Kth logical capture buffer.
  • parno_to_logical is an array whose Kth element holds the logical capture buffer associated with the Kth physical capture buffer.
  • parno_to_logical_next is an array whose Kth element holds the next physical capture buffer with the same logical id, or 0 if there isn't one.

and here's the thing: all three of these arrays are ONLY populated when the pattern uses the branch reset concept 🚨. patterns that don't use branch-reset effectively have a 1:1 mapping between logical and physical, so there's just no need for this meta-data.

here's an example of how it all shakes out:

     Pattern /(a) (?| (b) (c) (d) | (e) (f) | (g) ) (h)/
     Logical: $1      $2  $3  $4    $2  $3    $2    $5
     Physical: 1       2   3   4     5   6     7     8
     Next:     0       5   6   0     7   0     0     0

also, the 0th element of any of these arrays goes unused, because it represents the "entire pattern" πŸ’–.

πŸ“ "lastparen", and "lastcloseparen" πŸ“

these keep track of two things: which was the highest paren to be closed (that's $+, see perlvar), and which was the most recent paren to be closed (that's $^N, also in perlvar) ✨.

🧚 "intflags" 🧚

the engine's very own private copy of the flags the pattern was compiled with. usually it's the same as extflags, unless the engine chose to modify one of them πŸ™ˆ.

πŸ’– "pprivate" πŸ’–

a void* pointing at an engine-defined data structure. the perl engine uses the regexp_internal structure (see "Base Structures" in perlreguts) but a custom engine should use something else, do your own thing bestie ✨.

πŸ’… "offs" πŸ’…

a regexp_paren_pair structure that defines offsets into the string being matched, which correspond to the $& and $1, $2 etc. captures. the regexp_paren_pair struct looks like this:

typedef struct regexp_paren_pair {
    I32 start;
    I32 end;
} regexp_paren_pair;

if ->offs[num].start or ->offs[num].end is -1, then that capture group did not match, it's giving nope πŸ’€. ->offs[0].start/end represents $& (or ${^MATCH} under /p) and ->offs[paren].end matches $$paren where $paren = 1>.

⭐ "RX_PRECOMP" "RX_PRELEN" ⭐

optimisation girlies rise up πŸ’…. RX_PRECOMP holds a copy of the pattern that got compiled, and RX_PRELEN holds its length. when a new pattern is about to be compiled (say, inside a loop), the internal regcomp operator checks whether the last compiled REGEXP's RX_PRECOMP and RX_PRELEN are equivalent to the new one β€” and if they are, it just uses the old pattern instead of compiling a fresh one. iconic behaviour honestly πŸ”₯.

in older perls these two macros were actually fields in the structure, named precomp and prelen respectively.

πŸŽ€ "paren_names" πŸŽ€

a hash used internally to track named capture groups and their offsets. the keys are the names of the buffers, and the values are dualvars β€” with the IV slot holding the number of buffers with the given name and the pv being an embedded array of I32 πŸ‘‘. the values may also be contained independently in the data array in cases where named backreferences are used.

🌸 "substrs" 🌸

holds info on the longest string that must occur at a fixed offset from the start of the pattern, and the longest string that must occur at a floating offset from the start of the pattern πŸ¦‹. it's used to do Fast-Boyer-Moore searches on the string, to figure out whether it's even worth using the regex engine at all β€” and if it is, where in the string to search ✨.

πŸ’Ύ "subbeg" "sublen" "saved_copy" "suboffset" "subcoffset"

okay bestie, these five are the whole search-and-replace girl squad πŸ”₯ They do their thing during the execution phase, juggling search-and-replace patterns and serving up the actual text for $&, $1, etc. Like, that's the whole reason you can even see what matched.

  • "subbeg" β€” points at a buffer. Could be the original string, or a copy if RX_MATCH_COPIED(rx_sv) said so. Either way, that's where the goods live.
  • "sublen" β€” the length of that buffer, periodt.
  • The RX_OFFS_START(rx_sv,n) and RX_OFFS_END(rx_sv,n) macros index into this buffer, and so does the data structure returned by RX_OFFSp(rx_sv) β€” but do not touch that one directly, okay? Hands off. πŸ™ˆ

Now, when REXEC_COPY_STR is in the building, but REXEC_COPY_SKIP_PRE or REXEC_COPY_SKIP_POST also showed up, an engine is allowed to not copy the full buffer. Cute, right? Except β€” and this is the crunchy part β€” it must still copy the whole thing if RXf_PMf_KEEPCOPY is around, or if the relevant bits are set in PL_sawampersand. No skipping on those.

When it does skip, the engine can set suboffset to say how many bytes from the logical start of the buffer over to the physical start (aka subbeg). And it should also set subcoffset β€” that's the number of characters in that offset. Why both? Because @- and @+ count in characters, not bytes, so they need subcoffset to function. iykyk πŸ’…


πŸŽ€ "RX_WRAPPED" "RX_WRAPLEN"

These are the macros that reach into the string that qr// stringifies to. The Perl engine, for example, stores (?^:eek) when you write qr/eek/. Wild, I know.

But if you're rocking a custom engine that doesn't understand the (?:) construct for inline modifiers? Then honestly the move is to just have qr// stringify to the pattern you were handed. Just know that this creates some genuinely undesired patterns in situations like:

my $x = qr/a|b/;  # "a|b"
my $y = qr/c/i;   # "c"
my $z = qr/$x$y/; # "a|bc"

Look at that last one. "a|bc". Not what anyone asked for. 😭

And there's no solution to this problem other than teaching your custom engine to understand a construct like (?:). That's it. That's the whole fix. No secret third option. 🫢


πŸ‘‘ RX_REFCNT()

This is how many times the structure is being referenced. The moment it drops to 0, the regexp gets automatically freed by a call to pregfree. So set it to 1 in each engine's comp routine β€” every single one. ✨

Tiny history moment: in older perls this was a struct member literally named refcnt. But in more modern perls, where the regexp structure got unified with the SV structure, it's an alias to SvREFCNT(). Glow-up behavior honestly. πŸ’–


πŸ“œ HISTORY

Originally part of perlreguts. It said "I'm leaving," and then it became its own whole thing. main character energy. 🌈


πŸ’– AUTHORS

Originally written by Yves Orton, and expanded by Γ†var ArnfjΓΆrΓ° Bjarmason. Our founding mothers of this page. 🫢


βš–οΈ LICENSE

Copyright 2006 Yves Orton and 2007 Γ†var ArnfjΓΆrΓ° Bjarmason.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


okay bestie that's the whole page, we ate every last section and left zero crumbs πŸ“ This was PERLREAPI(1perl) from perl v5.44.0, dated 2026-10-17 β€” go forth and write engines, you icon, and remember: the facts stay, only the vibe is new. πŸ’…βœ¨

πŸ“¦ where this page comes from
  • arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms