[antlr-interest] On trees and JavaBeans part 1: the AST interface

Scott Stanchfield scott at javadude.com
Mon Apr 18 04:26:21 PDT 2005


That other note got me thinking about something I wanted to do...

The problem with ANTLR tree nodes (at least in ANTLR 2.x) is that each node
must implement an interface. To use non-ANTLR objects as tree nodes, you
must adapt every single object, which creates a lot of overhead.

For example, suppose I wanted to use an ANTLR tree parser to explore an
Eclipse-generated Java AST. I would have to write an AST adapter that I wrap
around each Eclipse node, and when the adapter is asked for first child, I'd
return a wrapped "first child", and when asked for "nextSibling" I'd return
a wrapped next child. Very inefficient...


Instead of doing trees as an AST interface per node, we should do them more
like Swing does its TreeModel.

Swing has a TreeModel interface that represents "an entire tree". It has
methods like

   Object getRoot();
   Object getChild(Object parent, int index);
   int getChildCount(Object parent);
   ...

The JTree component asks whatever implements this interface for the
relationships so it can determine what to render on the screen. Incredibly
flexible.

If the new tree parsers used something like this, *a tree parser could walk
**any** data structure*.

For the Eclipse AST example, I could write a single "ASTModel"
implementation that interprets Eclipse's AST nodes. The tree parser
implementation would ask

   model.getChild(parent, num)

instead of

   parent.getChild(num)


Swing has a default implementation that uses a TreeNode interface for each
node. The same could be done for ANTLR trees, and the default ast model
could work with AST nodes exactly as today. The default model basically does
things like

  public Object getChild(Object parent, int num) {
    return ((AST)parent).getChild(num);
  }


This would allow a very efficient adapter mechanism for existing data
structures, allowing ANTLR tree parsers to be used to easily explore DOMs,
non-ANTLR ASTs, and pretty much any other data structure.


More in part 2...

-- Scott






More information about the antlr-interest mailing list