Created
July 24, 2018 17:37
-
-
Save t184256/3d969d4bf862d124ed1948dea9042466 to your computer and use it in GitHub Desktop.
Getable woes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_use] | |
extern crate gluon_codegen; | |
extern crate gluon; | |
#[macro_use] | |
extern crate gluon_vm; | |
use gluon::vm::{self, ExternModule}; | |
use gluon::{import, Compiler, Thread}; | |
use gluon::{import::Import, RootedThread}; | |
pub fn new_vm() -> RootedThread { | |
if ::std::env::var("GLUON_PATH").is_err() { | |
::std::env::set_var("GLUON_PATH", ".."); | |
} | |
let vm = gluon::new_vm(); | |
let import = vm.get_macros().get("import"); | |
import | |
.as_ref() | |
.and_then(|import| import.downcast_ref::<Import>()) | |
.expect("Import macro") | |
.add_path(".."); | |
vm | |
} | |
extern crate serde; | |
#[macro_use] | |
extern crate serde_derive; | |
#[derive(Getable, Pushable, VmType, Debug, Serialize, Deserialize)] | |
#[gluon(vm_type = "types.Struct")] | |
struct Struct { | |
string: String, | |
int: i32, | |
tuple: (f64, f64), | |
} | |
fn load_struct_mod(vm: &Thread) -> vm::Result<ExternModule> { | |
let module = record! { | |
struct_to_str => primitive!(1 struct_to_str), | |
make_struct => primitive!(1 make_struct), | |
}; | |
ExternModule::new(vm, module) | |
} | |
fn struct_to_str(val: Struct) -> String { | |
format!("{:?}", val) | |
} | |
fn make_struct(s: String) -> Struct { | |
Struct {string: s, int: 5, tuple: (0.1, 0.2)} | |
} | |
fn main() { | |
let vm = new_vm(); | |
let mut compiler = Compiler::new(); | |
let src = gluon::vm::api::typ::make_source::<Struct>(&vm).unwrap(); | |
compiler.load_script(&vm, "types", &src).unwrap(); | |
import::add_extern_module(&vm, "functions", load_struct_mod); | |
let script = r#" | |
let { Struct } = import! types | |
let { struct_to_str, make_struct } = import! functions | |
let { assert } = import! std.test | |
assert (struct_to_str { string = "test", int = 55, tuple = (0.0, 1.0) } == "Struct { string: \"test\", int: 55, tuple: (0.0, 1.0) }") | |
make_struct "Hello" | |
"#; | |
if let Err(why) = compiler.run_expr::<Struct>(&vm, "test", script) { | |
panic!("{}", why); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment