1
1
Fork 0
mirror of https://github.com/azur1s/bobbylisp.git synced 2024-10-16 02:37:40 -05:00

feat: slurp or file read to string

This commit is contained in:
Natapat Samutpong 2022-02-05 13:53:05 +07:00
parent a7a61acd6e
commit 3297545d4d
3 changed files with 19 additions and 2 deletions

View file

@ -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])?;

View file

@ -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())) },
}
}

3
example/quine.blsp Normal file
View file

@ -0,0 +1,3 @@
(fun main (do
(def file (slurp "quine.blsp"))
(print file)))