in reply to Re^2: Forcing parse to fail in PArse::RecDescent
in thread Forcing parse to fail in Parse::RecDescent

<leftop> backtracks and successfully matches 4. Since the production matches, pending errors are canceled. The parsing error happens later, when * {201({2}} attempts to match /^\Z/.

This problem would be solved by committing after matching the *. Since <leftop> doesn't provide a means for us to do that, we'll have to roll out an alternative to <leftop>. The code in section 3.c.ii of Operator Associativity and Eliminating Left-Recursion in Parse::RecDescent suits your needs perfectly.

prod_op : term prod_op_[ $item[1] ] prod_op_ : PROD <commit> term prod_op_[ [ $item[1], $arg[0], $item[2] +] ] | { $arg[0] }

We can even add some extra diagnostics:

prod_op : term prod_op_[ $item[1] ] prod_op_ : PROD <commit> term prod_op_[ [ $item[1], $arg[0], $item[2] +] ] | <error?: Expecting term following operator> <reject> | { $arg[0] }

Using the test program found below generated the following output:

4 * 5 >> match ===== {201({2}} ERROR (line 1): GRRRRRRRRRRRR >> no match ===== 4 * {201({2}} ERROR (line 1): GRRRRRRRRRRRR ERROR (line 1): Expecting term following operator >> no match
use strict; use warnings; use Parse::RecDescent qw( ); { my $grammar = <<'__EOI__'; { use strict; use warnings; } parse : prod_op /^\Z/ prod_op : term prod_op_[ $item[1] ] prod_op_ : PROD <commit> term prod_op_[ [ $item[1], $arg[0], +$item[2] ] ] | <error?: Expecting term following operator> <rejec +t> | { $arg[0] } term : NUMBER | abstraction abstraction : '{' NUMBER '(' <commit> NUMBER ')' '}' | '{' <commit> NUMBER '}' | <error?: GRRRRRRRRRRRR> <reject> PROD : '*' NUMBER : /[+-]?(?:\d+\.?\d*|\.\d+)/ __EOI__ my $parser = Parse::RecDescent->new($grammar) or die; # $::RD_TRACE = 'defined'; my $not_first; foreach my $text ( '4 * 5', '{201({2}}', '4 * {201({2}}', ) { print("\n=====\n\n") if $not_first++; print("$text\n"); print("\n>> ", defined($parser->parse($text)) ? 'match' : 'no ma +tch', "\n"); } }

Replies are listed 'Best First'.
Re^4: Forcing parse to fail in PArse::RecDescent
by suaveant (Parson) on Sep 17, 2007 at 15:09 UTC
    Ahhhh, yes... that makes sense (after a few minutes :)

    I was actually thinking I might need a commit after the operator but wasn't sure how to get it in there. Interesting. Thank you.

                    - Ant
                    - Some of my best work - (1 2 3)