1
//! An observation must mean the same thing after the pass that made it is
2
//! rolled back, whatever scope encloses that pass.
3

            
4
use super::{Leaf, Observations, ObservedBlock, StructuralType};
5
use crate::ast::{PairElement, WasmType};
6
use crate::compiler::context::CompileContext;
7
use crate::compiler::recompile::Trial;
8
use crate::compiler::recompile::recompile;
9
use crate::error::{Error, Result};
10
use crate::runtime::SymbolTable;
11

            
12
9
fn setup() -> (CompileContext, SymbolTable) {
13
9
    let ctx = CompileContext::new_with_host_fns(&[]).expect("context");
14
9
    let symbols = SymbolTable::with_builtins_for_wasm();
15
9
    (ctx, symbols)
16
9
}
17

            
18
/// `ratio -> (ratio -> pair<i32>)`
19
10
fn expected() -> StructuralType {
20
10
    StructuralType {
21
10
        arrows: vec![vec![Leaf::Ratio], vec![Leaf::Ratio]],
22
10
        result: Leaf::PairRef(PairElement::I32),
23
10
    }
24
10
}
25

            
26
10
fn nested_block(join: StructuralType) -> ObservedBlock {
27
10
    ObservedBlock {
28
10
        name: "INNER".to_string(),
29
10
        body_len: 2,
30
10
        join,
31
10
    }
32
10
}
33

            
34
/// Mints the closure type and a local holding it, as a pass binding one
35
/// would, and observes it, both as the result and as a nested block's join.
36
6
fn observe(ctx: &mut CompileContext) -> Result<Observations> {
37
    let inner =
38
6
        ctx.intern_closure_signature(&[WasmType::Ratio], WasmType::PairRef(PairElement::I32))?;
39
6
    let outer = ctx.intern_closure_signature(&[WasmType::Ratio], WasmType::Closure(inner))?;
40
6
    ctx.alloc_local(WasmType::Closure(outer))?;
41
6
    let result = StructuralType::of(WasmType::Closure(outer), ctx)?;
42
6
    let start = ctx.block_join_start();
43
6
    ctx.record_block_join(start, nested_block(result.clone()));
44
6
    let blocks = ctx.take_block_joins(start);
45
6
    Ok(Observations { result, blocks })
46
6
}
47

            
48
6
fn discarded_pass(ctx: &mut CompileContext, symbols: &mut SymbolTable) -> Result<Observations> {
49
6
    match recompile(ctx, symbols, |ctx, _| {
50
6
        Ok(Trial::<(), _>::Discard(observe(ctx)?))
51
6
    })? {
52
6
        Trial::Discard(observations) => Ok(observations),
53
        Trial::Commit(()) => panic!("the pass discards"),
54
    }
55
6
}
56

            
57
2
fn in_committed_pass(ctx: &mut CompileContext, symbols: &mut SymbolTable) -> Result<Observations> {
58
2
    match recompile(ctx, symbols, |ctx, symbols| {
59
2
        Ok(Trial::<Observations, Observations>::Commit(discarded_pass(
60
2
            ctx, symbols,
61
2
        )?))
62
2
    })? {
63
2
        Trial::Commit(observations) => Ok(observations),
64
        Trial::Discard(_) => panic!("the pass commits"),
65
    }
66
2
}
67

            
68
/// Signature ids and local indices a context has already handed out.
69
4
fn shift_ids(ctx: &mut CompileContext) {
70
4
    ctx.intern_closure_signature(&[WasmType::I32], WasmType::I32)
71
4
        .expect("intern");
72
4
    ctx.intern_closure_signature(&[], WasmType::StringRef)
73
4
        .expect("intern");
74
4
    for _ in 0..3 {
75
12
        ctx.alloc_local(WasmType::I32).expect("local");
76
    }
77
4
}
78

            
79
type Scope = fn(&mut CompileContext, &mut SymbolTable) -> Result<Observations>;
80

            
81
#[test]
82
1
fn observations_hold_no_local_index_or_signature_id_under_any_scope() {
83
1
    let scopes: [Scope; 2] = [discarded_pass, in_committed_pass];
84
1
    for scope in scopes {
85
2
        for shifted in [false, true] {
86
4
            let (mut ctx, mut symbols) = setup();
87
4
            if shifted {
88
2
                shift_ids(&mut ctx);
89
2
            }
90
4
            let observations = scope(&mut ctx, &mut symbols).expect("scope");
91
4
            assert_eq!(observations.result, expected(), "shifted: {shifted}");
92
4
            assert_eq!(
93
4
                observations.blocks,
94
4
                vec![nested_block(expected())],
95
                "shifted: {shifted}"
96
            );
97
        }
98
    }
99
1
}
100

            
101
#[test]
102
1
fn an_observed_closure_reinterns_to_its_signature_after_the_rollback() {
103
1
    let (mut ctx, mut symbols) = setup();
104
1
    let observations = discarded_pass(&mut ctx, &mut symbols).expect("pass");
105
1
    let ty = observations.result.intern(&mut ctx).expect("intern");
106
1
    let WasmType::Closure(outer) = ty else {
107
        panic!("a closure observation interns to a closure: {ty:?}");
108
    };
109
1
    let outer = ctx.closure_sig(outer).unwrap();
110
1
    assert_eq!(outer.params, vec![WasmType::Ratio]);
111
1
    let WasmType::Closure(inner) = outer.result else {
112
        panic!("the outer closure returns a closure: {:?}", outer.result);
113
    };
114
1
    assert_eq!(
115
1
        ctx.closure_sig(inner).unwrap().params,
116
1
        vec![WasmType::Ratio]
117
    );
118
1
    assert_eq!(
119
1
        ctx.closure_sig(inner).unwrap().result,
120
1
        WasmType::PairRef(PairElement::I32)
121
    );
122
1
    assert_eq!(StructuralType::of(ty, &ctx).expect("of"), expected());
123
1
}
124

            
125
#[test]
126
1
fn a_nested_block_join_reinterns_after_the_rollback_under_a_shifted_registry() {
127
1
    let (mut ctx, mut symbols) = setup();
128
1
    let observations = discarded_pass(&mut ctx, &mut symbols).expect("pass");
129
1
    shift_ids(&mut ctx);
130
1
    let [block] = observations.blocks.as_slice() else {
131
        panic!("one nested block: {:?}", observations.blocks);
132
    };
133
1
    let ty = block.join.intern(&mut ctx).expect("intern");
134
1
    let WasmType::Closure(sig) = ty else {
135
        panic!("a closure join interns to a closure: {ty:?}");
136
    };
137
1
    assert_eq!(ctx.closure_sig(sig).unwrap().params, vec![WasmType::Ratio]);
138
1
    assert_eq!(StructuralType::of(ty, &ctx).expect("of"), expected());
139
1
}
140

            
141
const CHAIN_DEPTH: usize = 12;
142

            
143
36
fn chain_params(depth: usize) -> Vec<Leaf> {
144
36
    let leaves = [
145
36
        Leaf::Ratio,
146
36
        Leaf::StringRef,
147
36
        Leaf::PairRef(PairElement::I32),
148
36
    ];
149
36
    leaves[..depth % leaves.len()].to_vec()
150
36
}
151

            
152
/// A curried chain whose `depth`-th link takes `chain_params(depth)`.
153
2
fn chain() -> StructuralType {
154
2
    StructuralType {
155
2
        arrows: (0..CHAIN_DEPTH).map(chain_params).collect(),
156
2
        result: Leaf::Bool,
157
2
    }
158
2
}
159

            
160
1
fn observe_chain(ctx: &mut CompileContext) -> Result<Observations> {
161
1
    let mut ty = WasmType::Bool;
162
1
    for depth in (0..CHAIN_DEPTH).rev() {
163
12
        let params: Vec<WasmType> = chain_params(depth).into_iter().map(Into::into).collect();
164
12
        ty = WasmType::Closure(ctx.intern_closure_signature(&params, ty)?);
165
    }
166
1
    ctx.alloc_local(ty)?;
167
1
    let result = StructuralType::of(ty, ctx)?;
168
1
    Ok(Observations {
169
1
        result,
170
1
        blocks: Vec::new(),
171
1
    })
172
1
}
173

            
174
#[test]
175
1
fn a_deep_closure_chain_round_trips_across_the_rollback() {
176
1
    let (mut ctx, mut symbols) = setup();
177
1
    shift_ids(&mut ctx);
178
1
    let observations = match recompile(&mut ctx, &mut symbols, |ctx, _| {
179
1
        Ok(Trial::<(), _>::Discard(observe_chain(ctx)?))
180
1
    })
181
1
    .expect("pass")
182
    {
183
1
        Trial::Discard(observations) => observations,
184
        Trial::Commit(()) => panic!("the pass discards"),
185
    };
186
1
    assert_eq!(observations.result, chain());
187
1
    let ty = observations.result.intern(&mut ctx).expect("intern");
188
1
    assert_eq!(StructuralType::of(ty, &ctx).expect("of"), chain());
189
1
}
190

            
191
#[test]
192
1
fn a_closure_typed_parameter_is_refused() {
193
1
    let (mut ctx, _) = setup();
194
1
    let inner = ctx
195
1
        .intern_closure_signature(&[WasmType::Ratio], WasmType::Ratio)
196
1
        .expect("intern");
197
1
    let outer = ctx
198
1
        .intern_closure_signature(&[WasmType::Closure(inner)], WasmType::Ratio)
199
1
        .expect("intern");
200
1
    let refused = StructuralType::of(WasmType::Closure(outer), &ctx);
201
1
    assert!(
202
1
        matches!(refused, Err(Error::Compile(ref msg)) if msg.contains("closure-typed")),
203
        "{refused:?}"
204
    );
205
1
}
206

            
207
#[test]
208
1
fn every_plain_type_round_trips() {
209
1
    let (mut ctx, _) = setup();
210
1
    let plain = [
211
1
        WasmType::I32,
212
1
        WasmType::Bool,
213
1
        WasmType::Ratio,
214
1
        WasmType::StringRef,
215
1
        WasmType::Commodity,
216
1
        WasmType::PairRef(PairElement::AnyRef),
217
1
        WasmType::AnyRef,
218
1
        WasmType::EntityRef(crate::ast::EntityKind::Account),
219
1
    ];
220
1
    for ty in plain {
221
8
        let structural = StructuralType::of(ty, &ctx).expect("of");
222
8
        assert_eq!(structural.intern(&mut ctx).expect("intern"), ty);
223
    }
224
1
}