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