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

Vaclav Barta vbar at comp.cz
Thu Jul 19 13:12:21 PDT 2007


On Thursday 19 July 2007 21:18, Jim Idle wrote:
> I would suggest that perhaps what you want here is:
>
> sourceFile
> @init {
>  	DocumentBuilderFactory factory;
>  	DocumentBuilder builder;
> 	// What is document?
@members {
	Document document;
}

where Document is org.w3c.dom.Document .

> }
>  	: {
>
>  		factory = DocumentBuilderFactory.newInstance();
>  		builder = factory.newDocumentBuilder();
> 		document = builder.newDocument();
> 	  }
>
> 		assignments rules
>  	;
Well, I might want that, but I'll have to get it past the compiler first...

    [javac] Compiling 1 source file to /home/vb/antlr/antmaker/classes
    [javac] /home/vb/antlr/antmaker/src/Dumper.java:58: unreported exception 
javax.xml.parsers.ParserConfigurationException; must be caught or declared to 
be thrown
    [javac]                     builder = factory.newDocumentBuilder();

(IOW the same problem as in my original version).

> 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:
Well, I'm skimping on custom classes by using XML, but obviously I'll still 
need some code to build it, which must go somewhere, so why not directly into 
the grammar? This is supposed to be a simple example, really... :-)

> sourceFile[ myCodeGenClassInterface cgIn]
If I had a myCodeGenClass(es), I'd build a typed tree directly from the parser 
rules and wouldn't bother with a tree grammar at all (I actually did just 
that in my production project) - but the purpose of the exercise above is 
exactly to discover the delights of using a tree grammar... So far, I'm 
hard-pressed to find any. :-/

 	Bye
 		Vasek


More information about the antlr-interest mailing list