15.08.2013 Views

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Needed Infrastructure: Environments<br />

Need a structure to keep track of the values of declared identifiers.<br />

(take shadowing into account)<br />

Definition 470 An environment is a finite partial function from keys (identifiers) to values.<br />

We will need the following operations on environments:<br />

creation of an empty environment ( the empty function)<br />

insertion of a key/value pair 〈k, v〉 into an environment ϕ: ( ϕ, [v/k])<br />

lookup of the value v for a key k in ϕ ( ϕ(k))<br />

Realization in SML by a structure with the following signature<br />

type ’a env (* a is the value type *)<br />

exception Unbound of id (* Unbound *)<br />

val empty : ’a env<br />

val insert : id * ’a * ’a env -> ’a env (* id is the key type *)<br />

val lookup : id * ’a env -> ’a<br />

c○: Michael Kohlhase 300<br />

The next slide has the main SML function for compiling SW programs. Its argument is a SW program<br />

(type program) and its result is an expression of type code, i.e. a list of L(VM) instructions. From<br />

there, we only need to apply a simple conversion (which we omit) to numbers to obtain L(VM)<br />

byte code.<br />

Compiling SW programs<br />

SML function from SW programs (type program) to L(VM) programs (type code).<br />

uses three auxiliary functions for compiling declarations (compileD), statements (compileS),<br />

and expressions (compileE).<br />

these use an environment to relate variable names with their stack index.<br />

the initial environment is created by the declarations.<br />

(therefore compileD has an environment as return value)<br />

type env = index env<br />

fun compile ((ds,s,e) : program) : code =<br />

let<br />

val (cds, env) = compileD(ds, empty, ~1)<br />

in<br />

cds @ compileS(s,env) @ compileE(e,env) @ [halt]<br />

end<br />

c○: Michael Kohlhase 301<br />

The next slide has the function for compiling SW expressions. It is realized as a case statement<br />

over the structure of the expression.<br />

Compiling SW Expressions<br />

constants are pushed to the stack.<br />

variables are looked up in the stack by the index determined by the environment (and pushed<br />

to the stack).<br />

167

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!