add closure example that is passed to the host

This commit is contained in:
Folkert 2020-10-31 22:44:19 +01:00
parent 00445b3bc6
commit 95a69f5a9b
5 changed files with 89 additions and 0 deletions

View file

@ -0,0 +1,8 @@
app Closure provides [ closure ] imports []
closure : {} -> Int
closure =
x = 42
\{} -> x

23
examples/closure/platform/Cargo.lock generated Normal file
View file

@ -0,0 +1,23 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "host"
version = "0.1.0"
dependencies = [
"roc_std 0.1.0",
]
[[package]]
name = "libc"
version = "0.2.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "roc_std"
version = "0.1.0"
dependencies = [
"libc 0.2.79 (registry+https://github.com/rust-lang/crates.io-index)",
]
[metadata]
"checksum libc 0.2.79 (registry+https://github.com/rust-lang/crates.io-index)" = "2448f6066e80e3bfc792e9c98bf705b4b0fc6e8ef5b43e5889aff0eaa9c58743"

View file

@ -0,0 +1,13 @@
[package]
name = "host"
version = "0.1.0"
authors = ["Richard Feldman <oss@rtfeldman.com>"]
edition = "2018"
[lib]
crate-type = ["staticlib"]
[dependencies]
roc_std = { path = "../../../roc_std" }
[workspace]

View file

@ -0,0 +1,7 @@
#include <stdio.h>
extern int rust_main();
int main() {
return rust_main();
}

View file

@ -0,0 +1,38 @@
use std::mem::MaybeUninit;
use std::time::SystemTime;
extern "C" {
#[link_name = "closure_1_exposed"]
fn closure(output: *mut u8) -> ();
#[link_name = "closure_1_size"]
fn closure_size() -> i64;
}
#[no_mangle]
pub fn rust_main() -> isize {
println!("Running Roc closure");
let start_time = SystemTime::now();
let (function_pointer, closure_data) = unsafe {
let mut output: MaybeUninit<(fn(i64) -> i64, i64)> = MaybeUninit::uninit();
closure(output.as_mut_ptr() as _);
output.assume_init()
};
let answer = function_pointer(closure_data);
let end_time = SystemTime::now();
let duration = end_time.duration_since(start_time).unwrap();
println!(
"Roc closure took {:.4} ms to compute this answer: {:?}",
duration.as_secs_f64() * 1000.0,
// truncate the answer, so stdout is not swamped
answer
);
println!("closure size {:?}", unsafe { closure_size() });
// Exit code
0
}