Search code examples
c#antlr4antlr4cs

How to detect beginning of line, or: "The name 'getCharPositionInLine' does not exist in the current context"


I'm trying to create a Beginning-Of-Line token:

lexer grammar ScriptLexer;

BOL : {getCharPositionInLine() == 0;}; // Beginning Of Line token

But the above emits the error

The name 'getCharPositionInLine' does not exist in the current context

As it creates this code:

private void BOL_action(RuleContext _localctx, int actionIndex) {
    switch (actionIndex) {
    case 0: getCharPositionInLine() == 0; break;
    }
}

Where the getCharPositionInLine() method doesn't exist...


Solution

  • Simplest approach is to just recognize an EOL as the corresponding BOL token.

    BC  : '/*' .*? '*/' -> channel(HIDDEN) ;
    LC  : '//' ~[\r\n]* -> channel(HIDDEN) ;
    HWS : [ \t]*        -> channel(HIDDEN) ;
    BOL : [\r\n\f]+ ;
    

    Rules like a block comment rule will consume the EOLs internally, so no problem there. Rules like a line comment will not consume the EOL, so a proper BOL will be emitted for the line immediately following.

    A potential problem is that no BOL will be emitted for the beginning of input. Simplest way to handle this is to force prefix the input text with a line terminal before feeding it to the lexer.