CS453 example reprise using visitor that does traversal Visitor - - PowerPoint PPT Presentation

cs453
SMART_READER_LITE
LIVE PREVIEW

CS453 example reprise using visitor that does traversal Visitor - - PowerPoint PPT Presentation

Plan for Today PA3 Note Quiz 3 Visitor Design Pattern main idea and example CS453 example reprise using visitor that does traversal Visitor patterns FAQ about visitors Type checking and Code Generation Dot visitor Other


slide-1
SLIDE 1

CS453 Visitor patterns Type checking and Code Generation

CS453 Lecture Building ASTs and Visitor Design Pattern 2

Plan for Today

PA3 Note Quiz 3 Visitor Design Pattern – main idea and example – example reprise using visitor that does traversal – FAQ about visitors – Dot visitor – Other examples including integer and byte expression evaluation Debugging Ideas Big picture: using visitor design pattern for PA3 – Type checking for PA3 – Code generation for PA3

CS453 Lecture Building ASTs and Visitor Design Pattern 3

PA3 Note: Syntax-directed Construction of AST

Need the following in MJDriver.java ast.node.Node ast_root = (ast.node.Node)parser.parse().value;! Need the following in mj.cup (or mj_ast.cup if that is what you call it) Program ::=

… {: RESULT = new Program( . . . ); :} ;

Quiz 3

Go to RamCT results.

CS453 Lecture Building ASTs and Visitor Design Pattern 4

slide-2
SLIDE 2

CS453 Lecture Building ASTs and Visitor Design Pattern 5

Program MainClass BlockStatement MeggySetPixel ByteCast ByteCast ColorLiteral Meggy.Color.WHITE MulExp ByteCast ByteCast IntLiteral 1 IntLiteral 2 PlusExp ByteCast IntLiteral 4 IntLiteral 3

Building AST Bottom Up

class Byte {! public static void main(String[] whatever){! Meggy.setPixel( ! // Byte multiplication: Byte x Byte -> Int ! (byte)( (byte)1*(byte)2 ),! // Mixed type expression: Byte x Int -> Int ! (byte)( (byte)3 + 4 ), Meggy.Color.WHITE );! }! }!

CS453 Lecture Building ASTs and Visitor Design Pattern 6

Visitor Design Pattern

Situation

– Want to perform some processing on all items in a data structure, e.g type check or code generate – Will be adding many different ways to process items depending on the type (class) – Will not be changing the classes of the data structure itself (much, or at all)

Possibilities

– OO: For each functionality and each class, add a method – con: each new functionality is spread over multiple files – con: sometimes can’t add methods to existing class hierarchy – Procedural: Use switch statement in one method traversing the data structure – pro: keeps all the code for the feature in one place – con: can be costly and involve lots of casting – Visitor design pattern (best of all)

CS453 Lecture Building ASTs and Visitor Design Pattern 7

AST and visitors

We will generate an AST instead of directly generating code.

  • Why is that a good idea? What can we now do better?

We can walk over this AST multiple times and perform different functions, e.g. Create symbol table, Check types, Generate code We will then traverse the AST for each particular need using visitors each node of the AST has an accept method, that calls an appropriate visitor method, e.g. plusExp.accept() calls visitPlusExp() Class hierarchy is USEFUL, because we only override a few methods the ones that differ from standard behavior

Visit, In , Out

When visiting the AST, we encounter a node for the first time (In encounter) and we encounter the node for the last time (Out encounter). These encounters are often associated with certain actions:

Visitor::visitXYZ(node) {! inXYZ(node);! for each child c of node in left to right order ! c.accept(this);!

  • utXYZ(node);!

}!

inXYZ is called when the node is first encountered in the DFLR walk,

and outXYZ is called when the node is left behind in the DFLR walk. This is often sufficient for code generation purposes (+,-,*,setPixel), but not always: (if, while, &&). WHY NOT?

CS453 Lecture Building ASTs and Visitor Design Pattern 8

slide-3
SLIDE 3

CS453 Lecture Building ASTs and Visitor Design Pattern 9

Program MainClass BlockStatement MeggySetPixel ByteCast ByteCast ColorLiteral Meggy.Color.WHITE MulExp ByteCast ByteCast IntLiteral 1 IntLiteral 2 PlusExp ByteCast IntLiteral 4 IntLiteral 3

Depth First Visitor and in and out methods

class Byte {! public static void main(String[] whatever){! Meggy.setPixel( ! // Byte multiplication: Byte x Byte -> Int ! (byte)( (byte)1*(byte)2 ),! // Mixed type expression: Byte x Int -> Int ! (byte)( (byte)3 + 4 ), Meggy.Color.WHITE );! }! }!

CS453 Lecture Building ASTs and Visitor Design Pattern 10

Example Use of the visitor design pattern

// in driver:

ast_root.accept(new AVRgenVisitor(outfilehandle));

// in AST class MulExp

public void accept(Visitor v) { v.visitMulExp(this); }

// in class DepthFirstVisitor

public void inMulExp(MulExp node) { defaultIn(node); } public void outMulExp(MulExp node) { defaultOut(node); } public void visitMulExp(MulExp node){ inMulExp(node); if if(node.getLExp() != null null) node.getLExp().accept(this this); if if(node.getRExp() != null null) node.getRExp().accept(this this);

  • utMulExp(node);

}

// in type checker and code generator  This is YOUR job

public void outMulExp(MulExp node) { // overrides default // gen code to pop operands, do the *, push the result }

CS453 Lecture Building ASTs and Visitor Design Pattern 11

FAQ, Debugging Ideas

Check out your recit from last week. It tells you a lot!! How do I associate data with a node in the AST if I can’t add fields to the

node classes? What if I want to do the same thing on each node? What if I only need to do something on certain nodes?

Debugging System.out.println in parser actions

Break points in visitor methods Use the DotVisitorWithMap

Big Picture

PA2

– Syntax-directed expression “evaluation” – Syntax-directed code generation

PA3

– Syntax-directed AST creation – Visitors for creating the dot file for visualization (provided) – Visitor for checking types – Visitor for generating code

Later assignments

– Visitor for building a symbol table – Visitor for allocating memory for variables – Visitor for doing register allocation

CS453 Lecture Building ASTs and Visitor Design Pattern 12

slide-4
SLIDE 4

Code Structure

In driver, first call the parser to get an AST: mj_ast_parser parser = new mj_ast_parser(lexer); ast.node.Node ast_root = (ast.node.Node)parser.parse().value; Next create a dot file for the AST for debugging purposes: java.io.PrintStream astout = new java.io.PrintStream(…); ast_root.accept(new DotVisitor(new PrintWriter(astout))); Finally, create Type-Checker and an AVRgenVisitor instances: java.io.PrintStream avrsout = new java.io.PrintStream(…); symtable.SymTable globalST = new symtable.SymTable(); ast_root.accept(new CheckTypes(globalST)); ast_root.accept(new AVRgenVisitor(new PrintWriter(avrsout)));

CS453 Lecture Building ASTs and Visitor Design Pattern 13

Code Structure cont’

  • CheckTypes and AVRgenVisitor inherit from DepthFirstVisitor.
  • The first thing to do is move all of the code generation for the main

prologue and epilogue into the AVRgenVisitor.

  • The Meggy.setPixel() code generation should occur in outMeggySetPixel().
  • Code generation for expressions: use the AVR run-time stack.

Code that evaluates an expression should expects its operands and leaves its result on the top of the run-time stack (RTS), e.g.

  • utFalseExp outTrueExp

ldi r24, 0 ldi r24,1 push r24 push r24

  • The DFLR visitor can use the outOP method to generate code for an
  • perator, because code for the children has just been generated and has left

the result(s) on the RTS

CS453 Lecture Building ASTs and Visitor Design Pattern 14 CS453 Lecture Building ASTs and Visitor Design Pattern 15

Program MainClass BlockStatement MeggySetPixel ByteCast ByteCast ColorLiteral Meggy.Color.WHITE MulExp ByteCast ByteCast IntLiteral 1 IntLiteral 2 PlusExp ByteCast IntLiteral 4 IntLiteral 3

Code Generation with a Visitor

class Byte {! public static void main(String[] whatever){! Meggy.setPixel( ! // Byte multiplication: Byte x Byte -> Int ! (byte)( (byte)1*(byte)2 ),! // Mixed type expression: Byte x Int -> Int ! (byte)( (byte)3 + 4 ), Meggy.Color.WHITE );! }! }!

Type Checking

Java allows mixing numeric types. For Meggy-Java this means that many

  • perators allow mixing byte and int

byte a = 0, b = 1;! byte b2 = (byte)-b;! byte wrong1 = -b;! byte sum = (byte)(a + 5);! byte wrong2 = a+5;! int ok = - - -b;! // but check out ! int wrong3 = ---b;! int j, i = 2;!

if (i==b) j = i+b; else j=(byte)((byte)i+b);!

CS453 Lecture Building ASTs and Visitor Design Pattern 16

slide-5
SLIDE 5

If Statement code generation

By default, the result of the condition evaluation has been pushed on the RTS. When the visitor encounters ifStmt, inIF and outIF do not suffice.

  • WHY? We need more complex control:

if / | \ B S1 S2 We need to handle the if statement with a visit statement so we can control the order that code is generated for its children, using branches, jumps and labels. First, code needs to be generated for the condition, followed by branching instructions, the then block, control to jump over else block, then the else block, and then the end label.

CS453 Lecture Building ASTs and Visitor Design Pattern 17

Branches and jumps

An AVR detail: conditional branches can only go so far in the code, and code generated, e.g for then or else block is not bounded and thus can exceed that limit. Therefore we have to use jmp sometimes. Notice: breq is replaced with with a brne followed by a jmp to handle this cp r24, r25 #WANT breq MJ_L6 brne MJ_L7 jmp MJ_L6 MJ_L7: ... inbounded stretch of code … MJ_L6:

CS453 Lecture Building ASTs and Visitor Design Pattern 18

Not: there is no not in AVR, but there is xor

truth table for not and xor x y !x x xor y 0 0 1 0 0 1 1 1 1 0 0 1 1 1 0 0 We can implement NOT x with x XOR 1 :

  • utNotExp

pop r24! ldi r22, 1! eor r24,r22! push r24!

CS453 Lecture Building ASTs and Visitor Design Pattern 19

While statement

while / \ B S What is the wiring logic? SLbl:! eval B on stack! if false jump to endLbL! gen Code for S! jump to Slbl! endLbL:!

CS453 Lecture Building ASTs and Visitor Design Pattern 20

slide-6
SLIDE 6

Short circuited (wired) AND, equals

Similar to the If Statement and While Statement, code generation will need to be implemented in the visitAndExp() && / \ B1 B2 can be implemented as: if (B1) return B2 else return false equalExp, the equality operator == Just like in plus and minus, we need to take the mixed type semantics of Java into account, by promoting a byte (1 register) to an int (register pair), making sure the int value correctly preserves the sign.

CS453 Lecture Building ASTs and Visitor Design Pattern 21