Search code examples
javaantlrantlr4

Antlr Syntax error: mismatched input 'p' expecting WS


I have the following grammar:

grammar myProject;

program: WS EOF myRules;
WS: [ \t\r\n]+ -> skip;
myRules: myRule+;
myRule: SELECTOR OPEN declarations CLOSE;
declarations: declaration+;
declaration: PROPERTY EQ value ENDSYMBOL;
value: INT | STRING | COLOR;

SELECTOR : (('#'CHAR+)|('.'CHAR+)|CHAR+);
PROPERTY : [A-z-]+;

STRING : '"' .*? '"';
INT : [0-9]+ ;
COLOR : '#' [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F];
CHAR: [A-z];

EQ : ':' ;
OPEN : '{';
CLOSE : '}';
ENDSYMBOL : ';' ;

Now my input is this:

p {
    color: #054593;
    width: 100px;
}

Now, when i parse this i get the following error:

Syntax error: mismatched input 'p' expecting WS

I have red many questions here on stack and googled a lot already, but I simpeley can't find a anwser. What am I doing wrong in my grammar? Why does the program needs a WS and how do I fix this. Many, many thanks in advance!


Solution

  • The very first thing you do in your grammar is demand WS:

    program: WS EOF myRules;
    

    So, lacking any whitespace characters, your parse fails. I'd simply suggest:

    program: myRule*;
    

    since you're discarding whitespace already with the skip option.