diff --git a/runtime/src/class_helpers.rs b/runtime/src/class_helpers.rs index 602c251..6c93024 100644 --- a/runtime/src/class_helpers.rs +++ b/runtime/src/class_helpers.rs @@ -383,6 +383,112 @@ pub(crate) fn overload_for_argc(bound: &MethodDeclaration, argc: usize) -> Optio }) } +/// Whether `p` is an in parameter. Out parameters keep their argument position, but a call may +/// leave trailing ones out (they come back in the result). +fn is_input_param(p: &metadata::declarations::parameter_declaration::ParameterDeclaration) -> bool { + !p.is_out() + && !p.metadata().map_or(false, |md| { + metadata::signature::Signature::to_string(md, &p.type_()) + .trim() + .starts_with("ByRef ") + }) +} + +fn arity_matches(m: &MethodDeclaration, argc: usize) -> bool { + argc == m.number_of_parameters() + || argc == m.parameters().iter().filter(|p| is_input_param(p)).count() +} + +/// Field names of the struct a parameter takes, or None for any other type. +fn struct_param_fields( + p: &metadata::declarations::parameter_declaration::ParameterDeclaration, +) -> Option> { + use metadata::declarations::declaration::DeclarationKind; + use metadata::declarations::struct_declaration::StructDeclaration; + let sig = metadata::signature::Signature::to_string(p.metadata()?, &p.type_()); + let sig = sig.trim(); + if !sig.contains('.') { + return None; + } + let decl = MetadataReader::find_by_name(crate::helpers::strip_generic_suffix(sig))?; + let lock = decl.read(); + if lock.kind() != DeclarationKind::Struct { + return None; + } + let sd = lock.as_any().downcast_ref::()?; + Some(sd.fields().iter().map(|f| f.name().to_string()).collect()) +} + +/// Index of the overload in `candidates` (methods sharing a public name) that a call with `argc` +/// arguments means. The argument count decides first. Overloads can share it +/// (VisualTreeHelper.FindElementsInHostCoordinates takes a Point or a Rect), so then the one whose +/// struct parameters' fields an object argument all has, matching the most fields, wins; then +/// [DefaultOverload]; then metadata order. `has(j, name)` is whether argument `j` has property +/// `name`, or None when it is not a plain object (a buffer, a primitive). +pub(crate) fn pick_overload( + candidates: &[MethodDeclaration], + argc: usize, + mut has: impl FnMut(usize, &str) -> Option, +) -> usize { + let same_arity: Vec = (0..candidates.len()) + .filter(|&i| arity_matches(&candidates[i], argc)) + .collect(); + match same_arity.len() { + 0 => { + return candidates + .iter() + .position(|m| m.is_default_overload()) + .unwrap_or(0) + } + 1 => return same_arity[0], + _ => {} + } + let mut best: Option<(usize, (bool, usize, bool))> = None; + for &i in &same_arity { + let m = &candidates[i]; + let (mut fits, mut fields) = (true, 0usize); + for (j, p) in m.parameters().iter().enumerate() { + if j >= argc || !is_input_param(p) { + continue; + } + let Some(names) = struct_param_fields(p).filter(|n| !n.is_empty()) else { + continue; + }; + if has(j, &names[0]).is_none() { + continue; + } + if names.iter().all(|n| has(j, n) == Some(true)) { + fields += names.len(); + } else { + fits = false; + } + } + let key = (fits, fields, m.is_default_overload()); + if best.as_ref().map_or(true, |(_, k)| key > *k) { + best = Some((i, key)); + } + } + best.map_or(same_arity[0], |(i, _)| i) +} + +/// [`pick_overload`] for a classic-engine call. +#[cfg(feature = "classic")] +pub(crate) fn pick_static_overload( + candidates: &[MethodDeclaration], + scope: &mut v8::PinScope<'_, '_>, + args: &v8::FunctionCallbackArguments, +) -> usize { + pick_overload(candidates, args.length() as usize, |j, name| { + let arg = args.get(j as i32); + if !arg.is_object() || arg.is_array_buffer() || arg.is_array_buffer_view() { + return None; + } + let obj = arg.to_object(scope)?; + let key = v8::String::new(scope, name)?; + obj.has(scope, key.into()) + }) +} + pub(crate) fn class_method_matches(class_declaration: &ClassDeclaration, name: &str) -> bool { let method_match = |m: &MethodDeclaration| { let on = m.overload_name(); diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 6cdc511..887b493 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -1305,7 +1305,15 @@ pub(crate) fn return_value_from_kind<'a>( let data = (result as *const u8).add(8) as *const c_void; received_array_from_slots(kind, result, data, scope) }, - ReturnKind::InterfaceObject { decl, type_name } => { + // Wrap by the runtime class: an interface such as IPropertySet declares no members itself + // and only requires the generic IMap/IIterable instances, and an unsealed class may be a + // subclass (VisualTreeHelper.GetParent declares DependencyObject and returns a Grid). + ReturnKind::InterfaceObject { decl, type_name } + | ReturnKind::Object { + decl, + type_name, + sealed: false, + } => { if result.is_null() { v8::null(scope).into() } else { @@ -1314,8 +1322,6 @@ pub(crate) fn return_value_from_kind<'a>( if let Some(local) = crate::wrapper_cache::get_for(scope, &instance) { return local.into(); } - // Wrap by the runtime class: an interface such as IPropertySet declares no - // members itself and only requires the generic IMap/IIterable instances. match crate::ns_proxy::resolve_runtime_class(&instance, type_name.as_ref()) { Some((name, class)) => { let instance = Some(instance); @@ -1951,6 +1957,88 @@ pub(crate) fn class_activation_factory(full_name: &str) -> windows::core::Result Ok(factory) } +/// One call of a static method bound to `dec` (see `create_ns_ctor_object`). +#[cfg(feature = "classic")] +fn call_static_method( + scope: &mut v8::PinScope<'_, '_>, + args: &v8::FunctionCallbackArguments, + retval: &mut v8::ReturnValue, + dec: &DeclarationFFI, +) { + let lock = dec.read(); + + let Some(method) = lock.as_any().downcast_ref::() else { + return; + }; + + // The class activation factory is a process-lifetime singleton, so the + // call is resolved (factory lookup + QueryInterface + vtable slot) once + // per static method and every invocation borrows that resolution. + let mut method = match dec.prepared_method.get() { + Some(prepared) => MethodCall::from_prepared(prepared), + None => { + let factory = match resolve_class_factory_from_parent(dec) { + Ok(factory) => factory, + Err(error) => { + throw_js_error( + scope, + format!( + "Failed to resolve WinRT static method factory for {}: {}", + method.name(), + error.message() + ) + .as_str(), + ); + return; + } + }; + match MethodCall::prepare(method, method.is_sealed(), factory.clone(), false) { + Some(prepared) => { + let _ = dec.prepared_method.set(prepared); + MethodCall::from_prepared(dec.prepared_method.get().unwrap()) + } + // The owned path reports the interface error. + None => MethodCall::new(method, method.is_sealed(), factory, false), + } + } + }; + + let (ret, result, outs) = method.call(scope, args); + + if ret.is_ok() { + if !outs.is_empty() { + let mut arr_len = outs.len(); + if !method.is_void() { + arr_len += 1; + } + let arr = v8::Array::new(scope, arr_len as i32); + let mut idx = 0u32; + + if !method.is_void() { + let rv = + return_value_from_kind(method.return_kind(), result, dec.parent.clone(), scope); + arr.set_index(scope, idx, rv); + idx += 1; + } + + for outv in outs.into_iter() { + arr.set_index(scope, idx, outv); + idx += 1; + } + retval.set(arr.into()); + return; + } + + let v = return_value_from_kind(method.return_kind(), result, dec.parent.clone(), scope); + retval.set(v); + } else { + let detail = crate::error::format_hresult_message(ret); + let message = v8::String::new(scope, &detail).unwrap(); + let error = v8::Exception::error(scope, message.into()); + scope.throw_exception(error); + } +} + #[cfg(feature = "classic")] pub(crate) fn resolve_class_factory_from_parent( dec: &DeclarationFFI, @@ -6926,135 +7014,80 @@ fn create_ns_ctor_object<'a>( return v8::undefined(scope).into(); }; let mut added_names: AHashSet = AHashSet::new(); - - for method in clazz.methods().iter() { - let name = v8::String::new(scope, method.name()); - let is_static = method.is_static(); - - if !is_static { - continue; + // Statics grouped by public name, in metadata order. Overloads with an [Overload] name + // are also reachable by it, as instance methods are. + let mut statics: Vec<(String, Vec)> = Vec::new(); + for method in clazz.methods().iter().filter(|m| m.is_static()) { + match statics.iter_mut().find(|(n, _)| n == method.name()) { + Some((_, group)) => group.push(method.clone()), + None => statics.push((method.name().to_string(), vec![method.clone()])), } - - // Skip duplicate method/property names to avoid adding the same - // descriptor multiple times to the FunctionTemplate which can - // corrupt V8 internal descriptor arrays. - let m_name = method.name(); - if added_names.contains(m_name) { - continue; + } + let mut entries = statics.clone(); + for (_, group) in statics.iter().filter(|(_, g)| g.len() > 1) { + for method in group { + let overload = method.overload_name(); + if !overload.is_empty() && !entries.iter().any(|(n, _)| n == overload) { + entries.push((overload.to_string(), vec![method.clone()])); + } } - added_names.insert(m_name.to_string()); - - let parent = Arc::clone(&declaration); - - let mut declaration = - DeclarationFFI::new_with_instance(Arc::new(RwLock::new(method.clone())), None); - - declaration.parent = Some(parent); - - let declaration = Box::into_raw(Box::new(declaration)); - - let ext = v8::External::new(scope, declaration as _); - - let func = v8::FunctionTemplate::builder( - |scope: &mut v8::PinScope<'_, '_>, - args: v8::FunctionCallbackArguments, - mut retval: v8::ReturnValue| { - let dec = unsafe { args.data().cast::() }; - - let dec = dec.value() as *mut DeclarationFFI; - - let dec = unsafe { &*dec }; - - let lock = dec.read(); - - let Some(method) = lock.as_any().downcast_ref::() else { - return; - }; - - // The class activation factory is a process-lifetime singleton, so the - // call is resolved (factory lookup + QueryInterface + vtable slot) once - // per static method and every invocation borrows that resolution. - let mut method = match dec.prepared_method.get() { - Some(prepared) => MethodCall::from_prepared(prepared), - None => { - let factory = match resolve_class_factory_from_parent(dec) { - Ok(factory) => factory, - Err(error) => { - throw_js_error( - scope, - format!( - "Failed to resolve WinRT static method factory for {}: {}", - method.name(), - error.message() - ) - .as_str(), - ); - return; - } - }; - match MethodCall::prepare( - method, - method.is_sealed(), - factory.clone(), - false, - ) { - Some(prepared) => { - let _ = dec.prepared_method.set(prepared); - MethodCall::from_prepared(dec.prepared_method.get().unwrap()) - } - // The owned path reports the interface error. - None => MethodCall::new(method, method.is_sealed(), factory, false), - } - } - }; - - let (ret, result, outs) = method.call(scope, &args); - - if ret.is_ok() { - if !outs.is_empty() { - let mut arr_len = outs.len(); - if !method.is_void() { - arr_len += 1; - } - let arr = v8::Array::new(scope, arr_len as i32); - let mut idx = 0u32; + } - if !method.is_void() { - let rv = return_value_from_kind( - method.return_kind(), - result, - dec.parent.clone(), - scope, - ); - arr.set_index(scope, idx, rv); - idx += 1; - } + for (js_name, group) in entries.iter() { + added_names.insert(js_name.clone()); + let name = v8::String::new(scope, js_name); + let decs: Vec<*mut DeclarationFFI> = group + .iter() + .map(|method| { + let mut ffi = DeclarationFFI::new_with_instance( + Arc::new(RwLock::new(method.clone())), + None, + ); + ffi.parent = Some(Arc::clone(&declaration)); + Box::into_raw(Box::new(ffi)) + }) + .collect(); - for outv in outs.into_iter() { - arr.set_index(scope, idx, outv); - idx += 1; - } - retval.set(arr.into()); + let func = if let [dec] = decs.as_slice() { + let ext = v8::External::new(scope, *dec as _); + v8::FunctionTemplate::builder( + |scope: &mut v8::PinScope<'_, '_>, + args: v8::FunctionCallbackArguments, + mut retval: v8::ReturnValue| { + let dec = unsafe { args.data().cast::() }; + let dec = unsafe { &*(dec.value() as *mut DeclarationFFI) }; + call_static_method(scope, &args, &mut retval, dec); + }, + ) + .data(ext.into()) + .build(scope) + } else { + let ext = v8::External::new(scope, Box::into_raw(Box::new(decs)) as _); + v8::FunctionTemplate::builder( + |scope: &mut v8::PinScope<'_, '_>, + args: v8::FunctionCallbackArguments, + mut retval: v8::ReturnValue| { + let decs = unsafe { args.data().cast::() }; + let decs = unsafe { &*(decs.value() as *const Vec<*mut DeclarationFFI>) }; + let methods: Vec = decs + .iter() + .filter_map(|d| { + let d = unsafe { &**d }; + let lock = d.read(); + lock.as_any().downcast_ref::().cloned() + }) + .collect(); + if methods.len() != decs.len() { return; } - - let v = return_value_from_kind( - method.return_kind(), - result, - dec.parent.clone(), - scope, - ); - retval.set(v); - } else { - let detail = crate::error::format_hresult_message(ret); - let message = v8::String::new(scope, &detail).unwrap(); - let error = v8::Exception::error(scope, message.into()); - scope.throw_exception(error); - } - }, - ) - .data(ext.into()) - .build(scope); + let i = crate::class_helpers::pick_static_overload(&methods, scope, &args); + let dec = unsafe { &*decs[i] }; + call_static_method(scope, &args, &mut retval, dec); + }, + ) + .data(ext.into()) + .build(scope) + }; tmpl.set(name.unwrap().into(), func.into()); } diff --git a/runtime/src/napi_engine/ns_hostobject.rs b/runtime/src/napi_engine/ns_hostobject.rs index ceb02ec..e7f7eb3 100644 --- a/runtime/src/napi_engine/ns_hostobject.rs +++ b/runtime/src/napi_engine/ns_hostobject.rs @@ -165,6 +165,15 @@ pub fn is_interface(declaration: &Decl) -> bool { ) } +/// True iff `declaration` is a class other types can derive from, so an object declared as it +/// may be a subclass (`VisualTreeHelper.GetParent` declares `DependencyObject` and returns a Grid). +pub fn is_unsealed_class(declaration: &Decl) -> bool { + let lock = declaration.read(); + lock.as_any() + .downcast_ref::() + .is_some_and(|class| !class.is_sealed()) +} + /// The metadata class named by `instance`'s GetRuntimeClassName. pub fn runtime_class(instance: &IUnknown) -> Option<(String, Decl)> { let inspectable = instance.cast::().ok()?; @@ -291,13 +300,20 @@ fn collect_args(ctx: &CallContext) -> napi::Result> { Ok(args) } -/// The overload whose parameter count matches the supplied argument count, by index into -/// `overloads`; the first overload when none matches (the call then raises a JS error). -fn pick_overload(overloads: &[MethodDeclaration], argc: usize) -> usize { - overloads - .iter() - .position(|m| m.number_of_parameters() == argc) - .unwrap_or(0) +/// The overload a call with `args` means, by index into `overloads` (see +/// `class_helpers::pick_overload`: argument count, then the shape of struct arguments). +fn pick_overload(overloads: &[MethodDeclaration], args: &[JsUnknown]) -> usize { + crate::class_helpers::pick_overload(overloads, args.len(), |j, name| { + let arg = args.get(j)?; + if arg.get_type().ok()? != napi::ValueType::Object + || arg.is_typedarray().unwrap_or(false) + || arg.is_dataview().unwrap_or(false) + { + return None; + } + let object: JsObject = unsafe { arg.cast() }; + object.has_named_property(name).ok() + }) } /// The value in `cell`, filling it through `prepare` on the first call. `None` when the cell @@ -468,7 +484,7 @@ fn class_prototype(env: &Env, class_name: &str) -> napi::Result { let env = &ctx.env; let handle = this_handle(&ctx)?; let args = collect_args(&ctx)?; - let method = &overloads[pick_overload(&overloads, args.len())]; + let method = &overloads[pick_overload(&overloads, &args)]; invoke_host_method(env, handle, method, is_sealed, &args).map_err(napi_err) })?; proto.set_named_property(js_name, f)?; @@ -771,7 +787,7 @@ pub fn build_host_ctor(env: &Env, class_name: &str, declaration: Decl) -> napi:: let env = &ctx.env; crate::napi_engine::invoke::ensure_winrt_initialized(); let args = collect_args(&ctx)?; - let idx = pick_overload(&overloads, args.len()); + let idx = pick_overload(&overloads, &args); let method = &overloads[idx]; let prepared = get_or_prepare(&cells[idx], || { let factory = crate::class_activation_factory(&cls).ok()?; diff --git a/runtime/src/napi_engine/ns_proxy.rs b/runtime/src/napi_engine/ns_proxy.rs index c33b60d..ddcbba4 100644 --- a/runtime/src/napi_engine/ns_proxy.rs +++ b/runtime/src/napi_engine/ns_proxy.rs @@ -1223,10 +1223,14 @@ pub fn create_instance_proxy( ) -> napi::Result { let identity = com_identity_key(&instance); - // An interface-typed return of an object that already has a class wrapper reuses it - // without asking for the runtime class again. + // The object may be of a more derived class than declared: an interface, or a class others + // derive from (`VisualTreeHelper.GetParent` declares `DependencyObject` and returns a Grid). + let interface = crate::napi_engine::ns_hostobject::is_interface(&declaration); + let open = interface || crate::napi_engine::ns_hostobject::is_unsealed_class(&declaration); + + // One that already has a class wrapper reuses it without asking for the runtime class again. if let Some(id) = identity { - if crate::napi_engine::ns_hostobject::is_interface(&declaration) { + if open { if let Some(existing) = cached_class_instance(env, id) { return Ok(existing); } @@ -1234,18 +1238,18 @@ pub fn create_instance_proxy( } // Hybrid fast path: wrap non-collection *class* instances as host objects (shared prototype, - // no Proxy trap). The effective type is the class from the declaration when it is itself a - // host-eligible class (`new` path), or — for interface-typed returns like `IJsonValue` whose - // concrete object is a class (`JsonValue`) — resolved from the runtime class name. Interfaces - // proper and indexable collections fall through to the Proxy below. - let host_target: Option<(String, Decl)> = - if crate::napi_engine::ns_hostobject::should_host(class_name, &declaration) { - Some((class_name.to_string(), declaration.clone())) - } else if crate::napi_engine::ns_hostobject::is_interface(&declaration) { - crate::napi_engine::ns_hostobject::runtime_class_host_target(&instance) - } else { - None - }; + // no Proxy trap). The effective type is the runtime class when the declared type is open and + // metadata has it, else the declared class when it is itself host-eligible (`new` path). + // Interfaces proper and indexable collections fall through to the Proxy below. + let host_target: Option<(String, Decl)> = if interface { + crate::napi_engine::ns_hostobject::runtime_class_host_target(&instance) + } else if crate::napi_engine::ns_hostobject::should_host(class_name, &declaration) { + open.then(|| crate::napi_engine::ns_hostobject::runtime_class_host_target(&instance)) + .flatten() + .or_else(|| Some((class_name.to_string(), declaration.clone()))) + } else { + None + }; if let Some((eff_name, _eff_decl)) = host_target { if let Some(id) = identity { if let Some(existing) = cached_instance(env, id, &eff_name) { @@ -1264,9 +1268,7 @@ pub fn create_instance_proxy( // An interface such as IPropertySet declares no members itself (only the generic IMap and // IIterable it requires), so proxy the runtime class when metadata has it. - let resolved = if !class_name.contains('<') - && crate::napi_engine::ns_hostobject::is_interface(&declaration) - { + let resolved = if !class_name.contains('<') && open { crate::napi_engine::ns_hostobject::runtime_class(&instance) } else { None