1
use crate::compiler::CompileMode;
2
use std::collections::HashSet;
3

            
4
use super::*;
5
use crate::ast::WasmType;
6
use crate::compiler::Compiler;
7
use crate::compiler::join::Arm;
8
use crate::reader::Reader;
9
use crate::runtime::HomeKey;
10

            
11
7
fn eval_type(source: &str) -> Result<Option<WasmType>> {
12
7
    let program = Reader::parse(source).expect("parses");
13
7
    let mut symbols = SymbolTable::with_builtins();
14
7
    Compiler::new()
15
7
        .compile_eval_with_type(&program, &mut symbols)
16
        .map(|(_, ty)| ty)
17
7
}
18

            
19
#[test]
20
1
fn a_unit_whose_homes_are_right_compiles_once() {
21
1
    let mut symbols = SymbolTable::new();
22
1
    let mut attempts = 0;
23
1
    let result = settle_homes(&mut symbols, |symbols| {
24
1
        attempts += 1;
25
1
        symbols.note_home(
26
1
            "G",
27
1
            vec![Arm::NumberLiteral(WasmType::I32)],
28
1
            None,
29
1
            WasmType::I32,
30
1
        );
31
1
        symbols.note_store(&HomeKey::global("G"), Arm::NumberLiteral(WasmType::I32));
32
1
        Ok(attempts)
33
1
    });
34
1
    assert_eq!(result.expect("settles"), 1);
35
1
}
36

            
37
#[test]
38
1
fn a_unit_that_never_settles_stops_at_the_cap() {
39
1
    let mut symbols = SymbolTable::new();
40
1
    let mut attempts = 0;
41
4
    let result: Result<()> = settle_homes(&mut symbols, |symbols| {
42
4
        attempts += 1;
43
4
        symbols.set_unit_specials(HashSet::from(["G".to_string()]), HashSet::new());
44
4
        symbols.note_home(
45
4
            "G",
46
4
            vec![Arm::NumberLiteral(WasmType::I32)],
47
4
            None,
48
4
            WasmType::I32,
49
4
        );
50
4
        symbols.note_store(&HomeKey::global("G"), Arm::Value(WasmType::Ratio));
51
4
        Ok(())
52
4
    });
53
1
    assert!(
54
1
        matches!(result, Err(Error::Resource(msg)) if msg == "the type of global G did not settle")
55
    );
56
1
    assert_eq!(attempts, 4);
57
1
}
58

            
59
#[test]
60
1
fn a_widening_is_seeded_into_the_next_attempt() {
61
1
    let mut symbols = SymbolTable::new();
62
1
    let mut hints = Vec::new();
63
2
    let result = settle_homes(&mut symbols, |symbols| {
64
2
        symbols.set_unit_specials(HashSet::from(["G".to_string()]), HashSet::new());
65
2
        let hint = symbols.hint(&HomeKey::global("G"));
66
2
        hints.push(hint);
67
2
        let ty = hint.unwrap_or(WasmType::I32);
68
2
        symbols.note_home("G", vec![Arm::NumberLiteral(WasmType::I32)], None, ty);
69
2
        symbols.note_store(&HomeKey::global("G"), Arm::Value(WasmType::Ratio));
70
2
        Ok(())
71
2
    });
72
1
    result.expect("settles");
73
1
    assert_eq!(hints, [None, Some(WasmType::Ratio)]);
74
1
}
75

            
76
#[test]
77
1
fn the_hints_do_not_outlive_the_unit() {
78
1
    let mut symbols = SymbolTable::new();
79
1
    settle_homes(&mut symbols, |symbols| {
80
1
        symbols.note_home(
81
1
            "G",
82
1
            vec![Arm::NumberLiteral(WasmType::I32)],
83
1
            None,
84
1
            WasmType::I32,
85
1
        );
86
1
        symbols.note_store(&HomeKey::global("G"), Arm::Value(WasmType::Ratio));
87
1
        Ok(())
88
1
    })
89
1
    .expect_err("never settles");
90
1
    assert_eq!(symbols.hint(&HomeKey::global("G")), None);
91
1
}
92

            
93
#[test]
94
1
fn a_defun_accumulator_seeded_with_an_index_is_refused_beside_a_scalar() {
95
    let err =
96
1
        eval_type("(defvar total 0) (defun add (a) (setf total (+ total a))) (add 1/2) total")
97
1
            .expect_err("a mix, CL 1/2");
98
1
    assert!(
99
1
        err.to_string()
100
1
            .contains("+ cannot mix an index (count) with a scalar"),
101
        "{err}"
102
    );
103
1
}
104

            
105
#[test]
106
1
fn a_defun_accumulator_seeded_with_a_scalar_is_a_scalar_home() {
107
    let ty =
108
1
        eval_type("(defvar total 0/1) (defun add (a) (setf total (+ total a))) (add 1/2) total");
109
1
    assert_eq!(ty.expect("compiles"), Some(WasmType::Ratio));
110
1
}
111

            
112
#[test]
113
1
fn a_defun_cons_onto_nil_settles_to_a_list_home() {
114
1
    let ty = eval_type("(defvar l nil) (defun add (v) (setf l (cons v l))) (add 1) l");
115
1
    assert!(matches!(ty.expect("compiles"), Some(WasmType::PairRef(_))));
116
1
}
117

            
118
#[test]
119
1
fn a_nil_after_a_number_settles_to_an_anyref_home() {
120
1
    let ty = eval_type("(defvar g 0) (setf g nil) g");
121
1
    assert_eq!(ty.expect("compiles"), Some(WasmType::AnyRef));
122
1
}
123

            
124
#[test]
125
1
fn a_unit_with_an_error_of_its_own_reports_it() {
126
1
    let err = eval_type("(defvar g 0) (setf g 1/2) (undefined-fn g)").expect_err("rejected");
127
1
    assert!(!matches!(err, Error::Resource(_)));
128
1
}
129

            
130
#[test]
131
1
fn the_measured_stats_come_from_the_final_attempt_and_the_work_adds_up() {
132
2
    let stats = |source: &str| {
133
2
        let program = Reader::parse(source).expect("parses");
134
2
        let mut compiler = Compiler::new();
135
2
        compiler
136
2
            .compile_eval_with_type(&program, &mut SymbolTable::with_builtins())
137
2
            .expect("compiles");
138
2
        compiler.stats()
139
2
    };
140
1
    let source = "(defun put (a) (setf total a)) (put 1/2) total";
141
1
    let widened = stats(&format!("(defvar total 0) {source}"));
142
1
    let direct = stats(&format!("(defvar total 1/2) {source}"));
143
1
    assert_eq!((widened.unit_attempts, direct.unit_attempts), (2, 1));
144
1
    assert_eq!(
145
1
        (widened.folds, widened.probe_walks, widened.stored_globals),
146
1
        (direct.folds, direct.probe_walks, direct.stored_globals)
147
    );
148
1
    assert!(widened.stack_compiles > direct.stack_compiles);
149
1
}
150

            
151
#[test]
152
1
fn a_settled_unit_leaves_no_hints_behind() {
153
1
    let mut symbols = SymbolTable::new();
154
1
    let mut attempts = 0;
155
2
    settle_homes(&mut symbols, |symbols| {
156
2
        attempts += 1;
157
2
        symbols.set_unit_specials(HashSet::from(["G".to_string()]), HashSet::new());
158
2
        let ty = symbols.hint(&HomeKey::global("G")).unwrap_or(WasmType::I32);
159
2
        symbols.note_home("G", vec![Arm::NumberLiteral(WasmType::I32)], None, ty);
160
2
        symbols.note_store(&HomeKey::global("G"), Arm::Value(WasmType::Ratio));
161
2
        Ok(())
162
2
    })
163
1
    .expect("settles");
164
1
    assert_eq!(attempts, 2);
165
1
    assert_eq!(symbols.hint(&HomeKey::global("G")), None);
166
1
}
167

            
168
#[test]
169
1
fn a_constant_list_init_is_built_at_the_element_of_its_widened_home() {
170
1
    let ty = eval_type("(defvar acc (list 0)) (setf acc (cons 1/2 acc)) acc");
171
1
    assert_eq!(
172
1
        ty.expect("compiles"),
173
1
        Some(WasmType::PairRef(crate::ast::PairElement::AnyRef))
174
    );
175
1
}
176

            
177
#[test]
178
1
fn the_cap_counts_the_stored_globals_a_setf_created() {
179
1
    let mut symbols = SymbolTable::new();
180
1
    symbols.set_stored_globals(HashSet::from(["G".to_string()]));
181
1
    assert_eq!(symbols.unit_home_count(), 1);
182
1
    symbols.set_unit_specials(HashSet::from(["G".to_string()]), HashSet::new());
183
1
    assert_eq!(symbols.unit_home_count(), 1);
184
1
}
185

            
186
#[test]
187
1
fn a_definition_with_a_runtime_init_compiles_again_as_a_cell() {
188
1
    let program = Reader::parse("(defvar z (entity-count)) z").expect("parses");
189
1
    let mut symbols = SymbolTable::with_builtins();
190
1
    let mut cells = Vec::new();
191
2
    settle_homes(&mut symbols, |symbols| {
192
2
        crate::compiler::expr::prepare_unit(symbols, &program.exprs, CompileMode::Script)?;
193
2
        cells.push(symbols.forced_cells());
194
2
        match cells.len() {
195
1
            1 => symbols.ask_cell("Z", crate::runtime::Asked::Typed(WasmType::I32)),
196
1
            _ => assert_eq!(symbols.hint(&HomeKey::global("Z")), Some(WasmType::I32)),
197
        }
198
2
        Ok(())
199
2
    })
200
1
    .expect("settles");
201
1
    assert_eq!(cells.len(), 2);
202
1
    assert!(cells[1].contains("Z"));
203
1
}
204

            
205
2
fn attempts_for(source: &str) -> u64 {
206
2
    let program = Reader::parse(source).expect("parses");
207
2
    let mut compiler = Compiler::new();
208
2
    compiler
209
2
        .compile_eval_with_type(&program, &mut SymbolTable::with_builtins())
210
2
        .expect("settles");
211
2
    compiler.stats().unit_attempts
212
2
}
213

            
214
#[test]
215
1
fn every_definition_with_a_runtime_init_asks_in_one_attempt() {
216
41
    let risky = |i: usize| format!("(defvar v{i} (handler-case (error 'boom \"m\") (t (e) 2)))");
217
1
    let independent: Vec<String> = (0..40).map(risky).collect();
218
1
    let chained: Vec<String> = (1..40)
219
39
        .map(|i| format!("(defvar v{i} (+ v{} 1))", i - 1))
220
        .collect();
221
1
    assert_eq!(attempts_for(&format!("{} 0", independent.join(" "))), 2);
222
1
    assert_eq!(
223
1
        attempts_for(&format!("{} {} 0", risky(0), chained.join(" "))),
224
1
        2
225
    );
226
1
}
227

            
228
#[test]
229
1
fn a_runtime_defvar_is_typed_by_its_init() {
230
1
    let ty = eval_type("(defvar z (handler-case 1 (t (e) 2))) z");
231
1
    assert_eq!(ty.expect("compiles"), Some(WasmType::I32));
232
1
}
233

            
234
#[test]
235
1
fn the_unsettled_home_is_the_one_that_fails_its_check_in_the_last_attempt() {
236
1
    let mut symbols = SymbolTable::new();
237
7
    let result: Result<()> = settle_homes(&mut symbols, |symbols| {
238
7
        symbols.set_unit_specials(
239
7
            HashSet::from(["A".to_string(), "Z".to_string()]),
240
7
            HashSet::new(),
241
7
        );
242
7
        for name in ["A", "Z"] {
243
14
            let ty = symbols
244
14
                .hint(&HomeKey::global(name))
245
14
                .unwrap_or(WasmType::I32);
246
14
            symbols.note_home(name, vec![Arm::NumberLiteral(WasmType::I32)], None, ty);
247
        }
248
7
        symbols.note_store(&HomeKey::global("A"), Arm::NumberLiteral(WasmType::Ratio));
249
7
        let z = symbols.hint(&HomeKey::global("Z")).unwrap_or(WasmType::I32);
250
7
        let flip = if z == WasmType::I32 {
251
4
            WasmType::Ratio
252
        } else {
253
3
            WasmType::I32
254
        };
255
7
        symbols.note_store(&HomeKey::global("Z"), Arm::Value(flip));
256
7
        Ok(())
257
7
    });
258
1
    assert!(
259
1
        matches!(result, Err(Error::Resource(msg)) if msg == "the type of global Z did not settle")
260
    );
261
1
}