1
//! `CASE` / `ECASE`: the key form is evaluated once into a fresh variable and
2
//! each clause becomes a `COND` clause testing `EQL` against its unevaluated
3
//! keys. `ECASE` ends with a clause raising a catchable `TYPE-ERROR`.
4

            
5
use super::super::SpecialFormSpec;
6
use crate::ast::{Expr, WasmType};
7
use crate::compiler::context::CompileContext;
8
use crate::compiler::emit::FunctionEmitter;
9
use crate::compiler::expr::{
10
    as_literal_arg, compile_expr, compile_for_effect, compile_for_stack, eval_value, format_form,
11
};
12
use crate::error::{Error, Result};
13
use crate::runtime::SymbolTable;
14

            
15
#[derive(Clone, Copy)]
16
enum Case {
17
    Case,
18
    Ecase,
19
}
20

            
21
macro_rules! case_spec {
22
    ($name:literal, $case:expr) => {
23
        SpecialFormSpec {
24
            name: $name,
25
1998
            eval: |symbols, args| eval_value(symbols, &expansion($case, args)?),
26
34
            compile: |ctx, emit, symbols, args| {
27
34
                compile_expr(ctx, emit, symbols, &expansion($case, args)?)
28
34
            },
29
925
            stack: Some(|ctx, emit, symbols, args| to_stack($case, ctx, emit, symbols, args)),
30
14
            effect: Some(|ctx, emit, symbols, args| {
31
14
                compile_for_effect(ctx, emit, symbols, &expansion($case, args)?)
32
14
            }),
33
        }
34
    };
35
}
36

            
37
pub(in crate::compiler::special) const FORMS: &[SpecialFormSpec] = &[
38
    case_spec!("CASE", Case::Case),
39
    case_spec!("ECASE", Case::Ecase),
40
];
41

            
42
const KEY: &str = "case key";
43

            
44
impl Case {
45
17
    fn name(self) -> &'static str {
46
17
        match self {
47
11
            Self::Case => "CASE",
48
6
            Self::Ecase => "ECASE",
49
        }
50
17
    }
51
}
52

            
53
9993
fn call(head: &str, args: Vec<Expr>) -> Expr {
54
9993
    Expr::List(std::iter::once(Expr::symbol(head)).chain(args).collect())
55
9993
}
56

            
57
3892
fn matches_key(key: &Expr) -> Expr {
58
3892
    call("EQL", vec![Expr::symbol(KEY), as_literal_arg(key)])
59
3892
}
60

            
61
6040
fn is_default_marker(keys: &Expr) -> bool {
62
6040
    match keys {
63
2220
        Expr::T => true,
64
3044
        Expr::Symbol(name) => name.eq_ignore_ascii_case("OTHERWISE"),
65
776
        _ => false,
66
    }
67
6040
}
68

            
69
6040
fn clause_test(case: Case, keys: &Expr, last: bool) -> Result<Expr> {
70
6040
    if is_default_marker(keys) {
71
2279
        if !matches!(case, Case::Case) || !last {
72
9
            return Err(Error::Compile(format!(
73
9
                "{}: {} is only allowed as the last clause of CASE",
74
9
                case.name(),
75
9
                format_form(keys)
76
9
            )));
77
2270
        }
78
2270
        return Ok(Expr::T);
79
3761
    }
80
3761
    Ok(match keys {
81
        Expr::Nil => Expr::Nil,
82
134
        Expr::List(items) => call("OR", items.iter().map(matches_key).collect()),
83
3627
        atom => matches_key(atom),
84
    })
85
6040
}
86

            
87
6044
fn clause(case: Case, form: &Expr, last: bool) -> Result<Expr> {
88
6044
    let (keys, body) = form
89
6044
        .as_list()
90
6044
        .and_then(<[Expr]>::split_first)
91
4
        .ok_or_else(|| {
92
4
            Error::Compile(format!(
93
4
                "{}: clause must be (keys form...), got {}",
94
4
                case.name(),
95
4
                format_form(form)
96
4
            ))
97
4
        })?;
98
6040
    let test = clause_test(case, keys, last)?;
99
6031
    let body = if body.is_empty() {
100
4
        vec![Expr::Nil]
101
    } else {
102
6027
        body.to_vec()
103
    };
104
6031
    Ok(Expr::List(std::iter::once(test).chain(body).collect()))
105
6044
}
106

            
107
2971
fn expansion(case: Case, args: &[Expr]) -> Result<Expr> {
108
2971
    let Some((keyform, clauses)) = args.split_first() else {
109
4
        return Err(Error::Arity {
110
4
            name: case.name().to_string(),
111
4
            expected: 1,
112
4
            actual: 0,
113
4
        });
114
    };
115
2967
    let mut arms = clauses
116
2967
        .iter()
117
2967
        .enumerate()
118
6044
        .map(|(at, form)| clause(case, form, at + 1 == clauses.len()))
119
13
        .collect::<Result<Vec<_>>>()?;
120
2954
    if matches!(case, Case::Ecase) {
121
59
        let no_match = call(
122
59
            "ERROR",
123
59
            vec![
124
59
                Expr::quoted_code(Expr::symbol("TYPE-ERROR")),
125
59
                Expr::String("ECASE: no clause matches the key".to_string()),
126
59
            ],
127
59
        );
128
59
        arms.push(Expr::List(vec![Expr::T, no_match]));
129
2895
    }
130
2954
    let binding = Expr::List(vec![Expr::List(vec![Expr::symbol(KEY), keyform.clone()])]);
131
2954
    Ok(call("LET", vec![binding, call("COND", arms)]))
132
2971
}
133

            
134
925
fn to_stack(
135
925
    case: Case,
136
925
    ctx: &mut CompileContext,
137
925
    emit: &mut FunctionEmitter,
138
925
    symbols: &mut SymbolTable,
139
925
    args: &[Expr],
140
925
) -> Result<WasmType> {
141
925
    compile_for_stack(ctx, emit, symbols, &expansion(case, args)?)
142
925
}
143

            
144
#[cfg(test)]
145
#[path = "case_tests.rs"]
146
mod tests;