[antlr-interest] Can @init code throw Java exceptions?

Jim Idle jimi at temporal-wave.com
Thu Jul 19 12:18:13 PDT 2007


I would suggest that perhaps what you want here is:

sourceFile
@init {
 	DocumentBuilderFactory factory;
 	DocumentBuilder builder;
	// What is document?
}
 	: {
 		factory = DocumentBuilderFactory.newInstance();
 		builder = factory.newDocumentBuilder();
		document = builder.newDocument();
	  }

		assignments rules
 	;

Or perhaps a scope.

In general though, I feel it is asking for trouble to put much of any
code directly in the grammar. Better to provide the rule with a
"codegen" object of some sort:


sourceFile[ myCodeGenClassInterface cgIn]
@scope
{
	myCodeGenClassInterface cg;
}
@init
{
	$sourceFile::cg = cgIn;
	$sourceFile::cg.init();
}
	:assignments rules
	;

Or some similar construct. This way your action code is small and
obvious as it just calls the object with whatever parameters it needs
and you can supply different implementations.


Jim

> -----Original Message-----
> From: antlr-interest-bounces at antlr.org [mailto:antlr-interest-
> bounces at antlr.org] On Behalf Of Vaclav Barta
> Sent: Thursday, July 19, 2007 11:50 AM
> To: antlr-interest at antlr.org
> Subject: [antlr-interest] Can @init code throw Java exceptions?
> 
> Hi,
> 
> I'm trying to construct an XML document in a tree grammar, and getting
> an
> interesting error. I put the XML doc initialization into the @init
> block of
> the topmost rule:
> 
> sourceFile
> @init {
> 	DocumentBuilderFactory factory =
> 		DocumentBuilderFactory.newInstance();
> 	DocumentBuilder builder = factory.newDocumentBuilder();
> 	document = builder.newDocument();
> }
> 	: assignments rules
> 	;
> 
> But that generates illegal Java, because the newDocumentBuilder is
> declared as
> throwing javax.xml.parsers.ParserConfigurationException while the
> enclosing
> sourceFile method isn't. I suppose I can put my own try...catch inside
> and
> wrap everything in RuntimeException, but that seems rather inelegant -
> is
> there a better way?
> 
> 	Bye
> 		Vasek


More information about the antlr-interest mailing list