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 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
#![feature(offset_to)] /*! rsjs is a small library which attempts to provide a convenient way to interface the Rust and JavaScript worlds. It currently requires using the rust nightly channel and either the `asmjs-unknown-emscripten` or `wasm-unknown-emscripten` targets. See the README for any help setting up a development environment. # Javascript helpers `RSJS` provides a number of helper JavaScript functions to store and convert JavaScript objects to be used from Rust. All of these can be accessed through the JavaScript global `RSJS` after [`init`] has been called. ## `RSJS` global A global JavaScript object named `RSJS` is created by [`init`]. It contains all the helper JavaScript functions as well as an object table to keep the JavaScript objects that are held by Rust code. See [`JSObject`] for more details. ## `RSJS.loadObject(index)` Loads a JavaScript object from the object table and returns it. ## `RSJS.storeObject(js_object)` Stores an object into the object table and returns the index. The result is commonly wrapped into a [`JSObject`] by [`js_obj!`]. ## Private helper functions ### `RSJS.releaseObject(index)` Removes an object from the object table. For use in the `Drop` implementation of [`JSObject`] only. Releasing an object that is still refered to by a `JSObject` will cause problems. ### `RSJS.copyStringToHeap(js_string)` Copy a JavaScript string into the Rust heap and returns the address. The string is stored as a 32-bit unsigned integer containing the number of 16-bit code units (not bytes or characters!) in the buffer, followed by that number of 16-bit code units from the UTF-16 string. Used by [`js_string!`] and the implementation of `std::convert::From<JSObject> for String`. ### `RSJS.copyStringFromHeap(pointer)` Convert a String stored on the Rust heap (as described in [`copyStringToHeap`]) into a JavaScript string. The memory is freed after conversion, so the pointer should be considered invalid by the caller. [`init`]: fn.init.html [`js_obj!`]: macro.js_obj.html [`js_int!`]: macro.js_int.html [`js_double!`]: macro.js_double.html [`js_string!`]: macro.js_string.html [`js!`]: macro.js.html [`JSObject`]: struct.JSObject.html [`copyStringToHeap`]: index.html#rsjscopystringtoheapjs_string */ use std::ptr; use std::rc::Rc; /// This module declares C functions provided by either emscripten or the C standard library. /// These are all unsafe, and most are described in [the emscripten documentation](http://kripken.github.io/emscripten-site/docs/api_reference/emscripten.h.html). /// You should probably avoid using these directly. pub mod emscripten { use std; // These functions are used in macros, so sometimes they will be considered dead. extern "C" { /// Run a snippet of JavaScript with no arguments and no return value. /// /// See [emscripten_run_script (emscripten documentation)](http://kripken.github.io/emscripten-site/docs/api_reference/emscripten.h.html#c.emscripten_run_script) for details. #[allow(dead_code)] pub fn emscripten_run_script(s: *const std::os::raw::c_char); /// Run a snippet of JavaScript with no arguments and an integer return value. /// /// See [emscripten_run_script (emscripten documentation)](http://kripken.github.io/emscripten-site/docs/api_reference/emscripten.h.html#c.emscripten_run_script_int) for details. #[allow(dead_code)] pub fn emscripten_run_script_int(s: *const std::os::raw::c_char) -> std::os::raw::c_int; /// Run a snippet of JavaScript with no arguments that returns a C string. /// /// See [emscripten_run_script (emscripten documentation)](http://kripken.github.io/emscripten-site/docs/api_reference/emscripten.h.html#c.emscripten_run_script_string) for details. #[allow(dead_code)] pub fn emscripten_run_script_string(s: *const std::os::raw::c_char) -> *const std::os::raw::c_char; /// Run a snippet of JavaScript with no arguments. /// /// This function is slightly faster than `emscripten_run_script` but requires that /// the code snippet has a static lifetime. The emscripten compiler uses some magic /// to inline the code directly into the generated asm.js (or webassembly scaffolding code) /// and this avoids using `eval()`. #[allow(dead_code)] pub fn emscripten_asm_const(s: *const std::os::raw::c_char); /// Run a snippet of JavaScript with any arguments that can be doubles or ints, and returns an int. /// /// This function is slightly faster than `emscripten_run_script_int` but requires that /// the code snippet has a static lifetime. The emscripten compiler uses some magic /// to inline the code directly into the generated asm.js (or webassembly scaffolding code) /// and this avoids using `eval()`. /// Unlike `emscripten_run_script_int`, this function also allows passing arguments to the JavaScript /// side. #[allow(dead_code)] pub fn emscripten_asm_const_int(s: *const std::os::raw::c_char, ...) -> std::os::raw::c_int; /// Run a snippet of JavaScript with any arguments that can be doubles or ints, and returns a double. /// /// This is a version of `emscripten_asm_const_int` which doesn't convert the JavaScript result to an /// int, but instead preserves it as a double-precision floating point. #[allow(dead_code)] pub fn emscripten_asm_const_double(s: *const std::os::raw::c_char, ...) -> std::os::raw::c_double; #[allow(dead_code)] pub fn emscripten_pause_main_loop(); #[allow(dead_code)] pub fn emscripten_set_main_loop(m: extern fn(), fps: std::os::raw::c_int, infinite: std::os::raw::c_int); /// See [free(3)](https://linux.die.net/man/3/free) pub fn free(p: *mut u8); } } fn string_from_js(ptr: *mut u16) -> String { unsafe { let size : u32 = *(ptr as *const _ as *const u32); let string_slice : &'static [u16] = std::slice::from_raw_parts(ptr, size as usize); let result = String::from_utf16_lossy(string_slice); emscripten::free(ptr as *mut _); result } } /// Run a snippet of JavaScript code. pub fn js_eval(code: &'static [u8]) { unsafe { emscripten::emscripten_asm_const(code as *const _ as *const std::os::raw::c_char); } } /// Helper macro used by [`js!`], [`js_int!`], [`js_double!`], [`js_string!`] or [`js_obj!`]. /// /// **Should not be used directly.** /// /// [`js_obj!`]: macro.js_obj.html /// [`js_int!`]: macro.js_int.html /// [`js_double!`]: macro.js_double.html /// [`js_string!`]: macro.js_string.html /// [`js!`]: macro.js.html #[macro_export] macro_rules! __js_macro { ( $emscr_func:ident, $jscode:expr, $($args:expr),* ) => { { let jscode : &'static [u8] = concat!($jscode, "\0").as_bytes(); unsafe { $crate::emscripten::$emscr_func(jscode as *const _ as *const std::os::raw::c_char, $( $crate::JSObject::from($args).value ),* ) } } }; } /// Macro that evaluates a JavaScript code snippet with no return value and takes any number of arguments. /// /// # Arguments /// /// * `$jscode` - A `&'static str` containing the JavaScript code that needs to be run. /// * `$args, ...` - Any number of arguments to be used by `$jscode`. All arguments must be of a type `T` /// where `std::convert::From<T> for JSObject` is implemented. They can be referenced in /// JavaScript snippet as `$0`, `$1`, ... /// /// Note that the JavaScript snippet is responsible for unpacking the arguments itself using `RSJS.loadObject(...)` /// if the argument is not a simple number of boolean. See the documentation for [`JSObject`] for more information. /// /// # See also /// /// For similar macros with different return types, see [`js_int!`], [`js_double!`], [`js_string!`] or [`js_obj!`]. /// /// [`JSObject`]: struct.JSObject.html /// [`js_int!`]: macro.js_int.html /// [`js_double!`]: macro.js_double.html /// [`js_string!`]: macro.js_string.html /// [`js_obj!`]: macro.js_obj.html #[macro_export] macro_rules! js { ($jscode:expr $(, $args:expr)*) => { __js_macro!(emscripten_asm_const_int, $jscode, $($args),*) } } /// Macro that evaluates a JavaScript code snippet which returns a JavaScript object. /// /// # Arguments /// /// * `$jscode` - A `&'static str` containing the JavaScript code that needs to be run. /// * `$args, ...` - Any number of arguments to be used by `$jscode`. All arguments must be of a type `T` /// where `std::convert::From<T> for JSObject` is implemented. They can be referenced in /// JavaScript snippet as `$0`, `$1`, ... /// /// Note that the JavaScript snippet is responsible for unpacking the arguments itself using `RSJS.loadObject(...)` /// if the argument is not a simple number of boolean. See the documentation for [`JSObject`] for more information. /// /// # Return value /// /// An instance of a [`JSObject`] wrapping the return value of the executed JavaScript. /// /// # See also /// /// For similar macros with different return types, see [`js_int!`], [`js_double!`], [`js_string!`] or [`js!`]. /// /// [`JSObject`]: struct.JSObject.html /// [`js_int!`]: macro.js_int.html /// [`js_double!`]: macro.js_double.html /// [`js_string!`]: macro.js_string.html /// [`js!`]: macro.js.html #[macro_export] macro_rules! js_obj { // TODO: test ($jscode:expr $(, $args:expr )*) => ( $crate::JSObject { value: __js_macro!(emscripten_asm_const_int, concat!("return RSJS.storeObject((function(){", $jscode, "})();"), $($args),*) as f64, jshandle: true, refcount: Rc::new(()), } ) } /// Macro that evaluates a JavaScript code snippet which returns a string. /// /// # Arguments /// /// * `$jscode` - A `&'static str` containing the JavaScript code that needs to be run. /// * `$args, ...` - Any number of arguments to be used by `$jscode`. All arguments must be of a type `T` /// where `std::convert::From<T> for JSObject` is implemented. They can be referenced in /// JavaScript snippet as `$0`, `$1`, ... /// /// Note that the JavaScript snippet is responsible for unpacking the arguments itself using `RSJS.loadObject(...)` /// if the argument is not a simple number of boolean. See the documentation for [`JSObject`] for more information. /// /// # Return value /// /// An instance of a `std::string::String` converted from the JavaScript string returned by `$jscode`. /// /// # See also /// /// For similar macros with different return types, see [`js_int!`], [`js_double!`], [`js!`] or [`js_obj!`]. /// /// [`JSObject`]: struct.JSObject.html /// [`js_int!`]: macro.js_int.html /// [`js_double!`]: macro.js_double.html /// [`js_obj!`]: macro.js_obj.html /// [`js!`]: macro.js.html #[macro_export] macro_rules! js_string { // TODO: test ($jscode:expr $(, $args:expr )*) => ( String::from(js_obj!($jscode, $($args),*)) ) } /// Macro that evaluates a JavaScript code snippet which returns an integer. /// /// # Arguments /// /// * `$jscode` - A `&'static str` containing the JavaScript code that needs to be run. /// * `$args, ...` - Any number of arguments to be used by `$jscode`. All arguments must be of a type `T` /// where `std::convert::From<T> for JSObject` is implemented. They can be referenced in /// JavaScript snippet as `$0`, `$1`, ... /// /// Note that the JavaScript snippet is responsible for unpacking the arguments itself using `RSJS.loadObject(...)` /// if the argument is not a simple number of boolean. See the documentation for [`JSObject`] for more information. /// /// # Return value /// /// The return value of `$jscode` as an `i32`. /// /// # See also /// /// For similar macros with different return types, see [`js!`], [`js_double!`], [`js_string!`] or [`js_obj!`]. /// /// [`JSObject`]: struct.JSObject.html /// [`js!`]: macro.js.html /// [`js_double!`]: macro.js_double.html /// [`js_obj!`]: macro.js_obj.html /// [`js_string!`]: macro.js_string.html #[macro_export] macro_rules! js_int { ($jscode:expr $(, $args:expr )*) => ( __js_macro!(emscripten_asm_const_int, $jscode, $($args),*) ) } /// Macro that evaluates a JavaScript code snippet which returns a floating point number. /// /// # Arguments /// /// * `$jscode` - A `&'static str` containing the JavaScript code that needs to be run. /// * `$args, ...` - Any number of arguments to be used by `$jscode`. All arguments must be of a type `T` /// where `std::convert::From<T> for JSObject` is implemented. They can be referenced in /// JavaScript snippet as `$0`, `$1`, ... /// /// Note that the JavaScript snippet is responsible for unpacking the arguments itself using `RSJS.loadObject(...)` /// if the argument is not a simple number of boolean. See the documentation for [`JSObject`] for more information. /// /// # Return value /// /// The return value of `$jscode` as an `f64`. /// /// # See also /// /// For similar macros with different return types, see [`js!`], [`js_double!`], [`js_string!`] or [`js_obj!`]. /// /// [`JSObject`]: struct.JSObject.html /// [`js!`]: macro.js.html /// [`js_double!`]: macro.js_double.html /// [`js_obj!`]: macro.js_obj.html /// [`js_string!`]: macro.js_string.html #[macro_export] macro_rules! js_double { ($jscode:expr $(, $args:expr )*) => ( __js_macro!(emscripten_asm_const_double, $jscode, $($args),*); ) } /// A reference to a JavaScript object. /// /// A JSObject holds a handle to an entry to the [`RSJS`] object table. /// /// The `Drop` implementation for `JSObject` will cause the JavaScript /// object to be removed from the [`RSJS`] object table, allowing it to /// be reclaimed by the JavaScript garbage collector. /// /// If you wish to add a type `T` that can be passed to JavaScript, you should /// implement `std::convert::From<T> for JSObject`. /// /// # Important note: /// /// The `value` field should never be read or modified directly, /// it is only public so that it can be used by the [`js!`] macro. /// /// [`RSJS`]: index.html#rsjs-global /// [`js!`]: macro.js.html #[derive(Clone)] pub struct JSObject { pub value: f64, jshandle: bool, refcount: Rc<()>, } impl<'a> std::convert::From<&'a JSObject> for JSObject { fn from(v: &'a JSObject) -> Self { JSObject::from(v.clone()) } } impl Drop for JSObject { fn drop(&mut self) { if self.jshandle && Rc::strong_count(&self.refcount) == 1 { let code : &'static [u8] = b"RSJS.releaseObject($0);\0"; unsafe { emscripten::emscripten_asm_const_int(code as *const _ as *const std::os::raw::c_char, self.value); } } } } impl<T> std::convert::From<Vec<T>> for JSObject where JSObject: std::convert::From<T> { fn from(v: Vec<T>) -> Self { let arr = js_obj!("return RSJS.storeObject([]);"); for elem in v { let elem_js = JSObject::from(elem); let code : &'static [u8] = if elem_js.jshandle { b"RSJS.loadObject($0).push(RSJS.loadObject($1))\0" } else { b"RSJS.loadObject($0).push($1)\0" }; unsafe { emscripten::emscripten_asm_const_int(code as *const _ as *const std::os::raw::c_char, arr.value, elem_js.value); } } arr } } macro_rules! __js_from_numeric { ( $( $type:ty ),+ ) => ( $( impl std::convert::From<$type> for JSObject { fn from(v: $type) -> Self { JSObject { value: v as f64, jshandle: false, refcount: Rc::new(()), } } } impl std::convert::From<JSObject> for $type { fn from(obj: JSObject) -> Self { if obj.jshandle { js_double!("return RSJS.loadObject($0);", obj) as $type } else { obj.value as $type } } } )+ ) } __js_from_numeric!(isize, usize, i32, u32, i16, u16, i8, u8, f32, f64); impl<'a> std::convert::From<&'a str> for JSObject { fn from(s: &'a str) -> Self { // TODO: This won't work when the pointer can't fit in 31bit int. let code : &'static [u8] = b"return RSJS.storeObject(RSJS.copyStringFromHeap($0, $1));\0"; let data : Vec<u16> = s.encode_utf16().collect(); let data_ptr_as_isize = ptr::null::<u16>().offset_to(data.as_ptr()).unwrap_or(0) * 2; unsafe { JSObject { value: emscripten::emscripten_asm_const_int(code as *const _ as *const std::os::raw::c_char, data_ptr_as_isize, data.len()) as f64, jshandle: true, refcount: Rc::new(()), } } } } impl<'a> std::convert::From<&'a String> for JSObject { fn from(s: &'a String) -> Self { JSObject::from(s.as_str()) } } impl std::convert::From<String> for JSObject { fn from(s: String) -> Self { JSObject::from(s.as_str()) } } impl std::convert::From<JSObject> for String { fn from(obj: JSObject) -> Self { let ptr = js_int!("return RSJS.storeObject(RSJS.copyStringToHeap(RSJS.loadObject($0)));", obj) as *mut u16; string_from_js(ptr) } } impl std::convert::From<bool> for JSObject { fn from(b: bool) -> Self { JSObject { value: if b { 1.0 } else { 0.0 }, jshandle: false, refcount: Rc::new(()), } } } impl std::convert::From<JSObject> for bool { fn from(obj: JSObject) -> Self { if obj.jshandle { js_int!("return RSJS.loadObject($0);", obj) != 0 } else { obj.value != 0f64 } } } /// Initializes the JavaScript [RSJS global object and helper functions](index.html#javascript-helpers). /// Should be called before using any other functions or macros from this crate. pub fn init() { js_eval(concat!(include_str!(concat!(env!("OUT_DIR"), "/rs.js")), "\0").as_bytes()) }