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