1
//! Stores into the runtime local backing a place (0014 Stage 2, §Stores to
2
//! globals): a global cell refuses a value of another representation with
3
//! the structured error ISS-031's shape names.
4

            
5
use crate::ast::{ClosureSigId, Expr, LambdaParams, Number, WasmType};
6
use crate::compiler::context::CompileContext;
7
use crate::compiler::emit::FunctionEmitter;
8
use crate::compiler::expr::{
9
    classify_stack_type, compile_for_stack, compile_for_stack_as, emit_box_anyref,
10
    is_probe_rejection, is_untyped, probe_value,
11
};
12
use crate::compiler::join::{Arm, reconcile_arms};
13
use crate::compiler::recompile::compiled_in_trial;
14
use crate::error::{Error, Result, with_article};
15
use crate::runtime::{ClosureShape, HomeKey, SymbolTable};
16

            
17
/// Where a store lands: a global's cell, or the home of an assigned binder's
18
/// local, whose type the stores of an attempt can widen for the next one.
19
#[derive(Clone, Copy)]
20
enum Landing<'a> {
21
    Cell(&'a str),
22
    Binder(&'a str, &'a HomeKey),
23
}
24

            
25
impl Landing<'_> {
26
395514
    fn name(&self) -> &str {
27
395514
        match self {
28
395514
            Self::Cell(name) | Self::Binder(name, _) => name,
29
        }
30
395514
    }
31

            
32
1126323
    fn key(&self) -> HomeKey {
33
1126323
        match self {
34
671364
            Self::Cell(name) => HomeKey::Global((*name).to_string()),
35
454959
            Self::Binder(_, key) => (*key).clone(),
36
        }
37
1126323
    }
38

            
39
379219
    fn probe_at_init(&self, symbols: &SymbolTable) -> Option<SymbolTable> {
40
379219
        symbols.probe_at_init(&self.key(), self.name())
41
379219
    }
42
}
43

            
44
/// Compiles the value stored into the runtime local backing `place`, coerced
45
/// to the local's type. A global cell (§Stores to globals) refuses a value
46
/// of another representation — a list into an Index cell, `nil` into a cell
47
/// that can never be nil — with the structured error ISS-031's shape names. An
48
/// assigned binder's local refuses it the same way, and its home records the
49
/// store, so the unit compiles again with the local wide enough.
50
822888
pub(in crate::compiler) fn compile_store_value(
51
822888
    ctx: &mut CompileContext,
52
822888
    emit: &mut FunctionEmitter,
53
822888
    symbols: &mut SymbolTable,
54
822888
    place: &Expr,
55
822888
    value_expr: &Expr,
56
822888
    ty: WasmType,
57
822888
) -> Result<()> {
58
822888
    if let Expr::Symbol(name) = place {
59
764082
        reject_captured_assignment(symbols, name)?;
60
58806
    }
61
822888
    let home = place
62
822888
        .as_symbol()
63
764082
        .and_then(|name| symbols.lookup(name)?.home().cloned());
64
822888
    let landing = match (place, &home) {
65
764082
        (Expr::Symbol(name), _) if symbols.cell_global(name).is_some() => Landing::Cell(name),
66
328932
        (Expr::Symbol(name), Some(key)) => Landing::Binder(name, key),
67
60404
        _ => return compile_for_stack_as(ctx, emit, symbols, value_expr, ty),
68
    };
69
762484
    let probed = probe_value(&mut symbols.clone(), value_expr)?;
70
762484
    if let Landing::Cell(cell) = landing
71
433552
        && !probed.is_wasm_runtime()
72
124611
        && !matches!(probed, Expr::Lambda(..))
73
    {
74
114783
        symbols.note_home_datum(cell, &probed);
75
647701
    }
76
762484
    match literal_arm(&probed) {
77
141974
        Some(arm) => store_literal(
78
141974
            ctx,
79
141974
            emit,
80
141974
            symbols,
81
141974
            (landing, ty),
82
141974
            value_expr,
83
141974
            (&probed, arm),
84
141974
        ),
85
620510
        None => store_compiled(ctx, emit, symbols, (landing, ty), value_expr, &probed),
86
    }
87
822888
}
88

            
89
/// A numeric literal or `nil` is typed by the home it lands in, so its arm is
90
/// known before it compiles.
91
1582213
pub(in crate::compiler) fn literal_arm(probed: &Expr) -> Option<Arm> {
92
1582213
    match probed {
93
915219
        Expr::Number(_) | Expr::Nil => store_arm(probed),
94
666994
        _ => None,
95
    }
96
1582213
}
97

            
98
141974
fn store_literal(
99
141974
    ctx: &mut CompileContext,
100
141974
    emit: &mut FunctionEmitter,
101
141974
    symbols: &mut SymbolTable,
102
141974
    (landing, ty): (Landing, WasmType),
103
141974
    value_expr: &Expr,
104
141974
    (probed, arm): (&Expr, Arm),
105
141974
) -> Result<()> {
106
141974
    if emit.is_reachable() {
107
139884
        fit(ctx, symbols, (landing, ty), arm, probed)?;
108
2090
    }
109
133944
    compile_into_home(
110
133944
        ctx,
111
133944
        emit,
112
133944
        symbols,
113
133944
        value_expr,
114
133944
        ty,
115
133944
        matches!(probed, Expr::Nil),
116
133944
    )
117
141974
}
118

            
119
/// Compiles the value as it is, records what codegen pushed as the store's
120
/// arm, then fits it into the home: a closure joins to `AnyRef`, so a home
121
/// never carries a closure type to the next attempt.
122
620510
fn store_compiled(
123
620510
    ctx: &mut CompileContext,
124
620510
    emit: &mut FunctionEmitter,
125
620510
    symbols: &mut SymbolTable,
126
620510
    (landing, ty): (Landing, WasmType),
127
620510
    value_expr: &Expr,
128
620510
    probed: &Expr,
129
620510
) -> Result<()> {
130
620510
    let actual = compile_for_stack(ctx, emit, symbols, value_expr).or_else(|err| {
131
5959
        if is_probe_rejection(&err) {
132
5959
            note_init_store(ctx, emit, symbols, &landing, value_expr)?;
133
        }
134
5959
        Err(err)
135
5959
    })?;
136
614551
    if !emit.is_reachable() {
137
8182
        emit.unreachable();
138
8182
        return Ok(());
139
606369
    }
140
606369
    let stored = Expr::WasmRuntime(actual);
141
606369
    let shown = if is_untyped(probed) { &stored } else { probed };
142
606369
    let arm = compiled_arm(symbols, (&landing, ty), value_expr, actual)?;
143
606369
    fit(ctx, symbols, (landing, ty), arm, shown)?;
144
598104
    if ty != WasmType::AnyRef {
145
577158
        return Ok(());
146
20946
    }
147
20946
    emit_box_anyref(ctx, emit, actual);
148
20946
    match landing {
149
12354
        Landing::Cell(cell) => note_stored_closure(ctx, symbols, cell, actual),
150
8592
        Landing::Binder(..) => Ok(()),
151
    }
152
620510
}
153

            
154
/// Records the store's arm in the home; a store the home cannot hold is refused.
155
746253
fn fit(
156
746253
    ctx: &CompileContext,
157
746253
    symbols: &SymbolTable,
158
746253
    (landing, ty): (Landing, WasmType),
159
746253
    arm: Arm,
160
746253
    shown: &Expr,
161
746253
) -> Result<()> {
162
746253
    symbols.note_store(&landing.key(), arm);
163
746253
    if reconcile_arms(&[Arm::Value(ty), arm]) != ty {
164
16295
        if let Landing::Cell(cell) = landing {
165
9320
            symbols.refuse_seed(cell);
166
6975
        }
167
16295
        return Err(cell_store_error(ctx, landing.name(), shown, ty));
168
729958
    }
169
729958
    Ok(())
170
746253
}
171

            
172
/// A store the home's own type rejects (it reads the home) is typed as its
173
/// first execution sees it, compiled with the variable holding its init.
174
5959
fn note_init_store(
175
5959
    ctx: &mut CompileContext,
176
5959
    emit: &FunctionEmitter,
177
5959
    symbols: &SymbolTable,
178
5959
    landing: &Landing,
179
5959
    value_expr: &Expr,
180
5959
) -> Result<()> {
181
5959
    let Some(mut probe) = landing.probe_at_init(symbols) else {
182
1070
        return Ok(());
183
    };
184
4889
    if let Some(arm) = literal_arm(&probe_value(&mut probe.clone(), value_expr)?) {
185
630
        symbols.note_store(&landing.key(), arm);
186
    } else if let Some(Some(ty)) =
187
4259
        compiled_in_trial(ctx, &mut probe, emit, value_expr, |_, ty| Ok(ty))?
188
    {
189
221
        symbols.note_store(&landing.key(), Arm::Value(ty));
190
4038
    }
191
4889
    Ok(())
192
5959
}
193

            
194
/// The arm of a store compiled to an index in an index home: a value its first
195
/// execution folds to an integer is a literal, which a scalar home adopts. In a
196
/// wider home the index it still compiles to is a runtime value.
197
606369
fn compiled_arm(
198
606369
    symbols: &SymbolTable,
199
606369
    (landing, ty): (&Landing, WasmType),
200
606369
    value_expr: &Expr,
201
606369
    actual: WasmType,
202
606369
) -> Result<Arm> {
203
606369
    let literal = match (actual, ty) {
204
373260
        (WasmType::I32, WasmType::I32) => match landing.probe_at_init(symbols) {
205
361620
            Some(mut probe) => literal_arm(&probe_value(&mut probe, value_expr)?),
206
11640
            None => None,
207
        },
208
233109
        _ => None,
209
    };
210
606369
    Ok(literal.unwrap_or(Arm::Value(actual)))
211
606369
}
212

            
213
1396707
pub(in crate::compiler) fn store_arm(value: &Expr) -> Option<Arm> {
214
1396707
    match value {
215
1396707
        _ if is_untyped(value) => None,
216
1194812
        Expr::Number(Number::Index(_)) => Some(Arm::NumberLiteral(WasmType::I32)),
217
33166
        Expr::Number(Number::Scalar(_)) => Some(Arm::NumberLiteral(WasmType::Ratio)),
218
152873
        Expr::Nil => Some(Arm::Nil),
219
15856
        other => classify_stack_type(other).map(Arm::Value),
220
    }
221
1396707
}
222

            
223
/// Compiles `value_expr` as the content of a home of type `ty`; a home of
224
/// any value (a nil-able special some binder binds to anything) boxes it.
225
763911
pub(in crate::compiler) fn compile_into_home(
226
763911
    ctx: &mut CompileContext,
227
763911
    emit: &mut FunctionEmitter,
228
763911
    symbols: &mut SymbolTable,
229
763911
    value_expr: &Expr,
230
763911
    ty: WasmType,
231
763911
    is_nil: bool,
232
763911
) -> Result<()> {
233
763911
    if ty != WasmType::AnyRef || is_nil {
234
743774
        return compile_for_stack_as(ctx, emit, symbols, value_expr, ty);
235
20137
    }
236
20137
    let actual = compile_for_stack(ctx, emit, symbols, value_expr)?;
237
20137
    emit_box_anyref(ctx, emit, actual);
238
20137
    Ok(())
239
763911
}
240

            
241
/// A closure boxed into a provisional `AnyRef` cell asks the next attempt for
242
/// a cell of its own signature.
243
12354
fn note_stored_closure(
244
12354
    ctx: &CompileContext,
245
12354
    symbols: &SymbolTable,
246
12354
    cell: &str,
247
12354
    actual: WasmType,
248
12354
) -> Result<()> {
249
12354
    if let WasmType::Closure(sig) = actual {
250
3871
        let sig = ctx.closure_sig(sig)?;
251
3871
        if let Some(shape) = ClosureShape::of(&sig.params, sig.result) {
252
3871
            symbols.note_closure_shape(cell, shape);
253
        }
254
8483
    }
255
12354
    Ok(())
256
12354
}
257

            
258
/// The net for a binder the cell scan does not cover: its variable is held by
259
/// the closure as a copy, so an assignment is a structured error, never a
260
/// silently stale read.
261
1357936
pub(in crate::compiler) fn reject_captured_assignment(
262
1357936
    symbols: &SymbolTable,
263
1357936
    name: &str,
264
1357936
) -> Result<()> {
265
1357936
    match symbols.lookup(name) {
266
1357935
        Some(symbol) if symbol.is_captured() => Err(captured_store_error(name)),
267
1357936
        _ => Ok(()),
268
    }
269
1357936
}
270

            
271
208
pub(in crate::compiler) fn captured_store_error(name: &str) -> Error {
272
208
    Error::Compile(format!(
273
208
        "{name}: a closure stores to a captured variable through a macro or an inlined function, or captures a variable an uncovered binder assigns; not supported yet"
274
208
    ))
275
208
}
276

            
277
/// The store error of a home.
278
16301
fn cell_store_error(ctx: &CompileContext, name: &str, stored: &Expr, ty: WasmType) -> Error {
279
16301
    store_message(ctx, name, stored, ty).map_or_else(|err| err, Error::Compile)
280
16301
}
281

            
282
16301
fn store_message(ctx: &CompileContext, name: &str, stored: &Expr, ty: WasmType) -> Result<String> {
283
16301
    let dim = match ty {
284
9911
        WasmType::I32 => "an Index".to_string(),
285
636
        WasmType::Ratio => "a Scalar".to_string(),
286
        WasmType::Commodity => "a Money".to_string(),
287
430
        WasmType::Closure(sig) => closure_text(ctx, sig)?,
288
5324
        other => with_article(other),
289
    };
290
16301
    Ok(format!(
291
16301
        "{name}: store of {} into {dim} cell",
292
16301
        stored_text(ctx, stored, ty)?
293
    ))
294
16301
}
295

            
296
/// A closure signature as `a closure (ratio, i32) -> ratio`.
297
432
fn closure_text(ctx: &CompileContext, sig: ClosureSigId) -> Result<String> {
298
432
    let sig = ctx.closure_sig(sig)?;
299
432
    let params: Vec<String> = sig.params.iter().map(ToString::to_string).collect();
300
432
    Ok(format!(
301
432
        "a closure ({}) -> {}",
302
432
        params.join(", "),
303
432
        sig.result
304
432
    ))
305
432
}
306

            
307
/// The stored value: a closure place by its signature; a lambda literal, whose
308
/// types are not emitted yet, by its parameter count, or as another signature
309
/// when the count matches the closure cell's.
310
16301
fn stored_text(ctx: &CompileContext, stored: &Expr, cell: WasmType) -> Result<String> {
311
16301
    Ok(match (stored, stored.place()) {
312
2
        (_, Some((_, WasmType::Closure(sig)))) => closure_text(ctx, sig)?,
313
        (Expr::Lambda(params, _), _) => {
314
652
            let arity = parameter_count(params);
315
652
            match cell {
316
216
                WasmType::Closure(sig) if ctx.closure_sig(sig)?.params.len() == arity => {
317
209
                    "a closure of another signature".to_string()
318
                }
319
443
                _ => format!("a {arity}-parameter closure"),
320
            }
321
        }
322
15647
        _ => with_article(value_kind(stored)),
323
    })
324
16301
}
325

            
326
653
fn parameter_count(params: &LambdaParams) -> usize {
327
653
    params.required.len()
328
653
        + params.optional.len()
329
653
        + params.key.len()
330
653
        + params.aux.len()
331
653
        + usize::from(params.rest.is_some())
332
653
}
333

            
334
/// The user-facing kind of a resolved value, for the cell-store error.
335
15647
fn value_kind(value: &Expr) -> &'static str {
336
15647
    match value {
337
1683
        Expr::Nil => "nil",
338
3
        Expr::T => "t",
339
6348
        Expr::Number(_) => "number",
340
838
        Expr::String(_) => "string",
341
        Expr::Lambda(_, _) => "closure",
342
1274
        Expr::Quote(inner) | Expr::Datum(inner) => match inner.as_ref() {
343
1271
            Expr::List(_) | Expr::Cons(_, _) => "list",
344
3
            _ => "symbol",
345
        },
346
        Expr::List(_) | Expr::Cons(_, _) => "list",
347
5293
        Expr::WasmRuntime(ty) | Expr::WasmLocal(_, ty) | Expr::WasmGlobal(_, ty) => match ty {
348
841
            WasmType::I32 => "index",
349
7
            WasmType::Ratio => "scalar",
350
416
            WasmType::Commodity => "money",
351
2559
            WasmType::PairRef(_) => "list",
352
            WasmType::StringRef => "string",
353
            WasmType::SymbolRef => "symbol",
354
211
            WasmType::EntityRef(_) => "entity",
355
208
            WasmType::StructRef(_) => "structure",
356
            WasmType::Closure(_) => "closure",
357
            WasmType::Bool => "boolean",
358
1051
            WasmType::AnyRef => "value of unknown type",
359
        },
360
208
        _ => "value",
361
    }
362
15647
}
363

            
364
#[cfg(test)]
365
#[path = "cell_store_tests.rs"]
366
mod tests;