boa_macros 0.21.1

Macros for the Boa JavaScript 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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! Macros for the Boa JavaScript engine.
#![doc = include_str!("../ABOUT.md")]
#![doc(
    html_logo_url = "https://raw.githubusercontent.com/boa-dev/boa/main/assets/logo_black.svg",
    html_favicon_url = "https://raw.githubusercontent.com/boa-dev/boa/main/assets/logo_black.svg"
)]
#![cfg_attr(not(test), forbid(clippy::unwrap_used))]

use crate::utils::RenameScheme;
use cow_utils::CowUtils;
use proc_macro::TokenStream;
use proc_macro2::Literal;
use quote::{ToTokens, quote};
use syn::{
    Data, DeriveInput, Expr, ExprLit, Fields, FieldsNamed, Ident, Lit, LitStr, Token,
    parse::{Parse, ParseStream},
    parse_macro_input,
    punctuated::Punctuated,
};
use synstructure::{AddBounds, Structure, decl_derive};

mod embedded_module_loader;

mod class;
mod module;
mod utils;
mod value;

/// The `js_value!` macro creates a `JsValue` instance based on a JSON-like DSL.
#[proc_macro]
pub fn js_value(input: TokenStream) -> TokenStream {
    value::js_value_impl(proc_macro2::TokenStream::from(input)).into()
}

/// Create a `JsObject` object from a simpler DSL that resembles JSON.
#[proc_macro]
pub fn js_object(input: TokenStream) -> TokenStream {
    value::js_object_impl(proc_macro2::TokenStream::from(input)).into()
}

/// Implementation of the inner iterator of the `embed_module!` macro. All
/// arguments are required.
///
/// # Warning
/// This should not be used directly as is, and instead should be used through
/// the `embed_module!` macro in `boa_engine` for convenience.
#[proc_macro]
pub fn embed_module_inner(input: TokenStream) -> TokenStream {
    embedded_module_loader::embed_module_impl(input)
}

/// `boa_class` proc macro attribute that applies to an `impl XYZ` block and
/// add a `[boa_engine::JsClass]` implementation for it.
///
/// It will transform functions in the `impl ...` block as follow (by default, see
/// below):
/// 1. `fn some_method(&self, ...) -> ... {}` will be added as class methods with
///    the name `some_method`, borrowing the object for the ref. This is dangerous
///    if the function execute/eval JavaScript back (potentially leading to a
///    `BorrowError`).
/// 2. `fn some_method(&mut self, ...) -> ... {}` will be added as class methods,
///    similar to the above but borrowing as mutable at runtime.
/// 3. `fn some_method(...) -> ... {}` (no self mention) will be added as a
///    static method.
/// 4. `#[boa(constructor)] fn ...(...) -> Self {}` (or returning `JsResult<Self>`)
///    will be used as the constructor of the class. If no constructor is declared,
///    `Default::default()` will be used instead. If the `Default` trait is not
///    defined for the type, an error will happen.
/// 5. `#[boa(getter)]`
///
/// To change this behaviour, you can use the following attributes on the function
/// declarations:
/// 1. `#[boa(rename = "...")]` renames the function in JavaScript with the string.
/// 2. `#[boa(getter)]` will declare a getter accessor.
/// 2. `#[boa(setter)]` will declare a setter accessor.
/// 3. `#[boa(static)]` will declare a static method.
/// 4. `#[boa(method)]` will declare a method.
/// 5. `#[boa(constructor)]` will declare a constructor.
/// 6. `#[boa(length = 123)]` sets the length of the function in JavaScript (ie. its
///    number of arguments accepted).
///
/// Multiple of those attributes can be added to a single method.
///
/// The top level `boa_class` supports the following:
/// 1. `#[boa_class(rename = "...")]` sets the name of the class in JavaScript.
/// 2. `#[boa(rename_all = "camelCase")]` will change the naming scheme of verbatim
///    to using "camelCase" or "none".
///
/// # Warning
/// This should not be used directly as is, and instead should be used through
/// the `embed_module!` macro in `boa_engine` for convenience.
#[proc_macro_attribute]
pub fn boa_class(attr: TokenStream, item: TokenStream) -> TokenStream {
    class::class_impl(attr, item)
}

/// `boa_module` proc macro attribute for declaring a `boa_engine::Module` based
/// on a Rust module. The original Rust module will also be exposed as is.
///
/// This macro exports two functions out of the existing module (and those
/// functions must not exist in the declared module):
///
/// ## `boa_module(realm: Option<Realm>, context: &mut Context) -> JsResult<Module>`
/// Create a JavaScript module from the rust module's content.
///
/// ## `boa_register(realm: Option<Realm>, context: &mut Context) -> JsResult<()>`
/// Register the constants, classes and functions from the module in the global
/// scope of the Realm (if specified) or the context (if no realm).
#[proc_macro_attribute]
pub fn boa_module(attr: TokenStream, item: TokenStream) -> TokenStream {
    module::module_impl(attr, item)
}

struct Static {
    literal: LitStr,
    ident: Ident,
}

impl Parse for Static {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let expr = Expr::parse(input)?;
        match expr {
            Expr::Tuple(expr) => {
                let mut elems = expr.elems.iter().cloned();
                let literal = elems
                    .next()
                    .ok_or_else(|| syn::Error::new_spanned(&expr, "invalid empty tuple"))?;
                let ident = elems.next();
                if elems.next().is_some() {
                    return Err(syn::Error::new_spanned(
                        &expr,
                        "invalid tuple with more than two elements",
                    ));
                }
                let Expr::Lit(ExprLit {
                    lit: Lit::Str(literal),
                    ..
                }) = literal
                else {
                    return Err(syn::Error::new_spanned(
                        literal,
                        "expected an UTF-8 string literal",
                    ));
                };

                let ident = if let Some(ident) = ident {
                    syn::parse2::<Ident>(ident.into_token_stream())?
                } else {
                    Ident::new(&literal.value().cow_to_uppercase(), literal.span())
                };

                Ok(Self { literal, ident })
            }
            Expr::Lit(expr) => match expr.lit {
                Lit::Str(str) => Ok(Self {
                    ident: Ident::new(&str.value().cow_to_uppercase(), str.span()),
                    literal: str,
                }),
                _ => Err(syn::Error::new_spanned(
                    expr,
                    "expected an UTF-8 string literal",
                )),
            },
            _ => Err(syn::Error::new_spanned(
                expr,
                "expected a string literal or a tuple expression",
            )),
        }
    }
}

struct Syms(Vec<Static>);

impl Parse for Syms {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let parsed = Punctuated::<Static, Token![,]>::parse_terminated(input)?;
        let literals = parsed.into_iter().collect();
        Ok(Self(literals))
    }
}

#[doc(hidden)]
#[proc_macro]
pub fn static_syms(input: TokenStream) -> TokenStream {
    let literals = parse_macro_input!(input as Syms).0;

    let consts = literals.iter().enumerate().map(|(mut idx, lit)| {
        let doc = format!(
            "Symbol for the \"{}\" string.",
            lit.literal
                .value()
                .cow_replace('<', r"\<")
                .cow_replace('>', r"\>")
                .cow_replace('*', r"\*")
        );
        let ident = &lit.ident;
        idx += 1;
        quote! {
            #[doc = #doc]
            pub const #ident: Self = unsafe { Self::new_unchecked(#idx) };
        }
    });

    let literals = literals.iter().map(|lit| &lit.literal).collect::<Vec<_>>();

    let caches = quote! {
        type Set<T> = ::indexmap::IndexSet<T, ::core::hash::BuildHasherDefault<::rustc_hash::FxHasher>>;

        /// Ordered set of commonly used static `UTF-8` strings.
        ///
        /// # Note
        ///
        /// `COMMON_STRINGS_UTF8`, `COMMON_STRINGS_UTF16` and the constants
        /// defined in [`Sym`] must always be in sync.
        pub(super) static COMMON_STRINGS_UTF8: ::phf::OrderedSet<&'static str> = {
            const COMMON_STRINGS: ::phf::OrderedSet<&'static str> = ::phf::phf_ordered_set! {
                #(#literals),*
            };
            // A `COMMON_STRINGS` of size `usize::MAX` would cause an overflow on our `Interner`
            ::static_assertions::const_assert!(COMMON_STRINGS.len() < usize::MAX);
            COMMON_STRINGS
        };

        /// Ordered set of commonly used static `UTF-16` strings.
        ///
        /// # Note
        ///
        /// `COMMON_STRINGS_UTF8`, `COMMON_STRINGS_UTF16` and the constants
        /// defined in [`Sym`] must always be in sync.
        // FIXME: use phf when const expressions are allowed.
        // <https://github.com/rust-phf/rust-phf/issues/188>
        pub(super) static COMMON_STRINGS_UTF16: ::once_cell::sync::Lazy<Set<&'static [u16]>> =
            ::once_cell::sync::Lazy::new(|| {
                let mut set = Set::with_capacity_and_hasher(
                    COMMON_STRINGS_UTF8.len(),
                    ::core::hash::BuildHasherDefault::default()
                );
                #(
                    set.insert(::boa_macros::utf16!(#literals));
                )*
                set
            });
    };

    quote! {
        impl Sym {
            #(#consts)*
        }
        #caches
    }
    .into()
}

/// Construct a utf-16 array literal from a utf-8 [`str`] literal.
#[proc_macro]
pub fn utf16(input: TokenStream) -> TokenStream {
    let literal = parse_macro_input!(input as LitStr);
    let utf8 = literal.value();
    let utf16 = utf8.encode_utf16().collect::<Vec<_>>();
    quote! {
        [#(#utf16),*].as_slice()
    }
    .into()
}

/// Convert a utf8 string literal to a `JsString`
#[proc_macro]
pub fn js_str(input: TokenStream) -> TokenStream {
    let literal = parse_macro_input!(input as LitStr);

    let mut is_latin1 = true;
    let codepoints = literal
        .value()
        .encode_utf16()
        .map(|x| {
            if x > u8::MAX.into() {
                is_latin1 = false;
            }
            Literal::u16_unsuffixed(x)
        })
        .collect::<Vec<_>>();
    if is_latin1 {
        quote! {
            ::boa_engine::string::JsStr::latin1([#(#codepoints),*].as_slice())
        }
    } else {
        quote! {
            ::boa_engine::string::JsStr::utf16([#(#codepoints),*].as_slice())
        }
    }
    .into()
}

decl_derive! {
    [Trace, attributes(boa_gc, unsafe_ignore_trace)] =>
    /// Derive the `Trace` trait.
    derive_trace
}

/// Derives the `Trace` trait.
#[allow(clippy::too_many_lines)]
fn derive_trace(mut s: Structure<'_>) -> proc_macro2::TokenStream {
    struct EmptyTrace {
        copy: bool,
        drop: bool,
    }

    impl Parse for EmptyTrace {
        fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
            let i: Ident = input.parse()?;

            if i != "empty_trace" && i != "unsafe_empty_trace" && i != "unsafe_no_drop" {
                let msg = format!(
                    "expected token \"empty_trace\", \"unsafe_empty_trace\" or \"unsafe_no_drop\", found {i:?}"
                );
                return Err(syn::Error::new_spanned(i.clone(), msg));
            }

            Ok(Self {
                copy: i == "empty_trace",
                drop: i == "empty_trace" || i != "unsafe_no_drop",
            })
        }
    }

    let mut drop = true;

    for attr in &s.ast().attrs {
        if attr.path().is_ident("boa_gc") {
            let trace = match attr.parse_args::<EmptyTrace>() {
                Ok(t) => t,
                Err(e) => return e.into_compile_error(),
            };

            if trace.copy {
                s.add_where_predicate(syn::parse_quote!(Self: Copy));
            }

            if !trace.drop {
                drop = false;
                continue;
            }

            return s.unsafe_bound_impl(
                quote!(::boa_gc::Trace),
                quote! {
                    #[inline(always)]
                    unsafe fn trace(&self, _tracer: &mut ::boa_gc::Tracer) {}
                    #[inline(always)]
                    unsafe fn trace_non_roots(&self) {}
                    #[inline]
                    fn run_finalizer(&self) {
                        ::boa_gc::Finalize::finalize(self)
                    }
                },
            );
        }
    }

    s.filter(|bi| {
        !bi.ast()
            .attrs
            .iter()
            .any(|attr| attr.path().is_ident("unsafe_ignore_trace"))
    });
    let trace_body = s.each(|bi| quote!(::boa_gc::Trace::trace(#bi, tracer)));
    let trace_other_body = s.each(|bi| quote!(mark(#bi)));

    s.add_bounds(AddBounds::Fields);
    let trace_impl = s.unsafe_bound_impl(
        quote!(::boa_gc::Trace),
        quote! {
            #[inline]
            unsafe fn trace(&self, tracer: &mut ::boa_gc::Tracer) {
                #[allow(dead_code)]
                let mut mark = |it: &dyn ::boa_gc::Trace| {
                    // SAFETY: The implementor must ensure that `trace` is correctly implemented.
                    unsafe {
                        ::boa_gc::Trace::trace(it, tracer);
                    }
                };
                match *self { #trace_body }
            }
            #[inline]
            unsafe fn trace_non_roots(&self) {
                #[allow(dead_code)]
                fn mark<T: ::boa_gc::Trace + ?Sized>(it: &T) {
                    // SAFETY: The implementor must ensure that `trace_non_roots` is correctly implemented.
                    unsafe {
                        ::boa_gc::Trace::trace_non_roots(it);
                    }
                }
                match *self { #trace_other_body }
            }
            #[inline]
            fn run_finalizer(&self) {
                ::boa_gc::Finalize::finalize(self);
                #[allow(dead_code)]
                fn mark<T: ::boa_gc::Trace + ?Sized>(it: &T) {
                    unsafe {
                        ::boa_gc::Trace::run_finalizer(it);
                    }
                }
                match *self { #trace_other_body }
            }
        },
    );

    // We also implement drop to prevent unsafe drop implementations on this
    // type and encourage people to use Finalize. This implementation will
    // call `Finalize::finalize` if it is safe to do so.
    let drop_impl = if drop {
        s.unbound_impl(
            quote!(::core::ops::Drop),
            quote! {
                #[allow(clippy::inline_always)]
                #[inline(always)]
                fn drop(&mut self) {
                    if ::boa_gc::finalizer_safe() {
                        ::boa_gc::Finalize::finalize(self);
                    }
                }
            },
        )
    } else {
        quote!()
    };

    quote! {
        #trace_impl
        #drop_impl
    }
}

decl_derive! {
    [Finalize] =>
    /// Derive the `Finalize` trait.
    derive_finalize
}

/// Derives the `Finalize` trait.
#[allow(clippy::needless_pass_by_value)]
fn derive_finalize(s: Structure<'_>) -> proc_macro2::TokenStream {
    s.unbound_impl(quote!(::boa_gc::Finalize), quote!())
}

decl_derive! {
    [JsData] =>
    /// Derive the `JsData` trait.
    derive_js_data
}

/// Derives the `JsData` trait.
#[allow(clippy::needless_pass_by_value)]
fn derive_js_data(s: Structure<'_>) -> proc_macro2::TokenStream {
    s.unbound_impl(quote!(::boa_engine::JsData), quote!())
}

/// Derives the `TryFromJs` trait, with the `#[boa()]` attribute.
///
/// # Panics
///
/// It will panic if the user tries to derive the `TryFromJs` trait in an `enum` or a tuple struct.
#[proc_macro_derive(TryFromJs, attributes(boa))]
pub fn derive_try_from_js(input: TokenStream) -> TokenStream {
    // Parse the input tokens into a syntax tree
    let input = parse_macro_input!(input as DeriveInput);

    let Data::Struct(data) = input.data else {
        panic!("you can only derive TryFromJs for structs");
    };

    let Fields::Named(fields) = data.fields else {
        panic!("you can only derive TryFromJs for named-field structs")
    };

    let renaming = match RenameScheme::from_named_attrs(&mut input.attrs.clone(), "rename_all") {
        Ok(renaming) => renaming.unwrap_or(RenameScheme::None),
        Err((span, msg)) => return syn::Error::new(span, msg).to_compile_error().into(),
    };

    let conv = generate_conversion(fields, renaming).unwrap_or_else(to_compile_errors);

    let type_name = input.ident;

    // Build the output, possibly using quasi-quotation
    let expanded = quote! {
        impl ::boa_engine::value::TryFromJs for #type_name {
            fn try_from_js(value: &boa_engine::JsValue, context: &mut boa_engine::Context)
                -> boa_engine::JsResult<Self> {
                let o = value.as_object().ok_or_else(|| ::boa_engine::JsError::from(
                    ::boa_engine::JsNativeError::typ()
                        .with_message("value is not an object")
                ))?;
                #conv
            }
        }
    };

    // Hand the output tokens back to the compiler
    expanded.into()
}

/// Generates the conversion field by field.
fn generate_conversion(
    fields: FieldsNamed,
    rename: RenameScheme,
) -> Result<proc_macro2::TokenStream, Vec<syn::Error>> {
    use syn::spanned::Spanned;

    let mut field_list = Vec::with_capacity(fields.named.len());
    let mut final_fields = Vec::with_capacity(fields.named.len());

    for field in fields.named {
        let span = field.span();
        let name = field.ident.ok_or_else(|| {
            vec![syn::Error::new(
                span,
                "you can only derive `TryFromJs` for named-field structs",
            )]
        })?;

        field_list.push(name.clone());

        let mut from_js_with = None;
        let mut field_name = rename.rename(format!("{name}"));
        if let Some(attr) = field
            .attrs
            .into_iter()
            .find(|attr| attr.path().is_ident("boa"))
        {
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("from_js_with") {
                    let value = meta.value()?;
                    from_js_with = Some(value.parse::<LitStr>()?);
                    Ok(())
                } else if meta.path.is_ident("rename") {
                    let value = meta.value()?;
                    field_name = value.parse::<LitStr>()?.value();
                    Ok(())
                } else {
                    Err(meta.error(
                        "invalid syntax in the `#[boa()]` attribute. \
                              Note that this attribute only accepts the following syntax: \
                            `#[boa(from_js_with = \"fully::qualified::path\")]`",
                    ))
                }
            })
            .map_err(|err| vec![err])?;
        }

        let error_str = format!("cannot get property {name} of value");
        final_fields.push(quote! {
            let #name = match props.get(&::boa_engine::js_string!(#field_name).into()) {
                Some(pd) => pd.value().ok_or_else(|| ::boa_engine::JsError::from(
                        ::boa_engine::JsNativeError::typ().with_message(#error_str)
                    ))?.clone().try_js_into(context)?,
                None => ::boa_engine::JsValue::undefined().try_js_into(context)?,
            };
        });

        if let Some(method) = from_js_with {
            let ident = Ident::new(&method.value(), method.span());
            final_fields.push(quote! {
                let #name = #ident(&#name, context)?;
            });
        }
    }

    // TODO: this could possibly skip accessors. Consider using `JsObject::get` instead.
    Ok(quote! {
        let o = o.borrow();
        let props = o.properties();
        #(#final_fields)*
        Ok(Self {
            #(#field_list),*
        })
    })
}

/// Generates a list of compile errors.
#[allow(clippy::needless_pass_by_value)]
fn to_compile_errors(errors: Vec<syn::Error>) -> proc_macro2::TokenStream {
    let compile_errors = errors.iter().map(syn::Error::to_compile_error);
    quote!(#(#compile_errors)*)
}

/// Derives the `TryIntoJs` trait, with the `#[boa()]` attribute.
///
/// # Panics
///
/// It will panic if the user tries to derive the `TryIntoJs` trait in an `enum` or a tuple struct.
#[proc_macro_derive(TryIntoJs, attributes(boa))]
pub fn derive_try_into_js(input: TokenStream) -> TokenStream {
    // Parse the input tokens into a syntax tree
    let input = parse_macro_input!(input as DeriveInput);

    let Data::Struct(data) = input.data else {
        panic!("you can only derive TryFromJs for structs");
    };
    // TODO: Enums ?

    let Fields::Named(fields) = data.fields else {
        panic!("you can only derive TryFromJs for named-field structs")
    };

    let renaming = match RenameScheme::from_named_attrs(&mut input.attrs.clone(), "rename_all") {
        Ok(renaming) => renaming.unwrap_or(RenameScheme::None),
        Err((span, msg)) => return syn::Error::new(span, msg).to_compile_error().into(),
    };

    let props = generate_obj_properties(fields, renaming)
        .map_err(|err| vec![err])
        .unwrap_or_else(to_compile_errors);

    let type_name = input.ident;

    // Build the output, possibly using quasi-quotation
    let expanded = quote! {
        impl ::boa_engine::value::TryIntoJs for #type_name {
            fn try_into_js(&self, context: &mut boa_engine::Context) -> boa_engine::JsResult<boa_engine::JsValue> {
                let obj = boa_engine::JsObject::default(context.intrinsics());
                #props
                boa_engine::JsResult::Ok(obj.into())
            }
        }
    };

    // Hand the output tokens back to the compiler
    expanded.into()
}

/// Generates property creation for object.
fn generate_obj_properties(
    fields: FieldsNamed,
    renaming: RenameScheme,
) -> Result<proc_macro2::TokenStream, syn::Error> {
    use syn::spanned::Spanned;

    let mut prop_ctors = Vec::with_capacity(fields.named.len());

    for field in fields.named {
        let span = field.span();
        let name = field.ident.ok_or_else(|| {
            syn::Error::new(
                span,
                "you can only derive `TryIntoJs` for named-field structs",
            )
        })?;

        let mut into_js_with = None;
        let mut prop_key = renaming.rename(format!("{name}"));
        let mut skip = false;

        for attr in field
            .attrs
            .into_iter()
            .filter(|attr| attr.path().is_ident("boa"))
        {
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("into_js_with") {
                    let value = meta.value()?;
                    into_js_with = Some(value.parse::<LitStr>()?);
                    Ok(())
                } else if meta.path.is_ident("rename") {
                    let value = meta.value()?;
                    prop_key = value.parse::<LitStr>()?.value();
                    Ok(())
                } else if meta.path.is_ident("skip") & meta.input.is_empty() {
                    skip = true;
                    Ok(())
                } else {
                    Err(meta.error(
                        "invalid syntax in the `#[boa()]` attribute. \
                              Note that this attribute only accepts the following syntax: \
                            \n* `#[boa(into_js_with = \"fully::qualified::path\")]`\
                            \n* `#[boa(rename = \"jsPropertyName\")]` \
                            \n* `#[boa(skip)]` \
                            ",
                    ))
                }
            })?;
        }

        if skip {
            continue;
        }

        let value = if let Some(into_js_with) = into_js_with {
            let into_js_with = Ident::new(&into_js_with.value(), into_js_with.span());
            quote! { #into_js_with(&self.#name, context)? }
        } else {
            quote! { boa_engine::value::TryIntoJs::try_into_js(&self.#name, context)? }
        };
        prop_ctors.push(quote! {
            obj.create_data_property_or_throw(boa_engine::js_string!(#prop_key), #value, context)?;
        });
    }

    Ok(quote! { #(#prop_ctors)* })
}