rquickjs-macro 0.11.0

Procedural macros for rquickjs
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
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote};
use syn::{
    fold::Fold,
    parse::{Parse, ParseStream},
    punctuated::{Pair, Punctuated},
    spanned::Spanned,
    Error, ItemEnum, ItemStruct, LitStr, Result, Token,
};

use crate::{
    attrs::{take_attributes, FlagOption, OptionList, ValueOption},
    common::{add_js_lifetime, crate_ident, kw, Case},
    fields::Fields,
};

#[derive(Debug, Default, Clone)]
pub(crate) struct ClassConfig {
    pub frozen: bool,
    pub crate_: Option<String>,
    pub rename: Option<String>,
    pub rename_all: Option<Case>,
}

pub(crate) enum ClassOption {
    Frozen(FlagOption<kw::frozen>),
    Crate(ValueOption<Token![crate], LitStr>),
    Rename(ValueOption<kw::rename, LitStr>),
    RenameAll(ValueOption<kw::rename_all, Case>),
}

impl Parse for ClassOption {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        if input.peek(kw::frozen) {
            input.parse().map(Self::Frozen)
        } else if input.peek(Token![crate]) {
            input.parse().map(Self::Crate)
        } else if input.peek(kw::rename) {
            input.parse().map(Self::Rename)
        } else if input.peek(kw::rename_all) {
            input.parse().map(Self::RenameAll)
        } else {
            Err(syn::Error::new(input.span(), "invalid class attribute"))
        }
    }
}

impl ClassConfig {
    pub fn apply(&mut self, option: &ClassOption) {
        match option {
            ClassOption::Frozen(ref x) => {
                self.frozen = x.is_true();
            }
            ClassOption::Crate(ref x) => {
                self.crate_ = Some(x.value.value());
            }
            ClassOption::Rename(ref x) => {
                self.rename = Some(x.value.value());
            }
            ClassOption::RenameAll(ref x) => {
                self.rename_all = Some(x.value);
            }
        }
    }

    pub fn crate_name(&self) -> Result<String> {
        if let Some(c) = self.crate_.clone() {
            return Ok(c);
        }
        crate_ident()
    }
}

#[derive(Debug)]
pub(crate) enum Class {
    Enum {
        config: ClassConfig,
        attrs: Vec<syn::Attribute>,
        vis: syn::Visibility,
        enum_token: Token![enum],
        ident: Ident,
        generics: syn::Generics,
        variants: syn::punctuated::Punctuated<syn::Variant, Token![,]>,
    },
    Struct {
        config: ClassConfig,
        attrs: Vec<syn::Attribute>,
        vis: syn::Visibility,
        struct_token: Token![struct],
        ident: Ident,
        generics: syn::Generics,
        fields: Fields,
    },
}

struct ErrorAttribute(Result<()>);

impl Fold for ErrorAttribute {
    fn fold_attribute(&mut self, i: syn::Attribute) -> syn::Attribute {
        if self.0.is_err() {
            return i;
        }

        if i.path().is_ident("qjs") {
            self.0 = Err(Error::new(i.span(), "qjs attributes not supported here"))
        }
        i
    }
}

impl Class {
    pub fn from_proc_macro_input(
        options: OptionList<ClassOption>,
        item: syn::Item,
    ) -> Result<Self> {
        let mut config = ClassConfig::default();
        options.0.iter().for_each(|x| config.apply(x));

        match item {
            syn::Item::Enum(enum_) => Self::from_enum(config, enum_),
            syn::Item::Struct(struct_) => Self::from_struct(config, struct_),
            x => Err(Error::new(
                x.span(),
                "class macro can only be applied to enum's and struct",
            )),
        }
    }

    pub fn config(&self) -> &ClassConfig {
        match self {
            Class::Enum { ref config, .. } => config,
            Class::Struct { ref config, .. } => config,
        }
    }

    pub fn ident(&self) -> &Ident {
        match self {
            Class::Struct { ref ident, .. } => ident,
            Class::Enum { ref ident, .. } => ident,
        }
    }

    pub fn from_enum(mut config: ClassConfig, enum_: ItemEnum) -> Result<Self> {
        let ItemEnum {
            mut attrs,
            vis,
            enum_token,
            ident,
            generics,
            variants,
            ..
        } = enum_;

        let mut new_variants = Punctuated::new();
        for variant in variants.into_pairs() {
            match variant {
                Pair::Punctuated(v, c) => {
                    let mut ensure_valid = ErrorAttribute(Ok(()));
                    let v = ensure_valid.fold_variant(v);
                    ensure_valid.0?;

                    new_variants.push(v);
                    new_variants.push_punct(c);
                }
                Pair::End(v) => {
                    let mut ensure_valid = ErrorAttribute(Ok(()));
                    let v = ensure_valid.fold_variant(v);
                    ensure_valid.0?;

                    new_variants.push(v);
                }
            }
        }
        let variants = new_variants;

        take_attributes(&mut attrs, |attr| {
            if !attr.path().is_ident("qjs") {
                return Ok(false);
            }

            let options: OptionList<ClassOption> = attr.parse_args()?;
            options.0.iter().for_each(|x| {
                config.apply(x);
            });
            Ok(true)
        })?;

        Ok(Class::Enum {
            config,
            attrs,
            vis,
            enum_token,
            ident,
            generics,
            variants,
        })
    }

    pub fn from_struct(mut config: ClassConfig, struct_: ItemStruct) -> Result<Self> {
        let ItemStruct {
            mut attrs,
            vis,
            struct_token,
            ident,
            generics,
            fields,
            ..
        } = struct_;

        take_attributes(&mut attrs, |attr| {
            if !attr.path().is_ident("qjs") {
                return Ok(false);
            }

            let options: OptionList<ClassOption> = attr.parse_args()?;
            options.0.iter().for_each(|x| {
                config.apply(x);
            });
            Ok(true)
        })?;

        let fields = Fields::from_fields(fields)?;

        Ok(Class::Struct {
            config,
            attrs,
            vis,
            struct_token,
            ident,
            generics,
            fields,
        })
    }

    pub fn generics(&self) -> &syn::Generics {
        match self {
            Class::Enum { ref generics, .. } => generics,
            Class::Struct { ref generics, .. } => generics,
        }
    }

    pub fn javascript_name(&self) -> String {
        self.config()
            .rename
            .clone()
            .unwrap_or_else(|| self.ident().to_string())
    }

    pub fn mutability(&self) -> TokenStream {
        if self.config().frozen {
            quote! {
               Readable
            }
        } else {
            quote! {
                Writable
            }
        }
    }

    pub fn expand_props(&self, crate_name: &Ident) -> TokenStream {
        let Class::Struct { ref fields, .. } = self else {
            return TokenStream::new();
        };

        match fields {
            Fields::Named(x) => {
                let props = x
                    .iter()
                    .map(|x| x.expand_property_named(crate_name, self.config().rename_all));
                quote!(#(#props)*)
            }
            Fields::Unnamed(x) => {
                let props = x
                    .iter()
                    .enumerate()
                    .map(|(idx, x)| x.expand_property_unnamed(crate_name, idx.try_into().unwrap()));
                quote!(#(#props)*)
            }
            Fields::Unit => TokenStream::new(),
        }
    }

    // Aeexpand the original definition with the attributes removed..
    pub fn reexpand(&self) -> TokenStream {
        match self {
            Class::Enum {
                attrs,
                vis,
                enum_token,
                ident,
                generics,
                variants,
                ..
            } => {
                quote! {
                    #(#attrs)*
                    #vis #enum_token #ident #generics { #variants }
                }
            }
            Class::Struct {
                attrs,
                vis,
                struct_token,
                ident,
                generics,
                fields,
                ..
            } => {
                let fields = match fields {
                    Fields::Named(fields) => {
                        let fields = fields.iter().map(|x| x.expand_field());
                        quote! {
                            {
                            #(#fields),*
                            }
                        }
                    }
                    Fields::Unnamed(fields) => {
                        let fields = fields.iter().map(|x| x.expand_field());
                        quote! {
                            (#(#fields),*)
                        }
                    }
                    Fields::Unit => TokenStream::new(),
                };

                quote! {
                    #(#attrs)*
                    #vis #struct_token #ident #generics #fields
                }
            }
        }
    }

    pub fn expand(self) -> Result<TokenStream> {
        let crate_name = format_ident!("{}", self.config().crate_name()?);
        let class_name = self.ident().clone();
        let javascript_name = self.javascript_name();
        let module_name = format_ident!("__impl_class_{}_", self.ident());

        let generics = self.generics().clone();
        let generics_with_lifetimes = add_js_lifetime(&generics);

        let mutability = self.mutability();
        let props = self.expand_props(&crate_name);
        let reexpand = self.reexpand();

        let res = quote! {
            #reexpand

            #[allow(non_snake_case)]
            mod #module_name{
                pub use super::*;

                impl #generics_with_lifetimes #crate_name::class::JsClass<'js> for #class_name #generics{
                    const NAME: &'static str = #javascript_name;

                    type Mutable = #crate_name::class::#mutability;

                    fn prototype(ctx: &#crate_name::Ctx<'js>) -> #crate_name::Result<Option<#crate_name::Object<'js>>>{
                        use #crate_name::class::impl_::MethodImplementor;

                        let proto = #crate_name::Object::new(ctx.clone())?;
                        #props
                        let implementor = #crate_name::class::impl_::MethodImpl::<Self>::new();
                        (&implementor).implement(&proto)?;
                        Ok(Some(proto))
                    }

                    fn constructor(ctx: &#crate_name::Ctx<'js>) -> #crate_name::Result<Option<#crate_name::function::Constructor<'js>>>{
                        use #crate_name::class::impl_::ConstructorCreator;

                        let implementor = #crate_name::class::impl_::ConstructorCreate::<Self>::new();
                        (&implementor).create_constructor(ctx)
                    }
                }

                impl #generics_with_lifetimes #crate_name::IntoJs<'js> for #class_name #generics{
                    fn into_js(self,ctx: &#crate_name::Ctx<'js>) -> #crate_name::Result<#crate_name::Value<'js>>{
                        let cls = #crate_name::class::Class::<Self>::instance(ctx.clone(),self)?;
                        #crate_name::IntoJs::into_js(cls, ctx)
                    }
                }

                impl #generics_with_lifetimes #crate_name::FromJs<'js> for #class_name #generics
                where
                    for<'a> #crate_name::class::impl_::CloneWrapper<'a,Self>: #crate_name::class::impl_::CloneTrait<Self>,
                {
                    fn from_js(ctx: &#crate_name::Ctx<'js>, value: #crate_name::Value<'js>) -> #crate_name::Result<Self>{
                        use #crate_name::class::impl_::CloneTrait;

                        let value = #crate_name::class::Class::<Self>::from_js(ctx,value)?;
                        let borrow = value.try_borrow()?;
                        Ok(#crate_name::class::impl_::CloneWrapper(&*borrow).wrap_clone())
                    }
                }
            }
        };

        Ok(res)
    }
}

pub(crate) fn expand(options: OptionList<ClassOption>, item: syn::Item) -> Result<TokenStream> {
    Class::from_proc_macro_input(options, item)?.expand()
}