Lines
98.16 %
Functions
85.29 %
Branches
100 %
//! Money and integral Scalar globals are carried across units as typed
//! constants (PERSIST P4).
use nomiscript::{Compiler, HostFnSpec, Reader, SymbolTable, WasmType};
use uuid::Uuid;
use wasmtime::{Caller, Linker, Store, Val};
use super::*;
const USD: u128 = 0x1111_1111_1111_1111_2222_2222_2222_2222;
fn specs() -> Vec<HostFnSpec> {
vec![
HostFnSpec::new("usd", "test", "usd").returns(WasmType::Commodity),
HostFnSpec::new("sc", "test", "sc").returns(WasmType::Ratio),
HostFnSpec::new("idx", "test", "idx").returns(WasmType::I32),
]
}
async fn run_unit(symbols: &mut SymbolTable, source: &str) -> Result<EvalValue, String> {
let program = Reader::parse(source).unwrap();
let (bytes, result_ty) = Compiler::with_host_fns(specs())
.compile_eval_with_type(&program, symbols)
.map_err(|e| e.to_string())?;
let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
let module = compile_module(&engine, &bytes).map_err(|e| format!("{e:?}"))?;
let mut linker: Linker<()> = Linker::new(&engine);
linker
.func_wrap_async("test", "usd", |mut caller: Caller<'_, ()>, ()| {
Box::new(async move {
Ok(Some(
alloc_commodity_ref(&mut caller, 3, 1, Uuid::from_u128(USD)).await?,
))
})
.unwrap();
.func_wrap("test", "sc", |mut caller: Caller<'_, ()>| {
alloc_ratio_ref(&mut caller, 2, 1).map(Some)
linker.func_wrap("test", "idx", || 4i32).unwrap();
linker.define_unknown_imports_as_traps(&module).unwrap();
let mut store: Store<()> = Store::new(&engine, ());
store.set_fuel(1_000_000_000).unwrap();
store.set_epoch_deadline(1);
let instance = linker
.instantiate_async(&mut store, &module)
.await
.map_err(|e| format!("{e:?}"))?;
let func = instance.get_func(&mut store, "nomi-eval").unwrap();
let mut results = [Val::AnyRef(None)];
func.call_async(&mut store, &[], &mut results)
carry_globals(&mut store, &instance, symbols, UnitEnd::Returned);
let Val::AnyRef(any) = results[0] else {
return Err("nomi-eval returned non-anyref".to_string());
};
let handles = resolve_type_handles(&mut store, &instance).map_err(|e| e.to_string())?;
decode_eval_result(&mut store, any, result_ty, &handles).map_err(|e| e.to_string())
pub(super) async fn units(sources: &[&str]) -> Vec<Result<EvalValue, String>> {
let mut symbols = SymbolTable::with_builtins();
symbols.register_host_fns(&specs());
let mut outcomes = Vec::new();
for source in sources {
outcomes.push(run_unit(&mut symbols, source).await);
outcomes
pub(super) fn money(numer: i64, denom: i64) -> Result<EvalValue, String> {
let (hi, lo) = Uuid::from_u128(USD).as_u64_pair();
Ok(EvalValue::Commodity {
numer,
denom,
commodity_hi: hi as i64,
commodity_lo: lo as i64,
#[tokio::test(flavor = "current_thread")]
async fn a_money_global_is_read_and_used_by_the_next_unit() {
let outcomes = units(&[
"(defvar m (usd))",
"(+ m m)",
"(* m 1/2)",
"(< m (+ m m))",
"(list m m)",
])
.await;
assert_eq!(outcomes[0], Ok(EvalValue::Nil));
assert_eq!(outcomes[1], money(6, 1));
assert_eq!(outcomes[2], money(3, 2));
assert_eq!(outcomes[3], Ok(EvalValue::T));
assert_eq!(
outcomes[4],
Ok(EvalValue::List(vec![
money(3, 1).unwrap(),
money(3, 1).unwrap()
]))
);
async fn compound_money_is_loud_in_the_next_unit() {
let outcomes = units(&["(defvar c (* (usd) (usd)))", "c"]).await;
outcomes[1],
Err("Compile error: C: its money value does not survive the form".to_string())
async fn a_list_of_money_is_carried() {
let outcomes = units(&["(defvar l (list (usd) (usd)))", "(car l)", "(length l)"]).await;
assert_eq!(outcomes[1], money(3, 1));
assert_eq!(outcomes[2], Ok(EvalValue::I32(2)));
async fn a_list_holding_compound_money_is_loud() {
let outcomes = units(&["(defvar l (list (* (usd) (usd))))", "l"]).await;
Err("Compile error: L: its list value does not survive the form".to_string())
async fn a_carried_money_is_read_inside_a_lambda_body() {
"(defvar l (list (usd) (usd)))",
"(map (lambda (x) (+ x m)) l)",
outcomes[2],
money(6, 1).unwrap(),
money(6, 1).unwrap()
async fn an_integral_scalar_is_read_in_the_next_unit_with_its_dimension() {
"(defvar x (sc))",
"(< x 3/1)",
"(= x 2/1)",
"(> x 1/2)",
"(map (lambda (y) (+ y x)) (list 1/2 3/2))",
"(let ((z x)) (/ z 4/1))",
"(eq x 2/1)",
"(eql x 2/1)",
"(equal x 2/1)",
let ratio = |numer, denom| Ok(EvalValue::Ratio { numer, denom });
assert_eq!(outcomes[1], Ok(EvalValue::T));
assert_eq!(outcomes[2], Ok(EvalValue::T));
ratio(5, 2).unwrap(),
ratio(7, 2).unwrap()
assert_eq!(outcomes[5], ratio(1, 2));
for outcome in &outcomes[6..] {
assert_eq!(outcome, &Ok(EvalValue::T));
async fn a_list_holding_an_integral_scalar_is_carried() {
"(defvar l (list (sc) 1/2))",
"(+ (car l) 1/2)",
"(defvar k (list (sc) (sc)))",
"(+ (car k) 1/2)",
assert_eq!(outcomes[1], Ok(EvalValue::Ratio { numer: 5, denom: 2 }));
assert_eq!(outcomes[3], Ok(EvalValue::Ratio { numer: 5, denom: 2 }));
async fn a_runtime_value_stored_to_an_undefined_name_is_carried() {
let outcomes = units(&["(setf n (idx))", "n"]).await;
assert_eq!(outcomes[1], Ok(EvalValue::I32(4)));
async fn a_store_of_money_into_an_earlier_global_is_carried() {
let outcomes = units(&["(defvar m 1)", "(setf m (usd))", "m"]).await;
assert_eq!(outcomes[2], money(3, 1));