Passing on Fates [was: Re: Teaching Rakudo the tricks of Perl 5's regex optimiser]

2019-08-13 Thread Timo Paulssen
On 13/08/2019 16:32, Brad Gilbert wrote:

> Perhaps the biggest one may be the one about passing around “fates”.
> (I barely understand the basics of this.)


The optimization opportunity Brad is refering to here is relevant mostly
to grammars with deeply nested multi-tokens:

Longest-Token-Matching is implemented by creating an NFA
(nondeterministic finite automaton) out of all the longest declarative
prefixes that go into a given multi, be it with explicit | operators or
with "proto token"/"multi token" etc.

The NFA runs and collects a list of potential decision outcomes that are
valid. Think of them simply as "which method to call" and ignore
explicit | operators for the moment.

An important thing to note about the NFA that get created is that in
order to have the actual full "longest declarative prefix", they need to
incorporate every subrule that can be reached.

Take this simplified example:

A  can be a , a , a , etc.
a  can be an , a , a , etc.
an  can be  or 
a  is basically <[-+]><[1..9]><[0..9]>*
a  is basically <[-+]>0<[obdx]><[1..9 a..f]><[0..9 a..f]>*

Now what does the regex engine currently do when it sees "0xaffe"?

 1. It runs the NFA for , which is able to successfully match the
entirety of "0xaffe" and points towards "literal" as the result.
 2. Then it calls the  subrule.
 3. It runs the NFA for , which is able to successfully match
the entirety of "0xaffe" and points towards "integer" as the result.
 4. Then it calls the  subrule.
 5. It runs the NFA for , which is able to successfully match
the entirety of "0xaffe" and points towards "basedInteger" as the
result.
 6. Then it calls the  subrule.
 7. Then it parses the whole thing.

As you can see, it runs three separate NFAs against the same text,
starting before 0 and ending after e.

The idea of passing on fates is that the first NFA already knows that
after  is called, it will directly call into , and
then directly into . However, it does not currently have a
way to communicate deeper results to the regex engine.

I hope that explanation makes sense even if you're not deep in the regex
engine with your head already.

Kind Regards
  - Timo



Re: Teaching Rakudo the tricks of Perl 5's regex optimiser

2019-08-13 Thread Timo Paulssen
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/:

> - QAST::Regex(:rxtype(concat) :subtype())
>   - QAST::Regex(:rxtype(scan) :subtype())
>     - foo
>   - QAST::Regex(:rxtype(concat) :subtype())  foo
>     - 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
>     - QAST::Regex(:rxtype(literal) :subtype())  f
>   - foo
>     - QAST::Regex(:rxtype(subrule) :subtype(zerowidth) :name(before)) 
> 
>   - 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  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; use nqp; say
> nqp::getcomp("perl6").eval(Q[/foo/], :target).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.

On 13/08/2019 11:36, Nicholas Clark wrote:
> 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
>

Re: Teaching Rakudo the tricks of Perl 5's regex optimiser

2019-08-13 Thread Patrick R. Michaud
FWIW, at one time there was discussion that "" and "" 
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  at -e line 1
> 
> timo@schmand ~ [1]> perl6 -e 'grammar test { regex before($re) { { say
> "yo" } }; regex TOP {  } }; 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  at -e line 1
> 
> timo@schmand ~ [1]> perl6 -e 'grammar test { regex before($re) { { say
> "yo" } }; regex TOP {  } }; test.parse("hi")'
> 
> As you can see, using  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.


Re: Teaching Rakudo the tricks of Perl 5's regex optimiser

2019-08-13 Thread Timo Paulssen


>     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  at -e line 1

timo@schmand ~ [1]> perl6 -e 'grammar test { regex before($re) { { say
"yo" } }; regex TOP {  } }; 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  at -e line 1

timo@schmand ~ [1]> perl6 -e 'grammar test { regex before($re) { { say
"yo" } }; regex TOP {  } }; test.parse("hi")'

As you can see, using  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.


Re: Teaching Rakudo the tricks of Perl 5's regex optimiser

2019-08-13 Thread Brad Gilbert
I would like to point out that regexes in Perl6 are treated as code.
(They can even have parameters and lexical variables.)

It uses the same compiler intrinsics as the rest of Perl6.
It uses the same VM opcodes as regular Perl6 code.

Regexes, string literals, and signatures are just domain specific
sub-languages.

Perl6 regexes are also missing features that are common to other regexes,
instead you just embed regular Perl6 code to handle it.

For example instead of `(?=…)` Perl6 uses a method call to `before` with a
regex argument.

<.before …>

use v5;
'abcd' =~ / . (?=c) . /x # "bc"

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

This means that the biggest wins in the Perl6 regex system are probably
going to look nothing like the ones in other regex engines.
At least in the short term.
Inlining method calls for instance.
Perhaps the biggest one may be the one about passing around “fates”. (I
barely understand the basics of this.)

So while information on how other projects do regex optimizations can help,
they are generally going to be small wins in comparison.
(That doesn't mean they aren't worth doing.)

Doing some of those optimizations may also make other bigger optimizations
harder to do.
(I'm fairly sure the “fates” optimization would be harder, but I'm not
sure.)

On Tue, Aug 13, 2019 at 4:53 AM Nicholas Clark  wrote:

> 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  (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 <>  |   0| 1:SBOL /^/(2)
>0 <>  |   0| 2:EXACT (4)
>4  < 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 <>  |   0| 1:SBOL /^/(2)
>0 <>  |   0| 2:EXACT (4)
>4  < 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  (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   |   0| 1:EXACT (3)
>3   |   0| 3:REG_ANY(4)
>4  < rules> |   0| 

Teaching Rakudo the tricks of Perl 5's regex optimiser

2019-08-13 Thread Nicholas Clark
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  (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 <>  |   0| 1:SBOL /^/(2)
   0 <>  |   0| 2:EXACT (4)
   4  < 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 <>  |   0| 1:SBOL /^/(2)
   0 <>  |   0| 2:EXACT (4)
   4  < 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  (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   |   0| 1:EXACT (3)
   3   |   0| 3:REG_ANY(4)
   4  < 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  (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  (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/