From 3297545d4de3e5387d0f42b21b0cfd16b2a66a3e Mon Sep 17 00:00:00 2001 From: Natapat Samutpong Date: Sat, 5 Feb 2022 13:53:05 +0700 Subject: [PATCH] feat: `slurp` or file read to string --- blspc/src/compiler/compile.rs | 6 +++++- blspc/src/vm/vm.rs | 12 +++++++++++- example/quine.blsp | 3 +++ 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 example/quine.blsp diff --git a/blspc/src/compiler/compile.rs b/blspc/src/compiler/compile.rs index 4eb946e..c4b0cb7 100644 --- a/blspc/src/compiler/compile.rs +++ b/blspc/src/compiler/compile.rs @@ -119,7 +119,11 @@ impl Compiler { result.append(&mut self.compile(args[0].clone())?); result.push(Instr::Call { function: "print".to_string() }); }, - "read" => { result.push(Instr::Call { function: "read".to_string() }); } + "read" => { result.push(Instr::Call { function: "read".to_string() }); }, + "slurp" => { + result.append(&mut self.compile(args[0].clone())?); + result.push(Instr::Call { function: "slurp".to_string() }); + }, "add" | "+" => { let mut lhs = self.compile_atom(&args[0])?; diff --git a/blspc/src/vm/vm.rs b/blspc/src/vm/vm.rs index d89f16b..e966539 100644 --- a/blspc/src/vm/vm.rs +++ b/blspc/src/vm/vm.rs @@ -1,4 +1,4 @@ -use std::{io, fmt::Display}; +use std::{io::{self, Read}, fmt::Display, fs::File}; use crate::vm::instr::{Instr::{self, *}, Type, Register}; @@ -8,6 +8,7 @@ pub enum Error { UnknownFunction(String), UnknownFunctionCall(String), InvalidAriphmeticOperation, + FileError(String), } impl Display for Error { @@ -18,6 +19,7 @@ impl Display for Error { Error::UnknownFunction(name) => write!(f, "Unknown function: {}", name), Error::UnknownFunctionCall(function) => write!(f, "Unknown function call: {}", function), Error::InvalidAriphmeticOperation => write!(f, "Invalid ariphmetic operation"), + Error::FileError(msg) => write!(f, "Could not open file: {}", msg), } } } @@ -217,6 +219,14 @@ impl VM { self.stack.push(input); Ok(()) }, + "slurp" => { + let file_name = self.stack.pop().unwrap().fmt(); + let mut result = String::new(); + match File::open(file_name).and_then(|mut f| f.read_to_string(&mut result)) { + Ok(_) => Ok(self.stack.push(Type::String(result))), + Err(e) => Err(Error::FileError(e.to_string())), + } + } _ => { dbg!(function); Err(Error::UnknownFunctionCall(function.to_string())) }, } } diff --git a/example/quine.blsp b/example/quine.blsp new file mode 100644 index 0000000..a0a6fd5 --- /dev/null +++ b/example/quine.blsp @@ -0,0 +1,3 @@ +(fun main (do + (def file (slurp "quine.blsp")) + (print file))) \ No newline at end of file