WIP commit:

* Fix up project structures
* combine vars and funcs table
* make a place for old code that may be useful to reference
* singleton pattern for sym table

Commentary:
When this change is finally finished I promise to use feature branches
from here on out
This commit is contained in:
Ava Hahn 2023-02-15 23:27:00 -08:00
parent b680e3ca9a
commit ca4c557d95
Signed by untrusted user who does not match committer: affine
GPG key ID: 3A4645B8CF806069
32 changed files with 1092 additions and 616 deletions

View file

@ -0,0 +1,150 @@
/* 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::func::FTable;
use crate::segment::{Seg, Ctr};
use crate::vars::VTable;
/* iterates over a syntax tree
* returns a NEW LIST of values
* representing the simplest possible form of the input
*/
/* Regarding 'a and 'b
* 'a intends to live beyond the call to eval
* 'b (input seg) only needs to live until this call to seg
*/
pub fn eval<'a, 'b>(
ast: &'b Seg<'b>,
vars: &'a mut VTable<'a>,
funcs: &'a mut FTable<'a>,
sym_loose: bool,
call_lazy: bool,
) -> Result<Box<Ctr<'b>>, String> {
// data to return
let mut ret = Box::from(Ctr::None);
// to be assigned from cloned/evaled data
let mut car;
let mut cdr = Box::from(Ctr::None);
// lets me redirect the input
let mut arg_car = &ast.car;
let mut arg_cdr = &ast.cdr;
// theres probably a better way to do this
let mut binding_for_vtable_get;
// doing an initial variable check here allows us
// to find functions passed in as variables
if let Ctr::Symbol(tok) = &**arg_car {
binding_for_vtable_get = vars.get(tok.clone());
if let Some(ref val) = binding_for_vtable_get {
arg_car = &val;
}
}
// Is ast a function call?
if !call_lazy {
if let Ctr::Symbol(ref tok) = &**arg_car {
match *ast.cdr {
Ctr::Seg(ref ast) => {
if let Some(ref func) = funcs.get(tok.clone()) {
return func.func_call(ast, vars, funcs);
} else if !sym_loose {
return Err(format!("Couldnt find definition of {}.", tok));
}
}
Ctr::None => {
if let Some(ref func) = funcs.get(tok.clone()) {
return (*func).func_call(&Seg::new(), vars, funcs);
} else if !sym_loose {
return Err(format!("Couldnt find definition of {}.", tok.clone()));
}
}
_ => return Err(format!("Arguments to function not a list!")),
}
}
}
// iterate over ast and build out ret
let mut none = false;
while !none {
match &**arg_car {
Ctr::Seg(ref inner) => {
match eval(inner, vars, funcs, sym_loose, call_lazy) {
Ok(res) => car = res,
Err(e) => return Err(format!("Evaluation error: {}", e)),
}
}
Ctr::Symbol(ref tok) => {
binding_for_vtable_get = vars.get(tok.clone());
if let Some(ref val) = binding_for_vtable_get {
car = val.clone();
} else if sym_loose {
car = arg_car.clone()
} else {
return Err(format!("Undefined variable: {}", tok.clone()));
}
}
_ => {
car = arg_car.clone();
}
}
match &**arg_cdr {
Ctr::Symbol(ref tok) => {
if let Some(val) = vars.get(tok.clone()) {
cdr = val.clone();
} else if sym_loose {
cdr = ast.cdr.clone()
} else {
return Err(format!("Undefined variable: {}", tok.clone()));
}
none = true;
}
Ctr::Seg(ref next) => {
if let Ctr::None = *ret {
*ret = Ctr::Seg(Seg::from(car, cdr.clone()))
} else if let Ctr::Seg(ref mut s) = *ret {
s.append(Box::from(Ctr::Seg(Seg::from(car, cdr.clone()))))
}
arg_car = &next.car;
arg_cdr = &next.cdr
}
// if OTHER: clone and set, and then end
_ => {
cdr = ast.cdr.clone();
none = true;
}
}
if let Ctr::None = **arg_car {
if let Ctr::None = **arg_cdr {
none = true;
}
}
}
return Ok(ret);
}

View file

@ -0,0 +1,70 @@
/* 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::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 {
name: String::from("append"),
loose_syms: false,
eval_lazy: false,
args: Args::Lazy(-1),
function: Operation::Internal(Box::new(
|a: Ast, _b: Rc<RefCell<VTable>>, _c: Rc<RefCell<FTable>>| -> Ctr {
let ptr = list_idx(a.clone(), 0);
match ptr {
Ctr::Seg(ref c) => {
let acpy = a.clone();
match acpy.borrow().cdr.clone() {
Ctr::Seg(cn) => {
// append to list case
if !circuit(cn, &mut |arg: &Ctr| -> bool {
list_append(c.clone(), arg.clone());
return true;
}) {
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 {
list_append(n.clone(), arg.clone());
return true;
}) {
eprintln!("get_append circuit loop should not have returned false");
}
return Ctr::Seg(n);
}
}
},
)),
};
}

View file

@ -0,0 +1,147 @@
/* 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

@ -0,0 +1,93 @@
/* 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::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 crate::vars::{define, VTable};
use std::cell::RefCell;
use std::fs;
use std::io::{self, Write};
use std::rc::Rc;
fn prompt_default_callback(_: Ast, _: Rc<RefCell<VTable>>, _: Rc<RefCell<FTable>>) -> Ctr {
return Ctr::String("λ ".to_string());
}
pub fn configure(filename: String, vars: Rc<RefCell<VTable>>) -> Result<Rc<RefCell<FTable>>, String> {
let funcs;
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) => {
funcs = Rc::new(RefCell::new(FTable::new()));
println!("Couldnt get stdlib: {}", s)
},
}
match 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)),
})),
) {
Some(e) => return Err(e),
None => {},
}
match fs::read_to_string(filename.clone()) {
Err(s) => {
return Err(format!("Couldnt open configuration file: {}", s));
}
Ok(raw_config) => {
let mut l = raw_config;
l = "(".to_owned() + &l + ")";
match lex(l) {
Err(s) => {
return Err(format!("Error in configuration: {}", s));
}
Ok(config) => {
if let Err(errst) = eval(config, vars, funcs.clone(), false) {
return Err(format!("Error loading {}: {}", filename.clone(), errst));
}
}
}
},
}
return Ok(funcs);
}

View file

@ -0,0 +1,40 @@
/* 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

@ -0,0 +1,144 @@
/* 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::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
* representing the simplest possible form of the input
*/
pub fn eval(
ast: Ast,
vars: Rc<RefCell<VTable>>,
funcs: Rc<RefCell<FTable>>,
sym_loose: bool,
) -> Result<Ctr, String> {
let mut car = ast.borrow().clone().car;
let mut cdr = ast.borrow().clone().cdr;
let ret = new_ast(Ctr::None, Ctr::None);
let mut iter = ret.clone();
// doing an initial variable check here allows us
// to find functions passed in as variables
if let Ctr::Symbol(ref tok) = car {
if let Some(val) = vars.borrow().get(tok) {
car = (**val).clone();
}
}
// another check to detect if we may have a function call
if let Ctr::Symbol(ref tok) = car {
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());
} else if !sym_loose {
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(),
);
} else if !sym_loose {
return Err(format!("Couldnt find definition of {}.", tok));
}
}
_ => return Err(format!("Arguments to function not a list!")),
}
}
let mut none = false;
while !none {
match car {
// if LIST: call eval inner on it with first_item=true
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)),
}
}
// if SYMBOL: unwrap naively
Ctr::Symbol(ref tok) => {
if let Some(val) = vars.borrow().get(&tok.clone()) {
(*iter).borrow_mut().car = (**val).clone();
} else if sym_loose {
(*iter).borrow_mut().car = Ctr::Symbol(tok.to_string());
} else {
return Err(format!("Undefined variable: {}", tok));
}
}
// if OTHER: clone and set
_ => {
(*iter).borrow_mut().car = car.clone();
}
}
match cdr {
// if SYMBOL: unwrap naively, then end
Ctr::Symbol(ref tok) => {
if let Some(val) = vars.borrow().get(&tok.clone()) {
(*iter).borrow_mut().car = (**val).clone();
} else if sym_loose {
(*iter).borrow_mut().car = Ctr::Symbol(tok.to_string());
} else {
return Err(format!("Undefined variable: {}", tok));
}
none = true;
}
// if LIST:
// - iter.cdr = new_ast(None, None)
// - iter = iter.cdr
// - car = cdr.car
// - cdr = cdr.cdr
// - LOOP
Ctr::Seg(next) => {
let n = new_ast(Ctr::None, Ctr::None);
iter.borrow_mut().cdr = Ctr::Seg(n.clone());
iter = n;
car = next.borrow().clone().car;
cdr = next.borrow().clone().cdr;
}
// if OTHER: clone and set, and then end
_ => {
(*iter).borrow_mut().cdr = cdr.clone();
none = true;
}
}
if let Ctr::None = car {
if let Ctr::None = cdr {
none = true;
}
}
}
return Ok(Ctr::Seg(ret));
}

View file

@ -0,0 +1,226 @@
/* 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::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>>>;
// Standardized function signature for stdlib functions
//pub type InternalOperation = impl Fn(Ast, Rc<RefCell<VTable>>, Rc<RefCell<FTable>>) -> Ctr;
#[derive(Debug)]
pub struct ExternalOperation {
// Un-evaluated abstract syntax tree
// TODO: Intermediate evaluation to simplify branches with no argument in them
// Simplified branches must not have side effects.
// TODO: Apply Memoization?
pub ast: Ast,
// list of argument string tokens
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),
}
/* Function Args
* If Lazy, is an integer denoting number of args
* If Strict, is a list of type tags denoting argument type.
*/
pub enum Args {
// signed: -1 denotes infinite args
Lazy(i128),
Strict(Vec<Type>),
}
// function which does not need args checked
pub struct Function {
pub function: Operation,
pub name: String,
pub args: Args,
// dont fail on undefined symbol (passed to eval)
pub loose_syms: bool,
// dont evaluate args at all. leave that to the function
pub eval_lazy: bool,
}
/* call
* routine is called by eval when a function call is detected
*/
pub fn func_call(
function: Rc<RefCell<Function>>,
args: Ast,
vars: Rc<RefCell<VTable>>,
funcs: Rc<RefCell<FTable>>,
) -> Result<Ctr, String> {
let called_func = function.borrow();
let mut n_args: Ast = args.clone();
if !called_func.eval_lazy {
match eval(args, vars.clone(), funcs.clone(), called_func.loose_syms) {
Ok(rc_seg) => {
if let Ctr::Seg(ast) = rc_seg {
n_args = ast
} else {
return Err("Panicking: eval returned not a list for function args.".to_string());
}
}
Err(s) => {
return Err(format!(
"error evaluating args to {}: {}",
called_func.name, s
))
}
}
}
match &called_func.args {
Args::Lazy(num) => {
let called_arg_count = list_len(n_args.clone()) as i128;
if *num == 0 {
if let Ctr::None = n_args.clone().borrow().car {
//pass
} else {
return Err(format!(
"expected 0 args in call to {}. Got one or more.",
called_func.name,
));
}
} else if *num > -1 && (*num != 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;
let passes = circuit(n_args.clone(), &mut |c: &Ctr| {
if idx >= arg_types.len() {
return false;
}
if let Ctr::None = c {
return false;
}
let ret = arg_types[idx] == c.to_type();
if ret {
idx += 1;
}
return ret;
});
if passes && idx < (arg_types.len() - 1) {
return Err(format!(
"{} too little arguments in call to {}",
arg_types.len() - (idx + 1),
called_func.name
));
}
if !passes {
if idx < (arg_types.len() - 1) {
return Err(format!(
"argument {} in call to {} is of wrong type (expected {})",
idx + 1,
called_func.name,
arg_types[idx].to_str()
));
}
if idx == (arg_types.len() - 1) {
return Err(format!(
"too many arguments in call to {}",
called_func.name
));
}
}
}
}
match &called_func.function {
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));
}
let mut result: Ctr;
let mut iterate = f.ast.clone();
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,
},
Err(e) => return Err(e),
}
} else {
panic!("function body not in standard form!")
}
match iterate.clone().borrow().clone().cdr {
Ctr::Seg(next) => iterate = next.clone(),
Ctr::None => break,
_ => 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);
}
}
}
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 {
if let Args::Lazy(i) = func.args {
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(),
);
}
} else {
return Some("external function must have lazy args".to_string());
}
}
drop(func);
ft.borrow_mut().insert(name, f);
None
}

View file

@ -0,0 +1,217 @@
/* relish: highly versatile lisp interpreter
* 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::{list_append, Ctr, Seg};
const UNMATCHED_STR_DELIM: &str = "Unmatched string delimiter in input";
const UNMATCHED_LIST_DELIM: &str = "Unmatched list delimiter in input";
/* takes a line of user input
* returns an unsimplified tree of tokens.
*/
pub fn lex<'a>(document: String) -> Result<Box<Seg<'a>>, String> {
if !document.is_ascii() {
return Err("document may only contain ascii characters".to_string());
}
let tree = process(document);
// TODO: Make multiple forms of Ok()
// To represent the multiple passable outcomes
return match tree {
Err(e) => Err(format!("Problem lexing document: {:?}", e)),
Ok(t) => Ok(t),
};
}
/* The logic used in lex
* Returns Ok(Rc<Seg>) if lexing passes
* Returns Err(String) if an error occurs
*/
fn process<'a>(document: &'a String) -> Result<Box<Seg<'a>>, String> {
let doc_len = document.len();
if doc_len == 0 {
return Err("Empty document".to_string());
}
/* State variables
* TODO: describe all of them
*/
let mut is_str = false;
let mut ign = false;
let mut token = String::new();
let mut delim_stack = Vec::new();
let mut ref_stack = vec![];
/* Iterate over document
* Manage currently sought delimiter
*/
for c in document.chars() {
let mut needs_alloc = false;
let mut alloc_list = false;
let delim: char;
if let Some(d) = delim_stack.last() {
delim = *d;
if delim == '*' {
token.push(c);
delim_stack.pop();
continue;
// normal delimiter cases
} else if c == delim {
needs_alloc = true;
// reset comment line status
if delim == '\n' {
delim_stack.pop();
ign = false;
continue;
}
// catch too many list end
// set alloc_list
if delim == ')' {
alloc_list = true;
if ref_stack.len() < 1 {
return Err("too many end parens".to_string());
}
}
delim_stack.pop();
// if we are in a commented out space, skip this char
} else if ign {
continue;
}
}
// try to generalize all whitespace
if !needs_alloc && char::is_whitespace(c) && !is_str {
// dont make empty tokens just because the document has consecutive whitespace
if token.len() == 0 {
continue;
}
needs_alloc = true;
}
// match a delimiter
if !needs_alloc {
match c {
// add a new Seg reference to the stack
'(' => {
if is_str {
token.push(c);
continue;
}
if token != "" {
return Err("list started in middle of another token".to_string());
}
ref_stack.push(Box::new(Seg::new()));
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('*');
}
// add to token
_ => {
token.push(c);
}
}
/* 1. Handle allocation of new Ctr
* 2. Handle expansion of current list ref
*/
} else {
if token.len() == 0 && !is_str && !alloc_list {
return Err("Empty token".to_string());
}
let mut current_seg = ref_stack.pop();
let mut obj;
if is_str {
obj = Ctr::String(token);
is_str = false;
token = String::new();
} else if token.len() > 0 {
if token == "true" {
obj = Ctr::Bool(true);
} else if token == "false" {
obj = Ctr::Bool(false);
} else if let Ok(i) = token.parse::<i128>() {
obj = Ctr::Integer(i);
} else if let Ok(f) = token.parse::<f64>() {
obj = Ctr::Float(f);
} else if let Some(s) = tok_is_symbol(&token) {
obj = Ctr::Symbol(s);
} else {
return Err(format!("Unparsable token: {}", token));
}
token = String::new();
}
list_append(current_seg, obj);
if alloc_list {
// return if we have finished the document
if ref_stack.len() == 0 {
return Ok(current_seg);
}
// shortening this will lead to naught but pain
obj = Ctr::Seg(current_seg.into_raw());
current_seg = ref_stack.pop();
list_append(current_seg, obj);
}
ref_stack.push(current_seg);
}
}
if is_str {
return Err(UNMATCHED_STR_DELIM.to_string());
}
return Err(UNMATCHED_LIST_DELIM.to_string());
}
/* Returns true if token
* - is all alphanumeric except dash and underscore
*
* else returns false
*/
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 Some(String::from(tok));
}

View file

@ -0,0 +1,49 @@
/* relish: highly versatile lisp interpreter
* 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/>.
*/
#![feature(derive_default_enum)]
mod append;
mod config;
mod eval;
mod func;
mod lex;
mod segment;
mod stl;
mod str;
mod vars;
pub mod ast {
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::{Ctr, Seg, Type};
pub use crate::vars::{define, VTable};
}
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 aux {
pub use crate::config::configure;
}

View file

@ -0,0 +1,210 @@
/* 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 std::fmt;
// Container
#[derive(Debug, Clone, Default)]
pub enum Ctr <'a> {
Symbol(String),
String(String),
Integer(i128),
Float(f64),
Bool(bool),
Seg(Seg<'a>),
#[default]
None,
}
// Type of Container
#[derive(PartialEq, Clone)]
pub enum Type {
Symbol,
String,
Integer,
Float,
Bool,
Seg,
None,
}
/* Segment
* Holds two Containers.
* Basic building block for more complex data structures.
*/
#[derive(Clone, Debug, Default)]
pub struct Seg <'a> {
/* "Contents of Address Register"
* Historical way of referring to the first value in a cell.
*/
pub car: &mut Ctr<'a>,
/* "Contents of Decrement Register"
* Historical way of referring to the second value in a cell.
*/
pub cdr: &mut Ctr<'a>,
}
impl Ctr<'_> {
pub fn to_type(&self) -> Type {
match self {
Ctr::Symbol(_s) => Type::Symbol,
Ctr::String(_s) => Type::String,
Ctr::Integer(_s) => Type::Integer,
Ctr::Float(_s) => Type::Float,
Ctr::Bool(_s) => Type::Bool,
Ctr::Seg(_s) => Type::Seg,
Ctr::None => Type::None,
}
}
}
fn seg_to_string(s: &Seg, parens: bool) -> String {
let mut string = String::new();
match s.car {
Ctr::None => string.push_str("<nil>"),
_ => string.push_str(s.car),
}
string.push(' ');
match s.cdr {
Ctr::Seg(inner) => string.push_str(seg_to_string(inner, false)),
Ctr::None => {},
_ => string.push_str(s.cdr),
}
if parens {
String::from("(" + string + ")")
}
}
impl fmt::Display for Ctr <'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Ctr::Symbol(s) => write!(f, "{}", s),
Ctr::String(s) => write!(f, "\'{}\'", s),
Ctr::Integer(s) => write!(f, "{}", s),
Ctr::Float(s) => write!(f, "{}", s),
Ctr::Bool(s) => {
if s {
write!(f, "T")
} else {
write!(f, "F")
}
},
Ctr::Seg(s) => write!(f, "{}", s),
Ctr::None => Ok(),
}
}
}
impl fmt::Display for Seg<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", seg_to_string(self, true))
}
}
impl Iterator for Seg<'_> {
fn next(&self) -> Option<&Seg> {
if let Ctr::Seg(s) = self.cdr {
Ok(s)
} else {
None()
}
}
}
impl Type {
pub fn to_string(&self) -> String {
let ret: &str;
match self {
Type::Symbol => ret = "symbol",
Type::String => ret = "string",
Type::Integer => ret = "integer",
Type::Float => ret = "float",
Type::Bool => ret = "bool",
Type::Seg => ret = "segment",
Type::None => ret = "none",
}
ret.to_owned()
}
}
/* applies a function across a list in standard form
* function must take a Ctr and return a bool
* short circuits on the first false returned.
* also returns false on a non standard form list
*/
pub fn circuit<F: Fn(&Ctr)>(list: &Seg, func: &mut F) -> bool {
if func(&list.car) {
match list.cdr {
Ctr::None => true,
Ctr::Seg(l) => circuit(l, func),
_ => false,
}
} else {
false
}
}
/* recurs over ast assumed to be list in standard form
* returns length
*/
pub fn list_len(list: &Seg) -> u128 {
let mut len = 0;
circuit(list, &circuit(&mut |c: &Ctr| -> bool { len += 1; true }))
}
/* recurs over tree assumed to be list in standard form
* returns clone of ctr at index provided
*
* TODO: return result (or option?)
*/
pub fn list_idx<'a>(list: &Seg, idx: u128) -> Ctr<'a> {
if idx > 0 {
if let Ctr::Seg(s) = list.car {
list_idx(s, idx - 1)
} else if idx == 1 {
list.cdr
} else {
Ctr::None
}
} else {
list.car
}
}
/* recurs over tree assumed to be list in standard form
* appends object to end of list
*
* TODO: return result
*/
pub fn list_append<'a>(list: &Seg, obj: Ctr) {
if let Ctr::None = list.car {
list.car = obj;
return
}
if let Ctr::Seg(s) = list.cdr {
list_append(s, obj)
}
if let Ctr::None = list.cdr {
list.cdr = Ctr::Seg(&Seg{car:obj, cdr:Ctr::None})
}
}

View file

@ -0,0 +1,245 @@
mod eval_tests {
use relish::ast::{ast_to_string, eval, lex, new_ast, FTable, VTable};
use relish::ast::{func_declare, Args};
use relish::ast::{Ctr, ExternalOperation, Function, Operation};
use std::cell::RefCell;
use std::rc::Rc;
// TODO: write generalized testing routine on top of list of inputs
#[test]
fn eval_singlet() {
let test_doc = "(1)".to_string();
let ft = Rc::new(RefCell::new(FTable::new()));
let vt = Rc::new(RefCell::new(VTable::new()));
match lex(test_doc.clone()) {
Err(e) => {
println!("Lexing error: {}\n", e);
assert!(false)
}
Ok(initial_ast) => match eval(initial_ast.clone(), vt.clone(), ft.clone(), false) {
Err(e) => {
println!("Evaluation error: {}\n", e);
assert!(false)
}
Ok(reduced) => {
if let Ctr::Seg(reduced_ast) = reduced {
assert_eq!(ast_to_string(reduced_ast), test_doc)
}
}
},
}
}
#[test]
fn eval_embedded_lists_no_funcs() {
let test_doc = "(1 (1 2 3 4 5) 5)".to_string();
let ft = Rc::new(RefCell::new(FTable::new()));
let vt = Rc::new(RefCell::new(VTable::new()));
match lex(test_doc.clone()) {
Err(e) => {
println!("Lexing error: {}\n", e);
assert!(false)
}
Ok(initial_ast) => match eval(initial_ast.clone(), vt.clone(), ft.clone(), false) {
Err(e) => {
println!("Evaluation error: {}\n", e);
assert!(false)
}
Ok(reduced) => {
if let Ctr::Seg(reduced_ast) = reduced {
assert_eq!(ast_to_string(reduced_ast), test_doc)
}
}
},
}
}
#[test]
fn eval_function_call() {
let test_doc = "('one' (echo 'unwrap_me'))".to_string();
let output = "('one' 'unwrap_me')";
let test_external_func: Function = Function {
name: String::from("echo"),
loose_syms: false,
eval_lazy: false,
args: Args::Lazy(1),
function: Operation::External(ExternalOperation {
arg_syms: vec!["input".to_string()],
ast: new_ast(
Ctr::Seg(new_ast(Ctr::Symbol("input".to_string()), Ctr::None)),
Ctr::None,
),
}),
};
let ft = Rc::new(RefCell::new(FTable::new()));
let vt = Rc::new(RefCell::new(VTable::new()));
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(test_external_func))) {
print!("Error declaring external func: {}", s);
assert!(false);
}
match lex(test_doc) {
Err(e) => {
println!("Lexing error: {}\n", e);
assert!(false)
}
Ok(initial_ast) => match eval(initial_ast.clone(), vt.clone(), ft.clone(), false) {
Err(e) => {
println!("Evaluation error: {}\n", e);
assert!(false)
}
Ok(reduced) => {
if let Ctr::Seg(reduced_ast) = reduced {
let out_doc = ast_to_string(reduced_ast);
if out_doc != output {
print!("Erroneous output: {}\n", out_doc);
assert!(false)
}
}
}
},
}
}
#[test]
fn eval_embedded_func_calls() {
let test_doc = "('one' (echo (echo 'unwrap_me')))".to_string();
let output = "('one' 'unwrap_me')";
let test_external_func: Function = Function {
name: String::from("echo"),
loose_syms: false,
eval_lazy: false,
args: Args::Lazy(1),
function: Operation::External(ExternalOperation {
arg_syms: vec!["input".to_string()],
ast: new_ast(
Ctr::Seg(new_ast(Ctr::Symbol("input".to_string()), Ctr::None)),
Ctr::None,
),
}),
};
let ft = Rc::new(RefCell::new(FTable::new()));
let vt = Rc::new(RefCell::new(VTable::new()));
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(test_external_func))) {
print!("Error declaring external func: {}", s);
assert!(false);
}
match lex(test_doc) {
Err(e) => {
println!("Lexing error: {}\n", e);
assert!(false)
}
Ok(initial_ast) => match eval(initial_ast.clone(), vt.clone(), ft.clone(), false) {
Err(e) => {
println!("Evaluation error: {}\n", e);
assert!(false)
}
Ok(reduced) => {
if let Ctr::Seg(reduced_ast) = reduced {
let out_doc = ast_to_string(reduced_ast);
if out_doc != output {
print!("Erroneous output: {}\n", out_doc);
assert!(false)
}
}
}
},
}
}
/*
#[test]
fn eval_bad_vars() {
let test_doc = "".to_string();
let ft = Rc::new(RefCell::new(FTable::new()));
let vt = Rc::new(RefCell::new(VTable::new()));
match lex(test_doc) {
Err(e) => {
println!("Lexing error: {}\n", e);
assert!(false)
},
Ok(initial_ast) => {
match eval(initial_ast.clone(), vt.clone(), ft.clone(), false) {
Err(e) => {
println!("Evaluation error: {}\n", e);
assert!(false)
},
Ok(reduced_ast) => {
// write tests here
}
}
}
}
}
#[test]
fn eval_bad_func() {
let test_doc = "".to_string();
let ft = Rc::new(RefCell::new(FTable::new()));
let vt = Rc::new(RefCell::new(VTable::new()));
match lex(test_doc) {
Err(e) => {
println!("Lexing error: {}\n", e);
assert!(false)
},
Ok(initial_ast) => {
match eval(initial_ast.clone(), vt.clone(), ft.clone(), false) {
Err(e) => {
println!("Evaluation error: {}\n", e);
assert!(false)
},
Ok(reduced_ast) => {
// write tests here
}
}
}
}
}
#[test]
fn eval_verify_all_elems_cloned() {
let test_doc = "".to_string();
let ft = Rc::new(RefCell::new(FTable::new()));
let vt = Rc::new(RefCell::new(VTable::new()));
match lex(test_doc) {
Err(e) => {
println!("Lexing error: {}\n", e);
assert!(false)
},
Ok(initial_ast) => {
match eval(initial_ast.clone(), vt.clone(), ft.clone(), false) {
Err(e) => {
println!("Evaluation error: {}\n", e);
assert!(false)
},
Ok(reduced_ast) => {
// write tests here
}
}
}
}
}*/
}

View file

@ -0,0 +1,356 @@
mod func_tests {
use relish::ast::VTable;
use relish::ast::{
func_call, func_declare, lex, Args, ExternalOperation, FTable, Function, Operation,
};
use relish::ast::{new_ast, Ast, Ctr, Type};
use std::cell::RefCell;
use std::rc::Rc;
#[test]
fn decl_and_call_internal_func() {
let test_internal_func: Function = Function {
name: String::from("test_func_in"),
loose_syms: false,
eval_lazy: false,
args: Args::Strict(vec![Type::Bool]),
function: Operation::Internal(Box::new(
|a: Ast, _b: Rc<RefCell<VTable>>, _c: Rc<RefCell<FTable>>| -> Ctr {
let inner = a.borrow();
let mut is_bool = false;
if let Ctr::Bool(_) = &inner.car {
is_bool = true;
}
Ctr::Bool(is_bool)
},
)),
};
let ft = Rc::new(RefCell::new(FTable::new()));
let vt = Rc::new(RefCell::new(VTable::new()));
let args = new_ast(Ctr::Bool(true), Ctr::None);
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(test_internal_func))) {
print!("Error declaring internal func: {}", s);
assert!(false);
}
let func: Rc<RefCell<Function>>;
if let Some(f) = ft.borrow().get(&"test_func_in".to_string()) {
func = f.clone();
} else {
print!("failed to retrieve function!");
assert!(false);
return;
}
if let Ok(ret) = func_call(func, args, vt, ft) {
match ret {
Ctr::Bool(b) => assert!(b),
_ => {
print!("invalid return from func!");
assert!(false);
}
}
} else {
print!("call to function failed!");
assert!(false);
}
}
#[test]
fn decl_and_call_external_func_singlet() {
match lex("((input))".to_string()) {
Err(e) => panic!("{}", e),
Ok(finner) => {
let test_external_func: Function = Function {
name: String::from("echo"),
loose_syms: false,
eval_lazy: false,
args: Args::Lazy(1),
function: Operation::External(ExternalOperation {
arg_syms: vec!["input".to_string()],
ast: finner,
}),
};
let ft = Rc::new(RefCell::new(FTable::new()));
let vt = Rc::new(RefCell::new(VTable::new()));
let args = new_ast(Ctr::String("test".to_string()), Ctr::None);
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(test_external_func)))
{
print!("Error declaring external func: {}", s);
assert!(false);
}
let func: Rc<RefCell<Function>>;
if let Some(f) = ft.borrow().get(&"echo".to_string()) {
func = f.clone();
} else {
print!("failed to retrieve function!");
assert!(false);
return;
}
match func_call(func, args, vt, ft) {
Ok(ret) => match ret {
Ctr::String(b) => assert!(b == "test"),
_ => {
print!("Invalid return from func. Got {:?}\n", ret);
assert!(false);
}
},
Err(e) => {
print!("Call to function failed: {}\n", e);
assert!(false);
}
}
}
}
}
#[test]
fn decl_and_call_external_func_multi_body() {
match lex("((input) (input))".to_string()) {
Err(e) => panic!("{}", e),
Ok(finner) => {
let test_external_func: Function = Function {
name: String::from("echo_2"),
loose_syms: false,
eval_lazy: false,
args: Args::Lazy(1),
function: Operation::External(ExternalOperation {
arg_syms: vec!["input".to_string()],
ast: finner,
}),
};
let ft = Rc::new(RefCell::new(FTable::new()));
let vt = Rc::new(RefCell::new(VTable::new()));
let args = new_ast(Ctr::String("test".to_string()), Ctr::None);
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(test_external_func)))
{
print!("Error declaring external func: {}", s);
assert!(false);
}
let func: Rc<RefCell<Function>>;
if let Some(f) = ft.borrow().get(&"echo_2".to_string()) {
func = f.clone();
} else {
print!("failed to retrieve function!");
assert!(false);
return;
}
match func_call(func, args, vt, ft) {
Ok(ret) => match ret {
Ctr::String(s) => {
assert!(s == "test");
}
_ => {
print!("Invalid return from function {:#?}. Should have recieved single string", ret);
assert!(false);
return;
}
},
Err(e) => {
print!("Call to function failed: {}\n", e);
assert!(false);
}
}
}
}
}
#[test]
fn decl_and_call_func_with_nested_call() {
let inner_func: Function = Function {
name: String::from("test_inner"),
loose_syms: false,
eval_lazy: false,
args: Args::Strict(vec![Type::Bool]),
function: Operation::Internal(Box::new(
|a: Ast, _b: Rc<RefCell<VTable>>, _c: Rc<RefCell<FTable>>| -> Ctr {
let inner = a.borrow();
if let Ctr::Bool(b) = &inner.car {
if *b {
Ctr::String("test".to_string())
} else {
Ctr::None
}
} else {
Ctr::None
}
},
)),
};
match lex("((test_inner true))".to_string()) {
Err(e) => panic!("{}", e),
Ok(finner) => {
let outer_func: Function = Function {
name: String::from("test_outer"),
loose_syms: false,
eval_lazy: false,
args: Args::Lazy(1),
function: Operation::External(ExternalOperation {
arg_syms: vec!["input".to_string()],
ast: finner,
}),
};
let ft = Rc::new(RefCell::new(FTable::new()));
let vt = Rc::new(RefCell::new(VTable::new()));
let args = new_ast(Ctr::Bool(true), Ctr::None);
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(inner_func))) {
print!("Error declaring inner func: {}", s);
assert!(false);
}
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(outer_func))) {
print!("Error declaring outer func: {}", s);
assert!(false);
}
let func: Rc<RefCell<Function>>;
if let Some(f) = ft.borrow().get(&"test_outer".to_string()) {
func = f.clone();
} else {
print!("failed to retrieve function!");
assert!(false);
return;
}
match func_call(func, args, vt, ft) {
Ok(ret) => match ret {
Ctr::String(b) => assert!(b == "test"),
_ => {
print!("Invalid return from func. Got {:?}\n", ret);
assert!(false);
}
},
Err(e) => {
print!("Call to function failed: {}\n", e);
assert!(false);
}
}
}
}
}
/* This test removed because it would make more sense to test this functionality in eval tests
* this function tested the evaluation of a complex argument ast that could be reduced in eval
#[test]
fn decl_and_call_func_eval_arg() {
let is_true_func: Function = Function{
name: String::from("is_true?"),
loose_syms: false,
eval_lazy: false,
args: Args::Strict(vec![Type::Bool]),
function: Operation::Internal(
|a: Ast, _b: Rc<RefCell<VTable>>, _c: Rc<RefCell<FTable>>| -> Ctr {
let inner = a.borrow();
if let Ctr::Bool(b) = &inner.car {
if *b {
Ctr::String("test".to_string())
} else {
Ctr::None
}
} else {
Ctr::None
}
}
)
};
let echo_func: Function = Function{
name: String::from("echo"),
loose_syms: false,
eval_lazy: false,
args: Args::Lazy(1),
function: Operation::External(
ExternalOperation{
arg_syms: vec!["input".to_string()],
ast: new_ast(Ctr::Symbol("input".to_string()), Ctr::None)
}
)
};
let ft = Rc::new(RefCell::new(FTable::new()));
let vt = Rc::new(RefCell::new(VTable::new()));
let args = new_ast(
Ctr::Seg(new_ast(
Ctr::Symbol("is_true?".to_string()),
Ctr::Seg(new_ast(
Ctr::Bool(true),
Ctr::None)))),
Ctr::None);
if let Some(s) = func_declare(ft.clone(),
Rc::new(RefCell::new(is_true_func))) {
print!("Error declaring inner func: {}", s);
assert!(false);
}
if let Some(s) = func_declare(ft.clone(),
Rc::new(RefCell::new(echo_func))) {
print!("Error declaring outer func: {}", s);
assert!(false);
}
let func: Rc<RefCell<Function>>;
if let Some(f) = ft.borrow().get(&"echo".to_string()) {
func = f.clone();
} else {
print!("failed to retrieve function!");
assert!(false);
return;
}
match func_call(func, args, vt, ft) {
Ok(ret) => {
match ret {
Ctr::String(b) => assert!(b == "test"),
_ => {
print!("Invalid return from func. Got {:?}\n", ret);
assert!(false);
}
}
},
Err(e) => {
print!("Call to function failed: {}\n", e);
assert!(false);
}
}
}*/
/*
// TODO: These tests need completion!
#[test]
fn eval_lazy_func_call() {
}
#[test]
fn sym_loose_func_call() {
}
#[test]
fn too_many_args() {
}
#[test]
fn not_enough_args() {
}
#[test]
fn bad_eval_arg() {
}
#[test]
fn bad_eval_fn_body() {
}*/
}

View file

@ -0,0 +1,178 @@
mod lex_tests {
use relish::ast::lex;
#[test]
fn test_lex_basic_pair() {
let document: &str = "(hello 'world')";
match lex(document) {
Ok(tree) => {
assert_eq!(tree, document);
}
Err(s) => {
print!("{}\n", s);
assert!(false);
}
}
}
#[test]
fn test_lex_basic_list() {
let document: &str = "(hello 'world' 1 2 3)";
match lex(document) {
Ok(tree) => {
assert_eq!(tree, document);
}
Err(s) => {
print!("{}\n", s);
assert!(false);
}
}
}
#[test]
fn test_lex_complex_list() {
let document: &str = "(hello 'world' (1 2 (1 2 3)) 1 2 3)";
match lex(document) {
Ok(tree) => {
assert_eq!(tree, document);
}
Err(s) => {
print!("{}\n", s);
assert!(false);
}
}
}
#[test]
fn test_bad_symbol() {
let document: &str = "(as;dd)";
let output: &str = "Problem lexing document: \"Unparsable token: as;dd\"";
match lex(document) {
Ok(tree) => {
print!("Bad token yielded: {}\n", tree);
assert!(false);
}
Err(s) => {
assert_eq!(s, output);
}
}
}
#[test]
fn test_list_delim_in_str() {
let document: &str = "('(')";
match lex(document) {
Ok(tree) => {
assert_eq!(tree, document);
}
Err(s) => {
print!("{}\n", s);
assert!(false);
}
}
}
#[test]
fn test_empty_string() {
let document: &str = "('')";
match lex(document) {
Ok(tree) => {
assert_eq!(tree, document);
}
Err(s) => {
print!("{}\n", s);
assert!(false);
}
}
}
#[test]
fn test_unmatched_list_delim_flat() {
let document: &str = "(one two";
let output: &str = "Problem lexing document: \"Unmatched list delimiter in input\"";
match lex(document) {
Ok(tree) => {
print!("Bad token yielded: {}\n", tree);
assert!(false);
}
Err(s) => {
assert_eq!(s, output);
}
}
}
#[test]
fn test_unmatched_list_delim_complex() {
let document: &str = "(one two (three)";
let output: &str = "Problem lexing document: \"Unmatched list delimiter in input\"";
match lex(document) {
Ok(tree) => {
print!("Bad token yielded: {}\n", tree);
assert!(false);
}
Err(s) => {
assert_eq!(s, output);
}
}
}
#[test]
fn test_comment() {
let document: &str = "#!/bin/relish\n(one two)";
let output: &str = "(one two)";
match lex(document) {
Ok(tree) => {
assert_eq!(tree, output);
}
Err(s) => {
print!("{}\n", s);
assert!(false);
}
}
}
#[test]
fn test_postline_comment() {
let document: &str = "#!/bin/relish\n((one two)# another doc comment\n(three four))";
let output: &str = "((one two) (three four))";
match lex(document) {
Ok(tree) => {
assert_eq!(tree, output.to_string());
}
Err(s) => {
print!("{}\n", s);
assert!(false);
}
}
}
#[test]
fn test_inline_comment() {
let document: &str = "#!/bin/relish\n((one two)\n# another doc comment\nthree)";
let output: &str = "((one two) three)";
match lex(document) {
Ok(tree) => {
assert_eq!(tree, output);
}
Err(s) => {
print!("{}\n", s);
assert!(false);
}
}
}
#[test]
fn test_bad_token_list() {
let document: &str = "(one t(wo)";
let output: &str = "Problem lexing document: \"list started in middle of another token\"";
match lex(document) {
Ok(tree) => {
print!("Bad token yielded: {}\n", tree);
assert!(false);
}
Err(s) => {
assert_eq!(s, output);
}
}
}
}

View file

@ -0,0 +1,166 @@
mod append_lib_tests {
use relish::ast::{ast_to_string, eval, lex, Ctr, FTable, VTable};
use relish::stdlib::get_stdlib;
use std::cell::RefCell;
use std::rc::Rc;
#[test]
fn test_append_to_empty_list() {
let document = "(append () 1 2 3)";
let result = "(1 2 3)";
let vt = Rc::new(RefCell::new(VTable::new()));
let ft: Rc<RefCell<FTable>>;
match get_stdlib(vt.clone()) {
Ok(f) => ft = f,
Err(s) => {
ft = Rc::new(RefCell::new(FTable::new()));
println!("Couldnt get stdlib: {}!", s);
assert!(false)
}
}
match lex(document.to_string()) {
Err(s) => {
println!("Couldnt lex {}: {}\n", document, s);
assert!(false);
}
Ok(tree) => match eval(tree, vt.clone(), ft.clone(), false) {
Err(s) => {
println!("Couldnt eval {}: {}\n", document, s);
assert!(false);
}
Ok(ctr) => match ctr {
Ctr::Symbol(_) => assert!(false),
Ctr::String(_) => assert!(false),
Ctr::Integer(_) => assert!(false),
Ctr::Float(_) => assert!(false),
Ctr::Bool(_) => assert!(false),
Ctr::Seg(s) => assert_eq!(ast_to_string(s), result),
Ctr::None => assert!(false),
},
},
}
}
#[test]
fn test_append_to_full_list() {
let document = "(append (1 2) 3)";
let result = "(1 2 3)";
let vt = Rc::new(RefCell::new(VTable::new()));
let ft: Rc<RefCell<FTable>>;
match get_stdlib(vt.clone()) {
Ok(f) => ft = f,
Err(s) => {
ft = Rc::new(RefCell::new(FTable::new()));
println!("Couldnt get stdlib: {}!", s);
assert!(false)
}
}
match lex(document.to_string()) {
Err(s) => {
println!("Couldnt lex {}: {}\n", document, s);
assert!(false);
}
Ok(tree) => match eval(tree, vt.clone(), ft.clone(), false) {
Err(s) => {
println!("Couldnt eval {}: {}\n", document, s);
assert!(false);
}
Ok(ctr) => match ctr {
Ctr::Symbol(_) => assert!(false),
Ctr::String(_) => assert!(false),
Ctr::Integer(_) => assert!(false),
Ctr::Float(_) => assert!(false),
Ctr::Bool(_) => assert!(false),
Ctr::Seg(s) => assert_eq!(ast_to_string(s), result),
Ctr::None => assert!(false),
},
},
}
}
#[test]
fn test_mono_append() {
let document = "(append)";
let result = "()";
let vt = Rc::new(RefCell::new(VTable::new()));
let ft: Rc<RefCell<FTable>>;
match get_stdlib(vt.clone()) {
Ok(f) => ft = f,
Err(s) => {
ft = Rc::new(RefCell::new(FTable::new()));
println!("Couldnt get stdlib: {}!", s);
assert!(false)
}
}
match lex(document.to_string()) {
Err(s) => {
println!("Couldnt lex {}: {}\n", document, s);
assert!(false);
}
Ok(tree) => match eval(tree, vt.clone(), ft.clone(), false) {
Err(s) => {
println!("Couldnt eval {}: {}\n", document, s);
assert!(false);
}
Ok(ctr) => match ctr {
Ctr::Symbol(_) => assert!(false),
Ctr::String(_) => assert!(false),
Ctr::Integer(_) => assert!(false),
Ctr::Float(_) => assert!(false),
Ctr::Bool(_) => assert!(false),
Ctr::Seg(s) => assert_eq!(ast_to_string(s), result),
Ctr::None => assert!(false),
},
},
}
}
#[test]
fn test_append_no_list() {
let document = "(append 'test' 1 2 3)";
let result = "('test' 1 2 3)";
let vt = Rc::new(RefCell::new(VTable::new()));
let ft: Rc<RefCell<FTable>>;
match get_stdlib(vt.clone()) {
Ok(f) => ft = f,
Err(s) => {
ft = Rc::new(RefCell::new(FTable::new()));
println!("Couldnt get stdlib: {}!", s);
assert!(false)
}
}
match lex(document.to_string()) {
Err(s) => {
println!("Couldnt lex {}: {}\n", document, s);
assert!(false);
}
Ok(tree) => match eval(tree, vt.clone(), ft.clone(), false) {
Err(s) => {
println!("Couldnt eval {}: {}\n", document, s);
assert!(false);
}
Ok(ctr) => match ctr {
Ctr::Symbol(_) => assert!(false),
Ctr::String(_) => assert!(false),
Ctr::Integer(_) => assert!(false),
Ctr::Float(_) => assert!(false),
Ctr::Bool(_) => assert!(false),
Ctr::Seg(s) => assert_eq!(ast_to_string(s), result),
Ctr::None => assert!(false),
},
},
}
}
}

View file

@ -0,0 +1,126 @@
mod str_lib_tests {
use relish::ast::{eval, lex, Ctr, FTable, VTable};
use relish::stdlib::get_stdlib;
use std::cell::RefCell;
use std::rc::Rc;
#[test]
fn test_simple_concat() {
let document = "(concat 'test')";
let result = "test";
let vt = Rc::new(RefCell::new(VTable::new()));
let ft: Rc<RefCell<FTable>>;
match get_stdlib(vt.clone()) {
Ok(f) => ft = f,
Err(s) => {
ft = Rc::new(RefCell::new(FTable::new()));
println!("Couldnt get stdlib: {}!", s);
assert!(false)
}
}
match lex(document.to_string()) {
Err(s) => {
println!("Couldnt lex {}: {}\n", document, s);
assert!(false);
}
Ok(tree) => match eval(tree, vt.clone(), ft.clone(), false) {
Err(s) => {
println!("Couldnt eval {}: {}\n", document, s);
assert!(false);
}
Ok(ctr) => match ctr {
Ctr::Symbol(_) => assert!(false),
Ctr::String(s) => assert_eq!(s, result),
Ctr::Integer(_) => assert!(false),
Ctr::Float(_) => assert!(false),
Ctr::Bool(_) => assert!(false),
Ctr::Seg(_) => assert!(false),
Ctr::None => assert!(false),
},
},
}
}
#[test]
fn test_poly_concat() {
let document = "(concat 'test' 1 2 3)";
let result = "test123";
let vt = Rc::new(RefCell::new(VTable::new()));
let ft: Rc<RefCell<FTable>>;
match get_stdlib(vt.clone()) {
Ok(f) => ft = f,
Err(s) => {
ft = Rc::new(RefCell::new(FTable::new()));
println!("Couldnt get stdlib: {}!", s);
assert!(false)
}
}
match lex(document.to_string()) {
Err(s) => {
println!("Couldnt lex {}: {}\n", document, s);
assert!(false);
}
Ok(tree) => match eval(tree, vt.clone(), ft.clone(), false) {
Err(s) => {
println!("Couldnt eval {}: {}\n", document, s);
assert!(false);
}
Ok(ctr) => match ctr {
Ctr::Symbol(_) => assert!(false),
Ctr::String(s) => assert_eq!(s, result),
Ctr::Integer(_) => assert!(false),
Ctr::Float(_) => assert!(false),
Ctr::Bool(_) => assert!(false),
Ctr::Seg(_) => assert!(false),
Ctr::None => assert!(false),
},
},
}
}
#[test]
fn test_empty_concat() {
let document = "(concat)";
let result = "";
let vt = Rc::new(RefCell::new(VTable::new()));
let ft: Rc<RefCell<FTable>>;
match get_stdlib(vt.clone()) {
Ok(f) => ft = f,
Err(s) => {
ft = Rc::new(RefCell::new(FTable::new()));
println!("Couldnt get stdlib: {}!", s);
assert!(false)
}
}
match lex(document.to_string()) {
Err(s) => {
println!("Couldnt lex {}: {}\n", document, s);
assert!(false);
}
Ok(tree) => match eval(tree, vt.clone(), ft.clone(), false) {
Err(s) => {
println!("Couldnt eval {}: {}\n", document, s);
assert!(false);
}
Ok(ctr) => match ctr {
Ctr::Symbol(_) => assert!(false),
Ctr::String(s) => assert_eq!(s, result),
Ctr::Integer(_) => assert!(false),
Ctr::Float(_) => assert!(false),
Ctr::Bool(_) => assert!(false),
Ctr::Seg(_) => assert!(false),
Ctr::None => assert!(false),
},
},
}
}
}

View file

@ -0,0 +1,64 @@
mod var_lib_tests {
use relish::ast::{eval, lex, Ctr, FTable, VTable};
use relish::stdlib::get_stdlib;
use std::cell::RefCell;
use std::rc::Rc;
#[test]
fn test_variable_export_and_lookup() {
let doc1 = "(export test 1)";
let doc2 = "(concat test)";
let result = "1";
let vt = Rc::new(RefCell::new(VTable::new()));
let ft: Rc<RefCell<FTable>>;
match get_stdlib(vt.clone()) {
Ok(f) => ft = f,
Err(s) => {
ft = Rc::new(RefCell::new(FTable::new()));
println!("Couldnt get stdlib: {}!", s);
assert!(false);
}
}
match lex(doc1.to_string()) {
Err(s) => {
println!("Couldnt lex {}: {}", doc1, s);
assert!(false);
}
Ok(tree) => match eval(tree, vt.clone(), ft.clone(), false) {
Err(s) => {
println!("Couldnt eval {}: {}", doc2, s);
assert!(false);
}
Ok(ctr) => {
println!("{:#?}", vt);
match ctr {
Ctr::None => assert!(true),
_ => assert!(false),
}
}
},
}
match lex(doc2.to_string()) {
Err(s) => {
println!("Couldnt lex {}: {}", doc2, s);
assert!(false);
}
Ok(tree) => match eval(tree, vt.clone(), ft.clone(), false) {
Err(s) => {
println!("Couldnt eval {}: {}", doc2, s);
assert!(false);
}
Ok(ctr) => match ctr {
Ctr::String(s) => assert_eq!(s, result),
_ => assert!(false),
},
},
}
}
}

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::append::get_append;
use crate::func::{func_declare, FTable};
use crate::segment::Ctr;
use crate::str::{get_concat, get_echo};
use crate::control::{get_if};
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);
}
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(get_append()))) {
return Err(s);
}
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(get_concat()))) {
return Err(s);
}
let mut cfg_env = true;
match conf.borrow().get(&String::from("CFG_RELISH_ENV")) {
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");
}
},
}
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(get_export(cfg_env)))) {
return Err(s);
}
if let Some(s) = func_declare(ft.clone(), Rc::new(RefCell::new(get_if()))) {
return Err(s);
}
return Ok(ft);
}

View file

@ -0,0 +1,85 @@
/* 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::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 {
name: String::from("echo"),
loose_syms: false,
eval_lazy: false,
args: Args::Lazy(-1),
function: Operation::Internal(Box::new(
|a: Ast, _b: Rc<RefCell<VTable>>, _c: Rc<RefCell<FTable>>| -> Ctr {
let mut string = String::from("");
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::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 => (),
}
println!("{}", string);
return true;
}) {
eprintln!("circuit loop in echo should not have returned false")
}
return Ctr::None;
},
)),
};
}
pub fn get_concat() -> Function {
return Function {
name: String::from("concat"),
loose_syms: false,
eval_lazy: false,
args: Args::Lazy(-1),
function: Operation::Internal(Box::new(
|a: Ast, _b: Rc<RefCell<VTable>>, _c: Rc<RefCell<FTable>>| -> Ctr {
let mut string = String::from("");
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::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 => (),
}
return true;
}) {
eprintln!("circuit loop in concat should not have returned false")
}
return Ctr::String(string);
},
)),
};
}

View file

@ -0,0 +1,111 @@
/* 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::eval::eval;
use crate::func::{Args, FTable, Function, Operation};
use crate::segment::{ast_to_string, Ast, Ctr};
use std::cell::RefCell;
use std::collections::HashMap;
use std::env;
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
*/
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>) {
if let Some(rc_segment) = vt.borrow_mut().insert(identifier, var_tree) {
drop(rc_segment);
}
}
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 {
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)
},
)),
};
} else {
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)
},
)),
};
}
}
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"),
},
Err(e) => eprintln!("couldnt eval symbol: {}", e),
},
Ctr::None => {
(*b).borrow_mut().remove(identifier);
if env_cfg {
// TODO: unset variable
}
}
_ => eprintln!("args not in standard form"),
}
}
_ => eprintln!("first argument to export must be a symbol"),
}
return Ctr::None;
}

View file

@ -0,0 +1,255 @@
/* 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::eval::eval;
use crate::segment::{Seg, Ctr, Type};
use crate::vars::{VAR_TABLE, VTable, LIB_EXPORT};
use std::collections::HashMap;
use std::convert::TryInto;
use lazy_static::lazy_static;
lazy_static! {
pub static ref FUNC_TABLE: FTable<'static> = {
let mut tab = FTable::new();
tab.declare(LIB_EXPORT);
tab
};
}
pub struct FTable<'a> (HashMap<String, &'a Function>);
impl FTable<'_> {
pub fn declare(&mut self, func: Box<Function>) -> Option<String> {
if let Operation::External(ref fun) = &func.function {
if let Args::Lazy(ref i) = func.args {
if fun.arg_syms.len() != i.clone().try_into().unwrap() {
return Some(
"external function must have lazy args equal to declared arg_syms length"
.to_string(),
);
}
} else {
return Some("external function must have lazy args".to_string());
}
}
self.0.insert(func.name, func);
None
}
pub fn get(&self, id: String) -> Option<&Box<Function>> {
self.0.get(&id)
}
pub fn remove(&mut self, id: String) {
self.0.remove(&id);
}
pub fn new() -> FTable<'static> {
FTable{0: HashMap::<String, Box<Function>>::new()}
}
}
// Standardized function signature for stdlib functions
//pub type InternalOperation = impl Fn(&Seg, &mut VTable, &mut FTable) -> Ctr;
#[derive(Debug)]
pub struct ExternalOperation<'a> {
// Un-evaluated abstract syntax tree
// TODO: Intermediate evaluation to simplify branches with no argument in them
// Simplified branches must not have side effects.
// TODO: Apply Memoization?
pub ast: Box<Seg<'a>>,
// list of argument string tokens
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<'a> {
Internal(Box<dyn Fn(&'a Seg) -> Ctr<'a>>),
External(ExternalOperation<'a>),
}
/* Function Args
* If Lazy, is an integer denoting number of args
* If Strict, is a list of type tags denoting argument type.
*/
pub enum Args {
// signed: -1 denotes infinite args
Lazy(i128),
Strict(Vec<Type>),
}
impl Args {
fn validate_inputs(&self, args: &Seg) -> Result<(), String> {
match self {
Args::Lazy(ref num) => {
let called_arg_count = args.len() as i128;
if *num == 0 {
if let Ctr::None = *args.car {
//pass
} else {
return Err("Expected 0 args. Got one or more.".to_string());
}
} else if *num > -1 && (*num != called_arg_count) {
return Err(format!(
"Expected {} args. Got {}.",
num, called_arg_count
));
}
}
Args::Strict(ref arg_types) => {
let mut idx: usize = 0;
let passes = args.circuit(&mut |c: &Ctr| -> bool {
if idx >= arg_types.len() {
return false;
}
if let Ctr::None = c {
return false;
}
if arg_types[idx] == c.to_type() {
idx += 1;
return true;
}
return false;
});
if passes && idx < (arg_types.len() - 1) {
return Err(format!(
"{} too few arguments",
arg_types.len() - (idx + 1)
));
}
if !passes {
if idx < (arg_types.len() - 1) {
return Err(format!(
"argument {} is of wrong type (expected {})",
idx + 1,
arg_types[idx].to_string()
));
}
if idx == (arg_types.len() - 1) {
return Err("too many arguments".to_string());
}
}
}
}
Ok(())
}
}
pub struct Function {
pub function: Operation,
pub name: String,
pub args: Args,
// dont fail on undefined symbol (passed to eval)
pub loose_syms: bool,
// dont evaluate args at all. leave that to the function
pub eval_lazy: bool,
}
impl<'b, 'c> Function {
/* call
* routine is called by eval when a function call is detected
*/
pub fn func_call(
&self,
args: &'b Seg<'b>,
) -> Result<Box<Ctr<'c>>, String> {
// put args in simplest desired form
let evaluated_args;
match eval(args, self.loose_syms, self.eval_lazy) {
Ok(arg_data) => {
if let Ctr::Seg(ast) = *arg_data {
evaluated_args = &ast;
} else {
return Err("Panicking: eval returned not a list for function args.".to_string());
}
}
Err(s) => {
return Err(format!(
"error evaluating args to {}: {}",
self.name, s
))
}
}
if let Err(msg) = self.args.validate_inputs(evaluated_args) {
return Err(format!("failure to call {}: {}", self.name, msg));
}
/* corecursive with eval.
* essentially calls eval on each body in the function.
* result of the final body is returned.
*/
match &self.function {
Operation::Internal(ref f) => return Ok(Box::new(f(evaluated_args))),
Operation::External(ref f) => {
let mut holding_table = VTable::new();
// Prep var table for function execution
for n in 0..f.arg_syms.len() {
let iter_arg = evaluated_args[n];
if let Some(val) = VAR_TABLE.get(f.arg_syms[n]) {
holding_table.insert(f.arg_syms[n].clone(), val);
}
VAR_TABLE.insert(f.arg_syms[n].clone(), Box::new(iter_arg));
}
// execute function
let mut result: Box<Ctr>;
let iterate = &*(f.ast);
loop {
if let Ctr::Seg(ref data) = *iterate.car {
match eval(data, self.loose_syms, true) {
Ok(ctr) => result = ctr,
Err(e) => return Err(e),
}
} else {
panic!("function body not in standard form!")
}
match *iterate.cdr {
Ctr::Seg(ref next) => iterate = next,
Ctr::None => break,
_ => panic!("function body not in standard form!"),
}
}
// clear local vars and restore previous values
for n in 0..f.arg_syms.len() {
VAR_TABLE.remove(f.arg_syms[n]);
if let Some(val) = holding_table.get(f.arg_syms[n]) {
VAR_TABLE.insert(f.arg_syms[n].clone(), val);
}
}
return Ok(result);
}
}
}
}

View file

@ -0,0 +1,120 @@
/* 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::eval::eval;
use crate::func::{Args, Function, Operation};
use crate::segment::{Seg, Ctr};
use std::collections::HashMap;
use std::env;
use lazy_static::lazy_static;
lazy_static! {
pub static ref VAR_TABLE: VTable<'static> = {
VTable::new()
};
}
/* 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
*/
pub struct VTable<'a>(HashMap<String, Box<Ctr<'a>>>);
impl<'a, 'b> VTable<'a> {
// WARNING: make sure var_tree is properly evaluated before storing
pub fn insert(&'a mut self, identifier: String, data: Box<Ctr<'a>>) {
if let Some(datum) = self.0.insert(identifier, data) {
drop(datum);
}
}
pub fn get(&'a self, id: String) -> Option<Box<Ctr<'b>>> {
match self.0.get(&id) {
Some(s) => Some(s.clone()),
None => None,
}
}
pub fn remove(&mut self, id: String) {
self.0.remove(&id);
}
pub fn new() -> VTable<'a> {
VTable{0: HashMap::<String, Box<Ctr>>::new()}
}
}
// the stdlib var export function with env_sync on
lazy_static! {
pub static ref LIB_EXPORT_ENV: Function = Function {
name: String::from("export"),
loose_syms: true,
eval_lazy: true,
args: Args::Lazy(2),
function: Operation::Internal(Box::new( move |ast: &Seg| -> Ctr {
_export_callback(ast, true)
},
)),
};
}
// the stdlib var export function with env_sync off
lazy_static! {
pub static ref LIB_EXPORT_NO_ENV: Function = Function {
name: String::from("export"),
loose_syms: true,
eval_lazy: true,
args: Args::Lazy(2),
function: Operation::Internal(Box::new( move |ast: &Seg| -> Ctr {
_export_callback(ast, false)
},
)),
};
}
fn _export_callback<'a> (ast: &Seg, env_cfg: bool) -> Ctr<'a> {
if let Ctr::Symbol(ref identifier) = *ast.car {
match &*ast.cdr {
Ctr::Seg(data_tree) => match eval(&Box::new(data_tree), false, true) {
Ok(seg) => match *seg {
Ctr::Seg(val) => {
SYM_TABLE.declare(Symbol {
value: UserVar(val.car),
name: identifier.clone(),
});
if env_cfg {
env::set_var(identifier.clone(), val.car.to_string())
}
},
_ => eprintln!("impossible args to export"),
},
Err(e) => eprintln!("couldnt eval symbol: {}", e),
},
Ctr::None => {
VAR_TABLE.remove(identifier.to_string());
if env_cfg {
env::remove_var(identifier.to_string());
}
},
_ => eprintln!("args not in standard form"),
}
} else {
eprintln!("first argument to export must be a symbol");
}
return Ctr::None;
}