Question

I am attempting to parse Lua, which depends on whitespace in some cases due to the fact that it doesn't use braces for scope. I figure that by throwing out whitespace only if another rule doesn't match is the best way, but i have no clue how to do that. Can someone help me?

Was it helpful?

Solution

Looking at Lua's documentation, I see no need to take spaces into account.

The parser rule ifStatement:

ifStatement
    :    'if' exp 'then' block ('elseif' exp 'then' block 'else' block)? 'end'
    ;

exp
    :    /* todo */
    ;

block
    :    /* todo */
    ;

should match both:

if j==10 then print ("j equals 10") end

and:

if j<10 then
    print ("j < 10")
elseif j>100 then
    print ("j > 100")
else
    print ("j >= 10 && j <= 100")
end

No need to take spaces into account, AFAIK. So you can just add:

Space
    :    (' ' | '\t' | '\r' | '\n'){$channel=HIDDEN;}
    ;

in your grammar.

EDIT

It seems there is a Lua grammar on the ANTLR wiki: http://www.antlr.org/grammar/1178608849736/Lua.g

And it seems I my suggestion for an if statement slightly differs from the grammar above:

'if' exp 'then' block ('elseif' exp 'then' block)* ('else' block)? 'end'

which is the correct one, as you can see.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top