Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions Source/ReactiveProperty.Core/Internals/PropertyPathAccessor.cs
Original file line number Diff line number Diff line change
@@ -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<Delegate, Func<object, object?>> s_getters = new();
private static readonly ConditionalWeakTable<Delegate, Action<object, object?>> s_setters = new();

public static Func<object, object?> Get(Delegate accessor) => s_getters.GetValue(accessor, CreateGetter);

public static Action<object, object?> Set(Delegate accessor) => s_setters.GetValue(accessor, CreateSetter);

private static Func<object, object?> 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<Func<object, object?>>(body, source).Compile();
}

private static Action<object, object?> 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<Action<object, object?>>(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)));
}
}
12 changes: 6 additions & 6 deletions Source/ReactiveProperty.Core/Internals/PropertyPathNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ internal class PropertyPathNode : IDisposable
{
private bool _isDisposed = false;
private Action? _callback;
private Delegate? _getAccessor;
private Delegate? _setAccessor;
private Func<object, object?>? _getAccessor;
private Action<object, object?>? _setAccessor;

public event EventHandler? PropertyChanged;

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ internal class PropertyPathNodeLegacy : IDisposable
{
private bool _isDisposed = false;
private Action? _callback;
private Delegate? _getAccessor;
private Delegate? _setAccessor;
private Func<object, object?>? _getAccessor;
private Action<object, object?>? _setAccessor;

public event EventHandler? PropertyChanged;

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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<ArgumentException>(() => 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<TargetInvocationException>(() => node.Get());
Assert.IsInstanceOfType<InvalidOperationException>(getError.InnerException);
var setError = Assert.ThrowsExactly<TargetInvocationException>(() => node.Set(1));
Assert.IsInstanceOfType<InvalidOperationException>(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<ArgumentException>(() => 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<ArgumentException>(() => 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<object> Update;
public readonly Func<object> Get;
public readonly Func<object, bool> 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()
{
Expand Down
35 changes: 35 additions & 0 deletions dev-docs/adr/0009-property-path-accessor-adapters.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions dev-docs/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Loading