Lines
97.44 %
Functions
72.58 %
Branches
100 %
//! The one scoped syntactic walk over a form (0014 Stage 2, ISS-053). It
//! carries the binder stack as it descends, expands template macros with
//! the evaluator's own `expand_macro`, skips quoted data, and hands every
//! node in code position to a [`Visit`]or that answers one question.
//!
//! Every walk errs the same way: a node the visitor cannot classify is
//! [`Step::Found`], the answer that ends the walk with `true`.
use std::borrow::Cow;
use crate::ast::Expr;
use crate::compiler::expr::expand_macro;
use crate::compiler::special::binding::spec_name;
use crate::compiler::special::labels_shadowed;
use crate::compiler::special::setf_scan::{code_forms, spec_forms};
use crate::error::Result;
use crate::runtime::{Head, SymbolTable};
use super::template::template_of;
/// What the visitor wants done with a node.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Step {
/// Walk the node's subforms.
Descend,
/// Leave the node's subforms unvisited.
Skip,
/// The question is answered: the walk ends with `true`.
Found,
}
/// A node in code position, classified against the live table.
pub(crate) enum Node<'a> {
/// A symbol read that no binder inside the form bounds.
Free(&'a str),
/// A special form call; `elems` is the whole form.
Special(&'a str, &'a [Expr]),
/// A native or operator call no user definition shadows.
Native(&'a str),
/// A call of a user function, a closure value, or an unknown name.
Call,
/// A macro use whose expansion is not a template, so it is not scanned.
OpaqueMacro,
/// A `LAMBDA` / `FUNCTION` form in a body's non-tail position.
DiscardedLambda,
/// A self-evaluating literal or quoted datum.
Datum,
/// Anything else: a quasiquote in code position, a cons, a placeholder.
Other,
/// The binders in scope at a node.
#[derive(Default)]
pub(crate) struct Scope {
vars: Vec<String>,
blocks: Vec<String>,
impl Scope {
pub(crate) fn binds_var(&self, name: &str) -> bool {
self.vars.iter().any(|v| v.eq_ignore_ascii_case(name))
pub(crate) trait Visit {
fn visit(&mut self, env: &SymbolTable, scope: &Scope, node: Node<'_>) -> Step;
/// Whether an `IF` with a literal test walks only its live branch.
fn prunes_dead_branches(&self) -> bool {
false
/// Walks `forms` as a body (all but the last for effect) in a fresh scope
/// whose variables are `bound`; `true` once the visitor answers [`Step::Found`].
pub(crate) fn walk_body<V: Visit>(
symbols: &SymbolTable,
bound: &[&str],
forms: &[Expr],
visitor: &mut V,
) -> Result<bool> {
let mut env = Cow::Borrowed(symbols);
let mut scope = Scope {
vars: bound.iter().map(|name| (*name).to_string()).collect(),
blocks: Vec::new(),
};
body(&mut env, &mut scope, forms, visitor)
type Env<'a> = Cow<'a, SymbolTable>;
fn body<V: Visit>(
env: &mut Env<'_>,
scope: &mut Scope,
let Some((tail, init)) = forms.split_last() else {
return Ok(false);
for form in init {
if is_lambda_literal(env, form) {
if visitor.visit(env, scope, Node::DiscardedLambda) == Step::Found {
return Ok(true);
continue;
if walk(env, scope, form, visitor)? {
walk(env, scope, tail, visitor)
fn all<'a, V: Visit>(
forms: impl IntoIterator<Item = &'a Expr>,
for form in forms {
Ok(false)
fn walk<V: Visit>(
form: &Expr,
let step = match form {
Expr::Nil
| Expr::T
| Expr::Number(_)
| Expr::String(_)
| Expr::Bytes(_)
| Expr::Keyword(_)
| Expr::Quote(_)
| Expr::Datum(_) => visitor.visit(env, scope, Node::Datum),
Expr::Symbol(name) if scope.binds_var(name) => Step::Skip,
Expr::Symbol(name) => visitor.visit(env, scope, Node::Free(name)),
Expr::List(elems) if elems.is_empty() => visitor.visit(env, scope, Node::Datum),
Expr::List(elems) => return call(env, scope, elems, visitor),
Expr::Quasiquote(template) => {
return match visitor.visit(env, scope, Node::Other) {
Step::Descend => walk_unquoted(env, scope, template, visitor),
Step::Skip => Ok(false),
Step::Found => Ok(true),
Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => {
Step::Descend => walk(env, scope, inner, visitor),
_ => visitor.visit(env, scope, Node::Other),
Ok(step == Step::Found)
fn walk_unquoted<V: Visit>(
template: &Expr,
for form in template.unquoted_forms() {
fn call<V: Visit>(
elems: &[Expr],
let Some(Expr::Symbol(head)) = elems.first() else {
return match visitor.visit(env, scope, Node::Call) {
Step::Descend => all(env, scope, elems, visitor),
let resolved = env.resolve_head(head);
let is_special = matches!(resolved, Head::SpecialForm);
let node = match resolved {
Head::Macro(..) => return macro_use(env, scope, head, elems, visitor),
Head::SpecialForm => Node::Special(head, elems),
Head::Native => Node::Native(head),
_ => Node::Call,
match visitor.visit(env, scope, node) {
Step::Descend if is_special => special(env, scope, head, elems, visitor),
// The type name of `(the TYPE form)` is not evaluated.
Step::Descend if head.eq_ignore_ascii_case("THE") => {
all(env, scope, elems.get(2..).unwrap_or_default(), visitor)
Step::Descend => all(env, scope, &elems[1..], visitor),
/// A template macro's expansion is walked in place of the use; any other
/// macro use is opaque to the walk.
fn macro_use<V: Visit>(
head: &str,
let args = &elems[1..];
let Some((params, body)) = template_of(env, head) else {
return Ok(visitor.visit(env, scope, Node::OpaqueMacro) == Step::Found);
let (params, body) = (params.clone(), body.clone());
let table = env.to_mut();
table.enter_macro_expansion()?;
let expansion = expand_macro(table, ¶ms, &body, args).and_then(|expansion| {
table.charge_work(crate::compiler::datum::cost(&expansion)?)?;
Ok(expansion)
});
let found = expansion.and_then(|code| walk(env, scope, &code, visitor));
env.to_mut().exit_macro_expansion()?;
found
/// The subforms of a special form, with its binders pushed around the forms
/// they scope.
fn special<V: Visit>(
let rest = &elems[1..];
match head.to_ascii_uppercase().as_str() {
"QUOTE" => Ok(false),
"IF" if visitor.prunes_dead_branches() => match rest.split_first() {
Some((test, branches)) if is_literal(test) => {
let live = usize::from(test.is_nil());
all(
env,
scope,
branches.get(live..=live).unwrap_or_default(),
visitor,
)
_ => all(env, scope, rest, visitor),
},
"PROGN" => body(env, scope, rest, visitor),
"LET" | "LET*" => let_form(env, scope, head.eq_ignore_ascii_case("LET*"), rest, visitor),
"DOLIST" => dolist(env, scope, rest, visitor),
"DO" | "DO*" => do_form(env, scope, head.eq_ignore_ascii_case("DO*"), rest, visitor),
"LAMBDA" => lambda(env, scope, rest, visitor),
"LABELS" => all(
&mut Cow::Owned(labels_shadowed(env, elems)),
code_forms(elems),
),
"BLOCK" => match rest.split_first() {
Some((Expr::Symbol(name), forms)) => {
scope.blocks.push(name.clone());
let found = body(env, scope, forms, visitor);
scope.blocks.pop();
_ => all(env, scope, code_forms(elems), visitor),
fn let_form<V: Visit>(
sequential: bool,
rest: &[Expr],
let Some((specs, forms)) = rest
.split_first()
.and_then(|(specs, forms)| Some((specs.as_list()?, forms)))
else {
return all(env, scope, rest, visitor);
let mark = scope.vars.len();
let mut found = false;
for spec in specs {
found = all(env, scope, spec_forms(spec), visitor)?;
if found {
break;
if sequential && let Some(name) = spec_name(spec) {
scope.vars.push(name.to_string());
if !found {
if !sequential {
scope
.vars
.extend(specs.iter().filter_map(spec_name).map(str::to_string));
found = body(env, scope, forms, visitor)?;
scope.vars.truncate(mark);
Ok(found)
fn dolist<V: Visit>(
let Some((Expr::List(spec), forms)) = rest.split_first() else {
let (Some(Expr::Symbol(var)), Some(list)) = (spec.first(), spec.get(1)) else {
if walk(env, scope, list, visitor)? {
scope.vars.push(var.clone());
scope.vars.pop();
if found? {
all(env, scope, spec.get(2..).unwrap_or_default(), visitor)
fn do_form<V: Visit>(
let Some((specs, tail)) = rest
.and_then(|(specs, tail)| Some((specs.as_list()?, tail)))
found = all(
spec_forms(spec).get(..1).unwrap_or_default(),
)?;
let steps: Vec<&Expr> = specs
.iter()
.filter_map(|spec| spec_forms(spec).get(1))
.collect();
found = steps.iter().try_fold(false, |found, step| {
Ok(found || walk(env, scope, step, visitor)?)
})?;
found = found
|| match tail.split_first() {
Some((Expr::List(end), forms)) => {
all(env, scope, end, visitor)? || body(env, scope, forms, visitor)?
_ => all(env, scope, tail, visitor)?,
fn lambda<V: Visit>(
let Some((Expr::List(params), forms)) = rest.split_first() else {
.extend(params.iter().filter_map(spec_name).map(str::to_string));
pub(crate) fn is_literal(form: &Expr) -> bool {
matches!(
form,
Expr::Nil | Expr::T | Expr::Number(_) | Expr::String(_) | Expr::Keyword(_)
/// A `(lambda …)` or `(function (lambda …))` list: the lambda a head spells
/// out, as opposed to one a call or a name produces.
pub(crate) fn is_lambda_head(symbols: &SymbolTable, form: &Expr) -> bool {
let Expr::List(elems) = form else {
return false;
match elems.as_slice() {
[head, inner] if is_special_head(symbols, head, "FUNCTION") => {
matches!(inner, Expr::List(_)) && is_lambda_head(symbols, inner)
[head, ..] => is_special_head(symbols, head, "LAMBDA"),
[] => false,
fn is_special_head(symbols: &SymbolTable, head: &Expr, name: &str) -> bool {
matches!(head, Expr::Symbol(head) if head.eq_ignore_ascii_case(name)
&& matches!(symbols.resolve_head(head), Head::SpecialForm))
/// A `lambda` / `function` form or a lambda value, whose body does not run
/// where it is created.
pub(crate) fn is_lambda_literal(symbols: &SymbolTable, form: &Expr) -> bool {
matches!(form, Expr::Lambda(..))
|| matches!(
Expr::List(elems) if matches!(
elems.first(),
Some(Expr::Symbol(head)) if (head.eq_ignore_ascii_case("LAMBDA")
|| head.eq_ignore_ascii_case("FUNCTION"))
&& matches!(symbols.resolve_head(head), Head::SpecialForm)