Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Binding SG] Add an API for creating instances of TypedBinding #23239

Merged
Merged
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
93 changes: 68 additions & 25 deletions src/Controls/src/BindingSourceGen/BindingCodeWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,19 @@ namespace Microsoft.Maui.Controls.Generated
using System.CodeDom.Compiler;

{{GeneratedCodeAttribute}}
internal static partial class GeneratedBindableObjectExtensions
internal static partial class GeneratedBindingInterceptors
{
private static bool ShouldUseSetter(BindingMode mode, BindableProperty bindableProperty)
=> mode == BindingMode.OneWayToSource
|| mode == BindingMode.TwoWay
|| (mode == BindingMode.Default
&& (bindableProperty.DefaultBindingMode == BindingMode.OneWayToSource
|| bindableProperty.DefaultBindingMode == BindingMode.TwoWay));

private static bool ShouldUseSetter(BindingMode mode)
=> mode == BindingMode.OneWayToSource
|| mode == BindingMode.TwoWay
|| mode == BindingMode.Default;
}
}
""";
Expand All @@ -75,15 +80,14 @@ namespace Microsoft.Maui.Controls.Generated
using System.Runtime.CompilerServices;
using Microsoft.Maui.Controls.Internals;

internal static partial class GeneratedBindableObjectExtensions
internal static partial class GeneratedBindingInterceptors
{
{{bindingMethodBody}}
}
}
""";


public static string GenerateBinding(SetBindingInvocationDescription binding, uint id)
public static string GenerateBinding(BindingInvocationDescription binding, uint id)
{
if (!binding.NullableContextEnabled)
{
Expand All @@ -95,7 +99,7 @@ public static string GenerateBinding(SetBindingInvocationDescription binding, ui
return GenerateBindingCode(bindingMethod);
}

private static string GenerateBindingMethod(SetBindingInvocationDescription binding, uint id)
private static string GenerateBindingMethod(BindingInvocationDescription binding, uint id)
{
using var builder = new BindingInterceptorCodeBuilder(indent: 2);
builder.AppendSetBindingInterceptor(id: id, binding: binding);
Expand All @@ -119,11 +123,11 @@ public BindingInterceptorCodeBuilder(int indent = 0)
_indentedTextWriter = new IndentedTextWriter(_stringWriter, "\t") { Indent = indent };
}

public void AppendSetBindingInterceptor(uint id, SetBindingInvocationDescription binding)
public void AppendSetBindingInterceptor(uint id, BindingInvocationDescription binding)
{
AppendLine(GeneratedCodeAttribute);
AppendInterceptorAttribute(binding.Location);
Append($"public static void SetBinding{id}");
AppendMethodName(binding, id);
if (binding.SourceType.IsGenericParameter && binding.PropertyType.IsGenericParameter)
{
Append($"<{binding.SourceType}, {binding.PropertyType}>");
Expand All @@ -138,20 +142,12 @@ public void AppendSetBindingInterceptor(uint id, SetBindingInvocationDescription
}
AppendLine('(');

AppendFunctionArguments(binding);

AppendLines($$"""
this BindableObject bindableObject,
BindableProperty bindableProperty,
Func<{{binding.SourceType}}, {{binding.PropertyType}}> getter,
BindingMode mode = BindingMode.Default,
IValueConverter? converter = null,
object? converterParameter = null,
string? stringFormat = null,
object? source = null,
object? fallbackValue = null,
object? targetNullValue = null)
{
Action<{{binding.SourceType}}, {{binding.PropertyType}}>? setter = null;
if (ShouldUseSetter(mode, bindableProperty))
if ({{GetShouldUseSetterCall(binding.MethodType)}})
{
""");

Expand All @@ -173,8 +169,7 @@ public void AppendSetBindingInterceptor(uint id, SetBindingInvocationDescription
}
else
{
// TODO is this too strict? I believe today when the Binding can't write to the property, it just silently ignores the value
AppendLine("throw new InvalidOperationException(\"Cannot set value on the source object.\");"); // TODO improve exception wording
AppendLine("throw new InvalidOperationException(\"Cannot set value on the source object.\");");
}

Unindent();
Expand Down Expand Up @@ -209,18 +204,67 @@ public void AppendSetBindingInterceptor(uint id, SetBindingInvocationDescription
FallbackValue = fallbackValue,
TargetNullValue = targetNullValue
};
bindableObject.SetBinding(bindableProperty, binding);

{{GetEpilog(binding.MethodType)}}
}
""");
}

private void AppendFunctionArguments(BindingInvocationDescription binding)
{
if (binding.MethodType == InterceptedMethodType.SetBinding)
{
AppendLines($$"""
this BindableObject bindableObject,
BindableProperty bindableProperty,
""");

}
AppendLines($$"""
Func<{{binding.SourceType}}, {{binding.PropertyType}}> getter,
BindingMode mode = BindingMode.Default,
IValueConverter? converter = null,
object? converterParameter = null,
string? stringFormat = null,
object? source = null,
object? fallbackValue = null,
object? targetNullValue = null)
""");
}

private static string GetEpilog(InterceptedMethodType interceptedMethodType) =>
interceptedMethodType switch
{
InterceptedMethodType.SetBinding => "bindableObject.SetBinding(bindableProperty, binding);",
InterceptedMethodType.Create => "return binding;",
_ => throw new ArgumentOutOfRangeException(nameof(interceptedMethodType))
};

private static string GetShouldUseSetterCall(InterceptedMethodType interceptedMethodType) =>
interceptedMethodType switch
{
InterceptedMethodType.SetBinding => "ShouldUseSetter(mode, bindableProperty)",
InterceptedMethodType.Create => "ShouldUseSetter(mode)",
_ => throw new ArgumentOutOfRangeException(nameof(interceptedMethodType))
};


private void AppendMethodName(BindingInvocationDescription binding, uint id)
{
Append(binding.MethodType switch
{
InterceptedMethodType.SetBinding => $"public static void SetBinding{id}",
InterceptedMethodType.Create => $"public static TypedBinding<{binding.SourceType}, {binding.PropertyType}> Create{id}",
_ => throw new ArgumentOutOfRangeException(nameof(binding.MethodType))
});
}

private void AppendInterceptorAttribute(InterceptorLocation location)
{
AppendLine($"[InterceptsLocationAttribute(@\"{location.FilePath}\", {location.Line}, {location.Column})]");
}

private void AppendSetterAction(SetBindingInvocationDescription binding, string sourceVariableName = "source", string valueVariableName = "value")
private void AppendSetterAction(BindingInvocationDescription binding, string sourceVariableName = "source", string valueVariableName = "value")
{
var assignedValueExpression = valueVariableName;

Expand Down Expand Up @@ -283,7 +327,7 @@ private void AppendSetterAction(SetBindingInvocationDescription binding, string
}
}

private void AppendHandlersArray(SetBindingInvocationDescription binding)
private void AppendHandlersArray(BindingInvocationDescription binding)
{
AppendLine($"new Tuple<Func<{binding.SourceType}, object?>, string>[]");
AppendLine('{');
Expand All @@ -296,7 +340,6 @@ private void AppendHandlersArray(SetBindingInvocationDescription binding)
{
var previousExpression = nextExpression;
nextExpression = AccessExpressionBuilder.ExtendExpression(previousExpression, MaybeWrapInConditionalAccess(part, forceConditonalAccessToNextPart));
var isNullableReferenceType = part is MemberAccess memberAccess && !memberAccess.IsValueType;
forceConditonalAccessToNextPart = part is Cast;

// Some parts don't have a property name, so we can't generate a handler for them (for example casts)
Expand Down
Loading
Loading