1
//! Money and integral Scalar globals are carried across units as typed
2
//! constants (PERSIST P4).
3

            
4
use nomiscript::{Compiler, HostFnSpec, Reader, SymbolTable, WasmType};
5
use uuid::Uuid;
6
use wasmtime::{Caller, Linker, Store, Val};
7

            
8
use super::*;
9

            
10
const USD: u128 = 0x1111_1111_1111_1111_2222_2222_2222_2222;
11

            
12
54
fn specs() -> Vec<HostFnSpec> {
13
54
    vec![
14
54
        HostFnSpec::new("usd", "test", "usd").returns(WasmType::Commodity),
15
54
        HostFnSpec::new("sc", "test", "sc").returns(WasmType::Ratio),
16
54
        HostFnSpec::new("idx", "test", "idx").returns(WasmType::I32),
17
    ]
18
54
}
19

            
20
41
async fn run_unit(symbols: &mut SymbolTable, source: &str) -> Result<EvalValue, String> {
21
41
    let program = Reader::parse(source).unwrap();
22
41
    let (bytes, result_ty) = Compiler::with_host_fns(specs())
23
41
        .compile_eval_with_type(&program, symbols)
24
4
        .map_err(|e| e.to_string())?;
25
37
    let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
26
37
    let module = compile_module(&engine, &bytes).map_err(|e| format!("{e:?}"))?;
27
37
    let mut linker: Linker<()> = Linker::new(&engine);
28
37
    linker
29
37
        .func_wrap_async("test", "usd", |mut caller: Caller<'_, ()>, ()| {
30
17
            Box::new(async move {
31
                Ok(Some(
32
17
                    alloc_commodity_ref(&mut caller, 3, 1, Uuid::from_u128(USD)).await?,
33
                ))
34
17
            })
35
17
        })
36
        .unwrap();
37
37
    linker
38
37
        .func_wrap("test", "sc", |mut caller: Caller<'_, ()>| {
39
4
            alloc_ratio_ref(&mut caller, 2, 1).map(Some)
40
4
        })
41
        .unwrap();
42
37
    linker.func_wrap("test", "idx", || 4i32).unwrap();
43
37
    linker.define_unknown_imports_as_traps(&module).unwrap();
44
37
    let mut store: Store<()> = Store::new(&engine, ());
45
37
    store.set_fuel(1_000_000_000).unwrap();
46
37
    store.set_epoch_deadline(1);
47
37
    let instance = linker
48
37
        .instantiate_async(&mut store, &module)
49
37
        .await
50
        .map_err(|e| format!("{e:?}"))?;
51
37
    let func = instance.get_func(&mut store, "nomi-eval").unwrap();
52
37
    let mut results = [Val::AnyRef(None)];
53
37
    func.call_async(&mut store, &[], &mut results)
54
37
        .await
55
        .map_err(|e| e.to_string())?;
56
37
    carry_globals(&mut store, &instance, symbols, UnitEnd::Returned);
57
37
    let Val::AnyRef(any) = results[0] else {
58
        return Err("nomi-eval returned non-anyref".to_string());
59
    };
60
37
    let handles = resolve_type_handles(&mut store, &instance).map_err(|e| e.to_string())?;
61
37
    decode_eval_result(&mut store, any, result_ty, &handles).map_err(|e| e.to_string())
62
41
}
63

            
64
13
pub(super) async fn units(sources: &[&str]) -> Vec<Result<EvalValue, String>> {
65
13
    let mut symbols = SymbolTable::with_builtins();
66
13
    symbols.register_host_fns(&specs());
67
13
    let mut outcomes = Vec::new();
68
13
    for source in sources {
69
41
        outcomes.push(run_unit(&mut symbols, source).await);
70
    }
71
13
    outcomes
72
13
}
73

            
74
10
pub(super) fn money(numer: i64, denom: i64) -> Result<EvalValue, String> {
75
10
    let (hi, lo) = Uuid::from_u128(USD).as_u64_pair();
76
10
    Ok(EvalValue::Commodity {
77
10
        numer,
78
10
        denom,
79
10
        commodity_hi: hi as i64,
80
10
        commodity_lo: lo as i64,
81
10
    })
82
10
}
83

            
84
#[tokio::test(flavor = "current_thread")]
85
1
async fn a_money_global_is_read_and_used_by_the_next_unit() {
86
1
    let outcomes = units(&[
87
1
        "(defvar m (usd))",
88
1
        "(+ m m)",
89
1
        "(* m 1/2)",
90
1
        "(< m (+ m m))",
91
1
        "(list m m)",
92
1
    ])
93
1
    .await;
94
1
    assert_eq!(outcomes[0], Ok(EvalValue::Nil));
95
1
    assert_eq!(outcomes[1], money(6, 1));
96
1
    assert_eq!(outcomes[2], money(3, 2));
97
1
    assert_eq!(outcomes[3], Ok(EvalValue::T));
98
1
    assert_eq!(
99
1
        outcomes[4],
100
1
        Ok(EvalValue::List(vec![
101
1
            money(3, 1).unwrap(),
102
1
            money(3, 1).unwrap()
103
1
        ]))
104
1
    );
105
1
}
106

            
107
#[tokio::test(flavor = "current_thread")]
108
1
async fn compound_money_is_loud_in_the_next_unit() {
109
1
    let outcomes = units(&["(defvar c (* (usd) (usd)))", "c"]).await;
110
1
    assert_eq!(
111
1
        outcomes[1],
112
1
        Err("Compile error: C: its money value does not survive the form".to_string())
113
1
    );
114
1
}
115

            
116
#[tokio::test(flavor = "current_thread")]
117
1
async fn a_list_of_money_is_carried() {
118
1
    let outcomes = units(&["(defvar l (list (usd) (usd)))", "(car l)", "(length l)"]).await;
119
1
    assert_eq!(outcomes[1], money(3, 1));
120
1
    assert_eq!(outcomes[2], Ok(EvalValue::I32(2)));
121
1
}
122

            
123
#[tokio::test(flavor = "current_thread")]
124
1
async fn a_list_holding_compound_money_is_loud() {
125
1
    let outcomes = units(&["(defvar l (list (* (usd) (usd))))", "l"]).await;
126
1
    assert_eq!(
127
1
        outcomes[1],
128
1
        Err("Compile error: L: its list value does not survive the form".to_string())
129
1
    );
130
1
}
131

            
132
#[tokio::test(flavor = "current_thread")]
133
1
async fn a_carried_money_is_read_inside_a_lambda_body() {
134
1
    let outcomes = units(&[
135
1
        "(defvar m (usd))",
136
1
        "(defvar l (list (usd) (usd)))",
137
1
        "(map (lambda (x) (+ x m)) l)",
138
1
    ])
139
1
    .await;
140
1
    assert_eq!(
141
1
        outcomes[2],
142
1
        Ok(EvalValue::List(vec![
143
1
            money(6, 1).unwrap(),
144
1
            money(6, 1).unwrap()
145
1
        ]))
146
1
    );
147
1
}
148

            
149
#[tokio::test(flavor = "current_thread")]
150
1
async fn an_integral_scalar_is_read_in_the_next_unit_with_its_dimension() {
151
1
    let outcomes = units(&[
152
1
        "(defvar x (sc))",
153
1
        "(< x 3/1)",
154
1
        "(= x 2/1)",
155
1
        "(> x 1/2)",
156
1
        "(map (lambda (y) (+ y x)) (list 1/2 3/2))",
157
1
        "(let ((z x)) (/ z 4/1))",
158
1
        "(eq x 2/1)",
159
1
        "(eql x 2/1)",
160
1
        "(equal x 2/1)",
161
1
    ])
162
1
    .await;
163
3
    let ratio = |numer, denom| Ok(EvalValue::Ratio { numer, denom });
164
1
    assert_eq!(outcomes[1], Ok(EvalValue::T));
165
1
    assert_eq!(outcomes[2], Ok(EvalValue::T));
166
1
    assert_eq!(outcomes[3], Ok(EvalValue::T));
167
1
    assert_eq!(
168
1
        outcomes[4],
169
1
        Ok(EvalValue::List(vec![
170
1
            ratio(5, 2).unwrap(),
171
1
            ratio(7, 2).unwrap()
172
1
        ]))
173
    );
174
1
    assert_eq!(outcomes[5], ratio(1, 2));
175
1
    for outcome in &outcomes[6..] {
176
3
        assert_eq!(outcome, &Ok(EvalValue::T));
177
1
    }
178
1
}
179

            
180
#[tokio::test(flavor = "current_thread")]
181
1
async fn a_list_holding_an_integral_scalar_is_carried() {
182
1
    let outcomes = units(&[
183
1
        "(defvar l (list (sc) 1/2))",
184
1
        "(+ (car l) 1/2)",
185
1
        "(defvar k (list (sc) (sc)))",
186
1
        "(+ (car k) 1/2)",
187
1
    ])
188
1
    .await;
189
1
    assert_eq!(outcomes[1], Ok(EvalValue::Ratio { numer: 5, denom: 2 }));
190
1
    assert_eq!(outcomes[3], Ok(EvalValue::Ratio { numer: 5, denom: 2 }));
191
1
}
192

            
193
#[tokio::test(flavor = "current_thread")]
194
1
async fn a_runtime_value_stored_to_an_undefined_name_is_carried() {
195
1
    let outcomes = units(&["(setf n (idx))", "n"]).await;
196
1
    assert_eq!(outcomes[1], Ok(EvalValue::I32(4)));
197
1
}
198

            
199
#[tokio::test(flavor = "current_thread")]
200
1
async fn a_store_of_money_into_an_earlier_global_is_carried() {
201
1
    let outcomes = units(&["(defvar m 1)", "(setf m (usd))", "m"]).await;
202
1
    assert_eq!(outcomes[2], money(3, 1));
203
1
}