Skip to content

Commit

Permalink
fix: fix branching and count-vowels
Browse files Browse the repository at this point in the history
  • Loading branch information
bhelx committed Oct 16, 2023
1 parent 4ee851f commit 7c6d4fa
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -161,12 +161,12 @@ void eval(List<Instruction> code) throws ChicoryException {
}
case END:
{
frame.blockDepth--;
// if this is the last end, then we're done with
// the function
if (frame.blockDepth == 0) {
break loop;
}
frame.blockDepth--;
break;
}
case LOCAL_GET:
Expand Down
24 changes: 13 additions & 11 deletions runtime/src/test/java/com/dylibso/chicory/runtime/ModuleTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -163,17 +163,19 @@ public void shouldSupportGlobals() {
assertEquals(42, result.asInt());
}

// @Test
// public void shouldCountVowels() {
// var instance =
// Module.build("src/test/resources/wasm/count_vowels.rs.wasm").instantiate();
// var countVowels = instance.getExport("count_vowels");
//// var memory = instance.getMemory();
//// memory.put(0, "Hello World!");
//// var result = countVowels.apply(Value.i32(0));
// var result = countVowels.apply();
// assertEquals(3, result.asInt());
// }
@Test
public void shouldCountVowels() {
var instance = Module.build("src/test/resources/wasm/count_vowels.rs.wasm").instantiate();
var alloc = instance.getExport("alloc");
var countVowels = instance.getExport("count_vowels");
var memory = instance.getMemory();
var message = "Hello, World!";
var len = message.getBytes().length;
var ptr = alloc.apply(Value.i32(len)).asInt();
memory.put(ptr, message);
var result = countVowels.apply(Value.i32(ptr), Value.i32(len));
assertEquals(3, result.asInt());
}

@Test
public void shouldRunBasicCProgram() {
Expand Down
23 changes: 21 additions & 2 deletions runtime/src/test/resources/wasm/count_vowels.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,27 @@
const VOWELS: &[char] = &['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'];

use std::mem;
use std::slice;
use std::str;

#[no_mangle]
pub extern "C" fn alloc(len: i32) -> *const u8 {
let mut buf = Vec::with_capacity(len as usize);
let ptr = buf.as_mut_ptr();
// tell Rust not to clean this up
mem::forget(buf);
ptr
}

#[no_mangle]
pub unsafe extern "C" fn dealloc(ptr: &mut u8) {
let _ = Vec::from_raw_parts(ptr, 0, 1024);
}

#[no_mangle]
pub extern fn count_vowels() -> i32 {
let s = String::from("Hello World!");
pub extern fn count_vowels(ptr: i32, len: i32) -> i32 {
let bytes = unsafe { slice::from_raw_parts(ptr as *const u8, len as usize) };
let s = str::from_utf8(bytes).unwrap();
let mut count: i32 = 0;
for ch in s.chars() {
if VOWELS.contains(&ch) {
Expand Down
Binary file modified runtime/src/test/resources/wasm/count_vowels.rs.wasm
Binary file not shown.

0 comments on commit 7c6d4fa

Please sign in to comment.