Lines
99.17 %
Functions
100 %
Branches
//! The conservative store scan (0014 Stage 2, §Stores to globals): which
//! globals the unit about to compile writes. A global is a constant datum
//! only when the unit has no writer for it or exactly one DEFVAR /
//! DEFPARAMETER form whose init folds; any other writer makes it a runtime
//! cell for the whole unit, allocated before the first form compiles. An init
//! folds unless the attempt that compiled it found otherwise.
//!
//! The scan reads the whole unit's text before any form of it is compiled:
//! every `SETF` head, inside quoted and quasiquoted data, DEFUN/DEFMACRO/
//! LAMBDA bodies, every binder and arm. A template macro is expanded at its
//! use site and the expansion scanned. A macro whose expansion the scan does
//! not run can only store if the symbol `SETF` reaches it from the unit's
//! text, so any `SETF` the scan cannot tie to a place marks the unit
//! *possibly storing*, and an opaque macro use in such a unit stores to
//! every global the unit defines.
mod walker;
use std::collections::{BTreeMap, BTreeSet, HashSet};
use crate::ast::Expr;
use crate::compiler::CompileMode;
use crate::compiler::special::has_v1_param_shape;
use crate::error::Result;
use crate::reserved::reject_reserved;
use crate::runtime::{SymbolTable, is_list_source};
#[derive(Default, Debug)]
pub(crate) struct StoreScan {
/// Each name a directly scanned `SETF` stores to, through a bare symbol
/// place or a struct accessor.
stored: BTreeSet<String>,
/// The names stored through a bare symbol place.
direct: BTreeSet<String>,
/// The symbol `SETF` occurs where the scan cannot tie it to a place.
possibly_storing: bool,
/// Uses of macros whose expansion the scan does not run.
opaque_uses: usize,
/// The DEFVAR / DEFPARAMETER names of the unit, in order, repeats kept.
defined: Vec<String>,
/// Each name a DEFUN or DEFMACRO of the unit defines.
functions: Vec<String>,
/// Each name a binder introduces.
rebound: BTreeSet<String>,
/// The first writer of each name, when it is a scalar literal: it types
/// the name's cell before any form compiles.
literals: BTreeMap<String, Expr>,
/// The names some writer has been noted for.
written: BTreeSet<String>,
/// The names some writer stores a lambda form to, and the names some
/// writer stores anything else to.
lambda_writers: BTreeSet<String>,
other_writers: BTreeSet<String>,
/// The names an unreadable macro use can store to: the symbols quoted in
/// its macro's text and every symbol of its arguments.
opaque_names: BTreeSet<String>,
/// The globals the unit makes cells of.
cells: BTreeSet<String>,
/// Every name of the unit's text, and of the earlier-unit functions it runs.
named: BTreeSet<String>,
/// The names an earlier unit left a lambda for, which the unit names and
/// does not make cells of: each gets a closure home.
adopted: BTreeSet<String>,
/// The cells some store reaches, found or assumed.
stores: BTreeSet<String>,
/// The cells that are specials some LET / LET* binds.
dynamic: BTreeSet<String>,
}
impl StoreScan {
/// The globals the unit makes runtime cells: every writer but exactly one
/// DEFVAR / DEFPARAMETER form whose init folds makes one. An opaque macro use in a possibly
/// storing unit stores to every global the unit defines or names.
pub(crate) fn cells(&self) -> &BTreeSet<String> {
&self.cells
/// The cells some store reaches: no fold may read them, and a macro body
/// cannot see their init.
pub(crate) fn stores(&self) -> HashSet<String> {
self.stores.iter().cloned().collect()
/// The unit's DEFVAR / DEFPARAMETER names.
pub(crate) fn defined(&self) -> HashSet<String> {
self.defined.iter().cloned().collect()
/// The specials some LET / LET* binds, among those the unit defines and
/// those an earlier unit left a value for: each is a dynamic special, a
/// mutable global every binder saves and restores.
pub(crate) fn dynamic(&self) -> HashSet<String> {
self.dynamic.iter().cloned().collect()
/// The names whose lambda from an earlier unit the unit runs as a closure.
pub(crate) fn adopted(&self) -> &BTreeSet<String> {
&self.adopted
/// Whether every writer of `name` in the unit is a lambda form, so a cell
/// that starts as a closure only ever holds one.
pub(crate) fn writes_only_lambdas(&self, name: &str) -> bool {
self.lambda_writers.contains(name)
&& !self.other_writers.contains(name)
&& !self.rebound.contains(name)
&& !self.opaque_names.contains(name)
&& (!self.stored.contains(name) || self.direct.contains(name))
/// Whether the unit has a DEFVAR / DEFPARAMETER of `name`.
pub(crate) fn defines(&self, name: &str) -> bool {
self.defined.iter().any(|defined| defined == name)
/// The scalar literal the unit first writes `name` to.
pub(crate) fn first_literal(&self, name: &str) -> Option<&Expr> {
self.literals.get(name)
/// Every name the unit writes: defined, stored, rebound or given a
/// function.
pub(crate) fn written_names(&self) -> Vec<String> {
let mut names: BTreeSet<String> = self.stored.clone();
names.extend(self.defined.iter().cloned());
names.extend(self.rebound.iter().cloned());
names.extend(self.functions.iter().cloned());
names.extend(self.adopted.iter().cloned());
names.into_iter().collect()
/// Notes `value` as written to `name`; the first writer of a name types
/// its cell when it is a scalar literal.
fn note_writer(&mut self, name: &str, value: Option<&Expr>) {
match value.is_some_and(is_lambda_form) {
true => self.lambda_writers.insert(name.to_string()),
false => self.other_writers.insert(name.to_string()),
};
if value.is_none() || !self.written.insert(name.to_string()) {
return;
if let Some(
value @ (Expr::Number(_) | Expr::String(_) | Expr::Keyword(_) | Expr::T | Expr::Nil),
) = value
{
self.literals.insert(name.to_string(), value.clone());
/// The scan's measures: actually stored names, whether the unit is
/// possibly storing, and its opaque macro uses.
pub(crate) fn measures(&self) -> (usize, bool, usize) {
(self.stored.len(), self.possibly_storing, self.opaque_uses)
/// Settles the cells against `symbols` once the walk has read the text.
fn settle(&mut self, symbols: &SymbolTable) {
let has_constant = |name: &String| symbols.constant_global(name).is_some();
let defined: HashSet<&String> = self.defined.iter().collect();
let mut stores: BTreeSet<String> = self.direct.clone();
stores.extend(
self.stored
.iter()
.filter(|name| defined.contains(name) || has_constant(name))
.cloned(),
);
if self.possibly_storing && self.opaque_uses > 0 {
self.opaque_names
self.dynamic = self
.rebound
.filter(|name| defined.contains(name) || symbols.is_special(name))
.cloned()
.collect();
let repeated = self
.defined
.filter(|name| self.defined.iter().filter(|other| other == name).count() > 1);
let mut cells = stores.clone();
cells.extend(self.dynamic.iter().cloned());
cells.extend(repeated.cloned());
cells.extend(symbols.forced_cells());
let lambdas: Vec<&String> = self
.named
.filter(|name| holds_lambda(symbols, name))
cells.extend(
lambdas
.filter(|name| defined.contains(*name))
.map(|name| (*name).clone()),
cells.retain(|name| is_writable(symbols, name));
self.adopted = lambdas
.into_iter()
.filter(|name| !cells.contains(*name))
stores.retain(|name| cells.contains(name));
self.stores = stores;
self.cells = cells;
fn is_lambda_form(form: &Expr) -> bool {
match form {
Expr::Lambda(..) => true,
Expr::List(items) => matches!(
items.first(),
Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case("LAMBDA")
),
_ => false,
/// Whether an earlier unit left the global `name` a lambda a closure can be,
/// or the source of a list of closures.
fn holds_lambda(symbols: &SymbolTable, name: &str) -> bool {
match symbols.constant_global(name) {
Some(Expr::Lambda(params, _)) => has_v1_param_shape(¶ms),
Some(constant) => is_list_source(&constant),
None => false,
/// Whether a global of this name can be a cell: a built-in or host function
/// name never is.
fn is_writable(symbols: &SymbolTable, name: &str) -> bool {
reject_reserved(symbols, name).is_ok()
/// Scans `unit` against `symbols`, on a scratch copy so the DEFMACROs the
/// unit itself defines expand at their later use sites.
pub(crate) fn scan_stores(
symbols: &SymbolTable,
unit: &[Expr],
mode: CompileMode,
) -> Result<StoreScan> {
let mut scan = walker::walk(symbols, unit, mode)?;
scan.settle(symbols);
Ok(scan)