1
//! Binding one `LET` / `LET*` variable: resolving its init, then either
2
//! keeping a constant, lifting a lambda to a closure local, or allocating a
3
//! runtime local, which for an assigned variable has a home its stores widen.
4

            
5
use crate::ast::{Expr, LambdaParams, Place, WasmType};
6
use crate::compiler::context::CompileContext;
7
use crate::compiler::emit::FunctionEmitter;
8
use crate::compiler::expr::{
9
    applying_lambda, bind_local, close_factory_call, compile_for_effect, compile_for_stack,
10
    emit_box_anyref, emit_local_read, emit_nil_default, eval_value, fold_value, probe_value,
11
    reads_only,
12
};
13
use crate::compiler::join::{Arm, reconcile_arms};
14
use crate::compiler::native::function_operand::runs_nothing;
15
use crate::compiler::special::{is_closure_factory_call, try_emit_lambda_for_value};
16
use crate::error::{Error, Result};
17
use crate::runtime::{HomeKey, SymbolTable};
18

            
19
use super::super::{compile_into_home, literal_arm};
20
use super::infer::assigned_var_runtime_type;
21

            
22
/// How a binding's init resolved, which decides what `bind_runtime_or_const`
23
/// emits for it.
24
pub(super) enum Init {
25
    /// A fold-safe constant: bound as data, nothing emitted.
26
    Datum(Expr),
27
    /// A constant whose form carries effects (a store, a print, a transfer):
28
    /// the form is compiled for effect, then the constant is bound.
29
    Effectful(Expr),
30
    /// A runtime value, or a compile-time value only the evaluator can hold
31
    /// (a lambda): bound as the evaluator resolved it.
32
    Resolved(Expr),
33
}
34

            
35
impl Init {
36
1923426
    fn value(&self) -> &Expr {
37
1923426
        match self {
38
1923426
            Init::Datum(value) | Init::Effectful(value) | Init::Resolved(value) => value,
39
        }
40
1923426
    }
41
}
42

            
43
/// Resolves one init: its fold-safe datum, else a probe on a clone decides
44
/// between a runtime local, an evaluator-only value and an effectful
45
/// constant (0014 Stage 2: a store inside an init is never lost, S24).
46
906293
pub(super) fn resolve_binding(
47
906293
    symbols: &mut SymbolTable,
48
906293
    init: Option<Expr>,
49
906293
) -> Result<(Option<Expr>, Init)> {
50
906293
    let Some(expr) = init else {
51
208
        return Ok((None, Init::Datum(Expr::Nil)));
52
    };
53
906085
    if let Some(datum) = fold_value(symbols, &expr)? {
54
612157
        return Ok((Some(expr), Init::Datum(datum)));
55
293928
    }
56
293928
    let probed = probe_value(&mut symbols.clone(), &expr)?;
57
291632
    let init = match probed {
58
291632
        ref value if value.is_wasm_runtime() => Init::Resolved(probed),
59
115770
        Expr::Lambda(..) if is_closure_factory_call(symbols, &expr)? => Init::Resolved(probed),
60
67823
        Expr::Lambda(..) if !runs_nothing(symbols, &expr) && !reads_only(symbols, &expr) => {
61
16285
            Init::Effectful(probed)
62
        }
63
51954
        Expr::Lambda(_, _) | Expr::RuntimeValue(_) => Init::Resolved(eval_value(symbols, &expr)?),
64
        // A binding holds data: a bare symbol an init evaluates to is bound
65
        // quoted, never as a reference to the variable it names (0014
66
        // obligation (f)).
67
        symbol @ Expr::Symbol(_) => Init::Effectful(Expr::quoted(symbol)),
68
1735
        constant => Init::Effectful(constant),
69
    };
70
291632
    Ok((Some(expr), init))
71
906293
}
72

            
73
/// Lifts a v1 lambda to a closure value held in a fresh local, or `None` when
74
/// the lambda does not fit the v1 emit slice.
75
118572
pub(in crate::compiler) fn bind_lambda_closure(
76
118572
    ctx: &mut CompileContext,
77
118572
    emit: &mut FunctionEmitter,
78
118572
    symbols: &mut SymbolTable,
79
118572
    params: &LambdaParams,
80
118572
    body: &Expr,
81
118572
    shared: bool,
82
118572
) -> Result<Option<Expr>> {
83
118572
    let Some(sig) = try_emit_lambda_for_value(ctx, emit, symbols, params, body)? else {
84
223
        return Ok(None);
85
    };
86
67177
    let ty = WasmType::Closure(sig);
87
67177
    let idx = bind_local(ctx, emit, ty, shared)?;
88
    // Only a capture-free closure keeps its source: inlining a capturing one
89
    // at a HOF call site would resolve its free variables there, not where it
90
    // was created. A celled closure variable can be reassigned from another
91
    // closure, so it keeps none either.
92
67177
    if !shared && crate::compiler::special::is_capture_free(symbols, params, body) {
93
56891
        symbols.record_closure_body(Place::Local(idx), params.clone(), body.clone());
94
10286
    }
95
67177
    Ok(Some(Expr::WasmLocal(idx, ty)))
96
118572
}
97

            
98
/// What binding a variable needs to know: its name, the scope forms that
99
/// follow, whether it lives in a shared cell, and the site of its home when a
100
/// store can reach it.
101
pub(super) struct Bind<'a> {
102
    pub(super) name: &'a str,
103
    pub(super) body: &'a [Expr],
104
    pub(super) shared: bool,
105
    /// The scope an assigned variable is sized in, when it must see its siblings.
106
    pub(super) sizing: Option<&'a SymbolTable>,
107
    pub(super) key: Option<&'a HomeKey>,
108
}
109

            
110
/// Binds one variable; an assigned one gets the home its stores record into.
111
903997
pub(super) fn bind_variable(
112
903997
    ctx: &mut CompileContext,
113
903997
    emit: &mut FunctionEmitter,
114
903997
    symbols: &mut SymbolTable,
115
903997
    bind: &Bind,
116
903997
    init_expr: Option<&Expr>,
117
903997
    init: &Init,
118
903997
) -> Result<(Expr, Option<HomeKey>)> {
119
903997
    let copies_closure = matches!(
120
903997
        (init.value(), init_expr),
121
        (
122
            Expr::WasmLocal(_, WasmType::Closure(_)),
123
            Some(Expr::Symbol(_))
124
        )
125
    );
126
903997
    match bind.key {
127
115435
        Some(key) if !copies_closure && !matches!(init.value(), Expr::Lambda(..)) => {
128
114531
            let val = init.value();
129
114531
            let (idx, ty) = bind_var_home(
130
114531
                ctx,
131
114531
                emit,
132
114531
                symbols,
133
114531
                Some(key),
134
114531
                (init_expr, val),
135
114531
                bind.shared,
136
49252
                |_, _, symbols| {
137
49252
                    let sizing = bind.sizing.unwrap_or(&*symbols);
138
49252
                    assigned_var_runtime_type(bind.body, bind.name, val, sizing)
139
49252
                },
140
18
            )?;
141
114513
            Ok((Expr::WasmLocal(idx, ty), Some(key.clone())))
142
        }
143
        _ => {
144
789466
            let value = bind_runtime_or_const(ctx, emit, symbols, bind.shared, init_expr, init)?;
145
737024
            Ok((value, None))
146
        }
147
    }
148
903997
}
149

            
150
/// Allocates the local of a variable that may be assigned, typed by its home:
151
/// the join of the init and the hint, the stores of the previous attempt that
152
/// did not fit. A literal init takes the home's type, a nil one without a hint
153
/// the type `seed` predicts; any other compiles as itself and is boxed when the
154
/// home holds any value.
155
265682
pub(in crate::compiler::special) fn bind_var_home(
156
265682
    ctx: &mut CompileContext,
157
265682
    emit: &mut FunctionEmitter,
158
265682
    symbols: &mut SymbolTable,
159
265682
    key: Option<&HomeKey>,
160
265682
    (init_expr, val): (Option<&Expr>, &Expr),
161
265682
    shared: bool,
162
265682
    seed: impl FnOnce(
163
265682
        &mut CompileContext,
164
265682
        &mut FunctionEmitter,
165
265682
        &mut SymbolTable,
166
265682
    ) -> Result<Option<WasmType>>,
167
265682
) -> Result<(u32, WasmType)> {
168
265682
    let hint = key.and_then(|key| symbols.hint(key));
169
265682
    let (arm, ty) = match literal_arm(val) {
170
        Some(arm) => {
171
241019
            let ty = var_home_type(arm, hint, || seed(ctx, emit, symbols))?;
172
241001
            match init_expr {
173
241001
                Some(expr) => compile_into_home(ctx, emit, symbols, expr, ty, arm == Arm::Nil)?,
174
                None => emit_nil_default(ctx, emit, ty)?,
175
            }
176
241001
            (arm, ty)
177
        }
178
24663
        None => bind_compiled(ctx, emit, symbols, init_expr, hint)?,
179
    };
180
265642
    let idx = bind_local(ctx, emit, ty, shared)?;
181
265642
    if let Some(key) = key {
182
263030
        let datum = (!val.is_wasm_runtime()).then(|| val.clone());
183
263030
        symbols.open_binder(key, arm, datum, ty);
184
2612
    }
185
265642
    Ok((idx, ty))
186
265682
}
187

            
188
188686
fn bind_compiled(
189
188686
    ctx: &mut CompileContext,
190
188686
    emit: &mut FunctionEmitter,
191
188686
    symbols: &mut SymbolTable,
192
188686
    init_expr: Option<&Expr>,
193
188686
    hint: Option<WasmType>,
194
188686
) -> Result<(Arm, WasmType)> {
195
188686
    let expr = init_expr
196
        .ok_or_else(|| Error::Compile("runtime binding requires an init expression".to_string()))?;
197
188686
    let actual = compile_for_stack(ctx, emit, symbols, expr)?;
198
187394
    let ty = home_type(Arm::Value(actual), hint);
199
187394
    box_into_home(ctx, emit, actual, ty);
200
187394
    Ok((Arm::Value(actual), ty))
201
188686
}
202

            
203
/// Boxes the value of type `actual` on the stack when its `home` holds any value.
204
222067
pub(in crate::compiler::special) fn box_into_home(
205
222067
    ctx: &CompileContext,
206
222067
    emit: &mut FunctionEmitter,
207
222067
    actual: WasmType,
208
222067
    home: WasmType,
209
222067
) {
210
222067
    if home == WasmType::AnyRef {
211
8637
        emit_box_anyref(ctx, emit, actual);
212
213430
    }
213
222067
}
214

            
215
/// The type of an assigned variable's local: the init `arm` joined with the
216
/// `hint` the refused stores of the previous attempt left, else for a nil init
217
/// with the type its stores are sized to, which `seed` computes.
218
428562
pub(in crate::compiler::special) fn var_home_type(
219
428562
    arm: Arm,
220
428562
    hint: Option<WasmType>,
221
428562
    seed: impl FnOnce() -> Result<Option<WasmType>>,
222
428562
) -> Result<WasmType> {
223
428562
    let seed = match (hint, arm) {
224
131316
        (None, Arm::Nil) => seed()?,
225
297246
        _ => hint,
226
    };
227
428544
    Ok(home_type(arm, seed))
228
428562
}
229

            
230
/// The type a local holds that the init `arm` and the `seed` both fit.
231
817206
pub(in crate::compiler::special) fn home_type(arm: Arm, seed: Option<WasmType>) -> WasmType {
232
817206
    let arms: Vec<Arm> = std::iter::once(arm).chain(seed.map(Arm::Value)).collect();
233
817206
    reconcile_arms(&arms)
234
817206
}
235

            
236
/// If the init is a runtime value, compile the init expression to the WASM
237
/// stack, allocate a local, and return `WasmLocal`. If it is an
238
/// `Expr::Lambda` that fits the Tier 1.5 v1 emit slice, lift it to a real
239
/// wasm closure value: emit the closure construction sequence, allocate a
240
/// `Closure(sig)` local, and return the corresponding `WasmLocal`.
241
/// Otherwise return the constant value untouched (the body's const-fold
242
/// path keeps working), after compiling an effectful init for its effects.
243
789466
fn bind_runtime_or_const(
244
789466
    ctx: &mut CompileContext,
245
789466
    emit: &mut FunctionEmitter,
246
789466
    symbols: &mut SymbolTable,
247
789466
    shared: bool,
248
789466
    init_expr: Option<&Expr>,
249
789466
    init: &Init,
250
789466
) -> Result<Expr> {
251
789466
    let val = init.value();
252
789466
    match val {
253
        // A closure variable bound from another one gets its own local: sharing
254
        // the slot would make a later `setf` of either change both.
255
        Expr::WasmLocal(from, ty @ WasmType::Closure(_))
256
1070
            if matches!(init_expr, Some(Expr::Symbol(_))) =>
257
        {
258
1070
            emit_local_read(ctx, emit, *from);
259
1070
            let idx = bind_local(ctx, emit, *ty, shared)?;
260
1070
            Ok(Expr::WasmLocal(idx, *ty))
261
        }
262
788396
        value if value.is_wasm_runtime() => {
263
            // The compiled type is authoritative: the eval-time placeholder can
264
            // disagree with what codegen pushes (e.g. a fold over a runtime closure).
265
164023
            let (_, actual_ty) = bind_compiled(ctx, emit, symbols, init_expr, None)?;
266
162753
            let idx = bind_local(ctx, emit, actual_ty, shared)?;
267
162753
            Ok(Expr::WasmLocal(idx, actual_ty))
268
        }
269
        Expr::Lambda(..) => {
270
115770
            if let (Init::Effectful(_), Some(expr)) = (init, init_expr) {
271
16285
                compile_for_effect(ctx, emit, symbols, expr)?;
272
99485
            }
273
115770
            let closed = match init_expr {
274
115770
                Some(call) if is_closure_factory_call(symbols, call)? => {
275
47947
                    close_factory_call(ctx, emit, symbols, call)?
276
                }
277
67823
                _ => val.clone(),
278
            };
279
115770
            let Expr::Lambda(params, body) = &closed else {
280
                return Ok(closed);
281
            };
282
115770
            let source = init_expr.unwrap_or(&closed);
283
115770
            let emitted = applying_lambda(symbols, source, |symbols| {
284
115770
                bind_lambda_closure(ctx, emit, symbols, params, body, shared)
285
115770
            })?;
286
64598
            Ok(emitted.unwrap_or_else(|| closed.clone()))
287
        }
288
        _ => {
289
508603
            if let (Init::Effectful(_), Some(expr)) = (init, init_expr) {
290
1730
                compile_for_effect(ctx, emit, symbols, expr)?;
291
506873
            }
292
508603
            Ok(val.clone())
293
        }
294
    }
295
789466
}