1
//! A `DEFSTRUCT` instance on the host: the shape the guest builds, how a
2
//! result or a list cell holding one decodes, and that carry never reads one
3
//! back stale.
4

            
5
use crate::checked_ref::CheckedAnyRef;
6
use nomiscript::{Compiler, Expr, Number, Program, SymbolTable, WasmType};
7
use wasmtime::{Instance, Linker, Store};
8

            
9
use super::*;
10

            
11
34
fn number(n: i64) -> Expr {
12
34
    Expr::Number(Number::Index(n))
13
34
}
14

            
15
25
fn call(head: &str, args: Vec<Expr>) -> Expr {
16
25
    let mut form = vec![Expr::symbol(head)];
17
25
    form.extend(args);
18
25
    Expr::List(form)
19
25
}
20

            
21
13
fn new_pt(id: u32, x: i64) -> Expr {
22
13
    call("(STRUCT-NEW)", vec![number(i64::from(id)), number(x)])
23
13
}
24

            
25
5
fn instance(serial: u32, layout: u32) -> EvalValue {
26
5
    EvalValue::Instance { serial, layout }
27
5
}
28

            
29
9
fn pt_symbols() -> (SymbolTable, u32) {
30
9
    let mut symbols = SymbolTable::with_builtins();
31
9
    let id = symbols
32
9
        .define_struct("PT", vec!["X".to_string()])
33
9
        .expect("PT defines");
34
9
    (symbols, id.0)
35
9
}
36

            
37
struct Ran {
38
    store: Store<()>,
39
    instance: Instance,
40
    result: Option<Rooted<AnyRef>>,
41
    result_ty: Option<WasmType>,
42
}
43

            
44
12
async fn run(symbols: &mut SymbolTable, forms: Vec<Expr>) -> Result<Ran, String> {
45
12
    let (bytes, result_ty) = Compiler::new()
46
12
        .compile_eval_with_type(&Program::new(forms), symbols)
47
        .map_err(|e| e.to_string())?;
48
12
    let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
49
12
    let module = compile_module(&engine, &bytes).map_err(|e| format!("{e:?}"))?;
50
12
    let mut linker: Linker<()> = Linker::new(&engine);
51
12
    linker.define_unknown_imports_as_traps(&module).unwrap();
52
12
    let mut store: Store<()> = Store::new(&engine, ());
53
12
    store.set_fuel(1_000_000_000).unwrap();
54
12
    store.set_epoch_deadline(1);
55
12
    let instance = linker
56
12
        .instantiate_async(&mut store, &module)
57
12
        .await
58
        .map_err(|e| format!("{e:?}"))?;
59
12
    let func = instance.get_func(&mut store, "nomi-eval").unwrap();
60
12
    let mut results = [Val::AnyRef(None)];
61
12
    func.call_async(&mut store, &[], &mut results)
62
12
        .await
63
        .map_err(|e| e.to_string())?;
64
12
    carry_globals(&mut store, &instance, symbols, UnitEnd::Returned);
65
12
    let Val::AnyRef(result) = results[0] else {
66
        return Err("nomi-eval returned non-anyref".to_string());
67
    };
68
12
    Ok(Ran {
69
12
        store,
70
12
        instance,
71
12
        result,
72
12
        result_ty,
73
12
    })
74
12
}
75

            
76
5
async fn decoded(symbols: &mut SymbolTable, forms: Vec<Expr>) -> Result<EvalValue, String> {
77
5
    let mut ran = run(symbols, forms).await?;
78
5
    let handles = resolve_type_handles(&mut ran.store, &ran.instance).map_err(|e| e.to_string())?;
79
5
    let (Some(any), Some(ty)) = (ran.result, ran.result_ty) else {
80
1
        return Ok(EvalValue::Nil);
81
    };
82
4
    decode_anyref(
83
4
        &mut ran.store,
84
4
        any,
85
4
        ty,
86
4
        &handles,
87
4
        structure::InstanceMode::Identity,
88
4
    )
89
    .map_err(|e| e.to_string())
90
5
}
91

            
92
2
async fn sent(symbols: &mut SymbolTable, forms: Vec<Expr>) -> Result<EvalValue, String> {
93
2
    let mut ran = run(symbols, forms).await?;
94
2
    let handles = resolve_type_handles(&mut ran.store, &ran.instance).map_err(|e| e.to_string())?;
95
2
    decode_eval_result(&mut ran.store, ran.result, ran.result_ty, &handles)
96
        .map_err(|e| e.to_string())
97
2
}
98

            
99
#[tokio::test(flavor = "current_thread")]
100
1
async fn an_instance_result_decodes_by_its_identity() {
101
1
    let (mut symbols, pt) = pt_symbols();
102
1
    let outcome = decoded(&mut symbols, vec![new_pt(pt, 1)]).await;
103
1
    assert_eq!(outcome, Ok(instance(0, pt)));
104
1
}
105

            
106
#[tokio::test(flavor = "current_thread")]
107
1
async fn an_instance_in_a_list_cell_decodes_by_its_identity() {
108
1
    let (mut symbols, pt) = pt_symbols();
109
1
    let typed = call("LIST", vec![new_pt(pt, 1), new_pt(pt, 2)]);
110
1
    let mixed = call("LIST", vec![new_pt(pt, 1), number(7)]);
111
1
    assert_eq!(
112
1
        decoded(&mut symbols, vec![typed]).await,
113
1
        Ok(EvalValue::List(vec![instance(0, pt), instance(1, pt)]))
114
    );
115
1
    assert_eq!(
116
1
        decoded(&mut symbols, vec![mixed]).await,
117
1
        Ok(EvalValue::List(vec![instance(0, pt), EvalValue::I32(7)]))
118
1
    );
119
1
}
120

            
121
#[tokio::test(flavor = "current_thread")]
122
1
async fn the_host_classifies_an_instance_by_its_shape() {
123
1
    let (mut symbols, pt) = pt_symbols();
124
1
    let form = call("LIST", vec![new_pt(pt, 1), number(7)]);
125
1
    let mut ran = run(&mut symbols, vec![form]).await.unwrap();
126
1
    let handles = resolve_type_handles(&mut ran.store, &ran.instance).unwrap();
127
1
    let head = ran.result.unwrap().checked_struct(&mut ran.store).unwrap();
128
1
    let Val::AnyRef(Some(car)) = head.field(&mut ran.store, 0).unwrap() else {
129
        panic!("the car is not an anyref");
130
    };
131
1
    let kind = classify_anyref(&mut ran.store, car, &handles).unwrap();
132
1
    assert!(matches!(kind, AnyRefKind::Struct));
133
1
}
134

            
135
#[tokio::test(flavor = "current_thread")]
136
1
async fn an_instance_is_serial_numbered_and_shares_its_layout() {
137
1
    let (mut symbols, pt) = pt_symbols();
138
1
    let form = call("LIST", vec![new_pt(pt, 1), new_pt(pt, 2)]);
139
1
    let mut ran = run(&mut symbols, vec![form]).await.unwrap();
140
1
    let store = &mut ran.store;
141
1
    let mut cell = Some(ran.result.unwrap().checked_struct(&mut *store).unwrap());
142
1
    let mut serials = Vec::new();
143
1
    let mut layouts = Vec::new();
144
3
    while let Some(node) = cell {
145
2
        let Val::AnyRef(Some(car)) = node.field(&mut *store, 0).unwrap() else {
146
            panic!("the car is not an anyref");
147
        };
148
2
        let instance = car.checked_struct(&mut *store).unwrap();
149
2
        serials.push(instance.field(&mut *store, 0).unwrap().i32().unwrap());
150
2
        let Val::AnyRef(Some(layout)) = instance.field(&mut *store, 1).unwrap() else {
151
            panic!("the layout is not an anyref");
152
        };
153
2
        layouts.push(layout);
154
2
        cell = match node.field(&mut *store, 1).unwrap() {
155
1
            Val::AnyRef(Some(next)) => Some(next.checked_struct(&mut *store).unwrap()),
156
1
            _ => None,
157
        };
158
    }
159
1
    assert_eq!(serials, [0, 1]);
160
1
    assert!(Rooted::<AnyRef>::ref_eq(&*store, &layouts[0], &layouts[1]).unwrap());
161
1
    let slots = layouts[0].checked_array(&mut *store).unwrap();
162
1
    assert_eq!(slots.len(&*store).unwrap(), 3);
163
1
    let Val::AnyRef(Some(id)) = slots.get(&mut *store, 0).unwrap() else {
164
        panic!("slot 0 is not an anyref");
165
    };
166
1
    assert_eq!(id.checked_i31(&*store).unwrap().get_i32(), pt as i32);
167
1
    for (slot, name) in [(1, "PT"), (2, ":X")] {
168
2
        let Val::AnyRef(Some(symbol)) = slots.get(&mut *store, slot).unwrap() else {
169
1
            panic!("slot {slot} is not an anyref");
170
1
        };
171
2
        assert_eq!(
172
2
            decode_symbol(&mut *store, &symbol).unwrap(),
173
2
            EvalValue::Symbol(name.to_string())
174
1
        );
175
1
    }
176
1
}
177

            
178
#[tokio::test(flavor = "current_thread")]
179
1
async fn a_carried_instance_is_the_same_instance_in_the_next_unit() {
180
1
    let (mut symbols, pt) = pt_symbols();
181
1
    let defvar = call("DEFVAR", vec![Expr::symbol("*P*"), new_pt(pt, 1)]);
182
1
    decoded(&mut symbols, vec![defvar]).await.unwrap();
183
1
    let outcome = decoded(&mut symbols, vec![Expr::symbol("*P*")]).await;
184
1
    assert_eq!(outcome, Ok(instance(0, pt)));
185
1
}
186

            
187
#[tokio::test(flavor = "current_thread")]
188
1
async fn a_nested_construction_numbers_every_instance_once() {
189
1
    let (mut symbols, pt) = pt_symbols();
190
1
    let boxed = symbols
191
1
        .define_struct("BOX", vec!["P".to_string()])
192
1
        .expect("BOX defines")
193
1
        .0;
194
1
    let outer = call(
195
1
        "(STRUCT-NEW)",
196
1
        vec![number(i64::from(boxed)), new_pt(pt, 1)],
197
1
    );
198
1
    let copy = call(
199
1
        "(STRUCT-COPY)",
200
1
        vec![outer.clone(), number(i64::from(boxed))],
201
1
    );
202
1
    let mut ran = run(&mut symbols, vec![call("LIST", vec![outer, copy])])
203
1
        .await
204
        .unwrap();
205
1
    let store = &mut ran.store;
206
1
    let head = ran.result.unwrap().checked_struct(&mut *store).unwrap();
207
2
    let serial_of = |store: &mut Store<()>, cell: &Rooted<StructRef>| {
208
2
        let Val::AnyRef(Some(car)) = cell.field(&mut *store, 0).unwrap() else {
209
            panic!("the car is not an anyref");
210
        };
211
2
        let instance = car.checked_struct(&mut *store).unwrap();
212
2
        let serial = instance.field(&mut *store, 0).unwrap().i32().unwrap();
213
2
        (serial, instance)
214
2
    };
215
1
    let (first, outer_instance) = serial_of(store, &head);
216
1
    let Val::AnyRef(Some(next)) = head.field(&mut *store, 1).unwrap() else {
217
        panic!("no second cell");
218
    };
219
1
    let second_cell = next.checked_struct(&mut *store).unwrap();
220
1
    let (second, _) = serial_of(store, &second_cell);
221
1
    let values = outer_instance.field(&mut *store, 2).unwrap();
222
1
    let Val::AnyRef(Some(values)) = values else {
223
        panic!("no values");
224
    };
225
1
    let inner = values
226
1
        .checked_array(&mut *store)
227
1
        .unwrap()
228
1
        .get(&mut *store, 0)
229
1
        .unwrap();
230
1
    let Val::AnyRef(Some(inner)) = inner else {
231
        panic!("no inner instance");
232
    };
233
1
    let inner_serial = inner
234
1
        .checked_struct(&mut *store)
235
1
        .unwrap()
236
1
        .field(&mut *store, 0)
237
1
        .unwrap()
238
1
        .i32()
239
1
        .unwrap();
240
1
    assert_eq!([inner_serial, first, second], [0, 1, 4]);
241
1
}
242

            
243
2
async fn viewed(symbols: &mut SymbolTable, forms: Vec<Expr>) -> Result<EvalValue, String> {
244
2
    let mut ran = run(symbols, forms).await?;
245
2
    let handles = resolve_type_handles(&mut ran.store, &ran.instance).map_err(|e| e.to_string())?;
246
2
    let head = ran.result.ok_or("no list result")?;
247
2
    structure::decode_pair(
248
2
        ran.store.as_context_mut(),
249
2
        head,
250
2
        nomiscript::PairElement::AnyRef,
251
2
        &handles,
252
2
        structure::InstanceMode::Contents,
253
2
        0,
254
2
    )
255
    .map_err(|e| e.to_string())
256
2
}
257

            
258
5
fn pt_view(x: i32) -> EvalValue {
259
5
    EvalValue::Struct(Box::new(StructView {
260
5
        name: "PT".to_string(),
261
5
        fields: vec![("X".to_string(), EvalValue::I32(x))],
262
5
    }))
263
5
}
264

            
265
#[tokio::test(flavor = "current_thread")]
266
1
async fn a_list_cell_holding_an_instance_views_its_name_and_fields() {
267
1
    let (mut symbols, pt) = pt_symbols();
268
1
    let mixed = call("LIST", vec![new_pt(pt, 1), number(7)]);
269
1
    assert_eq!(
270
1
        viewed(&mut symbols, vec![mixed]).await,
271
1
        Ok(EvalValue::List(vec![pt_view(1), EvalValue::I32(7)]))
272
1
    );
273
1
}
274

            
275
#[tokio::test(flavor = "current_thread")]
276
1
async fn a_struct_field_holding_an_instance_views_it_nested() {
277
1
    let (mut symbols, pt) = pt_symbols();
278
1
    let boxed = symbols
279
1
        .define_struct("BOX", vec!["P".to_string()])
280
1
        .expect("BOX defines")
281
1
        .0;
282
1
    let outer = call(
283
1
        "(STRUCT-NEW)",
284
1
        vec![number(i64::from(boxed)), new_pt(pt, 2)],
285
1
    );
286
1
    let form = call("LIST", vec![outer, number(7)]);
287
1
    let nested = EvalValue::Struct(Box::new(StructView {
288
1
        name: "BOX".to_string(),
289
1
        fields: vec![("P".to_string(), pt_view(2))],
290
1
    }));
291
1
    assert_eq!(
292
1
        viewed(&mut symbols, vec![form]).await,
293
1
        Ok(EvalValue::List(vec![nested, EvalValue::I32(7)]))
294
1
    );
295
1
}
296

            
297
#[test]
298
1
fn a_viewed_struct_prints_as_common_lisp() {
299
1
    let value = nomiscript::Value::from(EvalValue::List(vec![pt_view(1)]));
300
1
    assert_eq!(nomiscript::format_value(&value), "(#S(PT :X 1))");
301
1
}
302

            
303
#[tokio::test(flavor = "current_thread")]
304
1
async fn an_instance_result_sent_to_a_client_carries_its_name_and_fields() {
305
1
    let (mut symbols, pt) = pt_symbols();
306
1
    let list = call("LIST", vec![new_pt(pt, 1), number(7)]);
307
1
    assert_eq!(
308
1
        sent(&mut symbols, vec![new_pt(pt, 1)]).await,
309
1
        Ok(pt_view(1))
310
    );
311
1
    assert_eq!(
312
1
        sent(&mut symbols, vec![list]).await,
313
1
        Ok(EvalValue::List(vec![pt_view(1), EvalValue::I32(7)]))
314
1
    );
315
1
}