mark core as nostd
* implement custom hashmap to back symtable * pass in print and read callbacks to keep stdlib pure * use core / alloc versions of Box, Rc, Vec, etc * replace pow func with libm Signed-off-by: Ava Affine <ava@sunnypup.io>
This commit is contained in:
parent
0c2aad2cb6
commit
d6a0e68460
26 changed files with 493 additions and 288 deletions
|
|
@ -15,7 +15,10 @@
|
|||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
use std::fmt;
|
||||
use alloc::vec::Vec;
|
||||
use alloc::string::String;
|
||||
use core::fmt;
|
||||
use core::convert;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TraceItem {
|
||||
|
|
@ -32,7 +35,7 @@ pub fn start_trace(item: TraceItem) -> Traceback {
|
|||
|
||||
impl Traceback {
|
||||
pub fn new() -> Traceback {
|
||||
Traceback(vec![])
|
||||
Traceback(Vec::new())
|
||||
}
|
||||
|
||||
pub fn with_trace(mut self, item: TraceItem) -> Traceback {
|
||||
|
|
@ -56,13 +59,13 @@ impl fmt::Display for Traceback {
|
|||
}
|
||||
|
||||
|
||||
impl std::convert::From<Traceback> for String {
|
||||
impl convert::From<Traceback> for String {
|
||||
fn from(arg: Traceback) -> Self {
|
||||
format!("{}", arg)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::convert::From<(&String, &str)> for TraceItem {
|
||||
impl convert::From<(&String, &str)> for TraceItem {
|
||||
fn from(value: (&String, &str)) -> Self {
|
||||
TraceItem {
|
||||
caller: value.0.clone(),
|
||||
|
|
@ -71,7 +74,7 @@ impl std::convert::From<(&String, &str)> for TraceItem {
|
|||
}
|
||||
}
|
||||
|
||||
impl std::convert::From<(&String, String)> for TraceItem {
|
||||
impl convert::From<(&String, String)> for TraceItem {
|
||||
fn from(value: (&String, String)) -> Self {
|
||||
TraceItem {
|
||||
caller: value.0.clone(),
|
||||
|
|
@ -80,7 +83,7 @@ impl std::convert::From<(&String, String)> for TraceItem {
|
|||
}
|
||||
}
|
||||
|
||||
impl std::convert::From<(&str, String)> for TraceItem {
|
||||
impl convert::From<(&str, String)> for TraceItem {
|
||||
fn from(value: (&str, String)) -> Self {
|
||||
TraceItem {
|
||||
caller: String::from(value.0),
|
||||
|
|
@ -89,7 +92,7 @@ impl std::convert::From<(&str, String)> for TraceItem {
|
|||
}
|
||||
}
|
||||
|
||||
impl std::convert::From<(&str, &str)> for TraceItem {
|
||||
impl convert::From<(&str, &str)> for TraceItem {
|
||||
fn from(value: (&str, &str)) -> Self {
|
||||
TraceItem {
|
||||
caller: String::from(value.0),
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@
|
|||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
use alloc::boxed::Box;
|
||||
use crate::segment::{Ctr, Seg};
|
||||
use crate::sym::{SymTable, call_lambda};
|
||||
use crate::error::Traceback;
|
||||
|
|
|
|||
159
core/src/hashmap.rs
Normal file
159
core/src/hashmap.rs
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
/* Flesh: Flexible 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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
use alloc::slice;
|
||||
use alloc::vec::Vec;
|
||||
use alloc::boxed::Box;
|
||||
use alloc::string::String;
|
||||
|
||||
/* Use a prime number so that the modulus operation
|
||||
* provides better avalanche effect
|
||||
*/
|
||||
const INDEXED_BUCKETS: u8 = 199;
|
||||
|
||||
/* This only has to work to make quasi unique indexes from
|
||||
* variable names. Any given program will not have so many
|
||||
* symbols that this becomes a bottleneck in runtime.
|
||||
*
|
||||
* Priorities:
|
||||
* - SPEED in embedded code
|
||||
* - avalanche effect
|
||||
*
|
||||
* Not a priority: minimal collisions
|
||||
*
|
||||
* Just to make sure this is not misused I keep it private
|
||||
*/
|
||||
#[inline]
|
||||
fn string_hash(input: &String) -> u8 {
|
||||
input
|
||||
.chars()
|
||||
.map(|c| c.to_digit(10)
|
||||
.or_else(|| Some(0))
|
||||
.unwrap())
|
||||
.reduce(|acc, i| (acc + i) % INDEXED_BUCKETS as u32)
|
||||
.or_else(|| Some(0))
|
||||
.unwrap() as u8
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Bucket<T: Clone>(Vec<(String, T)>);
|
||||
#[derive(Clone)]
|
||||
pub struct QuickMap<T: Clone>(Box<[Bucket<T>; INDEXED_BUCKETS as usize]>);
|
||||
|
||||
impl<'a, T: Clone> QuickMap<T> {
|
||||
const ARRAY_REPEAT_VALUE: Bucket<T> = Bucket(vec![]);
|
||||
|
||||
pub fn new() -> QuickMap<T> {
|
||||
QuickMap(Box::new([QuickMap::ARRAY_REPEAT_VALUE; INDEXED_BUCKETS as usize]))
|
||||
}
|
||||
|
||||
pub fn get(&self, arg: &String) -> Option<&T> {
|
||||
let idx = string_hash(&arg);
|
||||
for kv in self.0[idx as usize].0.iter() {
|
||||
if &kv.0 == arg {
|
||||
return Some(&kv.1);
|
||||
}
|
||||
}
|
||||
|
||||
return None;
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, arg: &String) -> Option<T> {
|
||||
let idx = string_hash(&arg);
|
||||
let len = self.0[idx as usize].0.len();
|
||||
for i in 0..len {
|
||||
if &self
|
||||
.0[idx as usize]
|
||||
.0[i as usize]
|
||||
.0 == arg {
|
||||
return Some(self.0[idx as usize].0.swap_remove(i).1);
|
||||
}
|
||||
}
|
||||
|
||||
return None;
|
||||
}
|
||||
|
||||
pub fn contains_key(&self, arg: &String) -> bool {
|
||||
let idx = string_hash(arg);
|
||||
for kv in self.0[idx as usize].0.iter() {
|
||||
if &kv.0 == arg {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, k: String, v: T) -> Option<T> {
|
||||
let idx = string_hash(&k);
|
||||
for kv in self.0[idx as usize].0.iter_mut() {
|
||||
if kv.0 == k {
|
||||
let tmp = kv.1.clone();
|
||||
kv.1 = v;
|
||||
return Some(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
self.0[idx as usize].0.push((k, v));
|
||||
return None
|
||||
}
|
||||
|
||||
pub fn iter(&'a self) -> QuickMapIter<'a, T> {
|
||||
QuickMapIter::<'a, T>{
|
||||
buckets: &self.0,
|
||||
bucket_cursor: 0,
|
||||
vec_iter: self.0[0].0.iter(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct QuickMapIter<'a, T: Clone> {
|
||||
buckets: &'a [Bucket<T>; INDEXED_BUCKETS as usize],
|
||||
bucket_cursor: usize,
|
||||
vec_iter: slice::Iter<'a, (String, T)>,
|
||||
}
|
||||
|
||||
impl<'a, T: Clone> Iterator for QuickMapIter<'a, T> {
|
||||
type Item = &'a (String, T);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.vec_iter
|
||||
.next()
|
||||
.or_else(|| {
|
||||
self.bucket_cursor += 1;
|
||||
if self.bucket_cursor == INDEXED_BUCKETS as usize{
|
||||
None
|
||||
} else {
|
||||
self.vec_iter = self.buckets[self.bucket_cursor].0.iter();
|
||||
self.next()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn add_and_fetch_simple() {
|
||||
let mut q = QuickMap::<u8>::new();
|
||||
q.insert(String::from("test"), 1);
|
||||
assert_eq!(*q.get(&String::from("test")).unwrap(), 1);
|
||||
}
|
||||
}
|
||||
|
|
@ -15,6 +15,8 @@
|
|||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
use alloc::boxed::Box;
|
||||
use alloc::string::{String, ToString};
|
||||
use crate::segment::{Ctr, Seg};
|
||||
use crate::error::{Traceback, start_trace};
|
||||
use phf::{Map, phf_map};
|
||||
|
|
@ -67,7 +69,7 @@ fn process(document: &String) -> Result<Box<Seg>, String> {
|
|||
let mut is_str = false;
|
||||
let mut ign = false;
|
||||
let mut token = String::new();
|
||||
let mut delim_stack = Vec::new();
|
||||
let mut delim_stack = vec![];
|
||||
let mut ref_stack = vec![];
|
||||
let mut cursor = 0;
|
||||
|
||||
|
|
@ -130,7 +132,6 @@ fn process(document: &String) -> Result<Box<Seg>, String> {
|
|||
match c {
|
||||
// add a new Seg reference to the stack
|
||||
'(' if !is_str && token.is_empty() => {
|
||||
let mut s = Seg::new();
|
||||
ref_stack.push(Seg::new());
|
||||
delim_stack.push(')');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@
|
|||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
//#![no_std]
|
||||
#![cfg_attr(not(test), no_std)]
|
||||
|
||||
mod eval;
|
||||
mod lex;
|
||||
|
|
@ -24,6 +24,9 @@ mod stl;
|
|||
mod sym;
|
||||
mod error;
|
||||
|
||||
#[macro_use]
|
||||
extern crate alloc;
|
||||
|
||||
pub mod ast {
|
||||
pub use crate::eval::eval;
|
||||
pub use crate::lex::lex;
|
||||
|
|
|
|||
|
|
@ -15,9 +15,12 @@
|
|||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
use crate::sym::UserFn;
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
use std::ops::{Add, Div, Index, Mul, Sub};
|
||||
use alloc::fmt;
|
||||
use alloc::string::{String, ToString};
|
||||
use alloc::boxed::Box;
|
||||
use core::convert;
|
||||
use core::marker::PhantomData;
|
||||
use core::ops::{Add, Div, Index, Mul, Sub};
|
||||
|
||||
// Container
|
||||
#[derive(Debug, Default)]
|
||||
|
|
@ -409,7 +412,7 @@ impl fmt::Display for Type {
|
|||
}
|
||||
}
|
||||
|
||||
impl std::convert::From<String> for Type {
|
||||
impl convert::From<String> for Type {
|
||||
fn from(value: String) -> Self {
|
||||
match value.as_str() {
|
||||
"symbol" => Type::Symbol,
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@
|
|||
*/
|
||||
|
||||
use crate::sym::SymTable;
|
||||
use alloc::string::String;
|
||||
|
||||
pub mod append;
|
||||
pub mod boolean;
|
||||
|
|
@ -29,10 +30,10 @@ pub const CFG_FILE_VNAME: &str = "FLESH_CFG_FILE";
|
|||
/// static_stdlib
|
||||
/// inserts all stdlib functions that can be inserted without
|
||||
/// any kind of further configuration data into a symtable
|
||||
pub fn static_stdlib(syms: &mut SymTable) {
|
||||
pub fn static_stdlib(syms: &mut SymTable, print: fn(&String), read: fn() -> String) {
|
||||
append::add_list_lib(syms);
|
||||
strings::add_string_lib(syms);
|
||||
decl::add_decl_lib_static(syms);
|
||||
strings::add_string_lib(syms, print, read);
|
||||
decl::add_decl_lib_static(syms, print);
|
||||
control::add_control_lib(syms);
|
||||
boolean::add_bool_lib(syms);
|
||||
math::add_math_lib(syms);
|
||||
|
|
|
|||
|
|
@ -18,7 +18,10 @@
|
|||
use crate::segment::{Ctr, Seg, Type};
|
||||
use crate::sym::{SymTable, Symbol, Args, ValueType};
|
||||
use crate::error::{Traceback, start_trace};
|
||||
use std::rc::Rc;
|
||||
use alloc::rc::Rc;
|
||||
use alloc::boxed::Box;
|
||||
use alloc::string::{String, ToString};
|
||||
|
||||
|
||||
const CONS_DOCSTRING: &str = "traverses any number of arguments collecting them into a list.
|
||||
If the first argument is a list, all other arguments are added sequentially to the end of the list contained in the first argument.";
|
||||
|
|
|
|||
|
|
@ -18,7 +18,9 @@
|
|||
use crate::segment::{Ctr, Seg, Type};
|
||||
use crate::error::{Traceback, start_trace};
|
||||
use crate::sym::{SymTable, ValueType, Args, Symbol};
|
||||
use std::rc::Rc;
|
||||
use alloc::rc::Rc;
|
||||
use alloc::boxed::Box;
|
||||
use alloc::string::{String, ToString};
|
||||
|
||||
const AND_DOCSTRING: &str =
|
||||
"traverses a list of N arguments, all of which are expected to be boolean.
|
||||
|
|
|
|||
|
|
@ -19,8 +19,9 @@ use crate::eval::eval;
|
|||
use crate::error::{Traceback, start_trace};
|
||||
use crate::segment::{Ctr, Seg, Type};
|
||||
use crate::sym::{SymTable, Symbol, ValueType, Args};
|
||||
use std::rc::Rc;
|
||||
use std::process;
|
||||
use alloc::rc::Rc;
|
||||
use alloc::boxed::Box;
|
||||
use alloc::string::{String, ToString};
|
||||
|
||||
const IF_DOCSTRING: &str =
|
||||
"accepts three bodies, a condition, an unevaluated consequence, and an alternative consequence.
|
||||
|
|
@ -397,33 +398,7 @@ fn assert_callback(ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, Traceback> {
|
|||
}
|
||||
}
|
||||
|
||||
const EXIT_DOCSTRING: &str = "Takes on input: an integer used as an exit code.
|
||||
Entire REPL process quits with exit code.";
|
||||
fn exit_callback(ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, Traceback> {
|
||||
if let Ctr::Integer(i) = *ast.car {
|
||||
if i > 2 ^ 32 {
|
||||
panic!("argument to exit too large!")
|
||||
} else {
|
||||
process::exit(i as i32);
|
||||
}
|
||||
} else {
|
||||
panic!("impossible argument to exit")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_control_lib(syms: &mut SymTable) {
|
||||
syms.insert(
|
||||
"exit".to_string(),
|
||||
Symbol {
|
||||
name: String::from("exit"),
|
||||
args: Args::Strict(vec![Type::Integer]),
|
||||
conditional_branches: false,
|
||||
docs: EXIT_DOCSTRING.to_string(),
|
||||
value: ValueType::Internal(Rc::new(exit_callback)),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
syms.insert(
|
||||
"assert".to_string(),
|
||||
Symbol {
|
||||
|
|
|
|||
|
|
@ -19,7 +19,9 @@ use crate::eval::eval;
|
|||
use crate::error::{Traceback, start_trace};
|
||||
use crate::segment::{Ctr, Seg, Type};
|
||||
use crate::sym::{SymTable, Symbol, UserFn, ValueType, Args};
|
||||
use std::rc::Rc;
|
||||
use alloc::rc::Rc;
|
||||
use alloc::boxed::Box;
|
||||
use alloc::string::{String, ToString};
|
||||
|
||||
const QUOTE_DOCSTRING: &str = "takes a single unevaluated tree and returns it as it is: unevaluated.";
|
||||
fn quote_callback(ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, Traceback> {
|
||||
|
|
@ -84,7 +86,7 @@ fn eval_callback(ast: &Seg, syms: &mut SymTable) -> Result<Ctr, Traceback> {
|
|||
}
|
||||
|
||||
const HELP_DOCSTRING: &str = "prints help text for a given symbol. Expects only one argument.";
|
||||
fn help_callback(ast: &Seg, syms: &mut SymTable) -> Result<Ctr, Traceback> {
|
||||
fn help_callback(ast: &Seg, syms: &mut SymTable, print: fn(&String)) -> Result<Ctr, Traceback> {
|
||||
if ast.len() != 1 {
|
||||
return Err(start_trace(("help", "expected one input").into()));
|
||||
}
|
||||
|
|
@ -96,7 +98,7 @@ fn help_callback(ast: &Seg, syms: &mut SymTable) -> Result<Ctr, Traceback> {
|
|||
} else {
|
||||
args_str = sym.args.to_string();
|
||||
}
|
||||
println!(
|
||||
print(&format!(
|
||||
"NAME: {0}\n
|
||||
ARGS: {1}\n
|
||||
DOCUMENTATION:\n
|
||||
|
|
@ -104,7 +106,7 @@ DOCUMENTATION:\n
|
|||
CURRENT VALUE AND/OR BODY:
|
||||
{3}",
|
||||
sym.name, args_str, sym.docs, sym.value
|
||||
);
|
||||
));
|
||||
} else {
|
||||
return Err(start_trace(("help", format!("{symbol} is undefined")).into()));
|
||||
}
|
||||
|
|
@ -129,7 +131,7 @@ fn isset_callback(ast: &Seg, syms: &mut SymTable) -> Result<Ctr, Traceback> {
|
|||
|
||||
const ENV_DOCSTRING: &str = "takes no arguments
|
||||
prints out all available symbols and their associated values";
|
||||
fn env_callback(_ast: &Seg, syms: &mut SymTable) -> Result<Ctr, Traceback> {
|
||||
fn env_callback(_ast: &Seg, syms: &mut SymTable, print: fn(&String)) -> Result<Ctr, Traceback> {
|
||||
let mut functions = vec![];
|
||||
let mut variables = vec![];
|
||||
for (name, val) in syms.iter() {
|
||||
|
|
@ -146,13 +148,13 @@ fn env_callback(_ast: &Seg, syms: &mut SymTable) -> Result<Ctr, Traceback> {
|
|||
}
|
||||
}
|
||||
|
||||
println!("VARIABLES:");
|
||||
print(&String::from("VARIABLES:"));
|
||||
for var in variables {
|
||||
println!("{}", var)
|
||||
print(&var)
|
||||
}
|
||||
println!("\nFUNCTIONS:");
|
||||
print(&String::from("\nFUNCTIONS:"));
|
||||
for func in functions {
|
||||
println!("{}", func);
|
||||
print(&func);
|
||||
}
|
||||
Ok(Ctr::None)
|
||||
}
|
||||
|
|
@ -414,7 +416,8 @@ pub fn store_callback(ast: &Seg, syms: &mut SymTable) -> Result<Ctr, Traceback>
|
|||
}
|
||||
}
|
||||
|
||||
pub fn add_decl_lib_static(syms: &mut SymTable) {
|
||||
pub fn add_decl_lib_static(syms: &mut SymTable, print: fn(&String)) {
|
||||
let help_print = print.clone();
|
||||
syms.insert(
|
||||
"help".to_string(),
|
||||
Symbol {
|
||||
|
|
@ -422,7 +425,11 @@ pub fn add_decl_lib_static(syms: &mut SymTable) {
|
|||
args: Args::Strict(vec![Type::Symbol]),
|
||||
conditional_branches: true,
|
||||
docs: HELP_DOCSTRING.to_string(),
|
||||
value: ValueType::Internal(Rc::new(help_callback)),
|
||||
value: ValueType::Internal(Rc::new(
|
||||
move |ast: &Seg, syms: &mut SymTable| -> Result<Ctr, Traceback> {
|
||||
help_callback(ast, syms, help_print)
|
||||
}
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
|
@ -511,6 +518,7 @@ pub fn add_decl_lib_static(syms: &mut SymTable) {
|
|||
}
|
||||
);
|
||||
|
||||
let env_print = print.clone();
|
||||
syms.insert(
|
||||
"env".to_string(),
|
||||
Symbol {
|
||||
|
|
@ -518,7 +526,11 @@ pub fn add_decl_lib_static(syms: &mut SymTable) {
|
|||
args: Args::None,
|
||||
conditional_branches: false,
|
||||
docs: ENV_DOCSTRING.to_string(),
|
||||
value: ValueType::Internal(Rc::new(env_callback)),
|
||||
value: ValueType::Internal(Rc::new(
|
||||
move |ast: &Seg, syms: &mut SymTable| -> Result<Ctr, Traceback> {
|
||||
env_callback(ast, syms, env_print)
|
||||
}
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -18,7 +18,12 @@
|
|||
use crate::segment::{Ctr, Seg};
|
||||
use crate::sym::{SymTable, ValueType, Symbol, Args};
|
||||
use crate::error::{Traceback, start_trace};
|
||||
use std::rc::Rc;
|
||||
|
||||
use libm::pow;
|
||||
|
||||
use alloc::rc::Rc;
|
||||
use alloc::boxed::Box;
|
||||
use alloc::string::{String, ToString};
|
||||
|
||||
fn isnumeric(arg: &Ctr) -> bool {
|
||||
matches!(arg, Ctr::Integer(_) | Ctr::Float(_))
|
||||
|
|
@ -189,12 +194,7 @@ fn floatcast_callback(ast: &Seg, _: &mut SymTable) -> Result<Ctr, Traceback> {
|
|||
|
||||
const EXP_DOCSTRING: &str = "Takes two args, both expected to be numeric.
|
||||
Returns the first arg to the power of the second arg.
|
||||
Does not handle overflow or underflow.
|
||||
|
||||
PANIC CASES:
|
||||
- arg1 is a float and arg2 is greater than an int32
|
||||
- an integer exceeding the size of a float64 is raised to a float power
|
||||
- an integer is rased to the power of another integer exceeding the max size of an unsigned 32bit integer";
|
||||
Does not handle overflow or underflow.";
|
||||
fn exp_callback(ast: &Seg, _: &mut SymTable) -> Result<Ctr, Traceback> {
|
||||
let first = *ast.car.clone();
|
||||
if !isnumeric(&first) {
|
||||
|
|
@ -218,15 +218,15 @@ fn exp_callback(ast: &Seg, _: &mut SymTable) -> Result<Ctr, Traceback> {
|
|||
|
||||
match first {
|
||||
Ctr::Float(lf) => match second {
|
||||
Ctr::Float(rf) => Ok(Ctr::Float(f64::powf(lf, rf))),
|
||||
Ctr::Integer(ri) => Ok(Ctr::Float(f64::powi(lf, ri as i32))),
|
||||
Ctr::Float(rf) => Ok(Ctr::Float(pow(lf, rf))),
|
||||
Ctr::Integer(ri) => Ok(Ctr::Float(pow(lf as f64, ri as f64))),
|
||||
_ => Err(start_trace(
|
||||
("exp", "not implemented for these input types")
|
||||
.into())),
|
||||
},
|
||||
Ctr::Integer(li) => match second {
|
||||
Ctr::Float(rf) => Ok(Ctr::Float(f64::powf(li as f64, rf))),
|
||||
Ctr::Integer(ri) => Ok(Ctr::Integer(li.pow(ri as u32))),
|
||||
Ctr::Float(rf) => Ok(Ctr::Float(pow(li as f64, rf))),
|
||||
Ctr::Integer(ri) => Ok(Ctr::Float(pow(li as f64, ri as f64))),
|
||||
_ => Err(start_trace(
|
||||
("exp", "not implemented for these input types")
|
||||
.into())),
|
||||
|
|
|
|||
|
|
@ -18,18 +18,19 @@
|
|||
use crate::segment::{Ctr, Seg, Type};
|
||||
use crate::sym::{SymTable, Symbol, ValueType, Args};
|
||||
use crate::error::{Traceback, start_trace};
|
||||
use std::io::Write;
|
||||
use std::io;
|
||||
use std::rc::Rc;
|
||||
use alloc::rc::Rc;
|
||||
use alloc::boxed::Box;
|
||||
use alloc::string::{String, ToString};
|
||||
|
||||
|
||||
const ECHO_DOCSTRING: &str =
|
||||
"traverses any number of arguments. Prints their evaluated values on a new line for each.";
|
||||
fn echo_callback(ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, Traceback> {
|
||||
fn echo_callback(ast: &Seg, _syms: &mut SymTable, print_callback: fn(&String)) -> Result<Ctr, Traceback> {
|
||||
ast.circuit(&mut |arg: &Ctr| match arg {
|
||||
Ctr::String(s) => print!("{}", s) == (),
|
||||
_ => print!("{}", arg) == (),
|
||||
Ctr::String(s) => print_callback(s) == (),
|
||||
_ => print_callback(&arg.to_string()) == (),
|
||||
});
|
||||
println!();
|
||||
print_callback(&String::from("\n"));
|
||||
Ok(Ctr::None)
|
||||
}
|
||||
|
||||
|
|
@ -239,13 +240,15 @@ fn split_callback(ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, Traceback> {
|
|||
const INPUT_DOCSTRING: &str = "Takes one argument (string) and prints it.
|
||||
Then prompts for user input.
|
||||
User input is returned as a string";
|
||||
fn input_callback(ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, Traceback> {
|
||||
fn input_callback(
|
||||
ast: &Seg,
|
||||
_syms: &mut SymTable,
|
||||
print_callback: fn(&String),
|
||||
read_callback: fn() -> String,
|
||||
) -> Result<Ctr, Traceback> {
|
||||
if let Ctr::String(ref s) = *ast.car {
|
||||
print!("{}", s);
|
||||
let _= io::stdout().flush();
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input).expect("couldnt read user input");
|
||||
Ok(Ctr::String(input.trim().to_string()))
|
||||
print_callback(s);
|
||||
Ok(Ctr::String(read_callback()))
|
||||
} else {
|
||||
Err(start_trace(
|
||||
("input", "expected a string input to prompt user with")
|
||||
|
|
@ -253,7 +256,8 @@ fn input_callback(ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, Traceback> {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn add_string_lib(syms: &mut SymTable) {
|
||||
pub fn add_string_lib(syms: &mut SymTable, print: fn(&String), read: fn() -> String) {
|
||||
let echo_print = print.clone();
|
||||
syms.insert(
|
||||
"echo".to_string(),
|
||||
Symbol {
|
||||
|
|
@ -261,7 +265,11 @@ pub fn add_string_lib(syms: &mut SymTable) {
|
|||
args: Args::Infinite,
|
||||
conditional_branches: false,
|
||||
docs: ECHO_DOCSTRING.to_string(),
|
||||
value: ValueType::Internal(Rc::new(echo_callback)),
|
||||
value: ValueType::Internal(Rc::new(
|
||||
move |ast: &Seg, syms: &mut SymTable| -> Result<Ctr, Traceback> {
|
||||
echo_callback(ast, syms, echo_print)
|
||||
}
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
|
@ -344,6 +352,8 @@ pub fn add_string_lib(syms: &mut SymTable) {
|
|||
},
|
||||
);
|
||||
|
||||
let input_print = print.clone();
|
||||
let input_read = read.clone();
|
||||
syms.insert(
|
||||
"input".to_string(),
|
||||
Symbol {
|
||||
|
|
@ -351,7 +361,11 @@ pub fn add_string_lib(syms: &mut SymTable) {
|
|||
args: Args::Strict(vec![Type::String]),
|
||||
conditional_branches: false,
|
||||
docs: INPUT_DOCSTRING.to_string(),
|
||||
value: ValueType::Internal(Rc::new(input_callback)),
|
||||
value: ValueType::Internal(Rc::new(
|
||||
move |ast: &Seg, syms: &mut SymTable| -> Result<Ctr, Traceback> {
|
||||
input_callback(ast, syms, input_print, input_read)
|
||||
}
|
||||
)),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
|
|
|
|||
|
|
@ -15,15 +15,21 @@
|
|||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#[path = "hashmap.rs"]
|
||||
mod hashmap;
|
||||
use hashmap::{QuickMap, QuickMapIter};
|
||||
|
||||
use crate::eval::eval;
|
||||
use crate::error::{Traceback, start_trace};
|
||||
use crate::segment::{Ctr, Seg, Type};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::rc::Rc;
|
||||
use alloc::fmt;
|
||||
use alloc::rc::Rc;
|
||||
use alloc::vec::Vec;
|
||||
use alloc::boxed::Box;
|
||||
use alloc::string::{String, ToString};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SymTable(HashMap<String, Symbol>, usize);
|
||||
pub struct SymTable(QuickMap<Symbol>, usize);
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct UserFn {
|
||||
|
|
@ -76,7 +82,7 @@ pub struct Symbol {
|
|||
|
||||
impl SymTable {
|
||||
pub fn new() -> SymTable {
|
||||
SymTable(HashMap::<String, Symbol>::new(), 0)
|
||||
SymTable(QuickMap::<Symbol>::new(), 0)
|
||||
}
|
||||
|
||||
pub fn get(&self, arg: &String) -> Option<&Symbol> {
|
||||
|
|
@ -97,33 +103,30 @@ impl SymTable {
|
|||
self.0.remove(arg)
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> std::collections::hash_map::Iter<'_, String, Symbol> {
|
||||
pub fn iter(&self) -> QuickMapIter<'_, Symbol>{
|
||||
self.0.iter()
|
||||
}
|
||||
|
||||
pub fn keys(&self) -> std::collections::hash_map::Keys<String, Symbol> {
|
||||
self.0.keys()
|
||||
}
|
||||
|
||||
pub fn update(&mut self, other: &mut SymTable) {
|
||||
/* updates self with all syms in other that match the following cases:
|
||||
* * sym is not in self
|
||||
* * sym has a newer generation than the entry in self
|
||||
*
|
||||
* TODO: Write a method for QuickMap for update in place
|
||||
* so that none of these need to be reallocated
|
||||
*/
|
||||
let tmp = self.1;
|
||||
for i in other.iter() {
|
||||
self.0.entry(i.0.to_string())
|
||||
.and_modify(|inner: &mut Symbol| {
|
||||
if tmp < i.1.__generation {
|
||||
inner.__generation = i.1.__generation;
|
||||
inner.value = i.1.value.clone();
|
||||
inner.args = i.1.args.clone();
|
||||
inner.docs = i.1.docs.clone();
|
||||
inner.conditional_branches = i.1.conditional_branches;
|
||||
inner.name = i.1.name.clone();
|
||||
}
|
||||
})
|
||||
.or_insert(i.1.clone());
|
||||
let s = self.0
|
||||
.remove(&i.0)
|
||||
.map_or(
|
||||
i.1.clone(),
|
||||
|existing| if tmp < i.1.__generation {
|
||||
i.1.clone()
|
||||
} else {
|
||||
existing
|
||||
});
|
||||
self.0.insert(i.0.to_string(), s);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue