1
//! Tests that span multiple context submodules. Each test verifies a
2
//! property of the assembled `CompileContext` produced by `new()` —
3
//! type registrations, helper-function registrations, and concrete-vs-
4
//! abstract heap-type accessors.
5

            
6
use super::CompileContext;
7
use crate::ast::EntityKind;
8
use wasm_encoder::{Function, HeapType, Instruction, ValType};
9

            
10
#[test]
11
1
fn test_ratio_type_registered() {
12
1
    let ctx = CompileContext::new_with_host_fns(&[]).unwrap();
13
    // Type indices live in the typed `WasmIds` (poison `u32::MAX` means
14
    // unresolved); a real registered index is below the module's type count.
15
1
    assert!(ctx.ids.ty_ratio < ctx.type_count);
16
1
    assert!(ctx.ids.ty_i8_array < ctx.type_count);
17
1
}
18

            
19
#[test]
20
1
fn test_entity_types_registered() {
21
1
    let ctx = CompileContext::new_with_host_fns(&[]).unwrap();
22
1
    for kind in [
23
1
        EntityKind::Account,
24
1
        EntityKind::Commodity,
25
1
        EntityKind::Transaction,
26
1
        EntityKind::Split,
27
1
        EntityKind::Tag,
28
1
        EntityKind::Price,
29
1
        EntityKind::SshKey,
30
1
    ] {
31
7
        let name = kind.type_name();
32
        // Every entity kind resolves to a registered struct-type index via the
33
        // exhaustive `ids.entity_type` match.
34
7
        assert!(
35
7
            ctx.ids.entity_type(kind) < ctx.type_count,
36
            "missing entity wasm struct: ${name}"
37
        );
38
        // Accessor returns a `(ref null $<kind>)` resolving to that index —
39
        // regression check that `entity_ref` and `ids.entity_type` stay in sync.
40
7
        let ty = ctx.entity_ref(kind);
41
7
        match ty {
42
7
            ValType::Ref(r) => assert!(r.nullable),
43
            _ => panic!("entity_ref for {name} must produce Ref ValType"),
44
        }
45
    }
46
1
}
47

            
48
#[test]
49
1
fn test_pair_type_registered() {
50
1
    let ctx = CompileContext::new_with_host_fns(&[]).unwrap();
51
1
    assert!(
52
1
        ctx.ids.ty_pair < ctx.type_count,
53
        "missing $pair WasmGC type"
54
    );
55
1
    assert!(
56
1
        ctx.func_names.contains_key("pair_new"),
57
        "missing pair_new helper"
58
    );
59
1
}
60

            
61
#[test]
62
1
fn test_pair_ref_type_is_concrete_pair() {
63
1
    let ctx = CompileContext::new_with_host_fns(&[]).unwrap();
64
1
    let pair_ref = ctx.pair_ref();
65
1
    match pair_ref {
66
        ValType::Ref(r) => {
67
1
            assert!(r.nullable);
68
1
            assert_eq!(r.heap_type, HeapType::Concrete(ctx.ids.ty_pair));
69
        }
70
        _ => panic!("expected Ref type"),
71
    }
72
1
}
73

            
74
#[test]
75
1
fn test_anyref_is_abstract_any() {
76
1
    let ctx = CompileContext::new_with_host_fns(&[]).unwrap();
77
1
    match ctx.anyref() {
78
        ValType::Ref(r) => {
79
1
            assert!(r.nullable);
80
1
            assert_eq!(r.heap_type, HeapType::ANY);
81
        }
82
        _ => panic!("expected Ref type"),
83
    }
84
1
}
85

            
86
#[test]
87
1
fn test_ratio_helpers_registered() {
88
1
    let ctx = CompileContext::new_with_host_fns(&[]).unwrap();
89
1
    for name in [
90
1
        "gcd",
91
1
        "ratio_new",
92
1
        "ratio_add",
93
1
        "ratio_sub",
94
1
        "ratio_mul",
95
1
        "ratio_div",
96
1
        "ratio_eq",
97
1
        "ratio_lt",
98
1
        "ratio_from_i64",
99
1
    ] {
100
9
        assert!(
101
9
            ctx.func_names.contains_key(name),
102
            "missing helper function: {name}"
103
        );
104
    }
105
1
}
106

            
107
#[test]
108
1
fn test_host_imports_registered() {
109
1
    let ctx = CompileContext::new_with_host_fns(&[]).unwrap();
110
1
    for name in [
111
1
        "get_output_offset",
112
1
        "get_input_offset",
113
1
        "get_strings_offset",
114
1
        "get_input_entities_count",
115
1
        "get_timestamp",
116
1
        "generate_uuid",
117
1
        "write_string",
118
1
        "write_bytes",
119
1
        "symbol_resolve",
120
1
        "log",
121
1
        "log_value",
122
1
    ] {
123
11
        assert!(
124
11
            ctx.func_names.contains_key(name),
125
            "missing host import: {name}"
126
        );
127
    }
128
1
}
129

            
130
#[test]
131
1
fn test_ratio_ref_type() {
132
1
    let ctx = CompileContext::new_with_host_fns(&[]).unwrap();
133
1
    let ratio_ref = ctx.ratio_ref();
134
1
    match ratio_ref {
135
        ValType::Ref(r) => {
136
1
            assert!(r.nullable);
137
1
            assert_eq!(r.heap_type, HeapType::Concrete(ctx.ids.ty_ratio));
138
        }
139
        _ => panic!("expected Ref type"),
140
    }
141
1
}
142

            
143
/// Asserts every common `WasmIds` field resolved to a real index (not the
144
/// `u32::MAX` poison) in BOTH module modes. This is the regression that would
145
/// have caught the original `log`-missing-in-eval panic at construction time:
146
/// `log` is now declared in both modes, so `ids.log` is resolved in both.
147
2
fn assert_common_ids_resolved(ctx: &CompileContext) {
148
2
    let ids = &ctx.ids;
149
2
    for (label, idx) in [
150
2
        ("gcd", ids.gcd),
151
2
        ("ratio_new", ids.ratio_new),
152
2
        ("ratio_add", ids.ratio_add),
153
2
        ("ratio_sub", ids.ratio_sub),
154
2
        ("ratio_mul", ids.ratio_mul),
155
2
        ("ratio_div", ids.ratio_div),
156
2
        ("ratio_eq", ids.ratio_eq),
157
2
        ("ratio_lt", ids.ratio_lt),
158
2
        ("ratio_from_i64", ids.ratio_from_i64),
159
2
        ("ratio_to_i64", ids.ratio_to_i64),
160
2
        ("i64_mul_checked", ids.i64_mul_checked),
161
2
        ("i64_add_checked", ids.i64_add_checked),
162
2
        ("i64_sub_checked", ids.i64_sub_checked),
163
2
        ("unit_singleton", ids.unit_singleton),
164
2
        ("unit_mul", ids.unit_mul),
165
2
        ("unit_negate", ids.unit_negate),
166
2
        ("unit_eq", ids.unit_eq),
167
2
        ("materialize_unit", ids.materialize_unit),
168
2
        ("commodity_add", ids.commodity_add),
169
2
        ("commodity_sub", ids.commodity_sub),
170
2
        ("commodity_mul", ids.commodity_mul),
171
2
        ("commodity_div", ids.commodity_div),
172
2
        ("commodity_mul_by_ratio", ids.commodity_mul_by_ratio),
173
2
        ("commodity_div_by_ratio", ids.commodity_div_by_ratio),
174
2
        ("commodity_neg", ids.commodity_neg),
175
2
        ("commodity_eq", ids.commodity_eq),
176
2
        ("commodity_lt", ids.commodity_lt),
177
2
        ("commodity_assert_atomic", ids.commodity_assert_atomic),
178
2
        ("commodity_new_with_term", ids.commodity_new_with_term),
179
2
        ("pair_new", ids.pair_new),
180
2
        ("box_index", ids.box_index),
181
2
        ("index_div", ids.index_div),
182
2
        ("index_rem", ids.index_rem),
183
2
        ("index_add", ids.index_add),
184
2
        ("index_sub", ids.index_sub),
185
2
        ("index_mul", ids.index_mul),
186
2
        ("index_narrow", ids.index_narrow),
187
2
        ("box_bool", ids.box_bool),
188
2
        ("car_of_nil", ids.car_of_nil),
189
2
        ("not_a_list", ids.not_a_list),
190
2
        ("nil_string", ids.nil_string),
191
2
        ("nil_entity", ids.nil_entity),
192
2
        ("output_overflow", ids.output_overflow),
193
2
        ("string_eq", ids.string_eq),
194
2
        ("symbol_eq", ids.symbol_eq),
195
2
        ("symbol_designator", ids.symbol_designator),
196
2
        ("symbol_keyword_p", ids.symbol_keyword_p),
197
2
        ("not_a_symbol", ids.not_a_symbol),
198
2
        ("not_an_index", ids.not_an_index),
199
2
        ("not_a_scalar", ids.not_a_scalar),
200
2
        ("not_money", ids.not_money),
201
2
        ("not_a_string", ids.not_a_string),
202
2
        ("not_printable", ids.not_printable),
203
2
        ("not_a_function", ids.not_a_function),
204
2
        ("wrong_function_arguments", ids.wrong_function_arguments),
205
2
        ("symbol_not_callable", ids.symbol_not_callable),
206
2
        ("nomi_raise", ids.nomi_raise),
207
2
        ("log", ids.log),
208
2
        ("log_value", ids.log_value),
209
2
        ("ty_i8_array", ids.ty_i8_array),
210
2
        ("ty_ratio", ids.ty_ratio),
211
2
        ("ty_pair", ids.ty_pair),
212
2
        ("ty_symbol", ids.ty_symbol),
213
2
        ("ty_commodity", ids.ty_commodity),
214
2
        ("ty_unit_term", ids.ty_unit_term),
215
2
        ("ty_nomi_condition", ids.ty_nomi_condition),
216
2
        ("ty_t", ids.ty_t),
217
2
        ("global_t", ids.global_t),
218
2
        ("ty_slots", ids.ty_slots),
219
2
        ("ty_struct", ids.ty_struct),
220
2
        ("struct_new", ids.struct_new),
221
2
        ("struct_copy", ids.struct_copy),
222
2
    ] {
223
144
        assert_ne!(idx, u32::MAX, "WasmIds field {label} left unresolved");
224
    }
225
2
    for kind in [
226
2
        EntityKind::Account,
227
2
        EntityKind::Commodity,
228
2
        EntityKind::Transaction,
229
2
        EntityKind::Split,
230
2
        EntityKind::Tag,
231
2
        EntityKind::Price,
232
2
        EntityKind::SshKey,
233
2
        EntityKind::Condition,
234
2
    ] {
235
16
        assert_ne!(
236
16
            ids.entity_type(kind),
237
16
            u32::MAX,
238
            "entity_type({kind:?}) left unresolved"
239
        );
240
    }
241
2
}
242

            
243
#[test]
244
1
fn wasm_ids_fully_resolved_script_mode() {
245
1
    let ctx = CompileContext::new_with_host_fns(&[]).unwrap();
246
1
    assert_common_ids_resolved(&ctx);
247
    // Script-mode-only env imports resolve; eval-only catch_each does not.
248
1
    assert!(ctx.ids.get_output_offset().is_ok());
249
1
    assert!(ctx.ids.get_input_offset().is_ok());
250
1
    assert!(ctx.ids.get_input_entities_count().is_ok());
251
1
    assert!(ctx.ids.nomi_catch_each().is_err());
252
1
}
253

            
254
#[test]
255
1
fn wasm_ids_fully_resolved_eval_mode() {
256
1
    let ctx = CompileContext::new_eval_with_host_fns(&[]).unwrap();
257
1
    assert_common_ids_resolved(&ctx);
258
    // Eval-mode-only catch_each resolves; script-only env imports do not.
259
1
    assert!(ctx.ids.nomi_catch_each().is_ok());
260
1
    assert!(ctx.ids.get_output_offset().is_err());
261
1
    assert!(ctx.ids.get_input_offset().is_err());
262
1
    assert!(ctx.ids.get_input_entities_count().is_err());
263
1
}
264

            
265
#[test]
266
1
fn host_fn_named_log_is_rejected_not_silently_rebound() {
267
    // A user `HostFnSpec` whose import_name collides with the reserved `env.log`
268
    // (or any built-in) must error at construction, not silently overwrite the
269
    // resolved index and misroute PRINT/DISPLAY or emit invalid wasm.
270
1
    let spec = crate::host_fn::HostFnSpec::new("user-log", "env", "log");
271
1
    let msg = match CompileContext::new_eval_with_host_fns(&[spec]) {
272
        Ok(_) => panic!("reserved-name collision must be rejected"),
273
1
        Err(e) => e.to_string(),
274
    };
275
1
    assert!(msg.contains("already registered"), "got: {msg}");
276
1
    assert!(msg.contains("log"), "got: {msg}");
277
1
}
278

            
279
#[test]
280
1
fn test_valid_wasm_with_ratio_helpers() {
281
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).unwrap();
282
1
    ctx.add_should_apply(CompileContext::default_should_apply(), usize::MAX);
283
1
    let mut f = Function::new([]);
284
1
    f.instruction(&Instruction::End);
285
1
    ctx.add_process(f);
286
1
    let wasm = ctx.finish();
287
1
    assert_eq!(&wasm[0..4], b"\0asm");
288
1
}
289

            
290
#[test]
291
1
fn pair_equal_helper_is_registered_and_the_module_validates() {
292
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).unwrap();
293
1
    assert_ne!(ctx.ids.pair_equal, u32::MAX);
294
1
    ctx.add_should_apply(CompileContext::default_should_apply(), usize::MAX);
295
1
    let mut f = Function::new([]);
296
1
    f.instruction(&Instruction::End);
297
1
    ctx.add_process(f);
298
1
    let wasm = ctx.finish();
299
1
    assert!(wasmparser::validate(&wasm).is_ok());
300
1
}
301

            
302
#[test]
303
1
fn anyref_equal_helper_validates_and_is_callable_on_two_anyrefs() {
304
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).unwrap();
305
1
    ctx.add_should_apply(CompileContext::default_should_apply(), usize::MAX);
306
1
    let mut f = Function::new([]);
307
1
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Abstract {
308
1
        shared: false,
309
1
        ty: wasm_encoder::AbstractHeapType::Any,
310
1
    }));
311
1
    f.instruction(&Instruction::RefNull(wasm_encoder::HeapType::Abstract {
312
1
        shared: false,
313
1
        ty: wasm_encoder::AbstractHeapType::Any,
314
1
    }));
315
1
    f.instruction(&Instruction::I32Const(1));
316
1
    f.instruction(&Instruction::Call(ctx.ids.anyref_equal));
317
1
    f.instruction(&Instruction::Drop);
318
1
    f.instruction(&Instruction::End);
319
1
    ctx.add_process(f);
320
1
    assert!(wasmparser::validate(&ctx.finish()).is_ok());
321
1
}
322

            
323
#[test]
324
1
fn shape_compare_is_the_one_table_of_reference_shapes() {
325
    use crate::ast::{PairElement, WasmType};
326
1
    let ctx = CompileContext::new_with_host_fns(&[]).unwrap();
327
1
    assert_ne!(ctx.ids.anyref_equal, u32::MAX);
328
1
    let pair = WasmType::PairRef(PairElement::I32);
329
1
    let structural = ctx.shape_compare(pair, true).unwrap().unwrap();
330
1
    assert_eq!(
331
1
        (structural.shape, structural.call),
332
1
        (ctx.ids.ty_pair, Some(ctx.ids.pair_equal))
333
    );
334
1
    assert_eq!(ctx.shape_compare(pair, false).unwrap().unwrap().call, None);
335
1
    let string = ctx
336
1
        .shape_compare(WasmType::StringRef, false)
337
1
        .unwrap()
338
1
        .unwrap();
339
1
    assert_eq!(string.call, Some(ctx.ids.string_eq));
340
1
    assert!(ctx.shape_compare(WasmType::I32, true).unwrap().is_none());
341
1
    assert!(ctx.shape_compare(WasmType::AnyRef, true).unwrap().is_none());
342
1
}