1
use wasm_encoder::{Encode, Instruction};
2

            
3
use super::{store_begin_place, store_end_place};
4
use crate::ast::{Place, WasmType};
5
use crate::compiler::context::CompileContext;
6
use crate::compiler::emit::FunctionEmitter;
7

            
8
5
fn encoded(instructions: &[Instruction<'_>]) -> Vec<u8> {
9
5
    let mut bytes = Vec::new();
10
5
    for instruction in instructions {
11
12
        instruction.encode(&mut bytes);
12
    }
13
5
    bytes
14
5
}
15

            
16
5
fn store(ctx: &CompileContext, place: Place, keep: bool) -> Vec<u8> {
17
5
    let mut emit = FunctionEmitter::new();
18
5
    store_begin_place(ctx, &mut emit, place);
19
5
    emit.i32_const(5);
20
5
    store_end_place(ctx, &mut emit, place, keep);
21
5
    emit.bytes_ref().to_vec()
22
5
}
23

            
24
#[test]
25
1
fn a_global_store_needs_nothing_below_the_value() {
26
1
    let ctx = CompileContext::new_with_host_fns(&[]).unwrap();
27
1
    assert_eq!(
28
1
        store(&ctx, Place::Global(3), false),
29
1
        encoded(&[Instruction::I32Const(5), Instruction::GlobalSet(3)])
30
    );
31
1
}
32

            
33
#[test]
34
1
fn a_kept_global_store_rereads_the_global() {
35
1
    let ctx = CompileContext::new_with_host_fns(&[]).unwrap();
36
1
    assert_eq!(
37
1
        store(&ctx, Place::Global(3), true),
38
1
        encoded(&[
39
1
            Instruction::I32Const(5),
40
1
            Instruction::GlobalSet(3),
41
1
            Instruction::GlobalGet(3),
42
1
        ])
43
    );
44
1
}
45

            
46
#[test]
47
1
fn a_plain_local_store_is_local_set_or_tee() {
48
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).unwrap();
49
1
    let idx = ctx.alloc_local(WasmType::I32).unwrap();
50
1
    assert_eq!(
51
1
        store(&ctx, Place::Local(idx), false),
52
1
        encoded(&[Instruction::I32Const(5), Instruction::LocalSet(idx)])
53
    );
54
1
    assert_eq!(
55
1
        store(&ctx, Place::Local(idx), true),
56
1
        encoded(&[Instruction::I32Const(5), Instruction::LocalTee(idx)])
57
    );
58
1
}
59

            
60
#[test]
61
1
fn a_celled_local_store_pushes_the_cell_first() {
62
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).unwrap();
63
1
    let idx = ctx.alloc_cell_local(WasmType::I32).unwrap();
64
1
    let cell = ctx.cell_of(idx).unwrap();
65
1
    assert_eq!(
66
1
        store(&ctx, Place::Local(idx), false),
67
1
        encoded(&[
68
1
            Instruction::LocalGet(idx),
69
1
            Instruction::I32Const(5),
70
1
            Instruction::StructSet {
71
1
                struct_type_index: cell,
72
1
                field_index: 0
73
1
            },
74
1
        ])
75
    );
76
1
}