Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions crates/js-component-bindgen-component/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,20 @@ impl From<BindingsMode> for js_component_bindgen::BindingsMode {
}
}

impl From<AsyncMode> for js_component_bindgen::AsyncMode {
fn from(value: AsyncMode) -> Self {
match value {
AsyncMode::Sync => js_component_bindgen::AsyncMode::Sync,
AsyncMode::Jspi(AsyncImportsExports { imports, exports }) => {
js_component_bindgen::AsyncMode::JavaScriptPromiseIntegration { imports, exports }
}
AsyncMode::Asyncify(AsyncImportsExports { imports, exports }) => {
js_component_bindgen::AsyncMode::Asyncify { imports, exports }
}
}
}
}

struct JsComponentBindgenComponent;

export!(JsComponentBindgenComponent);
Expand All @@ -76,6 +90,7 @@ impl Guest for JsComponentBindgenComponent {
multi_memory: options.multi_memory.unwrap_or(false),
import_bindings: options.import_bindings.map(Into::into),
guest: options.guest.unwrap_or(false),
async_mode: options.async_mode.map(Into::into),
};

let js_component_bindgen::Transpiled {
Expand Down Expand Up @@ -162,6 +177,7 @@ impl Guest for JsComponentBindgenComponent {
multi_memory: false,
import_bindings: None,
guest: opts.guest.unwrap_or(false),
async_mode: opts.async_mode.map(Into::into),
};

let files = generate_types(name, resolve, world, opts).map_err(|e| e.to_string())?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,31 @@ world js-component-bindgen {
/// Whether to generate namespaced exports like `foo as "local:package/foo"`.
/// These exports can break typescript builds.
no-namespaced-exports: option<bool>,

/// Whether to generate module declarations like `declare module "local:package/foo" {...`.
guest: option<bool>,

/// Whether to output core Wasm utilizing multi-memory or to polyfill
/// this handling.
multi-memory: option<bool>,

/// Configure whether to use `async` imports or exports with
/// JavaScript Promise Integration (JSPI) or Asyncify.
async-mode: option<async-mode>,
}

record async-imports-exports {
imports: list<string>,
exports: list<string>,
}

variant async-mode {
/// default to sync mode
sync,
/// use JavaScript Promise Integration (JSPI)
jspi(async-imports-exports),
/// use Asyncify
asyncify(async-imports-exports),
}

variant wit {
Expand Down Expand Up @@ -96,6 +114,9 @@ world js-component-bindgen {
features: option<enabled-feature-set>,
/// Whether to generate module declarations like `declare module "local:package/foo" {...`.
guest: option<bool>,
/// Configure whether to use `async` imports or exports with
/// JavaScript Promise Integration (JSPI) or Asyncify.
async-mode: option<async-mode>,
}

enum export-type {
Expand Down
1 change: 0 additions & 1 deletion crates/js-component-bindgen/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
use anyhow::{bail, Result};
use std::collections::{HashMap, HashSet};
use wasm_encoder::*;
use wasmparser::collections::IndexMap;
use wasmparser::*;
use wasmtime_environ::component::CoreDef;
use wasmtime_environ::{EntityIndex, MemoryIndex, ModuleTranslation, PrimaryMap};
Expand Down
18 changes: 15 additions & 3 deletions crates/js-component-bindgen/src/function_bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ pub struct FunctionBindgen<'a> {
pub callee: &'a str,
pub callee_resource_dynamic: bool,
pub resolve: &'a Resolve,
pub is_async: bool,
}

impl FunctionBindgen<'_> {
Expand Down Expand Up @@ -1048,7 +1049,13 @@ impl Bindgen for FunctionBindgen<'_> {
Instruction::CallWasm { sig, .. } => {
let sig_results_length = sig.results.len();
self.bind_results(sig_results_length, results);
uwriteln!(self.src, "{}({});", self.callee, operands.join(", "));
let maybe_async_await = if self.is_async { "await " } else { "" };
uwriteln!(
self.src,
"{maybe_async_await}{}({});",
self.callee,
operands.join(", ")
);

if let Some(prefix) = self.tracing_prefix {
let to_result_string = self.intrinsic(Intrinsic::ToResultString);
Expand All @@ -1066,15 +1073,20 @@ impl Bindgen for FunctionBindgen<'_> {

Instruction::CallInterface { func } => {
let results_length = func.results.len();
let maybe_async_await = if self.is_async { "await " } else { "" };
let call = if self.callee_resource_dynamic {
format!(
"{}.{}({})",
"{maybe_async_await}{}.{}({})",
operands[0],
self.callee,
operands[1..].join(", ")
)
} else {
format!("{}({})", self.callee, operands.join(", "))
format!(
"{maybe_async_await}{}({})",
self.callee,
operands.join(", ")
)
};
if self.err == ErrHandling::ResultCatchHandler {
// result<_, string> allows JS error coercion only, while
Expand Down
132 changes: 132 additions & 0 deletions crates/js-component-bindgen/src/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ use std::fmt::Write;

#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum Intrinsic {
AsyncifyAsyncInstantiate,
AsyncifySyncInstantiate,
AsyncifyWrapExport,
AsyncifyWrapImport,
Base64Compile,
ClampGuest,
ComponentError,
Expand All @@ -23,6 +27,7 @@ pub enum Intrinsic {
HasOwnProperty,
I32ToF32,
I64ToF64,
Imports,
InstantiateCore,
IsLE,
ResourceTableFlag,
Expand Down Expand Up @@ -114,6 +119,117 @@ pub fn render_intrinsics(

for i in intrinsics.iter() {
match i {
Intrinsic::AsyncifyAsyncInstantiate => output.push_str("
const asyncifyModules = [];
let asyncifyPromise;
let asyncifyResolved;
async function asyncifyInstantiate(module, imports) {
const instance = await instantiateCore(module, imports);
const memory = instance.exports.memory || (imports && imports.env && imports.env.memory);
const realloc = instance.exports.cabi_realloc || instance.exports.cabi_export_realloc;
if (instance.exports.asyncify_get_state && memory) {
let address;
if (realloc) {
address = realloc(0, 0, 4, 1024);
new Int32Array(memory.buffer, address).set([address + 8, address + 1024]);
} else {
address = 16;
new Int32Array(memory.buffer, address).set([address + 8, address + 1024]);
}
asyncifyModules.push({ instance, memory, address });
}
return instance;
}
function asyncifyState() {
return asyncifyModules[0]?.instance.exports.asyncify_get_state();
}
function asyncifyAssertNoneState() {
let state = asyncifyState();
if (state !== 0) {
throw new Error(`reentrancy not supported, expected asyncify state '0' but found '${state}'`);
}
}
"),

Intrinsic::AsyncifySyncInstantiate => output.push_str("
const asyncifyModules = [];
let asyncifyPromise;
let asyncifyResolved;
function asyncifyInstantiate(module, imports) {
const instance = instantiateCore(module, imports);
const memory = instance.exports.memory || (imports && imports.env && imports.env.memory);
const realloc = instance.exports.cabi_realloc || instance.exports.cabi_export_realloc;
if (instance.exports.asyncify_get_state && memory) {
let address;
if (realloc) {
address = realloc(0, 0, 4, 1024);
new Int32Array(memory.buffer, address).set([address + 8, address + 1024]);
} else {
address = 16;
new Int32Array(memory.buffer, address).set([address + 8, address + 1024]);
}
asyncifyModules.push({ instance, memory, address });
}
return instance;
}
function asyncifyState() {
return asyncifyModules[0]?.instance.exports.asyncify_get_state();
}
function asyncifyAssertNoneState() {
let state = asyncifyState();
if (state !== 0) {
throw new Error(`reentrancy not supported, expected asyncify state '0' but found '${state}'`);
}
}
"),

Intrinsic::AsyncifyWrapExport => output.push_str("
function asyncifyWrapExport(fn) {
return async (...args) => {
if (asyncifyModules.length === 0) {
throw new Error(`none of the Wasm modules were processed with wasm-opt asyncify`);
}
asyncifyAssertNoneState();
let result = fn(...args);
while (asyncifyState() === 1) {
asyncifyModules.forEach(({ instance }) => {
instance.exports.asyncify_stop_unwind();
});
asyncifyResolved = await asyncifyPromise;
asyncifyPromise = undefined;
asyncifyAssertNoneState();
asyncifyModules.forEach(({ instance, address }) => {
instance.exports.asyncify_start_rewind(address);
});
result = fn(...args);
}
asyncifyAssertNoneState();
return result;
};
}
"),

Intrinsic::AsyncifyWrapImport => output.push_str("
function asyncifyWrapImport(fn) {
return (...args) => {
if (asyncifyState() === 2) {
asyncifyModules.forEach(({ instance }) => {
instance.exports.asyncify_stop_rewind();
});
const ret = asyncifyResolved;
asyncifyResolved = undefined;
return ret;
}
asyncifyAssertNoneState();
let value = fn(...args);
asyncifyModules.forEach(({ instance, address }) => {
instance.exports.asyncify_start_unwind(address);
});
asyncifyPromise = value;
};
}
"),
Comment on lines +213 to +231
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add missing return statement in asyncifyWrapImport

In the asyncifyWrapImport function, the returned wrapper function does not return a value after setting asyncifyPromise (line 228), which can lead to unexpected undefined results or incorrect behavior.

Apply this diff to add the missing return statement:

        asyncifyPromise = value;
+       return;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function asyncifyWrapImport(fn) {
return (...args) => {
if (asyncifyState() === 2) {
asyncifyModules.forEach(({ instance }) => {
instance.exports.asyncify_stop_rewind();
});
const ret = asyncifyResolved;
asyncifyResolved = undefined;
return ret;
}
asyncifyAssertNoneState();
let value = fn(...args);
asyncifyModules.forEach(({ instance, address }) => {
instance.exports.asyncify_start_unwind(address);
});
asyncifyPromise = value;
};
}
"),
function asyncifyWrapImport(fn) {
return (...args) => {
if (asyncifyState() === 2) {
asyncifyModules.forEach(({ instance }) => {
instance.exports.asyncify_stop_rewind();
});
const ret = asyncifyResolved;
asyncifyResolved = undefined;
return ret;
}
asyncifyAssertNoneState();
let value = fn(...args);
asyncifyModules.forEach(({ instance, address }) => {
instance.exports.asyncify_start_unwind(address);
});
asyncifyPromise = value;
return;
};
}
"),


Intrinsic::Base64Compile => if !no_nodejs_compat {
output.push_str("
const base64Compile = str => WebAssembly.compile(typeof Buffer !== 'undefined' ? Buffer.from(str, 'base64') : Uint8Array.from(atob(str), b => b.charCodeAt(0)));
Expand Down Expand Up @@ -285,6 +401,8 @@ pub fn render_intrinsics(
const i64ToF64 = i => (i64ToF64I[0] = i, i64ToF64F[0]);
"),

Intrinsic::Imports => {},

Intrinsic::InstantiateCore => if !instantiation {
output.push_str("
const instantiateCore = WebAssembly.instantiate;
Expand Down Expand Up @@ -654,6 +772,14 @@ impl Intrinsic {
pub fn get_global_names() -> &'static [&'static str] {
&[
// Intrinsic list exactly as below
"asyncifyAssertNoneState",
"asyncifyInstantiate",
"asyncifyModules",
"asyncifyPromise",
"asyncifyResolved",
"asyncifyState",
"asyncifyWrapExport",
"asyncifyWrapImport",
"base64Compile",
"clampGuest",
"ComponentError",
Expand All @@ -671,6 +797,7 @@ impl Intrinsic {
"hasOwnProperty",
"i32ToF32",
"i64ToF64",
"imports",
"instantiateCore",
"isLE",
"resourceCallBorrows",
Expand Down Expand Up @@ -733,6 +860,10 @@ impl Intrinsic {

pub fn name(&self) -> &'static str {
match self {
Intrinsic::AsyncifyAsyncInstantiate => "asyncifyInstantiate",
Intrinsic::AsyncifySyncInstantiate => "asyncifyInstantiate",
Intrinsic::AsyncifyWrapExport => "asyncifyWrapExport",
Intrinsic::AsyncifyWrapImport => "asyncifyWrapImport",
Intrinsic::Base64Compile => "base64Compile",
Intrinsic::ClampGuest => "clampGuest",
Intrinsic::ComponentError => "ComponentError",
Expand All @@ -751,6 +882,7 @@ impl Intrinsic {
Intrinsic::HasOwnProperty => "hasOwnProperty",
Intrinsic::I32ToF32 => "i32ToF32",
Intrinsic::I64ToF64 => "i64ToF64",
Intrinsic::Imports => "imports",
Intrinsic::InstantiateCore => "instantiateCore",
Intrinsic::IsLE => "isLE",
Intrinsic::ResourceCallBorrows => "resourceCallBorrows",
Expand Down
2 changes: 1 addition & 1 deletion crates/js-component-bindgen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub mod function_bindgen;
pub mod intrinsics;
pub mod names;
pub mod source;
pub use transpile_bindgen::{BindingsMode, InstantiationMode, TranspileOpts};
pub use transpile_bindgen::{AsyncMode, BindingsMode, InstantiationMode, TranspileOpts};

use anyhow::Result;
use transpile_bindgen::transpile_bindgen;
Expand Down
Loading