1
//! The conservative store scan (0014 Stage 2, §Stores to globals): which
2
//! globals the unit about to compile writes. A global is a constant datum
3
//! only when the unit has no writer for it or exactly one DEFVAR /
4
//! DEFPARAMETER form whose init folds; any other writer makes it a runtime
5
//! cell for the whole unit, allocated before the first form compiles. An init
6
//! folds unless the attempt that compiled it found otherwise.
7
//!
8
//! The scan reads the whole unit's text before any form of it is compiled:
9
//! every `SETF` head, inside quoted and quasiquoted data, DEFUN/DEFMACRO/
10
//! LAMBDA bodies, every binder and arm. A template macro is expanded at its
11
//! use site and the expansion scanned. A macro whose expansion the scan does
12
//! not run can only store if the symbol `SETF` reaches it from the unit's
13
//! text, so any `SETF` the scan cannot tie to a place marks the unit
14
//! *possibly storing*, and an opaque macro use in such a unit stores to
15
//! every global the unit defines.
16

            
17
mod walker;
18

            
19
use std::collections::{BTreeMap, BTreeSet, HashSet};
20

            
21
use crate::ast::Expr;
22
use crate::compiler::CompileMode;
23
use crate::compiler::special::has_v1_param_shape;
24
use crate::error::Result;
25
use crate::reserved::reject_reserved;
26
use crate::runtime::{SymbolTable, is_list_source};
27

            
28
#[derive(Default, Debug)]
29
pub(crate) struct StoreScan {
30
    /// Each name a directly scanned `SETF` stores to, through a bare symbol
31
    /// place or a struct accessor.
32
    stored: BTreeSet<String>,
33
    /// The names stored through a bare symbol place.
34
    direct: BTreeSet<String>,
35
    /// The symbol `SETF` occurs where the scan cannot tie it to a place.
36
    possibly_storing: bool,
37
    /// Uses of macros whose expansion the scan does not run.
38
    opaque_uses: usize,
39
    /// The DEFVAR / DEFPARAMETER names of the unit, in order, repeats kept.
40
    defined: Vec<String>,
41
    /// Each name a DEFUN or DEFMACRO of the unit defines.
42
    functions: Vec<String>,
43
    /// Each name a binder introduces.
44
    rebound: BTreeSet<String>,
45
    /// The first writer of each name, when it is a scalar literal: it types
46
    /// the name's cell before any form compiles.
47
    literals: BTreeMap<String, Expr>,
48
    /// The names some writer has been noted for.
49
    written: BTreeSet<String>,
50
    /// The names some writer stores a lambda form to, and the names some
51
    /// writer stores anything else to.
52
    lambda_writers: BTreeSet<String>,
53
    other_writers: BTreeSet<String>,
54
    /// The names an unreadable macro use can store to: the symbols quoted in
55
    /// its macro's text and every symbol of its arguments.
56
    opaque_names: BTreeSet<String>,
57
    /// The globals the unit makes cells of.
58
    cells: BTreeSet<String>,
59
    /// Every name of the unit's text, and of the earlier-unit functions it runs.
60
    named: BTreeSet<String>,
61
    /// The names an earlier unit left a lambda for, which the unit names and
62
    /// does not make cells of: each gets a closure home.
63
    adopted: BTreeSet<String>,
64
    /// The cells some store reaches, found or assumed.
65
    stores: BTreeSet<String>,
66
    /// The cells that are specials some LET / LET* binds.
67
    dynamic: BTreeSet<String>,
68
}
69

            
70
impl StoreScan {
71
    /// The globals the unit makes runtime cells: every writer but exactly one
72
    /// DEFVAR / DEFPARAMETER form whose init folds makes one. An opaque macro use in a possibly
73
    /// storing unit stores to every global the unit defines or names.
74
2341696
    pub(crate) fn cells(&self) -> &BTreeSet<String> {
75
2341696
        &self.cells
76
2341696
    }
77

            
78
    /// The cells some store reaches: no fold may read them, and a macro body
79
    /// cannot see their init.
80
2341833
    pub(crate) fn stores(&self) -> HashSet<String> {
81
2341833
        self.stores.iter().cloned().collect()
82
2341833
    }
83

            
84
    /// The unit's DEFVAR / DEFPARAMETER names.
85
2341818
    pub(crate) fn defined(&self) -> HashSet<String> {
86
2341818
        self.defined.iter().cloned().collect()
87
2341818
    }
88

            
89
    /// The specials some LET / LET* binds, among those the unit defines and
90
    /// those an earlier unit left a value for: each is a dynamic special, a
91
    /// mutable global every binder saves and restores.
92
2341832
    pub(crate) fn dynamic(&self) -> HashSet<String> {
93
2341832
        self.dynamic.iter().cloned().collect()
94
2341832
    }
95

            
96
    /// The names whose lambda from an earlier unit the unit runs as a closure.
97
2341615
    pub(crate) fn adopted(&self) -> &BTreeSet<String> {
98
2341615
        &self.adopted
99
2341615
    }
100

            
101
    /// Whether every writer of `name` in the unit is a lambda form, so a cell
102
    /// that starts as a closure only ever holds one.
103
8325
    pub(crate) fn writes_only_lambdas(&self, name: &str) -> bool {
104
8325
        self.lambda_writers.contains(name)
105
3331
            && !self.other_writers.contains(name)
106
3330
            && !self.rebound.contains(name)
107
3329
            && !self.opaque_names.contains(name)
108
3329
            && (!self.stored.contains(name) || self.direct.contains(name))
109
8325
    }
110

            
111
    /// Whether the unit has a DEFVAR / DEFPARAMETER of `name`.
112
484752
    pub(crate) fn defines(&self, name: &str) -> bool {
113
484768
        self.defined.iter().any(|defined| defined == name)
114
484752
    }
115

            
116
    /// The scalar literal the unit first writes `name` to.
117
149995
    pub(crate) fn first_literal(&self, name: &str) -> Option<&Expr> {
118
149995
        self.literals.get(name)
119
149995
    }
120

            
121
    /// Every name the unit writes: defined, stored, rebound or given a
122
    /// function.
123
2341829
    pub(crate) fn written_names(&self) -> Vec<String> {
124
2341829
        let mut names: BTreeSet<String> = self.stored.clone();
125
2341829
        names.extend(self.defined.iter().cloned());
126
2341829
        names.extend(self.rebound.iter().cloned());
127
2341829
        names.extend(self.functions.iter().cloned());
128
2341829
        names.extend(self.adopted.iter().cloned());
129
2341829
        names.into_iter().collect()
130
2341829
    }
131

            
132
    /// Notes `value` as written to `name`; the first writer of a name types
133
    /// its cell when it is a scalar literal.
134
712235
    fn note_writer(&mut self, name: &str, value: Option<&Expr>) {
135
712235
        match value.is_some_and(is_lambda_form) {
136
41118
            true => self.lambda_writers.insert(name.to_string()),
137
671117
            false => self.other_writers.insert(name.to_string()),
138
        };
139
712235
        if value.is_none() || !self.written.insert(name.to_string()) {
140
86863
            return;
141
625372
        }
142
625372
        if let Some(
143
625372
            value @ (Expr::Number(_) | Expr::String(_) | Expr::Keyword(_) | Expr::T | Expr::Nil),
144
625372
        ) = value
145
        {
146
156861
            self.literals.insert(name.to_string(), value.clone());
147
468511
        }
148
712235
    }
149

            
150
    /// The scan's measures: actually stored names, whether the unit is
151
    /// possibly storing, and its opaque macro uses.
152
2341818
    pub(crate) fn measures(&self) -> (usize, bool, usize) {
153
2341818
        (self.stored.len(), self.possibly_storing, self.opaque_uses)
154
2341818
    }
155

            
156
    /// Settles the cells against `symbols` once the walk has read the text.
157
2341931
    fn settle(&mut self, symbols: &SymbolTable) {
158
346895
        let has_constant = |name: &String| symbols.constant_global(name).is_some();
159
2341931
        let defined: HashSet<&String> = self.defined.iter().collect();
160
2341931
        let mut stores: BTreeSet<String> = self.direct.clone();
161
2341931
        stores.extend(
162
2341931
            self.stored
163
2341931
                .iter()
164
406894
                .filter(|name| defined.contains(name) || has_constant(name))
165
                .cloned(),
166
        );
167
2341931
        if self.possibly_storing && self.opaque_uses > 0 {
168
835
            stores.extend(
169
835
                self.opaque_names
170
835
                    .iter()
171
1669
                    .filter(|name| defined.contains(name) || has_constant(name))
172
                    .cloned(),
173
            );
174
2341096
        }
175
2341931
        self.dynamic = self
176
2341931
            .rebound
177
2341931
            .iter()
178
1785747
            .filter(|name| defined.contains(name) || symbols.is_special(name))
179
            .cloned()
180
            .collect();
181
2341931
        let repeated = self
182
2341931
            .defined
183
2341931
            .iter()
184
349688
            .filter(|name| self.defined.iter().filter(|other| other == name).count() > 1);
185
2341931
        let mut cells = stores.clone();
186
2341931
        cells.extend(self.dynamic.iter().cloned());
187
2341931
        cells.extend(repeated.cloned());
188
2341931
        cells.extend(symbols.forced_cells());
189
2341931
        let lambdas: Vec<&String> = self
190
2341931
            .named
191
2341931
            .iter()
192
184349215
            .filter(|name| holds_lambda(symbols, name))
193
            .collect();
194
2341931
        cells.extend(
195
2341931
            lambdas
196
2341931
                .iter()
197
40370
                .filter(|name| defined.contains(*name))
198
2290
                .map(|name| (*name).clone()),
199
        );
200
2341931
        cells.retain(|name| is_writable(symbols, name));
201
2341931
        self.adopted = lambdas
202
2341931
            .into_iter()
203
40370
            .filter(|name| !cells.contains(*name))
204
            .cloned()
205
            .collect();
206
2341931
        stores.retain(|name| cells.contains(name));
207
2341931
        self.stores = stores;
208
2341931
        self.cells = cells;
209
2341931
    }
210
}
211

            
212
701371
fn is_lambda_form(form: &Expr) -> bool {
213
701371
    match form {
214
        Expr::Lambda(..) => true,
215
480128
        Expr::List(items) => matches!(
216
480128
            items.first(),
217
480128
            Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case("LAMBDA")
218
        ),
219
221243
        _ => false,
220
    }
221
701371
}
222

            
223
/// Whether an earlier unit left the global `name` a lambda a closure can be,
224
/// or the source of a list of closures.
225
184349215
fn holds_lambda(symbols: &SymbolTable, name: &str) -> bool {
226
184349215
    match symbols.constant_global(name) {
227
29549
        Some(Expr::Lambda(params, _)) => has_v1_param_shape(&params),
228
429359
        Some(constant) => is_list_source(&constant),
229
183890307
        None => false,
230
    }
231
184349215
}
232

            
233
/// Whether a global of this name can be a cell: a built-in or host function
234
/// name never is.
235
485043
fn is_writable(symbols: &SymbolTable, name: &str) -> bool {
236
485043
    reject_reserved(symbols, name).is_ok()
237
485043
}
238

            
239
/// Scans `unit` against `symbols`, on a scratch copy so the DEFMACROs the
240
/// unit itself defines expand at their later use sites.
241
2352359
pub(crate) fn scan_stores(
242
2352359
    symbols: &SymbolTable,
243
2352359
    unit: &[Expr],
244
2352359
    mode: CompileMode,
245
2352359
) -> Result<StoreScan> {
246
2352359
    let mut scan = walker::walk(symbols, unit, mode)?;
247
2341931
    scan.settle(symbols);
248
2341931
    Ok(scan)
249
2352359
}