Skip to content

[Blazor] Generate AOT-safe binding metadata - #68297

Open
javiercn wants to merge 6 commits into
javiercn-aot-stack-2-jsinteropfrom
javiercn-aot-stack-3-binding
Open

javiercn wants to merge 6 commits into
javiercn-aot-stack-2-jsinteropfrom
javiercn-aot-stack-3-binding

Conversation

@javiercn

@javiercn javiercn commented Aug 8, 2026 •

Copy link
Copy Markdown
Member

Overview

Stack layer 3/6 for #68332, stacked on #68296. Across six commits and 39 files, this change removes runtime generic closure from enum/array binding, evaluates supported form expressions without compiling them, and extends the existing application metadata generator with bindable model graphs and accessors.

The cross-cutting constraint is generated first, reflection last: described models use statically analyzable delegates, while undescribed models and unsupported expression shapes keep the existing compatibility fallback. This layer does not add component metadata, framework providers, strict-mode switches, or general FormMapping Native AOT support; the generator surface remains JsonTypeInfoResolver, JSInvokableMethods, and BindableTypes only.

Design

Applications opt a normal C# model into generation explicitly. The explicit model root is required because source generators cannot observe Razor types produced by another generator in the same compilation; ordinary model types are visible and can seed the complete reachable graph.

// src/Components/Web/src/Metadata/BindableModelAttribute.cs
// One declaration names a form root; the generator follows its fields, properties,
// collection element types, array elements, and single-argument indexers transitively.
[Experimental("ASPNETCORE9004", UrlFormat = "https://aka.ms/aspnet/analyzer/{0}")]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class BindableModelAttribute : Attribute
{
    public required Type ModelType { get; init; }
}

The generated contract describes only the model-side hops a binding expression may traverse. The component-side prefix is deliberately not described: the evaluator anchors the walk at the EditContext.Model, reducing metadata and avoiding a dependency on generated component types.

// src/Components/Components/src/Infrastructure/BindableTypeDescriptor.cs
// Members cover fields and properties; indexers are matched by their argument type.
// Arrays need no descriptor because the evaluator can use Array.GetValue directly.
[Experimental("ASPNETCORE9004", UrlFormat = "https://aka.ms/aspnet/analyzer/{0}")]
public sealed class BindableTypeDescriptor
{
    public required Type Type { get; init; }
    public IReadOnlyList<BindableMemberDescriptor> Members { get; init; } = [];
    public IReadOnlyList<BindableIndexerDescriptor> Indexers { get; init; } = [];
}

BindableMemberDescriptor carries Name, MemberType, and Func<object, object?> GetValue; BindableIndexerDescriptor carries IndexType, ValueType, and Func<object, object?, object?> GetValue. These sibling contracts use delegates rather than MemberInfo, so generated access is statically analyzable and private members can be bridged with generated UnsafeAccessor methods.

The existing metadata context gains the bindable list at the same point it is first emitted and consumed:

// src/Components/Web/src/Metadata/RazorComponentsMetadataContext.cs
public abstract class RazorComponentsMetadataContext
{
    public abstract IReadOnlyList<BindableTypeDescriptor> BindableTypes { get; }
    public abstract IReadOnlyList<JSInvokableMethodDescriptor> JSInvokableMethods { get; }
    public abstract IJsonTypeInfoResolver? JsonTypeInfoResolver { get; }
}

The rejected alternatives were runtime MakeGenericMethod/Expression.Compile (not available under Native AOT), describing component roots (unnecessary and unavailable to this generator layer), and removing reflection entirely (would break the default compatibility contract).

Implementation

BindConverter retains its existing specialized generic delegates when dynamic code is available, but selects non-generic enum APIs and reflectionless array construction otherwise. Enum and nullable-enum parsing are one equivalence class; array parsing and formatting are the second.

// src/Components/Components/src/BindConverter.cs
// JIT keeps the existing closed generic fast path. Native AOT does not attempt to
// manufacture a missing generic instantiation at runtime.
if (typeof(T).IsEnum)
{
    if (RuntimeFeature.IsDynamicCodeSupported)
    {
        var method = _convertToEnum ??= typeof(BindConverter).GetMethod(
            nameof(ConvertToEnum), BindingFlags.NonPublic | BindingFlags.Static)!;
        parser = method.MakeGenericMethod(typeof(T)).CreateDelegate(typeof(BindParser<T>), target: null);
    }
    else
    {
        parser = (BindParser<T>)ConvertToEnumDynamicCodeSafe<T>;
    }
}
else if (typeof(T).IsArray)
{
    if (RuntimeFeature.IsDynamicCodeSupported)
    {
        // Existing typed array converter construction — unchanged.
        var method = _makeArrayTypeConverter ??= typeof(ParserDelegateCache).GetMethod(
            nameof(MakeArrayTypeConverter), BindingFlags.NonPublic | BindingFlags.Static)!;
        parser = (Delegate)method.MakeGenericMethod(typeof(T).GetElementType()!).Invoke(null, null)!;
    }
    else
    {
        EnsureCanParseElementType(typeof(T).GetElementType()!);
        parser = (BindParser<T>)ConvertToArrayDynamicCodeSafe;
    }
}

The AOT array path preserves the exact runtime array type—including nested and non-vector array shapes—then converts each element through the same non-generic element dispatcher. Formatting mirrors the same branch and JSON-escapes each formatted element. Nullable enums use the same non-generic Enum.TryParse(Type, ...) pattern after recovering Nullable.GetUnderlyingType(typeof(T)); InputSelect<TValue> contains only the narrow closed-path suppression beside its array binder.

// src/Components/Components/src/BindConverter.cs
private static bool ConvertToArrayDynamicCodeSafe<T>(
    object? obj,
    CultureInfo? culture,
    [MaybeNullWhen(false)] out T value)
{
    if (obj is not Array initialArray)
    {
        value = default;
        return false;
    }

    var arrayType = typeof(T);
    var elementType = arrayType.GetElementType()!;
    var convertedArray = Array.CreateInstanceFromArrayType(arrayType, initialArray.Length);
    for (var i = 0; i < initialArray.Length; i++)
    {
        if (!TryConvertElement(initialArray.GetValue(i), elementType, culture, out var converted))
        {
            value = default;
            return false;
        }

        convertedArray.SetValue(converted, i);
    }

    value = (T)(object)convertedArray;
    return true;
}

InputBase<TValue> and ValidationMessage<TValue> now enter through one evaluator. It recognizes member access, single-argument indexers, and array indexing; unsupported shapes still call FieldIdentifier.Create, preserving previous behavior. Captured index values also avoid Expression.Compile when dynamic code is unavailable by reading the PropertyInfo or FieldInfo already embedded in the expression.

// src/Components/Web/src/Forms/BindingExpressionEvaluator.cs
// For model.Address.Street, the walk anchors at model, reads Address, and returns
// FieldIdentifier(model.Address, "Street"). Descriptors win; reflection is the fallback.
private static object? ReadMember(
    object target,
    MemberExpression member,
    IBindableTypeResolver? resolver)
{
    if (resolver is not null &&
        resolver.TryGetBindableTypeDescriptor(member.Expression!.Type, out var descriptor))
    {
        foreach (var described in descriptor.Members)
        {
            if (string.Equals(described.Name, member.Member.Name, StringComparison.Ordinal))
            {
                return described.GetValue(target);
            }
        }
    }

    return member.Member switch
    {
        PropertyInfo property => property.GetValue(target),
        FieldInfo field => field.GetValue(target),
        _ => throw new ArgumentException(
            $"The provided expression contains a {member.Member.GetType().Name} which is not supported. " +
            $"{nameof(FieldIdentifier)} only supports simple member accessors (fields, properties) of an object."),
    };
}

Generation follows the full bindable graph breadth-first, deduplicates cycles and inherited hidden members, follows array elements and generic type arguments, and stops at primitive/framework leaves. Directly accessible members become direct delegates; inaccessible properties and fields use generated UnsafeAccessor bridges. Single-argument indexers are emitted as typed delegates, while unsupported/inaccessible members are omitted with a targeted diagnostic for an inaccessible root.

// src/Components/Endpoints/gen/RazorComponentsMetadataGenerator.Bindables.cs
// Root -> Child -> Root terminates because visited deduplicates symbols.
// List<Order> enqueues both the collection type and Order, so row.Name is covered.
var results = new Dictionary<string, BindableTypeModel>(StringComparer.Ordinal);
var visited = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default);
var queue = new Queue<INamedTypeSymbol>();

while (queue.Count > 0)
{
    var type = queue.Dequeue();
    if (!visited.Add(type) || IsLeafType(type))
    {
        continue;
    }

    // Collect instance fields, properties, and one-argument indexers.
    // Enqueue their value types, array elements, and generic arguments.
}

Registration composes multiple metadata contexts once into a type-keyed resolver. The renderer carries that resolver through RenderHandle, so form components use generated descriptors without introducing a process-static registry; later providers do not mutate an already-built service provider.

// src/Components/Web/src/Metadata/ComponentBindableTypeResolver.cs
internal sealed class ComponentBindableTypeResolver : IBindableTypeResolver
{
    private readonly Dictionary<Type, BindableTypeDescriptor> _bindableTypesByType = [];

    public ComponentBindableTypeResolver(IEnumerable<RazorComponentsMetadataContext> contexts)
    {
        foreach (var context in contexts)
        {
            foreach (var descriptor in context.BindableTypes)
            {
                _bindableTypesByType[descriptor.Type] = descriptor;
            }
        }
    }

    public bool TryGetBindableTypeDescriptor(
        Type type,
        [NotNullWhen(true)] out BindableTypeDescriptor? descriptor)
        => _bindableTypesByType.TryGetValue(type, out descriptor);
}

Outcome

Equivalence class What is covered Validation
Enum and nullable-enum conversion Defined/undefined values, empty input semantics, parity with the dynamic-code path BindConverterTest: 41 passed
Array parsing and formatting Primitive, enum, nullable, nested, multidimensional/runtime array shapes; Endpoints converter construction remains annotation-safe FormDataMapperTests: 282 passed
Expression walking Single/nested members, fields, captured indexes, list indexers, arrays, model anchoring, null hops, and fallback parity with FieldIdentifier.Create BindingExpressionEvaluatorTest: 9 passed
Generated bindable graphs Public/private fields and properties, UnsafeAccessor, indexers, inheritance/hiding, transitive arrays/collections, cycles, stable ordering, unsupported members, and per-provider resolver isolation Repository Test target on MSTest/MTP: 15 passed, including all 5 bindable generator scenarios
Trimming/linkability Binding changes introduce no new linker diagnostics in the Components WebAssembly surface WasmLinkerTest build: 0 warnings, 0 errors

The result is an AOT-safe path for the binding scenarios this layer owns, while default JIT behavior and reflection fallback remain intact.

javiercn and others added 6 commits August 11, 2026 12:17
Use non-generic enum parsing and reflectionless array conversion so runtime-selected binding no longer depends on emitted generic closures.

Behavior: changed: enum and array binding works without dynamic code

State: builds; tests in #2

Review hint: compare the dynamic-code-safe enum and array branches with their existing generic counterparts

Co-authored-by: Copilot App <[email protected]>
Compare the reflectionless enum and array paths with the existing JIT conversion behavior.

Behavior: preserved

State: complete

Co-authored-by: Copilot App <[email protected]>
Evaluate known binding expression shapes through the MemberInfo already carried by each expression node, preserving the existing fallback for unsupported shapes.

Behavior: preserved

State: builds; reflection walk tests in #4

Review hint: this commit deliberately has no bindable descriptor abstraction; every recognized hop uses expression metadata

Co-authored-by: Copilot App <[email protected]>
Cover nested members, fields carried by closures, arrays, indexers, edit-context anchoring, and compatibility with FieldIdentifier.Create.

Behavior: preserved

State: complete

Co-authored-by: Copilot App <[email protected]>
Introduce bindable member, indexer, and type descriptors at their first generated use. Registered metadata contexts now resolve descriptor graphs before the existing reflection fallback.

The existing application metadata generator emits only JsonTypeInfoResolver, JSInvokableMethods, and BindableTypes at this layer.

Behavior: changed: described form models use generated accessors while undescribed models retain reflection compatibility

State: builds; generated graph and resolver tests in #6

Review hint: generator changes are limited to bindable discovery, accessors, context registration, and descriptor-first expression evaluation

Co-authored-by: Copilot App <[email protected]>
Cover transitive and cyclic model discovery, private member accessors, indexers, descriptor-first expression walks, and per-provider resolver composition.

Behavior: preserved

State: complete

Review hint: generated tests exercise descriptors as runtime delegates, not only emitted source text

Co-authored-by: Copilot App <[email protected]>
@javiercn
javiercn force-pushed the javiercn-aot-stack-3-binding branch from 5cce742 to 1c5e0b8 Compare August 11, 2026 10:26
@javiercn
javiercn marked this pull request as ready for review August 11, 2026 14:07
Copilot AI lite review requested due to automatic review settings August 11, 2026 14:07
@javiercn
javiercn requested a review from a team as a code owner August 11, 2026 14:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR extends the Blazor “metadata-first” pipeline to cover interactive form binding under Native AOT by generating bindable model descriptors and consuming them at runtime to avoid Expression.Compile/runtime generic closure for supported shapes, while preserving reflection fallback for compatibility.

Changes:

  • Adds an experimental bindable metadata contract (BindableTypeDescriptor + BindableModelAttribute) and flows it through RazorComponentsMetadataContext and DI via IBindableTypeResolver.
  • Introduces a binding-expression walker (BindingExpressionEvaluator) used by form components to resolve FieldIdentifier without compiling delegates.
  • Updates BindConverter enum/array parsing+formatting to choose dynamic-code-safe implementations when RuntimeFeature.IsDynamicCodeSupported is false, and extends the Endpoints generator to emit bindable graphs plus tests.

Reviewed changes

Copilot reviewed 39 out of 39 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/Components/WebAssembly/WebAssembly/test/Services/WebAssemblyHostSerializationContextTest.cs Updates test contexts to implement the new BindableTypes metadata surface.
src/Components/Web/test/Microsoft.AspNetCore.Components.Web.Tests.csproj Suppresses experimental warning ASPNETCORE9004 in Web tests that touch new experimental APIs.
src/Components/Web/test/Metadata/ComponentMetadataServiceCollectionExtensionsTest.cs Verifies DI composition/isolation for both JSON resolvers and bindable type resolver.
src/Components/Web/test/Forms/BindingExpressionEvaluatorTest.cs Adds unit tests for expression walking with descriptor-assisted and reflection fallback evaluation.
src/Components/Web/src/PublicAPI.Unshipped.txt Records new/updated public API surface in Components.Web (BindableModelAttribute, RazorComponentsMetadataContext.BindableTypes).
src/Components/Web/src/Microsoft.AspNetCore.Components.Web.csproj Suppresses ASPNETCORE9004 within Components.Web (declares/consumes experimental APIs).
src/Components/Web/src/Metadata/RazorComponentsMetadataContext.cs Adds BindableTypes to the metadata context contract.
src/Components/Web/src/Metadata/ComponentMetadataServiceCollectionExtensions.cs Registers ComponentBindableTypeResolver/IBindableTypeResolver alongside existing metadata services.
src/Components/Web/src/Metadata/ComponentBindableTypeResolver.cs New resolver that composes BindableTypeDescriptors across registered metadata contexts.
src/Components/Web/src/Metadata/BindableModelAttribute.cs New experimental attribute to declare form-model roots for generator graph discovery.
src/Components/Web/src/Forms/ValidationMessage.cs Switches FieldIdentifier creation to the evaluator using the renderer-scoped bindable resolver.
src/Components/Web/src/Forms/InputSelect.cs Adds AOT suppression rationale for array-related binding in BuildRenderTree.
src/Components/Web/src/Forms/InputBase.cs Switches FieldIdentifier creation to the evaluator using the renderer-scoped bindable resolver.
src/Components/Web/src/Forms/BindingExpressionEvaluator.cs New internal evaluator that walks member/indexer/array-index chains without compiling expressions.
src/Components/Shared/src/ExpressionFormatting/ExpressionFormatter.cs Avoids Expression.Compile for captured index formatting when dynamic code isn’t supported.
src/Components/Server/test/ProtectedBrowserStorageSerializerOptionsTest.cs Updates stub metadata contexts to implement BindableTypes.
src/Components/Server/test/Circuits/RemoteJSRuntimeMetadataTest.cs Updates stub metadata contexts to implement BindableTypes.
src/Components/Endpoints/test/Microsoft.AspNetCore.Components.Endpoints.Generators.Tests/RazorComponentsMetadataGeneratorBindableTests.cs Adds generator tests validating bindable graph emission (members, indexers, cycles, stability).
src/Components/Endpoints/test/Microsoft.AspNetCore.Components.Endpoints.Generators.Tests/Microsoft.AspNetCore.Components.Endpoints.Generators.Tests.csproj Moves xUnit global-using removal into a target to avoid ordering issues.
src/Components/Endpoints/test/DependencyInjection/ComponentJsonMetadataIsolationTest.cs Updates test contexts to implement BindableTypes.
src/Components/Endpoints/test/Binding/FormDataMapperTests.cs Adds reflection-based assertions around dynamic-code/unreferenced-code annotations on constructors.
src/Components/Endpoints/src/FormMapping/FormDataMapperOptions.cs Removes dynamic-code/unreferenced-code attributes from constructors to reduce AOT friction.
src/Components/Endpoints/gen/WellKnownTypes.cs Adds well-known type lookup for BindableModelAttribute.
src/Components/Endpoints/gen/RazorComponentsMetadataGenerator.cs Integrates bindable type collection into generator model and expands diagnostic payload.
src/Components/Endpoints/gen/RazorComponentsMetadataGenerator.Bindables.cs New bindable graph collector (BFS + leaf filtering + accessibility checks).
src/Components/Endpoints/gen/Models/MetadataContextModel.cs Extends generator model with bindable type/member/indexer records.
src/Components/Endpoints/gen/Emitters/RazorComponentsMetadataGenerator.Emitter.cs Emits BindableTypes descriptors + optional UnsafeAccessor bridges.
src/Components/Endpoints/gen/DiagnosticDescriptors.cs Adds BLAZORAOT002 for bindable model description failures.
src/Components/Components/test/BindConverterTest.cs Adds coverage for enum and array conversion/formatting parity, including “no dynamic code” remote execution.
src/Components/Components/src/RenderTree/Renderer.cs Captures IBindableTypeResolver from DI for renderer-scoped access.
src/Components/Components/src/RenderHandle.cs Exposes the renderer-scoped bindable resolver via RenderHandle.
src/Components/Components/src/PublicAPI.Unshipped.txt Records new experimental binding descriptor APIs in Components.
src/Components/Components/src/Microsoft.AspNetCore.Components.csproj Suppresses ASPNETCORE9004 within Components (declares/consumes experimental APIs).
src/Components/Components/src/Infrastructure/IBindableTypeResolver.cs New internal contract for runtime lookup of bindable type descriptors.
src/Components/Components/src/Infrastructure/BindableTypeDescriptor.cs New experimental descriptor for members/indexers a binding expression may traverse.
src/Components/Components/src/Infrastructure/BindableMemberDescriptor.cs New experimental descriptor for member name/type + getter delegate.
src/Components/Components/src/Infrastructure/BindableIndexerDescriptor.cs New experimental descriptor for single-arg indexers + getter delegate.
src/Components/Components/src/ComponentBase.cs Exposes internal Handle to allow friend assemblies to access renderer-scoped services without exposing the handle publicly.
src/Components/Components/src/BindConverter.cs Adds dynamic-code-safe enum/nullable-enum and array parse/format paths and supporting helpers for AOT scenarios.

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +2568 to +2575
if (obj is null)
{
value = null;
return true;
}

value = converter.ConvertFrom(context: null, culture ?? CultureInfo.CurrentCulture, obj);
return true;
@Youssef1313 Youssef1313 added the area-blazor Includes: Blazor, Razor Components label Sep 2, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime.
To make sure no conflicting changes have occurred, please rerun validation before merging. You can do this by leaving an /azp run comment here (requires commit rights), or by simply closing and reopening.

@dotnet-policy-service dotnet-policy-service Bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Sep 26, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-blazor Includes: Blazor, Razor Components pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants