textX / Arpeggio

Parser interpreter based on PEG grammars written in Python http://textx.github.io/Arpeggio/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Adding Logical Operators to Grammar

LeeKevin opened this issue · comments

Hello,

I'm trying to add AND and OR operators to my grammar. I have the following:

    def number():
        return _(r'\d*\.\d*|\d+')

    def function_name():
        return _(r'[a-zA-Z_0-9]+')

    def func():
        return function_name, "(", \
               [expression, number], \
               ZeroOrMore((',', [expression, number])), \
               ")"

    def factor():
        return Optional(["+", "-"]), [number, ("(", expression, ")"), func]

    def term():
        return factor, ZeroOrMore(["*", "/"], factor)

    def expression():
        return term, ZeroOrMore(["+", "-"], term)

    def check_term():
        return [func, ("(", check_expression, ")")]
    
    def check_expression():
        return check_term, ZeroOrMore(["AND", "OR"], check_term)

    def check():
        return check_expression, EOF

Where a function can return a number or a bool. However, when applying the grammar to something like GreaterThan(Avg(5, 6, 7), 0.25) AND LessThan(Avg(5, 6, 7), 0.3), I get the following error:

arpeggio.NoMatch: Expected '*' or '/' or '+' or '-' or EOF at position (1, 33) => ')), 0.25) *AND LessTh'.

GreaterThan and LessThan compare their numeric arguments to return a bool. Avg takes the average of its numeric arguments to return a number.

Seems like it's hitting expression instead of check_expression. Any ideas?

Hi @LeeKevin . I've tried your grammar/input and I'm getting no error. Can you check the input you provided. Is that the text you are trying to parse? Grammar looks good to me.

To debug, you can pass debug=True to Parser constructor which will give you a detailed trace of the parsing process.

Whoops. I was returning the wrong method in my grammar. Thanks for the debug tip anyways!