This commit is contained in:
Aidan Hahn 2022-01-16 22:02:40 -08:00
parent f805290a4b
commit be73b0b828
No known key found for this signature in database
GPG key ID: 327711E983899316
17 changed files with 588 additions and 675 deletions

View file

@ -15,14 +15,14 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::func::{FTable, Function, Args, Operation};
use crate::vars::{VTable};
use crate::segment::{Ctr, Ast, circuit, list_idx, list_append, new_ast};
use std::rc::Rc;
use crate::func::{Args, FTable, Function, Operation};
use crate::segment::{circuit, list_append, list_idx, new_ast, Ast, Ctr};
use crate::vars::VTable;
use std::cell::RefCell;
use std::rc::Rc;
pub fn get_append() -> Function {
return Function{
return Function {
name: String::from("append"),
loose_syms: false,
eval_lazy: false,
@ -40,16 +40,18 @@ pub fn get_append() -> Function {
list_append(c.clone(), arg.clone());
return true;
}) {
eprintln!("get_append circuit loop should not have returned false");
eprintln!(
"get_append circuit loop should not have returned false"
);
}
},
}
_ => {
eprintln!("get_append args somehow not in standard form");
}
}
return ptr;
},
}
_ => {
let n = new_ast(Ctr::None, Ctr::None);
if !circuit(a, &mut |arg: &Ctr| -> bool {
@ -62,7 +64,7 @@ pub fn get_append() -> Function {
return Ctr::Seg(n);
}
}
}
))
},
)),
};
}

View file

@ -15,15 +15,15 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use dirs::home_dir;
use relish::ast::{ast_to_string, eval, func_call, lex, new_ast, Ctr, FTable, VTable};
use relish::aux::configure;
use relish::stdlib::get_stdlib;
use rustyline::error::ReadlineError;
use rustyline::Editor;
use dirs::home_dir;
use std::rc::Rc;
use std::env;
use std::cell::RefCell;
use relish::ast::{VTable, FTable, Ctr, lex, eval, ast_to_string, new_ast, func_call};
use relish::aux::configure;
use relish::stdlib::{get_stdlib};
use std::env;
use std::rc::Rc;
fn main() {
let mut rl = Editor::<()>::new();
@ -52,12 +52,12 @@ fn main() {
match env::var("RELISH_CFG_FILE") {
Ok(s) => configure(s, vt.clone(), ft.clone()),
Err(_) => configure(cfg, vt.clone(), ft.clone())
Err(_) => configure(cfg, vt.clone(), ft.clone()),
}
match get_stdlib(vt.clone()) {
Ok(f) => ft = f,
Err(s) => println!("{}", s)
Err(s) => println!("{}", s),
}
loop {
@ -68,23 +68,26 @@ fn main() {
let t_ft_c_b = tmp_ft_clone.borrow();
let pfunc = t_ft_c_b.get("CFG_RELISH_PROMPT");
if let Some(fnc) = pfunc {
match func_call(fnc.clone(), new_ast(Ctr::None, Ctr::None), vt.clone(), ft.clone()) {
match func_call(
fnc.clone(),
new_ast(Ctr::None, Ctr::None),
vt.clone(),
ft.clone(),
) {
Err(s) => {
eprintln!("Couldnt generate prompt: {}", s);
readline = rl.readline("");
},
Ok(c) => {
match c {
Ctr::Symbol(s) => readline = rl.readline(&s.to_owned()),
Ctr::String(s) => readline = rl.readline(&s),
Ctr::Integer(i) => readline = rl.readline(&format!("{}", i)),
Ctr::Float(f) => readline = rl.readline(&format!("{}", f)),
Ctr::Bool(b) => readline = rl.readline(&format!("{}", b)),
Ctr::Seg(c) => readline = rl.readline(&ast_to_string(c.clone())),
Ctr::None => readline = rl.readline("")
}
}
Ok(c) => match c {
Ctr::Symbol(s) => readline = rl.readline(&s.to_owned()),
Ctr::String(s) => readline = rl.readline(&s),
Ctr::Integer(i) => readline = rl.readline(&format!("{}", i)),
Ctr::Float(f) => readline = rl.readline(&format!("{}", f)),
Ctr::Bool(b) => readline = rl.readline(&format!("{}", b)),
Ctr::Seg(c) => readline = rl.readline(&ast_to_string(c.clone())),
Ctr::None => readline = rl.readline(""),
},
}
} else {
readline = rl.readline("");
@ -103,40 +106,32 @@ fn main() {
}
match lex(l) {
Ok(a) => {
match eval(a.clone(), vt.clone(), ft.clone(), false) {
Ok(a) => {
match a {
Ctr::Symbol(s) => println!("{}", s),
Ctr::String(s) => println!("{}", s),
Ctr::Integer(i) => println!("{}", i),
Ctr::Float(f) => println!("{}", f),
Ctr::Bool(b) => println!("{}", b),
Ctr::Seg(c) => println!("{}", ast_to_string(c.clone())),
Ctr::None => ()
}
},
Err(s) => {
println!("{}", s);
}
Ok(a) => match eval(a.clone(), vt.clone(), ft.clone(), false) {
Ok(a) => match a {
Ctr::Symbol(s) => println!("{}", s),
Ctr::String(s) => println!("{}", s),
Ctr::Integer(i) => println!("{}", i),
Ctr::Float(f) => println!("{}", f),
Ctr::Bool(b) => println!("{}", b),
Ctr::Seg(c) => println!("{}", ast_to_string(c.clone())),
Ctr::None => (),
},
Err(s) => {
println!("{}", s);
}
},
Err(s) => {
println!("{}", s);
}
}
},
}
Err(ReadlineError::Interrupted) => {
break
},
Err(ReadlineError::Interrupted) => break,
Err(ReadlineError::Eof) => {
return
},
Err(ReadlineError::Eof) => return,
Err(err) => {
eprintln!("Prompt error: {:?}", err);
break
break;
}
}
}

View file

@ -15,16 +15,15 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::vars::{VTable, define};
use crate::func::{FTable, Args, Function, Operation, func_declare};
use crate::segment::{Ast, Ctr};
use crate::lex::lex;
use crate::eval::eval;
use crate::func::{func_declare, Args, FTable, Function, Operation};
use crate::lex::lex;
use crate::segment::{Ast, Ctr};
use crate::stl::get_stdlib;
use std::rc::Rc;
use crate::vars::{define, VTable};
use std::cell::RefCell;
use std::fs;
use std::rc::Rc;
fn prompt_default_callback(_: Ast, _: Rc<RefCell<VTable>>, _: Rc<RefCell<FTable>>) -> Ctr {
print!("λ ");
@ -32,52 +31,56 @@ fn prompt_default_callback(_: Ast, _: Rc<RefCell<VTable>>, _: Rc<RefCell<FTable>
}
pub fn configure(filename: String, vars: Rc<RefCell<VTable>>, mut funcs: Rc<RefCell<FTable>>) {
define(vars.clone(), String::from("CFG_RELISH_POSIX"), Rc::new(Ctr::String(String::from("0"))));
define(vars.clone(), String::from("CFG_RELISH_ENV"), Rc::new(Ctr::String(String::from("1"))));
define(
vars.clone(),
String::from("CFG_RELISH_POSIX"),
Rc::new(Ctr::String(String::from("0"))),
);
define(
vars.clone(),
String::from("CFG_RELISH_ENV"),
Rc::new(Ctr::String(String::from("1"))),
);
match get_stdlib(vars.clone()) {
Ok(f) => funcs = f,
Err(s) => println!("{}", s)
Err(s) => println!("{}", s),
}
func_declare(funcs.clone(), Rc::new(RefCell::new(Function{
name: String::from("CFG_RELISH_PROMPT"),
loose_syms: false,
eval_lazy: false,
args: Args::Lazy(0),
function: Operation::Internal(Box::new(prompt_default_callback))
})));
func_declare(
funcs.clone(),
Rc::new(RefCell::new(Function {
name: String::from("CFG_RELISH_PROMPT"),
loose_syms: false,
eval_lazy: false,
args: Args::Lazy(0),
function: Operation::Internal(Box::new(prompt_default_callback)),
})),
);
match fs::read_to_string(filename) {
Err(s) => {
eprintln!("Couldnt open configuration file: {}", s);
return
},
Ok(raw_config) => {
match lex(raw_config) {
Err(s) => {
println!("Error in configuration: {}", s);
return
},
Ok(config) => {
match eval(config, vars, funcs, false) {
Err(s) => {
println!("Error in applying configuration: {}", s);
return
},
Ok(ctr) => {
match ctr {
Ctr:: String(s) => println!("{}", s),
_ => ()
}
}
}
}
}
return;
}
Ok(raw_config) => match lex(raw_config) {
Err(s) => {
println!("Error in configuration: {}", s);
return;
}
Ok(config) => match eval(config, vars, funcs, false) {
Err(s) => {
println!("Error in applying configuration: {}", s);
return;
}
Ok(ctr) => match ctr {
Ctr::String(s) => println!("{}", s),
_ => (),
},
},
},
}
}

View file

@ -15,11 +15,11 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use std::rc::Rc;
use std::cell::RefCell;
use crate::segment::{Ast, Ctr, new_ast};
use crate::func::{FTable, func_call};
use crate::func::{func_call, FTable};
use crate::segment::{new_ast, Ast, Ctr};
use crate::vars::VTable;
use std::cell::RefCell;
use std::rc::Rc;
/* iterates over a syntax tree
* returns a NEW LIST of values
@ -29,7 +29,7 @@ pub fn eval(
ast: Ast,
vars: Rc<RefCell<VTable>>,
funcs: Rc<RefCell<FTable>>,
sym_loose: bool
sym_loose: bool,
) -> Result<Ctr, String> {
let mut car = ast.borrow().clone().car;
let mut cdr = ast.borrow().clone().cdr;
@ -49,19 +49,24 @@ pub fn eval(
match cdr.clone() {
Ctr::Seg(ast) => {
if let Some(func) = funcs.borrow().get(tok) {
return func_call(func.clone(), ast.clone(), vars.clone(), funcs.clone())
return func_call(func.clone(), ast.clone(), vars.clone(), funcs.clone());
} else if !sym_loose {
return Err(format!("Couldnt find definition of {}.", tok))
return Err(format!("Couldnt find definition of {}.", tok));
}
},
}
Ctr::None => {
if let Some(func) = funcs.borrow().get(tok) {
return func_call(func.clone(), new_ast(Ctr::None, Ctr::None), vars.clone(), funcs.clone())
return func_call(
func.clone(),
new_ast(Ctr::None, Ctr::None),
vars.clone(),
funcs.clone(),
);
} else if !sym_loose {
return Err(format!("Couldnt find definition of {}.", tok))
return Err(format!("Couldnt find definition of {}.", tok));
}
},
_ => return Err(format!("Arguments to function not a list!"))
}
_ => return Err(format!("Arguments to function not a list!")),
}
}
@ -72,9 +77,9 @@ pub fn eval(
Ctr::Seg(ref inner) => {
match eval(inner.clone(), vars.clone(), funcs.clone(), sym_loose) {
Ok(res) => (*iter).borrow_mut().car = res,
Err(e) => return Err(format!("Evaluation error: {}", e))
Err(e) => return Err(format!("Evaluation error: {}", e)),
}
},
}
// if SYMBOL: unwrap naively
Ctr::Symbol(ref tok) => {
@ -83,9 +88,9 @@ pub fn eval(
} else if sym_loose {
(*iter).borrow_mut().car = Ctr::Symbol(tok.to_string());
} else {
return Err(format!("Undefined variable: {}", tok))
return Err(format!("Undefined variable: {}", tok));
}
},
}
// if OTHER: clone and set
_ => {
@ -101,11 +106,11 @@ pub fn eval(
} else if sym_loose {
(*iter).borrow_mut().car = Ctr::Symbol(tok.to_string());
} else {
return Err(format!("Undefined variable: {}", tok))
return Err(format!("Undefined variable: {}", tok));
}
none = true;
},
}
// if LIST:
// - iter.cdr = new_ast(None, None)
@ -135,5 +140,5 @@ pub fn eval(
}
}
return Ok(Ctr::Seg(ret))
return Ok(Ctr::Seg(ret));
}

View file

@ -15,13 +15,13 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use std::rc::Rc;
use std::cell::RefCell;
use std::convert::TryInto;
use std::collections::HashMap;
use crate::segment::{Ctr, Type, circuit, list_len, list_idx, Ast};
use crate::vars::{VTable};
use crate::eval::eval;
use crate::segment::{circuit, list_idx, list_len, Ast, Ctr, Type};
use crate::vars::VTable;
use std::cell::RefCell;
use std::collections::HashMap;
use std::convert::TryInto;
use std::rc::Rc;
pub type FTable = HashMap<String, Rc<RefCell<Function>>>;
@ -34,15 +34,15 @@ pub struct ExternalOperation {
// TODO: Apply Memoization?
pub ast: Ast,
// list of argument string tokens
pub arg_syms: Vec<String>
pub arg_syms: Vec<String>,
}
/* A stored function may either be a pointer to a function
* or a syntax tree to eval with the arguments
*/
pub enum Operation {
Internal(Box<dyn Fn(Ast, Rc<RefCell<VTable>>, Rc<RefCell<FTable>>)->Ctr>),
External(ExternalOperation)
Internal(Box<dyn Fn(Ast, Rc<RefCell<VTable>>, Rc<RefCell<FTable>>) -> Ctr>),
External(ExternalOperation),
}
/* Function Args
@ -52,7 +52,7 @@ pub enum Operation {
pub enum Args {
// signed: -1 denotes infinite args
Lazy(i128),
Strict(Vec<Type>)
Strict(Vec<Type>),
}
// function which does not need args checked
@ -65,7 +65,7 @@ pub struct Function {
pub loose_syms: bool,
// dont evaluate args at all. leave that to the function
pub eval_lazy: bool
pub eval_lazy: bool,
}
/* call
@ -75,7 +75,7 @@ pub fn func_call(
function: Rc<RefCell<Function>>,
args: Ast,
vars: Rc<RefCell<VTable>>,
funcs: Rc<RefCell<FTable>>
funcs: Rc<RefCell<FTable>>,
) -> Result<Ctr, String> {
let called_func = function.borrow();
let mut n_args: Ast = args.clone();
@ -85,16 +85,15 @@ pub fn func_call(
if let Ctr::Seg(ast) = rc_seg {
n_args = ast
} else {
return Err("Panicking: eval returned not a list for function args.".to_string())
return Err("Panicking: eval returned not a list for function args.".to_string());
}
},
Err(s) => return Err(
format!(
}
Err(s) => {
return Err(format!(
"error evaluating args to {}: {}",
called_func.name,
s
)
)
called_func.name, s
))
}
}
}
@ -102,16 +101,12 @@ pub fn func_call(
Args::Lazy(num) => {
let called_arg_count = list_len(n_args.clone()) as i128;
if *num > -1 && (*num != called_arg_count) {
return Err(
format!(
"expected {} args in call to {}. Got {}.",
num,
called_func.name,
called_arg_count
)
)
return Err(format!(
"expected {} args in call to {}. Got {}.",
num, called_func.name, called_arg_count
));
}
},
}
Args::Strict(arg_types) => {
let mut idx: usize = 0;
@ -160,17 +155,13 @@ pub fn func_call(
}
match &called_func.function {
Operation::Internal(f) => {
return Ok(f(n_args, vars, funcs))
},
Operation::Internal(f) => return Ok(f(n_args, vars, funcs)),
Operation::External(f) => {
for n in 0..f.arg_syms.len() {
let iter_arg = list_idx(n_args.clone(), n as u128);
vars.borrow_mut().insert(
f.arg_syms[n].clone(),
Rc::new(iter_arg)
);
vars.borrow_mut()
.insert(f.arg_syms[n].clone(), Rc::new(iter_arg));
}
let mut result: Ctr;
@ -178,13 +169,11 @@ pub fn func_call(
loop {
if let Ctr::Seg(ast) = iterate.borrow().clone().car {
match eval(ast, vars.clone(), funcs.clone(), called_func.loose_syms) {
Ok(ctr) => {
match ctr {
Ctr::Seg(ast) => result = ast.borrow().clone().car,
_ => result = ctr
}
Ok(ctr) => match ctr {
Ctr::Seg(ast) => result = ast.borrow().clone().car,
_ => result = ctr,
},
Err(e) => return Err(e)
Err(e) => return Err(e),
}
} else {
panic!("function body not in standard form!")
@ -193,22 +182,19 @@ pub fn func_call(
match iterate.clone().borrow().clone().cdr {
Ctr::Seg(next) => iterate = next.clone(),
Ctr::None => break,
_ => panic!("function body not in standard form!")
_ => panic!("function body not in standard form!"),
}
}
for n in 0..f.arg_syms.len() {
vars.borrow_mut().remove(&f.arg_syms[n].clone());
}
return Ok(result)
return Ok(result);
}
}
}
pub fn func_declare(
ft: Rc<RefCell<FTable>>,
f: Rc<RefCell<Function>>
) -> Option<String> {
pub fn func_declare(ft: Rc<RefCell<FTable>>, f: Rc<RefCell<Function>>) -> Option<String> {
let func = f.borrow();
let name = func.name.clone();
if let Operation::External(fun) = &func.function {
@ -216,14 +202,11 @@ pub fn func_declare(
if fun.arg_syms.len() != i.try_into().unwrap() {
return Some(
"external function must have lazy args equal to declared arg_syms length"
.to_string()
.to_string(),
);
}
} else {
return Some(
"external function must have lazy args"
.to_string()
);
return Some("external function must have lazy args".to_string());
}
}

View file

@ -15,7 +15,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::segment::{Ctr, Ast, list_append, new_ast};
use crate::segment::{list_append, new_ast, Ast, Ctr};
const UNMATCHED_STR_DELIM: &str = "Unmatched string delimiter in input";
const UNMATCHED_LIST_DELIM: &str = "Unmatched list delimiter in input";
@ -34,8 +34,8 @@ pub fn lex(document: String) -> Result<Ast, String> {
// To represent the multiple passable outcomes
return match tree {
Err(e) => Err(format!("Problem lexing document: {:?}", e)),
Ok(t) => Ok(t)
}
Ok(t) => Ok(t),
};
}
/* The logic used in lex
@ -113,27 +113,27 @@ fn process(document: String) -> Result<Ast, String> {
'(' => {
if is_str {
token.push(c);
continue
continue;
}
if token != "" {
if token != "" {
return Err("list started in middle of another token".to_string());
}
ref_stack.push(new_ast(Ctr::None, Ctr::None));
delim_stack.push(')');
},
}
// begin parsing a string
'"' | '\'' | '`' => {
is_str = true;
delim_stack.push(c);
},
}
// eat the whole line
'#' => {
ign = true;
delim_stack.push('\n');
},
}
// escape next char
'\\' => {
delim_stack.push('*');
@ -200,7 +200,6 @@ fn process(document: String) -> Result<Ast, String> {
return Err(UNMATCHED_LIST_DELIM.to_string());
}
/* Returns true if token
* - is all alphanumeric except dash and underscore
*
@ -210,9 +209,9 @@ fn tok_is_symbol(token: &String) -> Option<String> {
let tok = token.as_str();
for t in tok.chars() {
if !t.is_alphabetic() && !t.is_digit(10) && !(t == '-') && !(t == '_') {
return None
return None;
}
}
return Some(String::from(tok))
return Some(String::from(tok));
}

View file

@ -15,31 +15,31 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
mod segment;
mod lex;
mod func;
mod eval;
mod vars;
mod stl;
mod str;
mod append;
mod config;
mod eval;
mod func;
mod lex;
mod segment;
mod stl;
mod str;
mod vars;
pub mod ast {
pub use crate::segment::{Seg, Ctr, ast_to_string, Type, Ast, new_ast};
pub use crate::lex::lex;
pub use crate::func::{Function, Operation, FTable, Args,
ExternalOperation, func_declare, func_call};
pub use crate::vars::{VTable, define};
pub use crate::eval::eval;
pub use crate::func::{
func_call, func_declare, Args, ExternalOperation, FTable, Function, Operation,
};
pub use crate::lex::lex;
pub use crate::segment::{ast_to_string, new_ast, Ast, Ctr, Seg, Type};
pub use crate::vars::{define, VTable};
}
pub mod stdlib {
pub use crate::stl::{get_stdlib};
pub use crate::str::{get_echo, get_concat};
pub use crate::append::{get_append};
pub use crate::vars::{get_export};
pub use crate::append::get_append;
pub use crate::stl::get_stdlib;
pub use crate::str::{get_concat, get_echo};
pub use crate::vars::get_export;
}
pub mod aux {

View file

@ -15,15 +15,14 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use std::rc::Rc;
use std::cell::RefCell;
use std::rc::Rc;
// Recursive data type for a tree of Segments
pub type Ast = Rc<RefCell<Seg>>;
// Container
#[derive(Clone)]
#[derive(Debug)]
#[derive(Clone, Debug)]
pub enum Ctr {
Symbol(String),
String(String),
@ -31,12 +30,11 @@ pub enum Ctr {
Float(f64),
Bool(bool),
Seg(Ast),
None
None,
}
// Type of Container
#[derive(PartialEq)]
#[derive(Clone)]
#[derive(PartialEq, Clone)]
pub enum Type {
Symbol,
String,
@ -44,7 +42,7 @@ pub enum Type {
Float,
Bool,
Seg,
None
None,
}
/* Segment
@ -53,8 +51,7 @@ pub enum Type {
* I was going to call it Cell and then I learned about
* how important RefCells were in Rust
*/
#[derive(Clone)]
#[derive(Debug)]
#[derive(Clone, Debug)]
pub struct Seg {
/* "Contents of Address Register"
* Historical way of referring to the first value in a cell.
@ -64,7 +61,7 @@ pub struct Seg {
/* "Contents of Decrement Register"
* Historical way of referring to the second value in a cell.
*/
pub cdr: Ctr
pub cdr: Ctr,
}
impl Ctr {
@ -76,7 +73,7 @@ impl Ctr {
Ctr::Float(_s) => Type::Float,
Ctr::Bool(_s) => Type::Bool,
Ctr::Seg(_s) => Type::Seg,
Ctr::None => Type::None
Ctr::None => Type::None,
}
}
}
@ -91,7 +88,7 @@ impl Type {
Type::Float => ret = "float",
Type::Bool => ret = "bool",
Type::Seg => ret = "segment",
Type::None => ret = "none"
Type::None => ret = "none",
}
ret.to_owned()
@ -105,17 +102,17 @@ pub fn ast_as_string(c: Ast, with_parens: bool) -> String {
let mut prn_space = true;
let seg = c.borrow();
match &seg.car {
Ctr::Symbol(s) => string.push_str(&s),
Ctr::String(s) => {
Ctr::Symbol(s) => string.push_str(&s),
Ctr::String(s) => {
string.push('\'');
string.push_str(&s);
string.push('\'');
},
}
Ctr::Integer(i) => string = string + &i.to_string(),
Ctr::Float(f) => string = string + &f.to_string(),
Ctr::Bool(b) => string = string + &b.to_string(),
Ctr::Seg(c) => string.push_str(ast_as_string(c.clone(), true).as_str()),
Ctr::None => prn_space = false
Ctr::Float(f) => string = string + &f.to_string(),
Ctr::Bool(b) => string = string + &b.to_string(),
Ctr::Seg(c) => string.push_str(ast_as_string(c.clone(), true).as_str()),
Ctr::None => prn_space = false,
}
if prn_space {
@ -123,17 +120,17 @@ pub fn ast_as_string(c: Ast, with_parens: bool) -> String {
}
match &seg.cdr {
Ctr::Symbol(s) => string.push_str(&s),
Ctr::String(s) => {
Ctr::Symbol(s) => string.push_str(&s),
Ctr::String(s) => {
string.push('\'');
string.push_str(&s);
string.push('\'');
},
}
Ctr::Integer(i) => string = string + &i.to_string(),
Ctr::Float(f) => string = string + &f.to_string(),
Ctr::Bool(b) => string = string + &b.to_string(),
Ctr::Seg(c) => string.push_str(ast_as_string(c.clone(), false).as_str()),
Ctr::None => {
Ctr::Float(f) => string = string + &f.to_string(),
Ctr::Bool(b) => string = string + &b.to_string(),
Ctr::Seg(c) => string.push_str(ast_as_string(c.clone(), false).as_str()),
Ctr::None => {
if prn_space {
string.pop();
}
@ -147,7 +144,7 @@ pub fn ast_as_string(c: Ast, with_parens: bool) -> String {
extra.push(')');
string = extra
}
return string
return string;
}
pub fn ast_to_string(c: Ast) -> String {
@ -162,10 +159,7 @@ pub fn ast_to_string(c: Ast) -> String {
/* Initializes a new ast node with segment car and cdr passed in
*/
pub fn new_ast(car: Ctr, cdr: Ctr) -> Ast {
Rc::new(RefCell::new(Seg{
car: car,
cdr: cdr
}))
Rc::new(RefCell::new(Seg { car: car, cdr: cdr }))
}
/* applies a function across a list in standard form
@ -173,13 +167,13 @@ pub fn new_ast(car: Ctr, cdr: Ctr) -> Ast {
* short circuits on the first false returned.
* also returns false on a non standard form list
*/
pub fn circuit<F: FnMut(&Ctr)-> bool>(tree: Ast, func: &mut F) -> bool{
pub fn circuit<F: FnMut(&Ctr) -> bool>(tree: Ast, func: &mut F) -> bool {
let inner = tree.borrow();
if func(&inner.car) {
match &inner.cdr {
Ctr::None => true,
Ctr::Seg(c) => circuit(c.clone(), func),
_ => false
_ => false,
}
} else {
false
@ -192,7 +186,7 @@ pub fn circuit<F: FnMut(&Ctr)-> bool>(tree: Ast, func: &mut F) -> bool{
pub fn list_len(tree: Ast) -> u128 {
match &tree.borrow().cdr {
Ctr::Seg(c) => list_len(c.clone()) + 1,
_ => 1
_ => 1,
}
}
@ -216,9 +210,7 @@ pub fn list_idx(tree: Ast, idx: u128) -> Ctr {
} else {
match inner.car {
Ctr::None => Ctr::None,
_ => {
inner.car.clone()
}
_ => inner.car.clone(),
}
}
}
@ -231,17 +223,15 @@ pub fn list_append(tree: Ast, obj: Ctr) {
match &inner.car {
Ctr::None => {
inner.car = obj;
},
_ => {
match &inner.cdr {
Ctr::None => {
inner.cdr = Ctr::Seg(new_ast(obj, Ctr::None));
},
Ctr::Seg(tr) => {
list_append(tr.clone(), obj);
},
_ => ()
}
}
_ => match &inner.cdr {
Ctr::None => {
inner.cdr = Ctr::Seg(new_ast(obj, Ctr::None));
}
Ctr::Seg(tr) => {
list_append(tr.clone(), obj);
}
_ => (),
},
}
}

View file

@ -15,24 +15,24 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::segment::{Ctr};
use crate::str::{get_echo, get_concat};
use crate::append::get_append;
use crate::func::{FTable, func_declare};
use crate::vars::{VTable, get_export};
use std::rc::Rc;
use crate::func::{func_declare, FTable};
use crate::segment::Ctr;
use crate::str::{get_concat, get_echo};
use crate::vars::{get_export, VTable};
use std::cell::RefCell;
use std::rc::Rc;
pub fn get_stdlib(conf: Rc<RefCell<VTable>>) -> Result<Rc<RefCell<FTable>>, String> {
let ft = Rc::new(RefCell::new(FTable::new()));
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(get_echo()))) {
return Err(s)
return Err(s);
}
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(get_append()))) {
return Err(s)
return Err(s);
}
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(get_concat()))) {
return Err(s)
return Err(s);
}
let mut cfg_env = true;
@ -40,22 +40,18 @@ pub fn get_stdlib(conf: Rc<RefCell<VTable>>) -> Result<Rc<RefCell<FTable>>, Stri
None => {
println!("CFG_RELISH_ENV not defined. defaulting to ON.")
}
Some(ctr) => {
match (**ctr).clone() {
Ctr::String(ref s) => {
cfg_env = s.eq("0")
}
_ => {
println!("Invalid value for CFG_RELISH_ENV. must be a string (0 or 1).");
println!("Defaulting CFG_RELISH_ENV to ON");
}
Some(ctr) => match (**ctr).clone() {
Ctr::String(ref s) => cfg_env = s.eq("0"),
_ => {
println!("Invalid value for CFG_RELISH_ENV. must be a string (0 or 1).");
println!("Defaulting CFG_RELISH_ENV to ON");
}
}
},
}
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(get_export(cfg_env)))) {
return Err(s)
return Err(s);
}
return Ok(ft)
return Ok(ft);
}

View file

@ -15,16 +15,16 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::func::{FTable, Function, Args, Operation};
use crate::vars::{VTable};
use crate::segment::{Ctr, Ast, circuit, ast_as_string};
use std::rc::Rc;
use crate::func::{Args, FTable, Function, Operation};
use crate::segment::{ast_as_string, circuit, Ast, Ctr};
use crate::vars::VTable;
use std::cell::RefCell;
use std::rc::Rc;
// Current primitive is to use a get_NNNNN function defined for each library function which returns a not-previously-owned
// copy of the Function struct.
pub fn get_echo() -> Function {
return Function{
return Function {
name: String::from("echo"),
loose_syms: false,
eval_lazy: false,
@ -35,13 +35,13 @@ pub fn get_echo() -> Function {
if !circuit(a, &mut |arg: &Ctr| {
match arg {
// should be a thing here
Ctr::Symbol(_) => return false,
Ctr::String(s) => string.push_str(&s),
Ctr::Symbol(_) => return false,
Ctr::String(s) => string.push_str(&s),
Ctr::Integer(i) => string.push_str(&i.to_string()),
Ctr::Float(f) => string.push_str(&f.to_string()),
Ctr::Bool(b) => string.push_str(&b.to_string()),
Ctr::Seg(c) => string.push_str(ast_as_string(c.clone(), true).as_str()),
Ctr::None => ()
Ctr::Float(f) => string.push_str(&f.to_string()),
Ctr::Bool(b) => string.push_str(&b.to_string()),
Ctr::Seg(c) => string.push_str(ast_as_string(c.clone(), true).as_str()),
Ctr::None => (),
}
println!("{}", string);
return true;
@ -49,13 +49,13 @@ pub fn get_echo() -> Function {
eprintln!("circuit loop in echo should not have returned false")
}
return Ctr::None;
}
))
},
)),
};
}
pub fn get_concat() -> Function {
return Function{
return Function {
name: String::from("concat"),
loose_syms: false,
eval_lazy: false,
@ -66,20 +66,20 @@ pub fn get_concat() -> Function {
if !circuit(a, &mut |arg: &Ctr| {
match arg {
// should be a thing here
Ctr::Symbol(_) => return false,
Ctr::String(s) => string.push_str(&s),
Ctr::Symbol(_) => return false,
Ctr::String(s) => string.push_str(&s),
Ctr::Integer(i) => string.push_str(&i.to_string()),
Ctr::Float(f) => string.push_str(&f.to_string()),
Ctr::Bool(b) => string.push_str(&b.to_string()),
Ctr::Seg(c) => string.push_str(ast_as_string(c.clone(), true).as_str()),
Ctr::None => ()
Ctr::Float(f) => string.push_str(&f.to_string()),
Ctr::Bool(b) => string.push_str(&b.to_string()),
Ctr::Seg(c) => string.push_str(ast_as_string(c.clone(), true).as_str()),
Ctr::None => (),
}
return true;
}) {
eprintln!("circuit loop in concat should not have returned false")
}
return Ctr::String(string);
}
))
},
)),
};
}

View file

@ -15,13 +15,13 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::eval::eval;
use crate::func::{Args, FTable, Function, Operation};
use crate::segment::{ast_to_string, Ast, Ctr};
use std::cell::RefCell;
use std::rc::Rc;
use std::collections::HashMap;
use std::env;
use crate::segment::{Ctr, Ast, ast_to_string};
use crate::eval::eval;
use crate::func::{Function, Operation, Args, FTable};
use std::rc::Rc;
/* Mapping between a string token and a tree of Segments
* The string token can be found in any Ctr::Symbol value
* it is expected that the trees stored are already evaluated
@ -29,11 +29,7 @@ use crate::func::{Function, Operation, Args, FTable};
pub type VTable = HashMap<String, Rc<Ctr>>;
// WARNING: make sure var_tree is properly evaluated before storing
pub fn define(
vt: Rc<RefCell<VTable>>,
identifier: String,
var_tree: Rc<Ctr>
) {
pub fn define(vt: Rc<RefCell<VTable>>, identifier: String, var_tree: Rc<Ctr>) {
if let Some(rc_segment) = vt.borrow_mut().insert(identifier, var_tree) {
drop(rc_segment);
}
@ -43,58 +39,58 @@ pub fn get_export(env_cfg: bool) -> Function {
// This is the most hilarious way to work around the lifetime of env_cfg
// TODO: figure out the RUSTEY way of doing this
if env_cfg {
return Function{
return Function {
name: String::from("export"),
loose_syms: true,
eval_lazy: true,
args: Args::Lazy(2),
function: Operation::Internal(Box::new(|a: Ast, b: Rc<RefCell<VTable>>, c: Rc<RefCell<FTable>>| -> Ctr {
export_callback(true, a, b, c)
})),
function: Operation::Internal(Box::new(
|a: Ast, b: Rc<RefCell<VTable>>, c: Rc<RefCell<FTable>>| -> Ctr {
export_callback(true, a, b, c)
},
)),
};
} else {
return Function{
return Function {
name: String::from("export"),
loose_syms: true,
eval_lazy: true,
args: Args::Lazy(2),
function: Operation::Internal(Box::new(|a: Ast, b: Rc<RefCell<VTable>>, c: Rc<RefCell<FTable>>| -> Ctr {
export_callback(false, a, b, c)
})),
function: Operation::Internal(Box::new(
|a: Ast, b: Rc<RefCell<VTable>>, c: Rc<RefCell<FTable>>| -> Ctr {
export_callback(false, a, b, c)
},
)),
};
}
}
fn export_callback(env_cfg: bool, a: Ast, b: Rc<RefCell<VTable>>, c: Rc<RefCell<FTable>>) -> Ctr{
fn export_callback(env_cfg: bool, a: Ast, b: Rc<RefCell<VTable>>, c: Rc<RefCell<FTable>>) -> Ctr {
let inner = a.borrow_mut();
match &inner.car {
Ctr::Symbol(identifier) => {
match &inner.cdr {
Ctr::Seg(tree) => {
match eval(tree.clone(), b.clone(), c.clone(), false) {
Ok(seg) => {
match seg {
Ctr::Seg(val) => {
define(b, identifier.to_string(), Rc::new(val.borrow().clone().car));
if env_cfg {
match val.borrow().clone().car {
Ctr::Symbol(s) => env::set_var(identifier, s),
Ctr::String(s) => env::set_var(identifier, s),
Ctr::Integer(i) => env::set_var(identifier, format!("{}", i)),
Ctr::Float(f) => env::set_var(identifier, format!("{}", f)),
Ctr::Bool(b) => env::set_var(identifier, format!("{}", b)),
Ctr::Seg(c) => env::set_var(identifier, ast_to_string(c)),
Ctr::None => ()
}
}
},
_ => eprintln!("impossible args to export")
Ctr::Seg(tree) => match eval(tree.clone(), b.clone(), c.clone(), false) {
Ok(seg) => match seg {
Ctr::Seg(val) => {
define(b, identifier.to_string(), Rc::new(val.borrow().clone().car));
if env_cfg {
match val.borrow().clone().car {
Ctr::Symbol(s) => env::set_var(identifier, s),
Ctr::String(s) => env::set_var(identifier, s),
Ctr::Integer(i) => env::set_var(identifier, format!("{}", i)),
Ctr::Float(f) => env::set_var(identifier, format!("{}", f)),
Ctr::Bool(b) => env::set_var(identifier, format!("{}", b)),
Ctr::Seg(c) => env::set_var(identifier, ast_to_string(c)),
Ctr::None => (),
}
}
},
}
Err(e) => eprintln!("couldnt eval symbol: {}", e)
}
_ => eprintln!("impossible args to export"),
},
Err(e) => eprintln!("couldnt eval symbol: {}", e),
},
Ctr::None => {
@ -102,13 +98,13 @@ fn export_callback(env_cfg: bool, a: Ast, b: Rc<RefCell<VTable>>, c: Rc<RefCell<
if env_cfg {
// TODO: unset variable
}
},
}
_ => eprintln!("args not in standard form")
_ => eprintln!("args not in standard form"),
}
},
}
_ => eprintln!("first argument to export must be a symbol")
_ => eprintln!("first argument to export must be a symbol"),
}
return Ctr::None;