WG: [antlr-interest] How to use a value more than once?

Terence Parr parrt at cs.usfca.edu
Wed Dec 21 11:29:53 PST 2005


On Dec 21, 2005, at 12:05 AM, Dr. Kocher, Hartmut wrote:
> I want to generate GUI classes (controls like Textfield, Checkbox,  
> etc.). Because each control has different properties to set, I have  
> different templates for each control type. In the window, I have to  
> combine those templates into one Form class (.NET). Therefore, I  
> have two lists of templates: one for setting up the fields in the  
> form, another to initialize the controls. Therefore, I have to call  
> the templates in my subrules but use it in the main rule.
>
> The actual grammar goes something like this:
>
> form : FORM ID '{' control* '}';
> control: textfield|checkbox|... ;
> textfield: TEXTFIELD ID label SEMI;
>
> You get the idea...
>
> For textfield I have to generate at least two templates with
>
> Textfield <name>;
>
> And another
>
> <name> = new Textfield();
> <name>.Text = <label>;
> ...

Can you collect the big templates in one pass and then simply pass a  
list of these templates to another template?  For example, antlr v3 I  
collect a bunch of rule templates for generating code and then I pass  
it to the header file template so it can iterate over the templates  
and pull out various attributes like the rule name to generate the  
header.  Templates can be treated as data objects :)

> So it would be useful to be able to
> - call multiple templates per rule.

We'd need a naming scheme to refer to them from the invoking rule.

> - add templates to lists (currently, there's only a shortcut for  
> the one and only return value (p+=... syntax).
>
> BTW, I think it would be useful if a rule like 'control' above  
> would return the template of textfield or checkbox by default  
> instead of nothing. If the user doesn't use the template, no harm  
> is done. If he wants another template he can override it using the - 
> > syntax.

True.  Was wondering about this.  THe problem is that it's only  
useful when you refer to a single rule in a production...not that  
common.  When there are multiple elements in a production, what do  
you do?

> Finally, another solution to my problem would be to make multiple  
> passes thru the grammar, one to get the fields, one to build the  
> contructor method. So I could build a tree parser first. Then make  
> multiple passes thru the AST. Can I specify multiple parsers in the  
> same combined grammar? That would be nice.

That gets awkward.  You need to have actions that say "if (pass==1)"  
etc...

Ter


More information about the antlr-interest mailing list