views:

283

answers:

2

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

filter = true

to the lexer?

Thanks

+1  A: 

You don't. The options{filter=true;} only works in lexer-grammars. You will need to define a parser- and lexer grammar in two separate files (EDIT: no, they can be put in one file, see chollida's answer):


FooParser.g

parser grammar FooParser;

parse
  :  Number+ EOF
  ;


FooLexer.g

lexer grammar FooLexer;

options{filter=true;}

Number
  :  '0'..'9'+
  ;


Combining these lexer and parser will result in a parser that will only parse the strings in a file (or string) consisting of digits.

Note that ANTLR plugins or ANTLRWorks might complain because because the lexer rule(s) is/are not visible to it, but generating a lexer and partser on the command line:

java -cp antlr-3.2.jar org.antlr.Tool FooLexer.g 
java -cp antlr-3.2.jar org.antlr.Tool FooParser.g 

works fine.

Bart Kiers
+3  A: 

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.

chollida
Didn't know that! Thanks for the info.
Bart Kiers