Skip to content
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
69 changes: 69 additions & 0 deletions src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,21 @@ static class UpdateComponentCodeWriter
}

var varName = $"__uc_{compIdx++}";
if (TryEmitResourceDictionaryItemChange(
codeWriter,
nodeDiff,
varName,
compilation,
xmlnsCache,
typeCache,
rootType,
sourceProductionContext,
projectItem))
{
codeWriter.WriteLine();
continue;
}

codeWriter.WriteLine($"if (global::Microsoft.Maui.Controls.Xaml.XamlComponentRegistry.TryGet(this, \"{nodeDiff.NodeId}\", out var {varName}))");
using (PrePost.NewBlock(codeWriter))
{
Expand Down Expand Up @@ -987,6 +1002,60 @@ static bool TryEmitResourceDictionaryChange(
return true;
}

static bool TryEmitResourceDictionaryItemChange(
IndentedTextWriter codeWriter,
NodeDiff nodeDiff,
string varName,
Compilation compilation,
AssemblyAttributes xmlnsCache,
IDictionary<XmlType, INamedTypeSymbol> typeCache,
INamedTypeSymbol rootType,
SourceProductionContext sourceProductionContext,
ProjectItem? projectItem)
{
if (!InheritsFrom(rootType, "global::Microsoft.Maui.Controls.ResourceDictionary")
&& rootType.ToFQDisplayString() != "global::Microsoft.Maui.Controls.ResourceDictionary")
{
return false;
}

var element = nodeDiff.NewNode;
if (element is null
|| nodeDiff.PropertyChanges.Count != 1
|| nodeDiff.PropertyChanges[0].Kind != PropertyDiffKind.Set
|| nodeDiff.PropertyChanges[0].PropertyName.LocalName != "__MAUI_Content__"
|| element.CollectionItems.Count != 1
|| element.CollectionItems[0] is not ValueNode
|| !element.Properties.TryGetValue(XmlName.xKey, out var keyNode)
|| keyNode is not ValueNode { Value: string key })
{
return false;
}

var parent = element.Parent is ListNode list ? list.Parent : element.Parent;
if (parent is not SGRootNode)
return false;

var valueExpression = BuildResourceValueExpression(
element,
compilation,
xmlnsCache,
typeCache,
rootType,
sourceProductionContext,
projectItem);
if (valueExpression is null)
return false;

codeWriter.WriteLine($"var {varName} = {valueExpression};");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[critical] Logic and Correctness — var {varName} = {valueExpression}; infers the resource's own type, so the guard emitted two lines below (if ({varName} is not null)) is a null constant pattern against a non-nullable value type whenever the resource is a struct. That is a hard compile error, not a warning: error CS0037: Cannot convert null to 'double' because it is a non-nullable value type (verified against Roslyn with var x = 14d; if (x is not null)).

Concrete scenario: a standalone x:Class ResourceDictionary containing <x:Double x:Key="FontSizeBody">14</x:Double> — the shape shipped by the MAUI project templates in Styles.xaml. Editing 14 → 16 produces exactly one __MAUI_Content__ Set diff on a keyed root-level element with a single ValueNode, so every gate in TryEmitResourceDictionaryItemChange passes and BuildResourceValueExpression returns a double-typed expression via ConvertTo. The generated UpdateComponent() then fails to compile and the hot-reload edit is lost. Same for Thickness, GridLength, CornerRadius, x:Int32, x:Boolean, Size, Point — all common root-level RD entries. Reference-typed resources (Color, x:String) are unaffected, which is why this is invisible today.

Fix is local: declare the local as object? so the boxing conversion is explicit and the null guard is legal:

codeWriter.WriteLine($"object? {varName} = {valueExpression};");

The following this["..."] = {varName}; (indexer is object) and XamlComponentRegistry.Register(this, ..., {varName}) (parameter is object) both already expect object, so no other emitted line changes.

codeWriter.WriteLine($"this[\"{EscapeString(key)}\"] = {varName};");
codeWriter.WriteLine($"if ({varName} is not null)");
codeWriter.Indent++;
codeWriter.WriteLine($"global::Microsoft.Maui.Controls.Xaml.XamlComponentRegistry.Register(this, \"{nodeDiff.NodeId}\", {varName});");
codeWriter.Indent--;
return true;
}

/// <summary>
/// Builds a C# expression for a resource element value.
/// For known types (Color, etc.), uses the IC compile-time converter pipeline.
Expand Down
19 changes: 15 additions & 4 deletions src/Controls/src/SourceGen/XamlNodeDiff.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,9 @@ namespace Microsoft.Maui.Controls.Xaml;
public static class XamlIncrementalHotReloadHandler
{
/// <summary>
/// Generator-only entry point retained for backward compatibility with previously
/// compiled <c>InitializeComponent()</c> bodies. <see cref="XamlComponentRegistry.Register"/>
/// already records every page instance, so live-instance enumeration is sourced from
/// <see cref="XamlComponentRegistry.GetInstances"/>. This method only validates its
/// argument and respects the <c>IsIncrementalHotReloadEnabled</c> feature switch.
/// Generator-only entry point that registers every XAML root for live-instance enumeration.
/// Roots such as <see cref="Application"/> and <see cref="ResourceDictionary"/> may not contain
/// child components, so they cannot rely on component registration to be tracked.
/// </summary>
public static void Track(object instance)
{
Expand All @@ -42,8 +40,7 @@ public static void Track(object instance)
if (!global::Microsoft.Maui.RuntimeFeature.IsIncrementalHotReloadEnabled)
return;

// No-op: XamlComponentRegistry.Register has already tracked this instance via
// its secondary type-indexed weak-reference list.
XamlComponentRegistry.RegisterComponent(instance, string.Empty);
}

/// <summary>
Expand Down
217 changes: 217 additions & 0 deletions src/Controls/tests/SourceGen.UnitTests/HotReload/Maui37888Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
#nullable enable

using System;
using System.Reflection;
using Microsoft.Maui.ApplicationModel;
using Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload;
using Microsoft.Maui.Controls.Xaml;
using Xunit;

namespace Microsoft.Maui.Controls.SourceGen.UnitTests;

[Collection("XamlHotReloadTests")]
public class Maui37888Tests
{
const string IncrementalHotReloadSwitch = "Microsoft.Maui.RuntimeFeature.IsIncrementalHotReloadEnabled";
const string ResourceKey = "ExploratoryCaption";

[MetadataUpdateTheory]
[InlineData(false)]
[InlineData(true)]
public void ApplicationResourceUpdate_ReachesExistingAndNewConsumers(bool useMergedDictionary)
{
AppContext.TryGetSwitch(IncrementalHotReloadSwitch, out var previousSwitch);
var previousApplication = Application.Current;
AppContext.SetSwitch(IncrementalHotReloadSwitch, true);
SetMainThreadImplementation();

try
{
if (useMergedDictionary)
VerifyMergedDictionaryUpdate();
else
VerifyInlineApplicationResourceUpdate();
}
finally
{
Application.Current = previousApplication;
AppContext.SetSwitch(IncrementalHotReloadSwitch, previousSwitch);
ClearMainThreadImplementation();
}
}

[Fact]
public void NullConvertedResource_GuardsComponentRegistration()
{
const string rootClass = "TestMaui37888.NullResources";
const string codeBehind = """
using System;
using System.ComponentModel;
using System.Globalization;

namespace TestMaui37888;

[TypeConverter(typeof(NullResourceConverter))]
public sealed class NullResource
{
}

public sealed class NullResourceConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) =>
sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);

public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) =>
null;
}

public partial class NullResources : global::Microsoft.Maui.Controls.ResourceDictionary
{
private partial void InitializeComponent();

public NullResources() => InitializeComponent();
}
""";

string Xaml(string value) => $$"""
<ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:TestMaui37888"
x:Class="{{rootClass}}">
<local:NullResource x:Key="NullResource">{{value}}</local:NullResource>
<x:String x:Key="FollowingResource">{{value}}</x:String>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Regression Prevention and Test Coverage — Every resource exercised by the new tests is reference-typed: x:String here and at lines 118/155, plus the custom local:NullResource class at line 81. NullConvertedResource_GuardsComponentRegistration asserts the generated text "if (__uc_0 is not null)" is present, but because both fixtures are classes the assertion cannot discriminate the case where that emitted guard is invalid C# — a value-typed resource (see the CS0037 finding on UpdateComponentCodeWriter.cs:1050). The suite also only inspects generated source and never compiles it for this path, so the break stays green.

Add a case with a struct resource at the dictionary root — e.g. <x:Double x:Key="FontSizeBody">14</x:Double> edited to 16, or a Thickness — and drive it through the live-session harness (ApplyUpdateThroughRuntimeHandler) rather than string-matching, so the generated UpdateComponent() is actually compiled and the updated value is asserted on Resources["FontSizeBody"]. That is the negative case the current fixtures conflate away.

</ResourceDictionary>
""";

using var harness = new XamlHotReloadTestHarness(
nameof(NullConvertedResource_GuardsComponentRegistration),
rootClass,
codeBehind);
var generation = harness.Generate(Xaml("V0"), Xaml("V1"));
var updateComponentSource = generation[1].UpdateComponentSource;

Assert.NotNull(updateComponentSource);
Assert.Contains("if (__uc_0 is not null)", updateComponentSource, StringComparison.Ordinal);
Assert.Contains("this[\"FollowingResource\"] = __uc_1;", updateComponentSource, StringComparison.Ordinal);
harness.Compile(generation[1]);
}

static void VerifyInlineApplicationResourceUpdate()
{
const string rootClass = "TestMaui37888.App";
const string codeBehind = """
namespace TestMaui37888;

public partial class App : global::Microsoft.Maui.Controls.Application
{
private partial void InitializeComponent();

public App() => InitializeComponent();
}
""";

string Xaml(string value) => $$"""
<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="{{rootClass}}">
<Application.Resources>
<x:String x:Key="{{ResourceKey}}">{{value}}</x:String>
</Application.Resources>
</Application>
""";

using var harness = new XamlHotReloadTestHarness(
nameof(ApplicationResourceUpdate_ReachesExistingAndNewConsumers) + "_Inline",
rootClass,
codeBehind);
var generation = harness.Generate(Xaml("App resource V0"), Xaml("App resource V1"));

harness.RunLive(generation, live =>
{
var application = live.GetInstance<Application>();
Application.Current = application;
VerifyConsumers(application, () => live.ApplyUpdateThroughRuntimeHandler<Application>(1));
});
}

static void VerifyMergedDictionaryUpdate()
{
const string rootClass = "TestMaui37888.AppResources";
const string codeBehind = """
namespace TestMaui37888;

public partial class AppResources : global::Microsoft.Maui.Controls.ResourceDictionary
{
private partial void InitializeComponent();

public AppResources() => InitializeComponent();
}
""";

string Xaml(string value) => $$"""
<ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="{{rootClass}}">
<x:String x:Key="{{ResourceKey}}">{{value}}</x:String>
</ResourceDictionary>
""";

using var harness = new XamlHotReloadTestHarness(
nameof(ApplicationResourceUpdate_ReachesExistingAndNewConsumers) + "_Merged",
rootClass,
codeBehind);
var generation = harness.Generate(Xaml("App resource V0"), Xaml("App resource V1"));

harness.RunLive(generation, live =>
{
var application = new Application();
var dictionary = live.GetInstance<global::Microsoft.Maui.Controls.ResourceDictionary>();
application.Resources.MergedDictionaries.Add(dictionary);
Application.Current = application;
VerifyConsumers(application, () => live.ApplyUpdateThroughRuntimeHandler<global::Microsoft.Maui.Controls.ResourceDictionary>(1));
});
}

static void VerifyConsumers(Application application, Action applyUpdate)
{
var existingConsumer = CreateConsumer();
#pragma warning disable CS0618
application.MainPage = new ContentPage { Content = existingConsumer };
#pragma warning restore CS0618
Assert.Equal("App resource V0", existingConsumer.Text);

applyUpdate();

Assert.Equal("App resource V1", existingConsumer.Text);
Assert.Equal("App resource V1", CreateConsumer().Text);
Assert.Equal("App resource V1", application.Resources[ResourceKey]);
}

static Label CreateConsumer()
{
var label = new Label();
label.SetDynamicResource(Label.TextProperty, ResourceKey);
return label;
}

static void SetMainThreadImplementation()
{
var method = typeof(MainThread).GetMethod(
"SetCustomImplementation",
BindingFlags.Static | BindingFlags.NonPublic,
binder: null,
[typeof(Func<bool>), typeof(Action<Action>)],
modifiers: null);
Assert.NotNull(method);
method!.Invoke(null, [() => true, (Action<Action>)(action => action())]);
}

static void ClearMainThreadImplementation()
{
var method = typeof(MainThread).GetMethod(
"ClearCustomImplementation",
BindingFlags.Static | BindingFlags.NonPublic);
Assert.NotNull(method);
method!.Invoke(null, null);
}
}
Loading
Loading