This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Promote v5.36 usage and feature bundles doc
[perl5.git] / regexp.h
1 /*    regexp.h
2  *
3  *    Copyright (C) 1993, 1994, 1996, 1997, 1999, 2000, 2001, 2003,
4  *    2005, 2006, 2007, 2008 by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  * Definitions etc. for regexp(3) routines.
13  *
14  * Caveat:  this is V8 regexp(3) [actually, a reimplementation thereof],
15  * not the System V one.
16  */
17 #ifndef PLUGGABLE_RE_EXTENSION
18 /* we don't want to include this stuff if we are inside of
19    an external regex engine based on the core one - like re 'debug'*/
20
21 #  include "utf8.h"
22
23 typedef SSize_t regnode_offset;
24
25 struct regnode_meta {
26     U8 type;
27     U8 arg_len;
28     U8 arg_len_varies;
29     U8 off_by_arg;
30 };
31
32 struct regnode {
33     U8  flags;
34     U8  type;
35     U16 next_off;
36 };
37
38 typedef struct regnode regnode;
39
40 struct reg_substr_data;
41
42 struct reg_data;
43
44 struct regexp_engine;
45 struct regexp;
46
47 struct reg_substr_datum {
48     SSize_t min_offset; /* min pos (in chars) that substr must appear */
49     SSize_t max_offset  /* max pos (in chars) that substr must appear */;
50     SV *substr;         /* non-utf8 variant */
51     SV *utf8_substr;    /* utf8 variant */
52     SSize_t end_shift;  /* how many fixed chars must end the string */
53 };
54 struct reg_substr_data {
55     U8      check_ix;   /* index into data[] of check substr */
56     struct reg_substr_datum data[3];    /* Actual array */
57 };
58
59 #  ifdef PERL_ANY_COW
60 #    define SV_SAVED_COPY   SV *saved_copy; /* If non-NULL, SV which is COW from original */
61 #  else
62 #    define SV_SAVED_COPY
63 #  endif
64
65 /* offsets within a string of a particular /(.)/ capture */
66
67 typedef struct regexp_paren_pair {
68     SSize_t start;
69     SSize_t end;
70     /* 'start_tmp' records a new opening position before the matching end
71      * has been found, so that the old start and end values are still
72      * valid, e.g.
73      *    "abc" =~ /(.(?{print "[$1]"}))+/
74      *outputs [][a][b]
75      * This field is not part of the API.  */
76     SSize_t start_tmp;
77 } regexp_paren_pair;
78
79 #  if defined(PERL_IN_REGCOMP_C) || defined(PERL_IN_UTF8_C)
80 #    define _invlist_union(a, b, output) _invlist_union_maybe_complement_2nd(a, b, FALSE, output)
81 #    define _invlist_intersection(a, b, output) _invlist_intersection_maybe_complement_2nd(a, b, FALSE, output)
82
83 /* Subtracting b from a leaves in a everything that was there that isn't in b,
84  * that is the intersection of a with b's complement */
85 #    define _invlist_subtract(a, b, output) _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
86 #  endif
87
88 /* record the position of a (?{...}) within a pattern */
89
90 struct reg_code_block {
91     STRLEN start;
92     STRLEN end;
93     OP     *block;
94     REGEXP *src_regex;
95 };
96
97 /* array of reg_code_block's plus header info */
98
99 struct reg_code_blocks {
100     int refcnt; /* we may be pointed to from a regex and from the savestack */
101     int  count;    /* how many code blocks */
102     struct reg_code_block *cb; /* array of reg_code_block's */
103 };
104
105
106 /*
107 = for apidoc AyT||regexp
108   The regexp/REGEXP struct, see L<perlreapi> for further documentation
109   on the individual fields. The struct is ordered so that the most
110   commonly used fields are placed at the start.
111
112   Any patch that adds items to this struct will need to include
113   changes to F<sv.c> (C<Perl_re_dup()>) and F<regcomp.c>
114   (C<pregfree()>). This involves freeing or cloning items in the
115   regexp's data array based on the data item's type.
116 */
117
118 typedef struct regexp {
119     _XPV_HEAD;
120     const struct regexp_engine* engine; /* what engine created this regexp? */
121     REGEXP *mother_re; /* what re is this a lightweight copy of? */
122     HV *paren_names;   /* Optional hash of paren names */
123
124     /*----------------------------------------------------------------------
125      * Information about the match that the perl core uses to manage things
126      */
127
128     U32 extflags;      /* Flags used both externally and internally */
129     U32 nparens;       /* number of capture buffers */
130     SSize_t minlen;    /* minimum possible number of chars in string to match */
131     SSize_t minlenret; /* mininum possible number of chars in $& */
132     STRLEN gofs;       /* chars left of pos that we search from */
133                        /* substring data about strings that must appear in
134                         * the final match, used for optimisations */
135     struct reg_substr_data *substrs;
136
137     /* private engine specific data */
138
139     void *pprivate;    /* Data private to the regex engine which
140                         * created this object. */
141     U32 intflags;      /* Engine Specific Internal flags */
142
143     /*----------------------------------------------------------------------
144      * Data about the last/current match. These are modified during matching
145      */
146
147     U32 lastparen;           /* highest close paren matched ($+) */
148     regexp_paren_pair *offs; /* Array of offsets for (@-) and (@+) */
149     char **recurse_locinput; /* used to detect infinite recursion, XXX: move to internal */
150     U32 lastcloseparen;      /* last close paren matched ($^N) */
151
152     /*---------------------------------------------------------------------- */
153
154     /* offset from wrapped to the start of precomp */
155     PERL_BITFIELD32 pre_prefix:4;
156
157     /* original flags used to compile the pattern, may differ from
158      * extflags in various ways */
159     PERL_BITFIELD32 compflags:9;
160
161     /*---------------------------------------------------------------------- */
162
163     char *subbeg;       /* saved or original string so \digit works forever. */
164     SV_SAVED_COPY       /* If non-NULL, SV which is COW from original */
165     SSize_t sublen;     /* Length of string pointed by subbeg */
166     SSize_t suboffset;  /* byte offset of subbeg from logical start of str */
167     SSize_t subcoffset; /* suboffset equiv, but in chars (for @-/@+) */
168     SSize_t maxlen;  /* minimum possible number of chars in string to match */
169
170     /*---------------------------------------------------------------------- */
171
172
173     CV *qr_anoncv;      /* the anon sub wrapped round qr/(?{..})/ */
174 } regexp;
175
176
177 #  define RXp_PAREN_NAMES(rx)   ((rx)->paren_names)
178
179 /* used for high speed searches */
180 typedef struct re_scream_pos_data_s
181 {
182     char **scream_olds;         /* match pos */
183     SSize_t *scream_pos;        /* Internal iterator of scream. */
184 } re_scream_pos_data;
185
186 /* regexp_engine structure. This is the dispatch table for regexes.
187  * Any regex engine implementation must be able to build one of these.
188  */
189 typedef struct regexp_engine {
190     REGEXP* (*comp) (pTHX_ SV * const pattern, U32 flags);
191     I32     (*exec) (pTHX_ REGEXP * const rx, char* stringarg, char* strend,
192                      char* strbeg, SSize_t minend, SV* sv,
193                      void* data, U32 flags);
194     char*   (*intuit) (pTHX_
195                         REGEXP * const rx,
196                         SV *sv,
197                         const char * const strbeg,
198                         char *strpos,
199                         char *strend,
200                         const U32 flags,
201                        re_scream_pos_data *data);
202     SV*     (*checkstr) (pTHX_ REGEXP * const rx);
203     void    (*rxfree) (pTHX_ REGEXP * const rx);
204     void    (*numbered_buff_FETCH) (pTHX_ REGEXP * const rx, const I32 paren,
205                                     SV * const sv);
206     void    (*numbered_buff_STORE) (pTHX_ REGEXP * const rx, const I32 paren,
207                                    SV const * const value);
208     I32     (*numbered_buff_LENGTH) (pTHX_ REGEXP * const rx, const SV * const sv,
209                                     const I32 paren);
210     SV*     (*named_buff) (pTHX_ REGEXP * const rx, SV * const key,
211                            SV * const value, const U32 flags);
212     SV*     (*named_buff_iter) (pTHX_ REGEXP * const rx, const SV * const lastkey,
213                                 const U32 flags);
214     SV*     (*qr_package)(pTHX_ REGEXP * const rx);
215 #  ifdef USE_ITHREADS
216     void*   (*dupe) (pTHX_ REGEXP * const rx, CLONE_PARAMS *param);
217 #  endif
218     REGEXP* (*op_comp) (pTHX_ SV ** const patternp, int pat_count,
219                     OP *expr, const struct regexp_engine* eng,
220                     REGEXP *old_re,
221                     bool *is_bare_re, U32 orig_rx_flags, U32 pm_flags);
222 } regexp_engine;
223
224 /*
225   These are passed to the numbered capture variable callbacks as the
226   paren name. >= 1 is reserved for actual numbered captures, i.e. $1,
227   $2 etc.
228 */
229 #  define RX_BUFF_IDX_CARET_PREMATCH  -5 /* ${^PREMATCH}  */
230 #  define RX_BUFF_IDX_CARET_POSTMATCH -4 /* ${^POSTMATCH} */
231 #  define RX_BUFF_IDX_CARET_FULLMATCH -3 /* ${^MATCH}     */
232 #  define RX_BUFF_IDX_PREMATCH        -2 /* $` */
233 #  define RX_BUFF_IDX_POSTMATCH       -1 /* $' */
234 #  define RX_BUFF_IDX_FULLMATCH        0 /* $& */
235
236 /*
237   Flags that are passed to the named_buff and named_buff_iter
238   callbacks above. Those routines are called from universal.c via the
239   Tie::Hash::NamedCapture interface for %+ and %- and the re::
240   functions in the same file.
241 */
242
243 /* The Tie::Hash::NamedCapture operation this is part of, if any */
244 #  define RXapif_FETCH     0x0001
245 #  define RXapif_STORE     0x0002
246 #  define RXapif_DELETE    0x0004
247 #  define RXapif_CLEAR     0x0008
248 #  define RXapif_EXISTS    0x0010
249 #  define RXapif_SCALAR    0x0020
250 #  define RXapif_FIRSTKEY  0x0040
251 #  define RXapif_NEXTKEY   0x0080
252
253 /* Whether %+ or %- is being operated on */
254 #  define RXapif_ONE       0x0100 /* %+ */
255 #  define RXapif_ALL       0x0200 /* %- */
256
257 /* Whether this is being called from a re:: function */
258 #  define RXapif_REGNAME         0x0400
259 #  define RXapif_REGNAMES        0x0800
260 #  define RXapif_REGNAMES_COUNT  0x1000
261
262 /*
263 =for apidoc Am|REGEXP *|SvRX|SV *sv
264
265 Convenience macro to get the REGEXP from a SV.  This is approximately
266 equivalent to the following snippet:
267
268     if (SvMAGICAL(sv))
269         mg_get(sv);
270     if (SvROK(sv))
271         sv = MUTABLE_SV(SvRV(sv));
272     if (SvTYPE(sv) == SVt_REGEXP)
273         return (REGEXP*) sv;
274
275 C<NULL> will be returned if a REGEXP* is not found.
276
277 =for apidoc Am|bool|SvRXOK|SV* sv
278
279 Returns a boolean indicating whether the SV (or the one it references)
280 is a REGEXP.
281
282 If you want to do something with the REGEXP* later use SvRX instead
283 and check for NULL.
284
285 =cut
286 */
287
288 #  define SvRX(sv)   (Perl_get_re_arg(aTHX_ sv))
289 #  define SvRXOK(sv) cBOOL(Perl_get_re_arg(aTHX_ sv))
290
291
292 /* Flags stored in regexp->extflags
293  * These are used by code external to the regexp engine
294  *
295  * Note that the flags whose names start with RXf_PMf_ are defined in
296  * op_reg_common.h, being copied from the parallel flags of op_pmflags
297  *
298  * NOTE: if you modify any RXf flags you should run regen.pl or
299  * regen/regcomp.pl so that regnodes.h is updated with the changes.
300  *
301  */
302
303 #  include "op_reg_common.h"
304
305 #  define RXf_PMf_STD_PMMOD     (RXf_PMf_MULTILINE|RXf_PMf_SINGLELINE|RXf_PMf_FOLD|RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE|RXf_PMf_NOCAPTURE)
306
307 #  define CASE_STD_PMMOD_FLAGS_PARSE_SET(pmfl, x_count)                       \
308     case IGNORE_PAT_MOD:    *(pmfl) |= RXf_PMf_FOLD;       break;           \
309     case MULTILINE_PAT_MOD: *(pmfl) |= RXf_PMf_MULTILINE;  break;           \
310     case SINGLE_PAT_MOD:    *(pmfl) |= RXf_PMf_SINGLELINE; break;           \
311     case XTENDED_PAT_MOD:   if (x_count == 0) {                             \
312                                 *(pmfl) |= RXf_PMf_EXTENDED;                \
313                                 *(pmfl) &= ~RXf_PMf_EXTENDED_MORE;          \
314                             }                                               \
315                             else {                                          \
316                                 *(pmfl) |= RXf_PMf_EXTENDED                 \
317                                           |RXf_PMf_EXTENDED_MORE;           \
318                             }                                               \
319                             (x_count)++; break;                             \
320     case NOCAPTURE_PAT_MOD: *(pmfl) |= RXf_PMf_NOCAPTURE; break;
321
322 /* Note, includes charset ones, assumes 0 is the default for them */
323 #  define STD_PMMOD_FLAGS_CLEAR(pmfl)                        \
324     *(pmfl) &= ~(RXf_PMf_FOLD|RXf_PMf_MULTILINE|RXf_PMf_SINGLELINE|RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE|RXf_PMf_CHARSET|RXf_PMf_NOCAPTURE)
325
326 /* chars and strings used as regex pattern modifiers
327  * Singular is a 'c'har, plural is a "string"
328  *
329  * NOTE, KEEPCOPY was originally 'k', but was changed to 'p' for preserve
330  * for compatibility reasons with Regexp::Common which highjacked (?k:...)
331  * for its own uses. So 'k' is out as well.
332  */
333 #  define DEFAULT_PAT_MOD      '^'    /* Short for all the default modifiers */
334 #  define EXEC_PAT_MOD         'e'
335 #  define KEEPCOPY_PAT_MOD     'p'
336 #  define NOCAPTURE_PAT_MOD    'n'
337 #  define ONCE_PAT_MOD         'o'
338 #  define GLOBAL_PAT_MOD       'g'
339 #  define CONTINUE_PAT_MOD     'c'
340 #  define MULTILINE_PAT_MOD    'm'
341 #  define SINGLE_PAT_MOD       's'
342 #  define IGNORE_PAT_MOD       'i'
343 #  define XTENDED_PAT_MOD      'x'
344 #  define NONDESTRUCT_PAT_MOD  'r'
345 #  define LOCALE_PAT_MOD       'l'
346 #  define UNICODE_PAT_MOD      'u'
347 #  define DEPENDS_PAT_MOD      'd'
348 #  define ASCII_RESTRICT_PAT_MOD 'a'
349
350 #  define ONCE_PAT_MODS        "o"
351 #  define KEEPCOPY_PAT_MODS    "p"
352 #  define NOCAPTURE_PAT_MODS   "n"
353 #  define EXEC_PAT_MODS        "e"
354 #  define LOOP_PAT_MODS        "gc"
355 #  define NONDESTRUCT_PAT_MODS "r"
356 #  define LOCALE_PAT_MODS      "l"
357 #  define UNICODE_PAT_MODS     "u"
358 #  define DEPENDS_PAT_MODS     "d"
359 #  define ASCII_RESTRICT_PAT_MODS "a"
360 #  define ASCII_MORE_RESTRICT_PAT_MODS "aa"
361
362 /* This string is expected by regcomp.c to be ordered so that the first
363  * character is the flag in bit RXf_PMf_STD_PMMOD_SHIFT of extflags; the next
364  * character is bit +1, etc. */
365 #  define STD_PAT_MODS        "msixxn"
366
367 #  define CHARSET_PAT_MODS    ASCII_RESTRICT_PAT_MODS DEPENDS_PAT_MODS LOCALE_PAT_MODS UNICODE_PAT_MODS
368
369 /* This string is expected by XS_re_regexp_pattern() in universal.c to be ordered
370  * so that the first character is the flag in bit RXf_PMf_STD_PMMOD_SHIFT of
371  * extflags; the next character is in bit +1, etc. */
372 #  define INT_PAT_MODS    STD_PAT_MODS    KEEPCOPY_PAT_MODS
373
374 #  define EXT_PAT_MODS    ONCE_PAT_MODS   KEEPCOPY_PAT_MODS  NOCAPTURE_PAT_MODS
375 #  define QR_PAT_MODS     STD_PAT_MODS    EXT_PAT_MODS     CHARSET_PAT_MODS
376 #  define M_PAT_MODS      QR_PAT_MODS     LOOP_PAT_MODS
377 #  define S_PAT_MODS      M_PAT_MODS      EXEC_PAT_MODS      NONDESTRUCT_PAT_MODS
378
379 /*
380  * NOTE: if you modify any RXf flags you should run regen.pl or
381  * regen/regcomp.pl so that regnodes.h is updated with the changes.
382  *
383  */
384
385 /*
386   Set in Perl_pmruntime for a split. Will be used by regex engines to
387   check whether they should set RXf_SKIPWHITE
388 */
389 #  define RXf_SPLIT   RXf_PMf_SPLIT
390
391 /* Currently the regex flags occupy a single 32-bit word.  Not all bits are
392  * currently used.  The lower bits are shared with their corresponding PMf flag
393  * bits, up to but not including _RXf_PMf_SHIFT_NEXT.  The unused bits
394  * immediately follow; finally the used RXf-only (unshared) bits, so that the
395  * highest bit in the word is used.  This gathers all the unused bits as a pool
396  * in the middle, like so: 11111111111111110000001111111111
397  * where the '1's represent used bits, and the '0's unused.  This design allows
398  * us to allocate off one end of the pool if we need to add a shared bit, and
399  * off the other end if we need a non-shared bit, without disturbing the other
400  * bits.  This maximizes the likelihood of being able to change things without
401  * breaking binary compatibility.
402  *
403  * To add shared bits, do so in op_reg_common.h.  This should change
404  * _RXf_PMf_SHIFT_NEXT so that things won't compile.  Then come to regexp.h and
405  * op.h and adjust the constant adders in the definitions of RXf_BASE_SHIFT and
406  * Pmf_BASE_SHIFT down by the number of shared bits you added.  That's it.
407  * Things should be binary compatible.  But if either of these gets to having
408  * to subtract rather than add, leave at 0 and instead adjust all the entries
409  * that are in terms of it.  But if the first one of those is already
410  * RXf_BASE_SHIFT+0, there are no bits left, and a redesign is in order.
411  *
412  * To remove unshared bits, just delete its entry.  If you're where breaking
413  * binary compatibility is ok to do, you might want to adjust things to move
414  * the newly opened space so that it gets absorbed into the common pool.
415  *
416  * To add unshared bits, first use up any gaps in the middle.  Otherwise,
417  * allocate off the low end until you get to RXf_BASE_SHIFT+0.  If that isn't
418  * enough, move RXf_BASE_SHIFT down (if possible) and add the new bit at the
419  * other end instead; this preserves binary compatibility.
420  *
421  * For the regexp bits, PL_reg_extflags_name[] in regnodes.h has a comment
422  * giving which bits are used/unused */
423
424 #  define RXf_BASE_SHIFT (_RXf_PMf_SHIFT_NEXT + 2)
425
426 /* What we have seen */
427 #  define RXf_NO_INPLACE_SUBST  (1U<<(RXf_BASE_SHIFT+2))
428 #  define RXf_EVAL_SEEN         (1U<<(RXf_BASE_SHIFT+3))
429
430 /* Special */
431 #  define RXf_UNBOUNDED_QUANTIFIER_SEEN   (1U<<(RXf_BASE_SHIFT+4))
432 #  define RXf_CHECK_ALL         (1U<<(RXf_BASE_SHIFT+5))
433
434 /* UTF8 related */
435 #  define RXf_MATCH_UTF8        (1U<<(RXf_BASE_SHIFT+6)) /* $1 etc are utf8 */
436
437 /* Intuit related */
438 #  define RXf_USE_INTUIT_NOML   (1U<<(RXf_BASE_SHIFT+7))
439 #  define RXf_USE_INTUIT_ML     (1U<<(RXf_BASE_SHIFT+8))
440 #  define RXf_INTUIT_TAIL       (1U<<(RXf_BASE_SHIFT+9))
441 #  define RXf_USE_INTUIT        (RXf_USE_INTUIT_NOML|RXf_USE_INTUIT_ML)
442
443 /* Do we have some sort of anchor? */
444 #  define RXf_IS_ANCHORED       (1U<<(RXf_BASE_SHIFT+10))
445
446 /* Copy and tainted info */
447 #  define RXf_COPY_DONE         (1U<<(RXf_BASE_SHIFT+11))
448
449 /* post-execution: $1 et al are tainted */
450 #  define RXf_TAINTED_SEEN      (1U<<(RXf_BASE_SHIFT+12))
451 /* this pattern was tainted during compilation */
452 #  define RXf_TAINTED           (1U<<(RXf_BASE_SHIFT+13))
453
454 /* Flags indicating special patterns */
455 #  define RXf_START_ONLY        (1U<<(RXf_BASE_SHIFT+14)) /* Pattern is /^/ */
456 #  define RXf_SKIPWHITE         (1U<<(RXf_BASE_SHIFT+15)) /* Pattern is for a */
457                                                           /* split " " */
458 #  define RXf_WHITE             (1U<<(RXf_BASE_SHIFT+16)) /* Pattern is /\s+/ */
459 #  define RXf_NULL              (1U<<(RXf_BASE_SHIFT+17)) /* Pattern is // */
460
461 /* See comments at the beginning of these defines about adding bits.  The
462  * highest bit position should be used, so that if RXf_BASE_SHIFT gets
463  * increased, the #error below will be triggered so that you will be reminded
464  * to adjust things at the other end to keep the bit positions unchanged */
465 #  if RXf_BASE_SHIFT+17 > 31
466 #     error Too many RXf_PMf bits used.  See comments at beginning of these for what to do
467 #  endif
468
469 /*
470  * NOTE: if you modify any RXf flags you should run regen.pl or
471  * regen/regcomp.pl so that regnodes.h is updated with the changes.
472  *
473  */
474
475 #  ifdef NO_TAINT_SUPPORT
476 #    define RX_ISTAINTED(rx_sv)           0
477 #    define RXp_ISTAINTED(prog)           0
478 #    define RX_TAINT_on(rx_sv)            NOOP
479 #    define RXp_MATCH_TAINTED(prog)       0
480 #    define RX_MATCH_TAINTED(rx_sv)       0
481 #    define RXp_MATCH_TAINTED_on(prog)    NOOP
482 #    define RX_MATCH_TAINTED_on(rx_sv)    NOOP
483 #    define RXp_MATCH_TAINTED_off(prog)   NOOP
484 #    define RX_MATCH_TAINTED_off(rx_sv)   NOOP
485 #  else
486 #    define RX_ISTAINTED(rx_sv)           (RX_EXTFLAGS(rx_sv) & RXf_TAINTED)
487 #    define RXp_ISTAINTED(prog)           (RXp_EXTFLAGS(prog) & RXf_TAINTED)
488 #    define RX_TAINT_on(rx_sv)            (RX_EXTFLAGS(rx_sv) |= RXf_TAINTED)
489 #    define RXp_MATCH_TAINTED(prog)       (RXp_EXTFLAGS(prog) & RXf_TAINTED_SEEN)
490 #    define RX_MATCH_TAINTED(rx_sv)       (RX_EXTFLAGS(rx_sv) & RXf_TAINTED_SEEN)
491 #    define RXp_MATCH_TAINTED_on(prog)    (RXp_EXTFLAGS(prog) |= RXf_TAINTED_SEEN)
492 #    define RX_MATCH_TAINTED_on(rx_sv)    (RX_EXTFLAGS(rx_sv) |= RXf_TAINTED_SEEN)
493 #    define RXp_MATCH_TAINTED_off(prog)   (RXp_EXTFLAGS(prog) &= ~RXf_TAINTED_SEEN)
494 #    define RX_MATCH_TAINTED_off(rx_sv)   (RX_EXTFLAGS(rx_sv) &= ~RXf_TAINTED_SEEN)
495 #  endif
496
497 #  define RXp_HAS_CUTGROUP(prog)          ((prog)->intflags & PREGf_CUTGROUP_SEEN)
498
499 #  define RX_MATCH_TAINTED_set(rx_sv, t)  ((t) \
500                                         ? RX_MATCH_TAINTED_on(rx_sv) \
501                                         : RX_MATCH_TAINTED_off(rx_sv))
502
503 #  define RXp_MATCH_COPIED(prog)          (RXp_EXTFLAGS(prog) & RXf_COPY_DONE)
504 #  define RX_MATCH_COPIED(rx_sv)          (RX_EXTFLAGS(rx_sv) & RXf_COPY_DONE)
505 #  define RXp_MATCH_COPIED_on(prog)       (RXp_EXTFLAGS(prog) |= RXf_COPY_DONE)
506 #  define RX_MATCH_COPIED_on(rx_sv)       (RX_EXTFLAGS(rx_sv) |= RXf_COPY_DONE)
507 #  define RXp_MATCH_COPIED_off(prog)      (RXp_EXTFLAGS(prog) &= ~RXf_COPY_DONE)
508 #  define RX_MATCH_COPIED_off(rx_sv)      (RX_EXTFLAGS(rx_sv) &= ~RXf_COPY_DONE)
509 #  define RX_MATCH_COPIED_set(rx_sv,t)    ((t) \
510                                          ? RX_MATCH_COPIED_on(rx_sv) \
511                                          : RX_MATCH_COPIED_off(rx_sv))
512
513 #  define RXp_EXTFLAGS(rx)                ((rx)->extflags)
514 #  define RXp_COMPFLAGS(rx)               ((rx)->compflags)
515
516 /* For source compatibility. We used to store these explicitly.  */
517 #  define RX_PRECOMP(rx_sv)              (RX_WRAPPED(rx_sv) \
518                                             + ReANY(rx_sv)->pre_prefix)
519 #  define RX_PRECOMP_const(rx_sv)        (RX_WRAPPED_const(rx_sv) \
520                                             + ReANY(rx_sv)->pre_prefix)
521 /* FIXME? Are we hardcoding too much here and constraining plugin extension
522    writers? Specifically, the value 1 assumes that the wrapped version always
523    has exactly one character at the end, a ')'. Will that always be true?  */
524 #  define RX_PRELEN(rx_sv)                (RX_WRAPLEN(rx_sv) \
525                                             - ReANY(rx_sv)->pre_prefix - 1)
526
527 #  define RX_WRAPPED(rx_sv)               SvPVX(rx_sv)
528 #  define RX_WRAPPED_const(rx_sv)         SvPVX_const(rx_sv)
529 #  define RX_WRAPLEN(rx_sv)               SvCUR(rx_sv)
530 #  define RX_CHECK_SUBSTR(rx_sv)          (ReANY(rx_sv)->check_substr)
531 #  define RX_REFCNT(rx_sv)                SvREFCNT(rx_sv)
532 #  define RX_EXTFLAGS(rx_sv)              RXp_EXTFLAGS(ReANY(rx_sv))
533 #  define RX_COMPFLAGS(rx_sv)             RXp_COMPFLAGS(ReANY(rx_sv))
534 #  define RXp_ENGINE(prog)                ((prog)->engine)
535 #  define RX_ENGINE(rx_sv)                (RXp_ENGINE(ReANY(rx_sv)))
536 #  define RXp_SUBBEG(prog)                (prog->subbeg)
537 #  define RX_SUBBEG(rx_sv)                (RXp_SUBBEG(ReANY(rx_sv)))
538 #  define RXp_SUBOFFSET(prog)             (prog->suboffset)
539 #  define RX_SUBOFFSET(rx_sv)             (RXp_SUBOFFSET(ReANY(rx_sv)))
540 #  define RX_SUBCOFFSET(rx_sv)            (ReANY(rx_sv)->subcoffset)
541 #  define RXp_OFFS(prog)                  (prog->offs)
542 #  define RX_OFFS(rx_sv)                  (RXp_OFFS(ReANY(rx_sv)))
543 #  define RXp_NPARENS(prog)               (prog->nparens)
544 #  define RX_NPARENS(rx_sv)               (RXp_NPARENS(ReANY(rx_sv)))
545 #  define RX_SUBLEN(rx_sv)                (ReANY(rx_sv)->sublen)
546 #  define RXp_MINLEN(prog)                (prog->minlen)
547 #  define RX_MINLEN(rx_sv)                (RXp_MINLEN(ReANY(rx_sv)))
548 #  define RXp_MINLENRET(prog)             (prog->minlenret)
549 #  define RX_MINLENRET(rx_sv)             (RXp_MINLENRET(ReANY(rx_sv)))
550 #  define RXp_GOFS(prog)                  (prog->gofs)
551 #  define RX_GOFS(rx_sv)                  (RXp_GOFS(ReANY(rx_sv)))
552 #  define RX_LASTPAREN(rx_sv)             (ReANY(rx_sv)->lastparen)
553 #  define RX_LASTCLOSEPAREN(rx_sv)        (ReANY(rx_sv)->lastcloseparen)
554 #  define RXp_SAVED_COPY(prog)            (prog->saved_copy)
555 #  define RX_SAVED_COPY(rx_sv)            (RXp_SAVED_COPY(ReANY(rx_sv)))
556 /* last match was zero-length */
557 #  define RXp_ZERO_LEN(prog) \
558         (RXp_OFFS(prog)[0].start + (SSize_t)RXp_GOFS(prog) \
559           == RXp_OFFS(prog)[0].end)
560 #  define RX_ZERO_LEN(rx_sv)              (RXp_ZERO_LEN(ReANY(rx_sv)))
561
562 #endif /* PLUGGABLE_RE_EXTENSION */
563
564 /* Stuff that needs to be included in the pluggable extension goes below here */
565
566 #ifdef PERL_ANY_COW
567 #  define RXp_MATCH_COPY_FREE(prog) \
568         STMT_START {if (RXp_SAVED_COPY(prog)) { \
569             SV_CHECK_THINKFIRST_COW_DROP(RXp_SAVED_COPY(prog)); \
570         } \
571         if (RXp_MATCH_COPIED(prog)) { \
572             Safefree(RXp_SUBBEG(prog)); \
573             RXp_MATCH_COPIED_off(prog); \
574         }} STMT_END
575 #else
576 #  define RXp_MATCH_COPY_FREE(prog) \
577         STMT_START {if (RXp_MATCH_COPIED(prog)) { \
578             Safefree(RXp_SUBBEG(prog)); \
579             RXp_MATCH_COPIED_off(prog); \
580         }} STMT_END
581 #endif
582 #define RX_MATCH_COPY_FREE(rx_sv)       RXp_MATCH_COPY_FREE(ReANY(rx_sv))
583
584 #define RXp_MATCH_UTF8(prog)            (RXp_EXTFLAGS(prog) & RXf_MATCH_UTF8)
585 #define RX_MATCH_UTF8(rx_sv)            (RX_EXTFLAGS(rx_sv) & RXf_MATCH_UTF8)
586 #define RXp_MATCH_UTF8_on(prog)         (RXp_EXTFLAGS(prog) |= RXf_MATCH_UTF8)
587 #define RX_MATCH_UTF8_on(rx_sv)         (RXp_MATCH_UTF8_on(ReANY(rx_sv)))
588 #define RXp_MATCH_UTF8_off(prog)        (RXp_EXTFLAGS(prog) &= ~RXf_MATCH_UTF8)
589 #define RX_MATCH_UTF8_off(rx_sv)        (RXp_MATCH_UTF8_off(ReANY(rx_sv))
590 #define RXp_MATCH_UTF8_set(prog, t)     ((t) \
591                                         ? RXp_MATCH_UTF8_on(prog) \
592                                         : RXp_MATCH_UTF8_off(prog))
593 #define RX_MATCH_UTF8_set(rx_sv, t)     (RXp_MATCH_UTF8_set(ReANY(rx_sv), t))
594
595 /* Whether the pattern stored at RX_WRAPPED is in UTF-8  */
596 #define RX_UTF8(rx_sv)                  SvUTF8(rx_sv)
597
598
599 /* bits in flags arg of Perl_regexec_flags() */
600
601 #define REXEC_COPY_STR  0x01    /* Need to copy the string for captures. */
602 #define REXEC_CHECKED   0x02    /* re_intuit_start() already called. */
603 #define REXEC_SCREAM    0x04    /* currently unused. */
604 #define REXEC_IGNOREPOS 0x08    /* use stringarg, not pos(), for \G match */
605 #define REXEC_NOT_FIRST 0x10    /* This is another iteration of //g:
606                                    no need to copy string again */
607
608                                      /* under REXEC_COPY_STR, it's ok for the
609                                         engine (modulo PL_sawamperand etc)
610                                         to skip copying: ... */
611 #define REXEC_COPY_SKIP_PRE  0x20    /* ...the $` part of the string, or */
612 #define REXEC_COPY_SKIP_POST 0x40    /* ...the $' part of the string */
613 #define REXEC_FAIL_ON_UNDERFLOW 0x80 /* fail the match if $& would start before
614                                         the start pos (so s/.\G// would fail
615                                         on second iteration */
616
617 #if defined(PERL_USE_GCC_BRACE_GROUPS)
618 #  define ReREFCNT_inc(re)                                              \
619     ({                                                                  \
620         /* This is here to generate a casting warning if incorrect.  */ \
621         REGEXP *const _rerefcnt_inc = (re);                             \
622         assert(SvTYPE(_rerefcnt_inc) == SVt_REGEXP);                    \
623         SvREFCNT_inc(_rerefcnt_inc);                                    \
624         _rerefcnt_inc;                                                  \
625     })
626 #  define ReREFCNT_dec(re)                                              \
627     ({                                                                  \
628         /* This is here to generate a casting warning if incorrect.  */ \
629         REGEXP *const _rerefcnt_dec = (re);                             \
630         SvREFCNT_dec(_rerefcnt_dec);                                    \
631     })
632 #else
633 #  define ReREFCNT_dec(re)      SvREFCNT_dec(re)
634 #  define ReREFCNT_inc(re)      ((REGEXP *) SvREFCNT_inc(re))
635 #endif
636 #define ReANY(re)               Perl_ReANY((const REGEXP *)(re))
637
638 /* FIXME for plugins. */
639
640 #define FBMcf_TAIL_DOLLAR       1
641 #define FBMcf_TAIL_DOLLARM      2
642 #define FBMcf_TAIL_Z            4
643 #define FBMcf_TAIL_z            8
644 #define FBMcf_TAIL              (FBMcf_TAIL_DOLLAR|FBMcf_TAIL_DOLLARM|FBMcf_TAIL_Z|FBMcf_TAIL_z)
645
646 #define FBMrf_MULTILINE 1
647
648 struct regmatch_state;
649 struct regmatch_slab;
650
651 /* like regmatch_info_aux, but contains extra fields only needed if the
652  * pattern contains (?{}). If used, is snuck into the second slot in the
653  * regmatch_state stack at the start of execution */
654
655 typedef struct {
656     regexp *rex;
657     PMOP    *curpm;     /* saved PL_curpm */
658 #ifdef PERL_ANY_COW
659     SV      *saved_copy; /* saved saved_copy field from rex */
660 #endif
661     char    *subbeg;    /* saved subbeg     field from rex */
662     STRLEN  sublen;     /* saved sublen     field from rex */
663     STRLEN  suboffset;  /* saved suboffset  field from rex */
664     STRLEN  subcoffset; /* saved subcoffset field from rex */
665     SV      *sv;        /* $_  during (?{}) */
666     MAGIC   *pos_magic; /* pos() magic attached to $_ */
667     SSize_t pos;        /* the original value of pos() in pos_magic */
668     U8      pos_flags;  /* flags to be restored; currently only MGf_BYTES*/
669 } regmatch_info_aux_eval;
670
671
672 /* fields that logically  live in regmatch_info, but which need cleaning
673  * up on croak(), and so are instead are snuck into the first slot in
674  * the regmatch_state stack at the start of execution */
675
676 typedef struct {
677     regmatch_info_aux_eval *info_aux_eval;
678     struct regmatch_state *old_regmatch_state; /* saved PL_regmatch_state */
679     struct regmatch_slab  *old_regmatch_slab;  /* saved PL_regmatch_slab */
680     char *poscache;     /* S-L cache of fail positions of WHILEMs */
681 } regmatch_info_aux;
682
683
684 /*
685 =for apidoc Ay||regmatch_info
686 Some basic information about the current match that is created by
687 Perl_regexec_flags and then passed to regtry(), regmatch() etc.
688 It is allocated as a local var on the stack, so nothing should be
689 stored in it that needs preserving or clearing up on croak().
690 For that, see the aux_info and aux_info_eval members of the
691 regmatch_state union.
692
693 =cut
694 */
695
696 typedef struct {
697     REGEXP *prog;        /* the regex being executed */
698     const char * strbeg; /* real start of string */
699     char *strend;        /* one byte beyond last char of match string */
700     char *till;          /* matches shorter than this fail (see minlen arg) */
701     SV *sv;              /* the SV string currently being matched */
702     char *ganch;         /* position of \G anchor */
703     char *cutpoint;      /* (*COMMIT) position (if any) */
704     regmatch_info_aux      *info_aux; /* extra fields that need cleanup */
705     regmatch_info_aux_eval *info_aux_eval; /* extra saved state for (?{}) */
706     I32  poscache_maxiter; /* how many whilems todo before S-L cache kicks in */
707     I32  poscache_iter;    /* current countdown from _maxiter to zero */
708     STRLEN poscache_size;  /* size of regmatch_info_aux.poscache */
709     bool intuit;    /* re_intuit_start() is the top-level caller */
710     bool is_utf8_pat;    /* regex is utf8 */
711     bool is_utf8_target; /* string being matched is utf8 */
712     bool warned; /* we have issued a recursion warning; no need for more */
713 } regmatch_info;
714
715
716 /* structures for holding and saving the state maintained by regmatch() */
717
718 #ifndef MAX_RECURSE_EVAL_NOCHANGE_DEPTH
719 #  define MAX_RECURSE_EVAL_NOCHANGE_DEPTH 10
720 #endif
721
722 /* The +1 is because everything matches itself, which isn't included in
723  * MAX_FOLD_FROMS; the +2 is based on the current Unicode standards needs, and
724  * is unlikely to change.  An assertion should fail in regexec.c if it is too
725  * low.  It is needed for certain edge cases involving multi-character folds
726  * when the first component also participates in a fold individually. */
727 #define MAX_MATCHES (MAX_FOLD_FROMS + 1 + 2)
728
729 struct next_matchable_info {
730     U8     first_byte_mask;
731     U8     first_byte_anded;
732     U32    mask32;
733     U32    anded32;
734     PERL_INT_FAST8_T count; /* Negative means not initialized */
735     PERL_UINT_FAST8_T min_length;
736     PERL_UINT_FAST8_T max_length;
737     PERL_UINT_FAST8_T initial_definitive;
738     PERL_UINT_FAST8_T initial_exact;
739     PERL_UINT_FAST8_T lengths[MAX_MATCHES];
740
741     /* The size is from trial and error, and could change with new Unicode
742      * standards, in which case there is an assertion that should start
743      * failing.  This size could be calculated in one of the regen scripts
744      * dealing with Unicode, but khw thinks the likelihood of it changing is
745      * low enough that it isn't worth the effort. */
746     U8 matches[18];
747 };
748
749 typedef I32 CHECKPOINT;
750
751 typedef struct regmatch_state {
752     int resume_state;           /* where to jump to on return */
753     char *locinput;             /* where to backtrack in string on failure */
754     char *loceol;
755     U8 *sr0;                    /* position of start of script run, or NULL */
756
757     union {
758
759         /* the 'info_aux' and 'info_aux_eval' union members are cuckoos in
760          * the nest. They aren't saved backtrack state; rather they
761          * represent one or two extra chunks of data that need allocating
762          * at the start of a match. These fields would logically live in
763          * the regmatch_info struct, except that is allocated on the
764          * C stack, and these fields are all things that require cleanup
765          * after a croak(), when the stack is lost.
766          * As a convenience, we just use the first 1 or 2 regmatch_state
767          * slots to store this info, as we will be allocating a slab of
768          * these anyway. Otherwise we'd have to malloc and then free them,
769          * or allocate them on the save stack (where they will get
770          * realloced if the save stack grows).
771          * info_aux contains the extra fields that are always needed;
772          * info_aux_eval contains extra fields that only needed if
773          * the pattern contains code blocks
774          * We split them into two separate structs to avoid increasing
775          * the size of the union.
776          */
777
778         regmatch_info_aux info_aux;
779
780         regmatch_info_aux_eval info_aux_eval;
781
782         /* this is a fake union member that matches the first element
783          * of each member that needs to store positive backtrack
784          * information */
785         struct {
786             struct regmatch_state *prev_yes_state;
787         } yes;
788
789         /* branchlike members */
790         /* this is a fake union member that matches the first elements
791          * of each member that needs to behave like a branch */
792         struct {
793             /* this first element must match u.yes */
794             struct regmatch_state *prev_yes_state;
795             U32 lastparen;
796             U32 lastcloseparen;
797             CHECKPOINT cp;
798
799         } branchlike;
800
801         struct {
802             /* the first elements must match u.branchlike */
803             struct regmatch_state *prev_yes_state;
804             U32 lastparen;
805             U32 lastcloseparen;
806             CHECKPOINT cp;
807
808             regnode *next_branch; /* next branch node */
809         } branch;
810
811         struct {
812             /* the first elements must match u.branchlike */
813             struct regmatch_state *prev_yes_state;
814             U32 lastparen;
815             U32 lastcloseparen;
816             CHECKPOINT cp;
817
818             U32         accepted; /* how many accepting states left */
819             bool        longfold;/* saw a fold with a 1->n char mapping */
820             U16         *jump;  /* positive offsets from me */
821             regnode     *me;    /* Which node am I - needed for jump tries*/
822             U8          *firstpos;/* pos in string of first trie match */
823             U32         firstchars;/* len in chars of firstpos from start */
824             U16         nextword;/* next word to try */
825             U16         topword; /* longest accepted word */
826         } trie;
827
828         /* special types - these members are used to store state for special
829            regops like eval, if/then, lookaround and the markpoint state */
830         struct {
831             /* this first element must match u.yes */
832             struct regmatch_state *prev_yes_state;
833             struct regmatch_state *prev_curlyx;
834             struct regmatch_state *prev_eval;
835             REGEXP      *prev_rex;
836             CHECKPOINT  cp;     /* remember current savestack indexes */
837             CHECKPOINT  lastcp;
838             U32         close_paren; /* which close bracket is our end (+1) */
839             regnode     *B;     /* the node following us  */
840             char        *prev_recurse_locinput;
841         } eval;
842
843         struct {
844             /* this first element must match u.yes */
845             struct regmatch_state *prev_yes_state;
846             I32 wanted;
847             I32 logical;        /* saved copy of 'logical' var */
848             U8  count;          /* number of beginning positions */
849             char *start;
850             char *end;
851             regnode  *me; /* the IFMATCH/SUSPEND/UNLESSM node  */
852             char *prev_match_end;
853         } ifmatch; /* and SUSPEND/UNLESSM */
854
855         struct {
856             /* this first element must match u.yes */
857             struct regmatch_state *prev_yes_state;
858             struct regmatch_state *prev_mark;
859             SV* mark_name;
860             char *mark_loc;
861         } mark;
862
863         struct {
864             int val;
865         } keeper;
866
867         /* quantifiers - these members are used for storing state for
868            the regops used to implement quantifiers */
869         struct {
870             /* this first element must match u.yes */
871             struct regmatch_state *prev_yes_state;
872             struct regmatch_state *prev_curlyx; /* previous cur_curlyx */
873             regnode     *me;    /* the CURLYX node  */
874             regnode     *B;     /* the B node in /A*B/  */
875             CHECKPOINT  cp;     /* remember current savestack index */
876             bool        minmod;
877             int         parenfloor;/* how far back to strip paren data */
878
879             /* these two are modified by WHILEM */
880             int         count;  /* how many instances of A we've matched */
881             char        *lastloc;/* where previous A matched (0-len detect) */
882         } curlyx;
883
884         struct {
885             /* this first element must match u.yes */
886             struct regmatch_state *prev_yes_state;
887             struct regmatch_state *save_curlyx;
888             CHECKPOINT  cp;     /* remember current savestack indexes */
889             CHECKPOINT  lastcp;
890             char        *save_lastloc;  /* previous curlyx.lastloc */
891             I32         cache_offset;
892             I32         cache_mask;
893         } whilem;
894
895         struct {
896             /* this first element must match u.yes */
897             struct regmatch_state *prev_yes_state;
898             CHECKPOINT cp;
899             U32 lastparen;
900             U32 lastcloseparen;
901             I32 alen;           /* length of first-matched A string */
902             I32 count;
903             bool minmod;
904             regnode *A, *B;     /* the nodes corresponding to /A*B/  */
905             regnode *me;        /* the curlym node */
906             struct next_matchable_info Binfo;
907         } curlym;
908
909         struct {
910             U32 paren;
911             CHECKPOINT cp;
912             U32 lastparen;
913             U32 lastcloseparen;
914             char *maxpos;       /* highest possible point in string to match */
915             char *oldloc;       /* the previous locinput */
916             int count;
917             int min, max;       /* {m,n} */
918             regnode *A, *B;     /* the nodes corresponding to /A*B/  */
919             struct next_matchable_info Binfo;
920         } curly; /* and CURLYN/PLUS/STAR */
921
922     } u;
923 } regmatch_state;
924
925
926
927 /* how many regmatch_state structs to allocate as a single slab.
928  * We do it in 4K blocks for efficiency. The "3" is 2 for the next/prev
929  * pointers, plus 1 for any mythical malloc overhead. */
930
931 #define PERL_REGMATCH_SLAB_SLOTS \
932     ((4096 - 3 * sizeof (void*)) / sizeof(regmatch_state))
933
934 typedef struct regmatch_slab {
935     regmatch_state states[PERL_REGMATCH_SLAB_SLOTS];
936     struct regmatch_slab *prev, *next;
937 } regmatch_slab;
938
939
940
941 /*
942  * ex: set ts=8 sts=4 sw=4 et:
943  */