The unexpected grammar of LPeg

Part of my Lua application is the search bar, and I'm trying to understand its logical expressions. I use LPeg, but the current grammar gives a weird result:

> re, yajl = require're', require'yajl'
> querypattern = re.compile[=[
    QUERY       <- ( EXPR / TERM )? S? !. -> {}
    EXPR        <- S? TERM ( (S OPERATOR)? S TERM )+ -> {}
    TERM        <- KEYWORD / ( "(" S? EXPR S? ")" ) -> {}
    KEYWORD     <- ( WORD {":"} )? ( WORD / STRING )
    WORD        <- {[A-Za-z][A-Za-z0-9]*}
    OPERATOR    <- {("AND" / "XOR" / "NOR" / "OR")}
    STRING      <- ('"' {[^"]*} '"' / "'" {[^']*} "'") -> {}
    S           <- %s+
]=]
> = yajl.to_string(lpeg.match(querypattern, "bar foo"))
"bar"
> = yajl.to_string(lpeg.match(querypattern, "name:bar AND foo"))
> = yajl.to_string(lpeg.match(querypattern, "name:bar AND foo"))
"name"
> = yajl.to_string(lpeg.match(querypattern, "name:'bar' AND foo"))
"name"
> = yajl.to_string(lpeg.match(querypattern, "bar AND (name:foo OR place:here)"))
"bar"

It only analyzes the first token, and I can’t understand why it does it. As far as I know, a partial match is impossible due !.to the end of the starting non-terminal. How can i fix this?

+5
source share
1 answer

The match gets the whole line, but the captures are erroneous. Note that '->' has a higher priority than concatenation, so you probably need parentheses around things like this:

  EXPR        <- S? ( TERM ( (S OPERATOR)? S TERM )+ ) -> {}
+10
source

All Articles