flesh/core/src/stl/boolean.rs
Ava Affine d6a0e68460 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>
2024-07-26 22:29:25 -07:00

223 lines
7.2 KiB
Rust

/* 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 crate::segment::{Ctr, Seg, Type};
use crate::error::{Traceback, start_trace};
use crate::sym::{SymTable, ValueType, Args, Symbol};
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.
starts with arg1 AND arg2, and then calculates prev_result AND next_arg.
returns final result.";
fn and_callback(ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, Traceback> {
let mut type_error = false;
let mut cursor = 0;
let result = ast.circuit(&mut |arg: &Ctr| -> bool {
if let Ctr::Bool(b) = *arg {
cursor += 1;
b
} else {
type_error = true;
false
}
});
if type_error {
Err(start_trace(("and", format!("input {} not a boolean", cursor)).into()))
} else {
Ok(Ctr::Bool(result))
}
}
const OR_DOCSTRING: &str =
"traverses a list of N arguments, all of which are expected to be boolean.
starts with arg1 OR arg2, and then calculates prev_result OR next_arg.
returns final result.";
fn or_callback(ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, Traceback> {
let mut result = false;
let mut cursor = 0;
let correct_types = ast.circuit(&mut |arg: &Ctr| -> bool {
if let Ctr::Bool(b) = *arg {
cursor += 1;
result = result || b;
true
} else {
false
}
});
if !correct_types {
Err(start_trace(("or", format!("input {} not a boolean", cursor)).into()))
} else {
Ok(Ctr::Bool(result))
}
}
const NOT_DOCSTRING: &str = "takes a single argument (expects a boolean).
returns false if arg is true or true if arg is false.";
fn not_callback(ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, Traceback> {
if let Ctr::Bool(b) = *ast.car {
Ok(Ctr::Bool(!b))
} else {
Err(start_trace(("not", "input is not a bool").into()))
}
}
const ISEQ_DOCSTRING: &str = "traverses a list of N arguments.
returns true if all arguments hold the same value.
NOTE: 1 and 1.0 are the same, but '1' 'one' or one (symbol) aren't";
fn iseq_callback(ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, Traceback> {
let head_ctr_ref = &*ast.car;
Ok(Ctr::Bool(
ast.circuit(&mut |arg: &Ctr| -> bool { arg == head_ctr_ref }),
))
}
const TOGGLE_DOCSTRING: &str = "switches a boolean symbol between true or false.
Takes a single argument (a symbol). Looks it up in the variable table.
Either sets the symbol to true if it is currently false, or vice versa.";
fn toggle_callback(ast: &Seg, syms: &mut SymTable) -> Result<Ctr, Traceback> {
let var_name: String;
if let Ctr::Symbol(ref s) = *ast.car {
var_name = s.clone();
} else {
return Err(start_trace(("toggle", "input must be a symbol").into()));
}
let mut sym = syms
.remove(&var_name)
.expect(&format!("symbol {var_name} is not defined"));
if let ValueType::VarForm(ref var) = sym.value {
if let Ctr::Bool(ref b) = **var {
sym.value = ValueType::VarForm(Box::new(Ctr::Bool(!b)));
} else {
syms.insert(var_name, sym);
return Err(start_trace(("toggle", "can only toggle a boolean").into()));
}
} else {
syms.insert(var_name, sym);
return Err(start_trace(("toggle", "cannot toggle a function").into()));
}
syms.insert(var_name, sym);
Ok(Ctr::None)
}
const BOOLCAST_DOCSTRING: &str = "takes one argument of any type.
attempts to cast argument to a bool.
Strings will cast to a bool if they are 'true' or 'false'.
Integers and Floats will cast to true if they are 0 and false otherwise.";
fn boolcast_callback(ast: &Seg, _syms: &mut SymTable) -> Result<Ctr, Traceback> {
match &*ast.car {
Ctr::Bool(_) => Ok(*ast.car.clone()),
Ctr::String(s) => {
if s == "true" {
Ok(Ctr::Bool(true))
} else if s == "false" {
Ok(Ctr::Bool(false))
} else {
Err(start_trace(("bool", "string cannot be parsed as a bool").into()))
}
},
Ctr::Integer(i) => Ok(Ctr::Bool(*i == 0)),
Ctr::Float(f) => Ok(Ctr::Bool(*f == 0.0)),
_ => Err(start_trace(("bool", format!("cannot convert a {} to a boolean",
ast.car.to_type())).into())),
}
}
pub fn add_bool_lib(syms: &mut SymTable) {
syms.insert(
"and".to_string(),
Symbol {
name: String::from("and"),
args: Args::Infinite,
conditional_branches: false,
docs: AND_DOCSTRING.to_string(),
value: ValueType::Internal(Rc::new(and_callback)),
optimizable: true,
..Default::default()
},
);
syms.insert(
"bool".to_string(),
Symbol {
name: String::from("bool"),
args: Args::Infinite,
conditional_branches: false,
docs: BOOLCAST_DOCSTRING.to_string(),
value: ValueType::Internal(Rc::new(boolcast_callback)),
optimizable: true,
..Default::default()
},
);
syms.insert(
"or".to_string(),
Symbol {
name: String::from("or"),
args: Args::Infinite,
conditional_branches: false,
docs: OR_DOCSTRING.to_string(),
value: ValueType::Internal(Rc::new(or_callback)),
optimizable: true,
..Default::default()
},
);
syms.insert(
"not".to_string(),
Symbol {
name: String::from("not"),
args: Args::Strict(vec![Type::Bool]),
conditional_branches: false,
docs: NOT_DOCSTRING.to_string(),
value: ValueType::Internal(Rc::new(not_callback)),
optimizable: true,
..Default::default()
},
);
syms.insert(
"eq?".to_string(),
Symbol {
name: String::from("eq?"),
args: Args::Infinite,
conditional_branches: false,
docs: ISEQ_DOCSTRING.to_string(),
value: ValueType::Internal(Rc::new(iseq_callback)),
optimizable: true,
..Default::default()
},
);
syms.insert(
"toggle".to_string(),
Symbol {
name: String::from("toggle"),
args: Args::Lazy(1),
conditional_branches: true,
docs: TOGGLE_DOCSTRING.to_string(),
value: ValueType::Internal(Rc::new(toggle_callback)),
..Default::default()
},
);
}