From 0f282f5bc3538103af8a2b939469fd8736b23594 Mon Sep 17 00:00:00 2001 From: Hans Larsen Date: Wed, 4 Sep 2024 21:43:26 -0700 Subject: [PATCH] Add support for boa(rename = "") in TryFromJs derive (#3980) * Add support for boa(rename = "") in TryFromJs derive * Fix clippies and fmt * Move macro test to boa_engine --- core/engine/tests/macros.rs | 36 ++++++++++++++++++++++++++++++++++++ core/macros/src/lib.rs | 11 +++++++---- 2 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 core/engine/tests/macros.rs diff --git a/core/engine/tests/macros.rs b/core/engine/tests/macros.rs new file mode 100644 index 0000000000..85ec2a27ad --- /dev/null +++ b/core/engine/tests/macros.rs @@ -0,0 +1,36 @@ +#![allow(unused_crate_dependencies)] +use boa_engine::value::TryFromJs; +use boa_engine::{js_string, Context, JsResult, JsValue, Source}; +use boa_string::JsString; + +#[test] +fn try_from_js_derive() { + #[derive(Debug, TryFromJs, Eq, PartialEq)] + struct TryFromJsTest { + a: JsString, + #[boa(rename = "bBB")] + b: i32, + #[boa(from_js_with = "check_tfj_called")] + c: i32, + } + + fn check_tfj_called(value: &JsValue, context: &mut Context) -> JsResult { + let v = value.to_i32(context)?; + Ok(v / 2) + } + + let mut context = Context::default(); + let obj = context + .eval(Source::from_bytes(br#"({ a: "hello", bBB: 42, c: 120 })"#)) + .unwrap(); + + let result = TryFromJsTest::try_from_js(&obj, &mut context).unwrap(); + assert_eq!( + result, + TryFromJsTest { + a: js_string!("hello"), + b: 42, + c: 60 + } + ); +} diff --git a/core/macros/src/lib.rs b/core/macros/src/lib.rs index 7803ca5185..0807d9a0a8 100644 --- a/core/macros/src/lib.rs +++ b/core/macros/src/lib.rs @@ -433,12 +433,10 @@ fn generate_conversion(fields: FieldsNamed) -> Result Result()?); Ok(()) + } else if meta.path.is_ident("rename") { + let value = meta.value()?; + field_name = value.parse::()?.value(); + Ok(()) } else { Err(meta.error( "invalid syntax in the `#[boa()]` attribute. \ @@ -460,8 +462,9 @@ fn generate_conversion(fields: FieldsNamed) -> Result pd.value().ok_or_else(|| ::boa_engine::JsError::from( ::boa_engine::JsNativeError::typ().with_message(#error_str) ))?.clone().try_js_into(context)?,