CS 496 - Lab 3

Code Generation

In Assignment 5, you will be implementing code generation, translating the ASTs of SPL programs into Java bytecode.

In this lab, we will extend the calculator program so that rather than directly evaluating expression values, we will emit instructions using a very simplified form of Java bytecode.

Getting started

If you already have a project called calc in your Eclipse workspace, rename it (right click on the project and choose Refactor->Rename).

Import lab3.zip into the Eclipse workspace (File->Import...->Existing Projects into Workspace->Archive File).  You should see a project called calc in your workspace.


The class called MiniJVM implements an extremely simplified subset of Java bytecode instructions:

only integer values are supported

there are no objects, methods, or local variables

static fields are the only kind of variables

a static method called println is available to pop one value from the operand stack and print its value

The following instructions are supported:

field fieldname - creates a static field with given name

iconst intvalue - pushes intvalue onto the operand stack

iadd - pop right operand, pop left operand, push the sum left + right

isub - pop right operand, pop left operand, push the difference left - right

imul - pop right operand, pop left operand, push the product left * right

idiv - pop right operand, pop left operand, push the quotient left / right

getstatic fieldname - pushes the value stored in the static field fieldname onto the stack

putstatic fieldname - pop value from operand stack, store it in static field fieldname

invokestatic methodname - pop value from operand stack, pass it to named method

the only method supported is println, which prints the value passed to it

Here is an example run of the MiniJVM program (user input in bold red):

field x
iconst 6
putstatic x
iconst 7
getstatic x
iconst 3
invokestatic println

Here is a detailed explanation of the program:

field x              - create a static field called x
iconst 6 - push the int value 6
putstatic x - pop the int value 6, store it in the field x
iconst 7 - push the int value 7
getstatic x - push the value (6) currently in the field x
imul - pop right (6), pop left (7), push left * right (42)
iconst 3 - push int value 3
isub - pop right (3), pop left (42), push left - right (39)
invokestatic println - pop the int value 39, print it

This program implements the following calculator "program"

field x
x = 6
7 * x - 3

Note that we are assuming that the calculator grammar is extended to support field declarations.

Your task

Modify the calculator so that

1. it supports field declarations of the form

field fieldname

where fieldname is an identifier

2. it emits MiniJVM instructions that will perform the computation embodied by the calculator "program"

Define a new RecursiveASTNodeVisitor subclass called CodeGeneratingVisitor to implement the code generation.