1
use super::{Sign, compile_sign, sign_eval};
2
use crate::ast::{Expr, Fraction, Number, WasmType};
3
use crate::compiler::context::CompileContext;
4
use crate::compiler::emit::FunctionEmitter;
5
use crate::compiler::expr::fold_value;
6
use crate::error::{Error, Result};
7
use crate::reader::Reader;
8
use crate::runtime::SymbolTable;
9

            
10
const SIGNS: [Sign; 3] = [Sign::Zero, Sign::Plus, Sign::Minus];
11

            
12
30
fn eval(sign: Sign, operand: Expr) -> Result<Expr> {
13
30
    sign_eval(&mut SymbolTable::with_builtins(), &[operand], sign)
14
30
}
15

            
16
17
fn number(numer: i64, denom: i64) -> Expr {
17
17
    Expr::Number(Number::Scalar(Fraction::new(numer, denom)))
18
17
}
19

            
20
15
fn truth(value: bool) -> Expr {
21
15
    if value { Expr::T } else { Expr::Nil }
22
15
}
23

            
24
#[test]
25
1
fn a_constant_folds_to_its_sign() -> Result<()> {
26
1
    for (numer, denom, zero, plus, minus) in [
27
1
        (-2, 1, false, false, true),
28
1
        (0, 1, true, false, false),
29
1
        (2, 1, false, true, false),
30
1
        (-1, 2, false, false, true),
31
1
        (1, 2, false, true, false),
32
1
    ] {
33
5
        for (sign, want) in SIGNS.into_iter().zip([zero, plus, minus]) {
34
15
            assert_eq!(
35
15
                eval(sign, number(numer, denom))?,
36
15
                truth(want),
37
                "{sign:?} {numer}/{denom}"
38
            );
39
        }
40
    }
41
1
    Ok(())
42
1
}
43

            
44
#[test]
45
1
fn a_runtime_number_answers_a_runtime_boolean() -> Result<()> {
46
1
    for sign in SIGNS {
47
3
        for ty in [WasmType::I32, WasmType::Ratio, WasmType::Commodity] {
48
9
            assert_eq!(
49
9
                eval(sign, Expr::WasmRuntime(ty))?,
50
9
                Expr::WasmRuntime(WasmType::Bool),
51
                "{sign:?} {ty}"
52
            );
53
        }
54
    }
55
1
    Ok(())
56
1
}
57

            
58
8
fn compile_error(result: Result<impl std::fmt::Debug>) -> String {
59
8
    match result {
60
8
        Err(Error::Compile(message)) => message,
61
        other => format!("not a compile error: {other:?}"),
62
    }
63
8
}
64

            
65
#[test]
66
1
fn an_any_operand_must_be_narrowed_with_the() {
67
1
    for sign in SIGNS {
68
3
        let message = compile_error(eval(sign, Expr::WasmRuntime(WasmType::AnyRef)));
69
3
        assert!(message.contains("got any; narrow it with THE"), "{message}");
70
    }
71
1
}
72

            
73
#[test]
74
1
fn a_non_number_is_a_compile_error() {
75
1
    for operand in [
76
1
        Expr::T,
77
1
        Expr::String("a".to_string()),
78
1
        Expr::WasmRuntime(WasmType::StringRef),
79
1
    ] {
80
3
        let message = compile_error(eval(Sign::Zero, operand));
81
3
        assert!(
82
3
            message.starts_with("zerop expects an index, scalar or money, got "),
83
            "{message}"
84
        );
85
    }
86
1
}
87

            
88
#[test]
89
1
fn a_wrong_arity_is_an_arity_error() {
90
1
    for args in [vec![], vec![number(1, 1), number(2, 1)]] {
91
2
        let result = sign_eval(&mut SymbolTable::with_builtins(), &args, Sign::Plus);
92
2
        assert!(
93
2
            matches!(result, Err(Error::Arity { expected: 1, .. })),
94
            "{result:?}"
95
        );
96
    }
97
1
}
98

            
99
11
fn lower(sign: Sign, ty: WasmType) -> Result<WasmType> {
100
11
    let mut ctx = CompileContext::new_with_host_fns(&[])?;
101
11
    let mut emit = FunctionEmitter::new();
102
11
    let local = ctx.alloc_local(ty)?;
103
11
    let lowered = compile_sign(
104
11
        &mut ctx,
105
11
        &mut emit,
106
11
        &mut SymbolTable::with_builtins(),
107
11
        &[Expr::WasmLocal(local, ty)],
108
11
        sign,
109
11
    )?;
110
9
    emit.finish(&[])?;
111
9
    Ok(lowered)
112
11
}
113

            
114
#[test]
115
1
fn every_numeric_local_lowers_to_a_boolean() -> Result<()> {
116
1
    for sign in SIGNS {
117
3
        for ty in [WasmType::I32, WasmType::Ratio, WasmType::Commodity] {
118
9
            assert_eq!(lower(sign, ty)?, WasmType::Bool, "{sign:?} {ty}");
119
        }
120
    }
121
1
    Ok(())
122
1
}
123

            
124
#[test]
125
1
fn a_local_of_another_type_is_refused() {
126
1
    let message = compile_error(lower(Sign::Minus, WasmType::AnyRef));
127
1
    assert!(message.contains("narrow it with THE"), "{message}");
128
1
    let message = compile_error(lower(Sign::Minus, WasmType::Bool));
129
1
    assert_eq!(
130
1
        message,
131
1
        "minusp expects an index, scalar or money, got bool"
132
    );
133
1
}
134

            
135
#[test]
136
1
fn a_constant_call_folds_on_the_codegen_surface() -> Result<()> {
137
1
    let mut symbols = SymbolTable::with_builtins();
138
1
    for (source, want) in [
139
1
        ("(zerop 0)", Some(Expr::T)),
140
1
        ("(plusp 1/2)", Some(Expr::T)),
141
1
        ("(minusp (- 3 5))", Some(Expr::T)),
142
1
        ("(plusp 0)", Some(Expr::Nil)),
143
1
        ("(zerop \"a\")", None),
144
1
        ("(zerop)", None),
145
1
    ] {
146
6
        let before = symbols.state_digest();
147
6
        assert_eq!(
148
6
            fold_value(&mut symbols, &Reader::parse_expr(source)?)?,
149
6
            want,
150
            "{source}"
151
        );
152
6
        assert_eq!(
153
6
            strip_charge(&before),
154
6
            strip_charge(&symbols.state_digest()),
155
            "{source} changed the table"
156
        );
157
    }
158
1
    Ok(())
159
1
}
160

            
161
12
fn strip_charge(digest: &str) -> Vec<&str> {
162
12
    digest
163
12
        .lines()
164
372
        .filter(|line| !line.starts_with("charged:"))
165
        .collect()
166
12
}