diff --git a/src/main/wacc/backend/writer.scala b/src/main/wacc/backend/writer.scala index 8789835..cae7110 100644 --- a/src/main/wacc/backend/writer.scala +++ b/src/main/wacc/backend/writer.scala @@ -13,15 +13,30 @@ import java.nio.file.Path object writer { import assemblyIR._ + // TODO: Judging from documentation it seems as though IO.blocking is the correct choice + // But needs checking + + /** Creates a resource safe BufferedWriter */ + private def bufferedWriter(outputPath: Path): Resource[IO, BufferedWriter] = + Resource.make { + IO.blocking(new BufferedWriter(new FileWriter(outputPath.toFile, StandardCharsets.UTF_8))) + } { writer => + IO.blocking(writer.close()) + .handleErrorWith(_ => IO.unit) // TODO: ensures writer is closed even if an error occurs + } + + /** Write line safely into a BufferedWriter */ + private def writeLines(writer: BufferedWriter, lines: Chain[AsmLine]): IO[Unit] = + IO.blocking { + lines.iterator.foreach { line => + writer.write(line.toString) + writer.newLine() + } + } + + /** Main function to write assembly to a file */ def writeTo(asmList: Chain[AsmLine], outputPath: Path)(using logger: Logger[IO]): IO[Unit] = - Resource - .fromAutoCloseable { - IO(BufferedWriter(FileWriter(outputPath.toFile, StandardCharsets.UTF_8))) - } - .use { writer => - IO { - asmList.iterator.foreach(line => writer.write(line.toString + "\n")) - writer.flush() // TODO: NECESSARY OR NOT? - } *> logger.info(s"Success: ${outputPath.toAbsolutePath}") - } + bufferedWriter(outputPath).use { writer => + writeLines(writer, asmList) *> logger.info(s"Success: ${outputPath.toAbsolutePath}") + } }