Debian Codegraph @

upstream/fedora-44/man1/perlreguts.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man v6.0.2 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\"
56 .\" Required to disable full justification in groff 1.23.0.
57 .if n .ds AD l
58 .\" ========================================================================
59 .\"
60 .IX Title "PERLREGUTS 1"
61 .TH PERLREGUTS 1 2026-03-09 "perl v5.42.1" "Perl Programmers Reference Guide"
62 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
63 .\" way too many mistakes in technical documents.
64 .if n .ad l
65 .nh
66 .SH NAME
67 perlreguts \- Description of the Perl regular expression engine.
68 .SH DESCRIPTION
69 .IX Header "DESCRIPTION"
70 This document is an attempt to shine some light on the guts of the regex
71 engine and how it works. The regex engine represents a significant chunk
72 of the perl codebase, but is relatively poorly understood. This document
73 is a meagre attempt at addressing this situation. It is derived from the
74 author\*(Aqs experience, comments in the source code, other papers on the
75 regex engine, feedback on the perl5\-porters mail list, and no doubt other
76 places as well.
77 .PP
78 \&\fBNOTICE!\fR It should be clearly understood that the behavior and
79 structures discussed in this represents the state of the engine as the
80 author understood it at the time of writing. It is \fBNOT\fR an API
81 definition, it is purely an internals guide for those who want to hack
82 the regex engine, or understand how the regex engine works. Readers of
83 this document are expected to understand perl\*(Aqs regex syntax and its
84 usage in detail. If you want to learn about the basics of Perl\*(Aqs
85 regular expressions, see perlre. And if you want to replace the
86 regex engine with your own, see perlreapi.
87 .SH OVERVIEW
88 .IX Header "OVERVIEW"
89 .SS "A quick note on terms"
90 .IX Subsection "A quick note on terms"
91 There is some debate as to whether to say "regexp" or "regex". In this
92 document we will use the term "regex" unless there is a special reason
93 not to, in which case we will explain why.
94 .PP
95 When speaking about regexes we need to distinguish between their source
96 code form and their internal form. In this document we will use the term
97 "pattern" when we speak of their textual, source code form, and the term
98 "program" when we speak of their internal representation. These
99 correspond to the terms \fIS\-regex\fR and \fIB\-regex\fR that Mark Jason
100 Dominus employs in his paper on "Rx" ([1] in "REFERENCES").
101 .SS "What is a regular expression engine?"
102 .IX Subsection "What is a regular expression engine?"
103 A regular expression engine is a program that takes a set of constraints
104 specified in a mini\-language, and then applies those constraints to a
105 target string, and determines whether or not the string satisfies the
106 constraints. See perlre for a full definition of the language.
107 .PP
108 In less grandiose terms, the first part of the job is to turn a pattern into
109 something the computer can efficiently use to find the matching point in
110 the string, and the second part is performing the search itself.
111 .PP
112 To do this we need to produce a program by parsing the text. We then
113 need to execute the program to find the point in the string that
114 matches. And we need to do the whole thing efficiently.
115 .SS "Structure of a Regexp Program"
116 .IX Subsection "Structure of a Regexp Program"
117 \fIHigh Level\fR
118 .IX Subsection "High Level"
119 .PP
120 Although it is a bit confusing and some people object to the terminology, it
121 is worth taking a look at a comment that has
122 been in \fIregexp.h\fR for years:
123 .PP
124 \&\fIThis is essentially a linear encoding of a nondeterministic
125 finite\-state machine (aka syntax charts or "railroad normal form" in
126 parsing technology).\fR
127 .PP
128 The term "railroad normal form" is a bit esoteric, with "syntax
129 diagram/charts", or "railroad diagram/charts" being more common terms.
130 Nevertheless it provides a useful mental image of a regex program: each
131 node can be thought of as a unit of track, with a single entry and in
132 most cases a single exit point (there are pieces of track that fork, but
133 statistically not many), and the whole forms a layout with a
134 single entry and single exit point. The matching process can be thought
135 of as a car that moves along the track, with the particular route through
136 the system being determined by the character read at each possible
137 connector point. A car can fall off the track at any point but it may
138 only proceed as long as it matches the track.
139 .PP
140 Thus the pattern \f(CW\*(C`/foo(?:\ew+|\ed+|\es+)bar/\*(C'\fR can be thought of as the
141 following chart:
142 .PP
143 .Vb 10
144 \& [start]
145 \& |
146 \& <foo>
147 \& |
148 \& +\-\-\-\-\-+\-\-\-\-\-+
149 \& | | |
150 \& <\ew+> <\ed+> <\es+>
151 \& | | |
152 \& +\-\-\-\-\-+\-\-\-\-\-+
153 \& |
154 \& <bar>
155 \& |
156 \& [end]
157 .Ve
158 .PP
159 The truth of the matter is that perl\*(Aqs regular expressions these days are
160 much more complex than this kind of structure, but visualising it this way
161 can help when trying to get your bearings, and it matches the
162 current implementation pretty closely.
163 .PP
164 To be more precise, we will say that a regex program is an encoding
165 of a graph. Each node in the graph corresponds to part of
166 the original regex pattern, such as a literal string or a branch,
167 and has a pointer to the nodes representing the next component
168 to be matched. Since "node" and "opcode" already have other meanings in the
169 perl source, we will call the nodes in a regex program "regops".
170 .PP
171 The program is represented by an array of \f(CW\*(C`regnode\*(C'\fR structures, one or
172 more of which represent a single regop of the program. Struct
173 \&\f(CW\*(C`regnode\*(C'\fR is the smallest struct needed, and has a field structure which is
174 shared with all the other larger structures. (Outside this document, the term
175 "regnode" is sometimes used to mean "regop", which could be confusing.)
176 .PP
177 The "next" pointers of all regops except \f(CW\*(C`BRANCH\*(C'\fR implement concatenation;
178 a "next" pointer with a \f(CW\*(C`BRANCH\*(C'\fR on both ends of it is connecting two
179 alternatives. [Here we have one of the subtle syntax dependencies: an
180 individual \f(CW\*(C`BRANCH\*(C'\fR (as opposed to a collection of them) is never
181 concatenated with anything because of operator precedence.]
182 .PP
183 The operand of some types of regop is a literal string; for others,
184 it is a regop leading into a sub\-program. In particular, the operand
185 of a \f(CW\*(C`BRANCH\*(C'\fR node is the first regop of the branch.
186 .PP
187 \&\fBNOTE\fR: As the railroad metaphor suggests, this is \fBnot\fR a tree
188 structure: the tail of the branch connects to the thing following the
189 set of \f(CW\*(C`BRANCH\*(C'\fRes. It is a like a single line of railway track that
190 splits as it goes into a station or railway yard and rejoins as it comes
191 out the other side.
192 .PP
193 \fIRegops\fR
194 .IX Subsection "Regops"
195 .PP
196 The base structure of a regop is defined in \fIregexp.h\fR as follows:
197 .PP
198 .Vb 5
199 \& struct regnode {
200 \& U8 flags; /* Various purposes, sometimes overridden */
201 \& U8 type; /* Opcode value as specified by regnodes.h */
202 \& U16 next_off; /* Offset in size regnode */
203 \& };
204 .Ve
205 .PP
206 Other larger \f(CW\*(C`regnode\*(C'\fR\-like structures are defined in \fIregcomp.h\fR. They
207 are almost like subclasses in that they have the same fields as
208 \&\f(CW\*(C`regnode\*(C'\fR, with possibly additional fields following in
209 the structure, and in some cases the specific meaning (and name)
210 of some of base fields are overridden. The following is a more
211 complete description.
212 .ie n .IP """regnode_1""" 4
213 .el .IP \f(CWregnode_1\fR 4
214 .IX Item "regnode_1"
215 .PD 0
216 .ie n .IP """regnode_2""" 4
217 .el .IP \f(CWregnode_2\fR 4
218 .IX Item "regnode_2"
219 .PD
220 \&\f(CW\*(C`regnode_1\*(C'\fR structures have the same header, followed by a single
221 four\-byte argument; \f(CW\*(C`regnode_2\*(C'\fR structures contain two two\-byte
222 arguments instead:
223 .Sp
224 .Vb 2
225 \& regnode_1 U32 arg1;
226 \& regnode_2 U16 arg1; U16 arg2;
227 .Ve
228 .ie n .IP """regnode_string""" 4
229 .el .IP \f(CWregnode_string\fR 4
230 .IX Item "regnode_string"
231 \&\f(CW\*(C`regnode_string\*(C'\fR structures, used for literal strings, follow the header
232 with a one\-byte length and then the string data. Strings are padded on
233 the tail end with zero bytes so that the total length of the node is a
234 multiple of four bytes:
235 .Sp
236 .Vb 2
237 \& regnode_string char string[1];
238 \& U8 str_len; /* overrides flags */
239 .Ve
240 .ie n .IP """regnode_charclass""" 4
241 .el .IP \f(CWregnode_charclass\fR 4
242 .IX Item "regnode_charclass"
243 Bracketed character classes are represented by \f(CW\*(C`regnode_charclass\*(C'\fR
244 structures, which have a four\-byte argument and then a 32\-byte (256\-bit)
245 bitmap indicating which characters in the Latin1 range are included in
246 the class.
247 .Sp
248 .Vb 2
249 \& regnode_charclass U32 arg1;
250 \& char bitmap[ANYOF_BITMAP_SIZE];
251 .Ve
252 .Sp
253 Various flags whose names begin with \f(CW\*(C`ANYOF_\*(C'\fR are used for special
254 situations. Above Latin1 matches and things not known until run\-time
255 are stored in "Perl\*(Aqs pprivate structure".
256 .ie n .IP """regnode_charclass_posixl""" 4
257 .el .IP \f(CWregnode_charclass_posixl\fR 4
258 .IX Item "regnode_charclass_posixl"
259 There is also a larger form of a char class structure used to represent
260 POSIX char classes under \f(CW\*(C`/l\*(C'\fR matching,
261 called \f(CW\*(C`regnode_charclass_posixl\*(C'\fR which has an
262 additional 32\-bit bitmap indicating which POSIX char classes
263 have been included.
264 .Sp
265 .Vb 3
266 \& regnode_charclass_posixl U32 arg1;
267 \& char bitmap[ANYOF_BITMAP_SIZE];
268 \& U32 classflags;
269 .Ve
270 .PP
271 \&\fIregnodes.h\fR defines an array called \f(CW\*(C`PL_regnode_arg_len[]\*(C'\fR which gives the size
272 of each opcode in units of \f(CW\*(C`size regnode\*(C'\fR (4\-byte). A macro is used
273 to calculate the size of an \f(CW\*(C`EXACT\*(C'\fR node based on its \f(CW\*(C`str_len\*(C'\fR field.
274 .PP
275 The regops are defined in \fIregnodes.h\fR which is generated from
276 \&\fIregcomp.sym\fR by \fIregcomp.pl\fR. Currently the maximum possible number
277 of distinct regops is restricted to 256, with about a quarter already
278 used.
279 .PP
280 A set of macros makes accessing the fields
281 easier and more consistent. These include \f(CWOP()\fR, which is used to determine
282 the type of a \f(CW\*(C`regnode\*(C'\fR\-like structure; \f(CWNEXT_OFF()\fR, which is the offset to
283 the next node (more on this later); \f(CWARG()\fR, \f(CWARG1()\fR, \f(CWARG2()\fR, \f(CWARG_SET()\fR,
284 and equivalents for reading and setting the arguments; and \f(CWSTR_LEN()\fR,
285 \&\f(CWSTRING()\fR and \f(CWOPERAND()\fR for manipulating strings and regop bearing
286 types.
287 .PP
288 \fIWhat regnode is next?\fR
289 .IX Subsection "What regnode is next?"
290 .PP
291 There are two distinct concepts of "next regnode" in the regex engine,
292 and it is important to keep them distinct in your thinking as they
293 overlap conceptually in many places, but where they don\*(Aqt overlap the
294 difference is critical. For the majority of regnode types the two
295 concepts are (nearly) identical in practice. The two types are
296 \&\f(CW\*(C`REGNODE_AFTER\*(C'\fR which is used heavily during compilation but only
297 occasionally during execution and \f(CW\*(C`regnext\*(C'\fR which is used heavily
298 during execution, and only occasionally during compilation.
299 .IP """REGNODE_AFTER""" 4
300 .IX Item """REGNODE_AFTER"""
301 This is the "positionally next regnode" in the compiled regex program.
302 For the smaller regnode types it is \f(CW\*(C`regnode_ptr+1\*(C'\fR under the hood, but
303 as regnode sizes vary and can change over time we offer macros which
304 hide the gory details.
305 .Sp
306 It is heavily used in the compiler phase but is only used by a few
307 select regnode types in the execution phase. It is also heavily used in
308 the code for dumping the regexp program for debugging.
309 .Sp
310 There are a selection of macros which can be used to compute this as
311 efficiently as possible depending on the circumstances. The canonical
312 macro is \f(CWREGNODE_AFTER()\fR, which is the most powerful and should handle
313 any case we have, but is also potentially the slowest. There are two
314 additional macros for the special case that you KNOW the current regnode
315 size is constant, and you know its type or opcode. In which case you can
316 use \f(CWREGNODE_AFTER_opcode()\fR or \f(CWREGNODE_AFTER_type()\fR.
317 .Sp
318 In older versions of the regex engine \f(CWREGNODE_AFTER()\fR was called
319 \&\f(CW\*(C`NEXTOPER\*(C'\fR but this was found to be confusing and it was renamed. There
320 is also a \f(CWREGNODE_BEFORE()\fR, but it is unsafe and should not be used
321 in new code.
322 .IP """regnext""" 4
323 .IX Item """regnext"""
324 This is the regnode which can be reached by jumping forward by the value
325 of the \f(CWNEXT_OFF()\fR member of the regnode, or in a few cases for longer
326 jumps by the \f(CW\*(C`arg1\*(C'\fR field of the \f(CW\*(C`regnode_1\*(C'\fR structure. The subroutine
327 \&\f(CWregnext()\fR handles this transparently. In the majority of cases the
328 \&\f(CW\*(C`regnext\*(C'\fR for a regnode is the regnode which should be executed after the
329 current one has successfully matched, but in some cases this may not be
330 true. In loop control and branch control regnode types the regnext may
331 signify something special, for BRANCH nodes \f(CW\*(C`regnext\*(C'\fR is the
332 next BRANCH that should be executed if the current one fails execution,
333 and some loop control regnodes set the regnext to be the end of the loop
334 so they can jump to their cleanup if the current iteration fails to match.
335 .PP
336 Most regnode types do not create a branch in the execution flow, and
337 leaving aside optimizations the two concepts of "next" are the same.
338 For instance the \f(CW\*(C`regnext\*(C'\fR and \f(CW\*(C`REGNODE_AFTER\*(C'\fR of a SBOL opcode are
339 the same during compilation phase. The main place this is not true is
340 \&\f(CW\*(C`BRANCH\*(C'\fR regnodes where the \f(CW\*(C`REGNODE_AFTER\*(C'\fR represents the start of
341 the pattern in the branch and the \f(CW\*(C`regnext\*(C'\fR represents the linkage to
342 the next BRANCH should this one fail to match, or 0 if it is the last
343 branch. The looping logic for quantifiers also makes similar use of
344 the distinction between the two types, with \f(CW\*(C`REGNODE_AFTER\*(C'\fR being the
345 inside of the loop construct, and the \f(CW\*(C`regnext\*(C'\fR pointing at the end
346 of the loop.
347 .PP
348 During compilation the engine may not know what the regnext is for a
349 given node, so during compilation \f(CW\*(C`regnext\*(C'\fR is only used where it must
350 be used and is known to be correct. At the very end of the compilation
351 phase we walk the regex program and correct the regnext data as
352 appropriate, and also perform various optimizations which may result in
353 regnodes that were required during construction becoming redundant, or
354 we may replace a large regnode with a much smaller one and filling in the
355 gap with OPTIMIZED regnodes. Thus we might start with something like
356 this:
357 .PP
358 .Vb 5
359 \& BRANCH
360 \& EXACT "foo"
361 \& BRANCH
362 \& EXACT "bar"
363 \& EXACT "!"
364 .Ve
365 .PP
366 and replace it with something like:
367 .PP
368 .Vb 5
369 \& TRIE foo|bar
370 \& OPTIMIZED
371 \& OPTIMIZED
372 \& OPTIMIZED
373 \& EXACT "!"
374 .Ve
375 .PP
376 the \f(CW\*(C`REGNODE_AFTER\*(C'\fR for the \f(CW\*(C`TRIE\*(C'\fR node would be an \f(CW\*(C`OPTIMIZED\*(C'\fR
377 regnode, and in theory the \f(CW\*(C`regnext\*(C'\fR would be the same as the
378 \&\f(CW\*(C`REGNODE_AFTER\*(C'\fR. But it would be inefficient to execute the OPTIMIZED
379 regnode as a noop three times, so the optimizer fixes the \f(CW\*(C`regnext\*(C'\fR so
380 such nodes are skipped during execution phase.
381 .PP
382 During execution phases we use the \f(CWregnext()\fR almost exclusively, and
383 only use \f(CW\*(C`REGNODE_AFTER\*(C'\fR in special cases where it has a well defined
384 meaning for a given regnode type. For instance /x+/ results in
385 .PP
386 .Vb 3
387 \& PLUS
388 \& EXACT "x"
389 \& END
390 .Ve
391 .PP
392 the \f(CW\*(C`regnext\*(C'\fR of the \f(CW\*(C`PLUS\*(C'\fR regnode is the \f(CW\*(C`END\*(C'\fR regnode, and the
393 \&\f(CW\*(C`REGNODE_AFTER\*(C'\fR of the \f(CW\*(C`PLUS\*(C'\fR regnode is the \f(CW\*(C`EXACT\*(C'\fR regnode. The
394 \&\f(CW\*(C`regnext\*(C'\fR and \f(CW\*(C`REGNODE_AFTER\*(C'\fR of the \f(CW\*(C`EXACT\*(C'\fR regnode is the
395 \&\f(CW\*(C`END\*(C'\fR regnode.
396 .SH "Process Overview"
397 .IX Header "Process Overview"
398 Broadly speaking, performing a match of a string against a pattern
399 involves the following steps:
400 .IP "A. Compilation" 5
401 .IX Item "A. Compilation"
402 .RS 5
403 .PD 0
404 .IP "1. Parsing" 5
405 .IX Item "1. Parsing"
406 .IP "2. Peep\-hole optimisation and analysis" 5
407 .IX Item "2. Peep-hole optimisation and analysis"
408 .PD
409 .RE
410 .RS 5
411 .RE
412 .IP "B. Execution" 5
413 .IX Item "B. Execution"
414 .RS 5
415 .PD 0
416 .IP "3. Start position and no\-match optimisations" 5
417 .IX Item "3. Start position and no-match optimisations"
418 .IP "4. Program execution" 5
419 .IX Item "4. Program execution"
420 .PD
421 .RE
422 .RS 5
423 .RE
424 .PP
425 Where these steps occur in the actual execution of a perl program is
426 determined by whether the pattern involves interpolating any string
427 variables. If interpolation occurs, then compilation happens at run time. If it
428 does not, then compilation is performed at compile time. (The \f(CW\*(C`/o\*(C'\fR modifier changes this,
429 as does \f(CW\*(C`qr//\*(C'\fR to a certain extent.) The engine doesn\*(Aqt really care that
430 much.
431 .SS Compilation
432 .IX Subsection "Compilation"
433 This code resides primarily in \fIregcomp.c\fR, along with the header files
434 \&\fIregcomp.h\fR, \fIregexp.h\fR and \fIregnodes.h\fR.
435 .PP
436 Compilation starts with \f(CWpregcomp()\fR, which is mostly an initialisation
437 wrapper which farms work out to two other routines for the heavy lifting: the
438 first is \f(CWreg()\fR, which is the start point for parsing; the second,
439 \&\f(CWstudy_chunk()\fR, is responsible for optimisation.
440 .PP
441 Initialisation in \f(CWpregcomp()\fR mostly involves the creation and data\-filling
442 of a special structure, \f(CW\*(C`RExC_state_t\*(C'\fR (defined in \fIregcomp.c\fR).
443 Almost all internally\-used routines in \fIregcomp.h\fR take a pointer to one
444 of these structures as their first argument, with the name \f(CW\*(C`pRExC_state\*(C'\fR.
445 This structure is used to store the compilation state and contains many
446 fields. Likewise there are many macros which operate on this
447 variable: anything that looks like \f(CW\*(C`RExC_xxxx\*(C'\fR is a macro that operates on
448 this pointer/structure.
449 .PP
450 \&\f(CWreg()\fR is the start of the parse process. It is responsible for
451 parsing an arbitrary chunk of pattern up to either the end of the
452 string, or the first closing parenthesis it encounters in the pattern.
453 This means it can be used to parse the top\-level regex, or any section
454 inside of a grouping parenthesis. It also handles the "special parens"
455 that perl\*(Aqs regexes have. For instance when parsing \f(CW\*(C`/x(?:foo)y/\*(C'\fR,
456 \&\f(CWreg()\fR will at one point be called to parse from the "?" symbol up to
457 and including the ")".
458 .PP
459 Additionally, \f(CWreg()\fR is responsible for parsing the one or more
460 branches from the pattern, and for "finishing them off" by correctly
461 setting their next pointers. In order to do the parsing, it repeatedly
462 calls out to \f(CWregbranch()\fR, which is responsible for handling up to the
463 first \f(CW\*(C`|\*(C'\fR symbol it sees.
464 .PP
465 \&\f(CWregbranch()\fR in turn calls \f(CWregpiece()\fR which
466 handles "things" followed by a quantifier. In order to parse the
467 "things", \f(CWregatom()\fR is called. This is the lowest level routine, which
468 parses out constant strings, character classes, and the
469 various special symbols like \f(CW\*(C`$\*(C'\fR. If \f(CWregatom()\fR encounters a "("
470 character it in turn calls \f(CWreg()\fR.
471 .PP
472 There used to be two main passes involved in parsing, the first to
473 calculate the size of the compiled program, and the second to actually
474 compile it. But now there is only one main pass, with an initial crude
475 guess based on the length of the input pattern, which is increased if
476 necessary as parsing proceeds, and afterwards, trimmed to the actual
477 amount used.
478 .PP
479 However, it may happen that parsing must be restarted at the beginning
480 when various circumstances occur along the way. An example is if the
481 program turns out to be so large that there are jumps in it that won\*(Aqt
482 fit in the normal 16 bits available. There are two special regops that
483 can hold bigger jump destinations, BRANCHJ and LONGBRANCH. The parse is
484 restarted, and these are used instead of the normal shorter ones.
485 Whenever restarting the parse is required, the function returns failure
486 and sets a flag as to what needs to be done. This is passed up to the
487 top level routine which takes the appropriate action and restarts from
488 scratch. In the case of needing longer jumps, the \f(CW\*(C`RExC_use_BRANCHJ\*(C'\fR
489 flag is set in the \f(CW\*(C`RExC_state_t\*(C'\fR structure, which the functions know
490 to inspect before deciding how to do branches.
491 .PP
492 In most instances, the function that discovers the issue sets the causal
493 flag and returns failure immediately. "Parsing complications"
494 contains an explicit example of how this works. In other cases, such as
495 a forward reference to a numbered parenthetical grouping, we need to
496 finish the parse to know if that numbered grouping actually appears in
497 the pattern. In those cases, the parse is just redone at the end, with
498 the knowledge of how many groupings occur in it.
499 .PP
500 The routine \f(CWregtail()\fR is called by both \f(CWreg()\fR and \f(CWregbranch()\fR
501 in order to "set the tail pointer" correctly. When executing and
502 we get to the end of a branch, we need to go to the node following the
503 grouping parens. When parsing, however, we don\*(Aqt know where the end will
504 be until we get there, so when we do we must go back and update the
505 offsets as appropriate. \f(CW\*(C`regtail\*(C'\fR is used to make this easier.
506 .PP
507 A subtlety of the parsing process means that a regex like \f(CW\*(C`/foo/\*(C'\fR is
508 originally parsed into an alternation with a single branch. It is only
509 afterwards that the optimiser converts single branch alternations into the
510 simpler form.
511 .PP
512 \fIParse Call Graph and a Grammar\fR
513 .IX Subsection "Parse Call Graph and a Grammar"
514 .PP
515 The call graph looks like this:
516 .PP
517 .Vb 10
518 \& reg() # parse a top level regex, or inside of
519 \& # parens
520 \& regbranch() # parse a single branch of an alternation
521 \& regpiece() # parse a pattern followed by a quantifier
522 \& regatom() # parse a simple pattern
523 \& regclass() # used to handle a class
524 \& reg() # used to handle a parenthesised
525 \& # subpattern
526 \& ....
527 \& ...
528 \& regtail() # finish off the branch
529 \& ...
530 \& regtail() # finish off the branch sequence. Tie each
531 \& # branch\*(Aqs tail to the tail of the
532 \& # sequence
533 \& # (NEW) In Debug mode this is
534 \& # regtail_study().
535 .Ve
536 .PP
537 A grammar form might be something like this:
538 .PP
539 .Vb 11
540 \& atom : constant | class
541 \& quant : \*(Aq*\*(Aq | \*(Aq+\*(Aq | \*(Aq?\*(Aq | \*(Aq{min,max}\*(Aq
542 \& _branch: piece
543 \& | piece _branch
544 \& | nothing
545 \& branch: _branch
546 \& | _branch \*(Aq|\*(Aq branch
547 \& group : \*(Aq(\*(Aq branch \*(Aq)\*(Aq
548 \& _piece: atom | group
549 \& piece : _piece
550 \& | _piece quant
551 .Ve
552 .PP
553 \fIParsing complications\fR
554 .IX Subsection "Parsing complications"
555 .PP
556 The implication of the above description is that a pattern containing nested
557 parentheses will result in a call graph which cycles through \f(CWreg()\fR,
558 \&\f(CWregbranch()\fR, \f(CWregpiece()\fR, \f(CWregatom()\fR, \f(CWreg()\fR, \f(CWregbranch()\fR \fIetc\fR
559 multiple times, until the deepest level of nesting is reached. All the above
560 routines return a pointer to a \f(CW\*(C`regnode\*(C'\fR, which is usually the last regnode
561 added to the program. However, one complication is that \fBreg()\fR returns NULL
562 for parsing \f(CW\*(C`(?:)\*(C'\fR syntax for embedded modifiers, setting the flag
563 \&\f(CW\*(C`TRYAGAIN\*(C'\fR. The \f(CW\*(C`TRYAGAIN\*(C'\fR propagates upwards until it is captured, in
564 some cases by \f(CWregatom()\fR, but otherwise unconditionally by
565 \&\f(CWregbranch()\fR. Hence it will never be returned by \f(CWregbranch()\fR to
566 \&\f(CWreg()\fR. This flag permits patterns such as \f(CW\*(C`(?i)+\*(C'\fR to be detected as
567 errors (\fIQuantifier follows nothing in regex; marked by <\-\- HERE in m/(?i)+
568 <\-\- HERE /\fR).
569 .PP
570 Another complication is that the representation used for the program differs
571 if it needs to store Unicode, but it\*(Aqs not always possible to know for sure
572 whether it does until midway through parsing. The Unicode representation for
573 the program is larger, and cannot be matched as efficiently. (See "Unicode
574 and Localisation Support" below for more details as to why.) If the pattern
575 contains literal Unicode, it\*(Aqs obvious that the program needs to store
576 Unicode. Otherwise, the parser optimistically assumes that the more
577 efficient representation can be used, and starts sizing on this basis.
578 However, if it then encounters something in the pattern which must be stored
579 as Unicode, such as an \f(CW\*(C`\ex{...}\*(C'\fR escape sequence representing a character
580 literal, then this means that all previously calculated sizes need to be
581 redone, using values appropriate for the Unicode representation. This
582 is another instance where the parsing needs to be restarted, and it can
583 and is done immediately. The function returns failure, and sets the
584 flag \f(CW\*(C`RESTART_UTF8\*(C'\fR (encapsulated by using the macro \f(CW\*(C`REQUIRE_UTF8\*(C'\fR).
585 This restart request is propagated up the call chain in a similar
586 fashion, until it is "caught" in \f(CWPerl_re_op_compile()\fR, which marks
587 the pattern as containing Unicode, and restarts the sizing pass. It is
588 also possible for constructions within run\-time code blocks to turn out
589 to need Unicode representation., which is signalled by
590 \&\f(CWS_compile_runtime_code()\fR returning false to \f(CWPerl_re_op_compile()\fR.
591 .PP
592 The restart was previously implemented using a \f(CW\*(C`longjmp\*(C'\fR in \f(CWregatom()\fR
593 back to a \f(CW\*(C`setjmp\*(C'\fR in \f(CWPerl_re_op_compile()\fR, but this proved to be
594 problematic as the latter is a large function containing many automatic
595 variables, which interact badly with the emergent control flow of \f(CW\*(C`setjmp\*(C'\fR.
596 .PP
597 \fIDebug Output\fR
598 .IX Subsection "Debug Output"
599 .PP
600 Starting in the 5.9.x development version of perl you can \f(CW\*(C`use re
601 Debug => \*(AqPARSE\*(Aq\*(C'\fR to see some trace information about the parse
602 process. We will start with some simple patterns and build up to more
603 complex patterns.
604 .PP
605 So when we parse \f(CW\*(C`/foo/\*(C'\fR we see something like the following table. The
606 left shows what is being parsed, and the number indicates where the next regop
607 would go. The stuff on the right is the trace output of the graph. The
608 names are chosen to be short to make it less dense on the screen. \*(Aqtsdy\*(Aq
609 is a special form of \f(CWregtail()\fR which does some extra analysis.
610 .PP
611 .Vb 6
612 \& >foo< 1 reg
613 \& brnc
614 \& piec
615 \& atom
616 \& >< 4 tsdy~ EXACT <foo> (EXACT) (1)
617 \& ~ attach to END (3) offset to 2
618 .Ve
619 .PP
620 The resulting program then looks like:
621 .PP
622 .Vb 2
623 \& 1: EXACT <foo>(3)
624 \& 3: END(0)
625 .Ve
626 .PP
627 As you can see, even though we parsed out a branch and a piece, it was ultimately
628 only an atom. The final program shows us how things work. We have an \f(CW\*(C`EXACT\*(C'\fR regop,
629 followed by an \f(CW\*(C`END\*(C'\fR regop. The number in parens indicates where the \f(CW\*(C`regnext\*(C'\fR of
630 the node goes. The \f(CW\*(C`regnext\*(C'\fR of an \f(CW\*(C`END\*(C'\fR regop is unused, as \f(CW\*(C`END\*(C'\fR regops mean
631 we have successfully matched. The number on the left indicates the position of
632 the regop in the regnode array.
633 .PP
634 Now let\*(Aqs try a harder pattern. We will add a quantifier, so now we have the pattern
635 \&\f(CW\*(C`/foo+/\*(C'\fR. We will see that \f(CWregbranch()\fR calls \f(CWregpiece()\fR twice.
636 .PP
637 .Vb 10
638 \& >foo+< 1 reg
639 \& brnc
640 \& piec
641 \& atom
642 \& >o+< 3 piec
643 \& atom
644 \& >< 6 tail~ EXACT <fo> (1)
645 \& 7 tsdy~ EXACT <fo> (EXACT) (1)
646 \& ~ PLUS (END) (3)
647 \& ~ attach to END (6) offset to 3
648 .Ve
649 .PP
650 And we end up with the program:
651 .PP
652 .Vb 4
653 \& 1: EXACT <fo>(3)
654 \& 3: PLUS(6)
655 \& 4: EXACT <o>(0)
656 \& 6: END(0)
657 .Ve
658 .PP
659 Now we have a special case. The \f(CW\*(C`EXACT\*(C'\fR regop has a \f(CW\*(C`regnext\*(C'\fR of 0. This is
660 because if it matches it should try to match itself again. The \f(CW\*(C`PLUS\*(C'\fR regop
661 handles the actual failure of the \f(CW\*(C`EXACT\*(C'\fR regop and acts appropriately (going
662 to regnode 6 if the \f(CW\*(C`EXACT\*(C'\fR matched at least once, or failing if it didn\*(Aqt).
663 .PP
664 Now for something much more complex: \f(CW\*(C`/x(?:foo*|b[a][rR])(foo|bar)$/\*(C'\fR
665 .PP
666 .Vb 10
667 \& >x(?:foo*|b... 1 reg
668 \& brnc
669 \& piec
670 \& atom
671 \& >(?:foo*|b[... 3 piec
672 \& atom
673 \& >?:foo*|b[a... reg
674 \& >foo*|b[a][... brnc
675 \& piec
676 \& atom
677 \& >o*|b[a][rR... 5 piec
678 \& atom
679 \& >|b[a][rR])... 8 tail~ EXACT <fo> (3)
680 \& >b[a][rR])(... 9 brnc
681 \& 10 piec
682 \& atom
683 \& >[a][rR])(f... 12 piec
684 \& atom
685 \& >a][rR])(fo... clas
686 \& >[rR])(foo|... 14 tail~ EXACT <b> (10)
687 \& piec
688 \& atom
689 \& >rR])(foo|b... clas
690 \& >)(foo|bar)... 25 tail~ EXACT <a> (12)
691 \& tail~ BRANCH (3)
692 \& 26 tsdy~ BRANCH (END) (9)
693 \& ~ attach to TAIL (25) offset to 16
694 \& tsdy~ EXACT <fo> (EXACT) (4)
695 \& ~ STAR (END) (6)
696 \& ~ attach to TAIL (25) offset to 19
697 \& tsdy~ EXACT <b> (EXACT) (10)
698 \& ~ EXACT <a> (EXACT) (12)
699 \& ~ ANYOF[Rr] (END) (14)
700 \& ~ attach to TAIL (25) offset to 11
701 \& >(foo|bar)$< tail~ EXACT <x> (1)
702 \& piec
703 \& atom
704 \& >foo|bar)$< reg
705 \& 28 brnc
706 \& piec
707 \& atom
708 \& >|bar)$< 31 tail~ OPEN1 (26)
709 \& >bar)$< brnc
710 \& 32 piec
711 \& atom
712 \& >)$< 34 tail~ BRANCH (28)
713 \& 36 tsdy~ BRANCH (END) (31)
714 \& ~ attach to CLOSE1 (34) offset to 3
715 \& tsdy~ EXACT <foo> (EXACT) (29)
716 \& ~ attach to CLOSE1 (34) offset to 5
717 \& tsdy~ EXACT <bar> (EXACT) (32)
718 \& ~ attach to CLOSE1 (34) offset to 2
719 \& >$< tail~ BRANCH (3)
720 \& ~ BRANCH (9)
721 \& ~ TAIL (25)
722 \& piec
723 \& atom
724 \& >< 37 tail~ OPEN1 (26)
725 \& ~ BRANCH (28)
726 \& ~ BRANCH (31)
727 \& ~ CLOSE1 (34)
728 \& 38 tsdy~ EXACT <x> (EXACT) (1)
729 \& ~ BRANCH (END) (3)
730 \& ~ BRANCH (END) (9)
731 \& ~ TAIL (END) (25)
732 \& ~ OPEN1 (END) (26)
733 \& ~ BRANCH (END) (28)
734 \& ~ BRANCH (END) (31)
735 \& ~ CLOSE1 (END) (34)
736 \& ~ EOL (END) (36)
737 \& ~ attach to END (37) offset to 1
738 .Ve
739 .PP
740 Resulting in the program
741 .PP
742 .Vb 10
743 \& 1: EXACT <x>(3)
744 \& 3: BRANCH(9)
745 \& 4: EXACT <fo>(6)
746 \& 6: STAR(26)
747 \& 7: EXACT <o>(0)
748 \& 9: BRANCH(25)
749 \& 10: EXACT <ba>(14)
750 \& 12: OPTIMIZED (2 nodes)
751 \& 14: ANYOF[Rr](26)
752 \& 25: TAIL(26)
753 \& 26: OPEN1(28)
754 \& 28: TRIE\-EXACT(34)
755 \& [StS:1 Wds:2 Cs:6 Uq:5 #Sts:7 Mn:3 Mx:3 Stcls:bf]
756 \& <foo>
757 \& <bar>
758 \& 30: OPTIMIZED (4 nodes)
759 \& 34: CLOSE1(36)
760 \& 36: EOL(37)
761 \& 37: END(0)
762 .Ve
763 .PP
764 Here we can see a much more complex program, with various optimisations in
765 play. At regnode 10 we see an example where a character class with only
766 one character in it was turned into an \f(CW\*(C`EXACT\*(C'\fR node. We can also see where
767 an entire alternation was turned into a \f(CW\*(C`TRIE\-EXACT\*(C'\fR node. As a consequence,
768 some of the regnodes have been marked as optimised away. We can see that
769 the \f(CW\*(C`$\*(C'\fR symbol has been converted into an \f(CW\*(C`EOL\*(C'\fR regop, a special piece of
770 code that looks for \f(CW\*(C`\en\*(C'\fR or the end of the string.
771 .PP
772 The next pointer for \f(CW\*(C`BRANCH\*(C'\fRes is interesting in that it points at where
773 execution should go if the branch fails. When executing, if the engine
774 tries to traverse from a branch to a \f(CW\*(C`regnext\*(C'\fR that isn\*(Aqt a branch then
775 the engine will know that the entire set of branches has failed.
776 .PP
777 \fIPeep\-hole Optimisation and Analysis\fR
778 .IX Subsection "Peep-hole Optimisation and Analysis"
779 .PP
780 The regular expression engine can be a weighty tool to wield. On long
781 strings and complex patterns it can end up having to do a lot of work
782 to find a match, and even more to decide that no match is possible.
783 Consider a situation like the following pattern.
784 .PP
785 .Vb 1
786 \& \*(Aqababababababababababab\*(Aq =~ /(a|b)*z/
787 .Ve
788 .PP
789 The \f(CW\*(C`(a|b)*\*(C'\fR part can match at every char in the string, and then fail
790 every time because there is no \f(CW\*(C`z\*(C'\fR in the string. So obviously we can
791 avoid using the regex engine unless there is a \f(CW\*(C`z\*(C'\fR in the string.
792 Likewise in a pattern like:
793 .PP
794 .Vb 1
795 \& /foo(\ew+)bar/
796 .Ve
797 .PP
798 In this case we know that the string must contain a \f(CW\*(C`foo\*(C'\fR which must be
799 followed by \f(CW\*(C`bar\*(C'\fR. We can use Fast Boyer\-Moore matching as implemented
800 in \f(CWfbm_instr()\fR to find the location of these strings. If they don\*(Aqt exist
801 then we don\*(Aqt need to resort to the much more expensive regex engine.
802 Even better, if they do exist then we can use their positions to
803 reduce the search space that the regex engine needs to cover to determine
804 if the entire pattern matches.
805 .PP
806 There are various aspects of the pattern that can be used to facilitate
807 optimisations along these lines:
808 .IP \(bu 5
809 anchored fixed strings
810 .IP \(bu 5
811 floating fixed strings
812 .IP \(bu 5
813 minimum and maximum length requirements
814 .IP \(bu 5
815 start class
816 .IP \(bu 5
817 Beginning/End of line positions
818 .PP
819 Another form of optimisation that can occur is the post\-parse "peep\-hole"
820 optimisation, where inefficient constructs are replaced by more efficient
821 constructs. The \f(CW\*(C`TAIL\*(C'\fR regops which are used during parsing to mark the end
822 of branches and the end of groups are examples of this. These regops are used
823 as place\-holders during construction and "always match" so they can be
824 "optimised away" by making the things that point to the \f(CW\*(C`TAIL\*(C'\fR point to the
825 thing that \f(CW\*(C`TAIL\*(C'\fR points to, thus "skipping" the node.
826 .PP
827 Another optimisation that can occur is that of "\f(CW\*(C`EXACT\*(C'\fR merging" which is
828 where two consecutive \f(CW\*(C`EXACT\*(C'\fR nodes are merged into a single
829 regop. An even more aggressive form of this is that a branch
830 sequence of the form \f(CW\*(C`EXACT BRANCH ... EXACT\*(C'\fR can be converted into a
831 \&\f(CW\*(C`TRIE\-EXACT\*(C'\fR regop.
832 .PP
833 All of this occurs in the routine \f(CWstudy_chunk()\fR which uses a special
834 structure \f(CW\*(C`scan_data_t\*(C'\fR to store the analysis that it has performed, and
835 does the "peep\-hole" optimisations as it goes.
836 .PP
837 The code involved in \f(CWstudy_chunk()\fR is extremely cryptic. Be careful. :\-)
838 .SS Execution
839 .IX Subsection "Execution"
840 Execution of a regex generally involves two phases, the first being
841 finding the start point in the string where we should match from,
842 and the second being running the regop interpreter.
843 .PP
844 If we can tell that there is no valid start point then we don\*(Aqt bother running
845 the interpreter at all. Likewise, if we know from the analysis phase that we
846 cannot detect a short\-cut to the start position, we go straight to the
847 interpreter.
848 .PP
849 The two entry points are \f(CWre_intuit_start()\fR and \f(CWpregexec()\fR. These routines
850 have a somewhat incestuous relationship with overlap between their functions,
851 and \f(CWpregexec()\fR may even call \f(CWre_intuit_start()\fR on its own. Nevertheless
852 other parts of the perl source code may call into either, or both.
853 .PP
854 Execution of the interpreter itself used to be recursive, but thanks to the
855 efforts of Dave Mitchell in the 5.9.x development track, that has changed: now an
856 internal stack is maintained on the heap and the routine is fully
857 iterative. This can make it tricky as the code is quite conservative
858 about what state it stores, with the result that two consecutive lines in the
859 code can actually be running in totally different contexts due to the
860 simulated recursion.
861 .PP
862 \fIStart position and no\-match optimisations\fR
863 .IX Subsection "Start position and no-match optimisations"
864 .PP
865 \&\f(CWre_intuit_start()\fR is responsible for handling start points and no\-match
866 optimisations as determined by the results of the analysis done by
867 \&\f(CWstudy_chunk()\fR (and described in "Peep\-hole Optimisation and Analysis").
868 .PP
869 The basic structure of this routine is to try to find the start\- and/or
870 end\-points of where the pattern could match, and to ensure that the string
871 is long enough to match the pattern. It tries to use more efficient
872 methods over less efficient methods and may involve considerable
873 cross\-checking of constraints to find the place in the string that matches.
874 For instance it may try to determine that a given fixed string must be
875 not only present but a certain number of chars before the end of the
876 string, or whatever.
877 .PP
878 It calls several other routines, such as \f(CWfbm_instr()\fR which does
879 Fast Boyer Moore matching and \f(CWfind_byclass()\fR which is responsible for
880 finding the start using the first mandatory regop in the program.
881 .PP
882 When the optimisation criteria have been satisfied, \f(CWreg_try()\fR is called
883 to perform the match.
884 .PP
885 \fIProgram execution\fR
886 .IX Subsection "Program execution"
887 .PP
888 \&\f(CWpregexec()\fR is the main entry point for running a regex. It contains
889 support for initialising the regex interpreter\*(Aqs state, running
890 \&\f(CWre_intuit_start()\fR if needed, and running the interpreter on the string
891 from various start positions as needed. When it is necessary to use
892 the regex interpreter \f(CWpregexec()\fR calls \f(CWregtry()\fR.
893 .PP
894 \&\f(CWregtry()\fR is the entry point into the regex interpreter. It expects
895 as arguments a pointer to a \f(CW\*(C`regmatch_info\*(C'\fR structure and a pointer to
896 a string. It returns an integer 1 for success and a 0 for failure.
897 It is basically a set\-up wrapper around \f(CWregmatch()\fR.
898 .PP
899 \&\f(CW\*(C`regmatch\*(C'\fR is the main "recursive loop" of the interpreter. It is
900 basically a giant switch statement that implements a state machine, where
901 the possible states are the regops themselves, plus a number of additional
902 intermediate and failure states. A few of the states are implemented as
903 subroutines but the bulk are inline code.
904 .SH MISCELLANEOUS
905 .IX Header "MISCELLANEOUS"
906 .SS "Unicode and Localisation Support"
907 .IX Subsection "Unicode and Localisation Support"
908 When dealing with strings containing characters that cannot be represented
909 using an eight\-bit character set, perl uses an internal representation
910 that is a permissive version of Unicode\*(Aqs UTF\-8 encoding[2]. This uses single
911 bytes to represent characters from the ASCII character set, and sequences
912 of two or more bytes for all other characters. (See perlunitut
913 for more information about the relationship between UTF\-8 and perl\*(Aqs
914 encoding, utf8. The difference isn\*(Aqt important for this discussion.)
915 .PP
916 No matter how you look at it, Unicode support is going to be a pain in a
917 regex engine. Tricks that might be fine when you have 256 possible
918 characters often won\*(Aqt scale to handle the size of the UTF\-8 character
919 set. Things you can take for granted with ASCII may not be true with
920 Unicode. For instance, in ASCII, it is safe to assume that
921 \&\f(CW\*(C`sizeof(char1) == sizeof(char2)\*(C'\fR, but in UTF\-8 it isn\*(Aqt. Unicode case folding is
922 vastly more complex than the simple rules of ASCII, and even when not
923 using Unicode but only localised single byte encodings, things can get
924 tricky (for example, \fBLATIN SMALL LETTER SHARP S\fR (U+00DF, ß)
925 should match \*(AqSS\*(Aq in localised case\-insensitive matching).
926 .PP
927 Making things worse is that UTF\-8 support was a later addition to the
928 regex engine (as it was to perl) and this necessarily made things a lot
929 more complicated. Obviously it is easier to design a regex engine with
930 Unicode support in mind from the beginning than it is to retrofit it to
931 one that wasn\*(Aqt.
932 .PP
933 Nearly all regops that involve looking at the input string have
934 two cases, one for UTF\-8, and one not. In fact, it\*(Aqs often more complex
935 than that, as the pattern may be UTF\-8 as well.
936 .PP
937 Care must be taken when making changes to make sure that you handle
938 UTF\-8 properly, both at compile time and at execution time, including
939 when the string and pattern are mismatched.
940 .SS "Base Structures"
941 .IX Subsection "Base Structures"
942 The \f(CW\*(C`regexp\*(C'\fR structure described in perlreapi is common to all
943 regex engines. Two of its fields are intended for the private use
944 of the regex engine that compiled the pattern. These are the
945 \&\f(CW\*(C`intflags\*(C'\fR and pprivate members. The \f(CW\*(C`pprivate\*(C'\fR is a void pointer to
946 an arbitrary structure whose use and management is the responsibility
947 of the compiling engine. perl will never modify either of these
948 values. In the case of the stock engine the structure pointed to by
949 \&\f(CW\*(C`pprivate\*(C'\fR is called \f(CW\*(C`regexp_internal\*(C'\fR.
950 .PP
951 Its \f(CW\*(C`pprivate\*(C'\fR and \f(CW\*(C`intflags\*(C'\fR fields contain data
952 specific to each engine.
953 .PP
954 There are two structures used to store a compiled regular expression.
955 One, the \f(CW\*(C`regexp\*(C'\fR structure described in perlreapi is populated by
956 the engine currently being used and some of its fields read by perl to
957 implement things such as the stringification of \f(CW\*(C`qr//\*(C'\fR.
958 .PP
959 The other structure is pointed to by the \f(CW\*(C`regexp\*(C'\fR struct\*(Aqs
960 \&\f(CW\*(C`pprivate\*(C'\fR and is in addition to \f(CW\*(C`intflags\*(C'\fR in the same struct
961 considered to be the property of the regex engine which compiled the
962 regular expression;
963 .PP
964 The regexp structure contains all the data that perl needs to be aware of
965 to properly work with the regular expression. It includes data about
966 optimisations that perl can use to determine if the regex engine should
967 really be used, and various other control info that is needed to properly
968 execute patterns in various contexts such as is the pattern anchored in
969 some way, or what flags were used during the compile, or whether the
970 program contains special constructs that perl needs to be aware of.
971 .PP
972 In addition it contains two fields that are intended for the private use
973 of the regex engine that compiled the pattern. These are the \f(CW\*(C`intflags\*(C'\fR
974 and pprivate members. The \f(CW\*(C`pprivate\*(C'\fR is a void pointer to an arbitrary
975 structure whose use and management is the responsibility of the compiling
976 engine. perl will never modify either of these values.
977 .PP
978 As mentioned earlier, in the case of the default engines, the \f(CW\*(C`pprivate\*(C'\fR
979 will be a pointer to a regexp_internal structure which holds the compiled
980 program and any additional data that is private to the regex engine
981 implementation.
982 .PP
983 \fIPerl\*(Aqs \fR\f(CI\*(C`pprivate\*(C'\fR\fI structure\fR
984 .IX Subsection "Perl's pprivate structure"
985 .PP
986 The following structure is used as the \f(CW\*(C`pprivate\*(C'\fR struct by perl\*(Aqs
987 regex engine. Since it is specific to perl it is only of curiosity
988 value to other engine implementations.
989 .PP
990 .Vb 8
991 \& typedef struct regexp_internal {
992 \& regnode *regstclass;
993 \& struct reg_data *data;
994 \& struct reg_code_blocks *code_blocks;
995 \& U32 proglen;
996 \& U32 name_list_idx;
997 \& regnode program[1];
998 \& } regexp_internal;
999 .Ve
1000 .PP
1001 Description of the attributes is as follows:
1002 .ie n .IP """regstclass""" 5
1003 .el .IP \f(CWregstclass\fR 5
1004 .IX Item "regstclass"
1005 Special regop that is used by \f(CWre_intuit_start()\fR to check if a pattern
1006 can match at a certain position. For instance if the regex engine knows
1007 that the pattern must start with a \*(AqZ\*(Aq then it can scan the string until
1008 it finds one and then launch the regex engine from there. The routine
1009 that handles this is called \f(CWfind_by_class()\fR. Sometimes this field
1010 points at a regop embedded in the program, and sometimes it points at
1011 an independent synthetic regop that has been constructed by the optimiser.
1012 .ie n .IP """data""" 5
1013 .el .IP \f(CWdata\fR 5
1014 .IX Item "data"
1015 This field points at a \f(CW\*(C`reg_data\*(C'\fR structure, which is defined as follows
1016 .Sp
1017 .Vb 5
1018 \& struct reg_data {
1019 \& U32 count;
1020 \& U8 *what;
1021 \& void* data[1];
1022 \& };
1023 .Ve
1024 .Sp
1025 This structure is used for handling data structures that the regex engine
1026 needs to handle specially during a clone or free operation on the compiled
1027 product. Each element in the data array has a corresponding element in the
1028 what array. During compilation regops that need special structures stored
1029 will add an element to each array using the \fBadd_data()\fR routine and then store
1030 the index in the regop.
1031 .Sp
1032 In modern perls the 0th element of this structure is reserved and is NEVER
1033 used to store anything of use. This is to allow things that need to index
1034 into this array to represent "no value".
1035 .ie n .IP """code_blocks""" 5
1036 .el .IP \f(CWcode_blocks\fR 5
1037 .IX Item "code_blocks"
1038 This optional structure is used to manage \f(CW\*(C`(?{})\*(C'\fR constructs in the
1039 pattern. It is made up of the following structures.
1040 .Sp
1041 .Vb 7
1042 \& /* record the position of a (?{...}) within a pattern */
1043 \& struct reg_code_block {
1044 \& STRLEN start;
1045 \& STRLEN end;
1046 \& OP *block;
1047 \& REGEXP *src_regex;
1048 \& };
1049 \&
1050 \& /* array of reg_code_block\*(Aqs plus header info */
1051 \& struct reg_code_blocks {
1052 \& int refcnt; /* we may be pointed to from a regex
1053 \& and from the savestack */
1054 \& int count; /* how many code blocks */
1055 \& struct reg_code_block *cb; /* array of reg_code_block\*(Aqs */
1056 \& };
1057 .Ve
1058 .ie n .IP """proglen""" 5
1059 .el .IP \f(CWproglen\fR 5
1060 .IX Item "proglen"
1061 Stores the length of the compiled program in units of regops.
1062 .ie n .IP """name_list_idx""" 5
1063 .el .IP \f(CWname_list_idx\fR 5
1064 .IX Item "name_list_idx"
1065 This is the index into the data array where an AV is stored that contains
1066 the names of any named capture buffers in the pattern, should there be
1067 any. This is only used in the debugging version of the regex engine and
1068 when RXp_PAREN_NAMES(prog) is true. It will be 0 if there is no such data.
1069 .ie n .IP """program""" 5
1070 .el .IP \f(CWprogram\fR 5
1071 .IX Item "program"
1072 Compiled program. Inlined into the structure so the entire struct can be
1073 treated as a single blob.
1074 .SH "SEE ALSO"
1075 .IX Header "SEE ALSO"
1076 perlreapi
1077 .PP
1078 perlre
1079 .PP
1080 perlunitut
1081 .SH AUTHOR
1082 .IX Header "AUTHOR"
1083 by Yves Orton, 2006.
1084 .PP
1085 With excerpts from Perl, and contributions and suggestions from
1086 Ronald J. Kimball, Dave Mitchell, Dominic Dunlop, Mark Jason Dominus,
1087 Stephen McCamant, and David Landgren.
1088 .PP
1089 Now maintained by Perl 5 Porters.
1090 .SH LICENCE
1091 .IX Header "LICENCE"
1092 Same terms as Perl.
1093 .SH REFERENCES
1094 .IX Header "REFERENCES"
1095 [1] <https://perl.plover.com/Rx/paper/>
1096 .PP
1097 [2] <https://www.unicode.org/>