Lines
98.91 %
Functions
77.78 %
Branches
100 %
//! `CASE` / `ECASE`: the key form is evaluated once into a fresh variable and
//! each clause becomes a `COND` clause testing `EQL` against its unevaluated
//! keys. `ECASE` ends with a clause raising a catchable `TYPE-ERROR`.
use super::super::SpecialFormSpec;
use crate::ast::{Expr, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{
as_literal_arg, compile_expr, compile_for_effect, compile_for_stack, eval_value, format_form,
};
use crate::error::{Error, Result};
use crate::runtime::SymbolTable;
#[derive(Clone, Copy)]
enum Case {
Case,
Ecase,
}
macro_rules! case_spec {
($name:literal, $case:expr) => {
SpecialFormSpec {
name: $name,
eval: |symbols, args| eval_value(symbols, &expansion($case, args)?),
compile: |ctx, emit, symbols, args| {
compile_expr(ctx, emit, symbols, &expansion($case, args)?)
},
stack: Some(|ctx, emit, symbols, args| to_stack($case, ctx, emit, symbols, args)),
effect: Some(|ctx, emit, symbols, args| {
compile_for_effect(ctx, emit, symbols, &expansion($case, args)?)
}),
pub(in crate::compiler::special) const FORMS: &[SpecialFormSpec] = &[
case_spec!("CASE", Case::Case),
case_spec!("ECASE", Case::Ecase),
];
const KEY: &str = "case key";
impl Case {
fn name(self) -> &'static str {
match self {
Self::Case => "CASE",
Self::Ecase => "ECASE",
fn call(head: &str, args: Vec<Expr>) -> Expr {
Expr::List(std::iter::once(Expr::symbol(head)).chain(args).collect())
fn matches_key(key: &Expr) -> Expr {
call("EQL", vec![Expr::symbol(KEY), as_literal_arg(key)])
fn is_default_marker(keys: &Expr) -> bool {
match keys {
Expr::T => true,
Expr::Symbol(name) => name.eq_ignore_ascii_case("OTHERWISE"),
_ => false,
fn clause_test(case: Case, keys: &Expr, last: bool) -> Result<Expr> {
if is_default_marker(keys) {
if !matches!(case, Case::Case) || !last {
return Err(Error::Compile(format!(
"{}: {} is only allowed as the last clause of CASE",
case.name(),
format_form(keys)
)));
return Ok(Expr::T);
Ok(match keys {
Expr::Nil => Expr::Nil,
Expr::List(items) => call("OR", items.iter().map(matches_key).collect()),
atom => matches_key(atom),
})
fn clause(case: Case, form: &Expr, last: bool) -> Result<Expr> {
let (keys, body) = form
.as_list()
.and_then(<[Expr]>::split_first)
.ok_or_else(|| {
Error::Compile(format!(
"{}: clause must be (keys form...), got {}",
format_form(form)
))
})?;
let test = clause_test(case, keys, last)?;
let body = if body.is_empty() {
vec![Expr::Nil]
} else {
body.to_vec()
Ok(Expr::List(std::iter::once(test).chain(body).collect()))
fn expansion(case: Case, args: &[Expr]) -> Result<Expr> {
let Some((keyform, clauses)) = args.split_first() else {
return Err(Error::Arity {
name: case.name().to_string(),
expected: 1,
actual: 0,
});
let mut arms = clauses
.iter()
.enumerate()
.map(|(at, form)| clause(case, form, at + 1 == clauses.len()))
.collect::<Result<Vec<_>>>()?;
if matches!(case, Case::Ecase) {
let no_match = call(
"ERROR",
vec![
Expr::quoted_code(Expr::symbol("TYPE-ERROR")),
Expr::String("ECASE: no clause matches the key".to_string()),
],
);
arms.push(Expr::List(vec![Expr::T, no_match]));
let binding = Expr::List(vec![Expr::List(vec![Expr::symbol(KEY), keyform.clone()])]);
Ok(call("LET", vec![binding, call("COND", arms)]))
fn to_stack(
case: Case,
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
args: &[Expr],
) -> Result<WasmType> {
compile_for_stack(ctx, emit, symbols, &expansion(case, args)?)
#[cfg(test)]
#[path = "case_tests.rs"]
mod tests;