1
//! The probe scope against the whole `SymbolTable` and `CompileContext`
2
//! state. The budget is compared on its own, since a discarded pass keeps it.
3

            
4
use super::{compiled_in_trial, recompile};
5
use crate::ast::{Expr, WasmType};
6
use crate::compiler::budget::MAX_ELAB_WORK;
7
use crate::compiler::context::CompileContext;
8
use crate::compiler::emit::FunctionEmitter;
9
use crate::compiler::join::{Arm, Exit};
10
use crate::compiler::observations::{Leaf, Observations, ObservedBlock, StructuralType};
11
use crate::compiler::recompile::Trial;
12
use crate::error::{Error, Result};
13
use crate::reader::Reader;
14
use crate::runtime::{HomeKey, Symbol, SymbolKind, SymbolTable};
15

            
16
6
fn setup() -> (CompileContext, SymbolTable) {
17
6
    let ctx = CompileContext::new_with_host_fns(&[]).expect("context");
18
6
    let symbols = SymbolTable::with_builtins_for_wasm();
19
6
    (ctx, symbols)
20
6
}
21

            
22
/// Everything but the budget.
23
10
fn state(ctx: &CompileContext, symbols: &SymbolTable) -> (String, String) {
24
10
    let digest = symbols.state_digest();
25
10
    let symbols: Vec<&str> = digest
26
10
        .lines()
27
310
        .filter(|line| !line.starts_with("charged:"))
28
        .collect();
29
10
    (ctx.state_digest(), symbols.join("\n"))
30
10
}
31

            
32
10
fn charged(symbols: &SymbolTable) -> u64 {
33
10
    symbols.budget().charged()
34
10
}
35

            
36
7
fn pass_work(ctx: &mut CompileContext, symbols: &mut SymbolTable, name: &str) -> Result<()> {
37
7
    ctx.alloc_local(WasmType::Ratio)?;
38
7
    ctx.intern_closure_signature(&[WasmType::Ratio], WasmType::I32)?;
39
7
    ctx.record_block_exit(
40
7
        "OUTER",
41
7
        Exit {
42
7
            arm: Arm::Value(WasmType::Ratio),
43
7
            emitted: WasmType::Ratio,
44
7
        },
45
7
    );
46
7
    ctx.record_block_join(ctx.block_join_start(), ratio_block(name));
47
7
    symbols.define(Symbol::new(name, SymbolKind::Variable).with_value(Expr::T));
48
7
    symbols.charge_work(100)
49
7
}
50

            
51
10
fn ratio_block(name: &str) -> ObservedBlock {
52
10
    ObservedBlock {
53
10
        name: name.to_string(),
54
10
        body_len: 1,
55
10
        join: StructuralType {
56
10
            arrows: vec![],
57
10
            result: Leaf::Ratio,
58
10
        },
59
10
    }
60
10
}
61

            
62
7
fn observed() -> Observations {
63
7
    Observations {
64
7
        result: StructuralType {
65
7
            arrows: vec![],
66
7
            result: Leaf::Ratio,
67
7
        },
68
7
        blocks: Vec::new(),
69
7
    }
70
7
}
71

            
72
#[test]
73
1
fn a_discarded_pass_restores_the_state_and_keeps_its_charge() {
74
1
    let (mut ctx, mut symbols) = setup();
75
1
    ctx.push_block_label("OUTER", 0, None);
76
1
    let before = state(&ctx, &symbols);
77
1
    let base = charged(&symbols);
78
1
    let pass = recompile(&mut ctx, &mut symbols, |ctx, symbols| {
79
1
        pass_work(ctx, symbols, "PASS")?;
80
1
        Ok(Trial::<(), _>::Discard(observed()))
81
1
    })
82
1
    .expect("pass");
83
1
    assert!(matches!(pass, Trial::Discard(obs) if obs == observed()));
84
1
    assert_eq!(state(&ctx, &symbols), before);
85
1
    assert_eq!(charged(&symbols), base + 100);
86
1
}
87

            
88
#[test]
89
1
fn an_error_inside_an_inner_pass_restores_the_outer_state_and_keeps_the_charge() {
90
1
    let (mut ctx, mut symbols) = setup();
91
1
    ctx.push_block_label("OUTER", 0, None);
92
1
    let before = state(&ctx, &symbols);
93
1
    let base = charged(&symbols);
94
1
    recompile(&mut ctx, &mut symbols, |ctx, symbols| {
95
1
        pass_work(ctx, symbols, "OUTER-PASS")?;
96
1
        let outer = state(ctx, symbols);
97
1
        let err = recompile(ctx, symbols, |ctx, symbols| {
98
1
            pass_work(ctx, symbols, "INNER-PASS")?;
99
1
            Err::<Trial<(), Observations>, _>(Error::Compile("inner".to_string()))
100
1
        })
101
1
        .expect_err("inner error");
102
1
        assert!(err.to_string().contains("inner"));
103
1
        assert_eq!(state(ctx, symbols), outer);
104
1
        assert_eq!(charged(symbols), base + 200);
105
1
        Ok(Trial::<(), _>::Discard(observed()))
106
1
    })
107
1
    .expect("outer");
108
1
    assert_eq!(state(&ctx, &symbols), before);
109
1
    assert_eq!(charged(&symbols), base + 200);
110
1
}
111

            
112
/// A disagreeing LET inside a disagreeing LET: the outer binding's first
113
/// pass runs the inner one twice, the outer's second pass agrees.
114
#[test]
115
1
fn a_nested_discard_restores_each_pre_pass_state_and_charges_every_pass() {
116
1
    let (mut ctx, mut symbols) = setup();
117
1
    ctx.push_block_label("OUTER", 0, None);
118
1
    let mut marks = vec![charged(&symbols)];
119
1
    let before = state(&ctx, &symbols);
120
1
    recompile(&mut ctx, &mut symbols, |ctx, symbols| {
121
1
        pass_work(ctx, symbols, "OUTER-1")?;
122
1
        let outer = state(ctx, symbols);
123
1
        marks.push(charged(symbols));
124
1
        recompile(ctx, symbols, |ctx, symbols| {
125
1
            pass_work(ctx, symbols, "INNER-1")?;
126
1
            Ok(Trial::<(), _>::Discard(observed()))
127
1
        })?;
128
1
        assert_eq!(state(ctx, symbols), outer);
129
1
        marks.push(charged(symbols));
130
1
        recompile(ctx, symbols, |ctx, symbols| {
131
1
            pass_work(ctx, symbols, "INNER-2")?;
132
1
            Ok(Trial::<(), Observations>::Commit(()))
133
1
        })?;
134
1
        marks.push(charged(symbols));
135
1
        Ok(Trial::<(), _>::Discard(observed()))
136
1
    })
137
1
    .expect("outer pass 1");
138
1
    assert_eq!(state(&ctx, &symbols), before);
139
1
    let second = recompile(&mut ctx, &mut symbols, |ctx, symbols| {
140
1
        pass_work(ctx, symbols, "OUTER-2")?;
141
1
        Ok(Trial::<(), Observations>::Commit(()))
142
1
    })
143
1
    .expect("outer pass 2");
144
1
    marks.push(charged(&symbols));
145
1
    assert!(matches!(second, Trial::Commit(())));
146
4
    assert!(marks.windows(2).all(|pair| pair[0] < pair[1]), "{marks:?}");
147
1
    assert!(symbols.lookup("OUTER-2").is_some());
148
1
    assert!(symbols.lookup("INNER-2").is_none());
149
1
}
150

            
151
#[test]
152
1
fn a_discarded_pass_puts_back_the_block_joins_it_consumed() {
153
1
    let (mut ctx, mut symbols) = setup();
154
1
    let join = ratio_block("B").join;
155
1
    ctx.expecting_block_joins(vec![ratio_block("A"), ratio_block("B")], |ctx| {
156
1
        assert!(ctx.expected_block_join("A", 1).is_some());
157
1
        recompile(ctx, &mut symbols, |ctx, _| {
158
1
            assert!(ctx.expected_block_join("B", 1).is_some());
159
1
            Ok(Trial::<(), _>::Discard(observed()))
160
1
        })
161
1
        .expect("pass");
162
1
        assert_eq!(ctx.expected_block_join("B", 1), Some(join));
163
1
        assert_eq!(ctx.expected_block_join("B", 1), None);
164
1
    });
165
1
}
166

            
167
2
fn symbols_with_home() -> SymbolTable {
168
2
    let mut symbols = SymbolTable::with_builtins_for_wasm();
169
2
    symbols.begin_home_attempt(std::collections::HashMap::new());
170
2
    symbols.note_home(
171
2
        "G",
172
2
        vec![Arm::NumberLiteral(WasmType::I32)],
173
2
        None,
174
2
        WasmType::I32,
175
2
    );
176
2
    symbols
177
2
}
178

            
179
#[test]
180
1
fn a_discarded_pass_forgets_the_stores_it_recorded() {
181
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("context");
182
1
    let mut symbols = symbols_with_home();
183
1
    recompile(&mut ctx, &mut symbols, |_, symbols| {
184
1
        symbols.note_store(&HomeKey::global("G"), Arm::Value(WasmType::Ratio));
185
1
        Ok(Trial::<(), _>::Discard(observed()))
186
1
    })
187
1
    .expect("pass");
188
1
    assert_eq!(symbols.widened_homes(), None);
189
1
}
190

            
191
#[test]
192
1
fn a_failed_pass_keeps_the_stores_it_recorded() {
193
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("context");
194
1
    let mut symbols = symbols_with_home();
195
1
    recompile(&mut ctx, &mut symbols, |_, symbols| {
196
1
        symbols.note_store(&HomeKey::global("G"), Arm::Value(WasmType::Ratio));
197
1
        Err::<Trial<(), Observations>, _>(Error::Compile("refused".to_string()))
198
1
    })
199
1
    .expect_err("refused");
200
1
    assert!(symbols.widened_homes().is_some());
201
1
}
202

            
203
#[test]
204
1
fn a_trial_out_of_budget_is_a_resource_error_not_a_form_that_does_not_compile() {
205
1
    let (mut ctx, mut symbols) = setup();
206
1
    let emit = FunctionEmitter::new();
207
1
    symbols.charge_work(MAX_ELAB_WORK).expect("within");
208
1
    let form = Reader::parse_expr("(+ 1 2)").expect("parses");
209
1
    let trial = compiled_in_trial(&mut ctx, &mut symbols, &emit, &form, |_, ty| Ok(ty));
210
1
    assert!(matches!(trial, Err(Error::Resource(_))), "{trial:?}");
211
1
}
212

            
213
#[test]
214
1
fn a_trial_that_does_not_compile_is_none() {
215
1
    let (mut ctx, mut symbols) = setup();
216
1
    let emit = FunctionEmitter::new();
217
1
    let form = Reader::parse_expr("(no-such-function 1)").expect("parses");
218
1
    let trial = compiled_in_trial(&mut ctx, &mut symbols, &emit, &form, |_, ty| Ok(ty));
219
1
    assert_eq!(trial.expect("no resource error"), None);
220
1
}