Skip to content

Commit ec0effd

Browse files
committedMay 30, 2021
bytecodealliancegh-59 Add example of calling rust code from JIT
1 parent aee927d commit ec0effd

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed
 

‎src/bin/toy.rs

+18
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ fn main() -> Result<(), String> {
1313
"iterative_fib(10) = {}",
1414
run_iterative_fib_code(&mut jit, 10)?
1515
);
16+
println!("counting down from 5:");
17+
run_countdown_code(&mut jit, 5)?;
1618
run_hello(&mut jit)?;
1719
Ok(())
1820
}
@@ -25,6 +27,10 @@ fn run_recursive_fib_code(jit: &mut jit::JIT, input: isize) -> Result<isize, Str
2527
unsafe { run_code(jit, RECURSIVE_FIB_CODE, input) }
2628
}
2729

30+
fn run_countdown_code(jit: &mut jit::JIT, input: isize) -> Result<isize, String> {
31+
unsafe { run_code(jit, COUNTDOWN_CODE, input) }
32+
}
33+
2834
fn run_iterative_fib_code(jit: &mut jit::JIT, input: isize) -> Result<isize, String> {
2935
unsafe { run_code(jit, ITERATIVE_FIB_CODE, input) }
3036
}
@@ -89,6 +95,18 @@ const RECURSIVE_FIB_CODE: &str = r#"
8995
}
9096
"#;
9197

98+
/// Another example: calling our builtin print functon.
99+
const COUNTDOWN_CODE: &str = r#"
100+
fn countdown(n) -> (r) {
101+
r = if n == 0 {
102+
0
103+
} else {
104+
print(n)
105+
countdown(n - 1)
106+
}
107+
}
108+
"#;
109+
92110
/// Another example: Iterative fibonacci.
93111
const ITERATIVE_FIB_CODE: &str = r#"
94112
fn iterative_fib(n) -> (r) {

‎src/jit.rs

+14-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,13 @@ pub struct JIT {
2626

2727
impl Default for JIT {
2828
fn default() -> Self {
29-
let builder = JITBuilder::new(cranelift_module::default_libcall_names());
29+
let mut builder = JITBuilder::new(cranelift_module::default_libcall_names());
30+
31+
// Register our print function with the JIT so that it can be
32+
// called from code.
33+
let print_addr = print_internal as *const u8;
34+
builder.symbol("print", print_addr);
35+
3036
let module = JITModule::new(builder);
3137
Self {
3238
builder_context: FunctionBuilderContext::new(),
@@ -458,3 +464,10 @@ fn declare_variable(
458464
}
459465
var
460466
}
467+
468+
// Prints a value used by the compiled code. Our JIT exposes this
469+
// function to compiled code with the name "print".
470+
fn print_internal(value: isize) -> isize {
471+
println!("{}", value);
472+
0
473+
}

0 commit comments

Comments
 (0)
Please sign in to comment.