Commit 0c0fa78f authored by Luca Bataillard's avatar Luca Bataillard
Browse files

write let CPS conversion

parent 18cbf312
......@@ -11,6 +11,7 @@ object CL3ToCPSTranslator extends (S.Tree => C.Tree) {
def transform(tree: S.Tree)(ctx: C.Atom => C.Tree): C.Tree = {
def transformApp(fun: S.Tree, args: Seq[S.Tree]) = {
// Build return continuation
val cntName = Symbol.fresh("c")
......@@ -28,8 +29,27 @@ object CL3ToCPSTranslator extends (S.Tree => C.Tree) {
transform(fun)(fId => transformArgs(args)(fId, Seq()))
}
def transformLetRec(funs: Seq[S.Fun], body: S.Tree) = {
val cpsFuns = funs map { case S.Fun(name, args, body) =>
val cName = Symbol.fresh("c-" + name)
val funCtx = (v: C.Atom) => C.AppC(cName, Seq(v))
C.Fun(name, cName, args, transform(body)(funCtx))
}
C.LetF(cpsFuns, transform(body)(ctx))
}
tree match {
case S.Lit(v) => ctx(C.AtomL(v))
case S.Ident(id) => ctx(C.AtomN(id))
case S.Let(bindings, body) =>
bindings.foldRight(transform(body)(ctx)) {
case ((name, expr), tree) => transform(expr)(v => C.LetP(name, L3.Id, Seq(v), tree))
}
case S.If(cnd, thn, els) => cnd match {
case S.Prim(p: L3TestPrimitive, primArgs) =>
// Context continuation name
......@@ -70,7 +90,7 @@ object CL3ToCPSTranslator extends (S.Tree => C.Tree) {
transform(newIf)(ctx)
}
case S.App(fun, args) => transformApp(fun, args)
case S.Halt(arg) => transform(arg)(a => C.Halt(a))
case S.LetRec(funs, body) => transformLetRec(funs, body)
case S.Prim(p, args) => p match {
case _ : L3TestPrimitive =>
val newPrim = S.If( tree,
......@@ -90,7 +110,7 @@ object CL3ToCPSTranslator extends (S.Tree => C.Tree) {
case _ => throw new Exception("unreachable code")
}
}
case S.Ident(id) => ctx(C.AtomN(id))
case S.Halt(arg) => transform(arg)(a => C.Halt(a))
}
}
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment