1PPIx::Regexp(3) User Contributed Perl Documentation PPIx::Regexp(3)
2
3
4
6 PPIx::Regexp - Represent a regular expression of some sort
7
9 use PPIx::Regexp;
10 use PPIx::Regexp::Dumper;
11 my $re = PPIx::Regexp->new( 'qr{foo}smx' );
12 PPIx::Regexp::Dumper->new( $re )
13 ->print();
14
16 "PPIx::Regexp" is a PPIx::Regexp::Node.
17
18 "PPIx::Regexp" has no descendants.
19
21 The purpose of the PPIx-Regexp package is to parse regular expressions
22 in a manner similar to the way the PPI package parses Perl. This class
23 forms the root of the parse tree, playing a role similar to
24 PPI::Document.
25
26 This package shares with PPI the property of being round-trip safe.
27 That is,
28
29 my $expr = 's/ ( \d+ ) ( \D+ ) /$2$1/smxg';
30 my $re = PPIx::Regexp->new( $expr );
31 print $re->content() eq $expr ? "yes\n" : "no\n"
32
33 should print 'yes' for any valid regular expression.
34
35 Navigation is similar to that provided by PPI. That is to say, things
36 like "children", "find_first", "snext_sibling" and so on all work
37 pretty much the same way as in PPI.
38
39 The class hierarchy is also similar to PPI. Except for some utility
40 classes (the dumper, the lexer, and the tokenizer) all classes are
41 descended from PPIx::Regexp::Element, which provides basic navigation.
42 Tokens are descended from PPIx::Regexp::Token, which provides content.
43 All containers are descended from PPIx::Regexp::Node, which provides
44 for children, and all structure elements are descended from
45 PPIx::Regexp::Structure, which provides beginning and ending
46 delimiters, and a type.
47
48 There are two features of PPI that this package does not provide -
49 mutability and operator overloading. There are no plans for serious
50 mutability, though something like PPI's "prune" functionality might be
51 considered. Similarly there are no plans for operator overloading,
52 which appears to the author to represent a performance hit for little
53 tangible gain.
54
56 The use of this class to parse non-regexp quote-like strings was an
57 experiment that I consider failed. Therefore this use is deprecated in
58 favor of PPIx::QuoteLike. As of version 0.058_01, the first use of the
59 "parse" argument to new() resulted in a warning. As of version
60 0.062_01, all uses of the "parse" argument resulted in a warning. After
61 another six months, the "parse" argument will become fatal.
62
63 The author will attempt to preserve the documented interface, but if
64 the interface needs to change to correct some egregiously bad design or
65 implementation decision, then it will change. Any incompatible changes
66 will go through a deprecation cycle.
67
68 The goal of this package is to parse well-formed regular expressions
69 correctly. A secondary goal is not to blow up on ill-formed regular
70 expressions. The correct identification and characterization of ill-
71 formed regular expressions is not a goal of this package, nor is the
72 consistent parsing of ill-formed regular expressions from release to
73 release.
74
75 This policy attempts to track features in development releases as well
76 as public releases. However, features added in a development release
77 and then removed before the next production release will not be
78 tracked, and any functionality relating to such features will be
79 removed. The issue here is the potential re-use (with different
80 semantics) of syntax that did not make it into the production release.
81
82 From time to time the Perl regular expression engine changes in ways
83 that change the parse of a given regular expression. When these changes
84 occur, "PPIx::Regexp" will be changed to produce the more modern parse.
85 Known examples of this include:
86
87 $( no longer interpolates as of Perl 5.005, per "perl5005delta".
88 Newer Perls seem to parse this as "qr{$}" (i.e. and end-of-string
89 or newline assertion) followed by an open parenthesis, and that is
90 what "PPIx::Regexp" does.
91
92 $) and $| also seem to parse as the "$" assertion
93 followed by the relevant meta-character, though I have no
94 documentation reference for this.
95
96 "@+" and "@-" no longer interpolate as of Perl 5.9.4
97 per "perl594delta". Subsequent Perls treat "@+" as a quantified
98 literal and "@-" as two literals, and that is what "PPIx::Regexp"
99 does. Note that subscripted references to these arrays do
100 interpolate, and are so parsed by "PPIx::Regexp".
101
102 Only space and horizontal tab are whitespace as of Perl 5.23.4
103 when inside a bracketed character class inside an extended
104 bracketed character class, per "perl5234delta". Formerly any white
105 space character parsed as whitespace. This change in "PPIx::Regexp"
106 will be reverted if the change in Perl does not make it into Perl
107 5.24.0.
108
109 Unescaped literal left curly brackets
110 These are being removed in positions where quantifiers are legal,
111 so that they can be used for new functionality. Some of them are
112 gone in 5.25.1, others will be removed in a future version of Perl.
113 In situations where they have been removed, perl_version_removed()
114 will return the version in which they were removed. When the new
115 functionality appears, the parse produced by this software will
116 reflect the new functionality.
117
118 NOTE that the situation with a literal left curly after a literal
119 character is complicated. It was made an error in Perl 5.25.1, and
120 remained so through all 5.26 releases, but became a warning again
121 in 5.27.1 due to its use in GNU Autoconf. Whether it will ever
122 become illegal again is not clear to me based on the contents of
123 perl5271delta. At the moment perl_version_removed() returns
124 "undef", but obviously that is not the whole story, and methods
125 accepts_perl() and requirements_for_perl() were introduced to deal
126 with this complication.
127
128 "\o{...}"
129 is parsed as the octal equivalent of "\x{...}". This is its meaning
130 as of perl 5.13.2. Before 5.13.2 it was simply literal 'o' and so
131 on.
132
133 There are very probably other examples of this. When they come to light
134 they will be documented as producing the modern parse, and the code
135 modified to produce this parse if necessary.
136
138 This class provides the following public methods. Methods not
139 documented here are private, and unsupported in the sense that the
140 author reserves the right to change or remove them without notice.
141
142 new
143 my $re = PPIx::Regexp->new('/foo/');
144
145 This method instantiates a "PPIx::Regexp" object from a string, a
146 PPI::Token::QuoteLike::Regexp, a PPI::Token::Regexp::Match, or a
147 PPI::Token::Regexp::Substitute. Honestly, any PPI::Element will work,
148 but only the three Regexp classes mentioned previously are likely to do
149 anything useful.
150
151 Whatever form the argument takes, it is assumed to consist entirely of
152 a valid match, substitution, or "qr<>" string.
153
154 Optionally you can pass one or more name/value pairs after the regular
155 expression. The possible options are:
156
157 default_modifiers array_reference
158 This option specifies a reference to an array of default modifiers
159 to apply to the regular expression being parsed. Each modifier is
160 specified as a string. Any actual modifiers found supersede the
161 defaults.
162
163 When applying the defaults, '?' and '/' are completely ignored, and
164 '^' is ignored unless it occurs at the beginning of the modifier.
165 The first dash ('-') causes subsequent modifiers to be negated.
166
167 So, for example, if you wish to produce a "PPIx::Regexp" object
168 representing the regular expression in
169
170 use re '/smx';
171 {
172 no re '/x';
173 m/ foo /;
174 }
175
176 you would (after some help from PPI in finding the relevant
177 statements), do something like
178
179 my $re = PPIx::Regexp->new( 'm/ foo /',
180 default_modifiers => [ '/smx', '-/x' ] );
181
182 encoding name
183 This option specifies the encoding of the regular expression. This
184 is passed to the tokenizer, which will "decode" the regular
185 expression string before it tokenizes it. For example:
186
187 my $re = PPIx::Regexp->new( '/foo/',
188 encoding => 'iso-8859-1',
189 );
190
191 parse parse_type
192 This option specifies what kind of parse is to be done. Possible
193 values are 'regex', 'string', or 'guess'. Any value but 'regex' is
194 experimental.
195
196 As it turns out, I consider parsing non-regexp quote-like things
197 with this class to be a failed experiment, and the relevant
198 functionality is being deprecated and removed in favor of
199 PPIx::QuoteLike. See above for details.
200
201 If 'regex' is specified, the first argument is expected to be a
202 valid regex, and parsed as though it were.
203
204 If 'string' is specified, the first argument is expected to be a
205 valid string literal and parsed as such. The return is still a
206 "PPIx::Regexp" object, but the regular_expression() and modifier()
207 methods return nothing, and the replacement() method returns the
208 content of the string.
209
210 If 'guess' is specified, this method will try to guess what the
211 first argument is. If the first argument is a PPI::Element, the
212 guess will reflect the PPI parse. But the guess can be wrong if the
213 first argument is a string representing an unusually-delimited
214 regex. For example, 'guess' will parse "foo" as a string, but Perl
215 will parse it as a regex if preceded by a regex binding operator
216 (e.g. "$x =~ "foo""), as shown by
217
218 perl -MO=Deparse -e '$x =~ "foo"'
219
220 which prints
221
222 $x =~ /foo/u
223
224 under Perl 5.22.0.
225
226 The default is 'regex'.
227
228 postderef boolean
229 This option is passed on to the tokenizer, where it specifies
230 whether postfix dereferences are recognized in interpolations and
231 code. This experimental feature was introduced in Perl 5.19.5.
232
233 The default is the value of
234 $PPIx::Regexp::Tokenizer::DEFAULT_POSTDEREF, which is true. When
235 originally introduced this was false, but was documented as
236 becoming true when and if postfix dereferencing became mainstream.
237 The intent to mainstream was announced with Perl 5.23.1, and
238 became official (so to speak) with Perl 5.24.0, so the default
239 became true with PPIx::Regexp 0.049_01.
240
241 Note that if PPI starts unconditionally recognizing postfix
242 dereferences, this argument will immediately become ignored, and
243 will be put through a deprecation cycle and removed.
244
245 strict boolean
246 This option is passed on to the tokenizer and lexer, where it
247 specifies whether the parse should assume "use re 'strict'" is in
248 effect.
249
250 The 'strict' pragma was introduced in Perl 5.22, and its
251 documentation says that it is experimental, and that there is no
252 commitment to backward compatibility. The same applies to the parse
253 produced when this option is asserted. Also, the usual caveat
254 applies: if "use re 'strict'" ends up being retracted, this option
255 and all related functionality will be also.
256
257 Given the nature of "use re 'strict'", you should expect that if
258 you assert this option, regular expressions that previously parsed
259 without error might no longer do so. If an element ends up being
260 declared an error because this option is set, its
261 "perl_version_introduced()" will be the Perl version at which "use
262 re 'strict'" started rejecting these elements.
263
264 The default is false.
265
266 trace number
267 If greater than zero, this option causes trace output from the
268 parse. The author reserves the right to change or eliminate this
269 without notice.
270
271 Passing optional input other than the above is not an error, but
272 neither is it supported.
273
274 new_from_cache
275 This static method wraps "new" in a caching mechanism. Only one object
276 will be generated for a given PPI::Element, no matter how many times
277 this method is called. Calls after the first for a given PPI::Element
278 simply return the same "PPIx::Regexp" object.
279
280 When the "PPIx::Regexp" object is returned from cache, the values of
281 the optional arguments are ignored.
282
283 Calls to this method with the regular expression in a string rather
284 than a PPI::Element will not be cached.
285
286 Caveat: This method is provided for code like Perl::Critic which might
287 instantiate the same object multiple times. The cache will persist
288 until "flush_cache" is called.
289
290 flush_cache
291 $re->flush_cache(); # Remove $re from cache
292 PPIx::Regexp->flush_cache(); # Empty the cache
293
294 This method flushes the cache used by "new_from_cache". If called as a
295 static method with no arguments, the entire cache is emptied. Otherwise
296 any objects specified are removed from the cache.
297
298 capture_names
299 foreach my $name ( $re->capture_names() ) {
300 print "Capture name '$name'\n";
301 }
302
303 This convenience method returns the capture names found in the regular
304 expression.
305
306 This method is equivalent to
307
308 $self->regular_expression()->capture_names();
309
310 except that if "$self->regular_expression()" returns "undef" (meaning
311 that something went terribly wrong with the parse) this method will
312 simply return.
313
314 delimiters
315 print join("\t", PPIx::Regexp->new('s/foo/bar/')->delimiters());
316 # prints '// //'
317
318 When called in list context, this method returns either one or two
319 strings, depending on whether the parsed expression has a replacement
320 string. In the case of non-bracketed substitutions, the start delimiter
321 of the replacement string is considered to be the same as its finish
322 delimiter, as illustrated by the above example.
323
324 When called in scalar context, you get the delimiters of the regular
325 expression; that is, element 0 of the array that is returned in list
326 context.
327
328 Optionally, you can pass an index value and the corresponding
329 delimiters will be returned; index 0 represents the regular
330 expression's delimiters, and index 1 represents the replacement
331 string's delimiters, which may be undef. For example,
332
333 print PPIx::Regexp->new('s{foo}<bar>')->delimiters(1);
334 # prints '<>'
335
336 If the object was not initialized with a valid regexp of some sort, the
337 results of this method are undefined.
338
339 errstr
340 This static method returns the error string from the most recent
341 attempt to instantiate a "PPIx::Regexp". It will be "undef" if the most
342 recent attempt succeeded.
343
344 extract_regexps
345 my $doc = PPI::Document->new( $path );
346 $doc->index_locations();
347 my @res = PPIx::Regexp->extract_regexps( $doc )
348
349 This convenience (well, sort-of) static method takes as its argument a
350 PPI::Document object and returns "PPIx::Regexp" objects corresponding
351 to all regular expressions found in it, in the order in which they
352 occur in the document. You will need to keep a reference to the
353 original PPI::Document object if you wish to be able to recover the
354 original PPI::Element objects via the PPIx::Regexp source() method.
355
356 failures
357 print "There were ", $re->failures(), " parse failures\n";
358
359 This method returns the number of parse failures. This is a count of
360 the number of unknown tokens plus the number of unterminated structures
361 plus the number of unmatched right brackets of any sort.
362
363 max_capture_number
364 print "Highest used capture number ",
365 $re->max_capture_number(), "\n";
366
367 This convenience method returns the highest capture number used by the
368 regular expression. If there are no captures, the return will be 0.
369
370 This method is equivalent to
371
372 $self->regular_expression()->max_capture_number();
373
374 except that if "$self->regular_expression()" returns "undef" (meaning
375 that something went terribly wrong with the parse) this method will
376 too.
377
378 modifier
379 my $re = PPIx::Regexp->new( 's/(foo)/${1}bar/smx' );
380 print $re->modifier()->content(), "\n";
381 # prints 'smx'.
382
383 This method retrieves the modifier of the object. This comes from the
384 end of the initializing string or object and will be a
385 PPIx::Regexp::Token::Modifier.
386
387 Note that this object represents the actual modifiers present on the
388 regexp, and does not take into account any that may have been applied
389 by default (i.e. via the "default_modifiers" argument to "new()"). For
390 something that takes account of default modifiers, see
391 modifier_asserted(), below.
392
393 In the event of a parse failure, there may not be a modifier present,
394 in which case nothing is returned.
395
396 modifier_asserted
397 my $re = PPIx::Regexp->new( '/ . /',
398 default_modifiers => [ 'smx' ] );
399 print $re->modifier_asserted( 'x' ) ? "yes\n" : "no\n";
400 # prints 'yes'.
401
402 This method returns true if the given modifier is asserted for the
403 regexp, whether explicitly or by the modifiers passed in the
404 "default_modifiers" argument.
405
406 Starting with version 0.036_01, if the argument is a single-character
407 modifier followed by an asterisk (intended as a wild card character),
408 the return is the number of times that modifier appears. In this case
409 an exception will be thrown if you specify a multi-character modifier
410 (e.g. 'ee*'), or if you specify one of the match semantics modifiers
411 (e.g. 'a*').
412
413 regular_expression
414 my $re = PPIx::Regexp->new( 's/(foo)/${1}bar/smx' );
415 print $re->regular_expression()->content(), "\n";
416 # prints '/(foo)/'.
417
418 This method returns that portion of the object which actually
419 represents a regular expression.
420
421 replacement
422 my $re = PPIx::Regexp->new( 's/(foo)/${1}bar/smx' );
423 print $re->replacement()->content(), "\n";
424 # prints '${1}bar/'.
425
426 This method returns that portion of the object which represents the
427 replacement string. This will be "undef" unless the regular expression
428 actually has a replacement string. Delimiters will be included, but
429 there will be no beginning delimiter unless the regular expression was
430 bracketed.
431
432 source
433 my $source = $re->source();
434
435 This method returns the object or string that was used to instantiate
436 the object.
437
438 type
439 my $re = PPIx::Regexp->new( 's/(foo)/${1}bar/smx' );
440 print $re->type()->content(), "\n";
441 # prints 's'.
442
443 This method retrieves the type of the object. This comes from the
444 beginning of the initializing string or object, and will be a
445 PPIx::Regexp::Token::Structure whose "content" is one of 's', 'm',
446 'qr', or ''.
447
449 By the nature of this module, it is never going to get everything
450 right. Many of the known problem areas involve interpolations one way
451 or another.
452
453 Ambiguous Syntax
454 Perl's regular expressions contain cases where the syntax is ambiguous.
455 A particularly egregious example is an interpolation followed by square
456 or curly brackets, for example $foo[...]. There is nothing in the
457 syntax to say whether the programmer wanted to interpolate an element
458 of array @foo, or whether he wanted to interpolate scalar $foo, and
459 then follow that interpolation by a character class.
460
461 The perlop documentation notes that in this case what Perl does is to
462 guess. That is, it employs various heuristics on the code to try to
463 figure out what the programmer wanted. These heuristics are documented
464 as being undocumented (!) and subject to change without notice. As an
465 example of the problems even perl faces in parsing Perl, see
466 <https://rt.perl.org/Public/Bug/Display.html?id=133027>.
467
468 Given this situation, this module's chances of duplicating every Perl
469 version's interpretation of every regular expression are pretty much
470 nil. What it does now is to assume that square brackets containing
471 only an integer or an interpolation represent a subscript; otherwise
472 they represent a character class. Similarly, curly brackets containing
473 only a bareword or an interpolation are a subscript; otherwise they
474 represent a quantifier.
475
476 Changes in Syntax
477 Sometimes the introduction of new syntax changes the way a regular
478 expression is parsed. For example, the "\v" character class was
479 introduced in Perl 5.9.5. But it did not represent a syntax error prior
480 to that version of Perl, it was simply parsed as "v". So
481
482 $ perl -le 'print "v" =~ m/\v/ ? "yes" : "no"'
483
484 prints "yes" under Perl 5.8.9, but "no" under 5.10.0. "PPIx::Regexp"
485 generally assumes the more modern parse in cases like this.
486
487 Equivocation
488 Very occasionally, a construction will be removed and then added back
489 -- and then, conceivably, removed again. In this case, the plan is for
490 perl_version_introduced() to return the earliest version in which the
491 construction appeared, and perl_version_removed() to return the version
492 after the last version in which it appeared (whether production or
493 development), or "undef" if it is in the highest-numbered Perl.
494
495 The constructions involved in this are:
496
497 Un-escaped literal left curly after literal
498
499 That is, something like "qr<x{>".
500
501 This was made an error in 5.25.1, and it was an error in 5.26.0. But
502 it became a warning again in 5.27.1. The perl5271delta says it was re-
503 instated because the changes broke GNU Autoconf, and the warning
504 message says it will be removed in Perl 5.30.
505
506 Accordingly, perl_version_introduced() returns 5.0. At the moment
507 perl_version_removed() returns '5.025001'. But if it is present with or
508 without warning in 5.28, perl_version_removed() will become "undef". If
509 you need finer resolution than this, see PPIx::Regexp::Element methods
510 l<accepts_perl()|PPIx::Regexp::Element/accepts_perl> and
511 l<requirements_for_perl()|PPIx::Regexp::Element/requirements_for_perl>
512
513 Static Parsing
514 It is well known that Perl can not be statically parsed. That is, you
515 can not completely parse a piece of Perl code without executing that
516 same code.
517
518 Nevertheless, this class is trying to statically parse regular
519 expressions. The main problem with this is that there is no way to know
520 what is being interpolated into the regular expression by an
521 interpolated variable. This is a problem because the interpolated value
522 can change the interpretation of adjacent elements.
523
524 This module deals with this by making assumptions about what is in an
525 interpolated variable. These assumptions will not be enumerated here,
526 but in general the principal is to assume the interpolated value does
527 not change the interpretation of the regular expression. For example,
528
529 my $foo = 'a-z]';
530 my $re = qr{[$foo};
531
532 is fine with the Perl interpreter, but will confuse the dickens out of
533 this module. Similarly and more usefully, something like
534
535 my $mods = 'i';
536 my $re = qr{(?$mods:foo)};
537
538 or maybe
539
540 my $mods = 'i';
541 my $re = qr{(?$mods)$foo};
542
543 probably sets a modifier of some sort, and that is how this module
544 interprets it. If the interpolation is not about modifiers, this module
545 will get it wrong. Another such semi-benign example is
546
547 my $foo = $] >= 5.010 ? '?<foo>' : '';
548 my $re = qr{($foo\w+)};
549
550 which will parse, but this module will never realize that it might be
551 looking at a named capture.
552
553 Non-Standard Syntax
554 There are modules out there that alter the syntax of Perl. If the
555 syntax of a regular expression is altered, this module has no way to
556 understand that it has been altered, much less to adapt to the
557 alteration. The following modules are known to cause problems:
558
559 Acme::PerlML, which renders Perl as XML.
560
561 "Data::PostfixDeref", which causes Perl to interpret suffixed empty
562 brackets as dereferencing the thing they suffix. This module by Ben
563 Morrow ("BMORROW") appears to have been retracted.
564
565 Filter::Trigraph, which recognizes ANSI C trigraphs, allowing Perl to
566 be written in the ISO 646 character set.
567
568 Perl6::Pugs. Enough said.
569
570 Perl6::Rules, which back-ports some of the Perl 6 regular expression
571 syntax to Perl 5.
572
573 Regexp::Extended, which extends regular expressions in various ways,
574 some of which seem to conflict with Perl 5.010.
575
577 Regexp::Parsertron, which uses Marpa::R2 to parse the regexp, and Tree
578 for navigation. Unlike "PPIx::Regexp|PPIx::Regexp", Regexp::Parsertron
579 supports modification of the parse tree.
580
581 Regexp::Parser, which parses a bare regular expression (without
582 enclosing "qr{}", "m//", or whatever) and uses a different navigation
583 model. After a long hiatus, this module has been adopted, and is again
584 supported.
585
587 Support is by the author. Please file bug reports at
588 <http://rt.cpan.org>, or in electronic mail to the author.
589
591 Thomas R. Wyant, III wyant at cpan dot org
592
594 Copyright (C) 2009-2019 by Thomas R. Wyant, III
595
596 This program is free software; you can redistribute it and/or modify it
597 under the same terms as Perl 5.10.0. For more details, see the full
598 text of the licenses in the directory LICENSES.
599
600 This program is distributed in the hope that it will be useful, but
601 without any warranty; without even the implied warranty of
602 merchantability or fitness for a particular purpose.
603
604
605
606perl v5.30.0 2019-09-02 PPIx::Regexp(3)