feat: File IO!
This commit is contained in:
parent
936f557536
commit
2d93c83b67
4 changed files with 60 additions and 23 deletions
21
src/env/core.rs
vendored
21
src/env/core.rs
vendored
|
@ -394,27 +394,6 @@ pub(super) fn core() -> HashMap<String, Node> {
|
|||
Ok(Node::Nil)
|
||||
}),
|
||||
),
|
||||
// IO
|
||||
(
|
||||
"print",
|
||||
Node::NativeFunc(|_env, args| {
|
||||
arg_count!(1, args.len());
|
||||
|
||||
print!("{}", args[0]);
|
||||
|
||||
Ok(Node::Void)
|
||||
}),
|
||||
),
|
||||
(
|
||||
"println",
|
||||
Node::NativeFunc(|_env, args| {
|
||||
arg_count!(1, args.len());
|
||||
|
||||
println!("{}", args[0]);
|
||||
|
||||
Ok(Node::Void)
|
||||
}),
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(k, v)| (k.to_string(), v))
|
||||
|
|
50
src/env/io.rs
vendored
Normal file
50
src/env/io.rs
vendored
Normal file
|
@ -0,0 +1,50 @@
|
|||
use std::borrow::Borrow;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::macros::arg_count;
|
||||
use crate::node::Node;
|
||||
|
||||
pub(super) fn io() -> HashMap<String, Node> {
|
||||
[
|
||||
// Stdout
|
||||
(
|
||||
"print",
|
||||
Node::NativeFunc(|_env, args| {
|
||||
arg_count!(1, args.len());
|
||||
|
||||
print!("{}", args[0]);
|
||||
|
||||
Ok(Node::Void)
|
||||
}),
|
||||
),
|
||||
(
|
||||
"println",
|
||||
Node::NativeFunc(|_env, args| {
|
||||
arg_count!(1, args.len());
|
||||
|
||||
println!("{}", args[0]);
|
||||
|
||||
Ok(Node::Void)
|
||||
}),
|
||||
),
|
||||
// File IO
|
||||
(
|
||||
"read-file",
|
||||
Node::NativeFunc(|_env, args| {
|
||||
arg_count!(1, args.len());
|
||||
|
||||
let val = args[0].borrow();
|
||||
if let Node::String(path) = val {
|
||||
let contents = std::fs::read_to_string(path)?;
|
||||
return Ok(Node::String(contents));
|
||||
}
|
||||
|
||||
Err(Error::ExpectedString)?
|
||||
}),
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(k, v)| (k.to_string(), v))
|
||||
.collect()
|
||||
}
|
10
src/env/mod.rs
vendored
10
src/env/mod.rs
vendored
|
@ -5,6 +5,7 @@ use std::rc::Rc;
|
|||
use crate::node::Node;
|
||||
|
||||
mod core;
|
||||
mod io;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Environment(Rc<RawEnvironment>);
|
||||
|
@ -17,10 +18,15 @@ pub struct RawEnvironment {
|
|||
|
||||
impl Environment {
|
||||
pub fn new() -> Environment {
|
||||
let current = RefCell::new(core::core());
|
||||
let mut env = HashMap::new();
|
||||
let core = core::core();
|
||||
let io = io::io();
|
||||
|
||||
env.extend(core);
|
||||
env.extend(io);
|
||||
|
||||
let env = RawEnvironment {
|
||||
current,
|
||||
current: RefCell::new(env),
|
||||
outer: None,
|
||||
};
|
||||
|
||||
|
|
|
@ -14,6 +14,8 @@ pub enum Error {
|
|||
ExpectedList,
|
||||
#[error("expected number")]
|
||||
ExpectedNumber,
|
||||
#[error("expected string")]
|
||||
ExpectedString,
|
||||
#[error("expected {0} arguments, got {1}")]
|
||||
MismatchedArgCount(usize, usize),
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue