How should I define a NOT operator which supports both NOT and AND NOT in LARK

360 Views Asked by At

This is how my current code looks like, it only supports a AND NOT b. Is there a way to make it also return the same tree for a NOT b? Any suggestions will be appreciated.

from lark import Lark


grammar = r'''
    start: or_test

    ?or_test: and_test ("OR" and_test)*
    ?and_test: not_test ("AND" not_test)*
    ?not_test: "NOT" not_test -> not
             | atom
    
    atom: WORD -> term
         | "(" or_test ")"

    WORD: /[a-zA-Z0-9]+/
    
    %import common.WS_INLINE
    %ignore WS_INLINE
'''

parser = Lark(grammar)

s = 'NOT a AND b AND NOT c'
tree = parser.parse(s)
print(tree.pretty())

output

start
  and_test
    not
      term  a
    term    b
    not
      term  c
1

There are 1 best solutions below

0
On BEST ANSWER

I think that should do what you asked:

from lark import Lark

grammar = r'''
    start: or_test

    ?or_test: and_test ("OR" and_test)*
    ?and_test: not_test ("AND" not_test | and_not)*
    and_not: "NOT" not_test -> not
    ?not_test: "NOT" not_test -> not
            | atom

    atom: WORD -> term
        | "(" or_test ")"

    WORD: /[a-zA-Z0-9]+/

    %import common.WS_INLINE
    %ignore WS_INLINE
'''

parser = Lark(grammar)

s = 'NOT a AND b AND NOT c NOT d'
tree = parser.parse(s)
print(tree.pretty())