0

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}
junli
  • 25
  • 10
  • Does this answer your question? [ANTLR4 skips empty line only](https://stackoverflow.com/questions/29519842/antlr4-skips-empty-line-only) – RedKnite May 26 '20 at 05:49
  • As i add blank line in if statement,it will throw Exception – junli May 26 '20 at 06:04

1 Answers1

1

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.

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288