1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
use wasm_gen;
use wasm_gen::{FuncCode, Imm};

use crate::{heap, Builtin, Symbol, PYTHON_STACK_POINTER};

// FIXME: check for stack overflow
// FIXME: create func that check_stack_overflow

pub fn generate_push() -> wasm_gen::Func {
    wasm_gen::Func {
        sig: wasm_gen::FuncType {
            params: vec![wasm_gen::I32], // symbol value
            results: vec![],
        },
        locals: vec![],
        code: vec![
            FuncCode::new1(wasm_gen::I32_CONST, Imm::I32(4)),
            FuncCode::new1(wasm_gen::CALL, Imm::I32(Builtin::PythonStackGrow as i32)),
            FuncCode::new1(wasm_gen::LOCAL_GET, Imm::I32(0)),
            FuncCode::new2(wasm_gen::I32_STORE, Imm::I64(0x0), Imm::I64(0x0)),
        ],
    }
}

pub fn push(symbol: Symbol) -> Vec<FuncCode> {
    match symbol {
        Symbol::FuncElem(_, _) => {
            panic!();
        }
        Symbol::Data(offset) => {
            let mut code = vec![];

            // tag the value
            code.append(&mut vec![
                FuncCode::new1(wasm_gen::I32_CONST, Imm::I32(offset as i32)),
                FuncCode::new1(wasm_gen::I32_CONST, Imm::I32(heap::TAG_DATA as i32)),
                FuncCode::new1(wasm_gen::CALL, Imm::I32(Builtin::BoxValue as i32)),
            ]);
            // push on the stack
            code.append(&mut vec![FuncCode::new1(
                wasm_gen::CALL,
                Imm::I32(Builtin::PythonStackPush as i32),
            )]);

            code
        }
        Symbol::HeapObject(offset) => vec![
            FuncCode::new1(wasm_gen::I32_CONST, Imm::I32(offset as i32)),
            FuncCode::new1(wasm_gen::CALL, Imm::I32(Builtin::PythonStackPush as i32)),
        ],
        Symbol::WasmTopOfStack => vec![FuncCode::new1(
            wasm_gen::CALL,
            Imm::I32(Builtin::PythonStackPush as i32),
        )],
        Symbol::Global(idx) => vec![
            FuncCode::new1(wasm_gen::GLOBAL_GET, Imm::I32(idx as i32)),
            FuncCode::new1(wasm_gen::CALL, Imm::I32(Builtin::PythonStackPush as i32)),
        ],
        Symbol::None => vec![
            FuncCode::new1(wasm_gen::I32_CONST, Imm::I32(33)),
            FuncCode::new1(wasm_gen::CALL, Imm::I32(Builtin::PythonStackPush as i32)),
        ],
        Symbol::Intrinsic(code) => code,
        Symbol::Int32(n) => vec![
            FuncCode::new1(wasm_gen::I32_CONST, Imm::I32(n)),
            FuncCode::new1(wasm_gen::CALL, Imm::I32(Builtin::PythonStackPush as i32)),
        ],
        e => unimplemented!("pushing symbol {:?}", e),
    }
}

/**
 * The stack grows.
 *   |----------------|----------->
 * start        ptr (old sp)    new sp
 */
pub fn generate_grow() -> wasm_gen::Func {
    let code = vec![
        // save for the next instruction to get the ptr
        FuncCode::new1(wasm_gen::GLOBAL_GET, Imm::I32(PYTHON_STACK_POINTER)),
        FuncCode::new1(wasm_gen::GLOBAL_GET, Imm::I32(PYTHON_STACK_POINTER)),
        FuncCode::new1(wasm_gen::LOCAL_GET, Imm::I32(0)),
        FuncCode::new0(wasm_gen::I32_ADD),
        FuncCode::new1(wasm_gen::GLOBAL_SET, Imm::I32(PYTHON_STACK_POINTER)),
    ];
    wasm_gen::Func {
        sig: wasm_gen::FuncType {
            params: vec![wasm_gen::I32],  // size in bytes
            results: vec![wasm_gen::I32], // ptr
        },
        locals: vec![],
        code,
    }
}

// Elements on the stack
pub fn generate_stack_size() -> wasm_gen::Func {
    let code = vec![
        FuncCode::new1(wasm_gen::GLOBAL_GET, Imm::I32(PYTHON_STACK_POINTER)),
        FuncCode::new1(wasm_gen::I32_CONST, Imm::I32(4)), // alignement
        FuncCode::new0(wasm_gen::I32_DIV_S),
    ];
    wasm_gen::Func {
        sig: wasm_gen::FuncType {
            params: vec![wasm_gen::I32],
            results: vec![wasm_gen::I32], // count
        },
        locals: vec![],
        code,
    }
}

/**
 *   |----------------|-----------<
 * start        new sp (old ptr)
 *
 * We return the old ptr that still points to the object, as long as nobody
 * allocated at the same time.
 */
pub fn generate_shrink() -> wasm_gen::Func {
    let code = vec![
        FuncCode::new1(wasm_gen::GLOBAL_GET, Imm::I32(PYTHON_STACK_POINTER)),
        FuncCode::new1(wasm_gen::LOCAL_GET, Imm::I32(0)),
        FuncCode::new0(wasm_gen::I32_SUB),
        FuncCode::new1(wasm_gen::LOCAL_TEE, Imm::I32(1)),
        // check if sp >= 0
        FuncCode::new1(wasm_gen::I32_CONST, Imm::I32(0)),
        FuncCode::new0(wasm_gen::I32_GE_S),
        FuncCode::new0(wasm_gen::I32_EQZ),
        FuncCode::new_control(wasm_gen::IF, wasm_gen::NONE),
        // {
        FuncCode::new1(
            wasm_gen::CALL,
            Imm::I32(Builtin::TrapPythonStackUnderflow as i32),
        ),
        // }
        FuncCode::new0(wasm_gen::END),
        // store
        FuncCode::new1(wasm_gen::LOCAL_GET, Imm::I32(1)),
        FuncCode::new1(wasm_gen::GLOBAL_SET, Imm::I32(PYTHON_STACK_POINTER)),
    ];

    wasm_gen::Func {
        sig: wasm_gen::FuncType {
            params: vec![wasm_gen::I32], // size in bytes
            results: vec![],
        },
        locals: vec![
            (1, wasm_gen::I32), // scratch to hold the sp
        ],
        code,
    }
}

pub fn generate_pop() -> wasm_gen::Func {
    let mut code = vec![];
    code.append(&mut vec![
        FuncCode::new1(wasm_gen::I32_CONST, Imm::I32(4)),
        FuncCode::new1(wasm_gen::CALL, Imm::I32(Builtin::PythonStackShrink as i32)),
        FuncCode::new1(wasm_gen::GLOBAL_GET, Imm::I32(PYTHON_STACK_POINTER)),
        FuncCode::new2(wasm_gen::I32_LOAD, Imm::I64(0x0), Imm::I64(0x0)),
    ]);

    wasm_gen::Func {
        sig: wasm_gen::FuncType {
            params: vec![],
            results: vec![wasm_gen::I32],
        },
        locals: vec![],
        code,
    }
}

// Peak at the last n'th element on the stack
pub fn generate_peak_last_n() -> wasm_gen::Func {
    wasm_gen::Func {
        sig: wasm_gen::FuncType {
            params: vec![wasm_gen::I32],  // n
            results: vec![wasm_gen::I32], // object
        },
        locals: vec![],
        code: vec![
            FuncCode::new1(wasm_gen::GLOBAL_GET, Imm::I32(PYTHON_STACK_POINTER)),
            FuncCode::new1(wasm_gen::I32_CONST, Imm::I32(4)), // alignement
            FuncCode::new1(wasm_gen::LOCAL_GET, Imm::I32(0)),
            FuncCode::new0(wasm_gen::I32_MUL),
            FuncCode::new0(wasm_gen::I32_SUB),
            FuncCode::new2(wasm_gen::I32_LOAD, Imm::I64(0x0), Imm::I64(0x0)),
        ],
    }
}

// A pop but without removing the stack element
pub fn generate_peak_last() -> wasm_gen::Func {
    wasm_gen::Func {
        sig: wasm_gen::FuncType {
            params: vec![],
            results: vec![wasm_gen::I32], // object
        },
        locals: vec![],
        code: vec![
            FuncCode::new1(wasm_gen::GLOBAL_GET, Imm::I32(PYTHON_STACK_POINTER)),
            FuncCode::new1(wasm_gen::I32_CONST, Imm::I32(4)), // alignement
            FuncCode::new0(wasm_gen::I32_SUB),
            FuncCode::new2(wasm_gen::I32_LOAD, Imm::I64(0x0), Imm::I64(0x0)),
        ],
    }
}

// For debugging purposes; dump Python's stack
pub fn dump() -> Vec<FuncCode> {
    vec![
        FuncCode::new1(wasm_gen::CALL, Imm::I64(0)), // lib.dump_python_stack
        FuncCode::new0(wasm_gen::UNREACHABLE),
    ]
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use wasmi::RuntimeValue;

    use super::*;
    use crate::{build_builtins, build_globals, build_imports, build_types, test_runner};
    use wasm_gen::WasmCodeGen;

    fn test_module() -> WasmCodeGen {
        let mut wasm_module = WasmCodeGen::new();
        wasm_module.add_table(wasm_gen::TableElemType::Funcref, 10, 10);
        let mem = wasm_module.add_memory(10, 64 * 100);
        wasm_module.add_export("mem".to_string(), mem, wasm_gen::ExportType::Mem);

        // reserve space for the Python stack at the start of the memory
        let mut end_of_data_offset = 8;

        build_types(&mut wasm_module);
        build_globals(&mut wasm_module);
        build_imports(
            &mut wasm_module,
            &mut end_of_data_offset,
            &mut HashMap::new(),
        );
        build_builtins(&mut wasm_module);

        wasm_module.add_export(
            "push_data".to_string(),
            Builtin::PythonStackPush as usize,
            wasm_gen::ExportType::Func,
        );
        wasm_module.add_export(
            "pop".to_string(),
            Builtin::PythonStackPop as usize,
            wasm_gen::ExportType::Func,
        );
        wasm_module.add_export(
            "size".to_string(),
            Builtin::PythonStackSize as usize,
            wasm_gen::ExportType::Func,
        );

        wasm_module
    }

    #[test]
    fn test_stack() {
        let instance = test_runner::instantiate(test_module());

        let v1 = RuntimeValue::I32(1);
        test_runner::call(&instance, "push_data", &[v1]);
        let v2 = RuntimeValue::I32(2);
        test_runner::call(&instance, "push_data", &[v2]);

        let r1 = test_runner::call(&instance, "pop", &[]);
        assert_eq!(r1.unwrap(), v2);
        let r2 = test_runner::call(&instance, "pop", &[]);
        assert_eq!(r2.unwrap(), v1);
    }

    #[test]
    fn test_stack_size() {
        let instance = test_runner::instantiate(test_module());

        let size0 = test_runner::call(&instance, "size", &[]);
        assert_eq!(size0.unwrap(), RuntimeValue::I32(0));

        test_runner::call(&instance, "push_data", &[RuntimeValue::I32(1)]);
        let size1 = test_runner::call(&instance, "size", &[]);
        assert_eq!(size1.unwrap(), RuntimeValue::I32(1));

        test_runner::call(&instance, "push_data", &[RuntimeValue::I32(2)]);
        let size2 = test_runner::call(&instance, "size", &[]);
        assert_eq!(size2.unwrap(), RuntimeValue::I32(2));
    }

    #[test]
    fn test_pop_stack_underflow() {
        let instance = test_runner::instantiate(test_module());

        test_runner::call(&instance, "push_data", &[RuntimeValue::I32(7)]);
        test_runner::call(&instance, "pop", &[]);
        let trap = test_runner::call_trap(&instance, "pop", &[]);

        match trap.kind() {
            wasmi::TrapKind::Unreachable => { /* ok */ }
            _ => panic!(),
        };
    }

    #[test]
    fn test_push_stack_overflow() {
        let instance = test_runner::instantiate(test_module());

        test_runner::call(&instance, "push_data", &[RuntimeValue::I32(7)]);
        test_runner::call(&instance, "push_data", &[RuntimeValue::I32(8)]);
        let trap = test_runner::call_trap(&instance, "push_data", &[RuntimeValue::I32(9)]);

        match trap.kind() {
            wasmi::TrapKind::Unreachable => { /* ok */ }
            _ => panic!(),
        };
    }
}