1
//! The cells a unit makes of the globals it writes (plan 0014 PERSIST): each
2
//! is allocated, seeded and registered before the first form compiles, with
3
//! one i32 flag that is 1 once the cell holds a value.
4

            
5
use crate::ast::{Expr, WasmType};
6
use crate::compiler::context::{CompileContext, LOST_FLAG};
7
use crate::compiler::emit::FunctionEmitter;
8
use crate::compiler::expr::fold::stores::StoreScan;
9
use crate::compiler::join::{Arm, reconcile_arms};
10
use crate::error::Result;
11
use crate::runtime::{HomeKey, Seed, Slot, Symbol, SymbolKind, SymbolTable, is_list_source};
12

            
13
use super::super::cell_store::store_arm;
14
use super::define::{
15
    closure_home, expansion_datum, list_source_home, register_expansion_value, seeded_home,
16
};
17
use super::let_compile::record_closure_result;
18

            
19
/// Makes a cell of every global the scan names, in name order. A cell with an
20
/// earlier unit's constant starts bound to it, one with an earlier unit's value
21
/// no constant holds starts bound but unreadable (flag `LOST_FLAG`); any other starts unbound, typed
22
/// by its first writer when that is a literal and by the previous attempt's
23
/// hint, or provisionally `AnyRef` until a second attempt joins its stores.
24
2341618
pub(super) fn allocate_cells(
25
2341618
    ctx: &mut CompileContext,
26
2341618
    emit: &mut FunctionEmitter,
27
2341618
    symbols: &mut SymbolTable,
28
2341618
    scan: &StoreScan,
29
2341618
) -> Result<()> {
30
2341618
    scan.cells()
31
2341618
        .iter()
32
484752
        .try_for_each(|name| allocate_cell(ctx, emit, symbols, scan, name))
33
2341618
}
34

            
35
484752
fn allocate_cell(
36
484752
    ctx: &mut CompileContext,
37
484752
    emit: &mut FunctionEmitter,
38
484752
    symbols: &mut SymbolTable,
39
484752
    scan: &StoreScan,
40
484752
    name: &str,
41
484752
) -> Result<()> {
42
484752
    let flag = ctx.alloc_mutable_global(WasmType::I32)?;
43
484752
    let (seed, lost) = cell_seed(symbols, scan, name);
44
484752
    let kind = match (&seed, &lost) {
45
2912
        (Some(Expr::Lambda(..)), _) => Seed::Closure,
46
325732
        (Some(_), _) => Seed::Constant,
47
5826
        (None, Some(_)) => Seed::Lost,
48
150282
        (None, None) => Seed::Unbound,
49
    };
50
484752
    symbols.note_cell(name, flag, kind);
51
484752
    match &seed {
52
        Some(constant) => {
53
328644
            let home = seeded_home(ctx, emit, symbols, name, constant)?;
54
328644
            emit.i32_const(1);
55
328644
            emit.global_set(flag);
56
328644
            bind_home(symbols, name, home);
57
328644
            let datum = expansion_datum(symbols, name, constant);
58
328644
            register_expansion_value(symbols, name, datum);
59
        }
60
        None => {
61
156108
            let home = unbound_home(ctx, symbols, scan, name)?;
62
156108
            match (&home, lost) {
63
                (Expr::WasmGlobal(idx, _), Some(type_name)) => {
64
5826
                    emit.i32_const(LOST_FLAG);
65
5826
                    emit.global_set(flag);
66
5826
                    ctx.note_lost_cell(*idx, flag, name, &type_name)?;
67
                }
68
150282
                (Expr::WasmGlobal(idx, _), None) => ctx.note_unbound_cell(*idx, flag, name)?,
69
                _ => {}
70
            }
71
156108
            bind_home(symbols, name, home);
72
        }
73
    }
74
484752
    if !scan.defines(name) && !symbols.is_special(name) {
75
22383
        symbols.mark_special(name);
76
22383
        symbols.mark_created_global(name);
77
462369
    }
78
484752
    symbols.note_definition(name, Slot::Value, flag);
79
484752
    Ok(())
80
484752
}
81

            
82
/// What a cell starts as: an earlier unit's constant, else the type of a value
83
/// no constant holds. A lambda seeds a closure only when the unit stores
84
/// nothing but lambdas to it; any other store would need the cell to hold
85
/// both, so the lambda is then a value that does not survive the unit. A store
86
/// of another signature refuses the seed for the next attempt.
87
484752
fn cell_seed(
88
484752
    symbols: &SymbolTable,
89
484752
    scan: &StoreScan,
90
484752
    name: &str,
91
484752
) -> (Option<Expr>, Option<String>) {
92
484752
    match symbols.constant_global(name) {
93
        Some(Expr::Lambda(..))
94
8320
            if !scan.writes_only_lambdas(name) || symbols.is_seed_refused(name) =>
95
        {
96
5408
            (None, Some("closure".to_string()))
97
        }
98
328437
        Some(source) if is_list_source(&source) => (None, Some("list".to_string())),
99
328019
        Some(constant) => (Some(constant), None),
100
150907
        None => match symbols.instance_global(name) {
101
625
            Some(instance) => (Some(instance), None),
102
150282
            None => (None, symbols.lost_type(name).map(str::to_string)),
103
        },
104
    }
105
484752
}
106

            
107
/// The home of a cell nothing has written: a closure of the shape the previous
108
/// attempt stored, else typed by the first literal writer and the previous
109
/// attempt's hint, else provisionally `AnyRef`.
110
156108
fn unbound_home(
111
156108
    ctx: &mut CompileContext,
112
156108
    symbols: &mut SymbolTable,
113
156108
    scan: &StoreScan,
114
156108
    name: &str,
115
156108
) -> Result<Expr> {
116
156108
    if let Some(shape) = symbols.closure_hint(name) {
117
6117
        let ty = WasmType::Closure(ctx.intern_closure_signature(&shape.params, shape.result)?);
118
6117
        let home = Expr::WasmGlobal(ctx.alloc_mutable_global(ty)?, ty);
119
6117
        record_closure_result(symbols, ctx, &home)?;
120
6117
        return Ok(home);
121
149991
    }
122
149991
    let hint = symbols.hint(&HomeKey::global(name)).map(Arm::Value);
123
149991
    let literal = scan.first_literal(name);
124
149991
    let base: Vec<Arm> = hint
125
149991
        .into_iter()
126
149991
        .chain(literal.and_then(store_arm))
127
149991
        .collect();
128
149991
    let ty = match base.is_empty() {
129
        true => {
130
14366
            symbols.note_provisional_home(name);
131
14366
            WasmType::AnyRef
132
        }
133
        false => {
134
135625
            let ty = reconcile_arms(&base);
135
135625
            symbols.note_home(name, base, literal.cloned(), ty);
136
135625
            ty
137
        }
138
    };
139
149991
    Ok(Expr::WasmGlobal(ctx.alloc_mutable_global(ty)?, ty))
140
156108
}
141

            
142
/// Gives every lambda an earlier unit left a global that the unit names a
143
/// closure home, as if the unit began with a DEFVAR of it that ran, so the
144
/// host carries it on again.
145
2341606
pub(super) fn adopt_closures(
146
2341606
    ctx: &mut CompileContext,
147
2341606
    emit: &mut FunctionEmitter,
148
2341606
    symbols: &mut SymbolTable,
149
2341606
    scan: &StoreScan,
150
2341606
) -> Result<()> {
151
2341606
    scan.adopted()
152
2341606
        .iter()
153
31617
        .try_for_each(|name| adopt_closure(ctx, emit, symbols, name))
154
2341606
}
155

            
156
31617
fn adopt_closure(
157
31617
    ctx: &mut CompileContext,
158
31617
    emit: &mut FunctionEmitter,
159
31617
    symbols: &mut SymbolTable,
160
31617
    name: &str,
161
31617
) -> Result<()> {
162
31617
    let Some(lambda) = symbols.constant_global(name) else {
163
        return Ok(());
164
    };
165
31617
    let home = match is_list_source(&lambda) {
166
10401
        true => list_source_home(ctx, emit, symbols, &lambda)?,
167
21216
        false => closure_home(ctx, emit, symbols, name, &lambda, &lambda)?,
168
    };
169
31409
    bind_home(symbols, name, home);
170
31409
    let flag = ctx.alloc_mutable_global(WasmType::I32)?;
171
31409
    emit.i32_const(1);
172
31409
    emit.global_set(flag);
173
31409
    symbols.note_definition(name, Slot::Value, flag);
174
31409
    Ok(())
175
31617
}
176

            
177
516161
fn bind_home(symbols: &mut SymbolTable, name: &str, home: Expr) {
178
516161
    match symbols.lookup_mut(name) {
179
368792
        Some(symbol) => symbol.set_value(home),
180
147369
        None => symbols.define(Symbol::new(name, SymbolKind::Variable).with_value(home)),
181
    }
182
516161
}