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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#![allow(clippy::wrong_self_convention)]
mod ctx;
mod emit;
mod error;
mod isolate;
mod op;
pub mod public;
mod stdlib;
pub mod util;
mod value;
use std::any;
use std::cell::{Ref, RefCell};
use std::fmt::{Debug, Display};
pub use error::Error;
use isolate::{Isolate, Stdout};
use public::{FunctionPtr, IntoStr, TypeInfo};
pub type Result<T, E = Error> = std::result::Result<T, E>;
use ctx::Context;
pub use derive::{class, function, methods};
pub use public::conv::{FromHebi, FromHebiRef, IntoHebi};
pub use public::{Args, Value};
pub use value::object::module::ModuleLoader;
use value::object::{NativeClass, NativeClassInstance, NativeFunction, UserData};
pub struct Hebi {
isolate: RefCell<Isolate>,
}
unsafe impl Send for Hebi {}
impl Hebi {
pub fn new() -> Self {
Self::default()
}
pub fn check(&self, src: &str) -> Result<(), Vec<syntax::Error>> {
syntax::parse(src)?;
Ok(())
}
pub fn eval<'a, T: FromHebi<'a>>(&'a self, src: &str) -> Result<T> {
let ctx = self.isolate.borrow().ctx();
let module = syntax::parse(src)?;
let module = emit::emit(ctx.clone(), "code", &module, true).unwrap();
let module = module.instance(&ctx, None);
let result = self.isolate.borrow_mut().run(module.root())?;
let result = Value::bind(result);
let ctx = self.ctx();
T::from_hebi(&ctx, result)
}
pub fn io<T: 'static>(&self) -> Option<Ref<'_, T>> {
match Ref::filter_map(self.isolate.borrow(), |isolate| {
isolate.io().as_any().downcast_ref()
}) {
Ok(v) => Some(v),
_ => None,
}
}
pub fn globals(&self) -> Globals {
Globals { hebi: self }
}
pub(crate) fn ctx(&self) -> public::Context {
public::Context::bind(self.isolate.borrow().ctx())
}
}
impl Hebi {
pub fn wrap<T: TypeInfo + 'static>(&self, v: T) -> Value<'_> {
self.try_wrap(v).unwrap()
}
pub fn try_wrap<T: TypeInfo + 'static>(&self, v: T) -> Result<Value<'_>> {
let Some(class) = self.isolate.borrow().class_map.get(&any::TypeId::of::<T>()).cloned() else {
return Err(Error::runtime(format!(
"`{}` has not been registered in this Hebi instance yet, use `Hebi::globals()` to register it",
any::type_name::<T>()
)));
};
let ctx = self.ctx();
Ok(Value::bind(NativeClassInstance::new(
ctx.inner(),
class,
UserData::new(ctx.inner(), v),
)))
}
}
pub struct Globals<'a> {
hebi: &'a Hebi,
}
impl<'a> Globals<'a> {
pub fn get(&self, name: &str) -> Option<Value<'a>> {
self.hebi.isolate.borrow().get_global(name).map(Value::bind)
}
pub fn set(&mut self, name: impl IntoStr<'a>, value: Value<'a>) {
let ctx = self.hebi.ctx();
let name = name.into_str(&ctx);
self
.hebi
.isolate
.borrow_mut()
.set_global(name.unbind(), value.unbind());
}
pub fn register_fn(&mut self, name: impl IntoStr<'a>, f: FunctionPtr) {
let ctx = self.hebi.ctx();
let name = name.into_str(&ctx);
self.set(
name.clone(),
Value::bind(NativeFunction::new(ctx.inner(), name.unbind(), f)),
)
}
pub fn register_class<T: TypeInfo + 'static>(&mut self) {
let ctx = self.hebi.ctx();
let class = NativeClass::new::<T>(ctx.inner());
self
.hebi
.isolate
.borrow_mut()
.class_map
.insert(any::TypeId::of::<T>(), class.clone());
self.set(class.name(), Value::bind(class))
}
}
pub struct HebiBuilder {
stdout: Option<Box<dyn Stdout>>,
module_loader: Option<Box<dyn ModuleLoader>>,
use_std: bool,
}
impl Hebi {
pub fn builder() -> HebiBuilder {
HebiBuilder {
stdout: None,
module_loader: None,
use_std: false,
}
}
}
impl HebiBuilder {
pub fn with_io<T: Stdout + 'static>(mut self, stdout: T) -> Self {
let _ = self.stdout.replace(Box::new(stdout));
self
}
pub fn with_module_loader<T: ModuleLoader + 'static>(mut self, loader: T) -> Self {
let _ = self.module_loader.replace(Box::new(loader));
self
}
pub fn with_std(mut self) -> Self {
self.use_std = true;
self
}
pub fn build(mut self) -> Hebi {
let ctx = Context::new();
let stdout = self
.stdout
.take()
.unwrap_or_else(|| Box::new(std::io::stdout()));
let module_loader = self
.module_loader
.take()
.unwrap_or_else(|| Box::new(NoopModuleLoader));
let isolate = Isolate::new(ctx, stdout, module_loader);
let vm = Hebi {
isolate: RefCell::new(isolate),
};
if self.use_std {
stdlib::register(&vm);
}
vm
}
}
impl Default for Hebi {
fn default() -> Self {
Self::builder().with_std().build()
}
}
pub struct NoopModuleLoader;
#[derive(Debug)]
pub struct ModuleLoadError {
pub path: String,
}
impl Display for ModuleLoadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "could not load module `{}`", self.path)
}
}
impl std::error::Error for ModuleLoadError {}
impl ModuleLoader for NoopModuleLoader {
fn load(
&mut self,
path: &[String],
) -> std::result::Result<&str, Box<dyn std::error::Error + 'static>> {
Err(Box::new(ModuleLoadError {
path: format!("could not load module `{}`", path.join(".")),
}))
}
}
#[cfg(test)]
mod tests;