views:

87

answers:

1

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?

+1  A: 

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.

Bart Kiers
Bu the problem is that i'm trying to match the behavior of lua's compiler, which won't compile `ifj==10thenprint('j equals 10')end` since neither ifj or thenprint are valid keywords.
RCIX
Parsing `ifj==10thenprint('j equals 10')end` wouldn't be accepted as a valid if statement. There's no need for you to specify spaces between them. Hiding the spaces will suffice.
Bart Kiers
Ok cool. Thanks for the help!
RCIX
No problem RCIX.
Bart Kiers