Section 3 with Remik (rz33@cornell.edu) Meeting #9 Notes =========================================================== Administrivia =========================================================== + Extra Credit is being added for good error & type checking on HW #2 =========================================================== Review =========================================================== + Abstract Syntax Trees (AST) & Compiling + Modeling ASTs in Java =========================================================== The 2 fundamental stages of compiling is generation of a tree and the final output code. The flow chart: | | | Source (or tokenized) code | \/ -------------------- | Tree | | Generation | -------------------- | | | AST Tree | \/ -------------------- | Code | | Generation | -------------------- | | | Target (object) code | \/ =========================================================== Abstract Syntax Trees (AST) =========================================================== To build a tree, we need to know what it looks like. We do it by using the actual language grammar. Lets use the BNF PRG ::= START EXP END START ::= "main()" END ::= "return" EXP ::= '(' EXP ')' | int | EXP OP EXP OP ::= '+' | '-' Sample Program: main() ((1+2) - (3+4)) return =========================================================== Modeling ASTs in Java =========================================================== We can replicate the trees in Java by using classes. Using the grammar we would have something like this, class PRG { EXP exp = null; public static final String START = "main()"; public static final String END = "return"; } class EXP { EXP exp = null; EXP expLeft = null; EXP expRight = null; int integer; char op; public static final char PLUS = '+'; public static final char MINUS = '-'; } Our sample program above would look as follows in tree form if we had the class instances PRG p; EXP e0, e, e1, e2, e3, e4, e5, e6; p | e0 | e /\ / \ / \ / \ e1 e2 /\ /\ / \ / \ / \ / \ / \ / \ e3 e4 e5 e6 But we still need to instantiate the objects to model our sample program. Here's one way: e3 = new EXP(); // base case Expressions e3.integer = 1; e4 = new EXP(); e4.integer = 2; e5 = new EXP(); e5.integer = 3; e6 = new EXP(); e6.integer = 4; e1 = new EXP(); // compound Expressions e1.expLeft = e3; e1.expRight = e4; e1.op = PLUS; e2 = new EXP(); e2.expLeft = e5; e2.expRight = e6; e2.op = PLUS e = new EXP(); e.expLeft = e1; e.expRight = e2; e.op = MINUS; e0 = new EXP(); // super-expression; remember '(' EXP ')' ? e0.exp = e; p = new PRG(); // the program p.exp = e0; =========================================================== Next week... Creating the tree recursively in Java & code generation using this tree.