/* 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; pub struct SymTable(HashMap); #[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, // for internal control flow constructs // eval() will not eval the args pub conditional_branches: bool, } impl SymTable { pub fn new() -> SymTable { SymTable(HashMap::::new()) } pub fn get(&self, arg: &String) -> Option<&Symbol> { self.0.get(arg) } pub fn insert(&mut self, k: String, v: Symbol) -> Option { self.0.insert(k, v) } pub fn remove(&mut self, arg: &String) -> Option { self.0.remove(arg) } pub fn call_symbol(&mut self, name: &String, args: &Seg, call_func: bool) -> Result, String> { let symbol = match self.remove(name) { Some(s) => s, None => return Err(format!("undefined symbol: {}", name)), }; let cond_args: &Seg; let outer_scope_seg_holder: Seg; if let ValueType::VarForm(ref val) = symbol.value { return Ok(val.clone()); } else if call_func { cond_args = args } else { outer_scope_seg_holder = Seg::new(); cond_args = &outer_scope_seg_holder; } let res = symbol.call(cond_args, self); self.insert(name.to_string(), symbol); res } } impl Default for SymTable { fn default() -> Self { Self::new() } } 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, syms: &mut SymTable ) -> Result, String> { let evaluated_args: &Seg; let outer_scope_seg_storage: Seg; let outer_scope_eval: Box; if self.conditional_branches { let outer_scope_eval_result = eval(args, syms); // dont listen to clippy. using ? will move the value. if let Err(s) = outer_scope_eval_result { return Err(s); } outer_scope_eval = outer_scope_eval_result.unwrap(); match *outer_scope_eval { Ctr::Seg(ref segment) => evaluated_args = segment, _ => { outer_scope_seg_storage = Seg::from_mono(outer_scope_eval); evaluated_args = &outer_scope_seg_storage; } } } else { evaluated_args = args; } if let Err(msg) = self.args.validate_inputs(evaluated_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(evaluated_args, syms))), 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) = syms.insert(f.arg_syms[n].clone(), Symbol{ name: f.arg_syms[n].clone(), value: ValueType::VarForm(Box::new(evaluated_args[n].clone())), args: Args::None, conditional_branches: 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, syms) { 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() { syms.remove(&f.arg_syms[n]); if let Some(val) = holding_table.remove(&f.arg_syms[n]) { syms.insert(f.arg_syms[n].clone(), val); } } Ok(result) } } } }