Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Teaching Rakudo the tricks of Perl 5's regex optimiser

3 views
Skip to first unread message

Nicholas Clark

unread,
Aug 13, 2019, 6:00:03 AM8/13/19
to perl6-c...@perl.org
I'm cheating here - I'm using an e-mail message as a way to publish some notes
for Jonathan (or *anyone else interested*):

Jonathan did a talk in Riga, Perl 6 performance update,
https://perlcon.eu/talk/80
The (re-uploaded) live stream is at
https://www.youtube.com/watch?v=S5iVBlk7pdg#t=4h39m

One thing that this talk revealed is that (currently) Perl 5 beats
Rakudo on various regular expressions. What *I* know is that this is because
Perl 5 cheats - it has an "optimiser", which happens to automatically do
what jnthn then showed manually implemented in some of his benchmarks.

You can see what the Perl 5 regex optimiser is doing by using the re pragma.
I'm no expert on this thing, but playing with it, I can see that it can do
various things

0) Know that it can't do anything useful (it is skipped)
1) Know that a fixed string must be present
Look for it (which is fast), not find it, and immediately return "no match"
2) Know that a fixed string must be present
Look for it find it, carry on into the real engine
(which arguably is slower than no optimiser)
3) Know that a fixed string must be present, *and* is the entire match
Look for it (which is fast), find it, and immediately return "match".

Clearly cases (1) and (3) are the big wins here. Case (3) was the one I had
forgotten about - the cheating is so good that often the engine is never
entered.


So, if you run this:

$ perl -wle 'use re "debug"; print "Perl rules" =~ /^Perl/ ? "Y" : "n"'
Compiling REx "^Perl"
Final program:
1: SBOL /^/ (2)
2: EXACT <Perl> (4)
4: END (0)
anchored "Perl" at 0 (checking anchored noscan) anchored(SBOL) minlen 4
Matching REx "^Perl" against "Perl rules"
Intuit: trying to determine minimum start position...
Looking for check substr at fixed offset 0...
Intuit: Successfully guessed: match at offset 0
0 <> <Perl rules> | 0| 1:SBOL /^/(2)
0 <> <Perl rules> | 0| 2:EXACT <Perl>(4)
4 <Perl> < rules> | 0| 4:END(0)
Match successful!
Y
Freeing REx: "^Perl"


"Final program" describes how the regex ended up being compiled. This isn't
really of interest here.

What is of interest is the parts between the two lines "Intuit". That's the
optimiser. For the case I specifically chose here, what we have is that

1) the optimiser knows that the fixed string "Perl" must be in target string
2) which it searches for and finds
3) at which point it calls the main engine (these lines):

0 <> <Perl rules> | 0| 1:SBOL /^/(2)
0 <> <Perl rules> | 0| 2:EXACT <Perl>(4)
4 <Perl> < rules> | 0| 4:END(0)

(that part isn't actually of interest here. I'm just noting it as "this is
the main engine, and comparable to what Rakudo does).


The interesting cases are things like:

$ perl -wle 'use re "debug"; print "Perl rules" =~ /er./ ? "Y" : "n"'
Compiling REx "er."
Final program:
1: EXACT <er> (3)
3: REG_ANY (4)
4: END (0)
anchored "er" at 0 (checking anchored) minlen 3
Matching REx "er." against "Perl rules"
Intuit: trying to determine minimum start position...
doing 'check' fbm scan, [0..9] gave 1
Found anchored substr "er" at offset 1 (rx_origin now 1)...
(multiline anchor test skipped)
try at offset...
Intuit: Successfully guessed: match at offset 1
1 <P> <erl rules> | 0| 1:EXACT <er>(3)
3 <Per> <l rules> | 0| 3:REG_ANY(4)
4 <Perl> < rules> | 0| 4:END(0)
Match successful!
Y
Freeing REx: "er."


You can see that
1) the compiler records that the longest fixed string is 'er'
2) the optimiser looks for this before even hitting the real engine
3) the optimiser tells the real engine that it doesn't even need to consider
trying to match at string offset 0


and this:

$ perl -wle 'use re "debug"; print "Perl rules" =~ /er/ ? "Y" : "n"'
Compiling REx "er"
Final program:
1: EXACT <er> (3)
3: END (0)
anchored "er" at 0 (checking anchored isall) minlen 2
Matching REx "er" against "Perl rules"
Intuit: trying to determine minimum start position...
doing 'check' fbm scan, [0..10] gave 1
Found anchored substr "er" at offset 1 (rx_origin now 1)...
(multiline anchor test skipped)
try at offset...
Intuit: Successfully guessed: match at offset 1
Y
Freeing REx: "er"


The optimiser matches, and knows that if its crib[1] matches, the entire
regex must match, so it doesn't even call into the engine.


and this:

$ perl -wle 'use re "debug"; print "Perl rules" =~ /Good *, #MoarVM/ ? "Y" : "n"'
Compiling REx "Good *, #MoarVM"
Final program:
1: EXACT <Good> (3)
3: STAR (6)
4: EXACT < > (0)
6: EXACT <, #MoarVM> (10)
10: END (0)
anchored "Good" at 0 floating ", #MoarVM" at 4..9223372036854775807 (checking floating) minlen 13
n
Freeing REx: "Good *, #MoarVM"

The optimiser knows that the pattern can't match less than 13 characters, but
the offered string is too short.

The optimiser also knows at what offsets the within the target string the
fixed string must lie, if there is also some variable length stuff, but this
is getting beyond what I know the plan for:

$ perl -wle 'use re "debug"; print "Perl rules" =~ /Perl.*s/ ? "Y" : "n"'
Compiling REx "Perl.*s"
Final program:
1: EXACT <Perl> (3)
3: STAR (5)
4: REG_ANY (0)
5: EXACT <s> (7)
7: END (0)
anchored "Perl" at 0 floating "s" at 4..9223372036854775807 (checking anchored) minlen 5
Matching REx "Perl.*s" against "Perl rules"
Intuit: trying to determine minimum start position...
doing 'check' fbm scan, [0..9] gave 0
Found anchored substr "Perl" at offset 0 (rx_origin now 0)...
doing 'other' fbm scan, [4..10] gave 9
Found floating substr "s" at offset 9 (rx_origin now 0)...
(multiline anchor test skipped)
Intuit: Successfully guessed: match at offset 0
0 <> <Perl rules> | 0| 1:EXACT <Perl>(3)
4 <Perl> < rules> | 0| 3:STAR(5)
| 0| REG_ANY can match 6 times out of 2147483647...
9 <Perl rule> <s> | 1| 5:EXACT <s>(7)
10 <Perl rules> <> | 1| 7:END(0)
Match successful!
Y
Freeing REx: "Perl.*s"


If you're wearing Peril Sensitive Sunglasses, then the code that does this is
the self-recursive Perl_re_intuit_start() in
https://perl5.git.perl.org/perl.git/blob/HEAD:/regexec.c

As a guide to reading that, for things like

DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
" String too short...\n"));


DEBUG_EXECUTE_r() only generates that debugging output if the command line
flag -Dr is set, *and* the `use re "debug";` de facto sets -Dr, even on a
perl binary compiled without all the other -D flags enabled.


I know that PCRE also exposes some information it derives from the pattern
which can be used to pre-match -- see PCRE_INFO_FIRSTCHARACTER and
PCRE_INFO_REQUIREDCHAR in
https://www.pcre.org/original/doc/html/pcre_fullinfo.html

I *thought* that Google's re2 library (which came out of code search) could
return the longest fixed string (if any) as part of its API, but I can't find
that now. In https://swtch.com/~rsc/regexp/regexp4.html it mentions building
trigrams (directly) from parsing the regex (with ANDs and ORs) which is what
some $ork code is doing (but then using PCRE, not re2).

Anyway, I hope that this helps someone, and helps make Rakudo's parser faster

I assume that the useful strategy is roughly

0) Do the most simple thing - no alternations, anchored starts. Reject match
if not present
1) Then 1+ character fixed substrings - Reject match if not present
2) Then the big cheat of "string is actually fixed" - compile to a sub that
build a match result immediately, instead of the more general engine
3) Then the even more general "fixed string as part of larger regex", where
failure is a fast-path, but otherwise the regular regex engine follows
4) Minimum match length
5) The stuff where one starts to tell the main engine how


but of course no plan survives contact with the enemy.

Nicholas Clark

1: https://en.wiktionary.org/wiki/crib -- definitions 14 and 23:
(usually in the plural) A collection of quotes or references for
use in speaking, for assembling a written document, or as an aid to
a project of some sort; a crib sheet.
[and]
A cheat sheet or past test used by students; crib sheet.

Patrick R. Michaud

unread,
Aug 13, 2019, 11:30:03 AM8/13/19
to Timo Paulssen, perl6-c...@perl.org
FWIW, at one time there was discussion that "<before>" and "<after>"
are actually keywords and not typical method calls that can be overridden,
precisely so optimizations can be made. They're that important to
efficient running of the regexes.


I'm not sure that a formal decision was ever made on this, however.
(I'd be okay with declaring them as keywords that cannot be overridden.)

Pm

On Tue, Aug 13, 2019 at 05:01:06PM +0200, Timo Paulssen wrote:
>
> >     use v6;
> >     'abcd' ~~ / . <.before( /c/ )> .  / # "bc"
> >     'abcd' ~~ / . <.before   c   > .  / # "bc" # (exactly identical)
> >
> > A person could change the code in the `before` method to have it do
> > something different
>
>
> At least at the moment, that's not 100% accurate (only by virtue of
> leaving out a piece):
>
> timo@schmand ~> perl6 -e 'grammar test { regex before($re) { { say "yo"
> } }; regex TOP { <.before "hi"> } }; test.parse("hi")'
> yo
> Too few positionals passed; expected 2 arguments but got 1
>   in regex before at -e line 1
>   in regex TOP at -e line 1
>   in block <unit> at -e line 1
>
> timo@schmand ~ [1]> perl6 -e 'grammar test { regex before($re) { { say
> "yo" } }; regex TOP { <before "hi"> } }; test.parse("hi")'
> yo
> Too few positionals passed; expected 2 arguments but got 1
>   in regex before at -e line 1
>   in regex TOP at -e line 1
>   in block <unit> at -e line 1
>
> timo@schmand ~ [1]> perl6 -e 'grammar test { regex before($re) { { say
> "yo" } }; regex TOP { <?before "hi"> } }; test.parse("hi")'
>
> As you can see, using <?before> gives you the "real" lookahead assertion.
>
> I'm not sure if that's part of the language yet, but should probably
> made to be.
>
>
> This will allow more optimization efforts.

Timo Paulssen

unread,
Aug 13, 2019, 11:30:04 AM8/13/19
to perl6-c...@perl.org
Here's some stuff that anybody who wants to work on regex optimization
in perl6 will want to know:

You can get a print-out of rakudo's internal AST that is generated for
the regex by passing --target=ast or --target=optimize to the perl6
commandline. I recommend grep -C5 Regex to skip some of the boilerplate
that's always there, but not important for regex stuff.

Here's an example of the output for the optimized p6 regex /foo<?before
bar>/:

> - QAST::Regex(:rxtype(concat) :subtype())
>   - QAST::Regex(:rxtype(scan) :subtype())
>     - foo
>   - QAST::Regex(:rxtype(concat) :subtype())  foo<?before bar>
>     - QAST::Regex(:rxtype(literal) :subtype())  f
>       - foo
>     - QAST::Regex(:rxtype(literal) :subtype(zerowidth))  b
>       - bar
>   - QAST::Regex(:rxtype(pass) :subtype())

And here it is before optimization:

> - QAST::Regex(:rxtype(concat) :subtype())
>   - QAST::Regex(:rxtype(scan) :subtype())
>     - foo
>   - QAST::Regex(:rxtype(concat) :subtype())  foo<?before bar>
>     - QAST::Regex(:rxtype(literal) :subtype())  f
>       - foo
>     - QAST::Regex(:rxtype(subrule) :subtype(zerowidth) :name(before)) 
> <?before bar>
>       - QAST::NodeList
>         - QAST::SVal(before)
>         - QAST::Block(:cuid(1))  :orig_qast<?> :code_object<?>
>           - QAST::Var(local self :decl(param))
>           - QAST::Var(lexical $¢ :decl(var))
>           - QAST::Regex(:rxtype(concat) :subtype())
>             - QAST::Regex(:rxtype(scan) :subtype())
>               - bar
>             - QAST::Regex(:rxtype(concat) :subtype())  bar
>               - QAST::Regex(:rxtype(literal) :subtype())  b
>                 - bar
>             - QAST::Regex(:rxtype(pass) :subtype())
>   - QAST::Regex(:rxtype(pass) :subtype())

As you can see, it shrunk quite a bit; Before optimization, the "bar"
inside of <?before bar> was put into the regex as a subrule with its own
complete block with lexical variables and everything. On top of that,
there was a scan operation there, which is normal for regexes in
general, but not useful for a lookahead or lookbehind (since they are
anchored implicitly). The optimizer simply turns all of that into a
"literal" "zerowidth" for "bar".

If you want to see how all that is currently implemented, you can look
at nqp's QRegex::Optimizer. The method "simplify_assertion" is probably
what does the optimization i outlined in the previous paragraph:
https://github.com/perl6/nqp/blob/master/src/QRegex/P6Regex/Optimizer.nqp#L88

Here's a perl6 one-liner that lets you eval a piece of perl6 code and
get the optimized QAST result as a tree of QAST nodes:

> perl6 -e 'use Perl6::Compiler:from<NQP>; use nqp; say
> nqp::getcomp("perl6").eval(Q[/foo/], :target<optimize>).dump'
Perhaps prototyping optimizations would be easiest in perl6 and later
translated into nqp.

If you want to hack on the "actual" regex optimizer, I recommend writing
your test code as nqp scripts; nqp is quickly recompiled to have the new
optimizer in it, and it applies the same way to perl6 regexes as it does
to nqp regexes. Running a rakudo with the changed optimizer requires a
full rebuild of rakudo, which of course includes the core setting.

The main optimization opportunities I can see for perl6 regexes are
exactly what nick points out in his mail:

If you can find out that a regex can only match if the target string
contains a certain substring (or even a short list of substrings that
can be or'd together would be interesting), you can generate code that
does a quick first check.

If you can prove that a specific part of the regex has a certain minimum
length, any scan through the target string can be aborted further from
the end. If the regex starts with a lookbehind that has a known minimum
length, the regex match attempt doesn't have to start at the very
beginning of the string.

I'm not entirely sure how we should go about skipping the regex engine
when a "simple match" can quickly be created, though.

Vadim Belman

unread,
Oct 16, 2019, 2:00:03 PM10/16/19
to Marcel Timmerman, perl6-c...@perl.org
Hi Marcel,

Could you, please, open a ticket on github about this? Meanwhile, `perl6 --ll-exception` could possibly provide you with more details.

Best regards,
Vadim Belman

> On Oct 16, 2019, at 1:15 PM, Marcel Timmerman <mt1...@gmail.com> wrote:
>
> Hi,
>
> I've seen a LTA error message when some module is not found. It only presents a line number but not the source file where it is 'use'd.
>
> E.g.
>
> running a perl program
>
> ===SORRY!===
> Could not find Gnome::Gtk3::ImageMenuItem at line 18 in:
> file#/home/marcel/Languages/Perl6/Projects/mongo-perl6-driver/lib
> file#/home/marcel/Languages/Perl6/Projects/gtk-v3/lib
> file#/home/marcel/Languages/Perl6/Projects/gtk-glade/lib
> file#/home/marcel/Languages/Perl6/Projects/Library/lib
> inst#/home/marcel/.perl6
> inst#/mnt/Data/opt/Perl6/rakudo/install/share/perl6/site
> inst#/mnt/Data/opt/Perl6/rakudo/install/share/perl6/vendor
> inst#/mnt/Data/opt/Perl6/rakudo/install/share/perl6/core
> ap#
> nqp#
> perl5#
>
> The project I'm working on is somewhat large and consists of many files. Grep didn't do it for me and also the search in the atom editor did not help me out. What the possible cause could be is a `require ::($x)` somewhere, where this name is not visible, so I'd rather see a module/program name along with the line number.
>
> Regards,
> Marcel Timmerman
>
0 new messages