diff -r b4f5714485e1 -r 30943d5491b6 progs/fun.scala --- a/progs/fun.scala Wed Oct 02 02:09:48 2019 +0100 +++ b/progs/fun.scala Wed Oct 02 14:05:36 2019 +0100 @@ -1,10 +1,26 @@ // A Small Compiler for a Simple Functional Language // (includes an external lexer and parser) +// +// call with +// +// scala fun.scala fact +// +// scala fun.scala defs +// +// this will generate a .j file and run the jasmin +// assembler (installed at jvm/jasmin-2.4/jasmin.jar) +// it runs the resulting JVM file twice for timing +// purposes. -import java.io._ + + object Compiler { +import java.io._ +import scala.util._ +import scala.sys.process._ + // Abstract syntax trees for the Fun language abstract class Exp extends Serializable abstract class BExp extends Serializable @@ -165,16 +181,15 @@ (end - start)/(i * 1.0e9) } -def deserialise[T](fname: String) : T = { - val in = new ObjectInputStream(new FileInputStream(fname)) - val data = in.readObject.asInstanceOf[T] - in.close - data +def deserialise[T](fname: String) : Try[T] = { + import scala.util.Using + Using(new ObjectInputStream(new FileInputStream(fname))) { + in => in.readObject.asInstanceOf[T] + } } - def compile(class_name: String) : String = { - val ast = deserialise[List[Decl]](class_name ++ ".prs") + val ast = deserialise[List[Decl]](class_name ++ ".prs").getOrElse(Nil) val instructions = ast.map(compile_decl).mkString (library + instructions).replaceAllLiterally("XXX", class_name) } @@ -184,9 +199,7 @@ scala.tools.nsc.io.File(s"${class_name}.j").writeAll(output) } -import scala.sys.process._ - -def compile_run(class_name: String) : Unit = { +def compile_and_run(class_name: String) : Unit = { compile_to_file(class_name) (s"java -jar jvm/jasmin-2.4/jasmin.jar ${class_name}.j").!! println("Time: " + time_needed(2, (s"java ${class_name}/${class_name}").!)) @@ -194,12 +207,13 @@ // some examples of .fun files -//compile_file("fact") -//compile_run("defs") -//compile_run("fact") +//compile_to_file("fact") +//compile_and_run("fact") +//compile_and_run("defs") + def main(args: Array[String]) = - compile_run(args(0)) + compile_and_run(args(0)) } \ No newline at end of file