progs/fun/fun_llvm.sc
changeset 958 fddf099a82f8
parent 905 15973df32613
child 959 64ec1884d860
--- a/progs/fun/fun_llvm.sc	Tue Nov 28 11:45:48 2023 +0000
+++ b/progs/fun/fun_llvm.sc	Sat Dec 02 21:37:04 2023 +0000
@@ -74,6 +74,35 @@
 }
 case class KReturn(v: KVal) extends KExp
 
+// some functions for drawing KVal-trees 
+// inspired by William Bradford Larcombe
+
+def draw_vals(vs: List[KVal], prefix: String) : String = {
+  val vsi = vs.iterator
+  vsi.map(v => draw_val(v, prefix, vsi.hasNext)).mkString 
+}
+
+def draw_val(k: KVal, prefix: String, more: Boolean) : String = {
+  val full_prefix = s"$prefix${if more then "├" else "└"}"
+  val childPrefix = s"$prefix${if more then "│" else ""}  "
+  s"\n${full_prefix}" ++ 
+  (k match {
+    case KVar(x) => x
+    case KNum(n) => n.toString
+    case Kop(op, v1 , v2) => s"KOp($op) ${draw_vals(List(v1, v2), childPrefix)}" 
+    case KCall(nme, as) => s"KCall($nme) ${draw_vals(as, childPrefix)}" 
+    case KWrite(v) => s"KWrite ${draw_val(v, childPrefix, false)}" 
+  })
+}
+
+def draw(k: KVal) = "│" ++ draw_val(k, "", false)
+
+// val k1 = KVar("foo")
+// val k2 = KNum(1)
+// val k3 = Kop("-", Kop("+", k1, k2), KNum(2))
+// println(draw(k3).mkString)
+// println(draw(KCall("bar", List(k1,k2,k3,k2,k1))).mkString)
+
 
 // CPS translation from Exps to KExps using a
 // continuation k.
@@ -112,6 +141,8 @@
 //initial continuation
 def CPSi(e: Exp) = CPS(e)(KReturn)
 
+
+
 //some testcases:
 // (1 + 2) * 3
 println(CPSi(Aop("*", Aop("+", Num(1), Num(2)), Num(3))).toString)
@@ -184,13 +215,12 @@
 
 
 
-
 // convenient string interpolations 
 // for instructions, labels and methods
 import scala.language.implicitConversions
 import scala.language.reflectiveCalls
 
-implicit def sring_inters(sc: StringContext) = new {
+extension (sc: StringContext) {
     def i(args: Any*): String = "   " ++ sc.s(args:_*) ++ "\n"
     def l(args: Any*): String = sc.s(args:_*) ++ ":\n"
     def m(args: Any*): String = sc.s(args:_*) ++ "\n"
@@ -271,14 +301,6 @@
 def compile(prog: List[Decl]) : String = 
   prelude ++ (prog.map(compile_decl).mkString)
 
-
-// pre-2.5.0 ammonite 
-// import ammonite.ops._
-
-// post 2.5.0 ammonite
-// import os._
-
-
 @main
 def main(fname: String) = {
     val path = os.pwd / fname