ANTLR 4 $channel = HIDDEN and options
Asked Answered
H

1

33

I need help with my ANTLR 4 grammar after deciding to switch to v4 from v3. I am not very experienced with ANTLR so I am really sorry if my question is dumb ;)

In v3 I used the following code to detect Java-style comments:

COMMENT
    :   '//' ~('\n'|'\r')* '\r'? '\n' {$channel=HIDDEN;}
    |   '/*' ( options {greedy=false;} : . )* '*/' {$channel=HIDDEN;}
    ;

In v4 there are no rule-specific options. The actions (move to hidden channel) are also invalid.

Could somebody please give me a hint how to do it in ANTLR v4?

Holiday answered 8/2, 2013 at 17:58 Comment(0)
A
45

The v4 equivalent would look like:

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

which will put all single- and multi line comment on the HIDDEN channel. However, if you're not doing anything with these HIDDEN-tokens, you could also skip these tokens, which would look like this:

COMMENT
    :   ( '//' ~[\r\n]* '\r'? '\n'
        | '/*' .*? '*/'
        ) -> skip
    ;

Note that to tell the lexer or parser to match ungreedy, you don't use options {greedy=false;} anymore, but append a ?, similar to many regex implementations.

Alltime answered 8/2, 2013 at 18:8 Comment(1)
I now use your suggested code (first variant using channel) which throws an error: ->command in lexer rule 'COMMENT' must be last element of single outermost alt What's the problem?Holiday

© 2022 - 2024 — McMap. All rights reserved.