0
votes

How do I skip sql single line comments in antlr4 grammar?

This is the input which I have given:

--
-- $INPUT.sql$
--


CREATE TABLE table_one ( customer_number integer, address character varying(30));

create table table_two ( id integer, city character varying(50));

2
Please post your entire grammar and a little driver class that shows the fact that SINGLE_LINE_COMMENT gobbles up your entire input.Bart Kiers

2 Answers

3
votes

Like this:

SINGLE_LINE_COMMENT
 : '--' ~[\r\n]* -> skip
 ;

If I parse your example input with the following grammar:

grammar Hello;

parse
 : .*? EOF
 ;

INTEGER
 : [0-9]+
 ;

IDENTIFIER
 : [a-zA-Z_]+
 ;

SINGLE_LINE_COMMENT
 : '--' ~[\r\n]* -> skip
 ;

SPACES
 : [ \t\r\n]+ -> skip
 ;

OTHER
 : .
 ;

and let ANTLRWorks2 print the tokens, I see the following:

[@0,23:28='CREATE',<2>,6:0]
[@1,30:34='TABLE',<2>,6:7]
[@2,36:44='table_one',<2>,6:13]
[@3,46:46='(',<5>,6:23]
[@4,48:62='customer_number',<2>,6:25]
[@5,64:70='integer',<2>,6:41]
[@6,71:71=',',<5>,6:48]
[@7,73:79='address',<2>,6:50]
[@8,81:89='character',<2>,6:58]
[@9,91:97='varying',<2>,6:68]
[@10,98:98='(',<5>,6:75]
[@11,99:100='30',<1>,6:76]
[@12,101:101=')',<5>,6:78]
[@13,102:102=')',<5>,6:79]
[@14,103:103=';',<5>,6:80]
[@15,106:111='create',<2>,8:0]
[@16,113:117='table',<2>,8:7]
[@17,119:127='table_two',<2>,8:13]
[@18,129:129='(',<5>,8:23]
[@19,131:132='id',<2>,8:25]
[@20,134:140='integer',<2>,8:28]
[@21,141:141=',',<5>,8:35]
[@22,143:146='city',<2>,8:37]
[@23,148:156='character',<2>,8:42]
[@24,158:164='varying',<2>,8:52]
[@25,165:165='(',<5>,8:59]
[@26,166:167='50',<1>,8:60]
[@27,168:168=')',<5>,8:62]
[@28,169:169=')',<5>,8:63]
[@29,170:170=';',<5>,8:64]
[@30,172:171='<EOF>',<-1>,9:0]

I.e.: the line comment are discarded properly. If it does not with happen in your case, something else is going wrong.

0
votes

try EOF on the end of the rule as one of the options not just \r\n, like:

LINE_COMMENT
   : '//' ~[\r\n]* (EOF|'\r'? '\n') -> channel(HIDDEN)
   ;