1
//! `GETF`, `ASSOC` and `MEMBER`, all keyed by `EQL`. A constant list folds
2
//! through the eval-path `EQL`; anything runtime lowers to a `DO` walk over
3
//! the cells built from `CAR` / `CDR` / `EQL`, so the result types are theirs.
4

            
5
use super::datum::compile_folded_to_stack;
6
use super::map::extract_list_elements;
7
use crate::ast::{Expr, WasmType};
8
use crate::compiler::context::CompileContext;
9
use crate::compiler::emit::FunctionEmitter;
10
use crate::compiler::expr::fold::is_constant_datum;
11
use crate::compiler::expr::{
12
    as_literal_arg, compile_for_stack, eval_value, fold_call, format_expr, member_value,
13
    probe_value, serialize_stack_to_output,
14
};
15
use crate::compiler::native::NativeSpec;
16
use crate::compiler::native::arithmetic::refuse_dim_mix;
17
use crate::error::{Error, Result};
18
use crate::runtime::SymbolTable;
19

            
20
#[derive(Clone, Copy)]
21
enum Search {
22
    Getf,
23
    Assoc,
24
    Member,
25
}
26

            
27
macro_rules! search_spec {
28
    ($name:literal, $search:expr) => {
29
        NativeSpec {
30
            name: $name,
31
3502
            eval: |symbols, args| eval($search, symbols, args),
32
3360
            stack: Some(|ctx, emit, symbols, args| to_stack($search, ctx, emit, symbols, args)),
33
98
            effect: Some(|ctx, emit, symbols, args| {
34
98
                let ty = to_stack($search, ctx, emit, symbols, args)?;
35
76
                serialize_stack_to_output(ctx, emit, ty)
36
98
            }),
37
        }
38
    };
39
}
40

            
41
pub(in crate::compiler::native) const NATIVES: &[NativeSpec] = &[
42
    search_spec!("GETF", Search::Getf),
43
    search_spec!("ASSOC", Search::Assoc),
44
    search_spec!("MEMBER", Search::Member),
45
];
46

            
47
const LIST: &str = "search list";
48
const KEY: &str = "search key";
49
const DEFAULT: &str = "search default";
50
const CELL: &str = "search cell";
51
const UNSUPPORTED_KEYS: [&str; 3] = ["TEST", "KEY", "TEST-NOT"];
52

            
53
impl Search {
54
3509
    fn name(self) -> &'static str {
55
3509
        match self {
56
2717
            Self::Getf => "GETF",
57
273
            Self::Assoc => "ASSOC",
58
519
            Self::Member => "MEMBER",
59
        }
60
3509
    }
61

            
62
6955
    fn arity(self) -> std::ops::RangeInclusive<usize> {
63
6955
        match self {
64
5469
            Self::Getf => 2..=3,
65
1486
            Self::Assoc | Self::Member => 2..=2,
66
        }
67
6955
    }
68

            
69
    /// Positions of the list and the key among the arguments.
70
20626
    fn operands(self) -> (usize, usize) {
71
20626
        match self {
72
16340
            Self::Getf => (0, 1),
73
4286
            Self::Assoc | Self::Member => (1, 0),
74
        }
75
20626
    }
76

            
77
6960
    fn check(self, args: &[Expr]) -> Result<()> {
78
6960
        if !matches!(self, Self::Getf)
79
1493
            && let Some(Expr::Keyword(key)) = args.get(2..).and_then(<[Expr]>::first)
80
21
            && UNSUPPORTED_KEYS.iter().any(|k| key.eq_ignore_ascii_case(k))
81
        {
82
12
            return Err(Error::Compile(format!(
83
12
                "{}: :{key} is not supported, keys compare with EQL",
84
12
                self.name()
85
12
            )));
86
6948
        }
87
6948
        if self.arity().contains(&args.len()) {
88
6941
            return Ok(());
89
7
        }
90
7
        Err(Error::Arity {
91
7
            name: self.name().to_string(),
92
7
            expected: *self.arity().start(),
93
7
            actual: args.len(),
94
7
        })
95
6960
    }
96
}
97

            
98
115033
fn form(items: Vec<Expr>) -> Expr {
99
115033
    Expr::List(items)
100
115033
}
101

            
102
74185
fn call(head: &str, args: Vec<Expr>) -> Expr {
103
74185
    form(std::iter::once(Expr::symbol(head)).chain(args).collect())
104
74185
}
105

            
106
66702
fn var(name: &str) -> Expr {
107
66702
    Expr::symbol(name)
108
66702
}
109

            
110
/// The cell walk, with the operands bound once in source order. The walk ends
111
/// on the first hit or the end of the list, and the result reads the cell.
112
6807
fn expansion(search: Search, args: &[Expr], list_is_any: bool) -> Expr {
113
6807
    let (list, key) = search.operands();
114
39462
    let cell = || var(CELL);
115
6807
    let (step, probe) = match search {
116
5427
        Search::Getf => (
117
5427
            call("CDR", vec![call("CDR", vec![cell()])]),
118
5427
            call("CAR", vec![cell()]),
119
5427
        ),
120
909
        Search::Member => (call("CDR", vec![cell()]), call("CAR", vec![cell()])),
121
471
        Search::Assoc => (
122
471
            call("CDR", vec![cell()]),
123
471
            call("CAR", vec![call("CAR", vec![cell()])]),
124
471
        ),
125
    };
126
6807
    let operands = if list < key {
127
5427
        [(LIST, list), (KEY, key)]
128
    } else {
129
1380
        [(KEY, key), (LIST, list)]
130
    };
131
6807
    let mut bindings: Vec<Expr> = operands
132
6807
        .into_iter()
133
13614
        .map(|(name, position)| {
134
13614
            let operand = args[position].clone();
135
13614
            let bound = if list_is_any && position == list {
136
3771
                call("APPEND", vec![Expr::Nil, operand])
137
            } else {
138
9843
                operand
139
            };
140
13614
            form(vec![var(name), bound])
141
13614
        })
142
        .collect();
143
6807
    let result = match search {
144
        Search::Getf => {
145
5427
            let miss = args.get(2).map_or(Expr::Nil, |default| {
146
6
                bindings.push(form(vec![var(DEFAULT), default.clone()]));
147
6
                var(DEFAULT)
148
6
            });
149
5427
            let value = call("CAR", vec![call("CDR", vec![cell()])]);
150
5427
            call("IF", vec![cell(), value, miss])
151
        }
152
909
        Search::Member => cell(),
153
471
        Search::Assoc => call("CAR", vec![cell()]),
154
    };
155
6807
    let ended = call(
156
6807
        "OR",
157
6807
        vec![
158
6807
            call("NULL?", vec![cell()]),
159
6807
            call("EQL", vec![probe, var(KEY)]),
160
6807
        ],
161
6807
    );
162
6807
    let walk = call(
163
6807
        "DO",
164
6807
        vec![
165
6807
            form(vec![form(vec![cell(), var(LIST), step])]),
166
6807
            form(vec![ended, result]),
167
6807
        ],
168
6807
    );
169
6807
    call("LET*", vec![form(bindings), walk])
170
6807
}
171

            
172
/// An `any` list operand is coerced to a list cell chain (`TYPE-ERROR` when it
173
/// is none) by `(append nil list)`, so the walk variable is typed as a pair.
174
6806
fn list_is_any(search: Search, probed: &[Expr]) -> bool {
175
6806
    let (list, _) = search.operands();
176
6806
    probed[list].wasm_type() == Some(WasmType::AnyRef)
177
6806
}
178

            
179
115
fn same(symbols: &mut SymbolTable, key: &Expr, member: &Expr) -> Result<bool> {
180
115
    let eql = call(
181
115
        "EQL",
182
115
        vec![as_literal_arg(key), member_value(member.clone())],
183
115
    );
184
115
    Ok(eval_value(symbols, &eql)? == Expr::T)
185
115
}
186

            
187
/// The car of an alist entry; `nil` entries have none.
188
95
fn entry_car(entry: &Expr) -> Result<Option<Expr>> {
189
95
    match entry {
190
2
        Expr::Nil => Ok(None),
191
91
        Expr::List(items) => Ok(items.first().cloned()),
192
        Expr::Cons(car, _) => Ok(Some((**car).clone())),
193
        Expr::Datum(inner) => entry_car(inner),
194
2
        other => Err(Error::Compile(format!(
195
2
            "ASSOC expects an alist, got an entry {}",
196
2
            format_expr(other)
197
2
        ))),
198
    }
199
95
}
200

            
201
161
fn candidates(search: Search, list: &Expr) -> Vec<Expr> {
202
161
    let elements = extract_list_elements(list).unwrap_or_default();
203
161
    match search {
204
45
        Search::Getf => elements.into_iter().step_by(2).collect(),
205
73
        Search::Member => elements,
206
43
        Search::Assoc => elements
207
43
            .iter()
208
66
            .filter_map(|entry| entry_car(entry).ok().flatten())
209
            .collect(),
210
    }
211
161
}
212

            
213
/// A constant list is searched by kind at compile time, as `EQL` of the key
214
/// against each candidate would be: the fold would swallow that refusal.
215
6945
fn refuse_kind_mix(search: Search, probed: &[Expr]) -> Result<()> {
216
6945
    let (list, key) = search.operands();
217
6945
    if !is_constant_datum(&probed[list]) {
218
6784
        return Ok(());
219
161
    }
220
161
    candidates(search, &probed[list])
221
161
        .iter()
222
294
        .try_for_each(|candidate| refuse_dim_mix(&probed[key], candidate, "EQL"))
223
6945
}
224

            
225
68
fn search_constant(
226
68
    search: Search,
227
68
    symbols: &mut SymbolTable,
228
68
    list: &Expr,
229
68
    key: &Expr,
230
68
    default: Expr,
231
68
) -> Result<Expr> {
232
68
    let name = search.name();
233
68
    let elements = extract_list_elements(list)
234
3
        .map_err(|_| Error::Compile(format!("{name} expects a list, got {}", format_expr(list))))?;
235
65
    match search {
236
        Search::Getf => {
237
21
            for pair in elements.chunks(2) {
238
30
                if same(symbols, key, &pair[0])? {
239
12
                    return Ok(pair.get(1).cloned().map_or(Expr::Nil, member_value));
240
18
                }
241
            }
242
9
            Ok(default)
243
        }
244
        Search::Member => {
245
27
            for (at, element) in elements.iter().enumerate() {
246
58
                if same(symbols, key, element)? {
247
23
                    return Ok(Expr::quoted_list(elements[at..].to_vec()));
248
35
                }
249
            }
250
4
            Ok(Expr::Nil)
251
        }
252
        Search::Assoc => {
253
17
            for entry in &elements {
254
29
                if let Some(car) = entry_car(entry)?
255
27
                    && same(symbols, key, &car)?
256
                {
257
15
                    return Ok(member_value(entry.clone()));
258
13
                }
259
            }
260
1
            Ok(Expr::Nil)
261
        }
262
    }
263
68
}
264

            
265
6947
fn probe_args(symbols: &SymbolTable, args: &[Expr]) -> Result<Vec<Expr>> {
266
6947
    let mut probe = symbols.clone();
267
6947
    args.iter()
268
13913
        .map(|arg| probe_value(&mut probe, arg))
269
        .collect()
270
6947
}
271

            
272
3502
fn eval(search: Search, symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
273
3502
    search.check(args)?;
274
3492
    let probed = probe_args(symbols, args)?;
275
3492
    refuse_kind_mix(search, &probed)?;
276
3489
    if probed.iter().any(Expr::is_wasm_runtime) {
277
3421
        let any = list_is_any(search, &probed);
278
3421
        return eval_value(symbols, &expansion(search, args, any));
279
68
    }
280
68
    let values: Vec<Expr> = args
281
68
        .iter()
282
143
        .map(|arg| eval_value(symbols, arg))
283
        .collect::<Result<_>>()?;
284
68
    let (list, key) = search.operands();
285
68
    let default = values.get(2).cloned().unwrap_or(Expr::Nil);
286
68
    search_constant(search, symbols, &values[list], &values[key], default)
287
3502
}
288

            
289
3458
fn to_stack(
290
3458
    search: Search,
291
3458
    ctx: &mut CompileContext,
292
3458
    emit: &mut FunctionEmitter,
293
3458
    symbols: &mut SymbolTable,
294
3458
    args: &[Expr],
295
3458
) -> Result<WasmType> {
296
3458
    search.check(args)?;
297
3449
    let probed = probe_args(symbols, args)?;
298
3449
    refuse_kind_mix(search, &probed)?;
299
3422
    if let Some(folded) = fold_call(symbols, search.name(), args)? {
300
39
        return compile_folded_to_stack(ctx, emit, symbols, folded);
301
3383
    }
302
3383
    let any = list_is_any(search, &probed);
303
3383
    compile_for_stack(ctx, emit, symbols, &expansion(search, args, any))
304
3458
}
305

            
306
#[cfg(test)]
307
#[path = "search_tests.rs"]
308
mod tests;