1
//! A BLOCK or IF of integer literals is an index, so beside a fractional
2
//! literal or a runtime scalar arithmetic refuses it; an operand that always
3
//! raises has no dimension.
4

            
5
use super::ExpectingForm;
6
use crate::ast::{Expr, WasmType};
7
use crate::compiler::CompileMode;
8
use crate::compiler::behaviour_oracle::{Outcome, observe};
9
use crate::compiler::expr::eval_value;
10
use crate::compiler::stats::CompileStats;
11
use crate::error::Result;
12
use crate::host_fn::HostFnSpec;
13
use crate::reader::Reader;
14
use crate::runtime::SymbolTable;
15

            
16
const TEST: &str = "(> (rpc-protocol-version) 0)";
17
const MACRO: &str = "(defmacro m (x) (list 'progn x))";
18
const REFUSED: &str = "+ cannot mix an index (count) with a scalar";
19

            
20
27
fn hosts() -> [HostFnSpec; 1] {
21
27
    [
22
27
        HostFnSpec::new("rpc-protocol-version", "nomi", "rpc_protocol_version")
23
27
            .returns(WasmType::I32),
24
27
    ]
25
27
}
26

            
27
/// The outcome in the empty-batch world (protocol 1) and the ledger world
28
/// (protocol 0), and the BLOCK pass counters.
29
20
fn run(source: &str) -> (Vec<String>, (u64, u64)) {
30
20
    let (outcomes, stats) = run_with_stats(source);
31
20
    (outcomes, (stats.block_passes_max, stats.block_passes_total))
32
20
}
33

            
34
20
fn run_with_stats(source: &str) -> (Vec<String>, CompileStats) {
35
20
    let (behaviours, stats) = observe(source, CompileMode::Eval, &hosts());
36
20
    let outcomes = behaviours
37
20
        .into_iter()
38
40
        .map(|b| match b.outcome {
39
4
            Outcome::Value(v) => v.replace("Struct(2), ", ""),
40
36
            Outcome::CompileError(e) => e,
41
            other => format!("{other:?}"),
42
40
        })
43
        .collect();
44
20
    (outcomes, stats)
45
20
}
46

            
47
2
fn ratio(numer: i64, denom: i64) -> String {
48
2
    format!("Some(Ratio) [I64({numer}), I64({denom})]")
49
2
}
50

            
51
13
fn refused(outcomes: &[String]) -> bool {
52
26
    outcomes.iter().all(|outcome| outcome.contains(REFUSED))
53
13
}
54

            
55
#[test]
56
1
fn a_block_of_literals_beside_a_fraction_is_refused() {
57
1
    let (outcomes, _) = run(&format!("{MACRO} (+ 1/2 (block b (m 2) 1))"));
58
1
    assert!(refused(&outcomes), "{outcomes:?}");
59
1
}
60

            
61
#[test]
62
1
fn a_block_with_a_literal_exit_beside_a_fraction_is_refused() {
63
1
    let (outcomes, _) = run(&format!(
64
1
        "(+ 1/2 (block b (if {TEST} (return-from b 1)) 2))"
65
1
    ));
66
1
    assert!(refused(&outcomes), "{outcomes:?}");
67
1
}
68

            
69
#[test]
70
1
fn an_if_of_literals_beside_a_fraction_is_refused() {
71
1
    let (outcomes, _) = run(&format!("(+ 1/2 (if {TEST} 1 2))"));
72
1
    assert!(refused(&outcomes), "{outcomes:?}");
73
1
}
74

            
75
#[test]
76
1
fn a_constant_test_if_beside_a_fraction_is_refused() {
77
1
    for form in [
78
1
        "(+ 1/2 (if t (block b (m 2) 1) 2))",
79
1
        "(+ 1/2 (if nil 2 (block b (m 2) 1)))",
80
1
    ] {
81
2
        let (outcomes, _) = run(&format!("{MACRO} {form}"));
82
2
        assert!(refused(&outcomes), "{form}: {outcomes:?}");
83
    }
84
1
}
85

            
86
#[test]
87
1
fn nested_forms_of_literals_beside_a_fraction_are_refused() {
88
1
    for form in [
89
1
        format!("(+ 1/2 (block b (m 2) (if {TEST} 1 2)))"),
90
1
        format!("(+ 1/2 (block b (if {TEST} (return-from b (if {TEST} 1 3))) 2))"),
91
1
        "(+ 1/2 (block a (block b (m 2) 1)))".to_string(),
92
1
        format!(
93
1
            "(+ 1/2 (block a (if {TEST} (return-from a (block b (m 2) 1))) (block c (m 3) 2)))"
94
1
        ),
95
1
    ] {
96
4
        let (outcomes, _) = run(&format!("{MACRO} {form}"));
97
4
        assert!(refused(&outcomes), "{form}: {outcomes:?}");
98
    }
99
1
}
100

            
101
#[test]
102
1
fn an_if_joining_an_index_arm_with_a_fraction_arm_is_refused() {
103
1
    let (outcomes, _) = run(&format!("(+ (if {TEST} (if {TEST} 1 2) 1/2) 1/2)"));
104
1
    assert!(
105
1
        outcomes
106
1
            .iter()
107
2
            .all(|outcome| outcome.contains("expects numeric arguments")),
108
        "{outcomes:?}"
109
    );
110
1
}
111

            
112
#[test]
113
1
fn a_block_whose_every_arm_raises_has_no_dimension() {
114
1
    let (outcomes, _) = run("(handler-case (+ 1/2 (block b (error 'boom \"x\"))) (boom (e) 1/4))");
115
1
    assert_eq!(outcomes, [ratio(1, 4), ratio(1, 4)]);
116
1
}
117

            
118
#[test]
119
1
fn every_arithmetic_operator_refuses_a_block_of_literals_beside_a_fraction() {
120
1
    for op in ["+", "-", "*", "/"] {
121
4
        let (outcomes, _) = run(&format!("{MACRO} ({op} (block b (m 2) 1) 1/2)"));
122
4
        let text = format!("{op} cannot mix an index (count) with a scalar");
123
4
        assert!(
124
8
            outcomes.iter().all(|outcome| outcome.contains(&text)),
125
            "{op}: {outcomes:?}"
126
        );
127
    }
128
1
}
129

            
130
#[test]
131
1
fn integer_literals_expect_nothing() {
132
1
    let (outcomes, _) = run(&format!("{MACRO} (+ 1 (block b (m 2) 1))"));
133
1
    assert_eq!(
134
1
        outcomes,
135
1
        ["Some(I32) [I64(2), I64(1)]", "Some(I32) [I64(2), I64(1)]"]
136
    );
137
1
}
138

            
139
#[test]
140
1
fn a_runtime_index_beside_a_fraction_is_refused() {
141
1
    let (outcomes, _) = run("(+ 1/2 (rpc-protocol-version))");
142
1
    assert!(refused(&outcomes), "{outcomes:?}");
143
1
}
144

            
145
#[test]
146
1
fn a_block_with_a_computed_index_exit_is_refused() {
147
1
    let (outcomes, _) = run(&format!(
148
1
        "(+ 1/2 (block b (if {TEST} (return-from b (rpc-protocol-version))) 1))"
149
1
    ));
150
1
    assert!(refused(&outcomes), "{outcomes:?}");
151
1
}
152

            
153
#[test]
154
1
fn an_if_with_a_computed_index_arm_is_refused() {
155
1
    let (outcomes, _) = run(&format!("(+ 1/2 (if {TEST} (rpc-protocol-version) 2))"));
156
1
    assert!(refused(&outcomes), "{outcomes:?}");
157
1
}
158

            
159
#[test]
160
1
fn a_closure_body_refuses_the_mix_on_the_eval_surface() {
161
1
    let (outcomes, _) = run(&format!(
162
1
        "(mapcar (lambda (x) (+ 1/2 (if {TEST} 1 2))) (list 1 2))"
163
1
    ));
164
1
    assert!(refused(&outcomes), "{outcomes:?}");
165
1
}
166

            
167
7
fn try_eval(source: &str) -> Result<Expr> {
168
7
    let mut symbols = SymbolTable::with_builtins_for_wasm();
169
7
    symbols.register_host_fns(&hosts());
170
7
    symbols.register_host_fns(&[
171
7
        HostFnSpec::new("money-source", "nomi", "money_source").returns(WasmType::Commodity)
172
7
    ]);
173
7
    let program = Reader::parse(source).expect("parse");
174
7
    eval_value(&mut symbols, &program.exprs[0])
175
7
}
176

            
177
4
fn eval(source: &str) -> Expr {
178
4
    try_eval(source).expect("eval")
179
4
}
180

            
181
#[test]
182
1
fn the_eval_surface_refuses_a_runtime_index_beside_a_fraction() {
183
1
    let err = try_eval("(+ 1/2 (rpc-protocol-version))").expect_err("refused");
184
1
    assert!(err.to_string().contains("cannot mix an index"), "{err}");
185
1
}
186

            
187
#[test]
188
1
fn the_eval_surface_refuses_a_block_or_if_operand_beside_a_fraction() {
189
1
    for operand in [
190
1
        format!("(if {TEST} 1 2)"),
191
1
        format!("(block b (if {TEST} (return-from b 1)) 2)"),
192
1
    ] {
193
2
        let err = try_eval(&format!("(+ 1/2 {operand})")).expect_err("refused");
194
2
        assert!(err.to_string().contains(REFUSED), "{operand}: {err}");
195
2
        assert_eq!(
196
2
            eval(&format!("(+ 1 {operand})")),
197
2
            Expr::WasmRuntime(WasmType::I32),
198
            "{operand}"
199
        );
200
    }
201
1
}
202

            
203
#[test]
204
1
fn only_a_block_or_an_if_takes_an_expected_type() {
205
1
    let forms = [
206
1
        "(block b 1)",
207
1
        "(if t 1 2)",
208
1
        "(progn 1)",
209
1
        "(foo 1)",
210
1
        "1",
211
1
        "()",
212
1
    ];
213
1
    let taken: Vec<bool> = forms
214
1
        .iter()
215
6
        .map(|source| {
216
6
            let program = Reader::parse(source).expect("parse");
217
6
            ExpectingForm::of(&program.exprs[0]).is_some()
218
6
        })
219
        .collect();
220
1
    assert_eq!(taken, [true, true, false, false, false, false]);
221
1
}
222

            
223
#[test]
224
1
fn the_eval_surface_keeps_a_money_operand_beside_a_fraction() {
225
1
    for operand in [
226
1
        format!("(if {TEST} (money-source) (money-source))"),
227
1
        format!("(block b (if {TEST} (return-from b (money-source))) (money-source))"),
228
1
    ] {
229
2
        assert_eq!(
230
2
            eval(&format!("(* 1/2 {operand})")),
231
2
            Expr::WasmRuntime(WasmType::Commodity),
232
            "{operand}"
233
        );
234
    }
235
1
}