in reply to HOP::Lexer not doing what I expected

Looking at code from HOP::Lexer I found some interesting things. First an example (most of the code is the same from original post, I only change the data and lexer rules):

use strict; my $sql = <<'--SQL--'; aaaa a baaaab a --SQL-- use HOP::Lexer 'make_lexer'; my @sql = $sql; my $lexer = make_lexer( sub { shift @sql }, # iterator [ A => qr/a+/i ], [ BAB => qr/ba+b/i ], [ SPACE => qr/\s+/, sub {} ], );

This gives us:

['A','aaaa'], ['A','a'], 'b', ['A','aaaa'], 'b', ['A','a']
which seems wrong but: note that the rule A matches everytime the rule B matches (not exactly the same match but both match something) and, here's the surprise, HOP::Lexer uses split instead of matching the start of the string. This makes sense because you can have garbage or non-matched data at the start of the buffer, e.g. in original post example there's = which isn't matched by any rule.

Now it's easy to see why the rules work like that, for example with:

[ WORD => qr/\w+/i ], [ DQWORD => qr/"\w+"/ ],

So, considering that split is used and WORD has precedence, always will happen that " will be considered what I called garbage. And that's why giving higher priority to DQWORD works (as I replied in the thread), because otherwise WORD would match the \w+ inside of the double quoted one.

As a rule of thumb: if a rule has other rule inside it, give it higher priority.

Replies are listed 'Best First'.
Re^2: HOP::Lexer not doing what I expected
by bart (Canon) on Nov 11, 2006 at 22:48 UTC
    Right, OK, got it. This even seems to work as I want:

    As to your rule of thumb, it's not always feasable, especially with possibly overlapping matches, for example in Perl, a string can contain a "#" symbol, and a comment can contain quotes. So, which to match first, the comment or the string?

      Indeed, my rule of thumb isn't that good after all :-(. This snippet illustrate what you said about string vs. comment:

      Here is ambiguous what to do, and both orders give a bad result. If STRING comes first, it finds strings inside comments, and if COMMENT comes first, it finds comments inside string.

      (Well, there's a workaround similar to what the original article used to deal with parenthesis, which involves another parsing phase, but this is a little bit cheating I guess ;-)