1
//! The fold-safety predicate and the one fold entry (0014 Stage 2).
2
//!
3
//! A codegen site may replace a form by its evaluated value only through
4
//! [`fold_value`], which evaluates nothing unless [`fold_safe`] holds: every
5
//! symbol the form reads resolves to a binder inside it or to a constant
6
//! datum in the table (no runtime value, no stored global, no function), the
7
//! form transfers nowhere, performs no effect, and every head is in
8
//! [`FOLD_HEADS`] — a fixed set whose eval functions each return a constant
9
//! datum or an error and leave the table as they found it (the per-head
10
//! lemma, pinned by `tests`). What the predicate refuses is compiled.
11

            
12
pub(crate) mod stores;
13
pub(crate) mod template;
14
pub(crate) mod walk;
15

            
16
#[cfg(test)]
17
mod stores_tests;
18
#[cfg(test)]
19
mod tests;
20
#[cfg(test)]
21
mod walk_tests;
22

            
23
use crate::ast::{Expr, WasmType};
24
use crate::error::{Error, Result};
25
use crate::runtime::{SymbolTable, Value};
26

            
27
use super::eval_value;
28
use walk::{Node, Scope, Step, Visit, walk_body};
29

            
30
/// The heads a fold-safe form may use (the whitelist `W`). Every head not
31
/// here is non-inert until its eval function is shown to satisfy the
32
/// per-head lemma; `tests::every_head_outside_the_whitelist_is_refused`
33
/// enumerates both registries against this list. `UPCASE-STRING` is the
34
/// one eval-only native admitted: it has no codegen, and its eval returns
35
/// a string datum or errs on anything else. `CAR`, `CDR`, `REVERSE` and
36
/// `APPEND` return an element, a tail or a fresh quoted list of constant
37
/// operands, or err on a non-list; `PAIR?`, `NULL?`, `ZEROP`, `PLUSP` and
38
/// `MINUSP` return `t` / `nil` (the sign three err on a non-number).
39
/// `MACROEXPAND-1` and `MACROEXPAND` expand in a private clone of the table and return the
40
/// expansion datum (a runtime result is refused by `is_constant_datum`). `STRING=`
41
/// stays out: on constant non-string operands it answers a placeholder.
42
/// `MAP`, `FILTER` and `FOLD` call a function argument (obligation (c)).
43
pub(crate) const FOLD_HEADS: &[&str] = &[
44
    "BLOCK",
45
    "IF",
46
    "PROGN",
47
    "LET",
48
    "LET*",
49
    "DOLIST",
50
    "AND",
51
    "OR",
52
    "QUOTE",
53
    "LIST",
54
    "CONS",
55
    "LENGTH",
56
    "CAR",
57
    "CDR",
58
    "REVERSE",
59
    "APPEND",
60
    "GETF",
61
    "ASSOC",
62
    "MEMBER",
63
    "PAIR?",
64
    "MACROEXPAND-1",
65
    "MACROEXPAND",
66
    "NOT",
67
    "NULL?",
68
    "=",
69
    "/=",
70
    "<",
71
    ">",
72
    "<=",
73
    ">=",
74
    "+",
75
    "-",
76
    "*",
77
    "/",
78
    "MOD",
79
    "UPCASE-STRING",
80
    "SYMBOLP",
81
    "KEYWORDP",
82
    "SYMBOL-NAME",
83
    "THE",
84
    "ZEROP",
85
    "PLUSP",
86
    "MINUSP",
87
];
88

            
89
9868472
fn whitelisted(head: &str) -> bool {
90
326947988
    FOLD_HEADS.iter().any(|h| h.eq_ignore_ascii_case(head))
91
9868472
}
92

            
93
/// Whether evaluating `form` can only produce a constant datum or an error,
94
/// with no effect, no transfer and no runtime reference (obligations (e),
95
/// (f), (b), (c) of 0014 Stage 2).
96
17586686
pub(crate) fn fold_safe(symbols: &SymbolTable, form: &Expr) -> bool {
97
17586686
    fold_safe_under(symbols, &[], form)
98
17586686
}
99

            
100
/// [`fold_safe`] with the variables `bound` treated as constant binders of
101
/// the form (a loop's variables while its control is checked).
102
18173782
pub(crate) fn fold_safe_under(symbols: &SymbolTable, bound: &[&str], form: &Expr) -> bool {
103
18173782
    let mut visitor = FoldSafe;
104
18173782
    matches!(
105
18173782
        walk_body(symbols, bound, std::slice::from_ref(form), &mut visitor),
106
        Ok(false)
107
    )
108
18173782
}
109

            
110
/// Whether `form` is [`fold_safe`] but for the variables it reads: no effect,
111
/// no call outside [`FOLD_HEADS`], and no head that may signal beside a runtime read.
112
17133
pub(crate) fn reads_only(symbols: &SymbolTable, form: &Expr) -> bool {
113
17133
    let mut visitor = ReadsOnly::default();
114
17133
    let walked = walk_body(symbols, &[], std::slice::from_ref(form), &mut visitor);
115
17133
    matches!(walked, Ok(false)) && !(visitor.reads_runtime && visitor.may_signal)
116
17133
}
117

            
118
/// The constant datum `form` folds to, or `None` when it must be compiled:
119
/// it is not fold-safe, or its evaluation raised an error a handler could
120
/// catch at runtime. A resource ceiling propagates: budget exhaustion is
121
/// never permission to keep emitting. A fold-safe form has no free symbol, so
122
/// a bare symbol result is a datum a selector extracted and is returned
123
/// quoted, as CL yields it (the normalisation of obligation (f)).
124
6164849
pub(crate) fn fold_value(symbols: &mut SymbolTable, form: &Expr) -> Result<Option<Expr>> {
125
6164849
    if !fold_safe(symbols, form) {
126
3239097
        return Ok(None);
127
2925752
    }
128
2925752
    match eval_value(symbols, form) {
129
        Ok(Expr::Symbol(name)) => Ok(Some(Expr::quoted(Expr::Symbol(name)))),
130
2906083
        Ok(value) => Ok((is_constant_datum(&value) || is_instance_leaf(&value)).then_some(value)),
131
19669
        Err(err) if is_operation_error(&err) => Ok(None),
132
209
        Err(other) => Err(other),
133
    }
134
6164849
}
135

            
136
/// An error the operation itself raises: compiled, the form raises it (or its
137
/// own rejection) at runtime, so it is no verdict on the form.
138
19671
pub(crate) fn is_operation_error(err: &Error) -> bool {
139
19671
    matches!(
140
19671
        err,
141
        Error::Compile(_)
142
            | Error::Dimension(_)
143
            | Error::UnclosableFactory { .. }
144
            | Error::Type { .. }
145
            | Error::Arity { .. }
146
            | Error::UndefinedSymbol(_)
147
    )
148
19671
}
149

            
150
/// Evaluates `expr` as a lowering probe: an operation the evaluator rejects
151
/// reads as a runtime value of unknown type, so the operand is compiled and
152
/// raises there. A malformed call (an undefined symbol, a wrong arity), a
153
/// resource ceiling and a transfer still propagate.
154
38900207
pub(crate) fn probe_value(symbols: &mut SymbolTable, expr: &Expr) -> Result<Expr> {
155
38900207
    match eval_value(symbols, expr) {
156
114494
        Err(err) if is_probe_rejection(&err) => Ok(Expr::WasmRuntime(WasmType::AnyRef)),
157
38835522
        other => other,
158
    }
159
38900207
}
160

            
161
/// [`probe_value`] for a caller that types the operand from the result: a
162
/// dimension error is the operand's own verdict, not an unknown type.
163
51910
pub(crate) fn probe_typed(symbols: &mut SymbolTable, expr: &Expr) -> Result<Expr> {
164
51910
    match eval_value(symbols, expr) {
165
3
        Err(err @ Error::Dimension(_)) => Err(err),
166
        Err(err) if is_probe_rejection(&err) => Ok(Expr::WasmRuntime(WasmType::AnyRef)),
167
51907
        other => other,
168
    }
169
51910
}
170

            
171
/// The condition message of a constant division or `MOD` by zero, the one
172
/// operation error that is a runtime condition (ISS-065), not a compile error.
173
pub(crate) const DIVISION_BY_ZERO: &str = "division by zero";
174

            
175
33010
pub(crate) fn is_division_by_zero(err: &Error) -> bool {
176
33010
    matches!(err, Error::Compile(msg) if msg.starts_with(DIVISION_BY_ZERO))
177
33010
}
178

            
179
/// Whether `form` is a fold-safe operation that always raises the division
180
/// condition: compiled, it throws, so no dimension is ever observed.
181
10041141
pub(crate) fn raises_division(symbols: &SymbolTable, form: &Expr) -> bool {
182
10041141
    fold_safe(symbols, form)
183
2683044
        && matches!(
184
2683044
            eval_value(&mut symbols.clone(), form),
185
14023
            Err(ref err) if is_division_by_zero(err)
186
        )
187
10041141
}
188

            
189
/// What a mistyped operand is, for a type error: its constant datum when it
190
/// folds to one, else its static type `ty`.
191
8353
pub(crate) fn describe_operand(symbols: &SymbolTable, operand: &Expr, ty: WasmType) -> String {
192
8353
    match probe_value(&mut symbols.clone(), operand) {
193
8353
        Ok(value) if is_constant_datum(&value) => super::format_expr(&value),
194
2929
        _ => ty.to_string(),
195
    }
196
8353
}
197

            
198
/// An operand [`probe_value`] could not type: rejected by the evaluator, or an
199
/// opaque runtime value. Only compiling it tells what it pushes.
200
7686330
pub(crate) fn is_untyped(probed: &Expr) -> bool {
201
7686330
    matches!(probed, Expr::WasmRuntime(WasmType::AnyRef))
202
7686330
}
203

            
204
/// An evaluator rejection a probe reads as a runtime value.
205
120456
pub(crate) fn is_probe_rejection(err: &Error) -> bool {
206
120456
    matches!(
207
120456
        err,
208
        Error::Compile(_) | Error::Dimension(_) | Error::Type { .. }
209
    )
210
120456
}
211

            
212
/// [`fold_value`] of `(HEAD args…)`: the one entry a native uses to ask
213
/// whether its call folds.
214
242891
pub(crate) fn fold_call(
215
242891
    symbols: &mut SymbolTable,
216
242891
    head: &str,
217
242891
    args: &[Expr],
218
242891
) -> Result<Option<Expr>> {
219
242891
    let form = Expr::List(
220
242891
        std::iter::once(Expr::symbol(head))
221
242891
            .chain(args.iter().cloned())
222
242891
            .collect(),
223
242891
    );
224
242891
    fold_value(symbols, &form)
225
242891
}
226

            
227
/// A self-evaluating value: the reader's literals and quoted or listed data
228
/// with no runtime placeholder, closure or bare symbol inside.
229
2921429
pub(crate) fn is_constant_datum(value: &Expr) -> bool {
230
2921429
    is_datum(value, false)
231
2921429
}
232

            
233
/// [`is_constant_datum`], with struct instance leaves counted as data when
234
/// `instances`.
235
9187236
fn is_datum(value: &Expr, instances: bool) -> bool {
236
9187236
    match value {
237
        Expr::Nil
238
        | Expr::T
239
        | Expr::Number(_)
240
        | Expr::String(_)
241
        | Expr::Bytes(_)
242
4276380
        | Expr::Keyword(_) => true,
243
250661
        Expr::Datum(inner) => is_data_with(inner, instances),
244
6
        Expr::List(items) => items.iter().all(|item| is_data_with(item, instances)),
245
        Expr::Cons(car, cdr) => is_data_with(car, instances) && is_data_with(cdr, instances),
246
4660193
        _ => false,
247
    }
248
9187236
}
249

            
250
115046
pub(crate) fn is_instance_leaf(value: &Expr) -> bool {
251
115046
    matches!(value, Expr::Instance(_, _))
252
115046
}
253

            
254
/// Whether a quoted element is data: anything but a runtime placeholder,
255
/// a compile-time value or a closure; a struct instance leaf only when
256
/// `instances`.
257
132670460
fn is_data_with(value: &Expr, instances: bool) -> bool {
258
132670460
    match value {
259
2080
        Expr::RuntimeValue(Value::Commodity { .. }) => true,
260
3341107
        Expr::Instance(_, _) => instances,
261
        Expr::WasmRuntime(_)
262
        | Expr::WasmLocal(_, _)
263
        | Expr::WasmGlobal(_, _)
264
        | Expr::RuntimeValue(_)
265
853
        | Expr::Lambda(_, _) => false,
266
        Expr::Quote(inner)
267
        | Expr::Datum(inner)
268
        | Expr::Quasiquote(inner)
269
        | Expr::Unquote(inner)
270
54
        | Expr::UnquoteSplicing(inner) => is_data_with(inner, instances),
271
132417241
        Expr::List(items) => items.iter().all(|item| is_data_with(item, instances)),
272
1249
        Expr::Cons(car, cdr) => is_data_with(car, instances) && is_data_with(cdr, instances),
273
125529650
        _ => true,
274
    }
275
132670460
}
276

            
277
/// A constant list whose members may be struct instance leaves: the one source
278
/// a fold may read an instance out of, since a list is immutable and an
279
/// instance's identity is its serial.
280
6265807
fn is_instance_source(value: &Expr) -> bool {
281
6265807
    is_datum(value, true)
282
6265807
}
283

            
284
/// Whether the table entry `name` is a constant datum a fold may read: a
285
/// variable holding self-evaluating data that no store in the unit makes a
286
/// runtime cell (§Stores to globals).
287
6799832
fn constant_entry(symbols: &SymbolTable, name: &str) -> bool {
288
6799832
    if symbols.is_stored_global(name) {
289
526466
        return false;
290
6273366
    }
291
6273366
    symbols
292
6273366
        .lookup(name)
293
6271460
        .is_some_and(|sym| sym.is_variable() && sym.value().is_some_and(is_instance_source))
294
6799832
}
295

            
296
/// Whether `name` holds a value only the running program knows, one a
297
/// signalling head could reject; an evaluator-held value (a closure list) is
298
/// known to be well-typed.
299
21
fn reads_runtime_value(symbols: &SymbolTable, name: &str) -> bool {
300
21
    symbols
301
21
        .lookup(name)
302
21
        .and_then(|sym| sym.value())
303
21
        .is_none_or(Expr::is_wasm_runtime)
304
21
}
305

            
306
struct FoldSafe;
307

            
308
/// A form that both reads a runtime variable and calls a head outside
309
/// `NEVER_SIGNALS` may signal on that value, so it is not quiet.
310
#[derive(Default)]
311
struct ReadsOnly {
312
    reads_runtime: bool,
313
    may_signal: bool,
314
}
315

            
316
/// Building a closure runs nothing; its body runs only when it is called.
317
5722
fn is_closure_form(head: &str) -> bool {
318
5722
    ["LAMBDA", "FUNCTION"]
319
5722
        .iter()
320
10387
        .any(|name| head.eq_ignore_ascii_case(name))
321
5722
}
322

            
323
/// Heads that cannot signal whatever their operands hold: control and
324
/// constructors only. Every other whitelisted head type-checks or divides
325
/// at runtime, so over runtime operands it is a call that may leave.
326
const NEVER_SIGNALS: &[&str] = &[
327
    "BLOCK", "IF", "PROGN", "LET", "LET*", "AND", "OR", "QUOTE", "LIST", "CONS", "PAIR?", "NULL?",
328
    "NOT",
329
];
330

            
331
5758
fn never_signals(head: &str) -> bool {
332
51736
    NEVER_SIGNALS.iter().any(|h| h.eq_ignore_ascii_case(head))
333
5758
}
334

            
335
impl Visit for ReadsOnly {
336
21219
    fn visit(&mut self, env: &SymbolTable, scope: &Scope, node: Node<'_>) -> Step {
337
21219
        match node {
338
            Node::Free(name) => {
339
21
                self.reads_runtime |= reads_runtime_value(env, name);
340
21
                Step::Skip
341
            }
342
5722
            Node::Special(head, _) if is_closure_form(head) => Step::Skip,
343
4665
            Node::Special(head, _) | Node::Native(head) if !never_signals(head) => {
344
3191
                self.may_signal |= whitelisted(head);
345
3191
                FoldSafe.visit(env, scope, node)
346
            }
347
16950
            other => FoldSafe.visit(env, scope, other),
348
        }
349
21219
    }
350

            
351
650
    fn prunes_dead_branches(&self) -> bool {
352
650
        true
353
650
    }
354
}
355

            
356
impl Visit for FoldSafe {
357
858920590
    fn visit(&mut self, env: &SymbolTable, _scope: &Scope, node: Node<'_>) -> Step {
358
858920590
        match node {
359
            // A lambda a body discards is a value built and dropped; its
360
            // body is never evaluated.
361
840597956
            Node::Datum | Node::DiscardedLambda => Step::Skip,
362
101217
            Node::Special(head, [_, Expr::Symbol(_)]) if head.eq_ignore_ascii_case("FUNCTION") => {
363
83374
                Step::Skip
364
            }
365
6799832
            Node::Free(name) if constant_entry(env, name) => Step::Skip,
366
4944652
            Node::Special(head, _) | Node::Native(head) if whitelisted(head) => Step::Descend,
367
            Node::Free(_)
368
            | Node::Special(..)
369
            | Node::Native(_)
370
            | Node::Call
371
            | Node::OpaqueMacro
372
11623959
            | Node::Other => Step::Found,
373
        }
374
858920590
    }
375

            
376
    /// The dead branch of an IF with a literal test is never evaluated, so
377
    /// nothing in it can run.
378
147639
    fn prunes_dead_branches(&self) -> bool {
379
147639
        true
380
147639
    }
381
}