5f9c1a22c8e243bb6418553723f74144a20258c3
[p5sagit/p5-mst-13.2.git] / pod / perlreapi.pod
1 =head1 NAME
2
3 perlreapi - perl regular expression plugin interface
4
5 =head1 DESCRIPTION
6
7 As of Perl 5.9.5 there is a new interface for using other regexp engines than
8 the default one.  Each engine is supposed to provide access to a constant
9 structure of the following format:
10
11     typedef struct regexp_engine {
12         REGEXP* (*comp) (pTHX_ const SV * const pattern, const U32 flags);
13         I32     (*exec) (pTHX_ REGEXP * const rx, char* stringarg, char* strend,
14                          char* strbeg, I32 minend, SV* screamer,
15                          void* data, U32 flags);
16         char*   (*intuit) (pTHX_ REGEXP * const rx, SV *sv, char *strpos,
17                            char *strend, U32 flags,
18                            struct re_scream_pos_data_s *data);
19         SV*     (*checkstr) (pTHX_ REGEXP * const rx);
20         void    (*free) (pTHX_ REGEXP * const rx);
21         void    (*numbered_buff_FETCH) (pTHX_ REGEXP * const rx, const I32 paren,
22                                  SV * const sv);
23         void    (*numbered_buff_STORE) (pTHX_ REGEXP * const rx, const I32 paren,
24                                        SV const * const value);
25         I32     (*numbered_buff_LENGTH) (pTHX_ REGEXP * const rx, const SV * const sv,
26                                         const I32 paren);
27         SV*     (*named_buff_FETCH) (pTHX_ REGEXP * const rx, SV * const sv,
28                                      const U32 flags);
29         SV*     (*qr_package)(pTHX_ REGEXP * const rx);
30     #ifdef USE_ITHREADS
31         void*   (*dupe) (pTHX_ REGEXP * const rx, CLONE_PARAMS *param);
32     #endif
33
34 When a regexp is compiled, its C<engine> field is then set to point at
35 the appropriate structure so that when it needs to be used Perl can find
36 the right routines to do so.
37
38 In order to install a new regexp handler, C<$^H{regcomp}> is set
39 to an integer which (when casted appropriately) resolves to one of these
40 structures. When compiling, the C<comp> method is executed, and the
41 resulting regexp structure's engine field is expected to point back at
42 the same structure.
43
44 The pTHX_ symbol in the definition is a macro used by perl under threading
45 to provide an extra argument to the routine holding a pointer back to
46 the interpreter that is executing the regexp. So under threading all
47 routines get an extra argument.
48
49 The routines are as follows:
50
51 =head2 comp
52
53     REGEXP* comp(pTHX_ const SV * const pattern, const U32 flags);
54
55 Compile the pattern stored in C<pattern> using the given C<flags> and
56 return a pointer to a prepared C<REGEXP> structure that can perform
57 the match. See L</The REGEXP structure> below for an explanation of
58 the individual fields in the REGEXP struct.
59
60 The C<pattern> parameter is the scalar that was used as the
61 pattern. previous versions of perl would pass two C<char*> indicating
62 the start and end of the stringifed pattern, the following snippet can
63 be used to get the old parameters:
64
65     STRLEN plen;
66     char*  exp = SvPV(pattern, plen);
67     char* xend = exp + plen;
68
69 Since any scalar can be passed as a pattern it's possible to implement
70 an engine that does something with an array (C<< "ook" =~ [ qw/ eek
71 hlagh / ] >>) or with the non-stringified form of a compiled regular
72 expression (C<< "ook" =~ qr/eek/ >>). perl's own engine will always
73 stringify everything using the snippet above but that doesn't mean
74 other engines have to.
75
76 The C<flags> paramater is a bitfield which indicates which of the
77 C<msixk> flags the regex was compiled with. In addition it contains
78 info about whether C<use locale> is in effect and optimization info
79 for C<split>. A regex engine might want to use the same split
80 optimizations with a different syntax, for instance a Perl6 engine
81 would treat C<split /^^/> equivalently to perl's C<split /^/>, see
82 L<split documentation|perlfunc> and the relevant code in C<pp_split>
83 in F<pp.c> to find out whether your engine should be setting these.
84
85 The C<eogc> flags are stripped out before being passed to the comp
86 routine. The regex engine does not need to know whether any of these
87 are set as those flags should only affect what perl does with the
88 pattern and its match variables, not how it gets compiled & executed.
89
90 =over 4
91
92 =item RXf_SKIPWHITE
93
94 C<split ' '> or C<split> with no arguments (which really means
95 C<split(' ', $_> see L<split|perlfunc>).
96
97 =item RXf_START_ONLY
98
99 Set if the pattern is C</^/> (C<<r->prelen == 1 && r->precomp[0] ==
100 '^'>>). Will be used by the C<split> operator to split the given
101 string on C<\n> (even under C</^/s>, see L<split|perlfunc>).
102
103 =item RXf_WHITE
104
105 Set if the pattern is exactly C</\s+/> and used by C<split>, the
106 definition of whitespace varies depending on whether RXf_UTF8 or
107 RXf_PMf_LOCALE is set.
108
109 =item RXf_PMf_LOCALE
110
111 Makes C<split> use the locale dependant definition of whitespace under C<use
112 locale> when RXf_SKIPWHITE or RXf_WHITE is in effect. Under ASCII whitespace is
113 defined as per L<isSPACE|perlapi/ISSPACE>, and by the internal macros
114 C<is_utf8_space> under UTF-8 and C<isSPACE_LC> under C<use locale>.
115
116 =item RXf_PMf_MULTILINE
117
118 The C</m> flag, this ends up being passed to C<Perl_fbm_instr> by
119 C<pp_split> regardless of the engine.
120
121 =item RXf_PMf_SINGLELINE
122
123 The C</s> flag. Guaranteed not to be used outside the regex engine.
124
125 =item RXf_PMf_FOLD
126
127 The C</i> flag. Guaranteed not to be used outside the regex engine.
128
129 =item RXf_PMf_EXTENDED
130
131 The C</x> flag. Guaranteed not to be used outside the regex
132 engine. However if present on a regex C<#> comments will be stripped
133 by the tokenizer regardless of the engine currently in use.
134
135 =item RXf_PMf_KEEPCOPY
136
137 The C</p> flag.
138
139 =item RXf_UTF8
140
141 Set if the pattern is L<SvUTF8()|perlapi/SvUTF8>, set by Perl_pmruntime.
142
143 =back
144
145 In general these flags should be preserved in regex->extflags after
146 compilation, although it is possible the regex includes constructs
147 that changes them. The perl engine for instance may upgrade non-utf8
148 strings to utf8 if the pattern includes constructs such as C<\x{...}>
149 that can only match unicode values. RXf_SKIPWHITE should always be
150 preserved verbatim in regex->extflags.
151
152 =head2 exec
153
154     I32 exec(pTHX_ REGEXP * const rx,
155              char *stringarg, char* strend, char* strbeg,
156              I32 minend, SV* screamer,
157              void* data, U32 flags);
158
159 Execute a regexp.
160
161 =head2 intuit
162
163     char* intuit(pTHX_ REGEXP * const rx,
164                   SV *sv, char *strpos, char *strend,
165                   const U32 flags, struct re_scream_pos_data_s *data);
166
167 Find the start position where a regex match should be attempted,
168 or possibly whether the regex engine should not be run because the
169 pattern can't match. This is called as appropriate by the core
170 depending on the values of the extflags member of the regexp
171 structure.
172
173 =head2 checkstr
174
175     SV* checkstr(pTHX_ REGEXP * const rx);
176
177 Return a SV containing a string that must appear in the pattern. Used
178 by C<split> for optimising matches.
179
180 =head2 free
181
182     void free(pTHX_ REGEXP * const rx);
183
184 Called by perl when it is freeing a regexp pattern so that the engine
185 can release any resources pointed to by the C<pprivate> member of the
186 regexp structure. This is only responsible for freeing private data;
187 perl will handle releasing anything else contained in the regexp structure.
188
189 =head2 numbered_buff_FETCH
190
191     void numbered_buff_FETCH(pTHX_ REGEXP * const rx, const I32 paren,
192                              SV * const sv);
193
194 Called to get the value of C<$`>, C<$'>, C<$&> (and their named
195 equivalents, see L<perlvar>) and the numbered capture buffers (C<$1>,
196 C<$2>, ...).
197
198 The C<paren> paramater will be C<-2> for C<$`>, C<-1> for C<$'>, C<0>
199 for C<$&>, C<1> for C<$1> and so forth.
200
201 C<sv> should be set to the scalar to return, the scalar is passed as
202 an argument rather than being returned from the function because when
203 it's called perl already has a scalar to store the value, creating
204 another one would be redundant. The scalar can be set with
205 C<sv_setsv>, C<sv_setpvn> and friends, see L<perlapi>.
206
207 This callback is where perl untaints its own capture variables under
208 taint mode (see L<perlsec>). See the C<Perl_reg_numbered_buff_get>
209 function in F<regcomp.c> for how to untaint capture variables if
210 that's something you'd like your engine to do as well.
211
212 =head2 numbered_buff_STORE
213
214     void    (*numbered_buff_STORE) (pTHX_ REGEXP * const rx, const I32 paren,
215                                     SV const * const value);
216
217 Called to set the value of a numbered capture variable. C<paren> is
218 the paren number (see the L<mapping|/numbered_buff_FETCH> above) and
219 C<value> is the scalar that is to be used as the new value. It's up to
220 the engine to make sure this is used as the new value (or reject it).
221
222 Example:
223
224     if ("ook" =~ /(o*)/) {
225         # `paren' will be `1' and `value' will be `ee'
226         $1 =~ tr/o/e/;
227     }
228
229 Perl's own engine will croak on any attempt to modify the capture
230 variables, to do this in another engine use the following callack
231 (copied from C<Perl_reg_numbered_buff_store>):
232
233     void
234     Example_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
235                                                             SV const * const value)
236     {
237         PERL_UNUSED_ARG(rx);
238         PERL_UNUSED_ARG(paren);
239         PERL_UNUSED_ARG(value);
240
241         if (!PL_localizing)
242             Perl_croak(aTHX_ PL_no_modify);
243     }
244
245 Actually perl 5.10 will not I<always> croak in a statement that looks
246 like it would modify a numbered capture variable. This is because the
247 STORE callback will not be called if perl can determine that it
248 doesn't have to modify the value. This is exactly how tied variables
249 behave in the same situation:
250
251     package CaptureVar;
252     use base 'Tie::Scalar';
253
254     sub TIESCALAR { bless [] }
255     sub FETCH { undef }
256     sub STORE { die "This doesn't get called" }
257
258     package main;
259
260     tie my $sv => "CatptureVar";
261     $sv =~ y/a/b/;
262
263 Because C<$sv> is C<undef> when the C<y///> operator is applied to it
264 the transliteration won't actually execute and the program won't
265 C<die>. This is different to how 5.8 behaved since the capture
266 variables were READONLY variables then, now they'll just die on
267 assignment in the default engine.
268
269 =head2 numbered_buff_LENGTH
270
271     I32 numbered_buff_LENGTH (pTHX_ REGEXP * const rx, const SV * const sv,
272                               const I32 paren);
273
274 Get the C<length> of a capture variable. There's a special callback
275 for this so that perl doesn't have to do a FETCH and run C<length> on
276 the result, since the length is (in perl's case) known from a memory
277 offset this is much more efficient:
278
279     I32 s1  = rx->offs[paren].start;
280     I32 s2  = rx->offs[paren].end;
281     I32 len = t1 - s1;
282
283 This is a little bit more complex in the case of UTF-8, see what
284 C<Perl_reg_numbered_buff_length> does with
285 L<is_utf8_string_loclen|perlapi/is_utf8_string_loclen>.
286
287 =head2 named_buff_FETCH
288
289     SV* named_buff_FETCH(pTHX_ REGEXP * const rx, SV * const key,
290                           const U32 flags);
291
292 Called to get the value of key in the C<%+> and C<%-> hashes, C<key>
293 is the hash key being requested and if C<flags & 1> is true C<%-> is
294 being requested (and C<%+> if it's not).
295
296 =head2 qr_package
297
298     SV* qr_package(pTHX_ REGEXP * const rx);
299
300 The package the qr// magic object is blessed into (as seen by C<ref
301 qr//>). It is recommended that engines change this to their package
302 name for identification regardless of whether they implement methods
303 on the object.
304
305 A callback implementation might be:
306
307     SV*
308     Example_reg_qr_package(pTHX_ REGEXP * const rx)
309     {
310         PERL_UNUSED_ARG(rx);
311         return newSVpvs("re::engine::Example");
312     }
313
314 Any method calls on an object created with C<qr//> will be dispatched to the
315 package as a normal object.
316
317     use re::engine::Example;
318     my $re = qr//;
319     $re->meth; # dispatched to re::engine::Example::meth()
320
321 To retrieve the C<REGEXP> object from the scalar in an XS function use the
322 following snippet:
323
324     void meth(SV * rv)
325     PPCODE:
326         MAGIC  * mg;
327         REGEXP * re;
328
329         if (SvMAGICAL(sv))
330             mg_get(sv);
331         if (SvROK(sv) &&
332             (sv = (SV*)SvRV(sv)) &&            /* assignment deliberate */
333             SvTYPE(sv) == SVt_PVMG &&
334             (mg = mg_find(sv, PERL_MAGIC_qr))) /* assignment deliberate */
335         {
336             re = (REGEXP *)mg->mg_obj; 
337         }
338
339 Or use the (CURRENTLY UNDOCUMENETED!) C<Perl_get_re_arg> function:
340
341     void meth(SV * rv)
342     PPCODE:
343         const REGEXP * const re = (REGEXP *)Perl_get_re_arg( aTHX_ rv, 0, NULL );
344
345 =head2 dupe
346
347     void* dupe(pTHX_ REGEXP * const rx, CLONE_PARAMS *param);
348
349 On threaded builds a regexp may need to be duplicated so that the pattern
350 can be used by mutiple threads. This routine is expected to handle the
351 duplication of any private data pointed to by the C<pprivate> member of
352 the regexp structure.  It will be called with the preconstructed new
353 regexp structure as an argument, the C<pprivate> member will point at
354 the B<old> private structue, and it is this routine's responsibility to
355 construct a copy and return a pointer to it (which perl will then use to
356 overwrite the field as passed to this routine.)
357
358 This allows the engine to dupe its private data but also if necessary
359 modify the final structure if it really must.
360
361 On unthreaded builds this field doesn't exist.
362
363 =head1 The REGEXP structure
364
365 The REGEXP struct is defined in F<regexp.h>. All regex engines must be able to
366 correctly build such a structure in their L</comp> routine.
367
368 The REGEXP structure contains all the data that perl needs to be aware of
369 to properly work with the regular expression. It includes data about
370 optimisations that perl can use to determine if the regex engine should
371 really be used, and various other control info that is needed to properly
372 execute patterns in various contexts such as is the pattern anchored in
373 some way, or what flags were used during the compile, or whether the
374 program contains special constructs that perl needs to be aware of.
375
376 In addition it contains two fields that are intended for the private use
377 of the regex engine that compiled the pattern. These are the C<intflags>
378 and pprivate members. The C<pprivate> is a void pointer to an arbitrary
379 structure whose use and management is the responsibility of the compiling
380 engine. perl will never modify either of these values.
381
382     typedef struct regexp {
383         /* what engine created this regexp? */
384         const struct regexp_engine* engine;
385
386         /* what re is this a lightweight copy of? */
387         struct regexp* mother_re;
388
389         /* Information about the match that the perl core uses to manage things */
390         U32 extflags;   /* Flags used both externally and internally */
391         I32 minlen;     /* mininum possible length of string to match */
392         I32 minlenret;  /* mininum possible length of $& */
393         U32 gofs;       /* chars left of pos that we search from */
394
395         /* substring data about strings that must appear
396            in the final match, used for optimisations */
397         struct reg_substr_data *substrs;
398
399         U32 nparens;  /* number of capture buffers */
400
401         /* private engine specific data */
402         U32 intflags;   /* Engine Specific Internal flags */
403         void *pprivate; /* Data private to the regex engine which 
404                            created this object. */
405
406         /* Data about the last/current match. These are modified during matching*/
407         U32 lastparen;            /* last open paren matched */
408         U32 lastcloseparen;       /* last close paren matched */
409         regexp_paren_pair *swap;  /* Swap copy of *offs */
410         regexp_paren_pair *offs;  /* Array of offsets for (@-) and (@+) */
411
412         char *subbeg;  /* saved or original string so \digit works forever. */
413         SV_SAVED_COPY  /* If non-NULL, SV which is COW from original */
414         I32 sublen;    /* Length of string pointed by subbeg */
415
416         /* Information about the match that isn't often used */
417         I32 prelen;           /* length of precomp */
418         const char *precomp;  /* pre-compilation regular expression */
419
420         /* wrapped can't be const char*, as it is returned by sv_2pv_flags */
421         char *wrapped;  /* wrapped version of the pattern */
422         I32 wraplen;    /* length of wrapped */
423
424         I32 seen_evals;   /* number of eval groups in the pattern - for security checks */
425         HV *paren_names;  /* Optional hash of paren names */
426
427         /* Refcount of this regexp */
428         I32 refcnt;             /* Refcount of this regexp */
429     } regexp;
430
431 The fields are discussed in more detail below:
432
433 =over 4
434
435 =item C<engine>
436
437 This field points at a regexp_engine structure which contains pointers
438 to the subroutines that are to be used for performing a match. It
439 is the compiling routine's responsibility to populate this field before
440 returning the regexp object.
441
442 Internally this is set to C<NULL> unless a custom engine is specified in
443 C<$^H{regcomp}>, perl's own set of callbacks can be accessed in the struct
444 pointed to by C<RE_ENGINE_PTR>.
445
446 =item C<mother_re>
447
448 TODO, see L<http://www.mail-archive.com/perl5-changes@perl.org/msg17328.html>
449
450 =item C<extflags>
451
452 This will be used by perl to see what flags the regexp was compiled with, this
453 will normally be set to the value of the flags parameter on L</comp>.
454
455 =item C<minlen> C<minlenret>
456
457 The minimum string length required for the pattern to match.  This is used to
458 prune the search space by not bothering to match any closer to the end of a
459 string than would allow a match. For instance there is no point in even
460 starting the regex engine if the minlen is 10 but the string is only 5
461 characters long. There is no way that the pattern can match.
462
463 C<minlenret> is the minimum length of the string that would be found
464 in $& after a match.
465
466 The difference between C<minlen> and C<minlenret> can be seen in the
467 following pattern:
468
469     /ns(?=\d)/
470
471 where the C<minlen> would be 3 but C<minlenret> would only be 2 as the \d is
472 required to match but is not actually included in the matched content. This
473 distinction is particularly important as the substitution logic uses the
474 C<minlenret> to tell whether it can do in-place substition which can result in
475 considerable speedup.
476
477 =item C<gofs>
478
479 Left offset from pos() to start match at.
480
481 =item C<substrs>
482
483 TODO: document
484
485 =item C<nparens>, C<lasparen>, and C<lastcloseparen>
486
487 These fields are used to keep track of how many paren groups could be matched
488 in the pattern, which was the last open paren to be entered, and which was
489 the last close paren to be entered.
490
491 =item C<intflags>
492
493 The engine's private copy of the flags the pattern was compiled with. Usually
494 this is the same as C<extflags> unless the engine chose to modify one of them
495
496 =item C<pprivate>
497
498 A void* pointing to an engine-defined data structure. The perl engine uses the
499 C<regexp_internal> structure (see L<perlreguts/Base Structures>) but a custom
500 engine should use something else.
501
502 =item C<swap>
503
504 TODO: document
505
506 =item C<offs>
507
508 A C<regexp_paren_pair> structure which defines offsets into the string being
509 matched which correspond to the C<$&> and C<$1>, C<$2> etc. captures, the
510 C<regexp_paren_pair> struct is defined as follows:
511
512     typedef struct regexp_paren_pair {
513         I32 start;
514         I32 end;
515     } regexp_paren_pair;
516
517 If C<< ->offs[num].start >> or C<< ->offs[num].end >> is C<-1> then that
518 capture buffer did not match. C<< ->offs[0].start/end >> represents C<$&> (or
519 C<${^MATCH> under C<//p>) and C<< ->offs[paren].end >> matches C<$$paren> where
520 C<$paren >= 1>.
521
522 =item C<precomp> C<prelen>
523
524 Used for debugging purposes. C<precomp> holds a copy of the pattern
525 that was compiled and C<prelen> its length.
526
527 =item C<paren_names>
528
529 This is a hash used internally to track named capture buffers and their
530 offsets. The keys are the names of the buffers the values are dualvars,
531 with the IV slot holding the number of buffers with the given name and the
532 pv being an embedded array of I32.  The values may also be contained
533 independently in the data array in cases where named backreferences are
534 used.
535
536 =item C<reg_substr_data>
537
538 Holds information on the longest string that must occur at a fixed
539 offset from the start of the pattern, and the longest string that must
540 occur at a floating offset from the start of the pattern. Used to do
541 Fast-Boyer-Moore searches on the string to find out if its worth using
542 the regex engine at all, and if so where in the string to search.
543
544 =item C<subbeg> C<sublen> C<saved_copy>
545
546     #define SAVEPVN(p,n) ((p) ? savepvn(p,n) : NULL)
547     if (RX_MATCH_COPIED(ret))
548         ret->subbeg = SAVEPVN(ret->subbeg, ret->sublen);
549     else
550         ret->subbeg = NULL;
551
552 C<PL_sawampersand || rx->extflags & RXf_PMf_KEEPCOPY>
553
554 These are used during execution phase for managing search and replace
555 patterns.
556
557 =item C<wrapped> C<wraplen>
558
559 Stores the string C<qr//> stringifies to, for example C<(?-xism:eek)>
560 in the case of C<qr/eek/>.
561
562 When using a custom engine that doesn't support the C<(?:)> construct for
563 inline modifiers it's best to have C<qr//> stringify to the supplied pattern,
564 note that this will create invalid patterns in cases such as:
565
566     my $x = qr/a|b/;  # "a|b"
567     my $y = qr/c/;    # "c"
568     my $z = qr/$x$y/; # "a|bc"
569
570 There's no solution for such problems other than making the custom engine
571 understand some for of inline modifiers.
572
573 The C<Perl_reg_stringify> in F<regcomp.c> does the stringification work.
574
575 =item C<seen_evals>
576
577 This stores the number of eval groups in the pattern. This is used for security
578 purposes when embedding compiled regexes into larger patterns with C<qr//>.
579
580 =item C<refcnt>
581
582 The number of times the structure is referenced. When this falls to 0 the
583 regexp is automatically freed by a call to pregfree. This should be set to 1 in
584 each engine's L</comp> routine.
585
586 =back
587
588 =head2 De-allocation and Cloning
589
590 Any patch that adds data items to the REGEXP struct will need to include
591 changes to F<sv.c> (C<Perl_re_dup()>) and F<regcomp.c> (C<pregfree()>). This
592 involves freeing or cloning items in the regexp's data array based on the data
593 item's type.
594
595 =head1 HISTORY
596
597 Originally part of L<perlreguts>.
598
599 =head1 AUTHORS
600
601 Originally written by Yves Orton, expanded by E<AElig>var ArnfjE<ouml>rE<eth>
602 Bjarmason.
603
604 =head1 LICENSE
605
606 Copyright 2006 Yves Orton and 2007 E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason.
607
608 This program is free software; you can redistribute it and/or modify it under
609 the same terms as Perl itself.
610
611 =cut