From e0dcfe22776f5f3b63f3f43b867c91b68199dcce Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Mon, 10 Aug 2026 13:21:24 +0800 Subject: [PATCH] Add projection fast paths Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 84688dea-d965-4933-a2d9-41f8f6ad2f2e --- bindings/js/src/lib.rs | 78 +++++++ .../src/metadata_table/method_handle.rs | 60 ++++++ crates/dynwinrt/src/native_call.rs | 196 +++++++++++++++++- crates/dynwinrt/src/signature.rs | 48 +++++ .../winrt/javascript/project/methods.rs | 133 ++++++++++-- .../codegen/winrt/javascript/project/mod.rs | 16 +- .../winrt/javascript/render/javascript/mod.rs | 1 + .../tests/element_factory_test.rs | 174 +++++++++++++++- .../uri/IIterator_IWwwFormUrlDecoderEntry.js | 4 +- ...UriRuntimeClassWithAbsoluteCanonicalUri.js | 4 +- .../snapshots/uri/IWwwFormUrlDecoderEntry.js | 4 +- .../tests/snapshots/uri/Uri.js | 38 ++-- 12 files changed, 705 insertions(+), 51 deletions(-) diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index 7998b093..d1b22a8f 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -540,6 +540,84 @@ impl DynWinRTMethodHandle { .map_err(|e| napi::Error::from_reason(e.message())) } + #[napi] + pub fn set_hstring(&self, obj: &DynWinRTValue, value: String) -> napi::Result<()> { + let raw = obj + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("set_hstring: not an Object"))? + .as_raw(); + self + .0 + .call_setter_hstring(raw, &HSTRING::from(value)) + .map_err(|e| napi::Error::from_reason(e.message())) + } + + #[napi] + pub fn set_bool(&self, obj: &DynWinRTValue, value: bool) -> napi::Result<()> { + let raw = obj + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("set_bool: not an Object"))? + .as_raw(); + self + .0 + .call_setter_bool(raw, value) + .map_err(|e| napi::Error::from_reason(e.message())) + } + + #[napi] + pub fn set_i32(&self, obj: &DynWinRTValue, value: i32) -> napi::Result<()> { + let raw = obj + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("set_i32: not an Object"))? + .as_raw(); + self + .0 + .call_setter_i32(raw, value) + .map_err(|e| napi::Error::from_reason(e.message())) + } + + #[napi] + pub fn set_u32(&self, obj: &DynWinRTValue, value: u32) -> napi::Result<()> { + let raw = obj + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("set_u32: not an Object"))? + .as_raw(); + self + .0 + .call_setter_u32(raw, value) + .map_err(|e| napi::Error::from_reason(e.message())) + } + + #[napi] + pub fn set_f32(&self, obj: &DynWinRTValue, value: f64) -> napi::Result<()> { + let raw = obj + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("set_f32: not an Object"))? + .as_raw(); + self + .0 + .call_setter_f32(raw, value as f32) + .map_err(|e| napi::Error::from_reason(e.message())) + } + + #[napi] + pub fn set_f64(&self, obj: &DynWinRTValue, value: f64) -> napi::Result<()> { + let raw = obj + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("set_f64: not an Object"))? + .as_raw(); + self + .0 + .call_setter_f64(raw, value) + .map_err(|e| napi::Error::from_reason(e.message())) + } + /// 1-arg invoke with hstring input → DynWinRTValue result #[napi] pub fn invoke_hstring(&self, obj: &DynWinRTValue, arg: String) -> napi::Result { diff --git a/crates/dynwinrt/src/metadata_table/method_handle.rs b/crates/dynwinrt/src/metadata_table/method_handle.rs index 2311ad29..19cc5db1 100644 --- a/crates/dynwinrt/src/metadata_table/method_handle.rs +++ b/crates/dynwinrt/src/metadata_table/method_handle.rs @@ -70,4 +70,64 @@ impl MethodHandle { let method_ptr = self.table.method_ptr(self.index); unsafe { (*method_ptr).call_getter_object(obj) }.map_err(crate::result::Error::WindowsError) } + + pub fn call_setter_hstring( + &self, + obj: *mut std::ffi::c_void, + value: &windows_core::HSTRING, + ) -> crate::result::Result<()> { + let method_ptr = self.table.method_ptr(self.index); + unsafe { (*method_ptr).call_setter_hstring(obj, value) } + .map_err(crate::result::Error::WindowsError) + } + + pub fn call_setter_bool( + &self, + obj: *mut std::ffi::c_void, + value: bool, + ) -> crate::result::Result<()> { + let method_ptr = self.table.method_ptr(self.index); + unsafe { (*method_ptr).call_setter_bool(obj, value) } + .map_err(crate::result::Error::WindowsError) + } + + pub fn call_setter_i32( + &self, + obj: *mut std::ffi::c_void, + value: i32, + ) -> crate::result::Result<()> { + let method_ptr = self.table.method_ptr(self.index); + unsafe { (*method_ptr).call_setter_i32(obj, value) } + .map_err(crate::result::Error::WindowsError) + } + + pub fn call_setter_u32( + &self, + obj: *mut std::ffi::c_void, + value: u32, + ) -> crate::result::Result<()> { + let method_ptr = self.table.method_ptr(self.index); + unsafe { (*method_ptr).call_setter_u32(obj, value) } + .map_err(crate::result::Error::WindowsError) + } + + pub fn call_setter_f32( + &self, + obj: *mut std::ffi::c_void, + value: f32, + ) -> crate::result::Result<()> { + let method_ptr = self.table.method_ptr(self.index); + unsafe { (*method_ptr).call_setter_f32(obj, value) } + .map_err(crate::result::Error::WindowsError) + } + + pub fn call_setter_f64( + &self, + obj: *mut std::ffi::c_void, + value: f64, + ) -> crate::result::Result<()> { + let method_ptr = self.table.method_ptr(self.index); + unsafe { (*method_ptr).call_setter_f64(obj, value) } + .map_err(crate::result::Error::WindowsError) + } } diff --git a/crates/dynwinrt/src/native_call.rs b/crates/dynwinrt/src/native_call.rs index f69af1ae..9124a008 100644 --- a/crates/dynwinrt/src/native_call.rs +++ b/crates/dynwinrt/src/native_call.rs @@ -1380,8 +1380,57 @@ impl Method { // --- Fast getter paths: zero Vec/WinRTValue allocation --- + fn validate_fast_getter( + &self, + label: &str, + accepts: impl FnOnce(&TypeKind) -> bool, + ) -> windows_core::Result<()> { + let valid = self.info.input_count == 0 + && self.info.out_count == 1 + && self.info.parameters.len() == 1 + && self.info.parameters[0].kind == ParamKind::Out + && matches!(self.info.return_kind, MethodReturn::HResult) + && matches!( + &self.info.parameters[0].typ, + ParameterType::WinRT(typ) if accepts(&typ.kind()) + ); + if valid { + Ok(()) + } else { + Err(invalid_argument(&format!( + "{label} requires a zero-input, one-output WinRT getter with the expected ABI type", + ))) + } + } + + fn validate_fast_setter( + &self, + label: &str, + accepts: impl FnOnce(&TypeKind) -> bool, + ) -> windows_core::Result<()> { + let valid = self.info.input_count == 1 + && self.info.out_count == 0 + && self.info.parameters.len() == 1 + && self.info.parameters[0].kind == ParamKind::In + && matches!(self.info.return_kind, MethodReturn::HResult) + && matches!( + &self.info.parameters[0].typ, + ParameterType::WinRT(typ) if accepts(&typ.kind()) + ); + if valid { + Ok(()) + } else { + Err(invalid_argument(&format!( + "{label} requires a one-input, zero-output WinRT setter with the expected ABI type", + ))) + } + } + /// Getter → i32 (0 in, 1 out). Writes directly to stack i32. pub fn call_getter_i32(&self, obj: *mut std::ffi::c_void) -> windows_core::Result { + self.validate_fast_getter("get_i32", |kind| { + matches!(kind, TypeKind::I32 | TypeKind::Enum(_)) + })?; let mut out: i32 = 0; let hr = call::call_winrt_method_1( self.info.index, @@ -1394,11 +1443,12 @@ impl Method { /// Getter → bool (0 in, 1 out). Writes directly to stack bool. pub fn call_getter_bool(&self, obj: *mut std::ffi::c_void) -> windows_core::Result { - let mut out: i32 = 0; // WinRT bool is i32 on ABI + self.validate_fast_getter("get_bool", |kind| matches!(kind, TypeKind::Bool))?; + let mut out: u8 = 0; let hr = call::call_winrt_method_1( self.info.index, obj, - &mut out as *mut i32 as *mut std::ffi::c_void, + &mut out as *mut u8 as *mut std::ffi::c_void, ); hr.ok()?; Ok(out != 0) @@ -1409,6 +1459,7 @@ impl Method { &self, obj: *mut std::ffi::c_void, ) -> windows_core::Result { + self.validate_fast_getter("get_hstring", |kind| matches!(kind, TypeKind::HString))?; // HSTRING is a pointer-sized handle on ABI. Let WinRT write it directly. let mut out = windows_core::HSTRING::new(); let hr = call::call_winrt_method_1( @@ -1425,6 +1476,16 @@ impl Method { &self, obj: *mut std::ffi::c_void, ) -> windows_core::Result { + self.validate_fast_getter("get_object", |kind| { + matches!( + kind, + TypeKind::Object + | TypeKind::Interface(_) + | TypeKind::Delegate(_) + | TypeKind::RuntimeClass(_) + | TypeKind::Parameterized(_) + ) + })?; let mut out: *mut std::ffi::c_void = std::ptr::null_mut(); let hr = call::call_winrt_method_1( self.info.index, @@ -1446,6 +1507,66 @@ impl Method { } } + // --- Fast setter paths: zero Vec/WinRTValue allocation --- + + pub fn call_setter_hstring( + &self, + obj: *mut std::ffi::c_void, + value: &windows_core::HSTRING, + ) -> windows_core::Result<()> { + self.validate_fast_setter("set_hstring", |kind| matches!(kind, TypeKind::HString))?; + // Pass the HSTRING handle value, not a pointer to the Rust wrapper. + let raw: *mut std::ffi::c_void = unsafe { std::mem::transmute_copy(value) }; + call::call_winrt_method_1(self.info.index, obj, raw).ok() + } + + pub fn call_setter_bool( + &self, + obj: *mut std::ffi::c_void, + value: bool, + ) -> windows_core::Result<()> { + self.validate_fast_setter("set_bool", |kind| matches!(kind, TypeKind::Bool))?; + call::call_winrt_method_1(self.info.index, obj, u8::from(value)).ok() + } + + pub fn call_setter_i32( + &self, + obj: *mut std::ffi::c_void, + value: i32, + ) -> windows_core::Result<()> { + self.validate_fast_setter("set_i32", |kind| { + matches!(kind, TypeKind::I32 | TypeKind::Enum(_)) + })?; + call::call_winrt_method_1(self.info.index, obj, value).ok() + } + + pub fn call_setter_u32( + &self, + obj: *mut std::ffi::c_void, + value: u32, + ) -> windows_core::Result<()> { + self.validate_fast_setter("set_u32", |kind| matches!(kind, TypeKind::U32))?; + call::call_winrt_method_1(self.info.index, obj, value).ok() + } + + pub fn call_setter_f32( + &self, + obj: *mut std::ffi::c_void, + value: f32, + ) -> windows_core::Result<()> { + self.validate_fast_setter("set_f32", |kind| matches!(kind, TypeKind::F32))?; + call::call_winrt_method_1(self.info.index, obj, value).ok() + } + + pub fn call_setter_f64( + &self, + obj: *mut std::ffi::c_void, + value: f64, + ) -> windows_core::Result<()> { + self.validate_fast_setter("set_f64", |kind| matches!(kind, TypeKind::F64))?; + call::call_winrt_method_1(self.info.index, obj, value).ok() + } + pub fn call_dynamic( &self, obj: *mut std::ffi::c_void, @@ -2067,6 +2188,23 @@ mod tests { windows_core::HRESULT(0) } + unsafe extern "system" fn write_bool( + _this: *mut std::ffi::c_void, + value: *mut u8, + ) -> windows_core::HRESULT { + unsafe { *value = 1 }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn record_bool( + this: *mut std::ffi::c_void, + value: u8, + ) -> windows_core::HRESULT { + let object = unsafe { &*(this as *const FakeComObject) }; + object.calls.store(value as u32, Ordering::Relaxed); + windows_core::HRESULT(0) + } + fn struct_in_out_method( table: &Arc, expected: TypeHandle, @@ -2099,6 +2237,60 @@ mod tests { assert_eq!(method.info.parameters[2].input_index, None); } + #[test] + fn fast_accessors_reject_incompatible_method_shapes() { + let table = MetadataTable::new(); + let setter = AbiMethodSignature::new(&table) + .add_in_type(ParameterType::winrt(table.i32_type())) + .build(0); + assert!(setter.call_getter_i32(std::ptr::null_mut()).is_err()); + + let getter = AbiMethodSignature::new(&table) + .add_out_type(ParameterType::winrt(table.i32_type())) + .build(0); + assert!(getter.call_setter_i32(std::ptr::null_mut(), 1).is_err()); + + let boolean_setter = AbiMethodSignature::new(&table) + .add_in_type(ParameterType::winrt(table.bool_type())) + .build(0); + assert!( + boolean_setter + .call_setter_i32(std::ptr::null_mut(), 1) + .is_err() + ); + } + + #[test] + fn fast_boolean_accessors_use_u8_abi() { + let table = MetadataTable::new(); + let getter = AbiMethodSignature::new(&table) + .add_out_type(ParameterType::winrt(table.bool_type())) + .build(0); + let getter_vtable = Box::new([write_bool as *mut std::ffi::c_void]); + let getter_object = FakeComObject { + vtable: getter_vtable.as_ptr(), + calls: AtomicU32::new(0), + }; + assert!( + getter + .call_getter_bool(&getter_object as *const _ as *mut _) + .unwrap() + ); + + let setter = AbiMethodSignature::new(&table) + .add_in_type(ParameterType::winrt(table.bool_type())) + .build(0); + let setter_vtable = Box::new([record_bool as *mut std::ffi::c_void]); + let setter_object = FakeComObject { + vtable: setter_vtable.as_ptr(), + calls: AtomicU32::new(0), + }; + setter + .call_setter_bool(&setter_object as *const _ as *mut _, true) + .unwrap(); + assert_eq!(setter_object.calls.load(Ordering::Relaxed), 1); + } + #[test] fn rejects_incorrect_argument_count_before_native_call() { let table = MetadataTable::new(); diff --git a/crates/dynwinrt/src/signature.rs b/crates/dynwinrt/src/signature.rs index edb885a8..58317bbe 100644 --- a/crates/dynwinrt/src/signature.rs +++ b/crates/dynwinrt/src/signature.rs @@ -72,6 +72,54 @@ impl Method { self.0.call_getter_object(obj) } + pub fn call_setter_hstring( + &self, + obj: *mut std::ffi::c_void, + value: &windows_core::HSTRING, + ) -> windows_core::Result<()> { + self.0.call_setter_hstring(obj, value) + } + + pub fn call_setter_bool( + &self, + obj: *mut std::ffi::c_void, + value: bool, + ) -> windows_core::Result<()> { + self.0.call_setter_bool(obj, value) + } + + pub fn call_setter_i32( + &self, + obj: *mut std::ffi::c_void, + value: i32, + ) -> windows_core::Result<()> { + self.0.call_setter_i32(obj, value) + } + + pub fn call_setter_u32( + &self, + obj: *mut std::ffi::c_void, + value: u32, + ) -> windows_core::Result<()> { + self.0.call_setter_u32(obj, value) + } + + pub fn call_setter_f32( + &self, + obj: *mut std::ffi::c_void, + value: f32, + ) -> windows_core::Result<()> { + self.0.call_setter_f32(obj, value) + } + + pub fn call_setter_f64( + &self, + obj: *mut std::ffi::c_void, + value: f64, + ) -> windows_core::Result<()> { + self.0.call_setter_f64(obj, value) + } + pub fn call_dynamic( &self, obj: *mut std::ffi::c_void, diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/methods.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/methods.rs index 4659777d..b6e2c9cc 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/methods.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/methods.rs @@ -88,6 +88,84 @@ fn convert_projected_return( } } +fn fast_getter_expression( + iface_var: &str, + vtable_index: usize, + obj_expr: &str, + typ: Option<&TypeMeta>, + invoke_expr: &str, + known_types: &HashSet, + delegate_names: &HashSet, +) -> Option { + let method = match typ { + Some(TypeMeta::String) => "getString", + Some(TypeMeta::Bool) => "getBool", + Some(TypeMeta::I32 | TypeMeta::Enum { .. }) => "getI32", + Some( + TypeMeta::Object + | TypeMeta::Interface { .. } + | TypeMeta::RuntimeClass { .. } + | TypeMeta::Delegate { .. } + | TypeMeta::Parameterized { .. }, + ) => "getObj", + _ => return None, + }; + let fallback = convert_projected_return(invoke_expr, typ, known_types, delegate_names); + if method != "getObj" { + return Some(format!( + "(() => {{ const _m = {iface}.method({index}); return typeof _m.{method} === 'function' ? _m.{method}({obj}) : {fallback}; }})()", + iface = iface_var, + index = vtable_index, + obj = obj_expr, + )); + } + + let fast_value = format!( + "(() => {{ const _m = {iface}.method({index}); return typeof _m.getObj === 'function' ? _m.getObj({obj}) : _m.invoke({obj}, []); }})()", + iface = iface_var, + index = vtable_index, + obj = obj_expr, + ); + Some(convert_projected_return( + &fast_value, + typ, + known_types, + delegate_names, + )) +} + +fn setter_line( + iface_var: &str, + vtable_index: usize, + obj_expr: &str, + typ: Option<&TypeMeta>, +) -> String { + let wrapped = typ + .map(|typ| wrap_arg("value", typ)) + .unwrap_or_else(|| "value".into()); + let fallback = format!("_m.invoke({}, [{}]);", obj_expr, wrapped); + let Some(method) = (match typ { + Some(TypeMeta::String) => Some("setHstring"), + Some(TypeMeta::Bool) => Some("setBool"), + Some(TypeMeta::I32 | TypeMeta::Enum { .. }) => Some("setI32"), + Some(TypeMeta::U32) => Some("setU32"), + Some(TypeMeta::F32) => Some("setF32"), + Some(TypeMeta::F64) => Some("setF64"), + _ => None, + }) else { + return format!( + "{}.method({}).invoke({}, [{}]);", + iface_var, vtable_index, obj_expr, wrapped, + ); + }; + format!( + "{{ const _m = {iface}.method({index}); if (typeof _m.{method} === 'function') _m.{method}({obj}, value); else {fallback} }}", + iface = iface_var, + index = vtable_index, + obj = obj_expr, + ) +} + fn output_ts_type( typ: &TypeMeta, known_types: &HashSet, @@ -364,8 +442,18 @@ pub(super) fn project_static_method( "_{}.method({}).invoke({}, [])", iface.name, method.vtable_index, statics_call ); - let converted = - convert_projected_return(&invoke_expr, return_type_meta, known_types, delegate_names); + let converted = fast_getter_expression( + &format!("_{}", iface.name), + method.vtable_index, + &statics_call, + return_type_meta, + &invoke_expr, + known_types, + delegate_names, + ) + .unwrap_or_else(|| { + convert_projected_return(&invoke_expr, return_type_meta, known_types, delegate_names) + }); let doc = build_method_doc(method, &in_params); return ProjectedMember::Property(ProjectedProperty { name: prop_name, @@ -644,12 +732,23 @@ pub(super) fn project_instance_method( "{}.method({}).invoke({}, [])", iface_var, method.vtable_index, obj_expr ); - let converted = convert_projected_return( - &invoke_expr, + let converted = fast_getter_expression( + iface_var, + method.vtable_index, + obj_expr, return_type_meta, + &invoke_expr, known_types, delegate_type_names, - ); + ) + .unwrap_or_else(|| { + convert_projected_return( + &invoke_expr, + return_type_meta, + known_types, + delegate_type_names, + ) + }); // Check if there's a corresponding setter let setter = @@ -685,13 +784,11 @@ pub(super) fn project_instance_method( .map(|p| ts_param_type_safe(&p.typ, known_types)) .unwrap_or_else(|| "any".to_string()) }; - let arg = in_params - .first() - .map(|p| wrap_arg("value", &p.typ)) - .unwrap_or_else(|| "value".to_string()); - let setter_line = format!( - "{}.method({}).invoke({}, [{}]);", - iface_var, method.vtable_index, obj_expr, arg + let setter_line = setter_line( + iface_var, + method.vtable_index, + obj_expr, + in_params.first().map(|param| ¶m.typ), ); // Check if there's a corresponding getter (if so, it will add the property) @@ -1061,14 +1158,12 @@ fn find_setter_for_property( .is_some() .then(|| ts_param_type_safe(¶m.typ, known_types)) }); - let arg = setter_in_params - .first() - .map(|p| wrap_arg("value", &p.typ)) - .unwrap_or_else(|| "value".to_string()); Some(( - format!( - "{}.method({}).invoke({}, [{}]);", - iface_var, setter.vtable_index, obj_expr, arg + setter_line( + iface_var, + setter.vtable_index, + obj_expr, + setter_in_params.first().map(|param| ¶m.typ), ), setter_ts_type, )) diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs index 95a1a6fb..edce23f4 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs @@ -563,12 +563,12 @@ pub fn project_class( async_kind: AsyncKind::None, is_static: true, invoke_expr: format!( - "_IActivationFactory.method(6).invoke(DynWinRtValue.activationFactory('{}'), [])", - class.full_name + "__get_ActivateInstance().invoke({}._defaultActivationFactory(), [])", + class.name, ), sync_return_expr: Some(format!( - "{}._fromNative(_IActivationFactory.method(6).invoke(DynWinRtValue.activationFactory('{}'), []))", - class.name, class.full_name + "{}._fromNative(__get_ActivateInstance().invoke({}._defaultActivationFactory(), []))", + class.name, class.name, )), async_convert_v: None, is_void: false, @@ -847,6 +847,14 @@ pub fn project_class( let mut static_cache_fields = Vec::new(); let mut static_accessors = Vec::new(); let mut declared: HashSet = HashSet::new(); + if class.has_default_constructor { + static_cache_fields.push("static __defaultActivationFactory;".into()); + static_accessors.push(format!( + "static _defaultActivationFactory() {{ return {class}.__defaultActivationFactory ??= DynWinRtValue.activationFactory('{full}'); }}", + class = class.name, + full = class.full_name, + )); + } for iface in &class.factory_interfaces { let key = format!("f_{}", iface.name); if !iface.iid.is_empty() && declared.insert(key.clone()) { diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs index c0d00968..a7658161 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs @@ -99,6 +99,7 @@ fn render_esm(file: &ProjectedFile) -> String { // Activation factory (if needed) if file.needs_activation_factory { out.push_str("const _IActivationFactory = DynWinRtType.registerInterface('IActivationFactory', WinGuid.parse('00000035-0000-0000-c000-000000000046'))\n .addMethod('ActivateInstance', new DynWinRtMethodSig().addOut(DynWinRtType.object()));\n"); + out.push_str("let __activateInstance;\nconst __get_ActivateInstance = () => (__activateInstance ??= _IActivationFactory.method(6));\n"); out.push('\n'); } diff --git a/tools/dynwinrt-codegen/tests/element_factory_test.rs b/tools/dynwinrt-codegen/tests/element_factory_test.rs index ac896145..01579277 100644 --- a/tools/dynwinrt-codegen/tests/element_factory_test.rs +++ b/tools/dynwinrt-codegen/tests/element_factory_test.rs @@ -4,9 +4,181 @@ use std::collections::{HashMap, HashSet}; use dynwinrt_codegen::codegen::{project, python, python_stub, render_dts, render_js}; -use dynwinrt_codegen::meta::{InterfaceMeta, MethodMeta, ParamDirection, ParamMeta}; +use dynwinrt_codegen::meta::{ClassMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta}; use dynwinrt_codegen::types::TypeMeta; +#[test] +fn projection_properties_feature_detect_fast_accessors() { + fn getter(name: &str, index: usize, typ: TypeMeta) -> MethodMeta { + MethodMeta { + name: format!("get_{name}"), + raw_name: format!("get_{name}"), + vtable_index: index, + return_type: Some(typ), + is_property_getter: true, + ..Default::default() + } + } + + fn setter(name: &str, index: usize, typ: TypeMeta) -> MethodMeta { + MethodMeta { + name: format!("put_{name}"), + raw_name: format!("put_{name}"), + vtable_index: index, + params: vec![ParamMeta { + name: "value".into(), + typ, + direction: ParamDirection::In, + }], + is_property_setter: true, + ..Default::default() + } + } + + let mode = TypeMeta::Enum { + namespace: "Contoso".into(), + name: "Mode".into(), + underlying: Box::new(TypeMeta::I32), + members: vec![], + is_flags: false, + doc: None, + deprecated: None, + }; + let interface = InterfaceMeta { + name: "IProjectionFastPaths".into(), + namespace: "Contoso".into(), + iid: "11111111-1111-1111-1111-111111111111".into(), + methods: vec![ + getter("Name", 6, TypeMeta::String), + setter("Name", 7, TypeMeta::String), + getter("Enabled", 8, TypeMeta::Bool), + setter("Enabled", 9, TypeMeta::Bool), + getter("Count", 10, TypeMeta::I32), + setter("Count", 11, TypeMeta::I32), + getter("Mode", 12, mode.clone()), + setter("Mode", 13, mode), + setter("Limit", 14, TypeMeta::U32), + setter("Ratio", 15, TypeMeta::F32), + setter("Scale", 16, TypeMeta::F64), + getter("Child", 17, TypeMeta::Object), + ], + ..Default::default() + }; + let projected = project::project_interface( + &interface, + &HashSet::from(["IProjectionFastPaths".into(), "Mode".into()]), + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ); + let js = render_js::render(&projected); + + for method in [ + "getString", + "getBool", + "getI32", + "getObj", + "setHstring", + "setBool", + "setI32", + "setU32", + "setF32", + "setF64", + ] { + assert!( + js.contains(&format!("typeof _m.{method} === 'function'")), + "missing feature detection for {method}:\n{js}" + ); + } + for fallback in [ + "_m.invoke(this._obj, [DynWinRtValue.hstring(value)])", + "_m.invoke(this._obj, [DynWinRtValue.boolValue(value)])", + "_m.invoke(this._obj, [DynWinRtValue.i32(value)])", + "_m.invoke(this._obj, [DynWinRtValue.u32(value)])", + "_m.invoke(this._obj, [DynWinRtValue.f32(value)])", + "_m.invoke(this._obj, [DynWinRtValue.f64(value)])", + "_m.invoke(this._obj, [])", + ] { + assert!( + js.contains(fallback), + "missing generic invoke fallback {fallback}:\n{js}" + ); + } +} + +#[test] +fn projection_caches_activation_factories_and_activate_method() { + let class = ClassMeta { + name: "Widget".into(), + namespace: "Contoso".into(), + full_name: "Contoso.Widget".into(), + default_interface: Some(InterfaceMeta { + name: "IWidget".into(), + namespace: "Contoso".into(), + iid: "22222222-2222-2222-2222-222222222222".into(), + ..Default::default() + }), + factory_interfaces: vec![InterfaceMeta { + name: "IWidgetFactory".into(), + namespace: "Contoso".into(), + iid: "33333333-3333-3333-3333-333333333333".into(), + ..Default::default() + }], + static_interfaces: vec![InterfaceMeta { + name: "IWidgetStatics".into(), + namespace: "Contoso".into(), + iid: "44444444-4444-4444-4444-444444444444".into(), + ..Default::default() + }], + has_default_constructor: true, + ..Default::default() + }; + let projected = project::project_class( + &class, + &HashSet::from(["Widget".into()]), + &HashSet::new(), + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ); + let js = render_js::render(&projected); + + assert!(js.contains("let __activateInstance;"), "{js}"); + assert!( + js.contains( + "const __get_ActivateInstance = () => (__activateInstance ??= _IActivationFactory.method(6));" + ), + "{js}" + ); + assert!( + js.contains("static __defaultActivationFactory;") + && js.contains( + "Widget.__defaultActivationFactory ??= DynWinRtValue.activationFactory('Contoso.Widget')" + ), + "{js}" + ); + assert!( + js.contains( + "Widget._f_IWidgetFactory ??= DynWinRtValue.activationFactory('Contoso.Widget').cast(IID_IWidgetFactory)" + ), + "{js}" + ); + assert!( + js.contains( + "Widget._s_IWidgetStatics ??= DynWinRtValue.activationFactory('Contoso.Widget').cast(IID_IWidgetStatics)" + ), + "{js}" + ); + assert!( + js.contains( + "Widget._fromNative(__get_ActivateInstance().invoke(Widget._defaultActivationFactory(), []))" + ), + "{js}" + ); +} + #[test] fn element_factory_projects_js_callback_constructor() { let get_args = TypeMeta::RuntimeClass { diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/IIterator_IWwwFormUrlDecoderEntry.js b/tools/dynwinrt-codegen/tests/snapshots/uri/IIterator_IWwwFormUrlDecoderEntry.js index 2559d151..881c67a3 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/IIterator_IWwwFormUrlDecoderEntry.js +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/IIterator_IWwwFormUrlDecoderEntry.js @@ -35,11 +35,11 @@ class IIterator_IWwwFormUrlDecoderEntry { } get current() { - return ((v) => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v))(_IIterator_IWwwFormUrlDecoderEntry.method(6).invoke(this._obj, [])); + return ((v) => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v))((() => { const _m = _IIterator_IWwwFormUrlDecoderEntry.method(6); return typeof _m.getObj === 'function' ? _m.getObj(this._obj) : _m.invoke(this._obj, []); })()); } get hasCurrent() { - return _IIterator_IWwwFormUrlDecoderEntry.method(7).invoke(this._obj, []).toBool(); + return (() => { const _m = _IIterator_IWwwFormUrlDecoderEntry.method(7); return typeof _m.getBool === 'function' ? _m.getBool(this._obj) : _IIterator_IWwwFormUrlDecoderEntry.method(7).invoke(this._obj, []).toBool(); })(); } moveNext() { diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/IUriRuntimeClassWithAbsoluteCanonicalUri.js b/tools/dynwinrt-codegen/tests/snapshots/uri/IUriRuntimeClassWithAbsoluteCanonicalUri.js index 607b4f55..12686c70 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/IUriRuntimeClassWithAbsoluteCanonicalUri.js +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/IUriRuntimeClassWithAbsoluteCanonicalUri.js @@ -27,11 +27,11 @@ class IUriRuntimeClassWithAbsoluteCanonicalUri { } get absoluteCanonicalUri() { - return _IUriRuntimeClassWithAbsoluteCanonicalUri.method(6).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClassWithAbsoluteCanonicalUri.method(6); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClassWithAbsoluteCanonicalUri.method(6).invoke(this._obj, []).toString(); })(); } get displayIri() { - return _IUriRuntimeClassWithAbsoluteCanonicalUri.method(7).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClassWithAbsoluteCanonicalUri.method(7); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClassWithAbsoluteCanonicalUri.method(7).invoke(this._obj, []).toString(); })(); } } exports.IID_IUriRuntimeClassWithAbsoluteCanonicalUri = IID_IUriRuntimeClassWithAbsoluteCanonicalUri; diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/IWwwFormUrlDecoderEntry.js b/tools/dynwinrt-codegen/tests/snapshots/uri/IWwwFormUrlDecoderEntry.js index ba1d7894..b870de39 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/IWwwFormUrlDecoderEntry.js +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/IWwwFormUrlDecoderEntry.js @@ -27,11 +27,11 @@ class IWwwFormUrlDecoderEntry { } get name() { - return _IWwwFormUrlDecoderEntry.method(6).invoke(this._obj, []).toString(); + return (() => { const _m = _IWwwFormUrlDecoderEntry.method(6); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IWwwFormUrlDecoderEntry.method(6).invoke(this._obj, []).toString(); })(); } get value() { - return _IWwwFormUrlDecoderEntry.method(7).invoke(this._obj, []).toString(); + return (() => { const _m = _IWwwFormUrlDecoderEntry.method(7); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IWwwFormUrlDecoderEntry.method(7).invoke(this._obj, []).toString(); })(); } } exports.IID_IWwwFormUrlDecoderEntry = IID_IWwwFormUrlDecoderEntry; diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/Uri.js b/tools/dynwinrt-codegen/tests/snapshots/uri/Uri.js index 1d59252b..5ce43d49 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/Uri.js +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/Uri.js @@ -130,49 +130,49 @@ class Uri { return _IUriEscapeStatics.method(7).invoke(Uri.s_IUriEscapeStatics(), [DynWinRtValue.hstring(toEscape)]).toString(); } get absoluteUri() { - return _IUriRuntimeClass.method(6).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClass.method(6); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClass.method(6).invoke(this._obj, []).toString(); })(); } get displayUri() { - return _IUriRuntimeClass.method(7).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClass.method(7); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClass.method(7).invoke(this._obj, []).toString(); })(); } get domain() { - return _IUriRuntimeClass.method(8).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClass.method(8); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClass.method(8).invoke(this._obj, []).toString(); })(); } get extension() { - return _IUriRuntimeClass.method(9).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClass.method(9); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClass.method(9).invoke(this._obj, []).toString(); })(); } get fragment() { - return _IUriRuntimeClass.method(10).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClass.method(10); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClass.method(10).invoke(this._obj, []).toString(); })(); } get host() { - return _IUriRuntimeClass.method(11).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClass.method(11); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClass.method(11).invoke(this._obj, []).toString(); })(); } get password() { - return _IUriRuntimeClass.method(12).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClass.method(12); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClass.method(12).invoke(this._obj, []).toString(); })(); } get path() { - return _IUriRuntimeClass.method(13).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClass.method(13); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClass.method(13).invoke(this._obj, []).toString(); })(); } get query() { - return _IUriRuntimeClass.method(14).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClass.method(14); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClass.method(14).invoke(this._obj, []).toString(); })(); } get queryParsed() { - return ((v) => v.isNull() ? null : (__get_WwwFormUrlDecoder())._fromNative(v))(_IUriRuntimeClass.method(15).invoke(this._obj, [])); + return ((v) => v.isNull() ? null : (__get_WwwFormUrlDecoder())._fromNative(v))((() => { const _m = _IUriRuntimeClass.method(15); return typeof _m.getObj === 'function' ? _m.getObj(this._obj) : _m.invoke(this._obj, []); })()); } get rawUri() { - return _IUriRuntimeClass.method(16).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClass.method(16); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClass.method(16).invoke(this._obj, []).toString(); })(); } get schemeName() { - return _IUriRuntimeClass.method(17).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClass.method(17); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClass.method(17).invoke(this._obj, []).toString(); })(); } get userName() { - return _IUriRuntimeClass.method(18).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClass.method(18); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClass.method(18).invoke(this._obj, []).toString(); })(); } get port() { - return _IUriRuntimeClass.method(19).invoke(this._obj, []).toNumber(); + return (() => { const _m = _IUriRuntimeClass.method(19); return typeof _m.getI32 === 'function' ? _m.getI32(this._obj) : _IUriRuntimeClass.method(19).invoke(this._obj, []).toNumber(); })(); } get suspicious() { - return _IUriRuntimeClass.method(20).invoke(this._obj, []).toBool(); + return (() => { const _m = _IUriRuntimeClass.method(20); return typeof _m.getBool === 'function' ? _m.getBool(this._obj) : _IUriRuntimeClass.method(20).invoke(this._obj, []).toBool(); })(); } equals(pUri) { return _IUriRuntimeClass.method(21).invoke(this._obj, [(pUri == null ? DynWinRtValue.nullValue() : _unwrap(pUri).cast(IID_ARG_Windows_Foundation_Uri))]).toBool(); @@ -191,10 +191,10 @@ class Uri { return InterfaceClass.from(this._obj); } get absoluteCanonicalUri() { - return _IUriRuntimeClassWithAbsoluteCanonicalUri.method(6).invoke(this._obj.cast(IID_IUriRuntimeClassWithAbsoluteCanonicalUri), []).toString(); + return (() => { const _m = _IUriRuntimeClassWithAbsoluteCanonicalUri.method(6); return typeof _m.getString === 'function' ? _m.getString(this._obj.cast(IID_IUriRuntimeClassWithAbsoluteCanonicalUri)) : _IUriRuntimeClassWithAbsoluteCanonicalUri.method(6).invoke(this._obj.cast(IID_IUriRuntimeClassWithAbsoluteCanonicalUri), []).toString(); })(); } get displayIri() { - return _IUriRuntimeClassWithAbsoluteCanonicalUri.method(7).invoke(this._obj.cast(IID_IUriRuntimeClassWithAbsoluteCanonicalUri), []).toString(); + return (() => { const _m = _IUriRuntimeClassWithAbsoluteCanonicalUri.method(7); return typeof _m.getString === 'function' ? _m.getString(this._obj.cast(IID_IUriRuntimeClassWithAbsoluteCanonicalUri)) : _IUriRuntimeClassWithAbsoluteCanonicalUri.method(7).invoke(this._obj.cast(IID_IUriRuntimeClassWithAbsoluteCanonicalUri), []).toString(); })(); } } @@ -210,11 +210,11 @@ class IUriRuntimeClassWithAbsoluteCanonicalUri { } get absoluteCanonicalUri() { - return _IUriRuntimeClassWithAbsoluteCanonicalUri.method(6).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClassWithAbsoluteCanonicalUri.method(6); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClassWithAbsoluteCanonicalUri.method(6).invoke(this._obj, []).toString(); })(); } get displayIri() { - return _IUriRuntimeClassWithAbsoluteCanonicalUri.method(7).invoke(this._obj, []).toString(); + return (() => { const _m = _IUriRuntimeClassWithAbsoluteCanonicalUri.method(7); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClassWithAbsoluteCanonicalUri.method(7).invoke(this._obj, []).toString(); })(); } }