/* 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 .
*/
use crate::eval::eval;
use crate::func::{Args, FTable, Function, Operation};
use crate::segment::{Seg, Ctr};
use std::collections::HashMap;
use std::env;
/* 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>>);
impl<'a> VTable<'a> {
// WARNING: make sure var_tree is properly evaluated before storing
pub fn insert(&'a mut self, identifier: String, data: Box>) {
if let Some(datum) = self.0.insert(identifier, data) {
drop(datum);
}
}
pub fn get(&'a self, id: String) -> Option>> {
match self.0.get(&id) {
Some(s) => Some(s.clone()),
None => None,
}
}
pub fn remove(&self, id: String) {
self.0.remove(&id);
}
pub fn new() -> VTable<'a> {
VTable{0: HashMap::>::new()}
}
}
// returns a callback for the stdlib var export function with env_sync on or off
pub fn get_export<'a>(env_cfg: bool) -> Function<'a>{
return Function {
name: String::from("export"),
loose_syms: true,
eval_lazy: true,
args: Args::Lazy(2),
function: Operation::Internal(Box::new(
move |ast: &Seg, vars: &mut VTable, funcs: &mut FTable| -> Ctr {
_export_callback(ast, vars, funcs, env_cfg)
},
)),
};
}
fn _export_callback<'a> (ast: &'a Seg, vars: &'a mut VTable, funcs: &'a mut FTable, 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), vars, funcs, false) {
Ok(seg) => match *seg {
Ctr::Seg(val) => {
vars.insert(identifier.clone(), val.car);
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 => {
vars.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;
}