rquickjs_macro/
lib.rs

1#![allow(clippy::uninlined_format_args)]
2#![allow(clippy::needless_doctest_main)]
3#![allow(clippy::doc_lazy_continuation)]
4
5use attrs::OptionList;
6use class::ClassOption;
7use function::FunctionOption;
8use methods::ImplOption;
9use module::ModuleOption;
10use proc_macro::TokenStream as TokenStream1;
11use syn::{parse_macro_input, spanned::Spanned, DeriveInput, Error, Item};
12
13#[cfg(test)]
14macro_rules! assert_eq_tokens {
15    ($actual:expr, $expected:expr) => {
16        let actual = $actual.to_string();
17        let expected = $expected.to_string();
18        difference::assert_diff!(&actual, &expected, " ", 0);
19    };
20}
21
22mod attrs;
23mod class;
24mod common;
25mod embed;
26mod fields;
27mod function;
28mod js_lifetime;
29mod methods;
30mod module;
31mod trace;
32
33/// An attribute for implementing [`JsClass`](rquickjs_core::class::JsClass`) for a Rust type.
34///
35/// # Attribute options
36///
37/// The attribute has a number of options for configuring the generated trait implementation. These
38/// attributes can be passed to the `class` attribute as an argument: `#[class(rename =
39/// "AnotherName")]` or with a separate `qjs` attribute on the struct item: `#[qjs(rename =
40/// "AnotherName")]`. A option which is a Flag can be set just by adding the attribute:
41/// `#[qjs(flag)]` or by setting it to specific boolean value: `#[qjs(flag = true)]`.
42///
43/// | **Option**   | **Value** | **Description**                                                                                                                                                                         |
44/// |--------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
45/// | `crate`      | String    | Changes the name from which the attribute tries to use rquickjs types. Use when the name behind which the rquickjs crate is declared is not properly resolved by the macro.             |
46/// | `rename`     | String    | Changes the name of the implemented class on the JavaScript side.                                                                                                                       |
47/// | `rename_all` | Casing    | Converts the case of all the fields of this struct which have implement accessors. Can be one of `lowercase`, `UPPERCASE`, `camelCase`, `PascalCase`,`snake_case`, or `SCREAMING_SNAKE` |
48/// | `frozen`     | Flag      | Changes the class implementation to only allow borrowing immutably.  Trying to borrow mutably will result in an error.                                                                  |
49///
50/// # Field options
51///
52/// The fields of a struct (doesn't work on enums) can also tagged with an attribute to, for
53/// example make the fields accessible from JavaScript. These attributes are all in the form of
54/// `#[qjs(option = value)]`.
55///
56/// | **Option**     | **Value** | **Description**                                                                         |
57/// |----------------|-----------|-----------------------------------------------------------------------------------------|
58/// | `get`          | Flag      | Creates a getter for this field, allowing read access to the field from JavaScript.     |
59/// | `set`          | Flag      | Creates a setter for this field, allowing write access to the field from JavaSccript.   |
60/// | `enumerable`   | Flag      | Makes the field, if it has a getter or setter, enumerable in JavaScript.                |
61/// | `configurable` | Flag      | Makes the field, if it has a getter or setter, configurable in JavaScript.              |
62/// | `skip_trace`   | Flag      | Skips the field deriving the `Trace` trait.                                             |
63/// | `rename`       | String    | Changes the name of the field getter and/or setter to the specified name in JavaScript. |
64///
65///
66/// # Example
67/// ```
68/// use rquickjs::{class::Trace, CatchResultExt, Class, Context, Object, Runtime, JsLifetime};
69///
70/// /// Implement JsClass for TestClass.
71/// /// This allows passing any instance of TestClass straight to JavaScript.
72/// /// It is command to also add #[derive(Trace)] as all types which implement JsClass need to
73/// /// also implement trace.
74/// #[derive(Trace, JsLifetime)]
75/// #[rquickjs::class(rename_all = "camelCase")]
76/// pub struct TestClass<'js> {
77///     /// These attribute make the accessible from JavaScript with getters and setters.
78///     /// As we used `rename_all = "camelCase"` in the attribute it will be called `innerObject`
79///     /// on the JavaScript side.
80///     #[qjs(get, set)]
81///     inner_object: Object<'js>,
82///
83///     /// This works for any value which implements `IntoJs` and `FromJs` and is clonable.
84///     #[qjs(get, set)]
85///     some_value: u32,
86///     /// Make a field enumerable.
87///     #[qjs(get, set, enumerable)]
88///     another_value: u32,
89/// }
90///
91/// pub fn main() {
92///     let rt = Runtime::new().unwrap();
93///     let ctx = Context::full(&rt).unwrap();
94///
95///     ctx.with(|ctx| {
96///         /// Create an insance of a JsClass
97///         let cls = Class::instance(
98///             ctx.clone(),
99///             TestClass {
100///                 inner_object: Object::new(ctx.clone()).unwrap(),
101///                 some_value: 1,
102///                 another_value: 2,
103///             },
104///         )
105///         .unwrap();
106///         /// Pass it to JavaScript
107///         ctx.globals().set("t", cls.clone()).unwrap();
108///         ctx.eval::<(), _>(
109///             r#"
110///             // use the actual value.
111///             if(t.someValue !== 1){
112///                 throw new Error(1)
113///             }"#
114///         ).unwrap();
115///     })
116/// }
117/// ```
118#[proc_macro_attribute]
119pub fn class(attr: TokenStream1, item: TokenStream1) -> TokenStream1 {
120    let options = parse_macro_input!(attr as OptionList<ClassOption>);
121    let item = parse_macro_input!(item as Item);
122    match class::expand(options, item) {
123        Ok(x) => x.into(),
124        Err(e) => e.into_compile_error().into(),
125    }
126}
127
128/// A attribute for implementing `IntoJsFunc` for a certain function.
129///
130/// Using this attribute allows a wider range of functions to be used as callbacks from JavaScript
131/// then when you use closures or the functions for which the proper traits are already
132/// implemented..
133///
134#[proc_macro_attribute]
135pub fn function(attr: TokenStream1, item: TokenStream1) -> TokenStream1 {
136    let options = parse_macro_input!(attr as OptionList<FunctionOption>);
137    let item = parse_macro_input!(item as Item);
138    match item {
139        Item::Fn(func) => match function::expand(options, func) {
140            Ok(x) => x.into(),
141            Err(e) => e.into_compile_error().into(),
142        },
143        item => Error::new(
144            item.span(),
145            "#[function] macro can only be used on functions",
146        )
147        .into_compile_error()
148        .into(),
149    }
150}
151
152/// A attribute for implementing methods for a class.
153///
154/// This attribute can be added to a impl block which implements methods for a type which uses the
155/// [`macro@class`] attribute to derive [`JsClass`](rquickjs_core::class::JsClass).
156///
157/// # Limitations
158/// Due to limitations in the Rust type system this attribute can be used on only one impl block
159/// per type.
160///
161/// # Attribute options
162///
163/// The attribute has a number of options for configuring the generated trait implementation. These
164/// attributes can be passed to the `methods` attribute as an argument: `#[methods(rename =
165/// "AnotherName")]` or with a separate `qjs` attribute on the impl item: `#[qjs(rename =
166/// "AnotherName")]`. A option which is a Flag can be set just by adding the attribute:
167/// `#[qjs(flag)]` or by setting it to specific boolean value: `#[qjs(flag = true)]`.
168///
169/// | **Option**   | **Value** | **Description**                                                                                                                                                                         |
170/// |--------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
171/// | `crate`      | String    | Changes the name from which the attribute tries to use rquickjs types. Use when the name behind which the rquickjs crate is declared is not properly resolved by the macro.             |
172/// | `rename`     | String    | Changes the name of the implemented class on the JavaScript side.                                                                                                                       |
173/// | `rename_all` | Casing    | Converts the case of all the fields of this struct which have implement accessors. Can be one of `lowercase`, `UPPERCASE`, `camelCase`, `PascalCase`,`snake_case`, or `SCREAMING_SNAKE` |
174///
175///
176/// # Item options
177///
178/// Each item of the impl block can also tagged with an attribute to change the resulting derived method definition.
179/// These attributes are all in the form of `#[qjs(option = value)]`.
180///
181/// | **Option**     | **Value**                                                         | **Description**                                                                                 |
182/// |----------------|-------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|
183/// | `get`          | Flag                                                              | Makes this method a getter for a field of the same name.                                        |
184/// | `set`          | Flag                                                              | Makes this method a setter for a field of the same name.                                        |
185/// | `enumerable`   | Flag                                                              | Makes the method, if it is a getter or setter, enumerable in JavaScript.                        |
186/// | `configurable` | Flag                                                              | Makes the method, if it is a getter or setter, configurable in JavaScript.                      |
187/// | `rename`       | String or [`PredefinedAtom`](rquickjs_core::atom::PredefinedAtom) | Changes the name of the field getter and/or setter to the specified name in JavaScript.         |
188/// | `static`       | Flag                                                              | Makes the method a static method i.e. defined on the type constructor instead of the prototype. |
189/// | `constructor`  | Flag                                                              | Marks this method a the constructor for this type.                                              |
190/// | `skip`         | Flag                                                              | Skips defining this method on the JavaScript class.                                             |
191///
192/// # Example
193/// ```
194/// use rquickjs::{
195///     atom::PredefinedAtom, class::Trace, prelude::Func, CatchResultExt, Class, Context, Ctx,
196///     Object, Result, Runtime, JsLifetime
197/// };
198///
199/// #[derive(Trace, JsLifetime)]
200/// #[rquickjs::class]
201/// pub struct TestClass {
202///     value: u32,
203///     another_value: u32,
204/// }
205///
206/// #[rquickjs::methods]
207/// impl TestClass {
208///     /// Marks a method as a constructor.
209///     /// This method will be used when a new TestClass object is created from JavaScript.
210///     #[qjs(constructor)]
211///     pub fn new(value: u32) -> Self {
212///         TestClass {
213///             value,
214///             another_value: value,
215///         }
216///     }
217///
218///     /// Mark a function as a getter.
219///     /// The value of this function can be accessed as a field.
220///     /// This function is also renamed to value
221///     #[qjs(get, rename = "value")]
222///     pub fn get_value(&self) -> u32 {
223///         self.value
224///     }
225///
226///     /// Mark a function as a setter.
227///     /// The value of this function can be set as a field.
228///     /// This function is also renamed to value
229///     #[qjs(set, rename = "value")]
230///     pub fn set_value(&mut self, v: u32) {
231///         self.value = v
232///     }
233///
234///     /// Mark a function as a enumerable gettter.
235///     #[qjs(get, rename = "anotherValue", enumerable)]
236///     pub fn get_another_value(&self) -> u32 {
237///         self.another_value
238///     }
239///
240///     #[qjs(set, rename = "anotherValue", enumerable)]
241///     pub fn set_another_value(&mut self, v: u32) {
242///         self.another_value = v
243///     }
244///
245///     /// Marks a function as static. It will be defined on the constructor object instead of the
246///     /// Class prototype.
247///     #[qjs(static)]
248///     pub fn compare(a: &Self, b: &Self) -> bool {
249///         a.value == b.value && a.another_value == b.another_value
250///     }
251///
252///     /// All functions declared in this impl block will be defined on the prototype of the
253///     /// class. This attributes allows you to skip certain functions.
254///     #[qjs(skip)]
255///     pub fn inner_function(&self) {}
256///
257///     /// Functions can also be renamed to specific symbols. This allows you to make an Rust type
258///     /// act like an iteratable value for example.
259///     #[qjs(rename = PredefinedAtom::SymbolIterator)]
260///     pub fn iterate<'js>(&self, ctx: Ctx<'js>) -> Result<Object<'js>> {
261///         let res = Object::new(ctx)?;
262///
263///         res.set(
264///             PredefinedAtom::Next,
265///             Func::from(|ctx: Ctx<'js>| -> Result<Object<'js>> {
266///                 let res = Object::new(ctx)?;
267///                 res.set(PredefinedAtom::Done, true)?;
268///                 Ok(res)
269///             }),
270///         )?;
271///         Ok(res)
272///     }
273/// }
274///
275/// pub fn main() {
276///     let rt = Runtime::new().unwrap();
277///     let ctx = Context::full(&rt).unwrap();
278///
279///     ctx.with(|ctx| {
280///         /// Define the class constructor on the globals object.
281///         Class::<TestClass>::define(&ctx.globals()).unwrap();
282///         ctx.eval::<(), _>(
283///             r#"
284///             let nv = new TestClass(5);
285///             if(nv.value !== 5){
286///                 throw new Error('invalid value')
287///             }
288///         "#,
289///         ).catch(&ctx).unwrap();
290///     });
291/// }
292/// ```
293#[proc_macro_attribute]
294pub fn methods(attr: TokenStream1, item: TokenStream1) -> TokenStream1 {
295    let options = parse_macro_input!(attr as OptionList<ImplOption>);
296    let item = parse_macro_input!(item as Item);
297    match item {
298        Item::Impl(item) => match methods::expand(options, item) {
299            Ok(x) => x.into(),
300            Err(e) => e.into_compile_error().into(),
301        },
302        item => Error::new(
303            item.span(),
304            "#[methods] macro can only be used on impl blocks",
305        )
306        .into_compile_error()
307        .into(),
308    }
309}
310
311/// An attribute which generates code for exporting a module to Rust.
312///
313/// Any supported item inside the module which is marked as `pub` will be exported as a JavaScript value.
314/// Different items result in different JavaScript values.
315/// The supported items are:
316///
317/// - `struct` and `enum` items. These will be exported as JavaScript
318/// classes with their constructor exported as a function from the module.
319/// - `fn` items, these will be exported as JavaScript functions.
320/// - `use` items, the types which are reexported with `pub` will be handled just like `struct` and
321/// `enum` items defined inside the module. The name of the class can be adjusted by renaming the
322/// reexport with `as`.
323/// - `const` and `static` items, these items will be exported as values with the same name.
324///
325/// # Attribute options
326///
327/// The attribute has a number of options for configuring the generated trait implementation. These
328/// attributes can be passed to the `module` attribute as an argument: `#[module(rename =
329/// "AnotherName")]` or with a separate `qjs` attribute on the impl item: `#[qjs(rename =
330/// "AnotherName")]`. A option which is a Flag can be set just by adding the attribute:
331/// `#[qjs(flag)]` or by setting it to specific boolean value: `#[qjs(flag = true)]`.
332///
333/// | **Option**     | **Value** | **Description**                                                                                                                                                                        |
334/// |----------------|-----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
335/// | `crate`        | String    | Changes the name from which the attribute tries to use rquickjs types. Use when the name behind which the rquickjs crate is declared is not properly resolved by the macro.            |
336/// | `rename`       | String    | Changes the name of the implemented module on the JavaScript side.                                                                                                                     |
337/// | `rename_vars`  | Casing    | Alters the name of all items exported as JavaScript values by changing the case.  Can be one of `lowercase`, `UPPERCASE`, `camelCase`, `PascalCase`,`snake_case`, or `SCREAMING_SNAKE` |
338/// | `rename_types` | Casing    | Alters the name of all items exported as JavaScript classes by changing the case. Can be one of `lowercase`, `UPPERCASE`, `camelCase`, `PascalCase`,`snake_case`, or `SCREAMING_SNAKE` |
339/// | `prefix`       | String    | The module will be implemented for a new type with roughly the same name as the Rust module with a prefix added. This changes the prefix which will be added. Defaults to `js_`        |
340///
341/// # Item options
342///
343/// The attribute also has a number of options for changing the resulting generated module
344/// implementation for specific items.
345/// These attributes are all in the form of `#[qjs(option = value)]`.
346///
347/// | **Option** | **Value** | **Item Type**  | **Description**                                                                                                                                                                                            |
348/// |------------|-----------|----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
349/// | `skip`     | Flag      | All            | Skips exporting this item from the JavaScript module.                                                                                                                                                      |
350/// | `rename`   | String    | All except use | Change the name from which this value is exported.                                                                                                                                                         |
351/// | `declare`  | Flag      | Functions Only | Marks this function as the declaration function. This function will be called when the module is declared allowing for exporting items which otherwise are difficult to export using the attribute.        |
352/// | `evaluate` | Flag      | Functions Only | Marks this function as the evaluation function. This function will be called when the module is being evaluated allowing for exporting items which otherwise are difficult to export using the attribute.  |
353///
354/// # Example
355///
356/// ```
357/// use rquickjs::{CatchResultExt, Context, Module, Runtime};
358///
359/// /// A class which will be exported from the module.
360/// #[derive(rquickjs::class::Trace, rquickjs::JsLifetime)]
361/// #[rquickjs::class]
362/// pub struct Test {
363///     foo: u32,
364/// }
365///
366/// #[rquickjs::methods]
367/// impl Test {
368///     #[qjs(constructor)]
369///     pub fn new() -> Test {
370///         Test { foo: 3 }
371///     }
372/// }
373///
374/// impl Default for Test {
375///     fn default() -> Self {
376///         Self::new()
377///     }
378/// }
379///
380/// #[rquickjs::module(rename_vars = "camelCase")]
381/// mod test_mod {
382///     /// Imports and other declarations which aren't `pub` won't be exported.
383///     use rquickjs::Ctx;
384///
385///     /// You can even use `use` to export types from outside.
386///     ///
387///     /// Note that this tries to export the type, not the value,
388///     /// So this won't work for functions.
389///     ///
390///     /// By using `as` you can change under which name the constructor is exported.
391///     /// The below type will exported as `RenamedTest`.
392///     pub use super::Test as RenamedTest;
393///
394///     /// A class which will be exported from the module under the name `FooBar`.
395///     #[derive(rquickjs::class::Trace, rquickjs::JsLifetime)]
396///     #[rquickjs::class(rename = "FooBar")]
397///     pub struct Test2 {
398///         bar: u32,
399///     }
400///
401///     /// Implement methods for the class like normal.
402///     #[rquickjs::methods]
403///     impl Test2 {
404///         /// A constructor is required for exporting types.
405///         #[qjs(constructor)]
406///         pub fn new() -> Test2 {
407///             Test2 { bar: 3 }
408///         }
409///     }
410///
411///     impl Default for Test2 {
412///         fn default() -> Self {
413///             Self::new()
414///         }
415///     }
416///
417///     /// Two variables exported as `aConstValue` and `aStaticValue` because of the `rename_all` attr.
418///     pub const A_CONST_VALUE: f32 = 2.0;
419///     pub static A_STATIC_VALUE: f32 = 2.0;
420///
421///     /// If your module doesn't quite fit with how this macro exports you can manually export from
422///     /// the declare and evaluate functions.
423///     #[qjs(declare)]
424///     pub fn declare(declare: &rquickjs::module::Declarations) -> rquickjs::Result<()> {
425///         declare.declare("aManuallyExportedValue")?;
426///         Ok(())
427///     }
428///
429///     #[qjs(evaluate)]
430///     pub fn evaluate<'js>(
431///         _ctx: &Ctx<'js>,
432///         exports: &rquickjs::module::Exports<'js>,
433///     ) -> rquickjs::Result<()> {
434///         exports.export("aManuallyExportedValue", "Some Value")?;
435///         Ok(())
436///     }
437///
438///     /// You can also export functions.
439///     #[rquickjs::function]
440///     pub fn foo() -> u32 {
441///         1 + 1
442///     }
443///
444///     /// You can make items public but not export them to JavaScript by adding the skip attribute.
445///     #[qjs(skip)]
446///     pub fn ignore_function() -> u32 {
447///         2 + 2
448///     }
449/// }
450///
451/// fn main() {
452///     assert_eq!(test_mod::ignore_function(), 4);
453///     let rt = Runtime::new().unwrap();
454///     let ctx = Context::full(&rt).unwrap();
455///
456///     ctx.with(|ctx| {
457///          // These modules are declared like normal with the declare_def function.
458///          // The name of the module is js_ + the name of the module. This prefix can be changed
459///          // by writing for example `#[rquickjs::module(prefix = "prefix_")]`.
460///          Module::declare_def::<js_test_mod, _>(ctx.clone(), "test").unwrap();
461///          let _ = Module::evaluate(
462///              ctx.clone(),
463///              "test2",
464///              r"
465///              import { RenamedTest, foo,aManuallyExportedValue, aConstValue, aStaticValue, FooBar } from 'test';
466///              if (foo() !== 2){
467///                  throw new Error(1);
468///              }
469///              "
470///          )
471///          .catch(&ctx)
472///          .unwrap();
473///      })
474/// }
475/// ```
476#[proc_macro_attribute]
477pub fn module(attr: TokenStream1, item: TokenStream1) -> TokenStream1 {
478    let options = parse_macro_input!(attr as OptionList<ModuleOption>);
479    let item = parse_macro_input!(item as Item);
480    match item {
481        Item::Mod(item) => match module::expand(options, item) {
482            Ok(x) => x.into(),
483            Err(e) => e.into_compile_error().into(),
484        },
485        item => Error::new(item.span(), "#[module] macro can only be used on modules")
486            .into_compile_error()
487            .into(),
488    }
489}
490
491/// A macro for auto deriving the trace trait.
492#[proc_macro_derive(Trace, attributes(qjs))]
493pub fn trace(stream: TokenStream1) -> TokenStream1 {
494    let derive_input = parse_macro_input!(stream as DeriveInput);
495    match trace::expand(derive_input) {
496        Ok(x) => x.into(),
497        Err(e) => e.into_compile_error().into(),
498    }
499}
500
501/// A macro for embedding JavaScript code into a binary.
502///
503/// Compiles a JavaScript module to bytecode and then compiles the resulting bytecode into the
504/// binary. Each file loaded is turned into its own module. The macro takes a list of paths to
505/// files to be compiled into a module with an option name. Module paths are relative to the crate
506/// manifest file.
507///
508/// # Usage
509///
510/// ```
511/// use rquickjs::{embed, loader::Bundle, CatchResultExt, Context, Module, Runtime};
512///
513/// /// load the `my_module.js` file and name it myModule
514/// static BUNDLE: Bundle = embed! {
515///     "myModule": "my_module.js",
516/// };
517///
518/// fn main() {
519///     let rt = Runtime::new().unwrap();
520///     let ctx = Context::full(&rt).unwrap();
521///
522///     rt.set_loader(BUNDLE, BUNDLE);
523///     ctx.with(|ctx| {
524///         Module::evaluate(
525///             ctx.clone(),
526///             "testModule",
527///             r#"
528///             import { foo } from 'myModule';
529///             if(foo() !== 2){
530///                 throw new Error("Function didn't return the correct value");
531///             }
532///         "#,
533///         )
534///         .unwrap()
535///         .finish::<()>()
536///         .catch(&ctx)
537///         .unwrap();
538///     })
539/// }
540/// ```
541#[proc_macro]
542pub fn embed(item: TokenStream1) -> TokenStream1 {
543    let embed_modules: embed::EmbedModules = parse_macro_input!(item);
544    match embed::embed(embed_modules) {
545        Ok(x) => x.into(),
546        Err(e) => e.into_compile_error().into(),
547    }
548}
549
550/// A Macro for auto deriving the JsLifetime trait.
551#[proc_macro_derive(JsLifetime, attributes(qjs))]
552pub fn js_lifetime(stream: TokenStream1) -> TokenStream1 {
553    let derive_input = parse_macro_input!(stream as DeriveInput);
554    match js_lifetime::expand(derive_input) {
555        Ok(x) => x.into(),
556        Err(e) => e.into_compile_error().into(),
557    }
558}