1
//! Dynamic binding of a special (ISS-208): a binder of a special saves the
2
//! special's global, stores the new value and restores the saved one on every
3
//! exit — normal, a crossing `return-from` / `go`, and a throw — by running
4
//! the restore as the cleanup of the UNWIND-PROTECT lowering. A callee or a
5
//! closure reads the global, so it sees the binding in force when it runs.
6
//! A special an earlier unit defined holds a constant and has no global: the
7
//! unit that binds it makes it a cell for the unit.
8

            
9
use crate::ast::{Expr, WasmType};
10
use crate::compiler::context::CompileContext;
11
use crate::compiler::emit::FunctionEmitter;
12
use crate::error::{Error, Result};
13
use crate::runtime::{Rebind, SymbolTable};
14
use wasm_encoder::BlockType;
15

            
16
/// A special a binder binds dynamically: its global and the global's type,
17
/// and the bound flag of a cell.
18
#[derive(Clone, Copy)]
19
pub(super) struct DynamicHome {
20
    pub(super) global: u32,
21
    pub(super) ty: WasmType,
22
    pub(super) flag: Option<u32>,
23
}
24

            
25
/// A special's global and type, the local holding the value to restore, the
26
/// bound flag with the local holding its value to restore, and its binding
27
/// depth global with the local holding the depth to restore.
28
#[derive(Clone, Copy)]
29
pub(super) struct Saved {
30
    pub(super) global: u32,
31
    pub(super) ty: WasmType,
32
    pub(super) local: u32,
33
    pub(super) flag: Option<(u32, u32)>,
34
    pub(super) depth_local: u32,
35
    pub(super) depth: u32,
36
}
37

            
38
/// The home of the special `name` when a binder of it binds dynamically; a
39
/// global a `SETF` created is not special. A macro body evaluates at compile
40
/// time, where no global holds a value, so its binders stay lexical.
41
15312325
pub(super) fn dynamic_home(symbols: &SymbolTable, name: &str) -> Option<DynamicHome> {
42
15312325
    match symbols.lookup(name)?.value()? {
43
        Expr::WasmGlobal(idx, ty)
44
53418
            if !symbols.is_macro_expansion()
45
53417
                && symbols.is_special(name)
46
53356
                && !symbols.is_created_global(name) =>
47
        {
48
50356
            Some(DynamicHome {
49
50356
                global: *idx,
50
50356
                ty: *ty,
51
50356
                flag: symbols.cell_flag(name),
52
50356
            })
53
        }
54
3472802
        _ => None,
55
    }
56
15312325
}
57

            
58
/// A binder of a unit special no source LET / LET* binds can only come from a
59
/// macro the scan could not read, so it must not silently bind lexically.
60
15242461
pub(super) fn reject_missed_specials<'a>(
61
15242461
    symbols: &SymbolTable,
62
15242461
    names: impl IntoIterator<Item = &'a str>,
63
15242461
) -> Result<()> {
64
15242461
    if symbols.is_macro_expansion() {
65
492919
        return Ok(());
66
14749542
    }
67
14749542
    for name in names {
68
14883708
        if symbols.is_unit_special(name) && !symbols.is_dynamic_special(name) {
69
1
            return Err(Error::Compile(format!(
70
1
                "{name}: a macro expansion rebinds the special {name}; not supported yet"
71
1
            )));
72
14883707
        }
73
    }
74
14749541
    Ok(())
75
15242461
}
76

            
77
/// Saves the current value and bound flag of each distinct global among
78
/// `homes`, and counts the binding in the global's depth.
79
698830
pub(super) fn save_all(
80
698830
    ctx: &mut CompileContext,
81
698830
    emit: &mut FunctionEmitter,
82
698830
    symbols: &SymbolTable,
83
698830
    homes: &[DynamicHome],
84
698830
) -> Result<Vec<Saved>> {
85
698830
    let mut saved: Vec<Saved> = Vec::new();
86
698830
    for &home in homes {
87
19848
        if saved.iter().any(|entry| entry.global == home.global) {
88
            continue;
89
19848
        }
90
19848
        let local = save(ctx, emit, home.global, home.ty)?;
91
19848
        let flag = home
92
19848
            .flag
93
19848
            .map(|flag| save(ctx, emit, flag, WasmType::I32).map(|local| (flag, local)))
94
            .transpose()?;
95
19848
        let (depth, depth_local) = enter(ctx, emit, symbols, home)?;
96
19848
        saved.push(Saved {
97
19848
            global: home.global,
98
19848
            ty: home.ty,
99
19848
            local,
100
19848
            flag,
101
19848
            depth_local,
102
19848
            depth,
103
19848
        });
104
    }
105
698830
    Ok(saved)
106
698830
}
107

            
108
/// Counts one more binding of the special `home`; the outermost one keeps the
109
/// value and flag outside it for a host to carry when the unit traps inside.
110
19848
fn enter(
111
19848
    ctx: &mut CompileContext,
112
19848
    emit: &mut FunctionEmitter,
113
19848
    symbols: &SymbolTable,
114
19848
    home: DynamicHome,
115
19848
) -> Result<(u32, u32)> {
116
19848
    let rebind = match symbols.rebind_of(home.global) {
117
1441
        Some(rebind) => rebind,
118
        None => {
119
            let rebind = Rebind {
120
18407
                depth: ctx.alloc_mutable_global(WasmType::I32)?,
121
18407
                outer: ctx.alloc_mutable_global(home.ty)?,
122
18407
                outer_bound: ctx.alloc_mutable_global(WasmType::I32)?,
123
            };
124
18407
            symbols.note_rebind(home.global, rebind);
125
18407
            rebind
126
        }
127
    };
128
19848
    let depth_local = save(ctx, emit, rebind.depth, WasmType::I32)?;
129
19848
    emit.global_get(rebind.depth);
130
19848
    emit.i32_eqz();
131
19848
    emit.if_block(BlockType::Empty);
132
19848
    emit.global_get(home.global);
133
19848
    emit.global_set(rebind.outer);
134
19848
    match home.flag {
135
19848
        Some(flag) => emit.global_get(flag),
136
        None => emit.i32_const(1),
137
    }
138
19848
    emit.global_set(rebind.outer_bound);
139
19848
    emit.block_end()?;
140
19848
    emit.global_get(rebind.depth);
141
19848
    emit.i32_const(1);
142
19848
    emit.i32_add();
143
19848
    emit.global_set(rebind.depth);
144
19848
    Ok((rebind.depth, depth_local))
145
19848
}
146

            
147
59544
fn save(
148
59544
    ctx: &mut CompileContext,
149
59544
    emit: &mut FunctionEmitter,
150
59544
    global: u32,
151
59544
    ty: WasmType,
152
59544
) -> Result<u32> {
153
59544
    let local = ctx.alloc_local(ty)?;
154
59544
    emit.global_get(global);
155
59544
    emit.local_set(local);
156
59544
    Ok(local)
157
59544
}
158

            
159
/// Stores the value on the stack into the binding `home` and marks it bound.
160
19848
pub(super) fn bind(emit: &mut FunctionEmitter, home: DynamicHome) {
161
19848
    emit.global_set(home.global);
162
19848
    if let Some(flag) = home.flag {
163
19848
        emit.i32_const(1);
164
19848
        emit.global_set(flag);
165
    }
166
19848
}
167

            
168
/// The cleanup forms restoring `saved` and its binding depth,
169
/// last-bound first.
170
19846
pub(super) fn restore_forms(saved: &[Saved]) -> Vec<Expr> {
171
19846
    saved
172
19846
        .iter()
173
19846
        .rev()
174
19850
        .flat_map(|entry| {
175
19850
            let value = restore(entry.global, entry.ty, entry.local);
176
19850
            let flag = entry
177
19850
                .flag
178
19849
                .map(|(flag, local)| restore(flag, WasmType::I32, local));
179
19850
            let depth = restore(entry.depth, WasmType::I32, entry.depth_local);
180
19850
            std::iter::once(value).chain(flag).chain([depth])
181
19850
        })
182
        .collect()
183
19846
}
184

            
185
59549
fn restore(global: u32, ty: WasmType, local: u32) -> Expr {
186
59549
    Expr::List(vec![
187
59549
        Expr::symbol("SETF"),
188
59549
        Expr::WasmGlobal(global, ty),
189
59549
        Expr::WasmLocal(local, ty),
190
59549
    ])
191
59549
}