1
//! Compile-time guards a closure emit runs before it trusts its captures.
2

            
3
use wasm_encoder::ValType;
4

            
5
use crate::ast::Expr;
6
use crate::compiler::context::CompileContext;
7
use crate::compiler::emit::FunctionEmitter;
8
use crate::error::{Error, Result};
9
use crate::runtime::SymbolTable;
10

            
11
use super::super::cell_store::captured_store_error;
12
use super::captures::CaptureSet;
13

            
14
/// The closure env holds a copy of each captured variable that is not a
15
/// shared cell, so a store to one would be lost (ISS-001).
16
263411
pub(super) fn reject_captured_stores(
17
263411
    ctx: &CompileContext,
18
263411
    symbols: &SymbolTable,
19
263411
    captures: &CaptureSet,
20
263411
) -> Result<()> {
21
263411
    let stored = captures.stored_captures().find(|name| {
22
4220
        matches!(
23
4220
            symbols.lookup(name).and_then(|sym| sym.value()),
24
4220
            Some(Expr::WasmLocal(idx, _)) if ctx.cell_of(*idx).is_none()
25
        )
26
4220
    });
27
263411
    match stored {
28
208
        Some(name) => Err(captured_store_error(name)),
29
263203
        None => Ok(()),
30
    }
31
263411
}
32

            
33
/// A helper body naming a local its own pool does not own would be an invalid
34
/// module: an outer variable reached without being captured.
35
209942
pub(super) fn reject_foreign_locals(
36
209942
    helper: &FunctionEmitter,
37
209942
    param_count: u32,
38
209942
    locals: &[(u32, ValType)],
39
209942
) -> Result<()> {
40
209942
    let owned = u32::try_from(locals.len())
41
209942
        .unwrap_or(u32::MAX)
42
209942
        .saturating_add(param_count);
43
209942
    if helper.locals_addressed()? > owned {
44
1
        return Err(Error::Compile(
45
1
            "a closure body reaches a variable it does not capture; not supported yet".to_string(),
46
1
        ));
47
209941
    }
48
209941
    Ok(())
49
209942
}
50

            
51
#[cfg(test)]
52
#[path = "guards_tests.rs"]
53
mod tests;