From 2ebad036127ad616714f38a61c9baaef4f00696c Mon Sep 17 00:00:00 2001 From: Altareos <8584797+Altareos@users.noreply.github.com> Date: Thu, 24 Feb 2022 16:11:58 +0100 Subject: [PATCH] full brainfuck --- sample/bf.pl.xml | 91 ++++++++++++++++++++++++++++++++++++++++++------ src/lib.rs | 46 ++++++++++++++++++++++++ src/main.rs | 2 +- 3 files changed, 127 insertions(+), 12 deletions(-) diff --git a/sample/bf.pl.xml b/sample/bf.pl.xml index 9c33d0e..6985ae6 100644 --- a/sample/bf.pl.xml +++ b/sample/bf.pl.xml @@ -3,8 +3,13 @@ - - + + + + + + + @@ -19,9 +24,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + @@ -134,10 +177,14 @@ - + - - + + + + + + @@ -150,7 +197,28 @@ - + + + + + + + + + + + + + + + + + + + + + + @@ -337,11 +405,7 @@ - - - - @@ -363,6 +427,11 @@ + diff --git a/src/lib.rs b/src/lib.rs index b9d3686..9999365 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -832,6 +832,10 @@ mod stl { String::from("array-length"), Value::StdFunction(array_length), ); + ctx.assign(String::from("to-ascii"), Value::StdFunction(to_ascii)); + ctx.assign(String::from("from-ascii"), Value::StdFunction(from_ascii)); + ctx.assign(String::from("get-args"), Value::StdFunction(get_args)); + } fn print(vals: Vec) -> Result, Box> { @@ -964,6 +968,48 @@ mod stl { Err("bad argument count in call to 'array-length'")? } } + + fn to_ascii(vals: Vec) -> Result, Box> { + if vals.len() == 1 { + if let Value::Integer(i) = &vals[0] { + if i <= &255 { + Ok(Some(Value::String(String::from_utf8(vec![*i as u8])?))) + } else { + Err("invalid integer in call to 'to-ascii'")? + } + } else { + Err("invalid argument in call to 'to-ascii'")? + } + } else { + Err("bad argument count in call to 'to-ascii'")? + } + } + + fn from_ascii(vals: Vec) -> Result, Box> { + if vals.len() == 1 { + if let Value::String(s) = &vals[0] { + if s.len() == 1 { + Ok(Some(Value::Integer(s.as_bytes()[0] as i64))) + } else { + Err("invalid string in call to 'from-ascii'")? + } + } else { + Err("invalid argument in call to 'from-ascii'")? + } + } else { + Err("bad argument count in call to 'from-ascii'")? + } + } + + fn get_args(vals: Vec) -> Result, Box> { + if vals.len() == 0 { + Ok(Some(Value::Array(Rc::new(RefCell::new( + std::env::args().skip(1).map(|arg| Value::String(arg)).collect() + ))))) + } else { + Err("bad argument count in call to 'get-args'")? + } + } } pub fn run(filename: &str) -> Result<(), Box> { diff --git a/src/main.rs b/src/main.rs index 84c3879..34480b3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,6 @@ use std::env; fn main() { let args: Vec = env::args().collect(); if let Err(e) = run(&args[1]) { - panic!("Error occurred: {}", e); + eprintln!("Error occurred: {}", e); } }