-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnative_type.rs
132 lines (114 loc) · 2.47 KB
/
native_type.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
use std::cell::RefCell;
use hebi::prelude::*;
fn main() {
struct Circle {
center: (f64, f64),
radius: f64,
}
impl Circle {
fn new(center: (f64, f64), radius: f64) -> Self {
Self { center, radius }
}
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius.powi(2)
}
fn unit() -> Circle {
Circle {
center: (0.0, 0.0),
radius: 1.0,
}
}
}
struct CircleClass(RefCell<Circle>);
let module = NativeModule::builder("shapes")
.class::<CircleClass>("Circle", |class| {
class
.init(|scope| {
let radius = scope.param::<f64>(0)?;
let center = (0.0, 0.0);
Ok(CircleClass(RefCell::new(Circle::new(center, radius))))
})
.field_mut(
"radius",
|_, this| this.0.borrow().radius,
|_, this, value| {
this.0.borrow_mut().radius = value;
Ok(())
},
)
.field_mut(
"x",
|_, this| this.0.borrow().center.0,
|_, this, value| {
this.0.borrow_mut().center.0 = value;
Ok(())
},
)
.field_mut(
"y",
|_, this| this.0.borrow().center.1,
|_, this, value| {
this.0.borrow_mut().center.1 = value;
Ok(())
},
)
.method("area", |_, this| this.0.borrow().area())
.static_method("unit", |scope| {
scope.new_instance(CircleClass(RefCell::new(Circle::unit())))
})
.finish()
})
.finish();
let mut hebi = Hebi::new();
hebi.register(&module);
hebi
.eval(
r#"
from shapes import Circle
c := Circle(20.0)
print(c.area()) # ~1256
print(3.14 * (c.radius ** 2)) # 1256
print(Circle.area(Circle.unit()))
print(c.x)
c.x = 10.0
print(c.x)
"#,
)
.unwrap();
}
/* fn example() {
struct Foo {
value: i32,
}
impl Foo {
fn bar(&mut self, f: impl Fn(&mut Self)) {
f(self)
}
}
let module = NativeModule::builder("test")
.class::<Foo>("Foo", |class| {
class.method_mut("bar", |mut scope, this: &mut Foo| {
let cb = scope.param(0)?;
this.value = 100;
scope.call(cb, &[]);
Ok(())
});
})
.finish();
let mut hebi = Hebi::new();
hebi.register(&module);
hebi
.eval(
r#"
from test import Foo
v := Foo()
fn baz():
fn test():
print "yo"
v.bar(test)
v.bar(baz)
# v.bar -> baz -> v.bar -> test
"#,
)
.unwrap();
} */