1
//! A journalled scope either commits everything it did or rolls all of it
2
//! back; its work stays charged either way.
3
//!
4
//! The journal is the `SymbolTable` state a trial can change plus the
5
//! `CompileContext` state `ContextSnapshot` covers — one rollback path, not a
6
//! second journal beside it. A trial lowers into a scratch emitter and may
7
//! add data segments, locals and pending helpers to the context; the snapshot
8
//! covers all of them, and the scratch is only spliced into the real function
9
//! on commit. Nested trials are LIFO by construction; an inner commit stays
10
//! covered by the outer journal.
11
//!
12
//! An error keeps the stores recorded into the unit's global homes: the
13
//! unit settles them before it compiles again (plan 0014 stage GJ).
14
//!
15
//! The probe scope (ADR-0034): a pass compiled only to classify. Discarding
16
//! it restores everything but the budget — its work stands — and hands the
17
//! next pass only its
18
//! [`Observations`](crate::compiler::observations::Observations).
19

            
20
use crate::ast::{Expr, WasmType};
21
use crate::compiler::context::{CompileContext, ContextSnapshot};
22
use crate::compiler::emit::FunctionEmitter;
23
use crate::compiler::expr::compile_for_stack;
24
use crate::error::{Error, Result};
25
use crate::runtime::{SymbolJournal, SymbolTable};
26

            
27
/// How a trial ends when it does not fail.
28
#[derive(Debug)]
29
pub(crate) enum Trial<C, D> {
30
    Commit(C),
31
    Discard(D),
32
}
33

            
34
struct Journal {
35
    context: ContextSnapshot,
36
    symbols: SymbolJournal,
37
}
38

            
39
impl Journal {
40
161143
    fn open(ctx: &CompileContext, symbols: &SymbolTable) -> Self {
41
161143
        Self {
42
161143
            context: ctx.snapshot(),
43
161143
            symbols: symbols.journal(),
44
161143
        }
45
161143
    }
46

            
47
102641
    fn roll_back(self, ctx: &mut CompileContext, symbols: &mut SymbolTable) {
48
102641
        ctx.restore(self.context);
49
102641
        symbols.restore_journal(self.symbols);
50
102641
    }
51
}
52

            
53
/// Runs one pass in a scope; see the module docs. A discard or an error
54
/// restores the journalled state, but not the budget.
55
161143
pub(crate) fn recompile<C, D>(
56
161143
    ctx: &mut CompileContext,
57
161143
    symbols: &mut SymbolTable,
58
161143
    pass: impl FnOnce(&mut CompileContext, &mut SymbolTable) -> Result<Trial<C, D>>,
59
161143
) -> Result<Trial<C, D>> {
60
161143
    let journal = Journal::open(ctx, symbols);
61
161143
    match pass(ctx, symbols) {
62
58502
        Ok(Trial::Commit(committed)) => Ok(Trial::Commit(committed)),
63
        Ok(Trial::Discard(summary)) => {
64
85243
            journal.roll_back(ctx, symbols);
65
85243
            Ok(Trial::Discard(summary))
66
        }
67
        Err(err) => {
68
17398
            let homes = symbols.home_book();
69
17398
            journal.roll_back(ctx, symbols);
70
17398
            symbols.restore_home_book(homes);
71
17398
            Err(err)
72
        }
73
    }
74
161143
}
75

            
76
/// What `form` pushes compiled on a scratch emitter seeded from `emit`,
77
/// `None` for one that never falls through, handed to `read` before the trial
78
/// rolls back; `None` too when the form does not compile, but a resource
79
/// ceiling is an error, not a form that does not compile.
80
79723
pub(crate) fn compiled_in_trial<T>(
81
79723
    ctx: &mut CompileContext,
82
79723
    symbols: &mut SymbolTable,
83
79723
    emit: &FunctionEmitter,
84
79723
    form: &Expr,
85
79723
    read: impl FnOnce(&CompileContext, Option<WasmType>) -> Result<T>,
86
79723
) -> Result<Option<T>> {
87
79723
    let trial = recompile(ctx, symbols, |ctx, symbols| {
88
79723
        let mut scratch = FunctionEmitter::new_seeded(emit.block_depth());
89
79723
        let ty = compile_for_stack(ctx, &mut scratch, symbols, form)?;
90
75051
        read(ctx, scratch.is_reachable().then_some(ty)).map(Trial::<(), _>::Discard)
91
79723
    });
92
79723
    match trial {
93
75051
        Ok(Trial::Discard(value)) => Ok(Some(value)),
94
1
        Err(err @ Error::Resource(_)) => Err(err),
95
4671
        _ => Ok(None),
96
    }
97
79723
}
98

            
99
#[cfg(test)]
100
#[path = "recompile_tests.rs"]
101
mod tests;
102

            
103
#[cfg(test)]
104
#[path = "rollback_tests.rs"]
105
mod rollback_tests;