Search code examples
filterantlrgrammarlexer

Combined grammar ANTLR option filter


I have a combined grammar (lexer and parser on the same file). How do I set the

filter = true

to the lexer?

Thanks


Solution

  • To Clarify what Bart said in his answer:

    The options{filter=true;} only works in lexer-grammars. You will need to define a parser- and lexer grammar in two separate files:
    

    You don't actually need to put the lexer and parser in 2 separate files. You just need to put the filter rule in the lexer grammar. Both the lexer and the parser grammars can be in the same file.

    Though Bart's advice of putting them in seperate files is the approach I normally use.

    So to take an example you can do this in a single file

    Single file with parser and lexer Grammar.g

    parser grammar FooParser;
    
    parse
    :  Number+ EOF
    ;
    
    lexer grammar FooLexer;
    
    options{filter=true;}
    
    Number
    :  '0'..'9'+
    ;
    

    Note how the filter rule is in the lexer class definition but the lexer and parser are in the same file.