mercredi 30 octobre 2019

Building AST automatically

I have a parser for a legacy programming language. The AST is not present in the parser and I need to build an AST automatically when an attributes are added to the node. For E.g., Let's consider the below Node along with some custom nodes extending the Node:

class Node {
    List<Node> parent;
    List<Node> child;
//getters and setters
}
final class MethodNode extends Node {
    Object o1;
    IfExpression o2;
//getters and setters
}
final class IfExpression extends Node {
    Object o1;
//getters and setters
}

Let's say I'm setting the IfExpression in MethodNode then it means MethodNode is the parent of IfExpression in the AST. So I need to add an Insert logic in the setters of MethodNode(Parent) like below

public void setO2(@NonNull final IfExpression o2){
    this.o2 = o2;
    super.child.add(o2);
    o2.parent.add(this);
} 

After parsing is complete, I have the logic to build the AST automatically using reflection. Reflection logic:

  1. Iterate all the fields in the Node/Custom Nodes
  2. Check if the field is not null
  3. If yes, Check if the field is of type Node
  4. If yes, Insert into a parent and child list
  5. I also added some custom annotations in case if we need to ignore certain fields. So there is this check along with 2nd and 3rd conditions mentioned above.

I would like to know, if there is any better approach than this custom reflection logic





Aucun commentaire:

Enregistrer un commentaire