Use Rust to implement JS API

For JavaScript developers, incorporating Rust functions into JavaScript APIs is useful. That enables developers to write programs in “pure JavaScript” and yet still take advantage of the high performance Rust functions. With the WasmEdge Runtime, you can do exactly that.

The internal_module folder in the official WasmEdge QuickJS distribution provides Rust-based implementations of some built-in JavaScript API functions. Those functions typically require interactions with host functions in the WasmEdge runtime (e.g., networking and tensorflow), and hence cannot be accessed by pure JavaScript implementations in modules.

Check out the wasmedge-quickjs Github repo and change to the examples/embed_js folder to follow along.

git clone https://github.com/second-state/wasmedge-quickjs cd examples/embed_js

You must have Rust and WasmEdge installed to build and run the examples we show you.

The embed_js demo showcases several different examples on how to embed JavaScript inside Rust. You can build and run all the examples as follows.

cargo build --target wasm32-wasi --release wasmedge --dir .:. target/wasm32-wasi/release/embed_js.wasm

Note: The --dir .:. on the command line is to give wasmedge permission to read the local directory in the file system.

Create a JavaScript function API

The following code snippet defines a Rust function that can be incorporate into the JavaScript interpreter as an API.

  1. #![allow(unused)]
  2. fn main() {
  3. fn run_rust_function(ctx: &mut Context) {
  4. struct HelloFn;
  5. impl JsFn for HelloFn {
  6. fn call(_ctx: &mut Context, _this_val: JsValue, argv: &[JsValue]) -> JsValue {
  7. println!("hello from rust");
  8. println!("argv={:?}", argv);
  9. JsValue::UnDefined
  10. }
  11. }
  12. ...
  13. }
  14. }

The following code snippet shows how to add this Rust function into the JavaScript interpreter, give a name hi() as its JavaScript API, and then call it from JavaScript code.

  1. #![allow(unused)]
  2. fn main() {
  3. fn run_rust_function(ctx: &mut Context) {
  4. ...
  5. let f = ctx.new_function::<HelloFn>("hello");
  6. ctx.get_global().set("hi", f.into());
  7. let code = r#"hi(1,2,3)"#;
  8. let r = ctx.eval_global_str(code);
  9. println!("return value:{:?}", r);
  10. }
  11. }

The execution result is as follows.

hello from rust argv=[Int(1), Int(2), Int(3)] return value:UnDefined

Using this approach, you can create a JavaScript interpreter with customized API functions. The interpreter runs inside WasmEdge, and can execute JavaScript code, which calls such API functions, from CLI or the network.

Create a JavaScript object API

In the JavaScript API design, we sometimes need to provide an object that encapsulates both data and function. In the following example, we define a Rust function for the JavaScript API.

  1. #![allow(unused)]
  2. fn main() {
  3. fn rust_new_object_and_js_call(ctx: &mut Context) {
  4. struct ObjectFn;
  5. impl JsFn for ObjectFn {
  6. fn call(_ctx: &mut Context, this_val: JsValue, argv: &[JsValue]) -> JsValue {
  7. println!("hello from rust");
  8. println!("argv={:?}", argv);
  9. if let JsValue::Object(obj) = this_val {
  10. let obj_map = obj.to_map();
  11. println!("this={:#?}", obj_map);
  12. }
  13. JsValue::UnDefined
  14. }
  15. }
  16. ...
  17. }
  18. }

We then create an “object” on the Rust side, set its data fields, and then register the Rust function as a JavaScript function associated with the objects.

  1. #![allow(unused)]
  2. fn main() {
  3. let mut obj = ctx.new_object();
  4. obj.set("a", 1.into());
  5. obj.set("b", ctx.new_string("abc").into());
  6. let f = ctx.new_function::<ObjectFn>("anything");
  7. obj.set("f", f.into());
  8. }

Next, we make the Rust “object” available as JavaScript object test_obj in the JavaScript interpreter.

  1. #![allow(unused)]
  2. fn main() {
  3. ctx.get_global().set("test_obj", obj.into());
  4. }

In the JavaScript code, you can now directly use test_obj as part of the API.

  1. #![allow(unused)]
  2. fn main() {
  3. let code = r#"
  4. print('test_obj keys=',Object.keys(test_obj))
  5. print('test_obj.a=',test_obj.a)
  6. print('test_obj.b=',test_obj.b)
  7. test_obj.f(1,2,3,"hi")
  8. "#;
  9. ctx.eval_global_str(code);
  10. }

The execution result is as follows.

test_obj keys= a,b,f test_obj.a= 1 test_obj.b= abc hello from rust argv=[Int(1), Int(2), Int(3), String(JsString(hi))] this=Ok( { "a": Int( 1, ), "b": String( JsString( abc, ), ), "f": Function( JsFunction( function anything() { [native code] }, ), ), }, )

A complete JavaScript object API

In the previous example, we demonstrated simple examples to create JavaScript APIs from Rust. In this example, we will create a complete Rust module and make it available as a JavaScript object API. The project is in the examples/embed_rust_module folder. You can build and run it as a standard Rust application in WasmEdge.

cargo build --target wasm32-wasi --release wasmedge --dir .:. target/wasm32-wasi/release/embed_rust_module.wasm

The Rust implementation of the object is a module as follows. It has data fields, constructor, getters and setters, and functions.

  1. #![allow(unused)]
  2. fn main() {
  3. mod point {
  4. use wasmedge_quickjs::*;
  5. #[derive(Debug)]
  6. struct Point(i32, i32);
  7. struct PointDef;
  8. impl JsClassDef<Point> for PointDef {
  9. const CLASS_NAME: &'static str = "Point\0";
  10. const CONSTRUCTOR_ARGC: u8 = 2;
  11. fn constructor(_: &mut Context, argv: &[JsValue]) -> Option<Point> {
  12. println!("rust-> new Point {:?}", argv);
  13. let x = argv.get(0);
  14. let y = argv.get(1);
  15. if let ((Some(JsValue::Int(ref x)), Some(JsValue::Int(ref y)))) = (x, y) {
  16. Some(Point(*x, *y))
  17. } else {
  18. None
  19. }
  20. }
  21. fn proto_init(p: &mut JsClassProto<Point, PointDef>) {
  22. struct X;
  23. impl JsClassGetterSetter<Point> for X {
  24. const NAME: &'static str = "x\0";
  25. fn getter(_: &mut Context, this_val: &mut Point) -> JsValue {
  26. println!("rust-> get x");
  27. this_val.0.into()
  28. }
  29. fn setter(_: &mut Context, this_val: &mut Point, val: JsValue) {
  30. println!("rust-> set x:{:?}", val);
  31. if let JsValue::Int(x) = val {
  32. this_val.0 = x
  33. }
  34. }
  35. }
  36. struct Y;
  37. impl JsClassGetterSetter<Point> for Y {
  38. const NAME: &'static str = "y\0";
  39. fn getter(_: &mut Context, this_val: &mut Point) -> JsValue {
  40. println!("rust-> get y");
  41. this_val.1.into()
  42. }
  43. fn setter(_: &mut Context, this_val: &mut Point, val: JsValue) {
  44. println!("rust-> set y:{:?}", val);
  45. if let JsValue::Int(y) = val {
  46. this_val.1 = y
  47. }
  48. }
  49. }
  50. struct FnPrint;
  51. impl JsMethod<Point> for FnPrint {
  52. const NAME: &'static str = "pprint\0";
  53. const LEN: u8 = 0;
  54. fn call(_: &mut Context, this_val: &mut Point, _argv: &[JsValue]) -> JsValue {
  55. println!("rust-> pprint: {:?}", this_val);
  56. JsValue::Int(1)
  57. }
  58. }
  59. p.add_getter_setter(X);
  60. p.add_getter_setter(Y);
  61. p.add_function(FnPrint);
  62. }
  63. }
  64. struct PointModule;
  65. impl ModuleInit for PointModule {
  66. fn init_module(ctx: &mut Context, m: &mut JsModuleDef) {
  67. m.add_export("Point\0", PointDef::class_value(ctx));
  68. }
  69. }
  70. pub fn init_point_module(ctx: &mut Context) {
  71. ctx.register_class(PointDef);
  72. ctx.register_module("point\0", PointModule, &["Point\0"]);
  73. }
  74. }
  75. }

In the interpreter implementation, we call point::init_point_module first to register the Rust module with the JavaScript context, and then we can run a JavaScript program that simply use the point object.

  1. use wasmedge_quickjs::*;
  2. fn main() {
  3. let mut ctx = Context::new();
  4. point::init_point_module(&mut ctx);
  5. let code = r#"
  6. import('point').then((point)=>{
  7. let p0 = new point.Point(1,2)
  8. print("js->",p0.x,p0.y)
  9. p0.pprint()
  10. try{
  11. let p = new point.Point()
  12. print("js-> p:",p)
  13. print("js->",p.x,p.y)
  14. p.x=2
  15. p.pprint()
  16. } catch(e) {
  17. print("An error has been caught");
  18. print(e)
  19. }
  20. })
  21. "#;
  22. ctx.eval_global_str(code);
  23. ctx.promise_loop_poll();
  24. }

The execution result from the above application is as follows.

rust-> new Point [Int(1), Int(2)] rust-> get x rust-> get y js-> 1 2 rust-> pprint: Point(1, 2) rust-> new Point [] js-> p: undefined An error has been caught TypeError: cannot read property 'x' of undefined

Next, you can see the Rust code in the internal_module folder for more examples on how to implement common JavaScript build-in functions including Node.js APIs.