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 StringExp extends Exp {
   public String value;
   public StringExp ( String s ) { value=s; }
}
class VariableExp extends Exp {
   public String name;
   public VariableExp ( String n ) { name=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 CallExp extends Exp {
   public String name;
   public List<Exp> arguments;
   public CallExp ( String nm, List<Exp> s ) { name=nm; arguments=s; }
}
class ProjectionExp extends Exp {
   public Exp record;
   public String attribute;
   public ProjectionExp ( Exp v, String a ) { record=v; attribute=a; }
}
class RecordElement {
   public String attribute;
   public Exp value;
   public RecordElement ( String a, Exp v ) { attribute=a; value=v; }
}
class RecordExp extends Exp {
    public List<RecordElement> elements;
    public RecordExp ( List<RecordElement> 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.



2015-01-20