开发者

Creating an AST Tree in Java given another AST Tree

Currently, I'm working on representing an AST tree I have, written in SML, in Java so I can traverse it in Java whenever I want.

I'm wondering if I should just create a Node class in Java that has the data I want to represent, along with a an Array list (List) to represent the children for that specific node? Then, I can have an ASTTree class that has only the root node.

I don't know if there is something more fancy I need to consider.

Any questions/comments will be greatly ap开发者_开发技巧preciated!

-Paul


It depends on what you want to do over that tree.

I usually implement it by creating a specific node for every kind of operation I would need, for example

ASTBinaryOperation implements ASTNode
{
  ASTNode left, right;
  Operator op;

  Result visit()
  {
    Result lr = left.visit();
    Result rr = right.visit();

    return op.apply(lr, rr);
  }
}

for a classical binary operator node, while I would use an ArrayList for example for declarations:

ASTDecl implements ASTNode
{
  String name;
  Type type;
  Value value;
}

ASTDecls implements ASTNode
{
  ArrayList<ASTDecl> declarations;
}

that is built up by the parser. So a root node would be something like:

ASTRoot {
  ASTDecls declarations;
  ASTFunctions functions;
}

ASTFunctions {
  ASTDecls args;
  ASTBody body;
  ..
}

ASTBody {
  ArrayList<ASTStatement> statements;
  ...
}

and so on.

Of course it depends what you will want to do, I used this approach to visit the AST to generate an intermediate code by recursively visiting the tree.. but storing whatever in an ArrayList will make you lose the specific behaviour and meaning of a single ASTNode.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜