picoe / Eto.Parse

Recursive descent LL(k) parser for .NET with Fluent API, BNF, EBNF and Gold Grammars
MIT License
148 stars 30 forks source link

Match Errors when a Parser is Optional #59

Closed RationalFragile closed 2 years ago

RationalFragile commented 2 years ago

Hi, I'm trying to make a very simple example like this:

var value = new NumberParser().WithName("value");
var op = Terminals.Set('+', '-', '*', '/').WithName("op");
var expr = new SequenceParser().WithName("expr");
var opexpr = (op & expr).WithName("opexpr");
expr.Add(value, opexpr.Optional());
var g = new Grammar(expr);
var m = g.Match("1+3*2+4");

And the matcher has m.ErrorMessage

Index=7, Line=1, Context="1+3*2+4>>>"
Expected:
Char: '+','-','*','/'
(Char: '+','-','*','/', (value, Optional: opexpr))

I don't understand why the error happens given than "opexpr" is optional. I tried printing the parsers just to double check, and opexpr is Optional.

Grammar: expr
    expr
        value
        Optional: opexpr
            opexpr
                Char: '+','-','*','/'
                expr

So why does it output an error when "opexpr" fails given that its parent parser is optional? Sorry if I'm doing something obviously wrong.

cwensley commented 2 years ago

Your grammar is fine, the ErrorMessage will be populated whether it is successful or not (it tells you what it expects next), so be sure to check m.Success first.