Wednesday , April 15 Handout: "Jasmin Instruction Syntax" is sent out. What does a code generator do? Look at an example: class simple { main() { int a; read(a); print("answer=",2*a+1,'\n'); } } The AST for this simple class is: classNode / \ / \ IdentNode MemberDeclsNode (simple) / \ / \ null methodDeclsNode / | | \ \ / | | \ \ IdentNode null null (*)stmtsNode (main) / \ / \ (*) / \ FieldDeclsNode ReadNode stmtsNode | / \ | \ | / null | \ VarDeclNode NameNode | null / | \ / \ printNode / | \ / null / \ IdentNode IntType null IdentNode / \ (a) (a) StringLitNode printNode ("answer=") / \ / \ / \ binaryOpNode printNode / (+) \ | \ / \ | null binaryOpNode IntLitNode charLitNode / (*) \ (1) ('\n') / \ IntLitNode NameNode (2) / \ / null IdentNode (a) The code generator will call CodeGen(File) to create a new File whose name is classname.j.For example, here it is simple. Then CG() will be called as member function in each class, which will traverse the AST, generate JVM code into File. The above program(class simple) might be translated into the following JVM assembler code: .class public simple //This part is fixed besides .super java/lang/object //the name of the class .method publec static([LJava/lang/String;)V //[ means array of strings //L means className followed //V means Void invokestatic simple/main()V //call main() return .limit stack 2 //mex depth of stack .end method (The above part is done for classNode) .method public static main()V invokestatic csxLib/readInt()I //call csxLib.readInt() istore 0 ldc "answer=" invokestatic csxLib/printString(Ljava/lang/String;)V //call csxLib.printString(String) ldc 2 //push 2 on the stack load 0 //integer load from VarIndex 0 imul ldc 1 iadd //compute 2*a + 1 invokestatic csxLib/printInt(I)V ldc 10 //integer representation for '\n' invokestatic csxLib/printChar(C)V return .limit stack 25 .limit locals 1 //number of local variables .end method About the length of stack, we can compute rhe precise number which will be covered later. Now we just guess a big enough number. Some suggestions to create a code generator: 1. make it clear what are the available Jasmin instruction 2. use javap -c test to see the JVM instructions selected by Java compiler (where test.class is a class file created by javac)