I know it is possible to switch between the default and hidden token channels in an ANTLR grammar, but lets say I want a third channel. How can I define a new token channel in the gramar? For instance, lets say I want a channel named ALTERNATIVE.
Asked
Active
Viewed 1,064 times
2
-
For anyone coming here in 2022 (I have 4.10) and being nonplussed about why the "channel name" trick as described in the ANTLR book is not accepted ("foo is not a recognized channel name" says ANTLR) see https://github.com/antlr/antlr4/issues/1555 - Custom channel names are no longer allowed in combined grammars (so use integers instead) and in lexer grammars, the syntax to define them is now `channels { FOO }`. – David Tonhofer Oct 29 '22 at 09:30
2 Answers
2
They're just final int
's in the Token
class
, so you could simply introduce an extra int
in your lexer like this:
grammar T;
@lexer::members {
public static final int ALTERNATIVE = HIDDEN + 1;
}
// parser rules ...
FOO
: 'foo' {$type=ALTERNATIVE;}
;
// other lexer rules ...
A related Q&A: How do I get an Antlr Parser rule to read from both default AND hidden channel

Community
- 1
- 1

Bart Kiers
- 166,582
- 36
- 299
- 288
1
For the C target you can use
//This must be assigned somewhere
@lexer::context {
ANTLR3_UINT32 defaultChannel;
}
TOKEN : 'blah' {$channel=defaultChannel;};
This gets reset after every rule so if you want a channel assignment to persist across rules you may have to override nextTokenStr().