1
use wasm_encoder::{Function, Instruction};
2
use wasmparser::{Parser, Payload};
3

            
4
use super::{CompileContext, global_export_name};
5
use crate::ast::{EntityKind, PairElement, StructId, WasmType};
6

            
7
1
fn runtime_types(ctx: &mut CompileContext) -> Vec<WasmType> {
8
1
    let closure = ctx
9
1
        .intern_closure_signature(&[WasmType::Ratio], WasmType::Ratio)
10
1
        .unwrap();
11
1
    vec![
12
1
        WasmType::I32,
13
1
        WasmType::Bool,
14
1
        WasmType::Ratio,
15
1
        WasmType::Commodity,
16
1
        WasmType::StringRef,
17
1
        WasmType::PairRef(PairElement::I32),
18
1
        WasmType::EntityRef(EntityKind::Condition),
19
1
        WasmType::StructRef(StructId(0)),
20
1
        WasmType::Closure(closure),
21
1
        WasmType::AnyRef,
22
    ]
23
1
}
24

            
25
2
fn validated_module(mut ctx: CompileContext) -> Vec<u8> {
26
2
    ctx.add_should_apply(CompileContext::default_should_apply(), usize::MAX);
27
2
    let mut process = Function::new([]);
28
2
    process.instruction(&Instruction::End);
29
2
    ctx.add_process(process);
30
2
    let bytes = ctx.finish();
31
2
    wasmparser::validate(&bytes).expect("module with runtime globals must validate");
32
2
    bytes
33
2
}
34

            
35
2
fn mutable_globals(bytes: &[u8]) -> Vec<bool> {
36
2
    Parser::new(0)
37
2
        .parse_all(bytes)
38
2
        .filter_map(Result::ok)
39
170
        .filter_map(|payload| match payload {
40
2
            Payload::GlobalSection(reader) => Some(reader),
41
168
            _ => None,
42
170
        })
43
2
        .flat_map(|reader| reader.into_iter().filter_map(Result::ok))
44
15
        .map(|global| global.ty.mutable)
45
        .collect()
46
2
}
47

            
48
1
fn exported_globals(bytes: &[u8]) -> Vec<(String, u32)> {
49
1
    Parser::new(0)
50
1
        .parse_all(bytes)
51
1
        .filter_map(Result::ok)
52
85
        .filter_map(|payload| match payload {
53
1
            Payload::ExportSection(reader) => Some(reader),
54
84
            _ => None,
55
85
        })
56
1
        .flat_map(|reader| reader.into_iter().filter_map(Result::ok))
57
35
        .filter(|export| export.kind == wasmparser::ExternalKind::Global)
58
12
        .map(|export| (export.name.to_string(), export.index))
59
        .collect()
60
1
}
61

            
62
#[test]
63
1
fn the_export_name_of_a_global_is_its_index() {
64
1
    assert_eq!(global_export_name(7), "g7");
65
1
}
66

            
67
#[test]
68
1
fn a_runtime_global_of_every_type_is_a_valid_exported_mutable_global() {
69
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).unwrap();
70
1
    let first = ctx.alloc_mutable_global(WasmType::I32).unwrap();
71
1
    let types = runtime_types(&mut ctx);
72
1
    for (offset, ty) in types.iter().enumerate() {
73
10
        let idx = ctx.alloc_mutable_global(*ty).unwrap();
74
10
        assert_eq!(idx, first + 1 + u32::try_from(offset).unwrap());
75
    }
76
1
    let bytes = validated_module(ctx);
77
1
    let mutability = mutable_globals(&bytes);
78
1
    assert_eq!(mutability.len(), types.len() + 2);
79
1
    assert!(!mutability[0], "the exported $t singleton stays immutable");
80
11
    assert!(mutability[1..].iter().all(|mutable| *mutable));
81
1
    let exported = exported_globals(&bytes);
82
1
    for idx in first..=first + u32::try_from(types.len()).unwrap() {
83
11
        assert!(exported.contains(&(global_export_name(idx), idx)));
84
    }
85
1
}
86

            
87
#[test]
88
1
fn a_global_allocated_in_a_rolled_back_trial_keeps_the_index_space_monotonic() {
89
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).unwrap();
90
1
    let snap = ctx.snapshot();
91
1
    let doomed = ctx.alloc_mutable_global(WasmType::Ratio).unwrap();
92
1
    ctx.restore(snap);
93
1
    let retry = ctx.alloc_mutable_global(WasmType::Ratio).unwrap();
94
1
    assert_eq!(retry, doomed + 1);
95
1
    let bytes = validated_module(ctx);
96
1
    assert_eq!(mutable_globals(&bytes).len(), 3);
97
1
}