Lines
98.75 %
Functions
87.5 %
Branches
100 %
//! Access to a user binding that may live in a shared cell: a binding both
//! assigned and captured by a closure in its scope is one `$cell_<ty>` struct
//! that the scope and every closure reach by reference.
use crate::ast::{Place, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::error::{Error, Result};
/// Pushes the value of user binding `idx`, reading through its cell if any.
pub(in crate::compiler) fn emit_local_read(
ctx: &CompileContext,
emit: &mut FunctionEmitter,
idx: u32,
) {
emit.local_get(idx);
if let Some(cell) = ctx.cell_of(idx) {
emit.struct_get(cell, 0);
}
/// Runs before the stored value is pushed: a cell needs its ref below it.
pub(in crate::compiler) fn store_begin(ctx: &CompileContext, emit: &mut FunctionEmitter, idx: u32) {
if ctx.cell_of(idx).is_some() {
/// Runs after the value is pushed; `keep` leaves the stored value on the stack.
pub(in crate::compiler) fn store_end(
keep: bool,
match (ctx.cell_of(idx), keep) {
(Some(cell), _) => {
emit.struct_set(cell, 0);
if keep {
emit_local_read(ctx, emit, idx);
(None, true) => emit.local_tee(idx),
(None, false) => emit.local_set(idx),
/// [`emit_local_read`] for a [`Place`].
pub(in crate::compiler) fn emit_place_read(
ctx: &mut CompileContext,
place: Place,
) -> Result<()> {
match place {
Place::Local(idx) => {
Ok(())
Place::Global(idx) => ctx.emit_global_read(emit, idx),
/// [`store_begin`] for a [`Place`]: a global needs nothing below the value.
pub(in crate::compiler) fn store_begin_place(
if let Place::Local(idx) = place {
store_begin(ctx, emit, idx);
/// [`store_end`] for a [`Place`].
pub(in crate::compiler) fn store_end_place(
Place::Local(idx) => store_end(ctx, emit, idx, keep),
Place::Global(idx) => {
emit.global_set(idx);
emit.global_get(idx);
/// Binds the value on the stack to a fresh local, in a fresh cell when
/// `shared`, so each binding entry gets its own cell.
pub(in crate::compiler) fn bind_local(
ty: WasmType,
shared: bool,
) -> Result<u32> {
if !shared {
let idx = ctx.alloc_local(ty)?;
emit.local_set(idx);
return Ok(idx);
let idx = ctx.alloc_cell_local(ty)?;
let cell = ctx
.cell_of(idx)
.ok_or_else(|| Error::Compile("a fresh cell local has no cell type".to_string()))?;
emit.struct_new(cell);
Ok(idx)
#[cfg(test)]
#[path = "local_cell_tests.rs"]
mod tests;