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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
The option
superClass=...
is used to let yourParser
extend a custom class. So, I don't think that is what you're after.Everything inside the
@header
section will be placed at the start of yourParser
class. 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 theParser
orLexer
: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.txt
has been created containing:Note that there is a strict order of all these
@...
andoptions {...}
etc. instances:grammar
definitionoptions
block (no@
sign!)tokens
block (no@
sign!)@header
block@members
blockEDIT
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.