1
use super::NATIVES;
2
use crate::ast::{Expr, PairElement, WasmType};
3
use crate::compiler::context::CompileContext;
4
use crate::compiler::emit::FunctionEmitter;
5
use crate::compiler::expr::eval_value;
6
use crate::error::{Error, Result};
7
use crate::reader::Reader;
8
use crate::runtime::SymbolTable;
9

            
10
37
fn spec(name: &str) -> &'static crate::compiler::native::NativeSpec {
11
37
    NATIVES
12
37
        .iter()
13
73
        .find(|spec| spec.name == name)
14
37
        .expect("registered search native")
15
37
}
16

            
17
44
fn args(sources: &[&str]) -> Result<Vec<Expr>> {
18
100
    sources.iter().map(|s| Reader::parse_expr(s)).collect()
19
44
}
20

            
21
27
fn eval(name: &str, sources: &[&str]) -> Result<Expr> {
22
27
    let mut symbols = SymbolTable::with_builtins();
23
27
    (spec(name).eval)(&mut symbols, &args(sources)?)
24
27
}
25

            
26
5
fn value(source: &str) -> Expr {
27
5
    let mut symbols = SymbolTable::with_builtins();
28
5
    eval_value(&mut symbols, &Reader::parse_expr(source).unwrap()).unwrap()
29
5
}
30

            
31
8
fn lower(name: &str, sources: &[&str]) -> Result<WasmType> {
32
8
    let mut ctx = CompileContext::new_with_host_fns(&[])?;
33
8
    let mut emit = FunctionEmitter::new();
34
8
    let mut symbols = SymbolTable::with_builtins();
35
8
    let stack = spec(name).stack.expect("search natives lower to the stack");
36
8
    let ty = stack(&mut ctx, &mut emit, &mut symbols, &args(sources)?)?;
37
5
    emit.finish(&[])?;
38
5
    Ok(ty)
39
8
}
40

            
41
#[test]
42
1
fn getf_folds_a_constant_plist() {
43
1
    assert_eq!(eval("GETF", &["'(:a 1 :b 2)", ":b"]).unwrap(), value("2"));
44
1
}
45

            
46
#[test]
47
1
fn getf_answers_the_default_or_nil_for_a_missing_key() {
48
1
    assert_eq!(eval("GETF", &["'(:a 1)", ":z", "9"]).unwrap(), value("9"));
49
1
    assert_eq!(eval("GETF", &["'(:a 1)", ":z"]).unwrap(), Expr::Nil);
50
1
}
51

            
52
#[test]
53
1
fn getf_keys_are_eql_so_a_keyword_is_not_its_symbol() {
54
1
    assert_eq!(eval("GETF", &["'(:a 1)", "'a"]).unwrap(), Expr::Nil);
55
1
}
56

            
57
#[test]
58
1
fn getf_of_a_trailing_key_without_a_value_is_nil() {
59
1
    assert_eq!(eval("GETF", &["'(:a 1 :b)", ":b"]).unwrap(), Expr::Nil);
60
1
}
61

            
62
#[test]
63
1
fn member_folds_to_the_tail() {
64
1
    assert_eq!(
65
1
        eval("MEMBER", &["'b", "'(a b c)"]).unwrap(),
66
1
        value("'(b c)")
67
    );
68
1
    assert_eq!(eval("MEMBER", &["'z", "'(a b c)"]).unwrap(), Expr::Nil);
69
1
}
70

            
71
#[test]
72
1
fn assoc_folds_to_the_first_matching_entry() {
73
1
    assert_eq!(
74
1
        eval("ASSOC", &["'b", "'((a 1) (b 2) (b 3))"]).unwrap(),
75
1
        value("'(b 2)")
76
    );
77
1
    assert_eq!(eval("ASSOC", &["'z", "'((a 1))"]).unwrap(), Expr::Nil);
78
1
}
79

            
80
#[test]
81
1
fn assoc_skips_nil_entries_and_refuses_other_atoms() {
82
1
    assert_eq!(
83
1
        eval("ASSOC", &["'b", "'(nil (b 2))"]).unwrap(),
84
1
        value("'(b 2)")
85
    );
86
1
    assert!(matches!(
87
1
        eval("ASSOC", &["'b", "'(1 (b 2))"]),
88
1
        Err(Error::Compile(ref m)) if m.contains("alist")
89
    ));
90
1
}
91

            
92
#[test]
93
1
fn a_non_list_is_a_compile_error() {
94
1
    for name in ["GETF", "MEMBER", "ASSOC"] {
95
3
        let sources: &[&str] = if name == "GETF" {
96
1
            &["1", ":a"]
97
        } else {
98
2
            &["'a", "1"]
99
        };
100
3
        assert!(
101
3
            matches!(eval(name, sources), Err(Error::Compile(ref m)) if m.contains(name)),
102
            "{name}"
103
        );
104
    }
105
1
}
106

            
107
#[test]
108
1
fn test_and_key_arguments_are_refused() {
109
1
    for name in ["MEMBER", "ASSOC"] {
110
2
        for keyword in [":test", ":key", ":test-not"] {
111
6
            let err = eval(name, &["'a", "'(a)", keyword, "'eql"]);
112
6
            assert!(
113
6
                matches!(err, Err(Error::Compile(ref m)) if m.contains("not supported")),
114
                "{name} {keyword}"
115
            );
116
        }
117
    }
118
1
}
119

            
120
#[test]
121
1
fn a_wrong_argument_count_is_an_arity_error() {
122
1
    assert!(matches!(
123
1
        eval("GETF", &["'(:a 1)"]),
124
        Err(Error::Arity { expected: 2, .. })
125
    ));
126
1
    assert!(matches!(
127
1
        eval("GETF", &["'(:a 1)", ":a", "1", "2"]),
128
        Err(Error::Arity { .. })
129
    ));
130
1
    for name in ["MEMBER", "ASSOC"] {
131
2
        assert!(matches!(
132
2
            eval(name, &["'a"]),
133
            Err(Error::Arity { expected: 2, .. })
134
        ));
135
    }
136
1
}
137

            
138
#[test]
139
1
fn a_runtime_operand_answers_the_type_of_the_walk() {
140
1
    let mut symbols = SymbolTable::with_builtins();
141
1
    let runtime = Expr::WasmRuntime(WasmType::PairRef(PairElement::AnyRef));
142
1
    let key = Reader::parse_expr(":a").unwrap();
143
1
    let got = (spec("GETF").eval)(&mut symbols, &[runtime.clone(), key]).unwrap();
144
1
    assert_eq!(got, Expr::WasmRuntime(WasmType::AnyRef));
145
1
    let item = Reader::parse_expr("'a").unwrap();
146
1
    let tail = (spec("MEMBER").eval)(&mut symbols, &[item, runtime]).unwrap();
147
1
    assert_eq!(
148
1
        tail,
149
1
        Expr::WasmRuntime(WasmType::PairRef(PairElement::AnyRef))
150
    );
151
1
}
152

            
153
#[test]
154
1
fn constant_operands_lower_to_the_folded_value() {
155
1
    assert_eq!(
156
1
        lower("GETF", &["'(:a 1 :b 2)", ":b"]).unwrap(),
157
1
        WasmType::I32
158
    );
159
1
    assert_eq!(
160
1
        lower("MEMBER", &["'b", "'(a b c)"]).unwrap(),
161
1
        WasmType::PairRef(PairElement::Symbol)
162
    );
163
1
    assert_eq!(
164
1
        lower("ASSOC", &["'b", "'((a 1) (b 2))"]).unwrap(),
165
1
        WasmType::PairRef(PairElement::AnyRef)
166
    );
167
1
}
168

            
169
#[test]
170
1
fn a_runtime_operand_lowers_to_the_walk() {
171
1
    assert_eq!(
172
1
        lower("MEMBER", &["(progn (print 1) 'b)", "'(a b c)"]).unwrap(),
173
1
        WasmType::PairRef(PairElement::Symbol)
174
    );
175
1
    assert_eq!(
176
1
        lower("GETF", &["'(:a 1)", "(progn (print 1) :a)"]).unwrap(),
177
1
        WasmType::AnyRef
178
    );
179
1
}
180

            
181
3
fn expansion_text(search: super::Search, sources: &[&str], any: bool) -> String {
182
3
    crate::compiler::expr::format_expr(&super::expansion(search, &args(sources).unwrap(), any))
183
3
}
184

            
185
#[test]
186
1
fn an_any_list_operand_is_coerced_to_a_list_once() {
187
1
    let any = expansion_text(super::Search::Getf, &["p", ":k"], true);
188
1
    assert!(any.contains("APPEND"), "{any}");
189
1
    let typed = expansion_text(super::Search::Getf, &["p", ":k"], false);
190
1
    assert!(!typed.contains("APPEND"), "{typed}");
191
1
}
192

            
193
#[test]
194
1
fn only_the_list_operand_is_coerced_for_assoc() {
195
1
    let text = expansion_text(super::Search::Assoc, &["k", "alist"], true);
196
1
    assert_eq!(text.matches("APPEND").count(), 1, "{text}");
197
1
    assert!(text.contains("(APPEND nil ALIST)"), "{text}");
198
1
}
199

            
200
#[test]
201
1
fn list_is_any_detects_only_an_any_operand() {
202
1
    let mut symbols = SymbolTable::with_builtins();
203
1
    let quoted = args(&["'(1 2)", "1"]).unwrap();
204
1
    let probed = super::probe_args(&symbols, &quoted).unwrap();
205
1
    assert!(!super::list_is_any(super::Search::Member, &probed));
206
1
    symbols.define(
207
1
        crate::runtime::Symbol::new("P", crate::runtime::SymbolKind::Variable)
208
1
            .with_value(Expr::WasmRuntime(WasmType::AnyRef)),
209
1
    );
210
1
    let any = args(&["1", "p"]).unwrap();
211
1
    let probed = super::probe_args(&symbols, &any).unwrap();
212
1
    assert!(super::list_is_any(super::Search::Member, &probed));
213
1
}
214

            
215
#[test]
216
1
fn refuse_kind_mix_refuses_a_key_of_another_kind_than_a_constant_candidate() {
217
1
    let symbols = SymbolTable::with_builtins();
218
1
    for (search, sources) in [
219
1
        (super::Search::Member, ["1", "'(1/1 \"a\")"]),
220
1
        (super::Search::Assoc, ["1", "'((1/1 2/1))"]),
221
1
        (super::Search::Getf, ["'(1/1 \"a\")", "1"]),
222
1
    ] {
223
3
        assert!(
224
3
            matches!(
225
3
                super::refuse_kind_mix(
226
3
                    search,
227
3
                    &super::probe_args(&symbols, &args(&sources).unwrap()).unwrap()
228
3
                ),
229
                Err(Error::Dimension(_))
230
            ),
231
            "{sources:?}"
232
        );
233
    }
234
1
}
235

            
236
#[test]
237
1
fn refuse_kind_mix_passes_a_key_of_the_candidates_kind() {
238
1
    let symbols = SymbolTable::with_builtins();
239
1
    let same_kind = args(&["1/2", "'(1/2 \"a\")"]).unwrap();
240
1
    let probed = super::probe_args(&symbols, &same_kind).unwrap();
241
1
    assert!(super::refuse_kind_mix(super::Search::Member, &probed).is_ok());
242
1
}
243

            
244
#[test]
245
1
fn constant_searches_across_kinds_are_refused_on_both_surfaces() {
246
1
    for (name, sources) in [
247
1
        ("MEMBER", ["1", "'(1/1 \"a\")"]),
248
1
        ("ASSOC", ["1", "'((1/1 \"a\"))"]),
249
1
        ("GETF", ["'(1/1 \"a\")", "1"]),
250
1
    ] {
251
3
        assert!(
252
3
            matches!(eval(name, &sources), Err(Error::Dimension(_))),
253
            "{name}"
254
        );
255
3
        assert!(
256
3
            matches!(lower(name, &sources), Err(Error::Dimension(_))),
257
            "{name}"
258
        );
259
    }
260
1
}