Regex Utility Functions and Substituion Fix (XML::Twig core dump)
[p5sagit/p5-mst-13.2.git] / ext / re / re.pm
1 package re;
2
3 # pragma for controlling the regex engine
4 use strict;
5 use warnings;
6
7 our $VERSION     = "0.06_03";
8 our @ISA         = qw(Exporter);
9 our @EXPORT_OK   = qw(is_regexp regexp_pattern);
10 our %EXPORT_OK = map { $_ => 1 } @EXPORT_OK;
11
12 # *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING ***
13 #
14 # If you modify these values see comment below!
15
16 my %bitmask = (
17     taint   => 0x00100000, # HINT_RE_TAINT
18     eval    => 0x00200000, # HINT_RE_EVAL
19 );
20
21 # - File::Basename contains a literal for 'taint' as a fallback.  If
22 # taint is changed here, File::Basename must be updated as well.
23 #
24 # - ExtUtils::ParseXS uses a hardcoded 
25 # BEGIN { $^H |= 0x00200000 } 
26 # in it to allow re.xs to be built. So if 'eval' is changed here then
27 # ExtUtils::ParseXS must be changed as well.
28 #
29 # *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING ***
30
31 sub setcolor {
32  eval {                         # Ignore errors
33   require Term::Cap;
34
35   my $terminal = Tgetent Term::Cap ({OSPEED => 9600}); # Avoid warning.
36   my $props = $ENV{PERL_RE_TC} || 'md,me,so,se,us,ue';
37   my @props = split /,/, $props;
38   my $colors = join "\t", map {$terminal->Tputs($_,1)} @props;
39
40   $colors =~ s/\0//g;
41   $ENV{PERL_RE_COLORS} = $colors;
42  };
43  if ($@) {
44     $ENV{PERL_RE_COLORS} ||= qq'\t\t> <\t> <\t\t';
45  }
46
47 }
48
49 my %flags = (
50     COMPILE         => 0x0000FF,
51     PARSE           => 0x000001,
52     OPTIMISE        => 0x000002,
53     TRIEC           => 0x000004,
54     DUMP            => 0x000008,
55
56     EXECUTE         => 0x00FF00,
57     INTUIT          => 0x000100,
58     MATCH           => 0x000200,
59     TRIEE           => 0x000400,
60
61     EXTRA           => 0xFF0000,
62     TRIEM           => 0x010000,
63     OFFSETS         => 0x020000,
64     OFFSETSDBG      => 0x040000,
65     STATE           => 0x080000,
66     OPTIMISEM       => 0x100000,
67     STACK           => 0x280000,
68 );
69 $flags{ALL} = -1;
70 $flags{All} = $flags{all} = $flags{DUMP} | $flags{EXECUTE};
71 $flags{Extra} = $flags{EXECUTE} | $flags{COMPILE};
72 $flags{More} = $flags{MORE} = $flags{All} | $flags{TRIEC} | $flags{TRIEM} | $flags{STATE};
73 $flags{State} = $flags{DUMP} | $flags{EXECUTE} | $flags{STATE};
74 $flags{TRIE} = $flags{DUMP} | $flags{EXECUTE} | $flags{TRIEC};
75
76 my $installed;
77 my $installed_error;
78
79 sub _do_install {
80     if ( ! defined($installed) ) {
81         require XSLoader;
82         $installed = eval { XSLoader::load('re', $VERSION) } || 0;
83         $installed_error = $@;
84     }
85 }
86
87 sub _load_unload {
88     my ($on)= @_;
89     if ($on) {
90         _do_install();        
91         if ( ! $installed ) {
92             die "'re' not installed!? ($installed_error)";
93         } else {
94             # We call install() every time, as if we didn't, we wouldn't
95             # "see" any changes to the color environment var since
96             # the last time it was called.
97
98             # install() returns an integer, which if casted properly
99             # in C resolves to a structure containing the regex
100             # hooks. Setting it to a random integer will guarantee
101             # segfaults.
102             $^H{regcomp} = install();
103         }
104     } else {
105         delete $^H{regcomp};
106     }
107 }
108
109 sub bits {
110     my $on = shift;
111     my $bits = 0;
112     unless (@_) {
113         require Carp;
114         Carp::carp("Useless use of \"re\" pragma"); 
115     }
116     foreach my $idx (0..$#_){
117         my $s=$_[$idx];
118         if ($s eq 'Debug' or $s eq 'Debugcolor') {
119             setcolor() if $s =~/color/i;
120             ${^RE_DEBUG_FLAGS} = 0 unless defined ${^RE_DEBUG_FLAGS};
121             for my $idx ($idx+1..$#_) {
122                 if ($flags{$_[$idx]}) {
123                     if ($on) {
124                         ${^RE_DEBUG_FLAGS} |= $flags{$_[$idx]};
125                     } else {
126                         ${^RE_DEBUG_FLAGS} &= ~ $flags{$_[$idx]};
127                     }
128                 } else {
129                     require Carp;
130                     Carp::carp("Unknown \"re\" Debug flag '$_[$idx]', possible flags: ",
131                                join(", ",sort keys %flags ) );
132                 }
133             }
134             _load_unload($on ? 1 : ${^RE_DEBUG_FLAGS});
135             last;
136         } elsif ($s eq 'debug' or $s eq 'debugcolor') {
137             setcolor() if $s =~/color/i;
138             _load_unload($on);
139         } elsif (exists $bitmask{$s}) {
140             $bits |= $bitmask{$s};
141         } elsif ($EXPORT_OK{$s}) {
142             _do_install();
143             require Exporter;
144             re->export_to_level(2, 're', $s);
145         } else {
146             require Carp;
147             Carp::carp("Unknown \"re\" subpragma '$s' (known ones are: ",
148                        join(', ', map {qq('$_')} 'debug', 'debugcolor', sort keys %bitmask),
149                        ")");
150         }
151     }
152     $bits;
153 }
154
155 sub import {
156     shift;
157     $^H |= bits(1, @_);
158 }
159
160 sub unimport {
161     shift;
162     $^H &= ~ bits(0, @_);
163 }
164
165 1;
166
167 __END__
168
169 =head1 NAME
170
171 re - Perl pragma to alter regular expression behaviour
172
173 =head1 SYNOPSIS
174
175     use re 'taint';
176     ($x) = ($^X =~ /^(.*)$/s);     # $x is tainted here
177
178     $pat = '(?{ $foo = 1 })';
179     use re 'eval';
180     /foo${pat}bar/;                # won't fail (when not under -T switch)
181
182     {
183         no re 'taint';             # the default
184         ($x) = ($^X =~ /^(.*)$/s); # $x is not tainted here
185
186         no re 'eval';              # the default
187         /foo${pat}bar/;            # disallowed (with or without -T switch)
188     }
189
190     use re 'debug';                # output debugging info during
191     /^(.*)$/s;                     #     compile and run time
192
193
194     use re 'debugcolor';           # same as 'debug', but with colored output
195     ...
196
197     use re qw(Debug All);          # Finer tuned debugging options.
198     use re qw(Debug More);         
199     no re qw(Debug ALL);           # Turn of all re debugging in this scope
200     
201     use re qw(is_regexp regexp_pattern); # import utility functions
202     my ($pat,$mods)=regexp_pattern(qr/foo/i);
203     if (is_regexp($obj)) { 
204         print "Got regexp: ",
205             scalar regexp_pattern($obj); # just as perl would stringify it
206     }                                    # but no hassle with blessed re's.
207         
208
209 (We use $^X in these examples because it's tainted by default.)
210
211 =head1 DESCRIPTION
212
213 =head2 'taint' mode
214
215 When C<use re 'taint'> is in effect, and a tainted string is the target
216 of a regex, the regex memories (or values returned by the m// operator
217 in list context) are tainted.  This feature is useful when regex operations
218 on tainted data aren't meant to extract safe substrings, but to perform
219 other transformations.
220
221 =head2 'eval' mode
222
223 When C<use re 'eval'> is in effect, a regex is allowed to contain
224 C<(?{ ... })> zero-width assertions even if regular expression contains
225 variable interpolation.  That is normally disallowed, since it is a
226 potential security risk.  Note that this pragma is ignored when the regular
227 expression is obtained from tainted data, i.e.  evaluation is always
228 disallowed with tainted regular expressions.  See L<perlre/(?{ code })>.
229
230 For the purpose of this pragma, interpolation of precompiled regular
231 expressions (i.e., the result of C<qr//>) is I<not> considered variable
232 interpolation.  Thus:
233
234     /foo${pat}bar/
235
236 I<is> allowed if $pat is a precompiled regular expression, even
237 if $pat contains C<(?{ ... })> assertions.
238
239 =head2 'debug' mode
240
241 When C<use re 'debug'> is in effect, perl emits debugging messages when
242 compiling and using regular expressions.  The output is the same as that
243 obtained by running a C<-DDEBUGGING>-enabled perl interpreter with the
244 B<-Dr> switch. It may be quite voluminous depending on the complexity
245 of the match.  Using C<debugcolor> instead of C<debug> enables a
246 form of output that can be used to get a colorful display on terminals
247 that understand termcap color sequences.  Set C<$ENV{PERL_RE_TC}> to a
248 comma-separated list of C<termcap> properties to use for highlighting
249 strings on/off, pre-point part on/off.
250 See L<perldebug/"Debugging regular expressions"> for additional info.
251
252 As of 5.9.5 the directive C<use re 'debug'> and its equivalents are
253 lexically scoped, as the other directives are.  However they have both 
254 compile-time and run-time effects.
255
256 See L<perlmodlib/Pragmatic Modules>.
257
258 =head2 'Debug' mode
259
260 Similarly C<use re 'Debug'> produces debugging output, the difference
261 being that it allows the fine tuning of what debugging output will be
262 emitted. Options are divided into three groups, those related to
263 compilation, those related to execution and those related to special
264 purposes. The options are as follows:
265
266 =over 4
267
268 =item Compile related options
269
270 =over 4
271
272 =item COMPILE
273
274 Turns on all compile related debug options.
275
276 =item PARSE
277
278 Turns on debug output related to the process of parsing the pattern.
279
280 =item OPTIMISE
281
282 Enables output related to the optimisation phase of compilation.
283
284 =item TRIEC
285
286 Detailed info about trie compilation.
287
288 =item DUMP
289
290 Dump the final program out after it is compiled and optimised.
291
292
293 =back
294
295 =item Execute related options
296
297 =over 4
298
299 =item EXECUTE
300
301 Turns on all execute related debug options.
302
303 =item MATCH
304
305 Turns on debugging of the main matching loop.
306
307 =item TRIEE
308
309 Extra debugging of how tries execute.
310
311 =item INTUIT
312
313 Enable debugging of start point optimisations.
314
315 =back
316
317 =item Extra debugging options
318
319 =over 4
320
321 =item EXTRA
322
323 Turns on all "extra" debugging options.
324
325 =item TRIEM
326
327 Enable enhanced TRIE debugging. Enhances both TRIEE
328 and TRIEC.
329
330 =item STATE
331
332 Enable debugging of states in the engine. 
333
334 =item STACK
335
336 Enable debugging of the recursion stack in the engine. Enabling
337 or disabling this option automatically does the same for debugging
338 states as well. This output from this can be quite large.
339
340 =item OPTIMISEM
341
342 Enable enhanced optimisation debugging and start point optimisations.
343 Probably not useful except when debugging the regex engine itself.
344
345 =item OFFSETS
346
347 Dump offset information. This can be used to see how regops correlate
348 to the pattern. Output format is
349
350    NODENUM:POSITION[LENGTH]
351
352 Where 1 is the position of the first char in the string. Note that position
353 can be 0, or larger than the actual length of the pattern, likewise length
354 can be zero.
355
356 =item OFFSETSDBG
357
358 Enable debugging of offsets information. This emits copious
359 amounts of trace information and doesn't mesh well with other
360 debug options.
361
362 Almost definitely only useful to people hacking
363 on the offsets part of the debug engine.
364
365 =back
366
367 =item Other useful flags
368
369 These are useful shortcuts to save on the typing.
370
371 =over 4
372
373 =item ALL
374
375 Enable all compile and execute options at once.
376
377 =item All
378
379 Enable DUMP and all execute options. Equivalent to:
380
381   use re 'debug';
382
383 =item MORE
384
385 =item More
386
387 Enable TRIEM and all execute compile and execute options.
388
389 =back
390
391 =back
392
393 As of 5.9.5 the directive C<use re 'debug'> and its equivalents are
394 lexically scoped, as the other directives are.  However they have both 
395 compile-time and run-time effects.
396
397 =head2 Exportable Functions
398
399 As of perl 5.9.5 're' debug contains a number of utility functions that
400 may be optionally exported into the callers namespace. They are listed
401 below.
402
403 =over 4
404
405 =item is_regexp($ref)
406
407 Returns true if the argument is a compiled regular expression as returned
408 by C<qr//>, false if it is not. 
409
410 This function will not be confused by overloading or blessing. In 
411 internals terms this extracts the regexp pointer out of the 
412 PERL_MAGIC_qr structure so it it cannot be fooled.
413
414 =item regexp_pattern($ref)
415
416 If the argument is a compiled regular expression as returned by C<qr//>
417 then this function returns the pattern. 
418
419 In list context it returns a two element list, the first element 
420 containing the pattern and the second containing the modifiers used when 
421 the pattern was compiled. 
422
423   my ($pat,$mods)=regexp_pattern($ref);
424
425 In scalar context it returns the same as perl would when strigifying a 
426 raw qr// with the same pattern inside.  If the argument is not a 
427 compiled reference then this routine returns false but defined in scalar 
428 context, and the empty list in list context. Thus the following 
429
430     if (regexp_pattern($ref) eq '(?i-xsm:foo)')
431
432 will be warning free regardless of what $ref actually is.
433
434 Like c<is_regexp> this function will not be confused by overloading 
435 or blessing of the object.  
436
437 =back
438
439 =head1 SEE ALSO
440
441 L<perlmodlib/Pragmatic Modules>.
442
443 =cut