/* 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::{Ctr, Seg, Type}; use crate::stdlib::{CONSOLE_XDIM_VNAME, RELISH_DEFAULT_CONS_WIDTH}; use crate::sym::{SymTable, Symbol, UserFn, ValueType}; use std::env; pub const QUOTE_DOCSTRING: &str = "takes a single unevaluated tree and returns it as it is: unevaluated."; pub fn quote_callback(ast: &Seg, _syms: &mut SymTable) -> Result { if ast.len() > 1 { Err("do not quote more than one thing at a time".to_string()) } else { Ok(*ast.car.clone()) } } pub const EVAL_DOCSTRING: &str = "takes an unevaluated argument and evaluates it. Specifically, does one pass of the tree simplification algorithm. If you have a variable referencing another variable you will get the referenced variable."; pub fn eval_callback(ast: &Seg, syms: &mut SymTable) -> Result { if ast.len() > 1 { Err("do not eval more than one thing at a time".to_string()) } else { match *ast.car { Ctr::Seg(ref s) => Ok(*eval(s, syms)?.clone()), Ctr::Symbol(ref sym) => { let intermediate = syms.call_symbol(sym, &Seg::new(), true)?; if let Ctr::Seg(ref s) = *intermediate { Ok(*eval(s, syms)?.clone()) } else { Ok(*intermediate) } }, _ => Ok(*ast.car.clone()) } /* this bit removed because it was determined eval shouldnt do things twice * kept here for reference purposes since I have gone back and forth on this * a bit * * thank you for your patience (ava) match arguments { Ctr::Seg(ref s) => Ok(*eval(s, syms)?.clone()), Ctr::Symbol(ref sym) => { let intermediate = syms.call_symbol(sym, &Seg::new(), true)?; if let Ctr::Seg(ref s) = *intermediate { Ok(*eval(s, syms)?.clone()) } else { Ok(*intermediate) } }, _ => Ok(arguments) }*/ } } pub const HELP_DOCSTRING: &str = "prints help text for a given symbol. Expects only one argument."; pub fn help_callback(ast: &Seg, syms: &mut SymTable) -> Result { if ast.len() != 1 { return Err("help only takes a single argument".to_string()); } if let Ctr::Symbol(ref symbol) = *ast.car { if let Some(ref sym) = syms.get(symbol) { let args_str: String; if let ValueType::VarForm(_) = sym.value { args_str = "(its a variable)".to_string(); } else { args_str = sym.args.to_string(); } println!( "NAME: {0}\n ARGS: {1}\n DOCUMENTATION:\n {2}\n CURRENT VALUE AND/OR BODY: {3}", sym.name, args_str, sym.docs, sym.value ); } else { return Err("undefined symbol".to_string()); } } else { return Err("help should only be called on a symbol".to_string()); } Ok(Ctr::None) } pub const ISSET_DOCSTRING: &str = "accepts a single argument: a symbol. returns true or false according to whether or not the symbol is found in the symbol table."; pub fn isset_callback(ast: &Seg, syms: &mut SymTable) -> Result { if ast.len() != 1 { Err("help only takes a single argument".to_string()) } else { if let Ctr::Symbol(ref symbol) = *ast.car { if let Some(_) = syms.get(symbol) { Ok(Ctr::Bool(true)) } else { Ok(Ctr::Bool(false)) } } else { Err("help should only be called on a symbol".to_string()) } } } pub const ENV_DOCSTRING: &str = "takes no arguments prints out all available symbols and their associated values"; pub fn env_callback(_ast: &Seg, syms: &mut SymTable) -> Result { // get width of current output let xdim: i128; if let Ctr::Integer(dim) = *syms .call_symbol(&CONSOLE_XDIM_VNAME.to_string(), &Seg::new(), true) .unwrap_or_else(|_: String| Box::new(Ctr::None)) { xdim = dim; } else { println!("{} contains non integer value, defaulting to {}", CONSOLE_XDIM_VNAME, RELISH_DEFAULT_CONS_WIDTH); xdim = RELISH_DEFAULT_CONS_WIDTH as i128; } let mut v_col_len = 0; let mut f_col_len = 0; let mut functions = vec![]; let mut variables = vec![]; for (name, val) in syms.iter() { if let ValueType::VarForm(l) = &val.value { let token: String; match l.to_type() { Type::Lambda => token = format!("{}: ", name), Type::Seg => token = format!("{}:
", name), _ => token = format!("{}: {}", name, val.value.to_string()), } if token.len() > v_col_len && token.len() < xdim as usize { v_col_len = token.len(); } variables.push(token); } else { if f_col_len < name.len() && name.len() < xdim as usize { f_col_len = name.len(); } functions.push(name.clone()); } } let mut n_v_cols = xdim / v_col_len as i128; // now decrement to make sure theres room for two spaces of padding while n_v_cols > 1 && xdim % (v_col_len as i128) < (2 * n_v_cols) { n_v_cols -= 1; } // again for functions let mut n_f_cols = xdim / f_col_len as i128; while n_f_cols > 1 && xdim & (f_col_len as i128) < (2 * n_f_cols) { n_f_cols -= 1; } let mut col_iter = 0; println!("VARIABLES:"); for var in variables { print!("{:v_col_len$}", var); col_iter += 1; if col_iter % n_v_cols == 0 { print!("\n"); } else { print!(" "); } } println!("\nFUNCTIONS:"); col_iter = 0; for func in functions { print!("{:f_col_len$}", func); col_iter += 1; if col_iter % n_f_cols == 0 { print!("\n"); } else { print!(" "); } } Ok(Ctr::None) } pub const LAMBDA_DOCSTRING: &str = "Takes two arguments of any type. No args are evaluated when lambda is called. Lambda makes sure the first argument is a list of symbols (or 'arguments') to the lambda function. The next arg is stored in a tree to evaluate on demand. Example: (lambda (x y) (add x y)) This can then be evaluated like so: ((lambda (x y) (add x y)) 1 2) which is functionally equivalent to: (add 1 2)"; pub fn lambda_callback( ast: &Seg, _syms: &mut SymTable ) -> Result { let mut args = vec![]; if let Ctr::Seg(ref arg_head) = *ast.car { if !arg_head.circuit(&mut |arg: &Ctr| -> bool { if let Ctr::Symbol(ref s) = *arg { args.push(s.clone()); true } else if let Ctr::None = *arg { // no args case true } else { false } }) { Err("all elements of first argumnets must be symbols".to_string()) } else { if let Ctr::Seg(ref eval_head) = *ast.cdr { if let Ctr::Seg(_) = *eval_head.car { Ok(Ctr::Lambda(UserFn{ ast: Box::new(eval_head.clone()), arg_syms: args, })) } else { Err("function body must be in list form".to_string()) } } else { Err("not enough args".to_string()) } } } else { Err("first argument should be a list of symbols".to_string()) } } pub const GETDOC_DOCSTRING: &str = "accepts an unevaluated symbol, returns the doc string. Returns an error if symbol is undefined. Note: make sure to quote the input like this: (get-doc (quote symbol-name))"; pub fn getdoc_callback(ast: &Seg, syms: &mut SymTable) -> Result { if let Ctr::Symbol(ref symbol) = *ast.car { if let Some(sym) = syms.get(symbol) { Ok(Ctr::String(sym.docs.clone())) } else { Err("undefined symbol".to_string()) } } else { Err("get-doc should only be called on a symbol".to_string()) } } pub const SETDOC_DOCSTRING: &str = "accepts a symbol and a doc string. Returns an error if symbol is undefined, otherwise sets the symbols docstring to the argument. Note: make sure to quote the input like this: (set-doc (quote symbol-name) my-new-docs)"; pub fn setdoc_callback(ast: &Seg, syms: &mut SymTable) -> Result { if ast.len() != 2 { Err("set-doc only takes two arguments".to_string()) } else { if let Ctr::Symbol(ref symbol) = *ast.car { if let Some(mut sym) = syms.remove(symbol) { if let Ctr::Seg(ref doc_node) = *ast.cdr { if let Ctr::String(ref doc) = *doc_node.car { sym.docs = doc.clone(); syms.insert(sym.name.clone(), sym); Ok(Ctr::None) } else { syms.insert(sym.name.clone(), sym); Err("second arg must be a string".to_string()) } } else { Err("impossible: not a second arg".to_string()) } } else { Err("undefined symbol".to_string()) } } else { Err("first argument must be a symbol".to_string()) } } } pub const STORE_DOCSTRING: &str = "allows user to define functions and variables. A call may take one of three forms: 1. variable declaration: Takes a name, doc string, and a value. (def myvar 'my special variable' 'my var value') 2. function declaration: Takes a name, doc string, list of arguments, and one or more bodies to evaluate. Result of evaluating the final body is returned. (def myfunc 'does a thing' (myarg1 myarg2) (dothing myarg1 myarg2) (add myarg1 myarg2)) 3. symbol un-definition: Takes just a name. Removes variable from table. (def useless-var) Additionally, passing a tree as a name will trigger def to evaluate the tree and try to derive a value from it. If it does not return a "; pub fn store_callback(ast: &Seg, syms: &mut SymTable, env_cfg: bool) -> Result { let is_var = ast.len() == 3; let name: String; let docs: String; match *ast.car { Ctr::String(ref s) => name = s.clone(), Ctr::Symbol(ref s) => name = s.clone(), Ctr::Seg(ref s) => match *eval(s, syms)? { Ctr::String(ref s) => name = s.clone(), Ctr::Symbol(ref s) => name = s.clone(), _ => { println!("{}", *eval(s, syms)?); return Err("evaluated symbol name doesnt make sense".to_string()); }, }, _ => return Err("symbol name doesnt make sense".to_string()), } // remove var case if ast.len() == 1 { syms.remove(&name); if env_cfg { env::remove_var(name); } return Ok(Ctr::None) } else { if ast.len() < 3 || ast.len() > 4 { return Err("expected 3 or 4 args".to_string()) } } let mut iter: &Seg; if let Ctr::Seg(ref s) = *ast.cdr { iter = s; } else { return Err("not enough args".to_string()) } match *iter.car { Ctr::String(ref s) => docs = s.clone(), Ctr::Symbol(ref s) => { if let Ctr::String(doc) = *syms.call_symbol(&s, &Seg::new(), true)? { docs = doc.clone(); } else { return Err("docs argument does not evaluate to a string".to_string()) } }, _ => return Err("docs argument does not evaluate to a string".to_string()) } if let Ctr::Seg(ref s) = *iter.cdr { iter = s; } else { return Err("not enough args".to_string()) } let mut outer_scope_val: Seg = Seg::new(); let noseg = Seg::new(); // similarly, rust shouldnt need this either let mut args = &noseg; let mut var_val_form: &Seg = &outer_scope_val; let mut expand = false; match *iter.car { Ctr::Seg(ref s) if !is_var => args = s, Ctr::Seg(ref s) if is_var => var_val_form = s, _ if is_var => { expand = true; outer_scope_val = Seg::from_mono(Box::new(*iter.car.clone())); var_val_form = &outer_scope_val; }, _ if !is_var => return Err("arg list must at least be a list".to_string()), _ => unimplemented!(), // rustc is haunted and cursed } if is_var { let var_val: Ctr; let var_eval_result = *eval(var_val_form, syms)?; match var_eval_result { Ctr::Seg(ref s) if expand => var_val = *s.car.clone(), Ctr::Seg(ref s) if !expand => var_val = Ctr::Seg(s.clone()), _ => var_val = var_eval_result, } let outer_seg = Seg::from_mono(Box::new(var_val.clone())); syms.insert( name.clone(), Symbol::from_ast(&name, &docs, &outer_seg, None), ); if env_cfg { match var_val.to_type() { Type::Lambda => {}, Type::Seg => {}, _ => { let mut s = var_val.to_string(); if let Ctr::String(tok) = var_val { s = tok; } env::set_var(name.clone(), s); } } } return Ok(Ctr::None) } let mut arg_list = vec![]; if !args.circuit(&mut |c: &Ctr| -> bool { if let Ctr::Symbol(s) = c { arg_list.push(s.clone()); true } else if let Ctr::None = c { // no args case true } else { false } }) { return Err("all arguments defined for function must be of type symbol".to_string()) } if let Ctr::Seg(ref eval_bodies) = *iter.cdr { syms.insert( name.clone(), Symbol::from_ast( &name, &docs, eval_bodies, Some(arg_list), ), ); Ok(Ctr::None) } else { Err("expected one or more bodies to evaluate in function".to_string()) } }