diff --git a/Source/ReactiveProperty.Core/Internals/PropertyPathAccessor.cs b/Source/ReactiveProperty.Core/Internals/PropertyPathAccessor.cs new file mode 100644 index 00000000..eee38908 --- /dev/null +++ b/Source/ReactiveProperty.Core/Internals/PropertyPathAccessor.cs @@ -0,0 +1,64 @@ +using System; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Reactive.Bindings.Internals; + +internal static class PropertyPathAccessor +{ + private static readonly ConditionalWeakTable> s_getters = new(); + private static readonly ConditionalWeakTable> s_setters = new(); + + public static Func Get(Delegate accessor) => s_getters.GetValue(accessor, CreateGetter); + + public static Action Set(Delegate accessor) => s_setters.GetValue(accessor, CreateSetter); + + private static Func CreateGetter(Delegate accessor) + { + var typeArguments = accessor.GetType().GetGenericArguments(); + var source = Expression.Parameter(typeof(object), "source"); + var invoke = Expression.Invoke(Expression.Constant(accessor), Expression.Convert(source, typeArguments[0])); + var fallback = Expression.Call( + Expression.Constant(accessor), + nameof(Delegate.DynamicInvoke), + Type.EmptyTypes, + Expression.NewArrayInit(typeof(object), source)); + var body = Expression.Condition( + Expression.TypeIs(source, typeArguments[0]), + Expression.Convert(WrapTargetExceptions(invoke), typeof(object)), + fallback); + return Expression.Lambda>(body, source).Compile(); + } + + private static Action CreateSetter(Delegate accessor) + { + var typeArguments = accessor.GetType().GetGenericArguments(); + var source = Expression.Parameter(typeof(object), "source"); + var value = Expression.Parameter(typeof(object), "value"); + var invoke = Expression.Invoke( + Expression.Constant(accessor), + Expression.Convert(source, typeArguments[0]), + Expression.Convert(value, typeArguments[1])); + var fallback = Expression.Call( + Expression.Constant(accessor), + nameof(Delegate.DynamicInvoke), + Type.EmptyTypes, + Expression.NewArrayInit(typeof(object), source, value)); + var body = Expression.IfThenElse( + Expression.AndAlso(Expression.TypeIs(source, typeArguments[0]), Expression.TypeIs(value, typeArguments[1])), + WrapTargetExceptions(invoke), + Expression.Block(fallback, Expression.Empty())); + return Expression.Lambda>(body, source, value).Compile(); + } + + private static Expression WrapTargetExceptions(Expression invoke) + { + var exception = Expression.Parameter(typeof(Exception), "exception"); + var constructor = typeof(TargetInvocationException).GetConstructor(new[] { typeof(Exception) })!; + // DynamicInvoke wraps exceptions thrown by the target delegate. + return Expression.TryCatch( + invoke, + Expression.Catch(exception, Expression.Throw(Expression.New(constructor, exception), invoke.Type))); + } +} diff --git a/Source/ReactiveProperty.Core/Internals/PropertyPathNode.cs b/Source/ReactiveProperty.Core/Internals/PropertyPathNode.cs index 4017bdf4..8ae1e7ef 100644 --- a/Source/ReactiveProperty.Core/Internals/PropertyPathNode.cs +++ b/Source/ReactiveProperty.Core/Internals/PropertyPathNode.cs @@ -8,8 +8,8 @@ internal class PropertyPathNode : IDisposable { private bool _isDisposed = false; private Action? _callback; - private Delegate? _getAccessor; - private Delegate? _setAccessor; + private Func? _getAccessor; + private Action? _setAccessor; public event EventHandler? PropertyChanged; @@ -69,8 +69,8 @@ private void StartObservePropertyChanged() { EnsureDispose(); if (Source == null) return null; - return (_getAccessor ?? (_getAccessor = AccessorCache.LookupGet(Source.GetType(), PropertyName))) - .DynamicInvoke(Source); + return (_getAccessor ?? (_getAccessor = PropertyPathAccessor.Get(AccessorCache.LookupGet(Source.GetType(), PropertyName)))) + .Invoke(Source); } public object? GetPropertyPathValue() @@ -101,8 +101,8 @@ public bool SetPropertyPathValue(object? value) } else { - var setter = _setAccessor ?? (_setAccessor = AccessorCache.LookupSet(Source.GetType(), PropertyName)); - setter.DynamicInvoke(Source, value); + var setter = _setAccessor ?? (_setAccessor = PropertyPathAccessor.Set(AccessorCache.LookupSet(Source.GetType(), PropertyName))); + setter(Source, value); return true; } } diff --git a/Source/ReactiveProperty.NETStandard/Internals/PropertyPathNodeLegacy.cs b/Source/ReactiveProperty.NETStandard/Internals/PropertyPathNodeLegacy.cs index 3071da11..f9f804d0 100644 --- a/Source/ReactiveProperty.NETStandard/Internals/PropertyPathNodeLegacy.cs +++ b/Source/ReactiveProperty.NETStandard/Internals/PropertyPathNodeLegacy.cs @@ -9,8 +9,8 @@ internal class PropertyPathNodeLegacy : IDisposable { private bool _isDisposed = false; private Action? _callback; - private Delegate? _getAccessor; - private Delegate? _setAccessor; + private Func? _getAccessor; + private Action? _setAccessor; public event EventHandler? PropertyChanged; @@ -70,8 +70,8 @@ private void StartObservePropertyChanged() { EnsureDispose(); if (Source == null) return null; - return (_getAccessor ?? (_getAccessor = AccessorCache.LookupGet(Source.GetType(), PropertyName))) - .DynamicInvoke(Source); + return (_getAccessor ?? (_getAccessor = PropertyPathAccessor.Get(AccessorCache.LookupGet(Source.GetType(), PropertyName)))) + .Invoke(Source); } public object? GetPropertyPathValue() @@ -102,8 +102,8 @@ public bool SetPropertyPathValue(object? value) } else { - var setter = _setAccessor ?? (_setAccessor = AccessorCache.LookupSet(Source.GetType(), PropertyName)); - setter.DynamicInvoke(Source, value); + var setter = _setAccessor ?? (_setAccessor = PropertyPathAccessor.Set(AccessorCache.LookupSet(Source.GetType(), PropertyName))); + setter(Source, value); return true; } } diff --git a/Test/ReactiveProperty.NETStandard.Tests/Internals/PropertyObservableTest.cs b/Test/ReactiveProperty.NETStandard.Tests/Internals/PropertyObservableTest.cs index 6ff68fe8..bea7ba5b 100644 --- a/Test/ReactiveProperty.NETStandard.Tests/Internals/PropertyObservableTest.cs +++ b/Test/ReactiveProperty.NETStandard.Tests/Internals/PropertyObservableTest.cs @@ -1,6 +1,9 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.ComponentModel; +using System.Reflection; using System.Runtime.CompilerServices; +using System.Threading.Tasks; using Microsoft.Reactive.Testing; using Microsoft.VisualStudio.TestTools.UnitTesting; using Reactive.Bindings; @@ -11,6 +14,175 @@ namespace ReactiveProperty.Tests.Internals; [TestClass] public class PropertyObservableTest : ReactiveTest { + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void PathAccessorPreservesNullAndReflectionConversions(bool legacy) + { + var source = new AccessorItem(); + using var node = new PathNodeHarness(legacy, nameof(AccessorItem.Number)); + node.Update(source); + + node.Set((short)7).IsTrue(); + source.Number.Is(7); + node.Set(null).IsTrue(); + source.Number.Is(0); + Assert.ThrowsExactly(() => node.Set("invalid")); + + node.Update(null); + node.Get().IsNull(); + node.Set(1).IsFalse(); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void PathAccessorPreservesNullableAndBoxedStructValues(bool legacy) + { + var source = new AccessorItem(); + using var nullable = new PathNodeHarness(legacy, nameof(AccessorItem.Optional)); + nullable.Update(source); + nullable.Set(5).IsTrue(); + source.Optional.Is(5); + nullable.Set(null).IsTrue(); + Assert.IsNull(source.Optional); + + object boxed = new AccessorStruct { Number = 1 }; + using var valueType = new PathNodeHarness(legacy, nameof(AccessorStruct.Number)); + valueType.Update(boxed); + valueType.Get().Is(1); + valueType.Set(2).IsTrue(); + ((AccessorStruct)boxed).Number.Is(1); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void PathAccessorPreservesGetterAndSetterExceptions(bool legacy) + { + using var node = new PathNodeHarness(legacy, nameof(ThrowingItem.Value)); + node.Update(new ThrowingItem()); + + var getError = Assert.ThrowsExactly(() => node.Get()); + Assert.IsInstanceOfType(getError.InnerException); + var setError = Assert.ThrowsExactly(() => node.Set(1)); + Assert.IsInstanceOfType(setError.InnerException); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void PathAccessorPreservesMissingMembersAndChangedSourceType(bool legacy) + { + using var missing = new PathNodeHarness(legacy, "Missing"); + missing.Update(new AccessorItem()); + Assert.ThrowsExactly(() => missing.Get()); + + using var node = new PathNodeHarness(legacy, nameof(AccessorItem.Number)); + node.Update(new AccessorItem()); + node.Set(1).IsTrue(); + node.Update(new OtherAccessorItem { Number = 9 }); + node.Get().Is(9); + Assert.ThrowsExactly(() => node.Set(2)); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void RepeatedPathReadsAvoidExcessAllocation(bool legacy) + { + using var node = new PathNodeHarness(legacy, nameof(AccessorItem.Text)); + node.Update(new AccessorItem()); + for (var i = 0; i < 32; i++) + { + GC.KeepAlive(node.Get()); + } + + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 64; i++) + { + GC.KeepAlive(node.Get()); + } + + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.IsTrue(allocated < 64 * 8, $"Allocated {allocated} bytes for 64 path reads."); + } + + [TestMethod] + public void PathAccessorCacheSupportsConcurrentFirstUse() + { + Parallel.For(0, 64, i => + { + var source = new ConcurrentAccessorItem { Number = i }; + using var node = new PathNodeHarness(i % 2 == 0, nameof(ConcurrentAccessorItem.Number)); + node.Update(source); + Assert.AreEqual(i, node.Get()); + Assert.IsTrue(node.Set(i + 1)); + Assert.AreEqual(i + 1, source.Number); + }); + } + + private sealed class PathNodeHarness : IDisposable + { + public readonly Action Update; + public readonly Func Get; + public readonly Func Set; + private readonly IDisposable _node; + + public PathNodeHarness(bool legacy, string propertyName) + { + if (legacy) + { + var node = new PropertyPathNodeLegacy(propertyName); + _node = node; + Update = node.UpdateSource; + Get = node.GetPropertyPathValue; + Set = node.SetPropertyPathValue; + } + else + { + var node = new PropertyPathNode(propertyName); + _node = node; + Update = node.UpdateSource; + Get = node.GetPropertyPathValue; + Set = node.SetPropertyPathValue; + } + } + + public void Dispose() => _node.Dispose(); + } + + private sealed class AccessorItem + { + public int Number { get; set; } + public int? Optional { get; set; } + public string Text { get; set; } = "value"; + } + + private struct AccessorStruct + { + public int Number { get; set; } + } + + private sealed class OtherAccessorItem + { + public int Number { get; set; } + } + + private sealed class ConcurrentAccessorItem + { + public int Number { get; set; } + } + + private sealed class ThrowingItem + { + public int Value + { + get => throw new InvalidOperationException("getter"); + set => throw new InvalidOperationException("setter"); + } + } + [TestMethod] public void ObserveProperty() { diff --git a/dev-docs/adr/0009-property-path-accessor-adapters.md b/dev-docs/adr/0009-property-path-accessor-adapters.md new file mode 100644 index 00000000..6cf7956f --- /dev/null +++ b/dev-docs/adr/0009-property-path-accessor-adapters.md @@ -0,0 +1,35 @@ +# 0009. Cache property-path accessor adapters + +- **Status:** Proposed +- **Date:** 2026-11-17 +- **Deciders:** ReactiveProperty maintainers + +## Context + +Core and Legacy property paths invoke cached typed property delegates through +`DynamicInvoke`, allocating argument arrays on repeated reads and writes. These +paths also rely on reflection's argument handling and target-exception wrapping. + +## Decision + +Cache object-based getter and setter adapters per existing accessor delegate. +For compatible, non-null arguments, adapters invoke the typed delegate directly +and wrap target exceptions in `TargetInvocationException`. For other arguments, +use `DynamicInvoke` to preserve its conversions and failures. Both path +implementations share the adapters; public and protected APIs stay unchanged. + +### Alternatives considered + +- **Continue using `DynamicInvoke`** — preserves behavior but retains repeated + reflection invocation and allocations. +- **Change accessor APIs to expose object delegates** — would affect existing + extension points and require a wider compatibility change. + +## Consequences + +Steady-state invocations avoid reflection argument arrays for compatible values, +at the cost of compiling an adapter the first time each accessor is used. +The weak-key cache is thread-safe, although concurrent first use can compile +more than one adapter. Existing property discovery and expression compilation +already rely on reflection and dynamic code; trimming and Native AOT have not +been validated for this change. diff --git a/dev-docs/adr/README.md b/dev-docs/adr/README.md index 5482e81e..9ec6bc68 100644 --- a/dev-docs/adr/README.md +++ b/dev-docs/adr/README.md @@ -32,6 +32,8 @@ Trivial, easily reversible choices (local refactors, naming) do not need an ADR. ## Index +Proposed follow-up: [0009. Cache property-path accessor adapters](./0009-property-path-accessor-adapters.md). + | ADR | Title | Status | |-----|-------|--------| | [0001](./0001-adopt-tdd-adr-and-dev-docs.md) | Adopt TDD, ADRs, and a dev-docs location | Accepted |