Lines
96.59 %
Functions
98.94 %
Branches
100 %
//! The walk of the store scan over the unit's text (see [`super`]).
use std::collections::HashSet;
use crate::ast::{Expr, LambdaParams};
use crate::compiler::CompileMode;
use crate::compiler::special::setf_scan::{
Binder, Step, binder, binder_steps, code_forms, spec_forms,
};
use crate::compiler::special::{binding, labels_shadowed};
use crate::error::{Error, Result};
use crate::runtime::{Head, SymbolTable, is_list_source, with_sufficient_stack};
use super::super::template::expand_macro_use;
use super::StoreScan;
use crate::compiler::special::expand_macro_places;
/// The function every script unit compiles in, whether or not its text names
/// it; an eval unit never compiles one.
const SHOULD_APPLY: &str = "SHOULD-APPLY";
/// Walks `unit` and every function body it reaches.
pub(super) fn walk(symbols: &SymbolTable, unit: &[Expr], mode: CompileMode) -> Result<StoreScan> {
let mut walker = Walker {
scratch: symbols.scan_scratch(),
scan: StoreScan::default(),
shadowed: Vec::new(),
visited: HashSet::new(),
pending: Vec::new(),
visited_opaque: HashSet::new(),
opaque_depth: 0,
macro_depth: 0,
for form in unit {
walker.visit(form)?;
}
if mode == CompileMode::Script {
walker.name(SHOULD_APPLY);
walker.drain()?;
walker.scan.named = walker.visited.into_iter().collect();
Ok(walker.scan)
/// The scan's state: the scratch table the unit's DEFMACROs register in,
/// the findings, and the lexical names in scope — a store to one of those
/// is a store to a local, not to a global.
struct Walker {
scratch: SymbolTable,
scan: StoreScan,
shadowed: Vec<String>,
/// The earlier-unit functions already walked.
visited: HashSet<String>,
/// The earlier-unit functions queued to be walked.
pending: Vec<(String, bool)>,
/// The earlier-unit functions queued from inside an unreadable macro text.
visited_opaque: HashSet<String>,
/// How many unreadable macro texts the walk is inside.
opaque_depth: usize,
/// How many DEFMACRO bodies the walk is inside.
macro_depth: usize,
impl Walker {
fn visit(&mut self, expr: &Expr) -> Result<()> {
with_sufficient_stack(|| {
match expr {
Expr::Symbol(name) if name.eq_ignore_ascii_case("SETF") => {
self.scan.possibly_storing = true;
Expr::Symbol(name) => self.name(name),
Expr::List(elems) => self.list(elems)?,
Expr::Quote(inner) | Expr::Datum(inner) => self.datum(inner)?,
Expr::Quasiquote(_) => {
self.datum(expr)?;
for form in expr.unquoted_forms() {
self.visit(form)?;
Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => self.visit(inner)?,
Expr::Cons(car, cdr) => {
self.visit(car)?;
self.visit(cdr)?;
Expr::Lambda(params, body) => {
let mark = self.shadowed.len();
self.shadowed.extend(params.required.iter().cloned());
let visited = self.parsed_sections(params).and_then(|()| self.visit(body));
self.shadowed.truncate(mark);
visited?;
_ => {}
Ok(())
})
fn function_name(&mut self, args: &[Expr]) {
if let Some(Expr::Symbol(name)) = args.first() {
self.scan.functions.push(name.clone());
/// Quoted data: its symbols are names of the unit, but nothing in it is
/// code, so no macro use in it is expanded.
fn datum(&mut self, expr: &Expr) -> Result<()> {
Expr::Symbol(name) => {
if self.opaque_depth > 0 {
self.scan.opaque_names.insert(name.to_ascii_uppercase());
self.visit(expr)
Expr::List(items) => items.iter().try_for_each(|item| self.datum(item)),
self.datum(car)?;
self.datum(cdr)
Expr::Quote(inner) | Expr::Datum(inner) | Expr::Quasiquote(inner) => self.datum(inner),
_ => Ok(()),
/// A symbol of the text: a global an earlier unit left a value for, and
/// an earlier-unit function whose body the unit now runs, queued so its
/// stores and bindings are the unit's own.
fn name(&mut self, name: &str) {
let name = name.to_ascii_uppercase();
let opaque = self.opaque_depth > 0;
if self.visited.insert(name.clone()) || (opaque && self.visited_opaque.insert(name.clone()))
{
self.pending.push((name, opaque));
/// Walks the queued function bodies, each of which may queue more: a
/// worklist, so a long chain of functions costs no native stack.
fn drain(&mut self) -> Result<()> {
while let Some((name, opaque)) = self.pending.pop() {
let Some(body) = self.code_of(&name) else {
continue;
self.shadowed.clear();
self.opaque_depth += usize::from(opaque);
let walked = self.visit(&body);
self.opaque_depth -= usize::from(opaque);
walked?;
/// The code the unit runs when it names `name`: an earlier unit's function
/// body, or the lambda or list-of-closures source it left in the global,
/// whose own names the unit then names too.
fn code_of(&self, name: &str) -> Option<Expr> {
let function = self.scratch.lookup(name).and_then(|s| s.function());
match function {
Some(body @ Expr::Lambda(..)) => Some(body.clone()),
_ => self
.scratch
.constant_global(name)
.filter(|value| matches!(value, Expr::Lambda(..)) || is_list_source(value)),
/// A `SETF` pair: a store to a global, a literal one typing its cell.
fn store(&mut self, pair: &[Expr]) {
place(&mut self.scan, &self.shadowed, pair);
if let Some(Expr::Symbol(name)) = pair.first()
&& !self.shadowed.contains(name)
self.scan.note_writer(name, pair.get(1));
/// The `SETF` arguments with each macro place expanded; a place that
/// cannot expand at scan time may store anywhere.
fn macro_places(&mut self, args: &[Expr]) -> Result<Vec<Expr>> {
match expand_macro_places(&self.scratch, args) {
Ok(expanded) => Ok(expanded),
Err(err @ Error::Resource(_)) => Err(err),
Err(_) => {
Ok(args.to_vec())
fn all<'a>(&mut self, exprs: impl IntoIterator<Item = &'a Expr>) -> Result<()> {
exprs.into_iter().try_for_each(|expr| self.visit(expr))
/// Visits `forms` with `names` in scope.
fn scoped(&mut self, names: Vec<String>, forms: &[Expr]) -> Result<()> {
self.shadowed.extend(names);
let visited = self.all(forms);
visited
fn list(&mut self, elems: &[Expr]) -> Result<()> {
let Some(Expr::Symbol(head)) = elems.first() else {
return self.all(elems);
let args = &elems[1..];
match head.to_ascii_uppercase().as_str() {
"SETF" => {
let args = self.macro_places(args)?;
for pair in args.chunks(2) {
self.store(pair);
self.all(&args)
"DEFVAR" | "DEFPARAMETER" => {
if let Some(Expr::Symbol(name)) = args.first()
&& self.opaque_depth + self.macro_depth == 0
self.scan.defined.push(name.clone());
self.scan.note_writer(name, args.get(1));
self.all(args)
"DEFMACRO" => {
self.function_name(args);
// Registered on the scratch so a template use below expands;
// a malformed definition is the compiler's to reject when it
// compiles the form.
if let Err(Error::Resource(what)) =
crate::compiler::special::call(&mut self.scratch, "DEFMACRO", args)
return Err(Error::Resource(what));
self.macro_depth += 1;
let walked = self.definition(args);
self.macro_depth -= 1;
walked
"DEFUN" => {
self.definition(args)
"DEFSTRUCT" => {
if let Some(name) = args.first().and_then(Expr::as_symbol) {
let names = crate::compiler::special::struct_function_names(name, &args[1..]);
self.scan.functions.extend(names);
self.scan.functions.push(name.to_string());
"LAMBDA" => self.definition_body(args),
"LET" | "LET*" | "DO" | "DO*" => match binder(elems) {
Some((kind, specs)) => self.binder(kind, specs, elems),
None => self.all(args),
},
"HANDLER-CASE" => {
let vars = args.iter().skip(1).filter_map(clause_var);
vars.for_each(|var| self.note_bound(var));
self.all(code_forms(elems))
"LABELS" => {
let defs = args.first().and_then(Expr::as_list).unwrap_or_default();
for def in defs {
let params =
(spec_forms(def).first().and_then(Expr::as_list)).unwrap_or_default();
params
.iter()
.filter_map(spec_name)
.for_each(|var| self.note_bound(var));
let local = labels_shadowed(&self.scratch, elems);
let outer = std::mem::replace(&mut self.scratch, local);
let walked = self.all(code_forms(elems));
self.scratch = outer;
"CATCH-EACH" => {
if let Some(Expr::Symbol(var)) = args.get(1) {
self.note_bound(var.clone());
"DOLIST" => match args.split_first() {
Some((Expr::List(spec), body)) => {
self.all(spec.get(1..).unwrap_or_default())?;
let var: Vec<String> = spec.first().and_then(spec_name).into_iter().collect();
var.iter().cloned().for_each(|name| self.note_bound(name));
self.scoped(var, body)
_ => self.all(args),
_ => {
if matches!(self.scratch.resolve_head(head), Head::Macro(..)) {
self.macro_use(head, args)
} else {
self.name(head);
/// `(defun name (params) body…)` / `(defmacro name (params) body…)`.
fn definition(&mut self, args: &[Expr]) -> Result<()> {
self.definition_body(args.get(1..).unwrap_or_default())
/// `(params body…)`: each default form sees the parameters before it,
/// the body sees them all.
fn definition_body(&mut self, args: &[Expr]) -> Result<()> {
let Some((params, body)) = args.split_first() else {
return Ok(());
let visited = self.list_params(params).and_then(|()| self.all(body));
fn list_params(&mut self, params: &Expr) -> Result<()> {
let Expr::List(items) = params else {
for item in items {
self.all(spec_forms(item))?;
if let Some(name) = spec_name(item).filter(|name| !name.starts_with('&')) {
self.note_bound(name.clone());
self.shadowed.push(name);
fn parsed_sections(&mut self, params: &LambdaParams) -> Result<()> {
for (name, default) in params.defaulted() {
default.iter().try_for_each(|form| self.visit(form))?;
self.note_bound(name.to_string());
self.shadowed.push(name.to_string());
for name in params.required.iter().chain(¶ms.rest) {
self.shadowed.extend(params.rest.iter().cloned());
/// A LET / LET* / DO / DO* form, walked as `binder_steps` orders it.
fn binder(&mut self, kind: Binder, specs: &[Expr], elems: &[Expr]) -> Result<()> {
self.note_rebound(specs);
let visited =
binder_steps(kind, specs, elems)
.into_iter()
.try_for_each(|step| match step {
Step::Visit(expr) => self.visit(expr),
Step::Shadow(name) => {
});
fn note_bound(&mut self, name: String) {
self.scan.rebound.insert(name);
fn note_rebound(&mut self, specs: &[Expr]) {
specs
.for_each(|name| self.note_bound(name));
/// The text of a macro whose use cannot expand at scan time, read as the
/// unit's own: the names it mentions, quoted ones included, and the stores.
fn opaque_body(&mut self, head: &str) -> Result<()> {
let Head::Macro(_, body) = self.scratch.resolve_head(head) else {
let body = body.clone();
self.opaque_depth += 1;
self.opaque_depth -= 1;
/// Every symbol of the arguments of an unreadable macro use.
fn opaque_args(&mut self, args: &[Expr]) {
for arg in args {
let mut found = Vec::new();
symbols_of(arg, &mut found);
self.scan.opaque_names.extend(found);
/// A macro's expansion is scanned in place of the use, which already
/// contains every argument it keeps (scanning the arguments too would walk
/// a nested macro argument twice per level). A use that cannot expand at
/// scan time is opaque: its macro's text and its arguments are scanned as
/// text of the unit.
fn macro_use(&mut self, head: &str, args: &[Expr]) -> Result<()> {
self.scratch.enter_macro_expansion()?;
let walked = match expand_macro_use(&mut self.scratch, head, args) {
Ok(Some(expansion)) => self.visit(&expansion),
Ok(None) => {
self.scan.opaque_uses += 1;
self.opaque_body(head)?;
self.opaque_args(args);
Err(err) => Err(err),
self.scratch.exit_macro_expansion()?;
fn symbols_of(expr: &Expr, found: &mut Vec<String>) {
with_sufficient_stack(|| match expr {
Expr::Symbol(name) => found.push(name.to_ascii_uppercase()),
Expr::List(items) => items.iter().for_each(|item| symbols_of(item, found)),
symbols_of(car, found);
symbols_of(cdr, found);
Expr::Quote(inner)
| Expr::Datum(inner)
| Expr::Quasiquote(inner)
| Expr::Unquote(inner)
| Expr::UnquoteSplicing(inner) => symbols_of(inner, found),
/// The condition variable of a HANDLER-CASE clause `(code (var) form…)`.
fn clause_var(clause: &Expr) -> Option<String> {
match clause {
Expr::List(parts) => match parts.get(1) {
Some(Expr::List(var)) => var.first().and_then(spec_name),
_ => None,
fn spec_name(spec: &Expr) -> Option<String> {
binding::spec_name(spec).map(str::to_string)
/// A `SETF` pair: a bare-symbol place is a store to that name; a struct
/// accessor place `(accessor sym …)` rebinds `sym` (see `set_place`); any
/// other place is one the scan cannot resolve.
fn place(scan: &mut StoreScan, shadowed: &[String], pair: &[Expr]) {
let (name, direct) = match pair.first() {
Some(Expr::Symbol(name)) => (Some(name), true),
Some(Expr::List(parts)) => match parts.get(1) {
Some(Expr::Symbol(target)) => (Some(target), false),
_ => (None, false),
match name {
Some(name) if shadowed.iter().any(|local| local == name) => {}
Some(name) => {
scan.stored.insert(name.clone());
if direct {
scan.direct.insert(name.clone());
None => scan.possibly_storing = true,