/* relish: versatile lisp shell * Copyright (C) 2021 Ava Affine * * 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, 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>>); 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>) { 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(&mut self, id: String) { self.0.remove(&id); } pub fn new() -> VTable<'a> { VTable{0: HashMap::>::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; }