This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
For the sake or robustness, avoid reproducing Perl guts in test file
[perl5.git] / ext / re / re.pm
1 package re;
2
3 # pragma for controlling the regexp engine
4 use strict;
5 use warnings;
6
7 our $VERSION     = "0.18";
8 our @ISA         = qw(Exporter);
9 our @EXPORT_OK   = ('regmust',
10                     qw(is_regexp regexp_pattern
11                        regname regnames regnames_count));
12 our %EXPORT_OK = map { $_ => 1 } @EXPORT_OK;
13
14 my %bitmask = (
15     taint   => 0x00100000, # HINT_RE_TAINT
16     eval    => 0x00200000, # HINT_RE_EVAL
17 );
18
19 my $flags_hint = 0x02000000; # HINT_RE_FLAGS
20 my $PMMOD_SHIFT = 0;
21 my %reflags = (
22     m => 1 << ($PMMOD_SHIFT + 0),
23     s => 1 << ($PMMOD_SHIFT + 1),
24     i => 1 << ($PMMOD_SHIFT + 2),
25     x => 1 << ($PMMOD_SHIFT + 3),
26     p => 1 << ($PMMOD_SHIFT + 4),
27 # special cases:
28     d => 0,
29     l => 1,
30     u => 2,
31     a => 3,
32     aa => 4,
33 );
34
35 sub setcolor {
36  eval {                         # Ignore errors
37   require Term::Cap;
38
39   my $terminal = Tgetent Term::Cap ({OSPEED => 9600}); # Avoid warning.
40   my $props = $ENV{PERL_RE_TC} || 'md,me,so,se,us,ue';
41   my @props = split /,/, $props;
42   my $colors = join "\t", map {$terminal->Tputs($_,1)} @props;
43
44   $colors =~ s/\0//g;
45   $ENV{PERL_RE_COLORS} = $colors;
46  };
47  if ($@) {
48     $ENV{PERL_RE_COLORS} ||= qq'\t\t> <\t> <\t\t';
49  }
50
51 }
52
53 my %flags = (
54     COMPILE         => 0x0000FF,
55     PARSE           => 0x000001,
56     OPTIMISE        => 0x000002,
57     TRIEC           => 0x000004,
58     DUMP            => 0x000008,
59     FLAGS           => 0x000010,
60
61     EXECUTE         => 0x00FF00,
62     INTUIT          => 0x000100,
63     MATCH           => 0x000200,
64     TRIEE           => 0x000400,
65
66     EXTRA           => 0xFF0000,
67     TRIEM           => 0x010000,
68     OFFSETS         => 0x020000,
69     OFFSETSDBG      => 0x040000,
70     STATE           => 0x080000,
71     OPTIMISEM       => 0x100000,
72     STACK           => 0x280000,
73     BUFFERS         => 0x400000,
74     GPOS            => 0x800000,
75 );
76 $flags{ALL} = -1 & ~($flags{OFFSETS}|$flags{OFFSETSDBG}|$flags{BUFFERS});
77 $flags{All} = $flags{all} = $flags{DUMP} | $flags{EXECUTE};
78 $flags{Extra} = $flags{EXECUTE} | $flags{COMPILE} | $flags{GPOS};
79 $flags{More} = $flags{MORE} = $flags{All} | $flags{TRIEC} | $flags{TRIEM} | $flags{STATE};
80 $flags{State} = $flags{DUMP} | $flags{EXECUTE} | $flags{STATE};
81 $flags{TRIE} = $flags{DUMP} | $flags{EXECUTE} | $flags{TRIEC};
82
83 if (defined &DynaLoader::boot_DynaLoader) {
84     require XSLoader;
85     XSLoader::load();
86 }
87 # else we're miniperl
88 # We need to work for miniperl, because the XS toolchain uses Text::Wrap, which
89 # uses re 'taint'.
90
91 sub _load_unload {
92     my ($on)= @_;
93     if ($on) {
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 regexp
100         # hooks. Setting it to a random integer will guarantee
101         # segfaults.
102         $^H{regcomp} = install();
103     } else {
104         delete $^H{regcomp};
105     }
106 }
107
108 sub bits {
109     my $on = shift;
110     my $bits = 0;
111     unless (@_) {
112         require Carp;
113         Carp::carp("Useless use of \"re\" pragma"); 
114     }
115    ARG:
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             last;
140         } elsif (exists $bitmask{$s}) {
141             $bits |= $bitmask{$s};
142         } elsif ($EXPORT_OK{$s}) {
143             require Exporter;
144             re->export_to_level(2, 're', $s);
145         } elsif ($s =~ s/^\///) {
146             my $reflags = $^H{reflags} || 0;
147             my $seen_charset;
148             while ($s =~ m/( . )/gx) {
149                 $_ = $1;
150                 if (/[adul]/) {
151                     # The 'a' may be repeated; hide this from the rest of the
152                     # code by counting and getting rid of all of them, then
153                     # changing to 'aa' if there is a repeat.
154                     if ($_ eq 'a') {
155                         my $sav_pos = pos $s;
156                         my $a_count = $s =~ s/a//g;
157                         pos $s = $sav_pos - 1;  # -1 because got rid of the 'a'
158                         if ($a_count > 2) {
159                             require Carp;
160                             Carp::carp(
161                             qq 'The "a" flag may only appear a maximum of twice'
162                             );
163                         }
164                         elsif ($a_count == 2) {
165                             $_ = 'aa';
166                         }
167                     }
168                     if ($on) {
169                         if ($seen_charset) {
170                             require Carp;
171                             if ($seen_charset ne $_) {
172                                 Carp::carp(
173                                 qq 'The "$seen_charset" and "$_" flags '
174                                 .qq 'are exclusive'
175                                 );
176                             }
177                             else {
178                                 Carp::carp(
179                                 qq 'The "$seen_charset" flag may not appear '
180                                 .qq 'twice'
181                                 );
182                             }
183                         }
184                         $^H{reflags_charset} = $reflags{$_};
185                         $seen_charset = $_;
186                     }
187                     else {
188                         delete $^H{reflags_charset}
189                          if  defined $^H{reflags_charset}
190                           && $^H{reflags_charset} == $reflags{$_};
191                     }
192                 } elsif (exists $reflags{$_}) {
193                     $on
194                       ? $reflags |= $reflags{$_}
195                       : ($reflags &= ~$reflags{$_});
196                 } else {
197                     require Carp;
198                     Carp::carp(
199                      qq'Unknown regular expression flag "$_"'
200                     );
201                     next ARG;
202                 }
203             }
204             ($^H{reflags} = $reflags or defined $^H{reflags_charset})
205              ? $^H |= $flags_hint
206              : ($^H &= ~$flags_hint);
207         } else {
208             require Carp;
209             Carp::carp("Unknown \"re\" subpragma '$s' (known ones are: ",
210                        join(', ', map {qq('$_')} 'debug', 'debugcolor', sort keys %bitmask),
211                        ")");
212         }
213     }
214     $bits;
215 }
216
217 sub import {
218     shift;
219     $^H |= bits(1, @_);
220 }
221
222 sub unimport {
223     shift;
224     $^H &= ~ bits(0, @_);
225 }
226
227 1;
228
229 __END__
230
231 =head1 NAME
232
233 re - Perl pragma to alter regular expression behaviour
234
235 =head1 SYNOPSIS
236
237     use re 'taint';
238     ($x) = ($^X =~ /^(.*)$/s);     # $x is tainted here
239
240     $pat = '(?{ $foo = 1 })';
241     use re 'eval';
242     /foo${pat}bar/;                # won't fail (when not under -T switch)
243
244     {
245         no re 'taint';             # the default
246         ($x) = ($^X =~ /^(.*)$/s); # $x is not tainted here
247
248         no re 'eval';              # the default
249         /foo${pat}bar/;            # disallowed (with or without -T switch)
250     }
251
252     use re '/ix';
253     "FOO" =~ / foo /; # /ix implied
254     no re '/x';
255     "FOO" =~ /foo/; # just /i implied
256
257     use re 'debug';                # output debugging info during
258     /^(.*)$/s;                     #     compile and run time
259
260
261     use re 'debugcolor';           # same as 'debug', but with colored output
262     ...
263
264     use re qw(Debug All);          # Finer tuned debugging options.
265     use re qw(Debug More);
266     no re qw(Debug ALL);           # Turn of all re debugging in this scope
267
268     use re qw(is_regexp regexp_pattern); # import utility functions
269     my ($pat,$mods)=regexp_pattern(qr/foo/i);
270     if (is_regexp($obj)) { 
271         print "Got regexp: ",
272             scalar regexp_pattern($obj); # just as perl would stringify it
273     }                                    # but no hassle with blessed re's.
274
275 (We use $^X in these examples because it's tainted by default.)
276
277 =head1 DESCRIPTION
278
279 =head2 'taint' mode
280
281 When C<use re 'taint'> is in effect, and a tainted string is the target
282 of a regexp, the regexp memories (or values returned by the m// operator
283 in list context) are tainted.  This feature is useful when regexp operations
284 on tainted data aren't meant to extract safe substrings, but to perform
285 other transformations.
286
287 =head2 'eval' mode
288
289 When C<use re 'eval'> is in effect, a regexp is allowed to contain
290 C<(?{ ... })> zero-width assertions and C<(??{ ... })> postponed
291 subexpressions, even if the regular expression contains
292 variable interpolation.  That is normally disallowed, since it is a
293 potential security risk.  Note that this pragma is ignored when the regular
294 expression is obtained from tainted data, i.e.  evaluation is always
295 disallowed with tainted regular expressions.  See L<perlre/(?{ code })> 
296 and L<perlre/(??{ code })>.
297
298 For the purpose of this pragma, interpolation of precompiled regular
299 expressions (i.e., the result of C<qr//>) is I<not> considered variable
300 interpolation.  Thus:
301
302     /foo${pat}bar/
303
304 I<is> allowed if $pat is a precompiled regular expression, even
305 if $pat contains C<(?{ ... })> assertions or C<(??{ ... })> subexpressions.
306
307 =head2 '/flags' mode
308
309 When C<use re '/flags'> is specified, the given flags are automatically
310 added to every regular expression till the end of the lexical scope.
311
312 C<no re '/flags'> will turn off the effect of C<use re '/flags'> for the
313 given flags.
314
315 For example, if you want all your regular expressions to have /msx on by
316 default, simply put
317
318     use re '/msx';
319
320 at the top of your code.
321
322 The character set /adul flags cancel each other out. So, in this example,
323
324     use re "/u";
325     "ss" =~ /\xdf/;
326     use re "/d";
327     "ss" =~ /\xdf/;
328
329 the second C<use re> does an implicit C<no re '/u'>.
330
331 Turning on one of the character set flags with C<use re> takes precedence over the
332 C<locale> pragma and the 'unicode_strings' C<feature>, for regular
333 expressions. Turning off one of these flags when it is active reverts to
334 the behaviour specified by whatever other pragmata are in scope. For
335 example:
336
337     use feature "unicode_strings";
338     no re "/u"; # does nothing
339     use re "/l";
340     no re "/l"; # reverts to unicode_strings behaviour
341
342 =head2 'debug' mode
343
344 When C<use re 'debug'> is in effect, perl emits debugging messages when
345 compiling and using regular expressions.  The output is the same as that
346 obtained by running a C<-DDEBUGGING>-enabled perl interpreter with the
347 B<-Dr> switch. It may be quite voluminous depending on the complexity
348 of the match.  Using C<debugcolor> instead of C<debug> enables a
349 form of output that can be used to get a colorful display on terminals
350 that understand termcap color sequences.  Set C<$ENV{PERL_RE_TC}> to a
351 comma-separated list of C<termcap> properties to use for highlighting
352 strings on/off, pre-point part on/off.
353 See L<perldebug/"Debugging Regular Expressions"> for additional info.
354
355 As of 5.9.5 the directive C<use re 'debug'> and its equivalents are
356 lexically scoped, as the other directives are.  However they have both 
357 compile-time and run-time effects.
358
359 See L<perlmodlib/Pragmatic Modules>.
360
361 =head2 'Debug' mode
362
363 Similarly C<use re 'Debug'> produces debugging output, the difference
364 being that it allows the fine tuning of what debugging output will be
365 emitted. Options are divided into three groups, those related to
366 compilation, those related to execution and those related to special
367 purposes. The options are as follows:
368
369 =over 4
370
371 =item Compile related options
372
373 =over 4
374
375 =item COMPILE
376
377 Turns on all compile related debug options.
378
379 =item PARSE
380
381 Turns on debug output related to the process of parsing the pattern.
382
383 =item OPTIMISE
384
385 Enables output related to the optimisation phase of compilation.
386
387 =item TRIEC
388
389 Detailed info about trie compilation.
390
391 =item DUMP
392
393 Dump the final program out after it is compiled and optimised.
394
395 =back
396
397 =item Execute related options
398
399 =over 4
400
401 =item EXECUTE
402
403 Turns on all execute related debug options.
404
405 =item MATCH
406
407 Turns on debugging of the main matching loop.
408
409 =item TRIEE
410
411 Extra debugging of how tries execute.
412
413 =item INTUIT
414
415 Enable debugging of start point optimisations.
416
417 =back
418
419 =item Extra debugging options
420
421 =over 4
422
423 =item EXTRA
424
425 Turns on all "extra" debugging options.
426
427 =item BUFFERS
428
429 Enable debugging the capture group storage during match. Warning,
430 this can potentially produce extremely large output.
431
432 =item TRIEM
433
434 Enable enhanced TRIE debugging. Enhances both TRIEE
435 and TRIEC.
436
437 =item STATE
438
439 Enable debugging of states in the engine.
440
441 =item STACK
442
443 Enable debugging of the recursion stack in the engine. Enabling
444 or disabling this option automatically does the same for debugging
445 states as well. This output from this can be quite large.
446
447 =item OPTIMISEM
448
449 Enable enhanced optimisation debugging and start point optimisations.
450 Probably not useful except when debugging the regexp engine itself.
451
452 =item OFFSETS
453
454 Dump offset information. This can be used to see how regops correlate
455 to the pattern. Output format is
456
457    NODENUM:POSITION[LENGTH]
458
459 Where 1 is the position of the first char in the string. Note that position
460 can be 0, or larger than the actual length of the pattern, likewise length
461 can be zero.
462
463 =item OFFSETSDBG
464
465 Enable debugging of offsets information. This emits copious
466 amounts of trace information and doesn't mesh well with other
467 debug options.
468
469 Almost definitely only useful to people hacking
470 on the offsets part of the debug engine.
471
472 =back
473
474 =item Other useful flags
475
476 These are useful shortcuts to save on the typing.
477
478 =over 4
479
480 =item ALL
481
482 Enable all options at once except OFFSETS, OFFSETSDBG and BUFFERS
483
484 =item All
485
486 Enable DUMP and all execute options. Equivalent to:
487
488   use re 'debug';
489
490 =item MORE
491
492 =item More
493
494 Enable TRIEM and all execute compile and execute options.
495
496 =back
497
498 =back
499
500 As of 5.9.5 the directive C<use re 'debug'> and its equivalents are
501 lexically scoped, as the other directives are.  However they have both
502 compile-time and run-time effects.
503
504 =head2 Exportable Functions
505
506 As of perl 5.9.5 're' debug contains a number of utility functions that
507 may be optionally exported into the caller's namespace. They are listed
508 below.
509
510 =over 4
511
512 =item is_regexp($ref)
513
514 Returns true if the argument is a compiled regular expression as returned
515 by C<qr//>, false if it is not.
516
517 This function will not be confused by overloading or blessing. In
518 internals terms, this extracts the regexp pointer out of the
519 PERL_MAGIC_qr structure so it cannot be fooled.
520
521 =item regexp_pattern($ref)
522
523 If the argument is a compiled regular expression as returned by C<qr//>,
524 then this function returns the pattern.
525
526 In list context it returns a two element list, the first element
527 containing the pattern and the second containing the modifiers used when
528 the pattern was compiled.
529
530   my ($pat, $mods) = regexp_pattern($ref);
531
532 In scalar context it returns the same as perl would when stringifying a raw
533 C<qr//> with the same pattern inside.  If the argument is not a compiled
534 reference then this routine returns false but defined in scalar context,
535 and the empty list in list context. Thus the following
536
537     if (regexp_pattern($ref) eq '(?^i:foo)')
538
539 will be warning free regardless of what $ref actually is.
540
541 Like C<is_regexp> this function will not be confused by overloading
542 or blessing of the object.
543
544 =item regmust($ref)
545
546 If the argument is a compiled regular expression as returned by C<qr//>,
547 then this function returns what the optimiser considers to be the longest
548 anchored fixed string and longest floating fixed string in the pattern.
549
550 A I<fixed string> is defined as being a substring that must appear for the
551 pattern to match. An I<anchored fixed string> is a fixed string that must
552 appear at a particular offset from the beginning of the match. A I<floating
553 fixed string> is defined as a fixed string that can appear at any point in
554 a range of positions relative to the start of the match. For example,
555
556     my $qr = qr/here .* there/x;
557     my ($anchored, $floating) = regmust($qr);
558     print "anchored:'$anchored'\nfloating:'$floating'\n";
559
560 results in
561
562     anchored:'here'
563     floating:'there'
564
565 Because the C<here> is before the C<.*> in the pattern, its position
566 can be determined exactly. That's not true, however, for the C<there>;
567 it could appear at any point after where the anchored string appeared.
568 Perl uses both for its optimisations, prefering the longer, or, if they are
569 equal, the floating.
570
571 B<NOTE:> This may not necessarily be the definitive longest anchored and
572 floating string. This will be what the optimiser of the Perl that you
573 are using thinks is the longest. If you believe that the result is wrong
574 please report it via the L<perlbug> utility.
575
576 =item regname($name,$all)
577
578 Returns the contents of a named buffer of the last successful match. If
579 $all is true, then returns an array ref containing one entry per buffer,
580 otherwise returns the first defined buffer.
581
582 =item regnames($all)
583
584 Returns a list of all of the named buffers defined in the last successful
585 match. If $all is true, then it returns all names defined, if not it returns
586 only names which were involved in the match.
587
588 =item regnames_count()
589
590 Returns the number of distinct names defined in the pattern used
591 for the last successful match.
592
593 B<Note:> this result is always the actual number of distinct
594 named buffers defined, it may not actually match that which is
595 returned by C<regnames()> and related routines when those routines
596 have not been called with the $all parameter set.
597
598 =back
599
600 =head1 SEE ALSO
601
602 L<perlmodlib/Pragmatic Modules>.
603
604 =cut