Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

ANTLR4 lexer rule with @init block

I have this lexer rule defined in my ANTLR v3 grammar file - it maths text in double quotes. I need to convert it to ANTLR v4. ANTLR compiler throws an error 'syntax error: mismatched input '@' expecting COLON while matching a lexer rule' (in @init line). Can lexer rule contain a @init block ? How this should be rewritten ?

DOUBLE_QUOTED_CHARACTERS
@init 
{
   int doubleQuoteMark = input.mark(); 
   int semiColonPos = -1;
}
: ('"' WS* '"') => '"' WS* '"' { $channel = HIDDEN; }
{
    RecognitionException re = new RecognitionException("Illegal empty quotes\"\"!", input);
    reportError(re);
}
| '"' (options {greedy=false;}: ~('"'))+ 
  ('"'|';' { semiColonPos = input.index(); } ('\u0020'|'\t')* ('\n'|'\r'))
{ 
    if (semiColonPos >= 0)
    {
        input.rewind(doubleQuoteMark);

        RecognitionException re = new RecognitionException("Missing closing double quote!", input);
        reportError(re);
        input.consume();            
    }
    else
    {
        setText(getText().substring(1, getText().length()-1));
    }
}
; 

Sample data:

  1. " " -> throws error "Illegal empty quotes!";
  2. "asd -> throws error "Missing closing double quote!"
  3. "text" -> returns text (valid input, content of "...")

Answer*

Cancel
1
  • LEXER RULES does not take init and after blocks. Commented Jan 4, 2019 at 14:33