[antlr-interest] Minor suggestion re. Java output

Guntis Ozols guntiso at latnet.lv
Sun Feb 3 15:52:37 PST 2008


> >> A tree is not guaranteed to be any particular type or interface as the
> >> tree adaptor can produce anything it likes. Hence it must be an object.
> >> This is explained in the code etc.
> >>
> >> Jim
> >
> > Casting tree once is not that big of a deal, but tons of casting could be
> > eliminated, plus there is no need for an option, if CommonTree.getChild()
> > returned CommonTree.
> >
> > Covariant return types are available since java 1.5 (Sept 2004).
> >
> > Guntis
>
> The Java target remains for the foreseeable future 1.4. I haven't looked
> if C# allows this, too, but it would be possible to use templates and
> specify the template parameter so that it uses the ASTLabelType value.
>
> > Also, how about using enum for tokens? It would free client code of
> prefixes in
> > switch statements, plus toString() would be available and more.
>
> Could do that only for C#, but for Java you are out of luck. As long
> people use 1.4 for projects, ANTLR can't easily move. I have that
> problem with the C# target, though I'm quite sure that no one uses C# 1
> in combination with ANTLR.
>
> Johannes

Ok, I've created a couple of simple classes and eliminated tens of casts and
newlines (I am using java 1.6). I think I'll get to tokens later. If I
understand correctly, since I have no actions, ASTLabelType is of no use
anyway. If somebody's interested, here's the code:

////////////////////////////////////////// Ast.java
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.CommonTree;

public class Ast extends CommonTree {

    public Ast(Ast node) {
        super(node);
    }

    public Ast(Token t) {
        super(t);
    }

    @Override
    public Ast dupNode() {
        return new Ast(this);
    }

    @Override
    public Ast getChild(int i) {
        return (Ast) super.getChild(i);
    }
}

////////////////////////////////////////// AstAdaptor.java
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.CommonTreeAdaptor;

public class AstAdaptor extends CommonTreeAdaptor {

    @Override
    public Object create(Token payload) {
        return new Ast(payload);
    }
}




More information about the antlr-interest mailing list