RCIX
RCIX

Reputation: 39427

ANTLR comment problem

I am trying to write a comment matching rule in ANTLR, which is currently the following:

LINE_COMMENT
    : '--' (options{greedy=false;}: .)* NEWLINE {Skip();}
    ;

NEWLINE : '\r'|'\n'|'\r\n' {Skip();};

This code works fine except in the case that a comment is the last characters of a file, in which case it throws a NoViableAlt exception. How can i fix this?

Upvotes: 2

Views: 1851

Answers (2)

cletus
cletus

Reputation: 625007

Why not:

LINE_COMMENT     : '--' (~ NEWLINE)* ;
fragment NEWLINE : '\r' '\n'? | '\n' ;

If you haven't come across this yet, lexical rules (all uppercase) can only consist of constants and tokens, not other lexemes. You need a parser rule for that.

Upvotes: 2

Bart Kiers
Bart Kiers

Reputation: 170128

I'd go for:

LINE_COMMENT
  :  '--' ~( '\r' | '\n' )* {Skip();}
  ;

NEWLINE 
  :  ( '\r'? '\n' | '\r' ) {Skip();}
  ;

Upvotes: 0

Related Questions