]> git.vpit.fr Git - perl/modules/re-engine-Plugin.git/blob - Plugin.pod
Remove trailing whitespace
[perl/modules/re-engine-Plugin.git] / Plugin.pod
1 =head1 NAME
2
3 re::engine::Plugin - API to write custom regex engines
4
5 =head1 VERSION
6
7 Version 0.09
8
9 =head1 DESCRIPTION
10
11 As of perl 5.9.5 it's possible to lexically replace perl's built-in
12 regular expression engine with your own (see L<perlreapi> and
13 L<perlpragma>). This module provides a glue interface to the relevant
14 parts of the perl C API enabling you to write an engine in Perl
15 instead of the C/XS interface provided by the core.
16
17 =head2 The gory details
18
19 Each regex in perl is compiled into an internal C<REGEXP> structure
20 (see L<perlreapi|perlreapi/The REGEXP structure>), this can happen
21 either during compile time in the case of patterns in the format
22 C</pattern/> or runtime for C<qr//> patterns, or something inbetween
23 depending on variable interpolation etc.
24
25 When this module is loaded into a scope it inserts a hook into
26 C<$^H{regcomp}> (as described in L<perlreapi> and L<perlpragma>) to
27 have each regexp constructed in its lexical scope handled by this
28 engine, but it differs from other engines in that it also inserts
29 other hooks into C<%^H> in the same scope that point to user-defined
30 subroutines to use during compilation, execution etc, these are
31 described in L</CALLBACKS> below.
32
33 The callbacks (e.g. L</comp>) then get called with a
34 L<re::engine::Plugin> object as their first argument. This object
35 provies access to perl's internal REGEXP struct in addition to its own
36 state (e.g. a L<stash|/stash>). The L<methods|/METHODS> on this object
37 allow for altering the C<REGEXP> struct's internal state, adding new
38 callbacks, etc.
39
40 =head1 CALLBACKS
41
42 Callbacks are specified in the C<re::engine::Plugin> import list as
43 key-value pairs of names and subroutine references:
44
45     use re::engine::Plugin (
46         comp => sub {},
47         exec => sub {},
48     );
49
50 To write a custom engine which imports your functions into the
51 caller's scope use use the following snippet:
52
53     package re::engine::Example;
54     use re::engine::Plugin ();
55
56     sub import
57     {
58         # Sets the caller's $^H{regcomp} his %^H with our callbacks
59         re::engine::Plugin->import(
60             comp => \&comp,
61             exec => \&exec,
62         );
63     }
64
65    *unimport = \&re::engine::Plugin::unimport;
66
67     # Implementation of the engine
68     sub comp { ... }
69     sub exec { ... }
70
71     1;
72
73 =head2 comp
74
75     comp => sub {
76         my ($rx) = @_;
77
78         # return value discarded
79     }
80
81 Called when a regex is compiled by perl, this is always the first
82 callback to be called and may be called multiple times or not at all
83 depending on what perl sees fit at the time.
84
85 The first argument will be a freshly constructed C<re::engine::Plugin>
86 object (think of it as C<$self>) which you can interact with using the
87 L<methods|/METHODS> below, this object will be passed around the other
88 L<callbacks|/CALLBACKS> and L<methods|/METHODS> for the lifetime of
89 the regex.
90
91 Calling C<die> or anything that uses it (such as C<carp>) here will
92 not be trapped by an C<eval> block that the pattern is in, i.e.
93
94    use Carp 'croak';
95    use re::engine::Plugin(
96        comp => sub {
97            my $rx = shift;
98            croak "Your pattern is invalid"
99                unless $rx->pattern ~~ /pony/;
100        }
101    );
102
103    # Ignores the eval block
104    eval { /you die in C<eval>, you die for real/ };
105
106 This happens because the real subroutine call happens indirectly at
107 compile time and not in the scope of the C<eval> block. This is how
108 perl's own engine would behave in the same situation if given an
109 invalid pattern such as C</(/>.
110
111 =head2 exec
112
113     exec => sub {
114         my ($rx, $str) = @_;
115
116         # We always like ponies!
117         return 1 if $str ~~ /pony/;
118
119         # Failed to match
120         return;
121     }
122
123 Called when a regex is being executed, i.e. when it's being matched
124 against something. The scalar being matched against the pattern is
125 available as the second argument (C<$str>) and through the L<str|/str>
126 method. The routine should return a true value if the match was
127 successful, and a false one if it wasn't.
128
129 This callback can also be specified on an individual basis with the
130 L</callbacks> method.
131
132 =head1 METHODS
133
134 =head2 str
135
136     "str" ~~ /pattern/;
137     # in comp/exec/methods:
138     my $str = $rx->str;
139
140 The last scalar to be matched against the L<pattern|/pattern> or
141 C<undef> if there hasn't been a match yet.
142
143 perl's own engine always stringifies the scalar being matched against
144 a given pattern, however a custom engine need not have such
145 restrictions. One could write a engine that matched a file handle
146 against a pattern or any other complex data structure.
147
148 =head2 pattern
149
150 The pattern that the engine was asked to compile, this can be either a
151 classic Perl pattern with modifiers like C</pat/ix> or C<qr/pat/ix> or
152 an arbitary scalar. The latter allows for passing anything that
153 doesn't fit in a string and five L<modifier|/mod> characters, such as
154 hashrefs, objects, etc.
155
156 =head2 mod
157
158     my %mod = $rx->mod;
159     say "has /ix" if %mod ~~ 'i' and %mod ~~ 'x';
160
161 A key-value pair list of the modifiers the pattern was compiled with.
162 The keys will zero or more of C<imsxp> and the values will be true
163 values (so that you don't have to write C<exists>).
164
165 You don't get to know if the C<eogc> modifiers were attached to the
166 pattern since these are internal to perl and shouldn't matter to
167 regexp engines.
168
169 =head2 stash
170
171     comp => sub { shift->stash( [ 1 .. 5 ) },
172     exec => sub { shift->stash }, # Get [ 1 .. 5 ]
173
174 Returns or sets a user defined stash that's passed around as part of
175 the C<$rx> object, useful for passing around all sorts of data between
176 the callback routines and methods.
177
178 =head2 minlen
179
180     $rx->minlen($num);
181     my $minlen = $rx->minlen // "not set";
182
183 The minimum C<length> a string must be to match the pattern, perl will
184 use this internally during matching to check whether the stringified
185 form of the string (or other object) being matched is at least this
186 long, if not the regexp engine in effect (that means you!) will not be
187 called at all.
188
189 The length specified will be used as a a byte length (using
190 L<SvPV|perlapi/SvPV>), not a character length.
191
192 =head2 nparens
193
194 =head2 gofs
195
196 =head2 callbacks
197
198     # A dumb regexp engine that just tests string equality
199     use re::engine::Plugin comp => sub {
200         my ($re) = @_;
201
202         my $pat = $re->pattern;
203
204         $re->callbacks(
205             exec => sub {
206                 my ($re, $str) = @_;
207                 return $pat eq $str;
208             },
209         );
210     };
211
212 Takes a list of key-value pairs of names and subroutines, and replace the
213 callback currently attached to the regular expression for the type given as
214 the key by the code reference passed as the corresponding value.
215
216 The only valid key is currently C<exec>. See L</exec> for more details about
217 this callback.
218
219 =head2 num_captures
220
221     $re->num_captures(
222         FETCH => sub {
223             my ($re, $paren) = @_;
224
225             return "value";
226         },
227         STORE => sub {
228             my ($re, $paren, $rhs) = @_;
229
230             # return value discarded
231         },
232         LENGTH => sub {
233             my ($re, $paren) = @_;
234
235             return 123;
236         },
237     );
238
239 Takes a list of key-value pairs of names and subroutines that
240 implement numbered capture variables. C<FETCH> will be called on value
241 retrieval (C<say $1>), C<STORE> on assignment (C<$1 = "ook">) and
242 C<LENGTH> on C<length $1>.
243
244 The second paramater of each routine is the paren number being
245 requested/stored, the following mapping applies for those numbers:
246
247     -2 => $` or ${^PREMATCH}
248     -1 => $' or ${^POSTMATCH}
249      0 => $& or ${^MATCH}
250      1 => $1
251      # ...
252
253 Assignment to capture variables makes it possible to implement
254 something like Perl 6 C<:rw> semantics, and since it's possible to
255 make the capture variables return any scalar instead of just a string
256 it becomes possible to implement Perl 6 match object semantics (to
257 name an example).
258
259 =head2 named_captures
260
261 B<TODO>: implement
262
263 perl internals still needs to be changed to support this but when it's
264 done it'll allow the binding of C<%+> and C<%-> and support the
265 L<Tie::Hash> methods FETCH, STORE, DELETE, CLEAR, EXISTS, FIRSTKEY,
266 NEXTKEY and SCALAR.
267
268 =head1 CONSTANTS
269
270 =head2 C<REP_THREADSAFE>
271
272 True iff the module could have been built with thread-safety features
273 enabled.
274
275 =head2 C<REP_FORKSAFE>
276
277 True iff this module could have been built with fork-safety features
278 enabled. This will always be true except on Windows where it's false
279 for perl 5.10.0 and below.
280
281 =head1 TAINTING
282
283 The only way to untaint an existing variable in Perl is to use it as a
284 hash key or referencing subpatterns from a regular expression match
285 (see L<perlsec|perlsec/Laundering and Detecting Tainted Data>), the
286 latter only works in perl's regex engine because it explicitly
287 untaints capture variables which a custom engine will also need to do
288 if it wants its capture variables to be untanted.
289
290 There are basically two ways to go about this, the first and obvious
291 one is to make use of Perl'l lexical scoping which enables the use of
292 its built-in regex engine in the scope of the overriding engine's
293 callbacks:
294
295     use re::engine::Plugin (
296         exec => sub {
297             my ($re, $str) = @_; # $str is tainted
298
299             $re->num_captures(
300                 FETCH => sub {
301                     my ($re, $paren) = @_;
302
303                     # This is perl's engine doing the match
304                     $str ~~ /(.*)/;
305
306                     # $1 has been untainted
307                     return $1;
308                 },
309             );
310         },
311     );
312
313 The second is to use something like L<Taint::Util> which flips the
314 taint flag on the scalar without invoking the perl's regex engine:
315
316     use Taint::Util;
317     use re::engine::Plugin (
318         exec => sub {
319             my ($re, $str) = @_; # $str is tainted
320
321             $re->num_captures(
322                 FETCH => sub {
323                     my ($re, $paren) = @_;
324
325                     # Copy $str and untaint the copy
326                     untaint(my $ret = $str);
327
328                     # Return the untainted value
329                     return $ret;
330                 },
331             );
332         },
333     );
334
335 In either case a regex engine using perl's L<regex api|perlapi> or
336 this module is responsible for how and if it untaints its variables.
337
338 =head1 SEE ALSO
339
340 L<perlreapi>, L<Taint::Util>
341
342 =head1 TODO & CAVEATS
343
344 I<here be dragons>
345
346 =over
347
348 =item *
349
350 Engines implemented with this module don't support C<s///> and C<split
351 //>, the appropriate parts of the C<REGEXP> struct need to be wrapped
352 and documented.
353
354 =item *
355
356 Still not a complete wrapper for L<perlreapi> in other ways, needs
357 methods for some C<REGEXP> struct members, some callbacks aren't
358 implemented etc.
359
360 =item *
361
362 Support overloading operations on the C<qr//> object, this allow
363 control over the of C<qr//> objects in a manner that isn't limited by
364 C<wrapped>/C<wraplen>.
365
366     $re->overload(
367         '""'  => sub { ... },
368         '@{}' => sub { ... },
369         ...
370     );
371
372 =item *
373
374 Support the dispatch of arbitary methods from the re::engine::Plugin
375 qr// object to user defined subroutines via AUTOLOAD;
376
377     package re::engine::Plugin;
378     sub AUTOLOAD
379     {
380         our $AUTOLOAD;
381         my ($name) = $AUTOLOAD =~ /.*::(.*?)/;
382         my $cv = getmeth($name); # or something like that
383         goto &$cv;
384     }
385
386     package re::engine::SomeEngine;
387
388     sub comp
389     {
390         my $re = shift;
391
392         $re->add_method( # or something like that
393             foshizzle => sub {
394                 my ($re, @arg) = @_; # re::engine::Plugin, 1..5
395             },
396         );
397     }
398
399     package main;
400     use re::engine::SomeEngine;
401     later:
402
403     my $re = qr//;
404     $re->foshizzle(1..5);
405
406 =item *
407
408 Implement the dupe callback, test this on a threaded perl (and learn
409 how to use threads and how they break the current model).
410
411 =item *
412
413 Allow the user to specify ->offs either as an array or a packed
414 string. Can pack() even pack I32? Only IV? int?
415
416 =item *
417
418 Add tests that check for different behavior when curpm is and is not
419 set.
420
421 =item *
422
423 Add tests that check the refcount of the stash and other things I'm
424 mucking with, run valgrind and make sure everything is destroyed when
425 it should.
426
427 =item *
428
429 Run the debugger on the testsuite and find cases when the intuit and
430 checkstr callbacks are called. Write wrappers around them and add
431 tests.
432
433 =back
434
435 =head1 DEPENDENCIES
436
437 L<perl> 5.10.
438
439 A C compiler.
440 This module may happen to build with a C++ compiler as well, but don't rely on it, as no guarantee is made in this regard.
441
442 L<XSLoader> (standard since perl 5.006).
443
444 =head1 BUGS
445
446 Please report any bugs that aren't already listed at
447 L<http://rt.cpan.org/Dist/Display.html?Queue=re-engine-Plugin> to
448 L<http://rt.cpan.org/Public/Bug/Report.html?Queue=re-engine-Plugin>
449
450 =head1 AUTHORS
451
452 E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason C<< <avar at cpan.org> >>
453
454 Vincent Pit C<< <perl at profvince.com> >>
455
456 =head1 LICENSE
457
458 Copyright 2007,2008 E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason.
459
460 Copyright 2009,2010,2011 Vincent Pit.
461
462 This program is free software; you can redistribute it and/or modify it
463 under the same terms as Perl itself.
464
465 =cut