Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/bin/toy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ fn main() -> Result<(), String> {
"iterative_fib(10) = {}",
run_iterative_fib_code(&mut jit, 10)?
);
println!("counting down from 5:");
run_countdown_code(&mut jit, 5)?;
run_hello(&mut jit)?;
Ok(())
}
Expand All @@ -25,6 +27,10 @@ fn run_recursive_fib_code(jit: &mut jit::JIT, input: isize) -> Result<isize, Str
unsafe { run_code(jit, RECURSIVE_FIB_CODE, input) }
}

fn run_countdown_code(jit: &mut jit::JIT, input: isize) -> Result<isize, String> {
unsafe { run_code(jit, COUNTDOWN_CODE, input) }
}

fn run_iterative_fib_code(jit: &mut jit::JIT, input: isize) -> Result<isize, String> {
unsafe { run_code(jit, ITERATIVE_FIB_CODE, input) }
}
Expand Down Expand Up @@ -89,6 +95,18 @@ const RECURSIVE_FIB_CODE: &str = r#"
}
"#;

/// Another example: calling our builtin print functon.
const COUNTDOWN_CODE: &str = r#"
fn countdown(n) -> (r) {
r = if n == 0 {
0
} else {
print(n)
countdown(n - 1)
}
}
"#;

/// Another example: Iterative fibonacci.
const ITERATIVE_FIB_CODE: &str = r#"
fn iterative_fib(n) -> (r) {
Expand Down
15 changes: 14 additions & 1 deletion src/jit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@ pub struct JIT {

impl Default for JIT {
fn default() -> Self {
let builder = JITBuilder::new(cranelift_module::default_libcall_names());
let mut builder = JITBuilder::new(cranelift_module::default_libcall_names());

// Register our print function with the JIT so that it can be
// called from code.
let print_addr = print_internal as *const u8;
builder.symbol("print", print_addr);

let module = JITModule::new(builder);
Self {
builder_context: FunctionBuilderContext::new(),
Expand Down Expand Up @@ -458,3 +464,10 @@ fn declare_variable(
}
var
}

// Prints a value used by the compiled code. Our JIT exposes this
// function to compiled code with the name "print".
extern "C" fn print_internal(value: isize) -> isize {
println!("{}", value);
0
}