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:
parent
b680e3ca9a
commit
ca4c557d95
32 changed files with 1092 additions and 616 deletions
|
|
@ -1,70 +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::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);
|
||||
}
|
||||
}
|
||||
},
|
||||
)),
|
||||
};
|
||||
}
|
||||
147
src/bin/main.rs
147
src/bin/main.rs
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,93 +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::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);
|
||||
}
|
||||
|
|
@ -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
|
||||
})
|
||||
),
|
||||
};
|
||||
}
|
||||
137
src/eval.rs
137
src/eval.rs
|
|
@ -15,130 +15,129 @@
|
|||
* 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;
|
||||
|
||||
use crate::segment::{Seg, Ctr};
|
||||
use crate::sym::SYM_TABLE;
|
||||
|
||||
/* 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>>,
|
||||
ast: &Seg,
|
||||
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();
|
||||
call_lazy: bool,
|
||||
) -> Result<Box<Ctr>, 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(ref tok) = car {
|
||||
if let Some(val) = vars.borrow().get(tok) {
|
||||
car = (**val).clone();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// 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));
|
||||
// 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(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));
|
||||
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!")),
|
||||
}
|
||||
_ => return Err(format!("Arguments to function not a list!")),
|
||||
}
|
||||
}
|
||||
|
||||
// iterate over ast and build out ret
|
||||
let mut none = false;
|
||||
while !none {
|
||||
match car {
|
||||
// if LIST: call eval inner on it with first_item=true
|
||||
match &**arg_car {
|
||||
Ctr::Seg(ref inner) => {
|
||||
match eval(inner.clone(), vars.clone(), funcs.clone(), sym_loose) {
|
||||
Ok(res) => (*iter).borrow_mut().car = res,
|
||||
match eval(inner, vars, funcs, sym_loose, call_lazy) {
|
||||
Ok(res) => 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();
|
||||
binding_for_vtable_get = vars.get(tok.clone());
|
||||
if let Some(ref val) = binding_for_vtable_get {
|
||||
car = val.clone();
|
||||
} else if sym_loose {
|
||||
(*iter).borrow_mut().car = Ctr::Symbol(tok.to_string());
|
||||
car = arg_car.clone()
|
||||
} else {
|
||||
return Err(format!("Undefined variable: {}", tok));
|
||||
return Err(format!("Undefined variable: {}", tok.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
// if OTHER: clone and set
|
||||
_ => {
|
||||
(*iter).borrow_mut().car = car.clone();
|
||||
car = arg_car.clone();
|
||||
}
|
||||
}
|
||||
|
||||
match cdr {
|
||||
// if SYMBOL: unwrap naively, then end
|
||||
match &**arg_cdr {
|
||||
Ctr::Symbol(ref tok) => {
|
||||
if let Some(val) = vars.borrow().get(&tok.clone()) {
|
||||
(*iter).borrow_mut().car = (**val).clone();
|
||||
if let Some(val) = vars.get(tok.clone()) {
|
||||
cdr = val.clone();
|
||||
} else if sym_loose {
|
||||
(*iter).borrow_mut().car = Ctr::Symbol(tok.to_string());
|
||||
cdr = ast.cdr.clone()
|
||||
} else {
|
||||
return Err(format!("Undefined variable: {}", tok));
|
||||
return Err(format!("Undefined variable: {}", tok.clone()));
|
||||
}
|
||||
|
||||
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;
|
||||
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
|
||||
_ => {
|
||||
(*iter).borrow_mut().cdr = cdr.clone();
|
||||
cdr = ast.cdr.clone();
|
||||
none = true;
|
||||
}
|
||||
}
|
||||
|
||||
if let Ctr::None = car {
|
||||
if let Ctr::None = cdr {
|
||||
if let Ctr::None = **arg_car {
|
||||
if let Ctr::None = **arg_cdr {
|
||||
none = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(Ctr::Seg(ret));
|
||||
return Ok(ret);
|
||||
}
|
||||
|
|
|
|||
226
src/func.rs
226
src/func.rs
|
|
@ -1,226 +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::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
|
||||
}
|
||||
44
src/lex.rs
44
src/lex.rs
|
|
@ -15,7 +15,7 @@
|
|||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
use crate::segment::{list_append, Ctr, Seg};
|
||||
use crate::segment::{Ctr, Seg};
|
||||
|
||||
const UNMATCHED_STR_DELIM: &str = "Unmatched string delimiter in input";
|
||||
const UNMATCHED_LIST_DELIM: &str = "Unmatched list delimiter in input";
|
||||
|
|
@ -23,7 +23,7 @@ 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> {
|
||||
pub fn lex<'a>(document: &'a String) -> Result<Box<Seg>, String> {
|
||||
if !document.is_ascii() {
|
||||
return Err("document may only contain ascii characters".to_string());
|
||||
}
|
||||
|
|
@ -42,7 +42,7 @@ pub fn lex<'a>(document: String) -> Result<Box<Seg<'a>>, String> {
|
|||
* 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> {
|
||||
fn process<'a>(document: &'a String) -> Result<Box<Seg>, String> {
|
||||
let doc_len = document.len();
|
||||
|
||||
if doc_len == 0 {
|
||||
|
|
@ -120,8 +120,7 @@ fn process<'a>(document: &'a String) -> Result<Box<Seg<'a>>, String> {
|
|||
return Err("list started in middle of another token".to_string());
|
||||
}
|
||||
|
||||
ref_stack.push(Box::new(Seg::new()));
|
||||
|
||||
ref_stack.push(Seg::new());
|
||||
delim_stack.push(')');
|
||||
}
|
||||
// begin parsing a string
|
||||
|
|
@ -152,42 +151,47 @@ fn process<'a>(document: &'a String) -> Result<Box<Seg<'a>>, String> {
|
|||
return Err("Empty token".to_string());
|
||||
}
|
||||
|
||||
let mut current_seg = ref_stack.pop();
|
||||
let mut obj;
|
||||
let mut current_seg = ref_stack.pop().unwrap();
|
||||
let obj;
|
||||
if is_str {
|
||||
obj = Ctr::String(token);
|
||||
obj = Box::from(Ctr::String(token));
|
||||
is_str = false;
|
||||
token = String::new();
|
||||
current_seg.append(obj);
|
||||
} else if token.len() > 0 {
|
||||
if token == "true" {
|
||||
obj = Ctr::Bool(true);
|
||||
obj = Box::from(Ctr::Bool(true));
|
||||
} else if token == "false" {
|
||||
obj = Ctr::Bool(false);
|
||||
obj = Box::from(Ctr::Bool(false));
|
||||
} else if let Ok(i) = token.parse::<i128>() {
|
||||
obj = Ctr::Integer(i);
|
||||
obj = Box::from(Ctr::Integer(i));
|
||||
} else if let Ok(f) = token.parse::<f64>() {
|
||||
obj = Ctr::Float(f);
|
||||
obj = Box::from(Ctr::Float(f));
|
||||
} else if let Some(s) = tok_is_symbol(&token) {
|
||||
obj = Ctr::Symbol(s);
|
||||
obj = Box::from(Ctr::Symbol(s));
|
||||
} else {
|
||||
return Err(format!("Unparsable token: {}", token));
|
||||
}
|
||||
|
||||
token = String::new();
|
||||
current_seg.append(obj.clone());
|
||||
}
|
||||
|
||||
list_append(current_seg, obj);
|
||||
|
||||
if alloc_list {
|
||||
// return if we have finished the document
|
||||
if ref_stack.len() == 0 {
|
||||
return Ok(current_seg);
|
||||
return Ok(Box::new(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);
|
||||
let t = current_seg;
|
||||
current_seg = ref_stack.pop().unwrap();
|
||||
/* TODO: is there a way to do this that doesnt
|
||||
* involve needlessly copying heap data? I am
|
||||
* not sure what optimizations rustc performs
|
||||
* but I assume this should not end up copying
|
||||
* contained segments around.
|
||||
*/
|
||||
current_seg.append(Box::from(Ctr::Seg(t)));
|
||||
}
|
||||
|
||||
ref_stack.push(current_seg);
|
||||
|
|
|
|||
28
src/lib.rs
28
src/lib.rs
|
|
@ -15,35 +15,37 @@
|
|||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#![feature(derive_default_enum)]
|
||||
|
||||
mod append;
|
||||
/*mod append;
|
||||
mod config;
|
||||
*/
|
||||
mod eval;
|
||||
mod func;
|
||||
mod lex;
|
||||
mod segment;
|
||||
mod stl;
|
||||
mod str;
|
||||
mod vars;
|
||||
/*mod stl;
|
||||
mod str;*/
|
||||
|
||||
extern crate lazy_static;
|
||||
|
||||
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 use crate::sym::{
|
||||
SYM_TABLE, SymTable, Symbol,
|
||||
UserFn, ValueType, Args,
|
||||
LIB_EXPORT_ENV, LIB_EXPORT_NO_ENV
|
||||
};
|
||||
}
|
||||
|
||||
pub mod stdlib {
|
||||
/*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 mod aux {
|
||||
pub use crate::config::configure;
|
||||
}
|
||||
}*/
|
||||
|
|
|
|||
247
src/segment.rs
247
src/segment.rs
|
|
@ -15,11 +15,12 @@
|
|||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
use std::fmt;
|
||||
|
||||
use std::marker::PhantomData;
|
||||
use std::ops::Index;
|
||||
|
||||
// Container
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub enum Ctr <'a> {
|
||||
#[derive(Debug, Default)]
|
||||
pub enum Ctr<'a> {
|
||||
Symbol(String),
|
||||
String(String),
|
||||
Integer(i128),
|
||||
|
|
@ -45,20 +46,31 @@ pub enum Type {
|
|||
/* Segment
|
||||
* Holds two Containers.
|
||||
* Basic building block for more complex data structures.
|
||||
* I was going to call it Cell and then I learned about
|
||||
* how important RefCells were in Rust
|
||||
*/
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Seg <'a> {
|
||||
#[derive(Debug)]
|
||||
pub struct Seg<'a> {
|
||||
/* "Contents of Address Register"
|
||||
* Historical way of referring to the first value in a cell.
|
||||
*/
|
||||
pub car: &mut Ctr<'a>,
|
||||
pub car: Box<Ctr<'a>>,
|
||||
|
||||
/* "Contents of Decrement Register"
|
||||
* Historical way of referring to the second value in a cell.
|
||||
*/
|
||||
pub cdr: &mut Ctr<'a>,
|
||||
pub cdr: Box<Ctr<'a>>,
|
||||
|
||||
/* Stupid hack that makes rust look foolish.
|
||||
* Needed to determine variance of lifetime.
|
||||
* How this is an acceptable solution I have
|
||||
* not a single clue.
|
||||
*/
|
||||
_lifetime_variance_determinant: PhantomData<&'a ()>
|
||||
}
|
||||
|
||||
static NOTHING: Ctr = Ctr::None;
|
||||
|
||||
impl Ctr<'_> {
|
||||
pub fn to_type(&self) -> Type {
|
||||
match self {
|
||||
|
|
@ -74,25 +86,140 @@ impl Ctr<'_> {
|
|||
|
||||
}
|
||||
|
||||
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),
|
||||
impl<'a> Seg<'a> {
|
||||
/* recurs over tree assumed to be list in standard form
|
||||
* appends object to end of list
|
||||
*
|
||||
* TODO: figure out how not to call CLONE on a CTR via obj arg
|
||||
* TODO: return result
|
||||
*/
|
||||
pub fn append<'b>(&mut self, obj: Box<Ctr<'a>>) {
|
||||
if let Ctr::None = &*(self.car) {
|
||||
self.car = obj;
|
||||
return
|
||||
}
|
||||
|
||||
if let Ctr::Seg(s) = &mut *(self.cdr) {
|
||||
s.append(obj);
|
||||
return
|
||||
}
|
||||
|
||||
if let Ctr::None = &mut *(self.cdr) {
|
||||
self.cdr = Box::new(Ctr::Seg(Seg::from_mono(obj)));
|
||||
// pray for memory lost to the void
|
||||
}
|
||||
}
|
||||
|
||||
if parens {
|
||||
String::from("(" + string + ")")
|
||||
/* 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: FnMut(&Ctr) -> bool>(&self, func: &mut F) -> bool {
|
||||
if func(&self.car) {
|
||||
match &*(self.cdr) {
|
||||
Ctr::None => true,
|
||||
Ctr::Seg(l) => l.circuit(func),
|
||||
_ => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_mono(arg: Box<Ctr<'a>>) -> Seg<'a> {
|
||||
return Seg{
|
||||
car: arg,
|
||||
cdr: Box::new(Ctr::None),
|
||||
_lifetime_variance_determinant: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from(car: Box<Ctr<'a>>, cdr: Box<Ctr<'a>>) -> Seg<'a> {
|
||||
return Seg{
|
||||
car,
|
||||
cdr,
|
||||
_lifetime_variance_determinant: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/* recurs over ast assumed to be list in standard form
|
||||
* returns length
|
||||
*/
|
||||
pub fn len(&self) -> u128 {
|
||||
let mut len = 0;
|
||||
self.circuit(&mut |_c: &Ctr| -> bool { len += 1; true });
|
||||
len
|
||||
}
|
||||
|
||||
pub fn new() -> Seg<'a> {
|
||||
return Seg{
|
||||
car: Box::new(Ctr::None),
|
||||
cdr: Box::new(Ctr::None),
|
||||
_lifetime_variance_determinant: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Ctr <'_> {
|
||||
fn seg_to_string(s: &Seg, parens: bool) -> String {
|
||||
let mut string = String::new();
|
||||
if parens { string.push('('); }
|
||||
match *(s.car) {
|
||||
Ctr::None => string.push_str("<nil>"),
|
||||
_ => string.push_str(&s.car.to_string()),
|
||||
}
|
||||
string.push(' ');
|
||||
match &*(s.cdr) {
|
||||
Ctr::Seg(inner) => string.push_str(&seg_to_string(&inner, false)),
|
||||
Ctr::None => {string.pop();},
|
||||
_ => string.push_str(&s.cdr.to_string()),
|
||||
}
|
||||
if parens { string.push(')'); }
|
||||
|
||||
string
|
||||
}
|
||||
|
||||
impl<'a> Clone for Seg<'a> {
|
||||
fn clone(&self) -> Seg<'a> {
|
||||
return Seg{
|
||||
car: self.car.clone(),
|
||||
cdr: self.cdr.clone(),
|
||||
_lifetime_variance_determinant: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Index<usize> for Seg<'a> {
|
||||
type Output = Ctr<'a>;
|
||||
|
||||
fn index(&self, idx: usize) -> &Self::Output {
|
||||
if idx == 0 {
|
||||
return &self.car;
|
||||
}
|
||||
|
||||
if let Ctr::Seg(ref s) = *self.cdr {
|
||||
return s.index(idx - 1)
|
||||
}
|
||||
|
||||
return &NOTHING;
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Clone for Ctr<'a> {
|
||||
fn clone(&self) -> Ctr<'a> {
|
||||
match self {
|
||||
Ctr::Symbol(s) => Ctr::Symbol(s.clone()),
|
||||
Ctr::String(s) => Ctr::String(s.clone()),
|
||||
Ctr::Integer(s) => Ctr::Integer(s.clone()),
|
||||
Ctr::Float(s) => Ctr::Float(s.clone()),
|
||||
Ctr::Bool(s) => Ctr::Bool(s.clone()),
|
||||
Ctr::Seg(s) => Ctr::Seg(s.clone()),
|
||||
Ctr::None => Ctr::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Ctr<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Ctr::Symbol(s) => write!(f, "{}", s),
|
||||
|
|
@ -100,14 +227,14 @@ impl fmt::Display for Ctr <'_> {
|
|||
Ctr::Integer(s) => write!(f, "{}", s),
|
||||
Ctr::Float(s) => write!(f, "{}", s),
|
||||
Ctr::Bool(s) => {
|
||||
if s {
|
||||
if *s {
|
||||
write!(f, "T")
|
||||
} else {
|
||||
write!(f, "F")
|
||||
}
|
||||
},
|
||||
Ctr::Seg(s) => write!(f, "{}", s),
|
||||
Ctr::None => Ok(),
|
||||
Ctr::None => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -118,16 +245,6 @@ impl fmt::Display for Seg<'_> {
|
|||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
|
@ -144,67 +261,3 @@ impl Type {
|
|||
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})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
62
src/stl.rs
62
src/stl.rs
|
|
@ -1,62 +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};
|
||||
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);
|
||||
}
|
||||
85
src/str.rs
85
src/str.rs
|
|
@ -1,85 +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::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);
|
||||
},
|
||||
)),
|
||||
};
|
||||
}
|
||||
111
src/vars.rs
111
src/vars.rs
|
|
@ -1,111 +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::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;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue