I want to use parser actions with basic file io (Java), e. g. PrintWriter in an ANTLR grammar. Must I use the superClass option or can I use @header? In both cases how can I declare the PrintWriter-object and how must I handle the exceptions?
Share
The option
superClass=...is used to let yourParserextend a custom class. So, I don’t think that is what you’re after.Everything inside the
@headersection will be placed at the start of yourParserclass. This is used to import classes:Note that
@header {...}is short for@parser::header {...}. You can also define:@lexer::header {...}for your lexer.And inside
@member {...}(or:@parser::member {...},@lexer::member {...}) sections, you can add instance variables and methods that can be used inside either theParserorLexer:A small demo of a grammar whose parser will write the parsed numbers to a specific writer:
which can be tested with:
If you run the class above, a file called
log.txthas been created containing:Note that there is a strict order of all these
@...andoptions {...}etc. instances:grammardefinitionoptionsblock (no@sign!)tokensblock (no@sign!)@headerblock@membersblockEDIT
There’s no built-in functionality for such a thing. But you can easily create a custom method
wrapUp()in your parser:and then automatically call that method from the entry point of your grammar like this:
Any code placed in the
@after {...}block of a rule is executed when everything in the rule is properly matched.