1
//! Struct instances a global holds are carried with their identity (rstruct S5).
2

            
3
use nomiscript::{CompileMode, Compiler, Expr, Number, Reader, StructInstance, SymbolTable};
4
use wasmtime::{Instance, Linker, Store, Val};
5

            
6
use crate::runtime::heap::{MAX_REACHED, settle_heap};
7
use crate::runtime::{
8
    EngineOpts, UnitEnd, build_engine, carry_globals, carry_not_run, compile_module,
9
    resolve_type_handles,
10
};
11

            
12
35
fn compile(symbols: &mut SymbolTable, source: &str) -> Result<Vec<u8>, String> {
13
35
    let program = Reader::parse(source).map_err(|err| err.to_string())?;
14
35
    Compiler::new()
15
35
        .compile_with_mode(&program, symbols, CompileMode::Eval)
16
3
        .map_err(|err| err.to_string())
17
35
}
18

            
19
32
fn instantiate(bytes: &[u8]) -> (Store<()>, Instance) {
20
32
    let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
21
32
    let module = compile_module(&engine, bytes).unwrap();
22
32
    let mut linker: Linker<()> = Linker::new(&engine);
23
32
    linker.define_unknown_imports_as_traps(&module).unwrap();
24
32
    let mut store: Store<()> = Store::new(&engine, ());
25
32
    store.set_fuel(10_000_000).unwrap();
26
32
    store.set_epoch_deadline(1);
27
32
    let instance = linker.instantiate(&mut store, &module).unwrap();
28
32
    (store, instance)
29
32
}
30

            
31
/// Compiles, runs and carries one unit, then reads its heap again within
32
/// `ceiling` objects; the compile error when it has one.
33
33
fn run_within(symbols: &mut SymbolTable, source: &str, ceiling: usize) -> Result<(), String> {
34
33
    let bytes = compile(symbols, source).inspect_err(|_| carry_not_run(symbols))?;
35
30
    let (mut store, instance) = instantiate(&bytes);
36
30
    let main = instance.get_func(&mut store, "nomi-eval").unwrap();
37
30
    let result = main.call(&mut store, &[], &mut [Val::AnyRef(None)]);
38
30
    let end = result
39
30
        .as_ref()
40
30
        .err()
41
30
        .map_or(UnitEnd::Returned, UnitEnd::of_failure);
42
30
    carry_globals(&mut store, &instance, symbols, end);
43
30
    let handles = resolve_type_handles(&mut store, &instance).ok();
44
30
    settle_heap(&mut store, &instance, symbols, handles.as_ref(), ceiling);
45
30
    Ok(())
46
33
}
47

            
48
32
fn run(symbols: &mut SymbolTable, source: &str) -> Result<(), String> {
49
32
    run_within(symbols, source, MAX_REACHED)
50
32
}
51

            
52
11
fn number(n: i64) -> Expr {
53
11
    Expr::Number(Number::Index(n))
54
11
}
55

            
56
15
fn heap(symbols: &SymbolTable) -> Vec<(u32, StructInstance)> {
57
15
    symbols
58
15
        .instances()
59
16
        .map(|(serial, instance)| (serial, instance.clone()))
60
        .collect()
61
15
}
62

            
63
11
fn pt(symbols: &mut SymbolTable, x: Expr) -> StructInstance {
64
11
    let layout = symbols.define_struct("PT", vec!["X".to_string()]).unwrap();
65
11
    StructInstance {
66
11
        layout,
67
11
        fields: vec![x],
68
11
    }
69
11
}
70

            
71
11
fn session() -> SymbolTable {
72
11
    let mut symbols = SymbolTable::with_builtins();
73
11
    run(&mut symbols, "(defstruct pt x)").unwrap();
74
11
    symbols
75
11
}
76

            
77
#[test]
78
1
fn an_instance_a_global_holds_enters_the_heap_with_a_serial_past_the_last() {
79
1
    let mut symbols = session();
80
1
    run(&mut symbols, "(defvar *a* (make-pt :x 1))").unwrap();
81
1
    assert_eq!(heap(&symbols), [(0, pt(&mut symbols, number(1)))]);
82
1
    assert_eq!(symbols.next_serial(), 1);
83
1
    run(&mut symbols, "(defvar *b* (make-pt :x 2))").unwrap();
84
1
    assert_eq!(
85
1
        heap(&symbols),
86
1
        [
87
1
            (0, pt(&mut symbols, number(1))),
88
1
            (1, pt(&mut symbols, number(2)))
89
1
        ]
90
    );
91
1
    assert_eq!(symbols.next_serial(), 2);
92
1
}
93

            
94
#[test]
95
1
fn an_instance_no_global_holds_any_more_is_swept_and_its_serial_not_reused() {
96
1
    let mut symbols = session();
97
1
    run(
98
1
        &mut symbols,
99
1
        "(defvar *a* (make-pt :x 1)) (defvar *b* (make-pt :x 2))",
100
1
    )
101
1
    .unwrap();
102
1
    run(&mut symbols, "(setf *a* nil)").unwrap();
103
1
    assert_eq!(heap(&symbols), [(1, pt(&mut symbols, number(2)))]);
104
1
    run(&mut symbols, "(defvar *c* (make-pt :x 3))").unwrap();
105
1
    assert_eq!(
106
1
        heap(&symbols),
107
1
        [
108
1
            (1, pt(&mut symbols, number(2))),
109
1
            (2, pt(&mut symbols, number(3)))
110
1
        ]
111
    );
112
1
}
113

            
114
#[test]
115
1
fn a_mutation_through_a_global_the_unit_never_wrote_is_read_back() {
116
1
    let mut symbols = session();
117
1
    run(&mut symbols, "(defvar *a* (make-pt :x 1))").unwrap();
118
1
    run(&mut symbols, "(setf (pt-x *a*) 9)").unwrap();
119
1
    assert_eq!(heap(&symbols), [(0, pt(&mut symbols, number(9)))]);
120
1
}
121

            
122
#[test]
123
1
fn a_trapped_unit_keeps_the_mutations_it_made_first() {
124
1
    let mut symbols = session();
125
1
    run(&mut symbols, "(defvar *a* (make-pt :x 1))").unwrap();
126
1
    run(
127
1
        &mut symbols,
128
1
        "(setf (pt-x *a*) 5) (do ((i 0 (+ i 1))) ((> i 1073741823) i))",
129
1
    )
130
1
    .unwrap();
131
1
    assert_eq!(heap(&symbols), [(0, pt(&mut symbols, number(5)))]);
132
1
}
133

            
134
#[test]
135
1
fn a_cycle_is_carried_as_an_instance_holding_itself() {
136
1
    let mut symbols = session();
137
1
    run(&mut symbols, "(defstruct box p) (defvar *c* (make-box))").unwrap();
138
1
    run(&mut symbols, "(setf (box-p *c*) *c*)").unwrap();
139
1
    let found = heap(&symbols);
140
1
    assert_eq!(found.len(), 1);
141
1
    let layout = symbols.define_struct("BOX", vec!["P".to_string()]).unwrap();
142
1
    assert_eq!(found[0].1.fields, [Expr::Instance(found[0].0, layout)]);
143
1
}
144

            
145
#[test]
146
1
fn an_instance_holding_a_closure_is_opaque_and_so_is_its_global() {
147
1
    let mut symbols = session();
148
1
    run(&mut symbols, "(defvar *a* (make-pt :x 1))").unwrap();
149
1
    run(&mut symbols, "(setf (pt-x *a*) (lambda () 1))").unwrap();
150
1
    assert_eq!(heap(&symbols), []);
151
1
    assert_eq!(
152
1
        run(&mut symbols, "*a*").unwrap_err(),
153
1
        "Compile error: *A*: its struct value does not survive the form"
154
    );
155
1
}
156

            
157
#[test]
158
1
fn a_unit_that_fails_to_compile_leaves_the_heap_as_it_was() {
159
1
    let mut symbols = session();
160
1
    run(&mut symbols, "(defvar *a* (make-pt :x 1))").unwrap();
161
1
    let before = heap(&symbols);
162
1
    run(
163
1
        &mut symbols,
164
1
        "(setf (pt-x *a*) 2) (undefined-function-here)",
165
1
    )
166
1
    .unwrap_err();
167
1
    assert_eq!(heap(&symbols), before);
168
1
    assert_eq!(symbols.next_serial(), 1);
169
1
}
170

            
171
#[test]
172
1
fn a_closure_cell_cycle_leaves_the_instances_beside_it_readable() {
173
1
    let mut symbols = session();
174
1
    run(&mut symbols, "(defvar *p* (make-pt :x 1))").unwrap();
175
1
    run(
176
1
        &mut symbols,
177
1
        "(defvar *h* (let ((g (lambda () 0))) (setf g (lambda () (funcall g))) g))",
178
1
    )
179
1
    .unwrap();
180
1
    assert_eq!(heap(&symbols), [(0, pt(&mut symbols, number(1)))]);
181
1
}
182

            
183
#[test]
184
1
fn a_heap_past_the_ceiling_loses_only_the_instances_it_did_not_reach() {
185
1
    let mut symbols = session();
186
40
    let items = (0..40).map(|n| n.to_string()).collect::<Vec<_>>().join(" ");
187
1
    run_within(
188
1
        &mut symbols,
189
1
        &format!("(defvar *a* (list {items} (make-pt :x 2))) (defvar *z* (make-pt :x 1))"),
190
1
        10,
191
1
    )
192
1
    .unwrap();
193
1
    assert_eq!(heap(&symbols), [(1, pt(&mut symbols, number(1)))]);
194
1
    assert_eq!(
195
1
        run(&mut symbols, "*a*").unwrap_err(),
196
1
        "Compile error: *A*: its struct value does not survive the form"
197
    );
198
1
}
199

            
200
#[test]
201
1
fn a_unit_whose_prologue_never_finished_leaves_the_heap_as_it_was() {
202
1
    let mut symbols = session();
203
1
    run(&mut symbols, "(defvar *a* (make-pt :x 1))").unwrap();
204
1
    let before = heap(&symbols);
205
1
    let bytes = compile(&mut symbols, "(setf (pt-x *a*) 5)").unwrap();
206
1
    let (mut store, instance) = instantiate(&bytes);
207
1
    carry_globals(&mut store, &instance, &mut symbols, UnitEnd::Trapped);
208
1
    assert_eq!(heap(&symbols), before);
209
1
    assert_eq!(symbols.next_serial(), 1);
210
1
}
211

            
212
#[test]
213
1
fn a_unit_whose_prologue_finished_settles_the_heap() {
214
1
    let mut symbols = session();
215
1
    run(&mut symbols, "(defvar *a* (make-pt :x 1))").unwrap();
216
1
    let bytes = compile(&mut symbols, "(setf (pt-x *a*) 5)").unwrap();
217
1
    let (mut store, instance) = instantiate(&bytes);
218
1
    let main = instance.get_func(&mut store, "nomi-eval").unwrap();
219
1
    main.call(&mut store, &[], &mut [Val::AnyRef(None)])
220
1
        .unwrap();
221
1
    carry_globals(&mut store, &instance, &mut symbols, UnitEnd::Returned);
222
1
    assert_eq!(heap(&symbols), [(0, pt(&mut symbols, number(5)))]);
223
1
}