Search code examples
antlrtokengrammarantlr3

ANTLR: Define new channel in grammar


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.


Solution

  • 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