WRIGHT STATE UNIVERSITY

Department of Computer Science and Engineering

Department of Computer Science and Engineering

CS 784 Spring 2012
Prasad

**Assignment 3 (Due: May 30) (15 pts)**

**Compiling and Evaluating Simple Expressions**

The primary goal of this assignment is to gain familiarity with language
processing concepts and techniques using the infrastructure developed for the
EOPL text.

An** **EBNF
(Extended Backus-Naur Form) grammar for arithmetic expressions containing
variables ( **i,
j ,
k**) and binary operators (

` <expr>
-> <term> {
+ <term> }`

` <term>
-> <factor> {
* <factor> }`

`
<factor> -> <var> |
( <expr> )`

` <var> ->
i |
j
| k `

`{<expr>, <term>, <factor>, <var>}`
are the non-terminals. `{ i,j,k,+,*,(,)}`
are the terminals.

Some example
arithmetic expressions derivable in the grammar are "** i**",
"

Now consider the following template for a collection of Java programs.

class Test {

static int f(int i, int j, int k) {

return<expr>;

}

public static void main(String[] args) {

System.out.println(f(2,4,8));

}

}

To obtain a valid Java
program (that is, valid function body), replace <expr>
with an expression derived from the above grammar.

A Java compiler takes
the source code and generates Java bytecodes, which resemble assembly language
instructions for an abstract *stack machine*. The translation of the return-expression "` ((i +
k) * j)"
`into bytecodes can be given symbolically as:

`
iload_`0

` iload_2`

` iadd`

` iload_`1

` imul `

The formal
arguments ` i,
j,`
and

On the right is an applet that
performs the required translation of the expression into Java bytecodes for
your reference. To generate more examples of such
translations, instantiate the above template by replacing <expr>
with a legal arithmetic expression in "Test.java",
compile it using

"%javac
Test.java", and reverse engineer
the class file using

"%javap -c
Test", focussing on "*Method
int f(int, int,
int)*".

*Note also that the solution written in Java
exemplifies object-oriented style of programming, while the Scheme solution to
be developed below exemplifies functional style of programming.*

** PART I:** Write a
function

>(**run**
"**((i * i) + j * (k) + j)**")

40

** PART II:** Now write a
function

>(**compile** "((i
* i) + j * (k) + j)")

(iload_0 iload_0 imul iload_1 iload_2 imul iadd iload_1 iadd)

** PART III:** Now write a
function

(run "EXPR") = (interpret (compile "EXPR"))

(Observe that the simulation of runtime stack object requires Scheme's set! and let constructs.)

>(**interpret** (**compile**
"**((i * i) + j * (k) + j)**"))

40

__What to hand in?__

Submit your well-documented solution
in a file named codegen.scm
by running the following turn-in command on
unixapps1.wright.edu`. ``
`

%/common/public/tkprasad/cs784/turnin-pa3