next up previous contents
Next: 4.2 Building Abstract Syntax Up: 4 Abstract Syntax Previous: 4 Abstract Syntax   Contents

4.1 Building Abstract Syntax Trees in Java

When building ASTs, it's a good idea to define multiple classes to capture various families of constructs. For example, we can have an Exp class to represent expressions, Stmt class to represent statements, and Type class to represent types. Here is an example of Exp in Java:

abstract class Exp {
}
class IntegerExp extends Exp {
   public int value;
   public IntegerExp ( int n ) { value=n; }
}
class TrueExp extends Exp {
   public TrueExp () {}
}
class FalseExp extends Exp {
   public FalseExp () {}
}
class VariableExp extends Exp {
   public String value;
   public VariableExp ( String n ) { value=n; }
}
class BinaryExp extends Exp {
   public String operator;
   public Exp left;
   public Exp right;
   public BinaryExp ( String o, Exp l, Exp r ) { operator=o; left=l; right=r; }
}
class UnaryExp extends Exp {
   public String operator;
   public Exp operand;
   public UnaryExp ( String o, Exp e ) { operator=o; operand=e; }
}
class ExpList {
   public Exp head;
   public ExpList next;
   public ExpList ( Exp h, ExpList n ) { head=h; next=n; }
}
class CallExp extends Exp {
   public String name;
   public ExpList arguments;
   public CallExp ( String nm, ExpList s ) { name=nm; arguments=s; }
}
class ProjectionExp extends Exp {
   public Exp value;
   public String attribute;
   public ProjectionExp ( Exp v, String a ) { value=v; attribute=a; }
}
class RecordElements {
   public String attribute;
   public Exp value;
   public RecordElements next;
   public RecordElements ( String a, Exp v, RecordElements el )
          { attribute=a; value=v; next=el; }
}
class RecordExp extends Exp {
    public RecordElements elements;
    public RecordExp ( RecordElements el ) { elements=el; }
}
For example,
new BinaryExp("+",new BinaryExp("-",new VariableExp("x"),new IntegerExp(2)),
              new IntegerExp(3))
constructs the AST for the input (x-2)+3.



fegaras 2012-01-10