diff -r b4f5714485e1 -r 30943d5491b6 progs/fun_parser.scala --- a/progs/fun_parser.scala Wed Oct 02 02:09:48 2019 +0100 +++ b/progs/fun_parser.scala Wed Oct 02 14:05:36 2019 +0100 @@ -1,10 +1,20 @@ -// A Small Compiler for a Simple Functional Language -// (includes a lexer and a parser) +// A parser for the Fun language +//================================ +// +// call with +// +// scala fun_parser.scala fact.tks +// +// scala fun_parser.scala defs.tks +// +// this will generate a .prs file that can be deserialised back +// into a list of declarations object Fun_Parser { import scala.language.implicitConversions import scala.language.reflectiveCalls +import scala.util._ import java.io._ abstract class Token extends Serializable @@ -162,28 +172,29 @@ // Reading tokens and Writing parse trees def serialise[T](fname: String, data: T) = { - val out = new ObjectOutputStream(new FileOutputStream(fname)) - out.writeObject(data) - out.close + import scala.util.Using + Using(new ObjectOutputStream(new FileOutputStream(fname))) { + out => out.writeObject(data) + } } -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 main(args: Array[String]) = { +def main(args: Array[String]) : Unit= { val fname = args(0) val pname = fname.stripSuffix(".tks") ++ ".prs" - val tks = deserialise[List[Token]](fname) + val tks = deserialise[List[Token]](fname).getOrElse(Nil) serialise(pname, Prog.parse_single(tks)) // testing whether read-back is working - //val ptree = deserialise[List[Decl]](pname) + //val ptree = deserialise[List[Decl]](pname).get //println(s"Reading back from ${pname}:\n${ptree.mkString("\n")}") } -} \ No newline at end of file +}