implement basic control flow, error handling from functions, many tests

Signed-off-by: Ava Hahn <ava@aidanis.online>
This commit is contained in:
Ava Hahn 2023-02-27 22:53:54 -08:00
parent ae365ad63c
commit 09e3546ba6
Signed by untrusted user who does not match committer: affine
GPG key ID: 3A4645B8CF806069
14 changed files with 315 additions and 488 deletions

View file

@ -1,147 +0,0 @@
/* relish: versatile lisp shell
* Copyright (C) 2021 Aidan Hahn
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* 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 rustyline::error::ReadlineError;
use rustyline::Editor;
use std::cell::RefCell;
use std::env;
use std::rc::Rc;
fn main() {
let mut rl = Editor::<()>::new();
const HIST_FILE: &str = "/.relish_hist";
const CONFIG_FILE_DEFAULT: &str = "/.relishrc";
let mut hist: String = "".to_owned();
let mut cfg: String = "".to_owned();
if let Some(home) = home_dir() {
if let Some(h) = home.to_str() {
hist = h.to_owned() + HIST_FILE;
cfg = h.to_owned() + CONFIG_FILE_DEFAULT;
}
}
if hist != "" {
// ignore result. it loads or it doesnt.
let _ = rl.load_history(&hist);
}
let vt = Rc::new(RefCell::new(VTable::new()));
let conf_file;
let ft;
match env::var("RELISH_CFG_FILE") {
Ok(s) => {
conf_file = s
},
Err(e) => {
eprintln!("{}", e);
conf_file = cfg;
},
}
match configure(conf_file, vt.clone()) {
Ok(f) => ft = f,
Err(e) => {
ft = Rc::new(RefCell::new(FTable::new()));
eprintln!("{}", e);
},
}
loop {
let readline: Result<String, ReadlineError>;
// Rust is pain
let tmp_ft_clone = ft.clone();
// this is not okay
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(),
) {
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(""),
},
}
} else {
readline = rl.readline("");
}
match readline {
Ok(line) => {
rl.add_history_entry(line.as_str());
let mut l = line.as_str().to_owned();
if !l.starts_with("(") {
l = "(".to_owned() + &l;
}
if !l.ends_with(")") {
l = l + ")";
}
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);
}
},
Err(s) => {
println!("{}", s);
}
}
}
Err(ReadlineError::Interrupted) => break,
Err(ReadlineError::Eof) => return,
Err(err) => {
eprintln!("Prompt error: {:?}", err);
break;
}
}
}
if hist != "" {
rl.save_history(&hist).unwrap();
}
}

View file

@ -1,40 +0,0 @@
/* relish: versatile lisp shell
* Copyright (C) 2021 Aidan Hahn
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::append::get_append;
use crate::func::{func_declare, FTable, Ast};
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_if() -> Function {
return Function {
name: String::from("if"),
loose_syms: false,
eval_lazy: true,
args: Args::Lazy(-1),
function: Operation::Internal(
Box::new(|args: Ast, vars: Rc<RefCell<VTable>>, funcs: Rc<RefCell<FTable>>| -> Ctr {
// Either 2 long or 3 long.
// arg 1 must eval to a bool
// then eval arg 2 or 3
})
),
};
}

View file

@ -15,16 +15,13 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*mod append;
mod config;
*/
//mod config;
mod eval;
mod lex;
mod segment;
mod sym;
mod stl;
/*mod stl;
mod str;*/
pub mod ast {
pub use crate::eval::eval;
@ -36,12 +33,9 @@ pub mod ast {
};
}
/*pub mod stdlib {
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 stdlib {
pub use crate::stl::{static_stdlib, dynamic_stdlib};
}
/*pub mod aux {
pub use crate::config::configure;

View file

@ -21,35 +21,56 @@ use crate::sym::{SymTable, Symbol, ValueType, Args, UserFn};
use std::env;
use std::rc::Rc;
fn store_stdlib(env: bool, syms: &mut SymTable) -> Result<(), String> {
syms.insert("def".to_string(), Symbol {
name: String::from("export"),
args: Args::Lazy(2),
conditional_branches: false,
value: ValueType::Internal(Rc::new( move |ast: &Seg, syms: &mut SymTable| -> Ctr {
_store_callback(ast, syms, env)
},
)),
});
pub mod control;
pub mod append;
//pub mod str;
/// static_stdlib
/// inserts all stdlib functions that can be inserted without
/// any kind of further configuration data into a symtable
pub fn static_stdlib(syms: &mut SymTable) -> Result<(), String> {
syms.insert("append".to_string(), Symbol {
name: String::from("append"),
args: Args::Infinite,
conditional_branches: false,
value: ValueType::Internal(Rc::new(_append_callback)),
value: ValueType::Internal(Rc::new(append::append_callback)),
});
syms.insert("expand".to_string(), Symbol {
name: String::from("expand"),
args: Args::Strict(vec![Type::Seg]),
conditional_branches: false,
value: ValueType::Internal(Rc::new(append::expand_callback)),
});
syms.insert("if".to_string(), Symbol {
name: String::from("if"),
args: Args::Lazy(3),
conditional_branches: true,
value: ValueType::Internal(Rc::new(control::if_callback)),
});
Ok(())
}
/// dynamic_stdlib
/// takes configuration data and uses it to insert dynamic
/// callbacks with configuration into a symtable
pub fn dynamic_stdlib(env: bool, syms: &mut SymTable) -> Result<(), String> {
syms.insert("def".to_string(), Symbol {
name: String::from("export"),
args: Args::Lazy(2),
conditional_branches: false,
value: ValueType::Internal(Rc::new( move |ast: &Seg, syms: &mut SymTable| -> Result<Ctr, String> {
_store_callback(ast, syms, env)
},
)),
});
fn _append_callback (_ast: &Seg, _syms: &mut SymTable) -> Ctr {
// if car is a list, append cdr
// otherwise create a list out of all arguments
todo!()
Ok(())
}
fn _store_callback (ast: &Seg, syms: &mut SymTable, env_cfg: bool) -> Ctr {
fn _store_callback (ast: &Seg, syms: &mut SymTable, env_cfg: bool) -> Result<Ctr, String> {
let is_var = ast.len() == 2;
if let Ctr::Symbol(ref identifier) = *ast.car {
match &*ast.cdr {
@ -65,9 +86,9 @@ fn _store_callback (ast: &Seg, syms: &mut SymTable, env_cfg: bool) -> Ctr {
env::set_var(identifier.clone(), val.car.to_string());
}
} else {
eprintln!("impossible args to export")
return Err("impossible args to export".to_string());
},
Err(e) => eprintln!("couldnt eval symbol: {}", e),
Err(e) => return Err(format!("couldnt eval symbol: {}", e)),
},
Ctr::Seg(data_tree) if !is_var => {
if let Ctr::Seg(ref args) = *data_tree.car {
@ -80,8 +101,7 @@ fn _store_callback (ast: &Seg, syms: &mut SymTable, env_cfg: bool) -> Ctr {
false
}
}) {
eprintln!("all arguments defined for function must be of type symbol");
return Ctr::None;
return Err("all arguments defined for function must be of type symbol".to_string());
};
if let Ctr::Seg(ref bodies) = *data_tree.cdr {
@ -98,12 +118,10 @@ fn _store_callback (ast: &Seg, syms: &mut SymTable, env_cfg: bool) -> Ctr {
conditional_branches: false,
});
} else {
eprintln!("expected one or more function bodies in function definition");
return Ctr::None;
return Err("expected one or more function bodies in function definition".to_string());
}
} else {
eprintln!("expected list of arguments in function definition");
return Ctr::None;
return Err("expected list of arguments in function definition".to_string());
}
}
Ctr::None => {
@ -112,11 +130,11 @@ fn _store_callback (ast: &Seg, syms: &mut SymTable, env_cfg: bool) -> Ctr {
env::remove_var(identifier);
}
},
_ => eprintln!("args not in standard form"),
_ => return Err("args not in standard form".to_string()),
}
} else {
eprintln!("first argument to export must be a symbol");
return Err("first argument to export must be a symbol".to_string());
}
Ctr::None
Ok(Ctr::None)
}

52
src/stl/append.rs Normal file
View file

@ -0,0 +1,52 @@
/* Copyright (C) 2021 Aidan Hahn
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::segment::{Ctr, Seg};
use crate::sym::{SymTable};
// Some essential operations below
pub fn append_callback (ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, String> {
// if car is a list, append cdr
// otherwise create a list out of all arguments
if let Ctr::Seg(ref s) = *ast.car {
let mut temp = s.clone();
temp.append(ast.cdr.clone());
Ok(Ctr::Seg(temp))
} else {
let mut temp = Seg::new();
let mut car_iter = &ast.car;
let mut cdr_iter = &ast.cdr;
loop {
temp.append(car_iter.clone());
if let Ctr::Seg(ref s) = **cdr_iter {
car_iter = &s.car;
cdr_iter = &s.cdr;
} else {
break;
}
}
Ok(Ctr::Seg(temp))
}
}
pub fn expand_callback (ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, String> {
if let Ctr::Seg(_) = *ast.car {
Ok(*ast.car.clone())
} else {
Err("non list passed to expand!".to_string())
}
}

62
src/stl/control.rs Normal file
View file

@ -0,0 +1,62 @@
/* relish: versatile lisp shell
* Copyright (C) 2021 Aidan Hahn
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::segment::{Ctr, Seg};
use crate::eval::eval;
use crate::sym::SymTable;
pub fn if_callback (ast: &Seg, syms: &mut SymTable) -> Result<Ctr, String> {
if let Ctr::Seg(ref cond_form) = *ast.car {
if let Ctr::Bool(cond) = *eval(cond_form, syms)? {
if let Ctr::Seg(ref first_form) = *ast.cdr {
if cond {
match *first_form.car {
Ctr::Seg(ref first_arg) => Ok(*eval(first_arg, syms)?),
_ => Ok(*eval(&Seg::from_mono(first_form.car.clone()), syms)?),
}
} else {
if let Ctr::Seg(ref second_form) = *first_form.cdr {
match *second_form.car {
Ctr::Seg(ref second_arg) => Ok(*eval(second_arg, syms)?),
_ => Ok(*eval(&Seg::from_mono(second_form.car.clone()), syms)?),
}
} else {
Err("impossible condition: args not in standard form".to_string())
}
}
} else {
Err("impossible condition: not 3 args to if".to_string())
}
} else {
Err("first argument to if must evaluate to be a boolean".to_string())
}
} else {
Err("impossible condition: not 3 args to if".to_string())
}
}
fn let_callback (_ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, String> {
todo!()
}
fn while_callback (_ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, String> {
todo!()
}
fn map_callback (_ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, String> {
todo!()
}

View file

@ -14,7 +14,7 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
use crate::func::{Args, FTable, Function, Operation};
use crate::segment::{ast_as_string, circuit, Ast, Ctr};
use crate::vars::VTable;
@ -83,3 +83,4 @@ pub fn get_concat() -> Function {
)),
};
}
*/

View file

@ -39,7 +39,7 @@ pub struct UserFn {
*/
#[derive(Clone)]
pub enum ValueType {
Internal(Rc<dyn Fn(&Seg, &mut SymTable) -> Ctr>),
Internal(Rc<dyn Fn(&Seg, &mut SymTable) -> Result<Ctr, String>>),
FuncForm(UserFn),
VarForm(Box<Ctr>)
}
@ -237,7 +237,7 @@ impl Symbol {
match &self.value {
ValueType::VarForm(ref f) => Ok(Box::new(*f.clone())),
ValueType::Internal(ref f) => Ok(Box::new(f(evaluated_args, syms))),
ValueType::Internal(ref f) => Ok(Box::new(f(evaluated_args, syms)?)),
ValueType::FuncForm(ref f) => {
// stores any value overwritten by local state
// If this ever becomes ASYNC this will need to