/* 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::segment::{Seg, Ctr, Type}; use std::collections::HashMap; use std::sync::RwLock; use lazy_static::lazy_static; pub type SymTable = HashMap; lazy_static! { pub static ref SYM_TABLE: RwLock = { RwLock::new(SymTable::new()) }; } #[derive(Debug, Clone)] pub struct UserFn { // 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, // list of argument string tokens pub arg_syms: Vec, } /* A symbol may either be a pointer to a function * or a syntax tree to eval with the arguments or * a simple variable declaration (which can also * be a macro) */ #[derive(Clone)] pub enum ValueType { Internal(Box Ctr>), FuncForm(UserFn), VarForm(Box) } /* Function Args * If Lazy, is an integer denoting number of args * If Strict, is a list of type tags denoting argument type. */ #[derive(Clone)] pub enum Args { Lazy(u128), Strict(Vec), Infinite, None } #[derive(Clone)] pub struct Symbol { pub value: ValueType, pub name: String, pub args: Args, pub has_undefined_symbols: bool, } impl Args { fn validate_inputs(&self, args: &Seg) -> Result<(), String> { match self { Args::None => { if args.is_empty() { return Ok(()) } else { return Err("expected no args".to_string()) } }, Args::Infinite => { if !args.is_empty() { return Ok(()) } else { return Err("expected args but none were provided".to_string()) } }, Args::Lazy(ref num) => { let called_arg_count = args.len(); 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 != 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; } 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] )); } if idx == (arg_types.len() - 1) { return Err("too many arguments".to_string()); } } } } Ok(()) } } impl Symbol { /* call * routine is called by eval when a symbol is expanded */ pub fn call( &self, args: &Seg, ) -> Result, String> { if let Err(msg) = self.args.validate_inputs(args) { return Err(format!("failure to call {}: {}", self.name, msg)); } match &self.value { ValueType::VarForm(ref f) => Ok(Box::new(*f.clone())), ValueType::Internal(ref f) => Ok(Box::new(f(args))), ValueType::FuncForm(ref f) => { // stores any value overwritten by local state // If this ever becomes ASYNC this will need to // become a more traditional stack design, and the // global table will need to be released let mut holding_table = SymTable::new(); // Prep var table for function execution for n in 0..f.arg_syms.len() { if let Some(old) = SYM_TABLE.write().unwrap() .insert(f.arg_syms[n].clone(), Symbol{ name: f.arg_syms[n].clone(), value: ValueType::VarForm(Box::new(args[n].clone())), args: Args::None, has_undefined_symbols: false, }) { holding_table.insert(f.arg_syms[n].clone(), old); } } // execute function let mut result: Box; let mut iterate = &*(f.ast); loop { if let Ctr::Seg(ref data) = *iterate.car { match eval(data, !self.has_undefined_symbols, 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() { SYM_TABLE.write().unwrap().remove(&f.arg_syms[n]); if let Some(val) = holding_table.remove(&f.arg_syms[n]) { SYM_TABLE.write().unwrap().insert(f.arg_syms[n].clone(), val); } } Ok(result) } } } }