Skip to content

Commit 559b1f7

Browse files
committed
chore: BindableType preserves properties and more
Context: unoplatform/uno.chefs#1712 Context: #21920 Context: unoplatform/uno.extensions#2966 Context: unoplatform/uno.extensions#2969 Context: https://discord.com/channels/732297728826277939/732297837953679412/1444909702512119899 While running the uno.chefs app on macOS under NativeAOT: dotnet publish -c Release -r osx-x64 -f net10.0-desktop -p:TargetFrameworkOverride=net10.0-desktop -bl \ Chefs/Chefs.csproj \ -p:SelfContained=true -p:PublishAot=true -p:IsAotCompatible=true -p:UseSkiaRendering=true \ -p:IlcGenerateMapFile=true -p:IlcGenerateMstatFile=true -p:IlcGenerateDgmlFile=true \ -p:EmitCompilerGeneratedFiles=true -p:CompilerGeneratedFilesOutputPath=`pwd`/_gen Chefs/bin/Release/net10.0-desktop/osx-x64/publish/Chefs Console output would contain the following errors: fail: Uno.UI.Dispatching.NativeDispatcher[0] The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView] fail: Uno.UI.Dispatching.NativeDispatcher[0] The [Y] property getter does not exist on type [Windows.Foundation.Point] fail: Uno.UI.Dispatching.NativeDispatcher[0] The [X] property getter does not exist on type [Windows.Foundation.Point] At this point, a description of the relation between NativeAOT and Reflection would be useful. *Parts* of System.Reflection can be used. Which parts *can* be used, and how to use them, is oddly *not* well specified in the [Native AOT deployment][0] documentation. What doesn't work is outlined in the [limitations][1] section: > * No dynamic loading, for example, `Assembly.LoadFile`. > * No run-time code generation, for example, `System.Reflection.Emit`. What *always* appears to work is: * `Type.GetType()` returns a `Type` instance. What ***can*** work is: * `Type.GetType(string)`, *so long as* an assembly-qualified name is used as a *string constant* // bad string name = GetSomeTypeName(); Type type = Type.GetType(name); // good Type type = Type.GetType("My.Example.TypeName, ExampleAssembly"); * `Type.GetMethod(string)`, but see fine print below. * `Type.GetProperty(string)`, but see fine print below. * `MethodInfo.Invoke()` * … **The Fine Print**: in order for many Reflection-based APIs such as `Type.GetMethod(string)` to work, the program must contain "reflection metadata." We can now describe, briefly, what NativeAOT does: 1. Accept IL/assemblies as input 2. Internally trim the IL, optimizes them, etc. 3. Generates a native binary containing two separate bits of data: * Native machine code for execution * "reflection metadata" You can get an inkling of what methods survived trimming and become native code by using `dotnet publish -p:IlcGenerateMstatFile=true …`, which will produce a `.mstat` file, a PE file which references every type and member which is in the native binary, ***after*** inlining. (Meaning if a member is inlined, it *won't* be present!) Use e.g. `monodis --memberref App.mstat` to list post-trimmed members. You can get an inkling of the "reflection metadata" that is present by using `dotnet publish -p:IlcGenerateMetadataLog=true …`, which produces a `.metadata.csv` file. It's not particularly scrutible, but can be used to verify observed behavior. Consider one of the above failure messages: The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView] An obvious question to ask: is the `TabNavigation` property in the reflection metadata? Search for `"TabNavigation"` (with quotes!), and it's *not* in there. Compare to when this commit is in use, and: 66087019, Property, "TabNavigation", "3410be9a 6810bea8 5410beae 5410beb2" 3410be9a, ConstantStringValue, "TabNavigation", "" The 3rd column is the property name `TabNavigation`, while the 2nd column is the type; for properties, we want `Property`. The 4th column is "Children", one of which is: 5410beae, MethodSemantics, "Getter : [HasThis] Microsoft.UI.Xaml.Input.KeyboardNavigationMode get_TabNavigation()", "50086c65" which at least verifies that `TabNavigation` is in play. Programs can control what is contained within reflection metadata by using string constants with Reflection APIs, for example: typeof(SomeKnownType).GetMethod("ConstantName") will ensure that reflection metadata contains `SomeKnownType.ConstantName()`, and `ConstantName()` will be returned from `typeof(SomeKnownType).GetMethods()` and can be invoked with `MethodInfo.Invoke()`. If you *don't* use `typeof(SomeKnownType)` or string constants with `Type.GetType(string)` or `type.GetMethod("constant")`, then you need to "suggest" that some pieces of information be added to reflection metadata. The two predominant ways to do this are via the custom attributes: * [`DynamicallyAccessedMembersAttribute`][2] * [`DynamicDependencyAttribute`][3] From the Uno perspective, enter `BindingPropertyHelper`: *everything* is based on Reflection! Fortunately NativeAOT "supports" Reflection! (See above.) *Unfortunately*, we now need to convince NativeAOT to store the reflection metadata Uno requires in order to work! Various other PRs have dealt with some of this, such as #21920. Returning to the original failure messages, e.g. fail: Uno.UI.Dispatching.NativeDispatcher[0] The [TabNavigation] property getter does not exist on type [Microsoft.UI.Xaml.Controls.FlipView] During the app build, `src/SourceGenerators/Uno.UI.SourceGenerators` generates a `BindableMetadata.g.cs` file which will mention `[Bindable]` types, e.g. for `Microsoft.UI.Xaml.Controls.FlipView`: /// <summary> /// Builder for Microsoft.UI.Xaml.Controls.FlipView /// </summary> [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute] static class MetadataBuilder_239 { internal static global::Uno.UI.DataBinding.IBindableType Build(global::Uno.UI.DataBinding.BindableType parent) { var bindableType = parent ?? new global::Uno.UI.DataBinding.BindableType(151, typeof(global::Microsoft.UI.Xaml.Controls.FlipView)); // … } private static object CreateInstance() => new global::Microsoft.UI.Xaml.Controls.FlipView(); } `BindableMetadata.g.cs` was needed in the ye olde Xamarin world order to tell *its* linker to e.g. "preserve the `FlipView` default ctor!" *Now*, we can build upon this infrastructure and update `BindableType` to request that Reflection information regarding properties, fields, and constructors be retained. We can do this by updating the `BindableType` constructor: partial class BindableType { internal const DynamicallyAccessedMemberTypes TypeRequirements = DynamicallyAccessedMemberTypes.PublicProperties | …; public BindableType(int estimatedPropertySize, [DynamicallyAccessedMembers(TypeRequirements)] Type sourceType) => … } *Because* we have `BindableMetadata.g.cs` *and* because it provides `typeof(FlipView)`, this directs NativeAOT to make property and other reflection metadata available to the app, *fixing* the error messages. Expand this addition of `[DynamicallyAccessedMembers]` to also include `BindableProperty` and related types. Note: the IL2111 warning "Method 'System.Type.TypeInitializer.get' …" is *caused by* `typeof(Type)` (?!), which is particularly odd given that we don't use `Type.TypeInitializer`! Thanks to Alexander Köplinger for [looking into this][4]. [0]: https://learn.microsoft.comdotnet/core/deploying/native-aot [1]: https://learn.microsoft.comdotnet/core/deploying/native-aot/#limitations-of-native-aot-deployment [2]: https://learn.microsoft.comdotnet/api/system.diagnostics.codeanalysis.dynamicallyaccessedmembersattribute?view=net-10.0 [3]: https://learn.microsoft.comdotnet/api/system.diagnostics.codeanalysis.dynamicdependencyattribute?view=net-10.0 [4]: https://discord.com/channels/732297728826277939/732297837953679412/1445773677152174150
1 parent c3a5b3f commit 559b1f7

8 files changed

Lines changed: 60 additions & 12 deletions

File tree

‎src/SourceGenerators/Uno.UI.SourceGenerators/BindableTypeProviders/BindableTypeProvidersGenerationTask.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,7 @@ where field.IsStatic
302302
writer.AppendLineIndented("[global::System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Maintainability\", \"CA1502:AvoidExcessiveComplexity\", Justification=\"Must be ignored even if generated code is checked.\")]");
303303
writer.AppendLineIndented("[global::System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Maintainability\", \"CA1506:AvoidExcessiveClassCoupling\", Justification = \"Must be ignored even if generated code is checked.\")]");
304304
writer.AppendLineIndented("[global::System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Maintainability\", \"CA1505:AvoidUnmaintainableCode\", Justification = \"Must be ignored even if generated code is checked.\")]");
305+
writer.AppendLineIndented("[global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage(\"Trimming\", \"IL2111\", Justification = \"`typeof(Type)` emits IL2111 because of `Type.TypeInitializer`, which is not used.\")]");
305306
using (writer.BlockInvariant("internal static global::Uno.UI.DataBinding.IBindableType Build(global::Uno.UI.DataBinding.BindableType parent)"))
306307
{
307308
RegisterHintMethod($"MetadataBuilder_{typeInfo.Index:000}", ownerType, "Uno.UI.DataBinding.IBindableType Build(Uno.UI.DataBinding.BindableType)");

‎src/Uno.UI/DataBinding/BindableProperty.cs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
using System;
44
using System.Collections.Generic;
5+
using System.Diagnostics.CodeAnalysis;
56
using System.Linq;
67
using System.Text;
78
using System.Threading.Tasks;
@@ -24,7 +25,11 @@ public BindableProperty(DependencyProperty property)
2425
/// <summary>
2526
/// This ctor is available for backward compatibility. On newer versions of Uno.UI, the BindableTypeProvidersSourceGenerator uses the single-parameter ctor
2627
/// </summary>
27-
public BindableProperty(Type propertyType, PropertyGetterHandler getter, PropertySetterHandler? setter)
28+
public BindableProperty(
29+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)]
30+
Type propertyType,
31+
PropertyGetterHandler getter,
32+
PropertySetterHandler? setter)
2833
{
2934
Getter = getter;
3035
Setter = setter;
@@ -35,6 +40,7 @@ public BindableProperty(Type propertyType, PropertyGetterHandler getter, Propert
3540

3641
public PropertySetterHandler? Setter { get; }
3742

43+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)]
3844
public Type PropertyType { get; }
3945

4046
public DependencyProperty? DependencyProperty { get; }

‎src/Uno.UI/DataBinding/BindableType.cs‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
using System;
44
using System.Collections.Generic;
5+
using System.Diagnostics.CodeAnalysis;
56
using System.Linq;
67
using System.Text;
78
using System.Threading.Tasks;
@@ -16,6 +17,13 @@ namespace Uno.UI.DataBinding
1617
/// </summary>
1718
public class BindableType : IBindableType
1819
{
20+
internal const DynamicallyAccessedMemberTypes TypeRequirements =
21+
DynamicallyAccessedMemberTypes.NonPublicConstructors // DependencyProperty.Register()
22+
| DynamicallyAccessedMemberTypes.PublicConstructors
23+
| DynamicallyAccessedMemberTypes.PublicFields
24+
| DynamicallyAccessedMemberTypes.PublicProperties
25+
;
26+
1927
private readonly Hashtable _properties;
2028
private StringIndexerGetterDelegate? _stringIndexerGetter;
2129
private StringIndexerSetterDelegate? _stringIndexerSetter;
@@ -26,12 +34,16 @@ public class BindableType : IBindableType
2634
/// </summary>
2735
/// <param name="estimatedPropertySize">Provide an estimated number of properties, so the dictionary does not need to grow unnecessarily.</param>
2836
/// <param name="sourceType">The actual .NET type that corresponds to this instance.</param>
29-
public BindableType(int estimatedPropertySize, Type sourceType)
37+
public BindableType(
38+
int estimatedPropertySize,
39+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)]
40+
Type sourceType)
3041
{
3142
_properties = new Hashtable(estimatedPropertySize);
3243
Type = sourceType;
3344
}
3445

46+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)]
3547
public Type Type { get; }
3648

3749
public ActivatorDelegate? CreateInstance()
@@ -61,7 +73,9 @@ public void AddActivator(ActivatorDelegate activator)
6173
_activator = activator;
6274
}
6375

64-
public void AddProperty<T>(string name, PropertyGetterHandler getter, PropertySetterHandler? setter = null)
76+
public void AddProperty<
77+
[DynamicallyAccessedMembers(TypeRequirements)] T
78+
>(string name, PropertyGetterHandler getter, PropertySetterHandler? setter = null)
6579
{
6680
_properties[name] = new BindableProperty(typeof(T), getter, setter);
6781
}
@@ -71,7 +85,12 @@ public void AddProperty(DependencyProperty property)
7185
_properties[property.Name] = new BindableProperty(property);
7286
}
7387

74-
public void AddProperty(string name, Type propertyType, PropertyGetterHandler getter, PropertySetterHandler? setter = null)
88+
public void AddProperty(
89+
string name,
90+
[DynamicallyAccessedMembers(TypeRequirements)]
91+
Type propertyType,
92+
PropertyGetterHandler getter,
93+
PropertySetterHandler? setter = null)
7594
{
7695
_properties[name] = new BindableProperty(propertyType, getter, setter);
7796
}

‎src/Uno.UI/DataBinding/IBindableProperty.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using Microsoft.UI.Xaml;
44
using System;
55
using System.Collections.Generic;
6+
using System.Diagnostics.CodeAnalysis;
67
using System.Linq;
78
using System.Text;
89

@@ -26,6 +27,7 @@ public interface IBindableProperty
2627
/// <summary>
2728
/// Gets the type of the property
2829
/// </summary>
30+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)]
2931
Type PropertyType { get; }
3032

3133
/// <summary>

‎src/Uno.UI/DataBinding/IBindableType.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
using System;
44
using System.Collections.Generic;
5+
using System.Diagnostics.CodeAnalysis;
56
using System.Linq;
67
using System.Text;
78
using System.Threading.Tasks;
@@ -31,6 +32,7 @@ public interface IBindableType
3132
/// <summary>
3233
/// Provides the Type of this bindable type
3334
/// </summary>
35+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)]
3436
Type Type { get; }
3537

3638
/// <summary>

‎src/Uno.UI/UI/Xaml/Controls/Frame/Frame.Properties.cs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Diagnostics.CodeAnalysis;
34
using Microsoft.UI.Xaml.Navigation;
45

56
namespace Microsoft.UI.Xaml.Controls;
@@ -117,6 +118,8 @@ public Type CurrentSourcePageType
117118
/// <summary>
118119
/// Identifies the CurrentSourcePageType dependency property.
119120
/// </summary>
121+
[UnconditionalSuppressMessage("Trimming", "IL2111", Justification = "`typeof(Type)` triggers IL2111 regarding `Type.TypeInitializer`, but Uno doesn't use `Type.TypeInitializer`!")]
122+
// warning IL2111: Method 'System.Type.TypeInitializer.get' with parameters or return value with `DynamicallyAccessedMembersAttribute` is accessed via reflection. Trimmer can't guarantee availability of the requirements of the method.
120123
public static DependencyProperty CurrentSourcePageTypeProperty { get; } =
121124
DependencyProperty.Register(
122125
nameof(CurrentSourcePageType),
@@ -174,6 +177,8 @@ public Type SourcePageType
174177
/// <summary>
175178
/// Identifies the SourcePageType dependency property.
176179
/// </summary>
180+
[UnconditionalSuppressMessage("Trimming", "IL2111", Justification = "`typeof(Type)` triggers IL2111 regarding `Type.TypeInitializer`, but Uno doesn't use `Type.TypeInitializer`!")]
181+
// warning IL2111: Method 'System.Type.TypeInitializer.get' with parameters or return value with `DynamicallyAccessedMembersAttribute` is accessed via reflection. Trimmer can't guarantee availability of the requirements of the method.
177182
public static DependencyProperty SourcePageTypeProperty { get; } =
178183
DependencyProperty.Register(
179184
nameof(SourcePageType),

‎src/Uno.UI/UI/Xaml/DependencyProperty.cs‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
using Uno;
1717
using Uno.Extensions;
1818
using Uno.UI;
19+
using Uno.UI.DataBinding;
1920
using Uno.UI.Dispatching;
2021
using Uno.UI.Helpers;
2122
using Uno.UI.Xaml.Media;
@@ -54,13 +55,22 @@ public sealed partial class DependencyProperty
5455

5556
private readonly Flags _flags;
5657
private string _name;
58+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)]
5759
private Type _propertyType;
60+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)]
5861
private Type _ownerType;
5962
private readonly int _uniqueId;
6063

6164
private static int _globalId = -1;
6265

63-
private DependencyProperty(string name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata, bool attached)
66+
private DependencyProperty(
67+
string name,
68+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)]
69+
Type propertyType,
70+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)]
71+
Type ownerType,
72+
PropertyMetadata defaultMetadata,
73+
bool attached)
6474
{
6575
_name = name;
6676
_propertyType = propertyType;
@@ -140,8 +150,8 @@ internal bool IsDependencyObjectCollection
140150
/// <exception cref="InvalidOperationException">A property with the same name has already been declared for the ownerType</exception>
141151
public static DependencyProperty Register(
142152
string name,
143-
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type propertyType,
144-
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type ownerType,
153+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)] Type propertyType,
154+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)] Type ownerType,
145155
PropertyMetadata typeMetadata)
146156
{
147157
typeMetadata = FixMetadataIfNeeded(propertyType, typeMetadata);
@@ -196,8 +206,8 @@ private static PropertyMetadata FixMetadataIfNeeded(
196206
/// </remarks>
197207
internal static DependencyProperty Register(
198208
string name,
199-
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type propertyType,
200-
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type ownerType,
209+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)] Type propertyType,
210+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)] Type ownerType,
201211
FrameworkPropertyMetadata typeMetadata)
202212
#pragma warning disable RS0030 // Do not used banned APIs
203213
=> Register(name, propertyType, ownerType, (PropertyMetadata)typeMetadata);
@@ -214,8 +224,8 @@ internal static DependencyProperty Register(
214224
/// <exception cref="InvalidOperationException">A property with the same name has already been declared for the ownerType</exception>
215225
public static DependencyProperty RegisterAttached(
216226
string name,
217-
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type propertyType,
218-
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type ownerType,
227+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)] Type propertyType,
228+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)] Type ownerType,
219229
PropertyMetadata defaultMetadata)
220230
{
221231
defaultMetadata = FixMetadataIfNeeded(propertyType, defaultMetadata);
@@ -297,11 +307,13 @@ public PropertyMetadata GetMetadata(Type forType)
297307
return _ownerTypeMetadata.CloneWithOverwrittenDefaultValue(defaultValueForType);
298308
}
299309

310+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)]
300311
internal Type OwnerType
301312
{
302313
get { return _ownerType; }
303314
}
304315

316+
[DynamicallyAccessedMembers(BindableType.TypeRequirements)]
305317
internal Type Type
306318
{
307319
get { return _propertyType; }

‎src/Uno.UI/UI/Xaml/Navigation/PageStackEntry.Properties.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@ public Type SourcePageType
3737
/// <summary>
3838
/// Identifies the SourcePageType dependency property.
3939
/// </summary>
40-
[UnconditionalSuppressMessage("Trimming", "IL2111", Justification = "@jonpryor has no idea what the trimmer is talking about.")]
40+
[UnconditionalSuppressMessage("Trimming", "IL2111", Justification = "`typeof(Type)` triggers IL2111 regarding `Type.TypeInitializer`, but Uno doesn't use `Type.TypeInitializer`!")]
41+
// warning IL2111: Method 'System.Type.TypeInitializer.get' with parameters or return value with `DynamicallyAccessedMembersAttribute` is accessed via reflection. Trimmer can't guarantee availability of the requirements of the method.
4142
public static DependencyProperty SourcePageTypeProperty { get; } =
4243
DependencyProperty.Register(
4344
nameof(SourcePageType),

0 commit comments

Comments
 (0)