Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
8be2d69
Add C# 14 extension property support for XAML
StephaneDelcroix Nov 27, 2025
fa76e88
Simplify SourceGen extension property detection and update comments
StephaneDelcroix Nov 28, 2025
faa8a7b
Enable SourceGen support for C# 14 extension properties
StephaneDelcroix Nov 28, 2025
40496cd
Add caching for extension property lookups to improve SourceGen perfo…
StephaneDelcroix Nov 28, 2025
fb4ab93
Adapt extension property changes to current main
StephaneDelcroix Aug 31, 2026
81bafcd
Resolve XAML extension properties from an explicitly named container
StephaneDelcroix Sep 7, 2026
a899949
Assert all three inflators reject unqualified and ambiguous extension…
StephaneDelcroix Sep 7, 2026
1856406
Only accept real extension containers, and let the setter define the …
StephaneDelcroix Sep 7, 2026
0530ffa
Cover qualified fallback, split accessors, object values and lookalik…
StephaneDelcroix Sep 7, 2026
ee6c759
Resolve a qualified member against the named owner, not the target's …
StephaneDelcroix Sep 7, 2026
7abea4b
Restrict the no-fallthrough rule to extension containers
StephaneDelcroix Sep 7, 2026
38f950f
Resolve unqualified extension properties through the element's xmlns …
StephaneDelcroix Sep 7, 2026
06bb3c0
Cover xmlns-scoped extension property resolution in the three inflators
StephaneDelcroix Sep 7, 2026
b0b89a8
Narrow extension property support to the source generator
StephaneDelcroix Sep 7, 2026
c75a40c
Select the most specific scoped candidate independently of enumeratio…
StephaneDelcroix Sep 7, 2026
4c17e8e
Renumber extension property diagnostics to MAUIX2020/MAUIX2021
StephaneDelcroix Nov 12, 2026
50d04b0
Fix extension property resolution issues found in review
StephaneDelcroix Nov 12, 2026
54ab75e
Fix extension property resolution and test gate
StephaneDelcroix Nov 16, 2026
368d727
Report generator diagnostics as test failures
StephaneDelcroix Nov 16, 2026
53509be
Merge candidate/11.0.1xx-sr2 into XAML extension properties
kubaflo Nov 17, 2026
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
2 changes: 2 additions & 0 deletions src/Controls/src/SourceGen/AnalyzerReleases.Unshipped.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,5 @@ MAUIX2017 | XamlInflation | Warning | DuplicatePropertyAssignment
MAUIX2018 | XamlParsing | Warning | StructIntermediateNotSettable
MAUIX2019 | XamlParsing | Error | LambdaMethodGroupReference
MAUIX2020 | XamlInflation | Warning | ConflictingXmlnsType
MAUIX2021 | XamlInflation | Error | ExtensionPropertyAmbiguous
MAUIX2022 | XamlInflation | Error | ExtensionPropertyResolution
16 changes: 16 additions & 0 deletions src/Controls/src/SourceGen/Descriptors.cs
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,22 @@ public static class Descriptors
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);

public static DiagnosticDescriptor ExtensionPropertyAmbiguous = new DiagnosticDescriptor(
id: "MAUIX2021",
title: new LocalizableResourceString(nameof(MauiGResources.SymbolResolution), MauiGResources.ResourceManager, typeof(MauiGResources)),
messageFormat: new LocalizableResourceString(nameof(MauiGResources.ExtensionPropertyAmbiguous), MauiGResources.ResourceManager, typeof(MauiGResources)),
category: "XamlInflation",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);

public static DiagnosticDescriptor ExtensionPropertyResolution = new DiagnosticDescriptor(
id: "MAUIX2022",
title: new LocalizableResourceString(nameof(MauiGResources.SymbolResolution), MauiGResources.ResourceManager, typeof(MauiGResources)),
messageFormat: new LocalizableResourceString(nameof(MauiGResources.ExtensionPropertyResolution), MauiGResources.ResourceManager, typeof(MauiGResources)),
category: "XamlInflation",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);

public static DiagnosticDescriptor DuplicatePropertyAssignment = new DiagnosticDescriptor(
id: "MAUIX2017",
title: new LocalizableResourceString(nameof(MauiGResources.DuplicatePropertyAssignmentTitle), MauiGResources.ResourceManager, typeof(MauiGResources)),
Expand Down
118 changes: 118 additions & 0 deletions src/Controls/src/SourceGen/ExtensionPropertyConventions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
namespace Microsoft.Maui.Controls.SourceGen
{
/// <summary>
/// Describes how the MAUI XAML source generator recognizes C# extension properties. The source generator
/// is the only inflator that supports them: it resolves everything at compile time, against the very
/// namespace map type names resolve through, and emits a direct call to the setter.
/// </summary>
/// <remarks>
/// <para>The C# compiler lowers</para>
/// <code>
/// public static class LabelExtensions
/// {
/// extension(Label label) { public string MyTag { get; set; } }
/// }
/// </code>
/// <para>
/// into a static class that declares <c>public static string get_MyTag(Label)</c> and
/// <c>public static void set_MyTag(Label, string)</c> implementation methods, plus a nested, unspeakable
/// "extension declaration" type that declares the extension property itself. The inflators call the
/// implementation method, and use the nested declaration as the marker that the container really is an
/// extension container.
/// </para>
/// <para>Both forms are supported in XAML:</para>
/// <code>
/// &lt;Label MyTag="Hello" /&gt; &lt;!-- resolved in the element's default xmlns --&gt;
/// &lt;Label local:LabelExtensions.MyTag="Hello" /&gt; &lt;!-- container named explicitly --&gt;
/// </code>
/// <para>
/// An unprefixed attribute carries no xml namespace, so an unqualified name is resolved in the default
/// xmlns declared for the element, which is what XAML uses as a scope, the way a C# file scopes extension
/// member lookup with its <c>using</c> directives. That scope is the very map type names are resolved
/// through: <c>[XmlnsDefinition]</c>, including everything the MAUI global xmlns pulls in for a document
/// that declares no xmlns at all. Candidates are therefore never searched for outside the namespaces and
/// assemblies the document already imports, and the map is cached per xmlns. An [XmlnsDefinition] only
/// imports its namespace from the assembly it names, so another referenced assembly reusing the namespace
/// name contributes no container. An assembly-less <c>using:</c> namespace searches referenced assemblies;
/// an assembly-less <c>clr-namespace:</c> namespace refers to the XAML assembly.
/// </para>
/// <para>
/// Naming the container explicitly stays available, to reach a container the document does not import and
/// to disambiguate. It is also the only form for which a name the container cannot resolve is an error
/// rather than a fallback, since naming a container means asking for one of its extension properties.
/// </para>
/// <para>Requirements for a container/accessor to be usable from XAML:</para>
/// <list type="bullet">
/// <item><description>the container is a non-generic static class;</description></item>
/// <item><description>the container declares an extension property with that name (see <see cref="IsSpeakable"/>);</description></item>
/// <item><description>the extension property is an instance property with a setter, and the container has the
/// <c>public static void set_Name(TReceiver, TValue)</c> implementation method matching that declaration's
/// receiver and value type. A hand-written static method that merely has that name is not an accessor;</description></item>
/// <item><description>the receiver parameter is not by-ref and is assignable from the target element type;</description></item>
/// <item><description>the container is accessible from the assembly declaring the XAML;</description></item>
/// <item><description>when several setters apply, whether on one container or across the containers a xmlns
/// brings in scope, exactly one has a receiver type more derived than all the others. All the setters of all
/// the containers in scope compete together, so an ambiguity inside one container is never hidden by a less
/// specific candidate from another.</description></item>
/// </list>
/// <para>
/// Ordinary members win: an unqualified name is only looked up among extension properties once events,
/// dynamic resources, bindings, bindable properties and the target's own properties have all been tried.
/// As in C#, an accessible instance property or field of that name hides extension properties even when it
/// cannot be assigned (no public setter, value not convertible): that is reported as an unresolved member.
/// </para>
/// <para>
/// Only assignment is supported, so the extension property declaring the selected setter alone defines the
/// receiver type and the value type, and supplies the [TypeConverter] used to convert attribute values.
/// Getters are never consulted: an extension property may be declared with its getter and its setter in
/// different extension blocks, with different receivers and even different value types, and merging those
/// into a single property shape would produce a shape no accessor actually has.
/// Reading an extension property (to add items to the collection it returns, for instance) is not supported
/// either, so that the three inflators keep accepting exactly the same markup. Generic extension blocks
/// (<c>extension&lt;T&gt;(ICollection&lt;T&gt;)</c>) and static extension properties have no applicable
/// <c>set_Name(TReceiver, TValue)</c> method and are reported, not silently ignored.
/// </para>
/// <para>
/// Markup extensions and converters receive the selected property through <c>IProvideValueTarget</c>.
/// Its <c>PropertyInfo.DeclaringType</c> is the compiler-generated extension declaration type, not the
/// type of the target element or the extension container.
/// </para>
/// <para>
/// Neither XamlC nor the runtime inflator resolve extension properties. Both would have to discover the
/// containers a xmlns brings in scope by enumerating the types of the mapped assemblies, which the source
/// generator gets for free from the namespace symbols of the compilation. XAML using an extension property
/// therefore has to be inflated by the source generator, and fails to resolve the member otherwise.
/// </para>
/// </remarks>
static class ExtensionPropertyConventions
{
public static string SetterName(string propertyName) => "set_" + propertyName;

/// <summary>
/// Tells whether a type name can be written in C#. The compiler names the nested extension declaration
/// types it generates with characters no C# identifier may contain, and those types are the marker the
/// inflators use to accept a container.
/// </summary>
/// <remarks>
/// The exact names are an implementation detail and differ between compiler versions, so they are never
/// matched; only their unspeakability is. <c>ExtensionAttribute</c> cannot be used instead: Roslyn does
/// not surface it through <c>ISymbol.GetAttributes()</c>, neither for source nor for metadata symbols,
/// and <c>INamedTypeSymbol.IsExtension</c> is newer than the Microsoft.CodeAnalysis version the MAUI
/// source generator is built against.
/// </remarks>
public static bool IsSpeakable(string typeName)
{
if (string.IsNullOrEmpty(typeName))
return false;

foreach (var c in typeName)
{
//generic arity (`1) and nesting separators are part of a speakable metadata name
if (!char.IsLetterOrDigit(c) && c != '_' && c != '.' && c != '`')
return false;
}

return true;
}
}
}
15 changes: 12 additions & 3 deletions src/Controls/src/SourceGen/KnownMarkups.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1168,7 +1168,8 @@ internal static bool ProvideValueForStaticResourceExtension(ElementNode node, In
{
var localName = propertyName.LocalName;
var bpFieldSymbol = parentVar.Type.GetBindableProperty(propertyName.NamespaceURI, ref localName, out System.Boolean attached, context, node as IXmlLineInfo);
var propertySymbol = parentVar.Type.GetAllProperties(localName, context).FirstOrDefault();
var extensionProperty = bpFieldSymbol == null ? SetPropertyHelpers.FindExtensionProperty(parentVar.Type, propertyName, node, context) : null;
var propertySymbol = extensionProperty ?? parentVar.Type.GetAllProperties(localName, context).FirstOrDefault();
var typeandconverter = bpFieldSymbol?.GetBPTypeAndConverter(context);

var propertyType = typeandconverter?.type ?? propertySymbol?.Type;
Expand All @@ -1181,15 +1182,23 @@ internal static bool ProvideValueForStaticResourceExtension(ElementNode node, In
converter = attributes.FirstOrDefault(ad => ad.AttributeClass?.ToString() == "System.ComponentModel.TypeConverterAttribute")?.ConstructorArguments[0].Value as ITypeSymbol;
}

if (propertyType!.Equals(context.Compilation.GetSpecialType(SpecialType.System_String), SymbolEqualityComparer.Default))
if (propertyType == null)
{
//no member to convert the resource to, let the assignment report it
returnType = context.Compilation.ObjectType;
value = string.Empty;
return false;
}

if (propertyType.Equals(context.Compilation.GetSpecialType(SpecialType.System_String), SymbolEqualityComparer.Default))
{
value = $"\"{vn.Value}\"";
returnType = context.Compilation.GetSpecialType(SpecialType.System_String);
return true;
}
try
{
value = vn.ConvertTo(propertyType!, converter, writer, context, parentVar);
value = vn.ConvertTo(propertyType!, converter, writer, context, parentVar, extensionProperty is not null ? node : null);
}
catch (Exception)
{
Expand Down
8 changes: 8 additions & 0 deletions src/Controls/src/SourceGen/MauiGResources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,14 @@
<value>No accessible property, BindableProperty, or event found for "{0}", or mismatching type between value and property.</value>
<comment>{0} is a property name</comment>
</data>
<data name="ExtensionPropertyAmbiguous" xml:space="preserve">
<value>Ambiguous extension property "{0}" for "{2}" in {1}. Multiple declarations apply, but none has a uniquely most-specific receiver.</value>
<comment>{0} is a property name, {1} is the namespace or container, {2} is the target type name</comment>
</data>
<data name="ExtensionPropertyResolution" xml:space="preserve">
<value>Cannot resolve the extension property "{0}" on "{1}". The extension property must be a non-generic instance extension property, declared in an accessible non-generic static extension container, with a receiver type matching "{2}" and an accessor for the requested operation, and it must be unambiguous.</value>
<comment>{0} is a property name, {1} is the extension container type name, {2} is the target type name</comment>
</data>
<data name="EasingConversionFailed" xml:space="preserve">
<value>Cannot convert "{0}" into Easing, expect value is "Linear", "SinOut", "SinIn", "SinInOut", "CubicIn", "CubicOut", "CubicInOut", "BounceOut", "BounceIn", "SpringIn" or "SpringOut".</value>
</data>
Expand Down
29 changes: 21 additions & 8 deletions src/Controls/src/SourceGen/NodeSGExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,12 @@ .. property.Type.GetAttributes()
public static bool CanConvertTo(this ValueNode valueNode, IPropertySymbol property, SourceGenContext context)
=> CanConvertTo(valueNode, property, context, out _);

public static bool CanConvertTo(this ValueNode valueNode, ITypeSymbol toType, SourceGenContext context)
{
var typeConverter = toType.GetAttributes().FirstOrDefault(ad => ad.AttributeClass?.ToFQDisplayString() == "global::System.ComponentModel.TypeConverterAttribute")?.ConstructorArguments[0].Value as ITypeSymbol;
return CanConvertTo(valueNode, toType, typeConverter, context);
}

public static bool CanConvertTo(this ValueNode valueNode, ITypeSymbol toType, ITypeSymbol? converter, SourceGenContext context)
{
// C# expressions can be assigned to any type - trust the user's code
Expand Down Expand Up @@ -403,7 +409,7 @@ public static string ConvertTo(this ValueNode valueNode, ITypeSymbol toType, Ind
return valueNode.ConvertTo(toType, typeConverter, writer, context, parentVar);
}

public static string ConvertTo(this ValueNode valueNode, ITypeSymbol toType, ITypeSymbol? typeConverter, IndentedTextWriter writer, SourceGenContext context, ILocalValue? parentVar = null)
public static string ConvertTo(this ValueNode valueNode, ITypeSymbol toType, ITypeSymbol? typeConverter, IndentedTextWriter writer, SourceGenContext context, ILocalValue? parentVar = null, INode? serviceProviderNode = null)
{
// C# expressions are emitted directly without conversion, but need quote transformation
if (valueNode.Value is Expression expression)
Expand All @@ -426,7 +432,9 @@ public static string ConvertTo(this ValueNode valueNode, ITypeSymbol toType, ITy
}

if (typeConverter is not null)
return valueNode.ConvertWithConverter(typeConverter, toType, writer, context, parentVar);
return serviceProviderNode is not null
? serviceProviderNode.ConvertWithConverter(SymbolDisplay.FormatLiteral(valueString, true), typeConverter, toType, writer, context)
: valueNode.ConvertWithConverter(typeConverter, toType, writer, context, parentVar);

if (toType.Equals(context.Compilation.GetTypeByMetadataName("System.Type"), SymbolEqualityComparer.Default))
return typeTypeConverter(valueString, valueNode, toType, writer, context, parentVar);
Expand Down Expand Up @@ -624,27 +632,32 @@ void reportDiagnostic()
public static string ConvertWithConverter(this ValueNode valueNode, ITypeSymbol typeConverter, ITypeSymbol targetType, IndentedTextWriter writer, SourceGenContext context, ILocalValue? parentVar = null)
{
var valueString = valueNode.Value as string ?? string.Empty;
return valueNode.ConvertWithConverter(SymbolDisplay.FormatLiteral(valueString, true), typeConverter, targetType, writer, context);
}

public static string ConvertWithConverter(this INode node, string valueExpression, ITypeSymbol typeConverter, ITypeSymbol targetType, IndentedTextWriter writer, SourceGenContext context)
{
//TODO check if there's a SourceGen version of the converter
if (typeConverter.Implements(context.Compilation.GetTypeByMetadataName("Microsoft.Maui.Controls.IExtendedTypeConverter")!))
{

var (acceptEmptyServiceProvider, requiredServices) = typeConverter.GetServiceProviderAttributes(context);
if (!acceptEmptyServiceProvider)
{
var serviceProvider = valueNode.GetOrCreateServiceProvider(writer, context, requiredServices);
var serviceProvider = node.GetOrCreateServiceProvider(writer, context, requiredServices);
if (targetType.IsReferenceType || targetType.NullableAnnotation == NullableAnnotation.Annotated)
return $"((global::Microsoft.Maui.Controls.IExtendedTypeConverter)new {typeConverter.ToFQDisplayString()}()).ConvertFromInvariantString(\"{valueString}\", {serviceProvider.ValueAccessor}) as {targetType.ToFQDisplayString()}";
return $"((global::Microsoft.Maui.Controls.IExtendedTypeConverter)new {typeConverter.ToFQDisplayString()}()).ConvertFromInvariantString({valueExpression}, {serviceProvider.ValueAccessor}) as {targetType.ToFQDisplayString()}";
else
return $"({targetType.ToFQDisplayString()})((global::Microsoft.Maui.Controls.IExtendedTypeConverter)new {typeConverter.ToFQDisplayString()}()).ConvertFromInvariantString(\"{valueString}\", {serviceProvider.ValueAccessor})!";
return $"({targetType.ToFQDisplayString()})((global::Microsoft.Maui.Controls.IExtendedTypeConverter)new {typeConverter.ToFQDisplayString()}()).ConvertFromInvariantString({valueExpression}, {serviceProvider.ValueAccessor})!";
}
else //should never happen. there's no point to implement IExtendedTypeConverter AND accept empty service provider
return $"((global::Microsoft.Maui.Controls.IExtendedTypeConverter)new {typeConverter.ToFQDisplayString()}()).ConvertFromInvariantString(\"{valueString}\", null) as {targetType.ToFQDisplayString()}";
return $"((global::Microsoft.Maui.Controls.IExtendedTypeConverter)new {typeConverter.ToFQDisplayString()}()).ConvertFromInvariantString({valueExpression}, null) as {targetType.ToFQDisplayString()}";
}
//TypeConverter returns an object, so we need to cast it to the target type
if (targetType.IsReferenceType || targetType.NullableAnnotation == NullableAnnotation.Annotated)
return $"((global::System.ComponentModel.TypeConverter)new {typeConverter.ToFQDisplayString()}()).ConvertFromInvariantString(\"{valueString}\") as {targetType.ToFQDisplayString()}";
return $"((global::System.ComponentModel.TypeConverter)new {typeConverter.ToFQDisplayString()}()).ConvertFromInvariantString({valueExpression}) as {targetType.ToFQDisplayString()}";
else
return $"({targetType.ToFQDisplayString()})new {typeConverter.ToFQDisplayString()}().ConvertFromInvariantString(\"{valueString}\")!";
return $"({targetType.ToFQDisplayString()})new {typeConverter.ToFQDisplayString()}().ConvertFromInvariantString({valueExpression})!";
}

public static bool IsValueProvider(this INode node, SourceGenContext context,
Expand Down
Loading
Loading