-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[XSG] Reduce dead code for Setters with compiled converters #32474
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
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
1bd90e2
Initial plan
Copilot 16a6ae0
Add test demonstrating XSG dead code issue with compiled converters
Copilot 53d15a5
Fix XSG dead code for Setter with compiled converters
Copilot 6bcdafd
Move test to SourceGen.UnitTests with snapshot testing
Copilot 04e8303
Add explicit assertion for XamlTypeResolver absence
Copilot 3f29b9d
Simplify test by removing Label with StaticResource
Copilot 878ad12
Eliminate dead Setter instantiation for simple value cases
Copilot 10302ae
Revert to conservative approach - skip property assignments only
Copilot b0f87e5
Implement IKnownMarkupValueProvider to fix markup extension handling
Copilot 4e7be2c
Move ProvideValueForSetter to SetterValueProvider and share code
Copilot 968f3b7
Fix SimplifyOnPlatform test and CanProvideValue logic
Copilot 9e35690
Skip variable creation for Setters that can be fully inlined
Copilot b2a6589
Fix tests
simonrozsival 1c61bf5
Rename knownSGValueProvidersV2 to knownSGValueProviders
Copilot bea0425
Merge branch 'main' into copilot/reduce-dead-code-converters
simonrozsival c8e838f
Fix merge conflict: use IKnownMarkupValueProvider instead of ProvideV…
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| using System.CodeDom.Compiler; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.Maui.Controls.Xaml; | ||
|
|
||
| namespace Microsoft.Maui.Controls.SourceGen; | ||
|
|
||
| /// <summary> | ||
| /// Interface for known markup types that can provide inline value initialization. | ||
| /// Separates the "can we inline?" check from the actual inlining logic. | ||
| /// </summary> | ||
| internal interface IKnownMarkupValueProvider | ||
| { | ||
| /// <summary> | ||
| /// Determines if this element can be fully inlined without requiring | ||
| /// property assignments or service provider infrastructure. | ||
| /// </summary> | ||
| /// <param name="node">The element node to check</param> | ||
| /// <param name="context">The source generation context</param> | ||
| /// <returns>True if the element can be inlined, false otherwise</returns> | ||
| bool CanProvideValue(ElementNode node, SourceGenContext context); | ||
|
|
||
| /// <summary> | ||
| /// Provides the inline value initialization code. | ||
| /// </summary> | ||
| /// <param name="node">The element node</param> | ||
| /// <param name="writer">The code writer</param> | ||
| /// <param name="context">The source generation context</param> | ||
| /// <param name="getNodeValue">Delegate to get node values</param> | ||
| /// <param name="returnType">The return type of the value</param> | ||
| /// <param name="value">The generated value code</param> | ||
| /// <returns>True if value was provided, false otherwise</returns> | ||
| bool TryProvideValue(ElementNode node, IndentedTextWriter writer, SourceGenContext context, NodeSGExtensions.GetNodeValueDelegate? getNodeValue, out ITypeSymbol? returnType, out string value); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| using System.CodeDom.Compiler; | ||
| using System.Linq; | ||
| using System.Xml; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.Maui.Controls.Xaml; | ||
|
|
||
| namespace Microsoft.Maui.Controls.SourceGen; | ||
|
|
||
| internal class SetterValueProvider : IKnownMarkupValueProvider | ||
| { | ||
| public bool CanProvideValue(ElementNode node, SourceGenContext context) | ||
| { | ||
| // Can only inline if all properties are simple ValueNodes (no markup extensions) | ||
| // We need to check both the properties and any collection items | ||
|
|
||
| // Get the value node (shared logic with TryProvideValue) | ||
| var valueNode = GetValueNode(node); | ||
|
|
||
| // Value must be a simple ValueNode (not a MarkupNode or ElementNode) | ||
| if (valueNode is MarkupNode or ElementNode) | ||
| return false; | ||
|
|
||
| // All properties must be simple ValueNodes (no ElementNode or MarkupNode) | ||
| foreach (var prop in node.Properties.Values) | ||
| { | ||
| if (prop is MarkupNode or ElementNode) | ||
| return false; | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| public bool TryProvideValue(ElementNode node, IndentedTextWriter writer, SourceGenContext context, NodeSGExtensions.GetNodeValueDelegate? getNodeValue, out ITypeSymbol? returnType, out string value) | ||
| { | ||
| returnType = context.Compilation.GetTypeByMetadataName("Microsoft.Maui.Controls.Setter")!; | ||
|
|
||
| // Get the value node (shared logic with CanProvideValue) | ||
| var valueNode = GetValueNode(node); | ||
| if (valueNode == null) | ||
| { | ||
| value = string.Empty; | ||
| return false; | ||
| } | ||
|
|
||
| var bpNode = (ValueNode)node.Properties[new XmlName("", "Property")]; | ||
| var bpRef = bpNode.GetBindableProperty(context); | ||
|
|
||
| string targetsetter; | ||
| if (node.Properties.TryGetValue(new XmlName("", "TargetName"), out var targetNode)) | ||
| targetsetter = $"TargetName = \"{((ValueNode)targetNode).Value}\", "; | ||
| else | ||
| targetsetter = ""; | ||
|
|
||
| if (valueNode is ValueNode vn) | ||
| { | ||
| value = $"new global::Microsoft.Maui.Controls.Setter {{{targetsetter}Property = {bpRef.ToFQDisplayString()}, Value = {vn.ConvertTo(bpRef, writer, context)}}}"; | ||
| return true; | ||
| } | ||
| else if (getNodeValue != null) | ||
| { | ||
| var lvalue = getNodeValue(valueNode, bpRef.Type); | ||
| value = $"new global::Microsoft.Maui.Controls.Setter {{{targetsetter}Property = {bpRef.ToFQDisplayString()}, Value = {lvalue.ValueAccessor}}}"; | ||
| return true; | ||
| } | ||
| else if (context.Variables.TryGetValue(valueNode, out var variable)) | ||
| { | ||
| value = $"new global::Microsoft.Maui.Controls.Setter {{{targetsetter}Property = {bpRef.ToFQDisplayString()}, Value = {variable.ValueAccessor}}}"; | ||
| return true; | ||
| } | ||
|
|
||
| value = string.Empty; | ||
| //FIXME context.ReportDiagnostic | ||
| return false; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Shared helper to get the value node from a Setter element. | ||
| /// Checks properties first, then collection items. | ||
| /// </summary> | ||
| private static INode? GetValueNode(ElementNode node) | ||
| { | ||
| INode? valueNode = null; | ||
| if (!node.Properties.TryGetValue(new XmlName("", "Value"), out valueNode) && | ||
| !node.Properties.TryGetValue(new XmlName(XamlParser.MauiUri, "Value"), out valueNode) && | ||
| node.CollectionItems.Count == 1) | ||
| valueNode = node.CollectionItems[0]; | ||
|
|
||
| return valueNode; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
143 changes: 143 additions & 0 deletions
143
src/Controls/tests/SourceGen.UnitTests/InitializeComponent/SetterCompiledConverters.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| using System; | ||
| using System.IO; | ||
| using System.Linq; | ||
| using Xunit; | ||
|
|
||
| namespace Microsoft.Maui.Controls.SourceGen.UnitTests; | ||
|
|
||
| public class SetterCompiledConverters : SourceGenXamlInitializeComponentTestBase | ||
| { | ||
| [Fact] | ||
| public void SetterWithCompiledConverters_DoesNotGenerateDeadCode() | ||
| { | ||
| var xaml = | ||
| """ | ||
| <?xml version="1.0" encoding="UTF-8"?> | ||
| <ContentPage | ||
| xmlns="http://schemas.microsoft.com/dotnet/2021/maui" | ||
| xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" | ||
| x:Class="Test.TestPage"> | ||
| <ContentPage.Resources> | ||
| <ResourceDictionary> | ||
| <Style x:Key="testStyle" TargetType="Label"> | ||
| <Setter Property="FontSize" Value="16" /> | ||
| <Setter Property="TextColor" Value="Red" /> | ||
| </Style> | ||
| </ResourceDictionary> | ||
| </ContentPage.Resources> | ||
| </ContentPage> | ||
| """; | ||
|
|
||
| var code = | ||
| """ | ||
| using Microsoft.Maui.Controls; | ||
| using Microsoft.Maui.Controls.Xaml; | ||
|
|
||
| namespace Test; | ||
|
|
||
| [XamlProcessing(XamlInflator.SourceGen)] | ||
| public partial class TestPage : ContentPage | ||
| { | ||
| public TestPage() | ||
| { | ||
| InitializeComponent(); | ||
| } | ||
| } | ||
| """; | ||
|
|
||
| var testXamlFilePath = Path.Combine(Environment.CurrentDirectory, "Test.xaml"); | ||
| var expected = | ||
| $$""" | ||
| //------------------------------------------------------------------------------ | ||
| // <auto-generated> | ||
| // This code was generated by a .NET MAUI source generator. | ||
| // | ||
| // Changes to this file may cause incorrect behavior and will be lost if | ||
| // the code is regenerated. | ||
| // </auto-generated> | ||
| //------------------------------------------------------------------------------ | ||
| #nullable enable | ||
|
|
||
| namespace Test; | ||
|
|
||
| [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Maui.Controls.SourceGen, Version=10.0.0.0, Culture=neutral, PublicKeyToken=null", "10.0.0.0")] | ||
| public partial class TestPage | ||
| { | ||
| private partial void InitializeComponent() | ||
| { | ||
| // Fallback to Runtime inflation if the page was updated by HotReload | ||
| static string? getPathForType(global::System.Type type) | ||
| { | ||
| var assembly = type.Assembly; | ||
| foreach (var xria in global::System.Reflection.CustomAttributeExtensions.GetCustomAttributes<global::Microsoft.Maui.Controls.Xaml.XamlResourceIdAttribute>(assembly)) | ||
| { | ||
| if (xria.Type == type) | ||
| return xria.Path; | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| var rlr = global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceProvider2?.Invoke(new global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceLoadingQuery | ||
| { | ||
| AssemblyName = typeof(global::Test.TestPage).Assembly.GetName(), | ||
| ResourcePath = getPathForType(typeof(global::Test.TestPage)), | ||
| Instance = this, | ||
| }); | ||
|
|
||
| if (rlr?.ResourceContent != null) | ||
| { | ||
| this.InitializeComponentRuntime(); | ||
| return; | ||
| } | ||
|
|
||
| var style1 = new global::Microsoft.Maui.Controls.Style(typeof(global::Microsoft.Maui.Controls.Label)); | ||
| global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(style1!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 8, 5); | ||
| var resourceDictionary = new global::Microsoft.Maui.Controls.ResourceDictionary(); | ||
| global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(resourceDictionary!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 7, 4); | ||
| var __root = this; | ||
| global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(__root!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 2, 2); | ||
| #if !_MAUIXAML_SG_NAMESCOPE_DISABLE | ||
| global::Microsoft.Maui.Controls.Internals.INameScope iNameScope = global::Microsoft.Maui.Controls.Internals.NameScope.GetNameScope(__root) ?? new global::Microsoft.Maui.Controls.Internals.NameScope(); | ||
| #endif | ||
| #if !_MAUIXAML_SG_NAMESCOPE_DISABLE | ||
| global::Microsoft.Maui.Controls.Internals.NameScope.SetNameScope(__root, iNameScope); | ||
| #endif | ||
| #if !_MAUIXAML_SG_NAMESCOPE_DISABLE | ||
| global::Microsoft.Maui.Controls.Internals.INameScope iNameScope1 = new global::Microsoft.Maui.Controls.Internals.NameScope(); | ||
| #endif | ||
| #if !_MAUIXAML_SG_NAMESCOPE_DISABLE | ||
| global::Microsoft.Maui.Controls.Internals.INameScope iNameScope2 = new global::Microsoft.Maui.Controls.Internals.NameScope(); | ||
| #endif | ||
| #line 7 "{{testXamlFilePath}}" | ||
| __root.Resources = (global::Microsoft.Maui.Controls.ResourceDictionary)resourceDictionary; | ||
| #line default | ||
| var setter = new global::Microsoft.Maui.Controls.Setter {Property = global::Microsoft.Maui.Controls.Label.FontSizeProperty, Value = 16D}; | ||
| if (global::Microsoft.Maui.VisualDiagnostics.GetSourceInfo(setter!) == null) | ||
| global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(setter!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 9, 6); | ||
| #line 9 "{{testXamlFilePath}}" | ||
| ((global::System.Collections.Generic.ICollection<global::Microsoft.Maui.Controls.Setter>)style1.Setters).Add((global::Microsoft.Maui.Controls.Setter)setter); | ||
| #line default | ||
| var setter1 = new global::Microsoft.Maui.Controls.Setter {Property = global::Microsoft.Maui.Controls.Label.TextColorProperty, Value = global::Microsoft.Maui.Graphics.Colors.Red}; | ||
| if (global::Microsoft.Maui.VisualDiagnostics.GetSourceInfo(setter1!) == null) | ||
| global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(setter1!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 10, 6); | ||
| #line 10 "{{testXamlFilePath}}" | ||
| ((global::System.Collections.Generic.ICollection<global::Microsoft.Maui.Controls.Setter>)style1.Setters).Add((global::Microsoft.Maui.Controls.Setter)setter1); | ||
| #line default | ||
| resourceDictionary["testStyle"] = style1; | ||
| #line 7 "{{testXamlFilePath}}" | ||
| __root.Resources = (global::Microsoft.Maui.Controls.ResourceDictionary)resourceDictionary; | ||
| #line default | ||
| } | ||
| } | ||
|
|
||
| """; | ||
|
|
||
| var (result, generated) = RunGenerator(xaml, code); | ||
| Assert.False(result.Diagnostics.Any()); | ||
| Assert.Equal(expected, generated, ignoreLineEndingDifferences: true); | ||
|
|
||
| // Explicitly verify that XamlTypeResolver is not used anywhere in the generated code | ||
| // This is critical because XamlTypeResolver is not AOT-compatible | ||
| Assert.DoesNotContain("XamlTypeResolver", generated, StringComparison.Ordinal); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.