taocpp / PEGTL

Parsing Expression Grammar Template Library
Boost Software License 1.0
1.94k stars 228 forks source link

Handling similar syntaxes #169

Closed qawbecrdtey closed 5 years ago

qawbecrdtey commented 5 years ago

I am making a simple parser with grammar where n, {e + e}, and {e - e} are expressions. I wrote a code like:

namespace Example {
    namespace {
///...
        struct integer : digits {};
        struct expression;
        struct add : tao::pegtl::must<
                  open_curly,
                  expression,
                  plus,
                  expression,
                  close_curly
                > {};
        struct subtract : tao::pegtl::must<
                  open_curly,
                  expression,
                  minus,
                  expression,
                  close_curly
                > {};
        struct expression : tao::pegtl::must<empty, tao::pegtl::sor<
                  integer,
                  add,
                  subtract
                >, empty> {};
    }

    struct grammar : tao::pegtl::until<eof, expression> {};

/// actions...
}

The program works well with input like {{1 + 2} + {3 + 4}}, but it will return an error parse error matching Example::(anonymous namespace)::plus whenever I put a - in the string. I think the error appears in struct expression since subtract appears after add in sor, but I can't find a way to fix this problem. Would anyone give me advice with this? Also, it would be nice if anyone could give me a way to actually calculate the expression.

nshcat commented 5 years ago

I think it will work if you remove the must rule in both add and subtract. It causes a failure of add to be converted into a global failure, but you want a local failure in order to use back tracking in your sor

qawbecrdtey commented 5 years ago

Thanks @nshcat ! I must have misunderstood the rule reference "Allows local failure of R... even within must<> etc."

ColinH commented 5 years ago

@qawbecrdtey The part of the rule reference that you quoted is indeed easy to misunderstand, we removed the offending occurrences of that sentence.