wasm-rquickjs 0.1.1

Tool for wrapping JavaScript modules as WebAssembly components using the QuickJS engine
Documentation
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use crate::javascript::escape_js_ident;
use crate::rust_bindgen::RustWitFunction;
use crate::types::{
    ProcessedParameter, ReturnTypeInformation, WrappedType, get_function_name, get_return_type,
    ident_in_exported_interface, ident_in_exported_interface_or_global, param_refs_as_tuple,
    process_parameter, to_original_func_arg_list, to_wrapped_param_refs, type_borrows_resource,
};
use crate::{EmbeddingMode, GeneratorContext, JsModuleSpec};
use anyhow::{Context, anyhow};
use heck::{ToLowerCamelCase, ToUpperCamelCase};
use proc_macro2::{Ident, Span, TokenStream};
use quote::quote;
use std::collections::BTreeMap;
use syn::{Lit, LitStr};
use wit_parser::{Function, FunctionKind, Interface, TypeId, WorldItem, WorldKey};

/// Generates the `<output>/src/lib.rs` file for the wrapper crate, implementing the component exports
/// and providing the general Rust module declarations.
pub fn generate_export_impls(
    context: &GeneratorContext<'_>,
    js_modules: &[JsModuleSpec],
) -> anyhow::Result<()> {
    let guest_impls = generate_guest_impls(context)?;
    let module_defs = generate_module_defs(js_modules)?;

    let lib_tokens = quote! {
        #[allow(static_mut_refs)]
        #[allow(unsafe_op_in_unsafe_fn)]
        mod bindings;
        mod builtin;
        mod conversions;
        #[allow(unused)]
        mod internal;
        #[allow(unused)]
        mod modules;
        mod wrappers;

        #module_defs

        struct Component;

        #(#guest_impls)*

        bindings::export!(Component with_types_in bindings);
    };

    let lib_ast: syn::File =
        syn::parse2(lib_tokens).context("failed to parse generated lib.rs tokens")?;

    let lib_path = context.output.join("src").join("lib.rs");
    let lib_src = prettier_please::unparse(&lib_ast);

    crate::write_if_changed(&lib_path, lib_src)?;

    Ok(())
}

/// Generates a list of code snippets, each implementing one of the `Guest` traits generated by
/// wit-bindgen-rust for the component's exports.
fn generate_guest_impls(context: &GeneratorContext<'_>) -> anyhow::Result<Vec<TokenStream>> {
    let mut result = Vec::new();

    let world = &context.resolve.worlds[context.world];

    let mut global_exports = Vec::new();
    let mut interface_exports = Vec::new();

    // Enumerating all exports and separating them into global exports and interface exports.
    for (name, export) in &world.exports {
        let name = match name {
            WorldKey::Name(name) => name.clone(),
            WorldKey::Interface(id) => {
                let interface = &context.resolve.interfaces[*id];
                interface
                    .name
                    .clone()
                    .ok_or_else(|| anyhow!("Interface export does not have a name"))?
            }
        };
        match export {
            WorldItem::Interface { id, .. } => {
                let interface = &context.resolve.interfaces[*id];
                interface_exports.push((name, interface));
            }
            WorldItem::Function(function) => {
                global_exports.push((name, function));
            }
            WorldItem::Type(_) => {}
        }
    }

    // Implementing a single Guest trait containing all the global exported functions
    if !global_exports.is_empty() {
        result.extend(generate_guest_impl(
            context,
            quote! { crate::bindings::Guest },
            None,
            &global_exports,
        )?);
    }

    // Implementing a Guest trait per exported interface
    for (name, interface) in interface_exports {
        let interface_exports: Vec<_> = interface
            .functions
            .iter()
            .map(|(name, function)| (name.clone(), function))
            .collect();

        result.extend(generate_guest_impl(
            context,
            ident_in_exported_interface(
                context,
                Ident::new("Guest", Span::call_site()),
                &name,
                interface,
            ),
            Some((&name, interface)),
            &interface_exports,
        )?);
    }

    Ok(result)
}

/// Generates the implementation of a `Guest` trait for the component, implementing the exported functions.
///
/// The `guest_trait` parameter is a Rust snippet containing the fully-qualified path to the `Guest` trait to
/// be implemented.
///
/// If there are resources in the interface, the return contains all the trait implementations, for the interface
/// and the resources as well.
fn generate_guest_impl(
    context: &GeneratorContext<'_>,
    guest_trait: TokenStream,
    interface: Option<(&str, &Interface)>,
    exports: &[(String, &Function)],
) -> anyhow::Result<Vec<TokenStream>> {
    let mut func_impls = Vec::new();
    let mut resource_impls = Vec::new();
    let mut resource_functions = BTreeMap::new();

    for (name, function) in exports {
        match &function.kind {
            FunctionKind::Freestanding => {
                if name == "wizer-initialize" {
                    // wizer-initialize calls directly into the skeleton's
                    // pre-init function instead of dispatching to JS
                    func_impls.push(quote! {
                        fn wizer_initialize() {
                            crate::internal::wizer_initialize();
                        }
                    });
                } else {
                    let func_impl =
                        generate_exported_function_impl(context, interface, name, function)?;
                    func_impls.push(func_impl);
                }
            }
            FunctionKind::AsyncFreestanding
            | FunctionKind::AsyncMethod(_)
            | FunctionKind::AsyncStatic(_) => {
                Err(anyhow!("Async exported functions are not supported yet"))?
            }
            FunctionKind::Method(type_id)
            | FunctionKind::Static(type_id)
            | FunctionKind::Constructor(type_id) => {
                resource_functions
                    .entry(type_id)
                    .or_insert_with(Vec::new)
                    .push((name, function));
            }
        }
    }

    let mut resource_types = Vec::new();
    for (resource_type_id, resource_funcs) in resource_functions {
        let typ = context
            .resolve
            .types
            .get(*resource_type_id)
            .ok_or_else(|| anyhow!("Unknown resource type id"))?;

        let resource_name = typ
            .name
            .as_ref()
            .ok_or_else(|| anyhow!("Resource type has no name"))?;
        let resource_name_ident =
            Ident::new(&resource_name.to_upper_camel_case(), Span::call_site());
        let resource_name_borrow_ident = Ident::new(
            &format!("{}Borrow", resource_name.to_upper_camel_case()),
            Span::call_site(),
        );
        let guest_name_ident = Ident::new(
            &format!("Guest{}", resource_name.to_upper_camel_case()),
            Span::call_site(),
        );
        let guest_trait =
            ident_in_exported_interface_or_global(context, guest_name_ident, interface);

        let borrow_wrapper =
            ident_in_exported_interface_or_global(context, resource_name_borrow_ident, interface);
        let owned_wrapper =
            ident_in_exported_interface_or_global(context, resource_name_ident.clone(), interface);

        let mut resource_func_impls = Vec::new();
        for (name, resource_function) in resource_funcs {
            let func_impl = generate_exported_resource_function_impl(
                context,
                interface,
                resource_type_id,
                name,
                resource_function,
            )?;
            resource_func_impls.push(func_impl);
        }

        resource_impls.push(quote! {
            struct #resource_name_ident {
                resource_id: usize
            }

            impl #guest_trait for #resource_name_ident {
                #(#resource_func_impls)*
            }

            impl Drop for #resource_name_ident {
                fn drop(&mut self) {
                    crate::internal::enqueue_drop_js_resource(self.resource_id);
                }
            }

            impl<'js> rquickjs::IntoJs<'js> for #borrow_wrapper<'_> {
                fn into_js(self, ctx: &rquickjs::Ctx<'js>) -> rquickjs::Result<rquickjs::Value<'js>> {
                    let inner: &#resource_name_ident = self.get();
                    let resource_table: rquickjs::Object = ctx.globals().get(crate::internal::RESOURCE_TABLE_NAME)
                        .expect("Failed to get the resource table");
                    let resource_instance: rquickjs::Object = resource_table.get(inner.resource_id.to_string())
                        .expect(&format!("Failed to get resource instance with id {}", inner.resource_id));
                    Ok(resource_instance.into_value())
                }
            }

            impl<'js> rquickjs::IntoJs<'js> for #owned_wrapper {
                fn into_js(self, ctx: &rquickjs::Ctx<'js>) -> rquickjs::Result<rquickjs::Value<'js>> {
                    let inner: &#resource_name_ident = self.get();
                    let resource_table: rquickjs::Object = ctx.globals().get(crate::internal::RESOURCE_TABLE_NAME)
                        .expect("Failed to get the resource table");
                    let resource_instance: rquickjs::Object = resource_table.get(inner.resource_id.to_string())
                        .expect(&format!("Failed to get resource instance with id {}", inner.resource_id));
                    Ok(resource_instance.into_value())
                }
            }

            impl<'js> rquickjs::FromJs<'js> for #owned_wrapper {
                fn from_js(ctx: &rquickjs::Ctx<'js>, value: rquickjs::Value<'js>) -> rquickjs::Result<Self> {
                    let resource = value.into_object().ok_or_else(|| {
                        rquickjs::Error::new_from_js_message(
                            "JS Resource instance",
                            "WASM resource instance",
                            "The value is not an object",
                        )
                    })?;

                    let already_registered = resource.contains_key(crate::internal::RESOURCE_ID_KEY)?;
                    let resource_id: usize = if already_registered {
                        // This resource instance is already registered in the resource table
                        resource.get(crate::internal::RESOURCE_ID_KEY)?
                    } else {
                        // This is a new resource instance, we need to store it in the resource table
                        let resource_table: rquickjs::Object = ctx.globals().get(crate::internal::RESOURCE_TABLE_NAME)?;
                        let resource_id = crate::internal::get_free_resource_id();
                        resource_table.set(resource_id.to_string(), resource)?;
                        resource_id
                    };

                    Ok(#owned_wrapper::new(#resource_name_ident { resource_id }))
                }
            }
        });

        resource_types.push(quote! {
            type #resource_name_ident = #resource_name_ident;
        })
    }

    let mut guest_impls = Vec::new();
    guest_impls.extend(resource_impls);
    guest_impls.push(quote! {
        impl #guest_trait for Component {
            #(#resource_types)*
            #(#func_impls)*
        }
    });

    Ok(guest_impls)
}

/// Generates one trait method implementation for an exported freestanding function
fn generate_exported_function_impl(
    context: &GeneratorContext<'_>,
    interface: Option<(&str, &Interface)>,
    name: &str,
    function: &Function,
) -> anyhow::Result<TokenStream> {
    let rust_fn = RustWitFunction::new(context, name, function);
    let func_name = rust_fn.function_name_ident();

    let param_ident_type: Vec<_> = function
        .params
        .iter()
        .zip(rust_fn.export_parameters.clone())
        .zip(rust_fn.import_parameters.clone())
        .map(
            |(((param_name, param_type), export_parameter), import_parameter)| {
                process_parameter(
                    context,
                    param_name,
                    param_type,
                    &export_parameter,
                    &import_parameter,
                )
            },
        )
        .collect::<anyhow::Result<Vec<_>>>()?;

    let func_arg_list = to_original_func_arg_list(&param_ident_type);
    let return_types = get_return_type(context, function, name, &rust_fn)?;

    let param_refs = to_wrapped_param_refs(&param_ident_type);
    let param_refs_tuple = param_refs_as_tuple(&param_refs);

    let js_func_name_str = Lit::Str(LitStr::new(
        &escape_js_ident(name.to_lower_camel_case()),
        func_name.span(),
    ));
    let (js_func_path, wit_package_lit) = match interface {
        Some((iface_name, iface)) => {
            let if_name_str = LitStr::new(
                &escape_js_ident(iface_name.to_lower_camel_case()),
                func_name.span(),
            );

            let owner_package_name = match iface.package {
                Some(package_id) => {
                    let package = context.resolve.packages.get(package_id).ok_or_else(|| {
                        anyhow!("Unknown owner package of interface: {iface_name}")
                    })?;
                    package.name.to_string()
                }
                None => context.root_package_name().to_string(),
            };

            (
                quote! { &[#if_name_str, #js_func_name_str] },
                Lit::Str(LitStr::new(&owner_package_name, Span::call_site())),
            )
        }
        None => (
            quote! { &[#js_func_name_str] },
            Lit::Str(LitStr::new(&context.root_package_name(), Span::call_site())),
        ),
    };

    let original_result = &return_types.wit_level_ret.original_type_ref;
    let wrapped_result = &return_types.wit_level_ret.wrapped_type_ref;
    let unwrap = &return_types.wit_level_ret.unwrap;
    let unwrap_result = unwrap.run(quote! { result });
    let call = if return_types.expected_exception.is_some() {
        quote! { call_js_export_returning_result }
    } else {
        quote! { call_js_export }
    };
    let func_impl = quote! {
       fn #func_name(#(#func_arg_list),*) -> #original_result {
           crate::internal::async_exported_function(async move {
               let result: #wrapped_result = crate::internal::#call(
                   #wit_package_lit,
                   #js_func_path,
                   #param_refs_tuple
               ).await;
               #unwrap_result
           })
       }
    };
    Ok(func_impl)
}

/// Generates one trait method implementation for an exported freestanding function
fn generate_exported_resource_function_impl(
    context: &GeneratorContext<'_>,
    interface: Option<(&str, &Interface)>,
    resource_type_id: &TypeId,
    name: &str,
    function: &Function,
) -> anyhow::Result<TokenStream> {
    let func_name = get_function_name(name, function)?;

    let rust_fn = RustWitFunction::new(context, &func_name, function);
    let func_name_ident = rust_fn.function_name_ident();

    let param_ident_type: Vec<_> = function
        .params
        .iter()
        .zip(rust_fn.export_parameters.clone())
        .zip(rust_fn.import_parameters.clone())
        .map(|(((param_name, param_type), export_param), import_param)| {
            if matches!(
                function.kind,
                FunctionKind::Method(_) | FunctionKind::AsyncMethod(_)
            ) && type_borrows_resource(context, param_type, resource_type_id)?
            {
                Ok(ProcessedParameter {
                    ident: Ident::new(param_name, Span::call_site()),
                    wrapped_type: None,
                    export_parameter: export_param,
                    import_parameter: import_param,
                })
            } else {
                process_parameter(
                    context,
                    param_name,
                    param_type,
                    &export_param,
                    &import_param,
                )
            }
        })
        .collect::<anyhow::Result<Vec<_>>>()?;

    let func_arg_list = to_original_func_arg_list(&param_ident_type);
    let return_types = if matches!(function.kind, FunctionKind::Constructor(_)) {
        ReturnTypeInformation {
            wit_level_ret: WrappedType::no_wrapping(quote! { Self }),
            func_ret: WrappedType::no_wrapping(quote! { Self }),
            expected_exception: None,
        }
    } else {
        get_return_type(context, function, name, &rust_fn)?
    };

    let param_refs = to_wrapped_param_refs(&param_ident_type);

    let resource_name = context
        .resolve
        .types
        .get(*resource_type_id)
        .ok_or_else(|| anyhow::anyhow!("Unknown resource type id"))?
        .name
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("Resource type has no name"))?;

    let js_resource_name_str = Lit::Str(LitStr::new(
        &resource_name.to_upper_camel_case(),
        Span::call_site(),
    ));
    let (js_resource_path, wit_package_lit) = match interface {
        Some((iface_name, iface)) => {
            let if_name_str = LitStr::new(
                &escape_js_ident(iface_name.to_lower_camel_case()),
                Span::call_site(),
            );

            let owner_package_name = match iface.package {
                Some(package_id) => {
                    let package = context.resolve.packages.get(package_id).ok_or_else(|| {
                        anyhow!("Unknown owner package of interface: {iface_name}")
                    })?;
                    package.name.to_string()
                }
                None => context.root_package_name().to_string(),
            };

            (
                quote! { &[#if_name_str, #js_resource_name_str] },
                Lit::Str(LitStr::new(&owner_package_name, Span::call_site())),
            )
        }
        None => (
            quote! { &[#js_resource_name_str] },
            Lit::Str(LitStr::new(&context.root_package_name(), Span::call_site())),
        ),
    };

    let js_func_name_str = Lit::Str(LitStr::new(
        &escape_js_ident(func_name.to_lower_camel_case()),
        Span::call_site(),
    ));
    let js_static_func_path = match interface {
        Some((iface_name, _)) => {
            let if_name_str = LitStr::new(
                &escape_js_ident(iface_name.to_lower_camel_case()),
                Span::call_site(),
            );
            quote! { &[#if_name_str, #js_resource_name_str, #js_func_name_str] }
        }
        None => quote! { &[#js_func_name_str] },
    };

    let func_impl = match &function.kind {
        FunctionKind::Constructor(_) => {
            let param_refs_tuple = param_refs_as_tuple(&param_refs);

            quote! {
              fn #func_name_ident(#(#func_arg_list),*) -> Self {
                  crate::internal::async_exported_function(async move {
                    let resource_id = crate::internal::call_js_resource_constructor(
                         #wit_package_lit,
                         #js_resource_path,
                         #param_refs_tuple,
                    ).await;
                    Self {
                        resource_id
                    }
                  })
              }
            }
        }
        FunctionKind::Method(_) => {
            let param_refs = param_refs[1..].to_vec();
            let param_refs_tuple = param_refs_as_tuple(&param_refs);
            let original_result = &return_types.func_ret.original_type_ref;
            let wrapped_result = &return_types.func_ret.wrapped_type_ref;
            let unwrap = &return_types.func_ret.unwrap;
            let unwrap_result = unwrap.run(quote! { result });
            let call = if return_types.expected_exception.is_some() {
                quote! { call_js_resource_method_returning_result }
            } else {
                quote! { call_js_resource_method }
            };
            quote! {
               fn #func_name_ident(#(#func_arg_list),*) -> #original_result {
                   crate::internal::async_exported_function(async move {
                       let result: #wrapped_result = crate::internal::#call(
                            #wit_package_lit,
                            #js_resource_path,
                            self.resource_id,
                            #js_func_name_str,
                            #param_refs_tuple,
                       ).await;
                       #unwrap_result
                   })
               }
            }
        }
        FunctionKind::Static(_) => {
            let param_refs_tuple = param_refs_as_tuple(&param_refs);
            let original_result = &return_types.wit_level_ret.original_type_ref;
            let wrapped_result = &return_types.wit_level_ret.wrapped_type_ref;
            let unwrap = &return_types.wit_level_ret.unwrap;
            let unwrap_result = unwrap.run(quote! { result });
            let call = if return_types.expected_exception.is_some() {
                quote! { call_js_export_returning_result }
            } else {
                quote! { call_js_export }
            };
            quote! {
               fn #func_name_ident(#(#func_arg_list),*) -> #original_result {
                   crate::internal::async_exported_function(async move {
                       let result: #wrapped_result = crate::internal::#call(
                           #wit_package_lit,
                           #js_static_func_path,
                           #param_refs_tuple,
                       ).await;
                       #unwrap_result
                   })
               }
            }
        }
        FunctionKind::AsyncMethod(_) | FunctionKind::AsyncStatic(_) => Err(anyhow::anyhow!(
            "Async exported functions are not supported yet",
        ))?,
        FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => Err(anyhow::anyhow!(
            "Freestanding functions are not expected in resource methods",
        ))?,
    };

    Ok(func_impl)
}

fn generate_module_defs(js_modules: &[JsModuleSpec]) -> anyhow::Result<TokenStream> {
    if let Some((export_module, additional_modules)) = js_modules.split_first() {
        let export_module_name = LitStr::new(&export_module.name, Span::call_site());
        let export_module_file_name = LitStr::new(&export_module.file_name(), Span::call_site());

        let mut additional_module_pairs = Vec::new();
        for module in additional_modules {
            match module.mode {
                EmbeddingMode::EmbedFile(_) => {
                    let name = LitStr::new(&module.name, Span::call_site());
                    let file_name = LitStr::new(&module.file_name(), Span::call_site());
                    additional_module_pairs
                        .push(quote! { (#name, Box::new(|| { include_str!(#file_name) })) });
                }
                EmbeddingMode::Composition => {
                    let name = LitStr::new(&module.name, Span::call_site());
                    additional_module_pairs
                        .push(quote! { (#name, Box::new(|| { crate::bindings::get_script() })) });
                }
            }
        }

        Ok(quote! {
            static JS_EXPORT_MODULE_NAME: &str = #export_module_name;
            static JS_EXPORT_MODULE: &str = include_str!(#export_module_file_name);

            static JS_ADDITIONAL_MODULES: std::sync::LazyLock<Vec<(&str, Box<dyn (Fn() -> String) + Send + Sync>)>> =
              std::sync::LazyLock::new(|| { vec![
                 #(#additional_module_pairs),*
              ]});
        })
    } else {
        Err(anyhow!("No JS modules provided."))?
    }
}