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
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Compiling µML Expressions (Continued)<br />
fun compileE (e:exp, env:env, tail:code) : code =<br />
case e of<br />
Con i => [con i] @ tail<br />
| Id i => [arg((lookupA(i,env)))] @ tail<br />
| Add(e1,e2) => compileEs([e1,e2], env) @ [add] @ tail<br />
| Sub(e1,e2) => compileEs([e1,e2], env) @ [sub] @ tail<br />
| Mul(e1,e2) => compileEs([e1,e2], env) @ [mul] @ tail<br />
| Leq(e1,e2) => compileEs([e1,e2], env) @ [leq] @ tail<br />
| If(e1,e2,e3) => let<br />
val c1 = compileE(e1,env,nil)<br />
val c2 = compileE(e2,env,tail)<br />
val c3 = compileE(e3,env,tail)<br />
in if null tail<br />
then c1 @ [cjp (4+wlen c2)] @ c2<br />
@ [jp (2+wlen c3)] @ c3<br />
else c1 @ [cjp (2+wlen c2)] @ c2 @ c3<br />
end<br />
| App(i, es) => compileEs(es,env) @ [call (lookupP(i,env))] @ tail<br />
and (* mutual recursion with compileE *)<br />
fun compileEs (es : exp list, env:env) : code =<br />
foldl (fn (e,c) => compileE(e, env, nil) @ c) nil es<br />
c○: Michael Kohlhase 321<br />
Now we turn to the declarations compiler. This is considerably more complex than the one for<br />
SW we had before due to the presence of formal arguments in the function declarations. We<br />
first define a function that inserts function arguments into an environment. Then we use that<br />
in the expression compiler to insert the function name and the list of formal arugments into the<br />
environment for later reference. In this environment env’’ we compile the body of the function<br />
(which may contain the formal arugments). Observe the use of the tail arugment for compileE to<br />
pass the return command. Note that we compile the rest of the declarations in the environment<br />
env’ that contains the function name, but not the function arguments.<br />
Compiling µML Expressions (Continued)<br />
fun insertArgs’ (i, (env, ai)) = (insert(i,Arg ai,env), ai+1)<br />
fun insertArgs (is, env) = (foldl insertArgs’ (env,1) is)<br />
fun compileD (ds: declaration list, env:env, ca:ca) : code*env =<br />
case ds of<br />
nil => (nil,env)<br />
| (i,is,e)::dr =><br />
let<br />
val env’ = insert(i, Proc(ca+1), env)<br />
val env’’ = insertArgs(is, env’)<br />
val ce = compileE(e, env’’, [return])<br />
val cd = [proc (length is, 3+wlen ce)] @ ce<br />
(* 3+wlen ce = wlen cd *)<br />
val (cdr,env’’) = compileD(dr, env’, ca + wlen cd)<br />
in<br />
(cd @ cdr, env’’)<br />
end<br />
c○: Michael Kohlhase 322<br />
182