in progress commit

- added vars to lib
- fixed adders and getters to both vtable and ftable
- made function operations a dual type (enum)
- prototyped calling of stored external ASTs with
arguments (additional operation type
- stub for eval
- added index function to Cell
This commit is contained in:
Aidan 2021-02-14 16:33:17 -08:00
parent 61e3985592
commit d2f60314f9
No known key found for this signature in database
GPG key ID: 327711E983899316
6 changed files with 162 additions and 54 deletions

View file

@ -20,6 +20,7 @@ use std::boxed::Box;
// Container // Container
#[derive(Clone)]
pub enum Ctr { pub enum Ctr {
Symbol(String), Symbol(String),
String(String), String(String),
@ -32,6 +33,7 @@ pub enum Ctr {
// Type of Container // Type of Container
#[derive(PartialEq)] #[derive(PartialEq)]
#[derive(Clone)]
pub enum Type { pub enum Type {
Symbol, Symbol,
String, String,
@ -46,6 +48,7 @@ pub enum Type {
* Holds two Containers. * Holds two Containers.
* Basic building block for more complex data structures. * Basic building block for more complex data structures.
*/ */
#[derive(Clone)]
pub struct Cell { pub struct Cell {
/* "Cell Address Register" /* "Cell Address Register"
* Historical way of referring to the first value in a cell. * Historical way of referring to the first value in a cell.
@ -165,7 +168,7 @@ impl Cell {
* short circuits on the first false returned. * short circuits on the first false returned.
* also returns false on a non standard form list * also returns false on a non standard form list
*/ */
pub fn circuit<F: FnOnce(Ctr)-> bool>(&mut self, func: F) -> bool{ pub fn circuit<F: FnOnce(Ctr)-> bool>(&self, func: F) -> bool{
if func(self.car) { if func(self.car) {
match self.cdr { match self.cdr {
Ctr::None => true, Ctr::None => true,
@ -213,4 +216,31 @@ impl Cell {
_ => 1 _ => 1
} }
} }
/* iterates through a list.
* returns a COPY of the cell at the cooresponding index
* WARNING: DESTRUCTIVE?
*/
pub fn index(&self, idx: usize) -> Ctr {
if idx > 0 {
match self.cdr {
Ctr::None => Ctr::None,
Ctr::Cell(c) => c.index(idx-1),
_ => {
if idx == 1 {
self.cdr
} else {
Ctr::None
}
}
}
} else {
match self.car {
Ctr::None => Ctr::None,
_ => {
self.cdr
}
}
}
}
} }

34
src/eval.rs Normal file
View file

@ -0,0 +1,34 @@
/* 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 <http://www.gnu.org/licenses/>.
*/
use std::boxed::Box;
use crate::cell::{Cell};
use crate::func::FTable;
use crate::vars::VTable;
/* iterates over a syntax tree
* returns a NEW LIST of values
* representing the simplest possible form of the input
*/
pub fn eval(
_ast: Box<Cell>,
_vars: Box<VTable>,
_funcs: Box<FTable>,
_sym_loose: bool
) -> Result<Box<Cell>, String> {
Err("Unimplemented".to_string())
}

View file

@ -16,14 +16,33 @@
*/ */
use std::boxed::Box; use std::boxed::Box;
use std::convert::TryInto;
use std::collections::HashMap; use std::collections::HashMap;
use crate::cell::{Ctr, Cell, Type}; use crate::cell::{Ctr, Cell, Type};
use crate::vars::{VTable}; use crate::vars::{VTable};
use crate::eval::eval; use crate::eval::eval;
pub type FTable = HashMap<String, Box<Function>>;
// Standardized function signature for stdlib functions // Standardized function signature for stdlib functions
pub type Operation = fn(Box<Cell>, Box<VTable>, Box<FTable>) -> Box<Cell>; pub type InternalOperation = fn(Box<Cell>, Box<VTable>, Box<FTable>) -> Box<Cell>;
pub type FTable = HashMap<String, Function>; pub struct ExternalOperation {
// 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?
ast: Box<Cell>,
// list of argument string tokens
arg_syms: Vec<String>
}
/* A stored function may either be a pointer to a function
* or a syntax tree to eval with the arguments
*/
pub enum Operation {
Internal(InternalOperation),
External(ExternalOperation)
}
/* Function Args /* Function Args
* If Lazy, is an integer denoting number of args * If Lazy, is an integer denoting number of args
@ -39,7 +58,6 @@ pub enum Args {
pub struct Function { pub struct Function {
pub function: Operation, pub function: Operation,
pub name: String, pub name: String,
pub times_called: u128,
pub args: Args, pub args: Args,
// dont fail on undefined symbol (passed to eval) // dont fail on undefined symbol (passed to eval)
@ -53,9 +71,9 @@ impl Function {
/* call /* call
* routine is called by eval when a function call is detected * routine is called by eval when a function call is detected
*/ */
pub fn call_function ( pub fn call(
&mut self, &self,
args: Box<cell>, args: Box<Cell>,
vars: Box<VTable>, vars: Box<VTable>,
funcs: Box<FTable> funcs: Box<FTable>
) -> Result<Box<Cell>, String> { ) -> Result<Box<Cell>, String> {
@ -66,33 +84,31 @@ impl Function {
Err(s) => return Err( Err(s) => return Err(
format!( format!(
"error evaluating args to {}: {}", "error evaluating args to {}: {}",
func.name, self.name,
s s
) )
) )
} }
} }
let mut passes = false;
match self.args { match self.args {
Args::Lazy(num) => { Args::Lazy(num) => {
if num < 0 { if num < 0 {
passes = true
} }
if !(num == (args.len() - 1)) { if !(num == (n_args.len() - 1)) {
return Err(format!("expected {} args in call to {}", num, self.name)) return Err(format!("expected {} args in call to {}", num, self.name))
} }
}, },
Args::Strict(arg_types) => { Args::Strict(arg_types) => {
let idx: usize = 0; let idx: usize = 0;
passes = args.circuit(|c: Ctr| { let mut passes = args.circuit(|c: Ctr| {
if idx >= arg_types.len() { if idx >= arg_types.len() {
return false; return false;
} }
if let c = Ctr::None { if let Ctr::None = c {
return false; return false;
} }
@ -104,7 +120,7 @@ impl Function {
}); });
if passes && idx < (arg_types.len() - 1) { if passes && idx < (arg_types.len() - 1) {
Err(format!( return Err(format!(
"{} too little arguments in call to {}", "{} too little arguments in call to {}",
arg_types.len() - (idx + 1), arg_types.len() - (idx + 1),
self.name self.name
@ -113,7 +129,7 @@ impl Function {
if !passes { if !passes {
if idx < (arg_types.len() - 1) { if idx < (arg_types.len() - 1) {
Err(format!( return Err(format!(
"argument {} in call to {} is of wrong type (expected {})", "argument {} in call to {} is of wrong type (expected {})",
idx + 1, idx + 1,
self.name, self.name,
@ -122,7 +138,7 @@ impl Function {
} }
if idx == (arg_types.len() - 1) { if idx == (arg_types.len() - 1) {
Err(format!( return Err(format!(
"too many arguments in call to {}", "too many arguments in call to {}",
self.name self.name
)); ));
@ -131,24 +147,54 @@ impl Function {
} }
} }
self.times_called += 1; match self.function {
return Ok((self.function)(args, vars, funcs)); Operation::Internal(f) => Ok((f)(n_args, vars, funcs)),
Operation::External(f) => {
// copy var table and add args
let temp = vars.clone();
for n in 0..f.arg_syms.len() {
temp.insert(
f.arg_syms[n],
Box::new(n_args.index(n))
);
}
eval(f.ast, temp, funcs, self.loose_syms)
}
}
} }
} }
impl FTable { pub fn declare(
pub fn declare( ft: Box<FTable>,
&mut self, f: Box<Function>
f: Function ) -> Option<String> {
) { if let Operation::External(fun) = f.function {
// memory leak here? where does Function go? maybe it should be boxed.... if let Args::Lazy(i) = f.args {
self.insert(f.name, f); if fun.arg_syms.len() != i.try_into().unwrap() {
return Some(
"external function must have lazy args equal to declared arg_syms length"
.to_string()
);
}
} else {
return Some(
"external function must have lazy args"
.to_string()
);
}
} }
pub fn get( ft.insert(f.name, f);
&mut self, None
}
pub fn get(
ft: Box<FTable>,
identifier: String identifier: String
) -> Result<Box<Cell>, String> { ) -> Option<Box<Function>> {
self.get(identifier) if let Some(f) = ft.get(&identifier) {
Some(*f)
} else {
None
} }
} }

View file

@ -23,10 +23,6 @@ const UNMATCHED_LIST_DELIM: &str = "Unmatched list delimiter in input";
/* takes a line of user input /* takes a line of user input
* returns an unsimplified tree of tokens. * returns an unsimplified tree of tokens.
*
* WARNING: lex and process ONLY SUPPORT ASCII CHARACTERS.
* Unicode and other technology where one rune can take multiple indexes
* can cause havoc if part of a rune matches a whitespace or other operator
*/ */
pub fn lex(document: String) -> Result<Box<Cell>, String> { pub fn lex(document: String) -> Result<Box<Cell>, String> {
if !document.is_ascii() { if !document.is_ascii() {
@ -46,8 +42,6 @@ pub fn lex(document: String) -> Result<Box<Cell>, String> {
/* The logic used in lex /* The logic used in lex
* Returns Ok(Box<Cell>) if lexing passes * Returns Ok(Box<Cell>) if lexing passes
* Returns Err(String) if an error occurs * Returns Err(String) if an error occurs
*
* WARNING: read docs for lex
*/ */
fn process(document: String) -> Result<Box<Cell>, String> { fn process(document: String) -> Result<Box<Cell>, String> {
let doc_len = document.len(); let doc_len = document.len();

View file

@ -19,10 +19,12 @@ mod cell;
mod lex; mod lex;
mod func; mod func;
mod eval; mod eval;
mod vars;
pub mod ast { pub mod ast {
pub use crate::cell::{Cell, Ctr, cons, cell_as_string}; pub use crate::cell::{Cell, Ctr, cons, cell_as_string};
pub use crate::lex::{lex}; pub use crate::lex::{lex};
pub use crate::func::{Function, Operation, FTable}; pub use crate::func::{Function, Operation, FTable};
pub use crate::vars::VTable;
pub use crate::eval::{eval}; pub use crate::eval::{eval};
} }

View file

@ -17,7 +17,7 @@
use std::boxed::Box; use std::boxed::Box;
use std::collections::HashMap; use std::collections::HashMap;
use crate::cell::{Ctr, Cell}; use crate::cell::{Ctr};
/* Mapping between a string token and a tree of Cells /* Mapping between a string token and a tree of Cells
* The string token can be found in any Ctr::Symbol value * The string token can be found in any Ctr::Symbol value
@ -25,23 +25,25 @@ use crate::cell::{Ctr, Cell};
* Considerations: should I use a structure of cells for this? * Considerations: should I use a structure of cells for this?
* Current thoughts: if this was a language without proper data types, yes. * Current thoughts: if this was a language without proper data types, yes.
*/ */
pub type VTable = HashMap<String, Cell>; pub type VTable = HashMap<String, Box<Ctr>>;
impl VTable { pub fn define(
pub fn define( vt: Box<VTable>,
&mut self,
identifier: String, identifier: String,
var_tree: Box<Cell> var_tree: Box<Ctr>
) { ) {
if let Some(boxed_cell) = self.insert(identifier, var_tree) { if let Some(boxed_cell) = vt.insert(identifier, var_tree) {
drop(boxed_cell); drop(boxed_cell);
} }
} }
pub fn get( pub fn get(
&self, vt: Box<VTable>,
identifier: String identifier: String
) -> Option<Box<Cell>> { ) -> Option<Box<Ctr>> {
self.get(identifier) if let Some(c) = vt.get(&identifier) {
Some(*c)
} else {
None
} }
} }