Lexer rule ANTLR4 with @init block

I have this lexer rule defined in my ANTLR v3 grammar file - this is double-quoted mathematical text. I need to convert it to ANTLR v4. The ANTLR compiler throws an error syntax error: an inconsistent input '@' expects COLON when it matches the lexer rule (on the @init line). Can a lexer rule contain an @init block? How should this 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:

  • "-> throws an error" Illegal empty quotation marks! ";
  • "asd → throws error" Missing closing double quote! "
  • "text" → returns text (valid input, contents "...")
+4
source share
1 answer

, .g4 lexer. , , ANTLR4. . , LEXER ( .g4), @input @after . + , , . , . 2-3 , . stackoverflow.

+1

All Articles