Search code examples
pythonantlr4blank-line

Tiny python add skip blank line rule, Antlr4


I am using https://github.com/antlr/grammars-v4/blob/master/python/tiny-python/tiny-grammar-without-actions/Python3.g4

grammar ,and I want to add a rule to skip blank line( line: 6)

a = 0
b = 2
sum = 0
if b > a:
    i = b

    sum += i
print(sum)

I have test this code ,but not work for me

WS:[ \t\r\n]+ -> skip;
line 8:4     : missing NEWLINE at 'sum'

Edit:

ss = 4
if 3>1:
    ss = 3
    #dddd
    ss = 4

when i add above code ,it will report another error

line 4:9 : extraneous input '\n ' expecting {'break', 'continue', 'if', 'while', 'for', 'print', 'def', 'return', NAME, '(', DEDENT}

Solution

  • By doing WS:[ \t\r\n]+ '\n'-> skip;, you're essentially removing (skipping) the new line after i = b and the empty line after it:

    i = b
    
    sum += i
    

    resulting in this:

    i = b sum += i
    

    which is no good: you need a new line after i = b.

    Instead of skipping empty lines, you could try to let empty lines be a part of your NEWLINE token. So instead of doing:

    NEWLINE
     : ( '\r'? '\n' | '\r' | '\f' ) SPACES?
     ;
    

    you'd do:

    NEWLINE
     : ( '\r'? '\n' | '\r' | '\f' ) (SPACES? ( '\r'? '\n' | '\r' | '\f' ))* SPACES?
     ;
    

    which will make sure the new line after i = b is not removed.