Macro embed_js::js [] [src]

macro_rules! js {
    ([$($args:tt)*] $($tt:tt)*) => { ... };
    ({$($tt:tt)*}) => { ... };
}

Call javascript, inline.

This macro must not be called from within any other macro, otherwise it will fail to work.

The javascript written inside calls to this macro must adhere to some additional rules:

  • Every statement must end in a semi-colon.
  • No single-quote multi-character strings are allowed.

There are three forms for calling this macro:

  • js!([arg1 as type1, arg2 as type2, &arg3, *arg3 as type3, &mut **arg3, ...] -> ret_type { /*javascript*/ })

    In this form, you specify arguments and a return type. There are two categories of argument.

    Arguments preceded by a & are references. These arguments may be any number of reference operations (both immutable and mutable) on an identifier that has been dereferenced via * some number of times (including zero). These arguments are passed to the JavaScript as pointers, with type wasm type i32. These pointers can then be looked up in the wasm module memory buffer to access the contents of the value referenced.

    Other arguments take the form of a possibly dereferenced identifier followed by as type, for some type type. Values are cast using as to this type before passing to the JavaScript.

    Every type specified, including the return type, must be one of i32, i64, f32 or f64. These are the only raw types supported by WebAssembly for interop at the moment. More complicated types are best passed by reference.

    Examples:

    Be careful when using this code, it's not being tested!
    let x = 2;
    let y = js!([x as i32] -> i32 {
      return x + 1;
    });
    // y is now 3
    Be careful when using this code, it's not being tested!
    let one_half = js!([] -> f64 {
      return 1.0 / 2.0;
    });
  • js!([arg1 as type1, arg2 as type2, ...] { /*javascript*/ })

    Like the previous form, but without a return type. Any value returned from javascript is discarded.

  • js!({ /*javascript*/ })

    No arguments or return type.