-
Notifications
You must be signed in to change notification settings - Fork 285
/
lib.rs
352 lines (300 loc) · 12.4 KB
/
lib.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
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
//! The `neon` crate provides the entire [Neon](https://www.neon-bindings.com/) API.
extern crate neon_runtime;
extern crate cslice;
extern crate semver;
#[cfg(test)]
extern crate rustc_version;
#[cfg(test)]
#[macro_use]
extern crate lazy_static;
pub mod mem;
pub mod vm;
pub mod scope;
pub mod js;
pub mod task;
pub mod meta;
#[doc(hidden)]
pub mod macro_internal;
/// Register the current crate as a Node module, providing startup
/// logic for initializing the module object at runtime.
///
/// Example:
///
/// ```rust,ignore
/// register_module!(m, {
/// m.export("foo", foo)?;
/// m.export("bar", bar)?;
/// m.export("baz", baz)?;
/// Ok(())
/// });
/// ```
#[macro_export]
macro_rules! register_module {
($module:ident, $init:block) => {
// Mark this function as a global constructor (like C++).
#[allow(improper_ctypes)]
#[cfg_attr(target_os = "linux", link_section = ".ctors")]
#[cfg_attr(target_os = "macos", link_section = "__DATA,__mod_init_func")]
#[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")]
pub static __LOAD_NEON_MODULE: extern "C" fn() = {
fn __init_neon_module(mut $module: $crate::vm::Module) -> $crate::vm::VmResult<()> $init
extern "C" fn __load_neon_module() {
// Put everything else in the ctor fn so the user fn can't see it.
#[repr(C)]
struct __NodeModule {
version: i32,
flags: u32,
dso_handle: *mut u8,
filename: *const u8,
register_func: Option<extern "C" fn(
$crate::mem::Handle<$crate::js::JsObject>, *mut u8, *mut u8)>,
context_register_func: Option<extern "C" fn(
$crate::mem::Handle<$crate::js::JsObject>, *mut u8, *mut u8, *mut u8)>,
modname: *const u8,
priv_data: *mut u8,
link: *mut __NodeModule
}
static mut __NODE_MODULE: __NodeModule = __NodeModule {
version: 0,
flags: 0,
dso_handle: 0 as *mut _,
filename: b"neon_source.rs\0" as *const u8,
register_func: Some(__register_neon_module),
context_register_func: None,
modname: b"neon_module\0" as *const u8,
priv_data: 0 as *mut _,
link: 0 as *mut _
};
extern "C" fn __register_neon_module(
m: $crate::mem::Handle<$crate::js::JsObject>, _: *mut u8, _: *mut u8) {
$crate::vm::Module::initialize(m, __init_neon_module);
}
extern "C" {
fn node_module_register(module: *mut __NodeModule);
}
// Suppress the default Rust panic hook, which prints diagnostics to stderr.
::std::panic::set_hook(::std::boxed::Box::new(|_| { }));
unsafe {
// Set the ABI version based on the NODE_MODULE_VERSION constant provided by the current node headers.
__NODE_MODULE.version = $crate::macro_internal::runtime::module::get_version();
node_module_register(&mut __NODE_MODULE);
}
}
__load_neon_module
};
}
}
#[doc(hidden)]
#[macro_export]
macro_rules! class_definition {
( $cls:ident ; $cname:ident ; $typ:ty ; $allocator:tt ; $call_ctor:tt ; $new_ctor:tt ; $mnames:tt ; $mdefs:tt ; init($call:pat) $body:block $($rest:tt)* ) => {
class_definition!($cls ;
$cname ;
$typ ;
{
fn _______allocator_rust_y_u_no_hygienic_items_______($call: $crate::vm::FunctionCall<$crate::js::JsUndefined>) -> $crate::vm::VmResult<$typ> {
$body
}
$crate::macro_internal::AllocateKernel::new(_______allocator_rust_y_u_no_hygienic_items_______)
} ;
$call_ctor ;
$new_ctor ;
$mnames ;
$mdefs ;
$($rest)*);
};
( $cls:ident ; $cname:ident ; $typ:ty ; $allocator:tt ; $call_ctor:tt ; $new_ctor:tt ; ($($mname:tt)*) ; ($($mdef:tt)*) ; method $name:ident($call:pat) $body:block $($rest:tt)* ) => {
class_definition!($cls ;
$cname ;
$typ ;
$allocator ;
$call_ctor ;
$new_ctor ;
($($mname)* $name) ;
($($mdef)* {
fn _______method_rust_y_u_no_hygienic_items_______($call: $crate::vm::FunctionCall<$cls>) -> $crate::vm::JsResult<$crate::js::JsValue> {
$body
}
$crate::macro_internal::MethodKernel::new(_______method_rust_y_u_no_hygienic_items_______)
}) ;
$($rest)*);
};
( $cls:ident ; $cname:ident ; $typ:ty ; $allocator:tt ; $call_ctor:tt ; $new_ctor:tt ; $mnames:tt ; $mdefs:tt ; constructor($call:pat) $body:block $($rest:tt)* ) => {
class_definition!($cls ;
$cname ;
$typ ;
$allocator ;
$call_ctor ;
({
fn _______constructor_rust_y_u_no_hygienic_items_______($call: $crate::vm::FunctionCall<$cls>) -> $crate::vm::VmResult<Option<$crate::mem::Handle<$crate::js::JsObject>>> {
$body
}
$crate::macro_internal::ConstructKernel::new(_______constructor_rust_y_u_no_hygienic_items_______)
}) ;
$mnames ;
$mdefs ;
$($rest)*);
};
( $cls:ident ; $cname:ident ; $typ:ty ; $allocator:tt ; $call_ctor:tt ; $new_ctor:tt ; $mnames:tt ; $mdefs:tt ; call($call:pat) $body:block $($rest:tt)* ) => {
class_definition!($cls ;
$cname ;
$typ ;
$allocator ;
({
fn _______call_rust_y_u_no_hygienic_items_______($call: $crate::vm::FunctionCall<$crate::js::JsValue>) -> $crate::vm::JsResult<$crate::js::JsValue> {
$body
}
$crate::macro_internal::ConstructorCallKernel::new(_______call_rust_y_u_no_hygienic_items_______)
}) ;
$new_ctor ;
$mnames ;
$mdefs ;
$($rest)*);
};
( $cls:ident ; $cname:ident ; $typ:ty ; $allocator:block ; ($($call_ctor:block)*) ; ($($new_ctor:block)*) ; ($($mname:ident)*) ; ($($mdef:block)*) ; $($rest:tt)* ) => {
impl $crate::js::class::Class for $cls {
type Internals = $typ;
fn setup<'a, T: $crate::scope::Scope<'a>>(_: &mut T) -> $crate::vm::VmResult<$crate::js::class::ClassDescriptor<'a, Self>> {
::std::result::Result::Ok(Self::describe(stringify!($cname), $allocator)
$(.construct($new_ctor))*
$(.call($call_ctor))*
$(.method(stringify!($mname), $mdef))*)
}
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! impl_managed {
($cls:ident) => {
impl $crate::mem::Managed for $cls {
fn to_raw(self) -> $crate::macro_internal::runtime::raw::Local {
let $cls(raw) = self;
raw
}
fn from_raw(raw: $crate::macro_internal::runtime::raw::Local) -> Self {
$cls(raw)
}
}
}
}
/// Declare custom native JavaScript types with Rust implementations.
///
/// Example:
///
/// ```rust,ignore
/// pub struct Greeter {
/// greeting: String
/// }
///
/// declare_types! {
///
/// /// A class for generating greeting strings.
/// pub class JsGreeter for Greeter {
/// init(call) {
/// let scope = call.scope;
/// let greeting = call.arguments.require(scope, 0)?.to_string(scope)?.value();
/// Ok(Greeter {
/// greeting: greeting
/// })
/// }
///
/// method hello(call) {
/// let scope = call.scope;
/// let name = call.arguments.require(scope, 0)?.to_string(scope)?.value();
/// let msg = vm::lock(call.arguments.this(scope), |greeter| {
/// format!("{}, {}!", greeter.greeting, name)
/// });
/// Ok(JsString::new_or_throw(scope, &msg[..])?.upcast())
/// }
/// }
///
/// }
/// ```
#[macro_export]
macro_rules! declare_types {
{ $(#[$attr:meta])* pub class $cls:ident for $typ:ident { $($body:tt)* } $($rest:tt)* } => {
declare_types! { $(#[$attr])* pub class $cls as $typ for $typ { $($body)* } $($rest)* }
};
{ $(#[$attr:meta])* class $cls:ident for $typ:ident { $($body:tt)* } $($rest:tt)* } => {
declare_types! { $(#[$attr])* class $cls as $typ for $typ { $($body)* } $($rest)* }
};
{ $(#[$attr:meta])* pub class $cls:ident as $cname:ident for $typ:ty { $($body:tt)* } $($rest:tt)* } => {
#[derive(Copy, Clone)]
#[repr(C)]
$(#[$attr])*
pub struct $cls($crate::macro_internal::runtime::raw::Local);
impl_managed!($cls);
class_definition!($cls ; $cname ; $typ ; () ; () ; () ; () ; () ; $($body)*);
declare_types! { $($rest)* }
};
{ $(#[$attr:meta])* class $cls:ident as $cname:ident for $typ:ty { $($body:tt)* } $($rest:tt)* } => {
#[derive(Copy, Clone)]
#[repr(C)]
$(#[$attr])*
struct $cls($crate::macro_internal::runtime::raw::Local);
impl_managed!($cls);
class_definition!($cls ; $cname ; $typ ; () ; () ; () ; () ; () ; $($body)*);
declare_types! { $($rest)* }
};
{ } => { };
}
#[cfg(all(windows, not(neon_profile = "release")))]
compile_error!("Neon only builds with --release. For tests, try `cargo test --release`.");
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;
use rustc_version::{version_meta, Channel};
// Create a mutex to enforce sequential running of the tests.
lazy_static! {
static ref TEST_MUTEX: Mutex<()> = Mutex::new(());
}
fn project_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf()
}
fn run(cmd: &str, dir: &Path) {
let (shell, command_flag) = if cfg!(windows) {
("cmd", "/C")
} else {
("sh", "-c")
};
assert!(Command::new(&shell)
.current_dir(dir)
.args(&[&command_flag, cmd])
.status()
.expect("failed to execute test command")
.success());
}
#[test]
fn cli_test() {
let _guard = TEST_MUTEX.lock();
let cli = project_root().join("cli");
run("npm install", &cli);
run("npm run transpile", &cli);
let test_cli = project_root().join("test").join("cli");
run("npm install", &test_cli);
run("npm run transpile", &test_cli);
run("npm test", &test_cli);
}
#[cfg(not(windows))]
#[test]
fn static_test() {
let _guard = TEST_MUTEX.lock();
if version_meta().unwrap().channel != Channel::Nightly {
return;
}
run("cargo test --release", &project_root().join("test").join("static"));
}
#[test]
fn dynamic_test() {
let _guard = TEST_MUTEX.lock();
let cli = project_root().join("cli");
run("npm install", &cli);
run("npm run transpile", &cli);
let test_dynamic = project_root().join("test").join("dynamic");
run("npm install", &test_dynamic);
run("npm test", &test_dynamic);
}
}