From 8d1adbb49fedeb34c5ebbea64458e8b6ebc5c90e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 24 May 2024 12:00:03 +0200 Subject: [PATCH 01/46] Add 'GeneratedCanvasEffectProperty' type --- .../GeneratedCanvasEffectPropertyAttribute.cs | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/ComputeSharp.D2D1.WinUI/Attributes/GeneratedCanvasEffectPropertyAttribute.cs diff --git a/src/ComputeSharp.D2D1.WinUI/Attributes/GeneratedCanvasEffectPropertyAttribute.cs b/src/ComputeSharp.D2D1.WinUI/Attributes/GeneratedCanvasEffectPropertyAttribute.cs new file mode 100644 index 00000000..48ead4d1 --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI/Attributes/GeneratedCanvasEffectPropertyAttribute.cs @@ -0,0 +1,65 @@ +using System; + +namespace ComputeSharp.D2D1.WinUI; + +/// +/// An attribute that indicates that a given property represents an effect property, which should invalidate the effect. +/// In order to use this attribute, the containing type has to inherit from . +/// +/// This attribute can be used as follows: +/// +/// partial class MyEffect : CanvasEffect +/// { +/// [GeneratedCanvasEffectProperty] +/// public int BlurAmount { get; set; } +/// } +/// +/// +/// And with this, code analogous to this will be generated: +/// +/// partial class MyEffect +/// { +/// public partial int BlurAmount +/// { +/// get => field; +/// set +/// { +/// if (EqualityComparer<int>.Default.Equals(field, value)) +/// { +/// return; +/// } +/// +/// int oldValue = field; +/// +/// OnBlurAmountChanging(value); +/// OnBlurAmountChanging(oldValue, value); +/// +/// field = value; +/// +/// OnBlurAmountChanged(value); +/// OnBlurAmountChanged(oldValue, value); +/// +/// InvalidateEffectGraph(<INVALIDATION_TYPE>); +/// } +/// } +/// +/// partial void OnBlurAmountChanging(int newValue); +/// partial void OnBlurAmountChanging(int oldValue, int newValue); +/// partial void OnBlurAmountChanged(int newValue); +/// partial void OnBlurAmountChanged(int oldValue, int newValue); +/// } +/// +/// +/// The invalidation type to request. +/// +/// The generated OnChanging and OnChanged methods will be completely removed by +/// the compiler if an implementation for the is not provided, making them fully pay-for-play. +/// +[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] +public sealed class GeneratedCanvasEffectPropertyAttribute(CanvasEffectInvalidationType invalidationType = CanvasEffectInvalidationType.Update) : Attribute +{ + /// + /// Gets the requested invalidation type for the effect graph when changing the proprty value. + /// + public CanvasEffectInvalidationType InvalidationType { get; } = invalidationType; +} \ No newline at end of file From 7dd827c87fe7c88d7e4dad11d89964a7adb91ede Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 24 May 2024 12:04:24 +0200 Subject: [PATCH 02/46] Add 'ComputeSharp.D2D1.WinUI.SourceGenerators' --- ComputeSharp.sln | 10 ++++++++++ .../ComputeSharp.D2D1.WinUI.SourceGenerators.csproj | 5 +++++ 2 files changed, 15 insertions(+) create mode 100644 src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj diff --git a/ComputeSharp.sln b/ComputeSharp.sln index ecce3d87..7ac58618 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -178,6 +178,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1.Uwp", "sr EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.SwapChain.D2D1.Uwp", "samples\ComputeSharp.SwapChain.D2D1.Uwp\ComputeSharp.SwapChain.D2D1.Uwp.csproj", "{9FBE070E-A210-4CEF-9F04-61C2B269C600}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.D2D1.WinUI.SourceGenerators", "src\ComputeSharp.D2D1.WinUI.SourceGenerators\ComputeSharp.D2D1.WinUI.SourceGenerators.csproj", "{FEBEC83A-FE70-4D4B-9B00-76DB31E75F17}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 @@ -502,6 +504,14 @@ Global {9FBE070E-A210-4CEF-9F04-61C2B269C600}.Release|x64.ActiveCfg = Release|x64 {9FBE070E-A210-4CEF-9F04-61C2B269C600}.Release|x64.Build.0 = Release|x64 {9FBE070E-A210-4CEF-9F04-61C2B269C600}.Release|x64.Deploy.0 = Release|x64 + {FEBEC83A-FE70-4D4B-9B00-76DB31E75F17}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {FEBEC83A-FE70-4D4B-9B00-76DB31E75F17}.Debug|ARM64.Build.0 = Debug|Any CPU + {FEBEC83A-FE70-4D4B-9B00-76DB31E75F17}.Debug|x64.ActiveCfg = Debug|Any CPU + {FEBEC83A-FE70-4D4B-9B00-76DB31E75F17}.Debug|x64.Build.0 = Debug|Any CPU + {FEBEC83A-FE70-4D4B-9B00-76DB31E75F17}.Release|ARM64.ActiveCfg = Release|Any CPU + {FEBEC83A-FE70-4D4B-9B00-76DB31E75F17}.Release|ARM64.Build.0 = Release|Any CPU + {FEBEC83A-FE70-4D4B-9B00-76DB31E75F17}.Release|x64.ActiveCfg = Release|Any CPU + {FEBEC83A-FE70-4D4B-9B00-76DB31E75F17}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj new file mode 100644 index 00000000..4641dbd6 --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj @@ -0,0 +1,5 @@ + + + netstandard2.0 + + From 6c628bf6df70f8e85b04d3f3cf035e29443809eb Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 24 May 2024 12:07:09 +0200 Subject: [PATCH 03/46] Add 'AnalyzerReleases.*' files to new project --- .../AnalyzerReleases.Shipped.md | 9 +++++++++ .../AnalyzerReleases.Unshipped.md | 2 ++ .../ComputeSharp.D2D1.WinUI.SourceGenerators.csproj | 9 +++++++++ 3 files changed, 20 insertions(+) create mode 100644 src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md create mode 100644 src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Unshipped.md diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md new file mode 100644 index 00000000..85c2ce90 --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md @@ -0,0 +1,9 @@ +; Shipped analyzer releases +; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md + +## Release 1.0 + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------- diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Unshipped.md new file mode 100644 index 00000000..6a6dd08d --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -0,0 +1,2 @@ +; Unshipped analyzer release +; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj index 4641dbd6..a65da1f7 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj @@ -2,4 +2,13 @@ netstandard2.0 + + + + + + + + + From c779ef65205ff17528545379906b48e000ebf2d7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 24 May 2024 12:11:37 +0200 Subject: [PATCH 04/46] Add 'ComputeSharp.D2D1.WinUI.targets' --- .../ComputeSharp.D2D1.WinUI.targets | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/ComputeSharp.D2D1.WinUI/ComputeSharp.D2D1.WinUI.targets diff --git a/src/ComputeSharp.D2D1.WinUI/ComputeSharp.D2D1.WinUI.targets b/src/ComputeSharp.D2D1.WinUI/ComputeSharp.D2D1.WinUI.targets new file mode 100644 index 00000000..7aaabd02 --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI/ComputeSharp.D2D1.WinUI.targets @@ -0,0 +1,55 @@ + + + + + + <_ComputeSharpD2D1WinUIAnalyzer Include="@(Analyzer)" Condition="'%(Analyzer.NuGetPackageId)' == 'ComputeSharp.D2D1.WinUI'" /> + + + + + + + + + + + + + + + @(ComputeSharpD2D1WinUICurrentCompilerAssemblyIdentity->'%(Version)') + + + true + + + + + + + + + + + + + + + + + + + + From e330bb53724ace3e3da9afe1186e335818cfcabb Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 25 May 2024 12:53:35 +0200 Subject: [PATCH 05/46] Share 'SyntaxNodeExtensions' with common project --- .../Extensions/SyntaxNodeExtensions.cs | 32 +--------------- .../ComputeSharp.SourceGeneration.projitems | 1 + .../Extensions/SyntaxNodeExtensions.cs | 38 +++++++++++++++++++ 3 files changed, 41 insertions(+), 30 deletions(-) create mode 100644 src/ComputeSharp.SourceGeneration/Extensions/SyntaxNodeExtensions.cs diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Extensions/SyntaxNodeExtensions.cs index fa7b4db0..104119d3 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/Extensions/SyntaxNodeExtensions.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Extensions/SyntaxNodeExtensions.cs @@ -6,37 +6,9 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGeneration.Extensions; -/// -/// A with some extension methods for C# syntax nodes. -/// -internal static class SyntaxNodeExtensions +/// +partial class SyntaxNodeExtensions { - /// - /// Checks whether a given is a given type declaration with or potentially with any base types, using only syntax. - /// - /// The type of declaration to check for. - /// The input to check. - /// Whether is a given type declaration with or potentially with any base types. - public static bool IsTypeDeclarationWithOrPotentiallyWithBaseTypes(this SyntaxNode node) - where T : TypeDeclarationSyntax - { - // Immediately bail if the node is not a type declaration of the specified type - if (node is not T typeDeclaration) - { - return false; - } - - // If the base types list is not empty, the type can definitely has implemented interfaces - if (typeDeclaration.BaseList is { Types.Count: > 0 }) - { - return true; - } - - // If the base types list is empty, check if the type is partial. If it is, it means - // that there could be another partial declaration with a non-empty base types list. - return typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword); - } - /// /// Returns a with a block body. /// diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index 3dc0426f..b932f8c9 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -19,6 +19,7 @@ + diff --git a/src/ComputeSharp.SourceGeneration/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/SyntaxNodeExtensions.cs new file mode 100644 index 00000000..28aad272 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Extensions/SyntaxNodeExtensions.cs @@ -0,0 +1,38 @@ +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ComputeSharp.SourceGeneration.Extensions; + +/// +/// A with some extension methods for C# syntax nodes. +/// +internal static partial class SyntaxNodeExtensions +{ + /// + /// Checks whether a given is a given type declaration with or potentially with any base types, using only syntax. + /// + /// The type of declaration to check for. + /// The input to check. + /// Whether is a given type declaration with or potentially with any base types. + public static bool IsTypeDeclarationWithOrPotentiallyWithBaseTypes(this SyntaxNode node) + where T : TypeDeclarationSyntax + { + // Immediately bail if the node is not a type declaration of the specified type + if (node is not T typeDeclaration) + { + return false; + } + + // If the base types list is not empty, the type can definitely has implemented interfaces + if (typeDeclaration.BaseList is { Types.Count: > 0 }) + { + return true; + } + + // If the base types list is empty, check if the type is partial. If it is, it means + // that there could be another partial declaration with a non-empty base types list. + return typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword); + } +} \ No newline at end of file From 8185999b72b76609cea7ac0598c0d2320be3c97a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 25 May 2024 12:53:52 +0200 Subject: [PATCH 06/46] Add initial 'CanvasEffectPropertyGenerator' type --- ComputeSharp.sln | 1 + .../CanvasEffectPropertyGenerator.Execute.cs | 42 +++++++++++++++++++ .../CanvasEffectPropertyGenerator.cs | 26 ++++++++++++ ...teSharp.D2D1.WinUI.SourceGenerators.csproj | 3 ++ .../ComputeSharp.SourceGenerators.csproj | 2 +- 5 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs create mode 100644 src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 7ac58618..91ef1788 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -587,5 +587,6 @@ Global src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5 samples\ComputeSharp.SwapChain.Shaders.D2D1\ComputeSharp.SwapChain.Shaders.D2D1.projitems*{f8bf7666-7ccf-4fe4-b055-2eba4bcd4564}*SharedItemsImports = 13 src\ComputeSharp.UI\ComputeSharp.UI.projitems*{fa18ba9f-76bf-4de0-8d24-02fc7657e6cb}*SharedItemsImports = 5 + src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{febec83a-fe70-4d4b-9b00-76db31e75f17}*SharedItemsImports = 5 EndGlobalSection EndGlobal diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs new file mode 100644 index 00000000..c056ab63 --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs @@ -0,0 +1,42 @@ +using System.Threading; +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ComputeSharp.D2D1.WinUI.SourceGenerators; + +/// +partial class CanvasEffectPropertyGenerator +{ + /// + /// A container for all the logic for . + /// + private static partial class Execute + { + /// + /// Checks whether an input syntax node is a candidate property declaration for the generator. + /// + /// The input syntax node to check. + /// The used to cancel the operation, if needed. + /// Whether is a candidate property declaration. + public static bool IsCandidatePropertyDeclaration(SyntaxNode node, CancellationToken token) + { + // The node must be a property declaration with two accessors + if (node is not PropertyDeclarationSyntax { AccessorList.Accessors: { Count: 2 } accessors }) + { + return false; + } + + // The accessors must be a get and a set (with any accessibility) + if (accessors[0].Kind() is not (SyntaxKind.GetAccessorDeclaration or SyntaxKind.SetAccessorDeclaration) || + accessors[1].Kind() is not (SyntaxKind.GetAccessorDeclaration or SyntaxKind.SetAccessorDeclaration)) + { + return false; + } + + // The property must be in a type with a base type (as it must derive from CanvasEffect) + return node.Parent?.IsTypeDeclarationWithOrPotentiallyWithBaseTypes() == true; + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs new file mode 100644 index 00000000..281cb62e --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -0,0 +1,26 @@ +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1.WinUI.SourceGenerators; + +/// +/// A source generator creating implementations of effect properties. +/// +[Generator(LanguageNames.CSharp)] +public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerator +{ + /// + /// The name of generator to include in the generated code. + /// + private const string GeneratorName = "ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator"; + + /// + public void Initialize(IncrementalGeneratorInitializationContext context) + { + IncrementalValuesProvider propertyInfo = + context.SyntaxProvider + .ForAttributeWithMetadataName( + "ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute", + Execute.IsCandidatePropertyDeclaration, + static (context, token) => (object?)null); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj index a65da1f7..8d807603 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj @@ -11,4 +11,7 @@ + + + diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 7dc48379..af7f8515 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -73,7 +73,7 @@ - + From 616766bc800202ae38de4c5b0e1bb81962562616 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 3 Jun 2024 01:12:41 +0200 Subject: [PATCH 07/46] Add initial 'CanvasEffectPropertyInfo' type --- .../Models/CanvasEffectPropertyInfo.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs new file mode 100644 index 00000000..2653c9ad --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs @@ -0,0 +1,16 @@ +using ComputeSharp.SourceGeneration.Models; + +namespace ComputeSharp.D2D1.WinUI.SourceGenerators.Models; + +/// +/// A model representing a generated canvas effect property. +/// +/// The hierarchy info for the shader type. +/// The type name for the generated property, including nullability annotations. +/// The generated property name. +/// Whether the old property value is being directly referenced. +internal sealed record CanvasEffectPropertyInfo( + HierarchyInfo Hierarchy, + string PropertyName, + string TypeNameWithNullabilityAnnotations, + bool IsOldPropertyValueDirectlyReferenced); From 63bf3d98e797d2e73a6565c308e43b723d9146b8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 3 Jun 2024 01:13:01 +0200 Subject: [PATCH 08/46] Initial prototype to gather property infos --- .../CanvasEffectPropertyGenerator.Execute.cs | 31 ++++++++++++++++ .../CanvasEffectPropertyGenerator.cs | 35 +++++++++++++++++-- .../Extensions/ISymbolExtensions.cs | 10 ++++++ .../Extensions/ITypeSymbolExtensions.cs | 23 ++++++++++++ 4 files changed, 97 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs index c056ab63..43b92c31 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs @@ -38,5 +38,36 @@ partial class CanvasEffectPropertyGenerator // The property must be in a type with a base type (as it must derive from CanvasEffect) return node.Parent?.IsTypeDeclarationWithOrPotentiallyWithBaseTypes() == true; } + + /// + /// Checks whether the generated code has to directly reference the old property value. + /// + /// The input instance to process. + /// Whether the generated code needs direct access to the old property value. + public static bool IsOldPropertyValueDirectlyReferenced(IPropertySymbol propertySymbol) + { + // Check OnChanging( oldValue, newValue) first + foreach (ISymbol symbol in propertySymbol.ContainingType.GetMembers($"On{propertySymbol.Name}Changing")) + { + // No need to be too specific as we're not expecting false positives (which also wouldn't really + // cause any problems anyway, just produce slightly worse codegen). Just checking the number of + // parameters is good enough, and keeps the code very simple and cheap to run. + if (symbol is IMethodSymbol { Parameters.Length: 2 }) + { + return true; + } + } + + // Do the same for OnChanged( oldValue, newValue) + foreach (ISymbol symbol in propertySymbol.ContainingType.GetMembers($"On{propertySymbol.Name}Changed")) + { + if (symbol is IMethodSymbol { Parameters.Length: 2 }) + { + return true; + } + } + + return false; + } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs index 281cb62e..02471ca7 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -1,3 +1,6 @@ +using ComputeSharp.D2D1.WinUI.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; namespace ComputeSharp.D2D1.WinUI.SourceGenerators; @@ -16,11 +19,39 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato /// public void Initialize(IncrementalGeneratorInitializationContext context) { - IncrementalValuesProvider propertyInfo = + IncrementalValuesProvider propertyInfo = context.SyntaxProvider .ForAttributeWithMetadataName( "ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute", Execute.IsCandidatePropertyDeclaration, - static (context, token) => (object?)null); + static (context, token) => + { + // Ensure we do have a property with a valid containing type + if (context.TargetSymbol is not IPropertySymbol { ContainingType: INamedTypeSymbol typeSymbol } propertySymbol) + { + return default; + } + + // Ensure that the containing type derives from CanvasEffect + if (!typeSymbol.InheritsFromFullyQualifiedMetadataName("ComputeSharp.D2D1.WinUI.CanvasEffect")) + { + return default; + } + + string typeNameWithNullabilityAnnotations = propertySymbol.Type.GetFullyQualifiedNameWithNullabilityAnnotations(); + bool isOldPropertyValueDirectlyReferenced = Execute.IsOldPropertyValueDirectlyReferenced(propertySymbol); + + // Finally, get the hierarchy too + HierarchyInfo hierarchyInfo = HierarchyInfo.From(typeSymbol); + + token.ThrowIfCancellationRequested(); + + return new CanvasEffectPropertyInfo( + Hierarchy: hierarchyInfo, + PropertyName: propertySymbol.Name, + TypeNameWithNullabilityAnnotations: typeNameWithNullabilityAnnotations, + IsOldPropertyValueDirectlyReferenced: isOldPropertyValueDirectlyReferenced); + }) + .Where(static item => item is not null)!; } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs index 612b5fb7..c52abfae 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs @@ -59,6 +59,16 @@ internal static class ISymbolExtensions : symbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat); } + /// + /// Gets the fully qualified name for a given symbol, including nullability annotations + /// + /// The input instance. + /// The fully qualified name for . + public static string GetFullyQualifiedNameWithNullabilityAnnotations(this ISymbol symbol) + { + return symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier)); + } + /// /// Checks whether or not a given symbol has an attribute with the specified type. /// diff --git a/src/ComputeSharp.SourceGeneration/Extensions/ITypeSymbolExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/ITypeSymbolExtensions.cs index 440a2503..5cb39bd5 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/ITypeSymbolExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/ITypeSymbolExtensions.cs @@ -44,6 +44,29 @@ internal static class ITypeSymbolExtensions return builder.WrittenSpan.SequenceEqual(name.AsSpan()); } + /// + /// Checks whether or not a given inherits from a specified type. + /// + /// The target instance to check. + /// The full name of the type to check for inheritance. + /// Whether or not inherits from . + public static bool InheritsFromFullyQualifiedMetadataName(this ITypeSymbol typeSymbol, string name) + { + INamedTypeSymbol? baseType = typeSymbol.BaseType; + + while (baseType is not null) + { + if (baseType.HasFullyQualifiedMetadataName(name)) + { + return true; + } + + baseType = baseType.BaseType; + } + + return false; + } + /// /// Checks whether or not a given implements an interface of a specified type. /// From 18839f5bd2d61c7772acb19f8d839caa23a86620 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 3 Jun 2024 01:51:21 +0200 Subject: [PATCH 09/46] Update 'WriteGeneratedAttributes' with more options --- .../IndentedTextWriterExtensions.cs | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs index 575c1c9d..14ec4e7f 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs @@ -21,7 +21,12 @@ internal static class IndentedTextWriterExtensions /// The instance to write into. /// The name of the generator. /// Whether to use fully qualified type names or not. - public static void WriteGeneratedAttributes(this IndentedTextWriter writer, string generatorName, bool useFullyQualifiedTypeNames = true) + /// Whether to also include the attribute for non-user code. + public static void WriteGeneratedAttributes( + this IndentedTextWriter writer, + string generatorName, + bool useFullyQualifiedTypeNames = true, + bool includeNonUserCodeAttributes = true) { // We can use this class to get the assembly, as all files for generators are just included // via shared projects. As such, the assembly will be the same as the generator type itself. @@ -30,14 +35,22 @@ internal static class IndentedTextWriterExtensions if (useFullyQualifiedTypeNames) { writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{generatorName}}", "{{assemblyVersion}}")]"""); - writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); - writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"""); + + if (includeNonUserCodeAttributes) + { + writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); + writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"""); + } } else { writer.WriteLine($$"""[GeneratedCode("{{generatorName}}", "{{assemblyVersion}}")]"""); - writer.WriteLine($$"""[DebuggerNonUserCode]"""); - writer.WriteLine($$"""[ExcludeFromCodeCoverage]"""); + + if (includeNonUserCodeAttributes) + { + writer.WriteLine($$"""[DebuggerNonUserCode]"""); + writer.WriteLine($$"""[ExcludeFromCodeCoverage]"""); + } } } From 58ad9e8bc9df8c70e491406f3606d34ce9110b0f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 3 Jun 2024 01:51:47 +0200 Subject: [PATCH 10/46] Port and update 'GroupBy' extension --- .../ComputeSharp.SourceGeneration.projitems | 1 + .../IncrementalValueProviderExtensions.cs | 64 +++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 src/ComputeSharp.SourceGeneration/Extensions/IncrementalValueProviderExtensions.cs diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index b932f8c9..4084a568 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -13,6 +13,7 @@ + diff --git a/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValueProviderExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValueProviderExtensions.cs new file mode 100644 index 00000000..ee226aa9 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValueProviderExtensions.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Helpers; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGeneration.Extensions; + +/// +/// Extension methods for . +/// +internal static class IncrementalValuesProviderExtensions +{ + /// + /// Groups items in a given sequence by a specified key. + /// + /// The type of value that this source provides access to. + /// The type of resulting key elements. + /// The type of resulting projected elements. + /// The input instance. + /// The key selection . + /// The element selection . + /// An with the grouped results. + public static IncrementalValuesProvider<(TKey Key, EquatableArray Right)> GroupBy( + this IncrementalValuesProvider source, + Func keySelector, + Func elementSelector) + where TValues : IEquatable + where TKey : IEquatable + where TElement : IEquatable + { + return source.Collect().SelectMany((item, token) => + { + Dictionary.Builder> map = []; + + foreach (TValues value in item) + { + TKey key = keySelector(value); + TElement element = elementSelector(value); + + if (!map.TryGetValue(key, out ImmutableArray.Builder builder)) + { + builder = ImmutableArray.CreateBuilder(); + + map.Add(key, builder); + } + + builder.Add(element); + } + + token.ThrowIfCancellationRequested(); + + ImmutableArray<(TKey Key, EquatableArray Elements)>.Builder result = + ImmutableArray.CreateBuilder<(TKey, EquatableArray)>(); + + foreach (KeyValuePair.Builder> entry in map) + { + result.Add((entry.Key, entry.Value.ToImmutable())); + } + + return result; + }); + } +} From 44959ce41719e6ff556e99803a477cd19c7b73c7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 3 Jun 2024 01:52:14 +0200 Subject: [PATCH 11/46] Complete prototype to also generate code --- .../CanvasEffectPropertyGenerator.Execute.cs | 95 +++++++++++++++++++ .../CanvasEffectPropertyGenerator.cs | 28 +++++- .../Models/CanvasEffectPropertyInfo.cs | 4 +- 3 files changed, 125 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs index 43b92c31..d298b1b5 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs @@ -1,5 +1,7 @@ using System.Threading; +using ComputeSharp.D2D1.WinUI.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -69,5 +71,98 @@ partial class CanvasEffectPropertyGenerator return false; } + + public static void WritePropertyDeclarations(EquatableArray properties, IndentedTextWriter writer) + { + // First, generate all partial property implementations at the top of the partial type declaration + foreach (CanvasEffectPropertyInfo propertyInfo in properties) + { + writer.WriteLine(skipIfPresent: true); + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine($$""" + public partial {{propertyInfo.TypeNameWithNullabilityAnnotations}} {{propertyInfo.PropertyName}} + { + get => field; + set + { + if (global::System.Collections.Generic.EqualityComparer<{{propertyInfo.TypeNameWithNullabilityAnnotations}}>.Default.Equals(field, value)) + { + return; + } + + int oldValue = field; + + On{{propertyInfo.PropertyName}}Changing(value); + On{{propertyInfo.PropertyName}}Changing(oldValue, value); + + field = value; + + On{{propertyInfo.PropertyName}}Changed(value); + On{{propertyInfo.PropertyName}}Changed(oldValue, value); + + InvalidateEffectGraph(default); + } + } + """, isMultiline: true); + } + + foreach (CanvasEffectPropertyInfo propertyInfo in properties) + { + // OnChanging, only with new value + writer.WriteLine(); + writer.WriteLine($""" + /// Executes the logic for when is changing. + /// The new property value being set. + /// This method is invoked right before the value of is changed. + """, isMultiline: true); + writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false); + writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changing({propertyInfo.TypeNameWithNullabilityAnnotations} newValue);"); + + // Prepare the nullable type for the previous property value. This is needed because if the type is a reference + // type, the previous value might be null even if the property type is not nullable, as the first invocation would + // happen when the property is first set to some value that is not null (but the backing field would still be so). + // As a cheap way to check whether we need to add nullable, we can simply check whether the type name with nullability + // annotations ends with a '?'. If it doesn't and the type is a reference type, we add it. Otherwise, we keep it. + string oldValueTypeNameAsNullable = propertyInfo.IsReferenceTypeOrUnconstraindTypeParameter switch + { + true when !propertyInfo.TypeNameWithNullabilityAnnotations.EndsWith("?") + => $"{propertyInfo.TypeNameWithNullabilityAnnotations}?", + _ => propertyInfo.TypeNameWithNullabilityAnnotations + }; + + // OnChanging, with both values + writer.WriteLine(); + writer.WriteLine($""" + /// Executes the logic for when is changing. + /// The previous property value that is being replaced. + /// The new property value being set. + /// This method is invoked right before the value of is changed. + """, isMultiline: true); + writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false); + writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changing({oldValueTypeNameAsNullable} oldValue, {propertyInfo.TypeNameWithNullabilityAnnotations} newValue);"); + + // OnChanged, only with new value + writer.WriteLine(); + writer.WriteLine($""" + /// Executes the logic for when has just changed. + /// The new property value that has been set. + /// This method is invoked right after the value of is changed. + """, isMultiline: true); + writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false); + writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changed({propertyInfo.TypeNameWithNullabilityAnnotations} newValue);"); + + // OnChanged, with both values + writer.WriteLine(); + writer.WriteLine($""" + /// Executes the logic for when has just changed. + /// The previous property value that has been replaced. + /// The new property value that has been set. + /// This method is invoked right after the value of is changed. + """, isMultiline: true); + writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false); + writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changed({oldValueTypeNameAsNullable} oldValue, {propertyInfo.TypeNameWithNullabilityAnnotations} newValue);"); + } + } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs index 02471ca7..8332fcaf 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -1,5 +1,6 @@ using ComputeSharp.D2D1.WinUI.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; @@ -41,6 +42,11 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato string typeNameWithNullabilityAnnotations = propertySymbol.Type.GetFullyQualifiedNameWithNullabilityAnnotations(); bool isOldPropertyValueDirectlyReferenced = Execute.IsOldPropertyValueDirectlyReferenced(propertySymbol); + // We're using IsValueType here and not IsReferenceType to also cover unconstrained type parameter cases. + // This will cover both reference types as well T when the constraints are not struct or unmanaged. + // If this is true, it means the field storage can potentially be in a null state (even if not annotated). + bool isReferenceTypeOrUnconstraindTypeParameter = !propertySymbol.Type.IsValueType; + // Finally, get the hierarchy too HierarchyInfo hierarchyInfo = HierarchyInfo.From(typeSymbol); @@ -50,8 +56,28 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato Hierarchy: hierarchyInfo, PropertyName: propertySymbol.Name, TypeNameWithNullabilityAnnotations: typeNameWithNullabilityAnnotations, - IsOldPropertyValueDirectlyReferenced: isOldPropertyValueDirectlyReferenced); + IsOldPropertyValueDirectlyReferenced: isOldPropertyValueDirectlyReferenced, + IsReferenceTypeOrUnconstraindTypeParameter: isReferenceTypeOrUnconstraindTypeParameter); }) .Where(static item => item is not null)!; + + // Split and group by containing type + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EquatableArray Properties)> groupedPropertyInfo = + propertyInfo + .GroupBy(keySelector: static item => item.Hierarchy, elementSelector: static item => item); + + // Generate the source files, if any + context.RegisterSourceOutput(groupedPropertyInfo, static (context, item) => + { + using IndentedTextWriter writer = new(); + + item.Hierarchy.WriteSyntax( + state: item.Properties, + writer: writer, + baseTypes: [], + memberCallbacks: [Execute.WritePropertyDeclarations]); + + context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", writer.ToString()); + }); } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs index 2653c9ad..98ab84ae 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs @@ -9,8 +9,10 @@ namespace ComputeSharp.D2D1.WinUI.SourceGenerators.Models; /// The type name for the generated property, including nullability annotations. /// The generated property name. /// Whether the old property value is being directly referenced. +/// Indicates whether the property is of a reference type or an unconstrained type parameter. internal sealed record CanvasEffectPropertyInfo( HierarchyInfo Hierarchy, string PropertyName, string TypeNameWithNullabilityAnnotations, - bool IsOldPropertyValueDirectlyReferenced); + bool IsOldPropertyValueDirectlyReferenced, + bool IsReferenceTypeOrUnconstraindTypeParameter); From 3f4d59e9813f6fb25157e18c4719e681a7e9f131 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 3 Jun 2024 02:16:23 +0200 Subject: [PATCH 12/46] Propagate the 'InvalidationType' parameter --- .../CanvasEffectInvalidationType.cs | 2 ++ .../CanvasEffectPropertyGenerator.Execute.cs | 19 ++++++++++++++++++- .../CanvasEffectPropertyGenerator.cs | 4 +++- ...teSharp.D2D1.WinUI.SourceGenerators.csproj | 12 ++++++++++++ .../Models/CanvasEffectPropertyInfo.cs | 4 +++- 5 files changed, 38 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs b/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs index 00b24c07..aef4f100 100644 --- a/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs +++ b/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs @@ -1,5 +1,7 @@ +#if !D2D1_UWINUI_SOURCE_GENERATOR using ABI.Microsoft.Graphics.Canvas; using Microsoft.Graphics.Canvas; +#endif #if WINDOWS_UWP namespace ComputeSharp.D2D1.Uwp; diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs index d298b1b5..1ac2abf1 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs @@ -41,6 +41,23 @@ partial class CanvasEffectPropertyGenerator return node.Parent?.IsTypeDeclarationWithOrPotentiallyWithBaseTypes() == true; } + /// + /// Gets the invalidation type to use for the generated effect property. + /// + /// The instance for the processed attribute. + /// The resulting to use for the generated property. + public static CanvasEffectInvalidationType GetCanvasEffectInvalidationType(AttributeData attributeData) + { + if (attributeData.ConstructorArguments is [{ Kind: TypedConstantKind.Enum, Value: byte enumValue }]) + { + return (CanvasEffectInvalidationType)enumValue; + } + + // No constructor parameter, or an invalid one. In this case we either just use the default + // invalidation mode, or let the analyzer emit a diagnostic to let the user know. + return CanvasEffectInvalidationType.Update; + } + /// /// Checks whether the generated code has to directly reference the old property value. /// @@ -101,7 +118,7 @@ partial class CanvasEffectPropertyGenerator On{{propertyInfo.PropertyName}}Changed(value); On{{propertyInfo.PropertyName}}Changed(oldValue, value); - InvalidateEffectGraph(default); + InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.{{propertyInfo.InvalidationType}}); } } """, isMultiline: true); diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs index 8332fcaf..d0d24d96 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -41,6 +41,7 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato string typeNameWithNullabilityAnnotations = propertySymbol.Type.GetFullyQualifiedNameWithNullabilityAnnotations(); bool isOldPropertyValueDirectlyReferenced = Execute.IsOldPropertyValueDirectlyReferenced(propertySymbol); + CanvasEffectInvalidationType invalidationType = Execute.GetCanvasEffectInvalidationType(context.Attributes[0]); // We're using IsValueType here and not IsReferenceType to also cover unconstrained type parameter cases. // This will cover both reference types as well T when the constraints are not struct or unmanaged. @@ -57,7 +58,8 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato PropertyName: propertySymbol.Name, TypeNameWithNullabilityAnnotations: typeNameWithNullabilityAnnotations, IsOldPropertyValueDirectlyReferenced: isOldPropertyValueDirectlyReferenced, - IsReferenceTypeOrUnconstraindTypeParameter: isReferenceTypeOrUnconstraindTypeParameter); + IsReferenceTypeOrUnconstraindTypeParameter: isReferenceTypeOrUnconstraindTypeParameter, + InvalidationType: invalidationType); }) .Where(static item => item is not null)!; diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj index 8d807603..8003250d 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj @@ -1,6 +1,13 @@ netstandard2.0 + $(DefineConstants);D2D1_UWINUI_SOURCE_GENERATOR + + + + + + $(NoWarn);CS1574 @@ -12,6 +19,11 @@ + + + + + diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs index 98ab84ae..7deb91a6 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs @@ -10,9 +10,11 @@ namespace ComputeSharp.D2D1.WinUI.SourceGenerators.Models; /// The generated property name. /// Whether the old property value is being directly referenced. /// Indicates whether the property is of a reference type or an unconstrained type parameter. +/// The invalidation type to request. internal sealed record CanvasEffectPropertyInfo( HierarchyInfo Hierarchy, string PropertyName, string TypeNameWithNullabilityAnnotations, bool IsOldPropertyValueDirectlyReferenced, - bool IsReferenceTypeOrUnconstraindTypeParameter); + bool IsReferenceTypeOrUnconstraindTypeParameter, + CanvasEffectInvalidationType InvalidationType); From 57f1d3902bf1e64f4795a39816598754d57e3b7b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 3 Jun 2024 02:18:57 +0200 Subject: [PATCH 13/46] Check for cancellation more often in generator --- .../CanvasEffectPropertyGenerator.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs index d0d24d96..0430b410 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -39,10 +39,20 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato return default; } + token.ThrowIfCancellationRequested(); + string typeNameWithNullabilityAnnotations = propertySymbol.Type.GetFullyQualifiedNameWithNullabilityAnnotations(); + + token.ThrowIfCancellationRequested(); + bool isOldPropertyValueDirectlyReferenced = Execute.IsOldPropertyValueDirectlyReferenced(propertySymbol); + + token.ThrowIfCancellationRequested(); + CanvasEffectInvalidationType invalidationType = Execute.GetCanvasEffectInvalidationType(context.Attributes[0]); + token.ThrowIfCancellationRequested(); + // We're using IsValueType here and not IsReferenceType to also cover unconstrained type parameter cases. // This will cover both reference types as well T when the constraints are not struct or unmanaged. // If this is true, it means the field storage can potentially be in a null state (even if not annotated). From 9f789d1bb3ffc8e84b872dc5a01c1483c1d8b807 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 3 Jun 2024 02:23:45 +0200 Subject: [PATCH 14/46] Remove micro-optimization for old field values --- .../CanvasEffectPropertyGenerator.Execute.cs | 31 ------------------- .../CanvasEffectPropertyGenerator.cs | 5 --- .../Models/CanvasEffectPropertyInfo.cs | 2 -- 3 files changed, 38 deletions(-) diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs index 1ac2abf1..878468cf 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs @@ -58,37 +58,6 @@ partial class CanvasEffectPropertyGenerator return CanvasEffectInvalidationType.Update; } - /// - /// Checks whether the generated code has to directly reference the old property value. - /// - /// The input instance to process. - /// Whether the generated code needs direct access to the old property value. - public static bool IsOldPropertyValueDirectlyReferenced(IPropertySymbol propertySymbol) - { - // Check OnChanging( oldValue, newValue) first - foreach (ISymbol symbol in propertySymbol.ContainingType.GetMembers($"On{propertySymbol.Name}Changing")) - { - // No need to be too specific as we're not expecting false positives (which also wouldn't really - // cause any problems anyway, just produce slightly worse codegen). Just checking the number of - // parameters is good enough, and keeps the code very simple and cheap to run. - if (symbol is IMethodSymbol { Parameters.Length: 2 }) - { - return true; - } - } - - // Do the same for OnChanged( oldValue, newValue) - foreach (ISymbol symbol in propertySymbol.ContainingType.GetMembers($"On{propertySymbol.Name}Changed")) - { - if (symbol is IMethodSymbol { Parameters.Length: 2 }) - { - return true; - } - } - - return false; - } - public static void WritePropertyDeclarations(EquatableArray properties, IndentedTextWriter writer) { // First, generate all partial property implementations at the top of the partial type declaration diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs index 0430b410..2ebcfa07 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -45,10 +45,6 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato token.ThrowIfCancellationRequested(); - bool isOldPropertyValueDirectlyReferenced = Execute.IsOldPropertyValueDirectlyReferenced(propertySymbol); - - token.ThrowIfCancellationRequested(); - CanvasEffectInvalidationType invalidationType = Execute.GetCanvasEffectInvalidationType(context.Attributes[0]); token.ThrowIfCancellationRequested(); @@ -67,7 +63,6 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato Hierarchy: hierarchyInfo, PropertyName: propertySymbol.Name, TypeNameWithNullabilityAnnotations: typeNameWithNullabilityAnnotations, - IsOldPropertyValueDirectlyReferenced: isOldPropertyValueDirectlyReferenced, IsReferenceTypeOrUnconstraindTypeParameter: isReferenceTypeOrUnconstraindTypeParameter, InvalidationType: invalidationType); }) diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs index 7deb91a6..e4aed430 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs @@ -8,13 +8,11 @@ namespace ComputeSharp.D2D1.WinUI.SourceGenerators.Models; /// The hierarchy info for the shader type. /// The type name for the generated property, including nullability annotations. /// The generated property name. -/// Whether the old property value is being directly referenced. /// Indicates whether the property is of a reference type or an unconstrained type parameter. /// The invalidation type to request. internal sealed record CanvasEffectPropertyInfo( HierarchyInfo Hierarchy, string PropertyName, string TypeNameWithNullabilityAnnotations, - bool IsOldPropertyValueDirectlyReferenced, bool IsReferenceTypeOrUnconstraindTypeParameter, CanvasEffectInvalidationType InvalidationType); From d37001d45d3734881aac7f4a130a920a29759abd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 8 Jun 2024 18:57:52 -0700 Subject: [PATCH 15/46] Add 'InvalidGeneratedCanvasEffectPropertyAnalyzer' --- .../AnalyzerReleases.Shipped.md | 1 + ...vasEffectPropertyContainingTypeAnalyzer.cs | 58 +++++++++++++++++++ .../Diagnostics/DiagnosticDescriptors.cs | 25 ++++++++ .../Extensions/ITypeSymbolExtensions.cs | 23 ++++++++ 4 files changed, 107 insertions(+) create mode 100644 src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs create mode 100644 src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md index 85c2ce90..c73b8c05 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md @@ -7,3 +7,4 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- +CMPSD2DWINUI0001 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs new file mode 100644 index 00000000..f002420b --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs @@ -0,0 +1,58 @@ +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.WinUI.SourceGenerators; + +/// +/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] is in an invalid type. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = [InvalidGeneratedCanvasEffectPropertyContainingType]; + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static context => + { + // Get the [GeneratedCanvasEffectProperty] and CanvasEffect symbols + if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute") is not { } generatedCanvasEffectPropertyAttributeSymbol || + context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.CanvasEffect") is not { } canvasEffectSymbol) + { + return; + } + + context.RegisterSymbolAction(context => + { + // Validate that we have a valid containing type + if (context.Symbol is not IPropertySymbol { ContainingType: { } containingTypeSymbol }) + { + return; + } + + // If the property is not using [GeneratedCanvasEffectProperty], there's nothing to do + if (!context.Symbol.TryGetAttributeWithType(generatedCanvasEffectPropertyAttributeSymbol, out AttributeData? generatedCanvasEffectPropertyAttribute)) + { + return; + } + + // Issue a diagnostic if the type doesn't derive from CanvasEffect + if (!containingTypeSymbol.InheritsFromType(canvasEffectSymbol)) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidGeneratedCanvasEffectPropertyContainingType, + generatedCanvasEffectPropertyAttribute.GetLocation(), + context.Symbol)); + } + }, SymbolKind.Property); + }); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs new file mode 100644 index 00000000..b8a841b0 --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -0,0 +1,25 @@ +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1.WinUI.SourceGenerators; + +/// +/// A container for all instances for errors reported by analyzers in this project. +/// +internal static class DiagnosticDescriptors +{ + /// + /// Gets a for an invalid CanvasEffect property. + /// + /// Format: "The property "{0}" is not in a type that derives from CanvasEffect ([GeneratedCanvasEffectProperty] must be used in effect types that extend CanvasEffect)". + /// + /// + public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyContainingType = new( + id: "CMPSD2DWINUI0001", + title: "Invalid generated CanvasEffect property containing type", + messageFormat: """The property "{0}" is not in a type that derives from CanvasEffect ([GeneratedCanvasEffectProperty] must be used in effect types that extend CanvasEffect)""", + category: "ComputeSharp.D2D1.WinUI.Effects", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A property using [GeneratedCanvasEffectProperty] is in a type that does not derive from CanvasEffect ([GeneratedCanvasEffectProperty] must be used in effect types that extend CanvasEffect).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Extensions/ITypeSymbolExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/ITypeSymbolExtensions.cs index 5cb39bd5..687fabdc 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/ITypeSymbolExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/ITypeSymbolExtensions.cs @@ -67,6 +67,29 @@ internal static class ITypeSymbolExtensions return false; } + /// + /// Checks whether or not a given inherits from a specified type. + /// + /// The target instance to check. + /// The instane to check for inheritance from. + /// Whether or not inherits from . + public static bool InheritsFromType(this ITypeSymbol typeSymbol, ITypeSymbol baseTypeSymbol) + { + INamedTypeSymbol? currentBaseTypeSymbol = typeSymbol.BaseType; + + while (currentBaseTypeSymbol is not null) + { + if (SymbolEqualityComparer.Default.Equals(currentBaseTypeSymbol, baseTypeSymbol)) + { + return true; + } + + currentBaseTypeSymbol = currentBaseTypeSymbol.BaseType; + } + + return false; + } + /// /// Checks whether or not a given implements an interface of a specified type. /// From d194620473a17e7500a917873d5b22bf508fef62 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 8 Jun 2024 19:09:21 -0700 Subject: [PATCH 16/46] Add 'ComputeSharp.D2D1.WinUI.Tests.SourceGenerators' --- ComputeSharp.sln | 11 ++++++ ...p.D2D1.WinUI.Tests.SourceGenerators.csproj | 36 +++++++++++++++++++ ...lyzerWithLanguageVersionTest{TAnalyzer}.cs | 10 ++++-- .../CSharpGeneratorTest{TGenerator}.cs | 10 ++++-- 4 files changed, 63 insertions(+), 4 deletions(-) create mode 100644 tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 91ef1788..bd3ed8d0 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -180,6 +180,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.SwapChain.D2D1 EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.D2D1.WinUI.SourceGenerators", "src\ComputeSharp.D2D1.WinUI.SourceGenerators\ComputeSharp.D2D1.WinUI.SourceGenerators.csproj", "{FEBEC83A-FE70-4D4B-9B00-76DB31E75F17}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.D2D1.WinUI.Tests.SourceGenerators", "tests\ComputeSharp.D2D1.WinUI.Tests.SourceGenerators\ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj", "{916331A5-1EA6-41D7-B199-2E50C513EFDE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 @@ -512,6 +514,14 @@ Global {FEBEC83A-FE70-4D4B-9B00-76DB31E75F17}.Release|ARM64.Build.0 = Release|Any CPU {FEBEC83A-FE70-4D4B-9B00-76DB31E75F17}.Release|x64.ActiveCfg = Release|Any CPU {FEBEC83A-FE70-4D4B-9B00-76DB31E75F17}.Release|x64.Build.0 = Release|Any CPU + {916331A5-1EA6-41D7-B199-2E50C513EFDE}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {916331A5-1EA6-41D7-B199-2E50C513EFDE}.Debug|ARM64.Build.0 = Debug|ARM64 + {916331A5-1EA6-41D7-B199-2E50C513EFDE}.Debug|x64.ActiveCfg = Debug|x64 + {916331A5-1EA6-41D7-B199-2E50C513EFDE}.Debug|x64.Build.0 = Debug|x64 + {916331A5-1EA6-41D7-B199-2E50C513EFDE}.Release|ARM64.ActiveCfg = Release|ARM64 + {916331A5-1EA6-41D7-B199-2E50C513EFDE}.Release|ARM64.Build.0 = Release|ARM64 + {916331A5-1EA6-41D7-B199-2E50C513EFDE}.Release|x64.ActiveCfg = Release|x64 + {916331A5-1EA6-41D7-B199-2E50C513EFDE}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -552,6 +562,7 @@ Global {1A3E20B3-F711-41C0-82EA-3B53A575955C} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} {551EF4FB-F34F-412A-B3E6-E345797560ED} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} {9FBE070E-A210-4CEF-9F04-61C2B269C600} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} + {916331A5-1EA6-41D7-B199-2E50C513EFDE} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC} diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj new file mode 100644 index 00000000..034fc6d3 --- /dev/null +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj @@ -0,0 +1,36 @@ + + + net8.0-windows10.0.22621.0 + 10.0.17763.0 + x64;ARM64 + win-x64;win-arm64 + + https://api.nuget.org/v3/index.json; + https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json; + + $(DefineConstants);D2D1_WINUI_TESTS + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpAnalyzerWithLanguageVersionTest{TAnalyzer}.cs b/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpAnalyzerWithLanguageVersionTest{TAnalyzer}.cs index 7298e776..11cfc23f 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpAnalyzerWithLanguageVersionTest{TAnalyzer}.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpAnalyzerWithLanguageVersionTest{TAnalyzer}.cs @@ -1,5 +1,8 @@ extern alias Core; -#if D2D1_TESTS +#if D2D1_TESTS || D2D1_WINUI_TESTS +#if D2D1_WINUI_TESTS +extern alias D2D1_WinUI; +#endif extern alias D2D1; #else extern alias D3D12; @@ -68,7 +71,10 @@ internal sealed class CSharpAnalyzerWithLanguageVersionTest : CSharpA test.TestState.ReferenceAssemblies = ReferenceAssemblies.Net.Net80; test.TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Hlsl).Assembly.Location)); -#if D2D1_TESTS +#if D2D1_TESTS || D2D1_WINUI_TESTS +#if D2D1_WINUI_TESTS + test.TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(D2D1_WinUI::ComputeSharp.D2D1.WinUI.CanvasEffect).Assembly.Location)); +#endif test.TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location)); #else test.TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(D3D12::ComputeSharp.IComputeShader).Assembly.Location)); diff --git a/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs b/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs index 739f5110..463ac95e 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs @@ -1,6 +1,9 @@ extern alias Core; -#if D2D1_TESTS +#if D2D1_TESTS || D2D1_WINUI_TESTS +#if D2D1_WINUI_TESTS +extern alias D2D1_WinUI; +#endif extern alias D2D1; #else extern alias D3D12; @@ -176,7 +179,10 @@ internal static class CSharpGeneratorTest [ .. Net80.References.All, MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Hlsl).Assembly.Location), -#if D2D1_TESTS +#if D2D1_TESTS || D2D1_WINUI_TESTS +#if D2D1_WINUI_TESTS + MetadataReference.CreateFromFile(typeof(D2D1_WinUI::ComputeSharp.D2D1.WinUI.CanvasEffect).Assembly.Location), +#endif MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location) #else MetadataReference.CreateFromFile(typeof(D3D12::ComputeSharp.IComputeShader).Assembly.Location) From abac84b15de7441492e9e658bda6aa26bbb8e628 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 8 Jun 2024 19:18:52 -0700 Subject: [PATCH 17/46] Add unit test for invalid containing type analyzer --- ...CanvasEffectPropertyGenerator_Analyzers.cs | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs new file mode 100644 index 00000000..539d1d96 --- /dev/null +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs @@ -0,0 +1,42 @@ +using System.Threading.Tasks; +using ComputeSharp.D2D1.WinUI.SourceGenerators; +using ComputeSharp.Tests.SourceGenerators.Helpers; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.D2D1.WinUI.Tests.SourceGenerators; + +[TestClass] +public class Test_CanvasEffectPropertyGenerator_Analyzers +{ + [TestMethod] + public async Task InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer_NoBaseType_Warns() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + public class MyEffect + { + [{|CMPSD2DWINUI0001:GeneratedCanvasEffectProperty|}] + public int Number { get; set; } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer_CorrectBaseType_DoesNotWarn() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + public abstract class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public int Number { get; set; } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } +} \ No newline at end of file From cc6c7c26078423dea6976649c9b940235da18880 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 8 Jun 2024 23:13:15 -0700 Subject: [PATCH 18/46] Add 'AccessibilityExtensions' type --- .../ComputeSharp.SourceGeneration.projitems | 1 + .../Extensions/AccessibilityExtensions.cs | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 src/ComputeSharp.SourceGeneration/Extensions/AccessibilityExtensions.cs diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index 4084a568..bab3f258 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -9,6 +9,7 @@ ComputeSharp.SourceGeneration + diff --git a/src/ComputeSharp.SourceGeneration/Extensions/AccessibilityExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/AccessibilityExtensions.cs new file mode 100644 index 00000000..a5e2e349 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Extensions/AccessibilityExtensions.cs @@ -0,0 +1,28 @@ +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGeneration.Extensions; + +/// +/// Extension methods for the type. +/// +internal static class AccessibilityExtensions +{ + /// + /// Gets the expression for a given value. + /// + /// The input value. + /// The expression for . + public static string GetExpression(this Accessibility accessibility) + { + return accessibility switch + { + Accessibility.Private => "private", + Accessibility.ProtectedAndInternal => "private protected", + Accessibility.Protected => "protected", + Accessibility.Internal => "internal", + Accessibility.ProtectedOrInternal => "protected internal", + Accessibility.Public => "public", + _ => "" + }; + } +} \ No newline at end of file From 269bc77dab92cb3889d365add442c0b1bacffae3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 8 Jun 2024 23:13:41 -0700 Subject: [PATCH 19/46] Update generator to track accessibility --- .../CanvasEffectPropertyGenerator.Execute.cs | 109 +++++++++++++++--- .../CanvasEffectPropertyGenerator.cs | 17 +++ .../Models/CanvasEffectPropertyInfo.cs | 9 +- 3 files changed, 116 insertions(+), 19 deletions(-) diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs index 878468cf..6afb2900 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs @@ -41,6 +41,60 @@ partial class CanvasEffectPropertyGenerator return node.Parent?.IsTypeDeclarationWithOrPotentiallyWithBaseTypes() == true; } + /// + /// Tries to get the accessibility of the property and accessors, if possible. + /// + /// The input node. + /// The input instance. + /// The accessibility of the property, if available. + /// The accessibility of the accessor, if available. + /// The accessibility of the accessor, if available. + /// Whether the property was valid and the accessibilities could be retrieved. + public static bool TryGetAccessibilityModifiers( + PropertyDeclarationSyntax node, + IPropertySymbol symbol, + out Accessibility declaredAccessibility, + out Accessibility getterAccessibility, + out Accessibility setterAccessibility) + { + declaredAccessibility = Accessibility.NotApplicable; + getterAccessibility = Accessibility.NotApplicable; + setterAccessibility = Accessibility.NotApplicable; + + // Ensure that we have a getter and a setter, and that the setter is not init-only + if (symbol is not { GetMethod: { } getMethod, SetMethod: { IsInitOnly: false } setMethod }) + { + return false; + } + + // Track the property accessibility if explicitly set + if (node.Modifiers.Count > 0) + { + declaredAccessibility = symbol.DeclaredAccessibility; + } + + // Track the accessors accessibility, if explicitly set + foreach (AccessorDeclarationSyntax accessor in node.AccessorList?.Accessors ?? []) + { + if (accessor.Modifiers.Count == 0) + { + continue; + } + + switch (accessor.Kind()) + { + case SyntaxKind.GetAccessorDeclaration: + getterAccessibility = getMethod.DeclaredAccessibility; + break; + case SyntaxKind.SetAccessorDeclaration: + setterAccessibility = setMethod.DeclaredAccessibility; + break; + } + } + + return true; + } + /// /// Gets the invalidation type to use for the generated effect property. /// @@ -60,24 +114,51 @@ partial class CanvasEffectPropertyGenerator public static void WritePropertyDeclarations(EquatableArray properties, IndentedTextWriter writer) { + // Helper to get the nullable type name for the initial property value + static string GetOldValueTypeNameAsNullable(CanvasEffectPropertyInfo propertyInfo) + { + // Prepare the nullable type for the previous property value. This is needed because if the type is a reference + // type, the previous value might be null even if the property type is not nullable, as the first invocation would + // happen when the property is first set to some value that is not null (but the backing field would still be so). + // As a cheap way to check whether we need to add nullable, we can simply check whether the type name with nullability + // annotations ends with a '?'. If it doesn't and the type is a reference type, we add it. Otherwise, we keep it. + return propertyInfo.IsReferenceTypeOrUnconstraindTypeParameter switch + { + true when !propertyInfo.TypeNameWithNullabilityAnnotations.EndsWith("?") + => $"{propertyInfo.TypeNameWithNullabilityAnnotations}?", + _ => propertyInfo.TypeNameWithNullabilityAnnotations + }; + } + + // Helper to get the accessibility with a trailing space + static string GetExpressionWithTrailingSpace(Accessibility accessibility) + { + return accessibility.GetExpression() switch + { + { Length: > 0 } expression => expression + " ", + _ => "" + }; + } + // First, generate all partial property implementations at the top of the partial type declaration foreach (CanvasEffectPropertyInfo propertyInfo in properties) { - writer.WriteLine(skipIfPresent: true); + string oldValueTypeNameAsNullable = GetOldValueTypeNameAsNullable(propertyInfo); + writer.WriteLine("/// "); writer.WriteGeneratedAttributes(GeneratorName); writer.WriteLine($$""" - public partial {{propertyInfo.TypeNameWithNullabilityAnnotations}} {{propertyInfo.PropertyName}} + {{GetExpressionWithTrailingSpace(propertyInfo.DeclaredAccessibility)}}partial {{propertyInfo.TypeNameWithNullabilityAnnotations}} {{propertyInfo.PropertyName}} { - get => field; - set + {{GetExpressionWithTrailingSpace(propertyInfo.GetterAccessibility)}}get => field; + {{GetExpressionWithTrailingSpace(propertyInfo.SetterAccessibility)}}set { - if (global::System.Collections.Generic.EqualityComparer<{{propertyInfo.TypeNameWithNullabilityAnnotations}}>.Default.Equals(field, value)) + if (global::System.Collections.Generic.EqualityComparer<{{oldValueTypeNameAsNullable}}>.Default.Equals(field, value)) { return; } - int oldValue = field; + {{oldValueTypeNameAsNullable}} oldValue = field; On{{propertyInfo.PropertyName}}Changing(value); On{{propertyInfo.PropertyName}}Changing(oldValue, value); @@ -91,12 +172,14 @@ partial class CanvasEffectPropertyGenerator } } """, isMultiline: true); + writer.WriteLine(); } + // Next, emit all partial method declarations at the bottom of the file foreach (CanvasEffectPropertyInfo propertyInfo in properties) { // OnChanging, only with new value - writer.WriteLine(); + writer.WriteLine(skipIfPresent: true); writer.WriteLine($""" /// Executes the logic for when is changing. /// The new property value being set. @@ -105,17 +188,7 @@ partial class CanvasEffectPropertyGenerator writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false); writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changing({propertyInfo.TypeNameWithNullabilityAnnotations} newValue);"); - // Prepare the nullable type for the previous property value. This is needed because if the type is a reference - // type, the previous value might be null even if the property type is not nullable, as the first invocation would - // happen when the property is first set to some value that is not null (but the backing field would still be so). - // As a cheap way to check whether we need to add nullable, we can simply check whether the type name with nullability - // annotations ends with a '?'. If it doesn't and the type is a reference type, we add it. Otherwise, we keep it. - string oldValueTypeNameAsNullable = propertyInfo.IsReferenceTypeOrUnconstraindTypeParameter switch - { - true when !propertyInfo.TypeNameWithNullabilityAnnotations.EndsWith("?") - => $"{propertyInfo.TypeNameWithNullabilityAnnotations}?", - _ => propertyInfo.TypeNameWithNullabilityAnnotations - }; + string oldValueTypeNameAsNullable = GetOldValueTypeNameAsNullable(propertyInfo); // OnChanging, with both values writer.WriteLine(); diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs index 2ebcfa07..90cb20b3 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -3,6 +3,7 @@ using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; namespace ComputeSharp.D2D1.WinUI.SourceGenerators; @@ -41,6 +42,19 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato token.ThrowIfCancellationRequested(); + // Get the accessibility values, if the property is valid + if (!Execute.TryGetAccessibilityModifiers( + node: (PropertyDeclarationSyntax)context.TargetNode, + symbol: propertySymbol, + out Accessibility declaredAccessibility, + out Accessibility getterAccessibility, + out Accessibility setterAccessibility)) + { + return default; + } + + token.ThrowIfCancellationRequested(); + string typeNameWithNullabilityAnnotations = propertySymbol.Type.GetFullyQualifiedNameWithNullabilityAnnotations(); token.ThrowIfCancellationRequested(); @@ -62,6 +76,9 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato return new CanvasEffectPropertyInfo( Hierarchy: hierarchyInfo, PropertyName: propertySymbol.Name, + DeclaredAccessibility: declaredAccessibility, + GetterAccessibility: getterAccessibility, + SetterAccessibility: setterAccessibility, TypeNameWithNullabilityAnnotations: typeNameWithNullabilityAnnotations, IsReferenceTypeOrUnconstraindTypeParameter: isReferenceTypeOrUnconstraindTypeParameter, InvalidationType: invalidationType); diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs index e4aed430..a49fb448 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs @@ -1,4 +1,5 @@ using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; namespace ComputeSharp.D2D1.WinUI.SourceGenerators.Models; @@ -6,13 +7,19 @@ namespace ComputeSharp.D2D1.WinUI.SourceGenerators.Models; /// A model representing a generated canvas effect property. /// /// The hierarchy info for the shader type. -/// The type name for the generated property, including nullability annotations. /// The generated property name. +/// The accessibility of the property, if available. +/// The accessibility of the accessor, if available. +/// The accessibility of the accessor, if available. +/// The type name for the generated property, including nullability annotations. /// Indicates whether the property is of a reference type or an unconstrained type parameter. /// The invalidation type to request. internal sealed record CanvasEffectPropertyInfo( HierarchyInfo Hierarchy, string PropertyName, + Accessibility DeclaredAccessibility, + Accessibility GetterAccessibility, + Accessibility SetterAccessibility, string TypeNameWithNullabilityAnnotations, bool IsReferenceTypeOrUnconstraindTypeParameter, CanvasEffectInvalidationType InvalidationType); From 2c2fea61c2333bdff6d6d40a18c44fb1c1c32818 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 8 Jun 2024 23:13:49 -0700 Subject: [PATCH 20/46] Add 'Test_CanvasEffectPropertyGenerator' --- .../Test_CanvasEffectPropertyGenerator.cs | 500 ++++++++++++++++++ 1 file changed, 500 insertions(+) create mode 100644 tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs new file mode 100644 index 00000000..5b4b6bf7 --- /dev/null +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs @@ -0,0 +1,500 @@ +using System.Threading.Tasks; +using ComputeSharp.D2D1.WinUI.SourceGenerators; +using ComputeSharp.Tests.SourceGenerators.Helpers; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.D2D1.WinUI.Tests.SourceGenerators; + +[TestClass] +public class Test_CanvasEffectPropertyGenerator +{ + [TestMethod] + public async Task SingleProperty() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + namespace MyNamespace; + + public abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public int Number { get; set; } + } + """; + + const string result = """" + // + #pragma warning disable + + namespace MyNamespace + { + /// + partial class MyEffect + { + /// + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCode] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + public partial int Number + { + get => field; + set + { + if (global::System.Collections.Generic.EqualityComparer.Default.Equals(field, value)) + { + return; + } + + int oldValue = field; + + OnNumberChanging(value); + OnNumberChanging(oldValue, value); + + field = value; + + OnNumberChanged(value); + OnNumberChanged(oldValue, value); + + InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Update); + } + } + + /// Executes the logic for when is changing. + /// The new property value being set. + /// This method is invoked right before the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnNumberChanging(int newValue); + + /// Executes the logic for when is changing. + /// The previous property value that is being replaced. + /// The new property value being set. + /// This method is invoked right before the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnNumberChanging(int oldValue, int newValue); + + /// Executes the logic for when has just changed. + /// The new property value that has been set. + /// This method is invoked right after the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnNumberChanged(int newValue); + + /// Executes the logic for when has just changed. + /// The previous property value that has been replaced. + /// The new property value that has been set. + /// This method is invoked right after the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnNumberChanged(int oldValue, int newValue); + } + } + """"; + + await VerifyGeneratedDiagnosticsAsync(source, ("MyNamespace.MyEffect.g.cs", result)); + } + + [TestMethod] + public async Task SingleProperty_WithNullabilityAnnotations() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + namespace MyNamespace; + + public abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public object? Instance { get; set; } + } + """; + + const string result = """" + // + #pragma warning disable + + namespace MyNamespace + { + /// + partial class MyEffect + { + /// + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCode] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + public partial object? Instance + { + get => field; + set + { + if (global::System.Collections.Generic.EqualityComparer.Default.Equals(field, value)) + { + return; + } + + object? oldValue = field; + + OnInstanceChanging(value); + OnInstanceChanging(oldValue, value); + + field = value; + + OnInstanceChanged(value); + OnInstanceChanged(oldValue, value); + + InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Update); + } + } + + /// Executes the logic for when is changing. + /// The new property value being set. + /// This method is invoked right before the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnInstanceChanging(object? newValue); + + /// Executes the logic for when is changing. + /// The previous property value that is being replaced. + /// The new property value being set. + /// This method is invoked right before the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnInstanceChanging(object? oldValue, object? newValue); + + /// Executes the logic for when has just changed. + /// The new property value that has been set. + /// This method is invoked right after the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnInstanceChanged(object? newValue); + + /// Executes the logic for when has just changed. + /// The previous property value that has been replaced. + /// The new property value that has been set. + /// This method is invoked right after the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnInstanceChanged(object? oldValue, object? newValue); + } + } + """"; + + await VerifyGeneratedDiagnosticsAsync(source, ("MyNamespace.MyEffect.g.cs", result)); + } + + [TestMethod] + public async Task SingleProperty_WithNotNullableReferenceType() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + namespace MyNamespace; + + public abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public object Instance { get; set; } + } + """; + + const string result = """" + // + #pragma warning disable + + namespace MyNamespace + { + /// + partial class MyEffect + { + /// + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCode] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + public partial object Instance + { + get => field; + set + { + if (global::System.Collections.Generic.EqualityComparer.Default.Equals(field, value)) + { + return; + } + + object? oldValue = field; + + OnInstanceChanging(value); + OnInstanceChanging(oldValue, value); + + field = value; + + OnInstanceChanged(value); + OnInstanceChanged(oldValue, value); + + InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Update); + } + } + + /// Executes the logic for when is changing. + /// The new property value being set. + /// This method is invoked right before the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnInstanceChanging(object newValue); + + /// Executes the logic for when is changing. + /// The previous property value that is being replaced. + /// The new property value being set. + /// This method is invoked right before the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnInstanceChanging(object? oldValue, object newValue); + + /// Executes the logic for when has just changed. + /// The new property value that has been set. + /// This method is invoked right after the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnInstanceChanged(object newValue); + + /// Executes the logic for when has just changed. + /// The previous property value that has been replaced. + /// The new property value that has been set. + /// This method is invoked right after the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnInstanceChanged(object? oldValue, object newValue); + } + } + """"; + + await VerifyGeneratedDiagnosticsAsync(source, ("MyNamespace.MyEffect.g.cs", result)); + } + + [TestMethod] + public async Task SingleProperty_WithCustomAccessorVisibility() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + namespace MyNamespace; + + public abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public int Number { get; private set; } + } + """; + + const string result = """" + // + #pragma warning disable + + namespace MyNamespace + { + /// + partial class MyEffect + { + /// + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCode] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + public partial int Number + { + get => field; + private set + { + if (global::System.Collections.Generic.EqualityComparer.Default.Equals(field, value)) + { + return; + } + + int oldValue = field; + + OnNumberChanging(value); + OnNumberChanging(oldValue, value); + + field = value; + + OnNumberChanged(value); + OnNumberChanged(oldValue, value); + + InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Update); + } + } + + /// Executes the logic for when is changing. + /// The new property value being set. + /// This method is invoked right before the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnNumberChanging(int newValue); + + /// Executes the logic for when is changing. + /// The previous property value that is being replaced. + /// The new property value being set. + /// This method is invoked right before the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnNumberChanging(int oldValue, int newValue); + + /// Executes the logic for when has just changed. + /// The new property value that has been set. + /// This method is invoked right after the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnNumberChanged(int newValue); + + /// Executes the logic for when has just changed. + /// The previous property value that has been replaced. + /// The new property value that has been set. + /// This method is invoked right after the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnNumberChanged(int oldValue, int newValue); + } + } + """"; + + await VerifyGeneratedDiagnosticsAsync(source, ("MyNamespace.MyEffect.g.cs", result)); + } + + [TestMethod] + public async Task MultipleProperties() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + namespace MyNamespace; + + public abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public int X { get; set; } + + [GeneratedCanvasEffectProperty] + public int Y { get; set; } + } + """; + + const string result = """" + // + #pragma warning disable + + namespace MyNamespace + { + /// + partial class MyEffect + { + /// + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCode] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + public partial int X + { + get => field; + set + { + if (global::System.Collections.Generic.EqualityComparer.Default.Equals(field, value)) + { + return; + } + + int oldValue = field; + + OnXChanging(value); + OnXChanging(oldValue, value); + + field = value; + + OnXChanged(value); + OnXChanged(oldValue, value); + + InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Update); + } + } + + /// + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCode] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + public partial int Y + { + get => field; + set + { + if (global::System.Collections.Generic.EqualityComparer.Default.Equals(field, value)) + { + return; + } + + int oldValue = field; + + OnYChanging(value); + OnYChanging(oldValue, value); + + field = value; + + OnYChanged(value); + OnYChanged(oldValue, value); + + InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Update); + } + } + + /// Executes the logic for when is changing. + /// The new property value being set. + /// This method is invoked right before the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnXChanging(int newValue); + + /// Executes the logic for when is changing. + /// The previous property value that is being replaced. + /// The new property value being set. + /// This method is invoked right before the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnXChanging(int oldValue, int newValue); + + /// Executes the logic for when has just changed. + /// The new property value that has been set. + /// This method is invoked right after the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnXChanged(int newValue); + + /// Executes the logic for when has just changed. + /// The previous property value that has been replaced. + /// The new property value that has been set. + /// This method is invoked right after the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnXChanged(int oldValue, int newValue); + + /// Executes the logic for when is changing. + /// The new property value being set. + /// This method is invoked right before the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnYChanging(int newValue); + + /// Executes the logic for when is changing. + /// The previous property value that is being replaced. + /// The new property value being set. + /// This method is invoked right before the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnYChanging(int oldValue, int newValue); + + /// Executes the logic for when has just changed. + /// The new property value that has been set. + /// This method is invoked right after the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnYChanged(int newValue); + + /// Executes the logic for when has just changed. + /// The previous property value that has been replaced. + /// The new property value that has been set. + /// This method is invoked right after the value of is changed. + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + partial void OnYChanged(int oldValue, int newValue); + } + } + """"; + + await VerifyGeneratedDiagnosticsAsync(source, ("MyNamespace.MyEffect.g.cs", result)); + } + + /// + /// Verifies the output of a source generator. + /// + /// The input source to process. + /// The expected source to be generated. + /// The task for the operation. + private static async Task VerifyGeneratedDiagnosticsAsync(string source, (string Filename, string Source) result) + { + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + + CSharpGeneratorTest.VerifySources(source, result); + } +} \ No newline at end of file From 71b2af9895cc1935e515222e2288e0047c215b29 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 9 Jun 2024 09:40:10 -0700 Subject: [PATCH 21/46] Add 'InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer' --- .../AnalyzerReleases.Shipped.md | 1 + ...edCanvasEffectPropertyAccessorsAnalyzer.cs | 51 +++++++++++++++++++ .../Diagnostics/DiagnosticDescriptors.cs | 16 ++++++ 3 files changed, 68 insertions(+) create mode 100644 src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md index c73b8c05..6d5cfa5f 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md @@ -8,3 +8,4 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- CMPSD2DWINUI0001 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DWINUI0002 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs new file mode 100644 index 00000000..163601a6 --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs @@ -0,0 +1,51 @@ +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.WinUI.SourceGenerators; + +/// +/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] has invalid accessors. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = [InvalidGeneratedCanvasEffectPropertyAccessors]; + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static context => + { + // Get the [GeneratedCanvasEffectProperty] symbols + if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute") is not { } generatedCanvasEffectPropertyAttributeSymbol) + { + return; + } + + context.RegisterSymbolAction(context => + { + // Check that the property doesn't have 'get' and 'set' accessors + if (context.Symbol is IPropertySymbol { GetMethod: { }, SetMethod.IsInitOnly: false }) + { + return; + } + + // If the property is using [GeneratedCanvasEffectProperty], emit the diagnostic + if (context.Symbol.TryGetAttributeWithType(generatedCanvasEffectPropertyAttributeSymbol, out AttributeData? generatedCanvasEffectPropertyAttribute)) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidGeneratedCanvasEffectPropertyAccessors, + generatedCanvasEffectPropertyAttribute.GetLocation(), + context.Symbol)); + } + }, SymbolKind.Property); + }); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index b8a841b0..21218efb 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -22,4 +22,20 @@ internal static class DiagnosticDescriptors isEnabledByDefault: true, description: "A property using [GeneratedCanvasEffectProperty] is in a type that does not derive from CanvasEffect ([GeneratedCanvasEffectProperty] must be used in effect types that extend CanvasEffect).", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a CanvasEffect property with invalid accessors. + /// + /// Format: "The property "{0}" does not have a getter and a setter ([GeneratedCanvasEffectProperty] must be used on properties with get and set accessors)". + /// + /// + public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyAccessors = new( + id: "CMPSD2DWINUI0002", + title: "Invalid generated CanvasEffect property declaration", + messageFormat: """The property "{0}" does not have a getter and a setter ([GeneratedCanvasEffectProperty] must be used on properties with get and set accessors)""", + category: "ComputeSharp.D2D1.WinUI.Effects", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A property using [GeneratedCanvasEffectProperty] does not have a getter and a setter ([GeneratedCanvasEffectProperty] must be used on properties with get and set accessors).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } \ No newline at end of file From 251640f4b61a76358281c29669a2885c91a53f79 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 9 Jun 2024 09:42:15 -0700 Subject: [PATCH 22/46] Add unit tests for new analyzer --- .../Test_CanvasEffectPropertyGenerator.cs | 1 + ...CanvasEffectPropertyGenerator_Analyzers.cs | 24 +++++++++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs index 5b4b6bf7..a14f1f7f 100644 --- a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs @@ -494,6 +494,7 @@ public class Test_CanvasEffectPropertyGenerator private static async Task VerifyGeneratedDiagnosticsAsync(string source, (string Filename, string Source) result) { await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); CSharpGeneratorTest.VerifySources(source, result); } diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs index 539d1d96..b37a091b 100644 --- a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs @@ -25,18 +25,34 @@ public class Test_CanvasEffectPropertyGenerator_Analyzers } [TestMethod] - public async Task InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer_CorrectBaseType_DoesNotWarn() + public async Task InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer_ReadOnlyProperty_Warns() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + public class MyEffect + { + [{|CMPSD2DWINUI0002:GeneratedCanvasEffectProperty|}] + public int Number { get; } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer_InitOnlyProperty_Warns() { const string source = """ using ComputeSharp.D2D1.WinUI; public abstract class MyEffect : CanvasEffect { - [GeneratedCanvasEffectProperty] - public int Number { get; set; } + [{|CMPSD2DWINUI0002:GeneratedCanvasEffectProperty|}] + public int Number { get; init; } } """; - await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); } } \ No newline at end of file From cc5bbd48c1f8452f45b9e9c4d55ea63a26d08359 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 9 Jun 2024 10:07:29 -0700 Subject: [PATCH 23/46] Add incrementality tests for new generator --- .../CanvasEffectPropertyGenerator.cs | 5 +- ...mputeSharp.SourceGeneration.Hlsl.projitems | 1 - .../ComputeSharp.SourceGeneration.projitems | 1 + .../Constants/WellKnownTrackingNames.cs | 0 .../Test_CanvasEffectPropertyGenerator.cs | 4 +- ...sEffectPropertyGenerator_Incrementality.cs | 116 ++++++++++++++++++ 6 files changed, 123 insertions(+), 4 deletions(-) rename src/{ComputeSharp.SourceGeneration.Hlsl => ComputeSharp.SourceGeneration}/Constants/WellKnownTrackingNames.cs (100%) create mode 100644 tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Incrementality.cs diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs index 90cb20b3..2af0f5a2 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -1,4 +1,5 @@ using ComputeSharp.D2D1.WinUI.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Constants; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; @@ -83,12 +84,14 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato IsReferenceTypeOrUnconstraindTypeParameter: isReferenceTypeOrUnconstraindTypeParameter, InvalidationType: invalidationType); }) + .WithTrackingName(WellKnownTrackingNames.Execute) .Where(static item => item is not null)!; // Split and group by containing type IncrementalValuesProvider<(HierarchyInfo Hierarchy, EquatableArray Properties)> groupedPropertyInfo = propertyInfo - .GroupBy(keySelector: static item => item.Hierarchy, elementSelector: static item => item); + .GroupBy(keySelector: static item => item.Hierarchy, elementSelector: static item => item) + .WithTrackingName(WellKnownTrackingNames.Output); // Generate the source files, if any context.RegisterSourceOutput(groupedPropertyInfo, static (context, item) => diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems index 253adccf..abd0cb56 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -9,7 +9,6 @@ ComputeSharp.SourceGeneration.Hlsl - diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index bab3f258..b68d6000 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -9,6 +9,7 @@ ComputeSharp.SourceGeneration + diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Constants/WellKnownTrackingNames.cs b/src/ComputeSharp.SourceGeneration/Constants/WellKnownTrackingNames.cs similarity index 100% rename from src/ComputeSharp.SourceGeneration.Hlsl/Constants/WellKnownTrackingNames.cs rename to src/ComputeSharp.SourceGeneration/Constants/WellKnownTrackingNames.cs diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs index a14f1f7f..e27f4a7a 100644 --- a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs @@ -357,7 +357,7 @@ public class Test_CanvasEffectPropertyGenerator [GeneratedCanvasEffectProperty] public int X { get; set; } - [GeneratedCanvasEffectProperty] + [GeneratedCanvasEffectProperty(CanvasEffectInvalidationType.Creation)] public int Y { get; set; } } """; @@ -423,7 +423,7 @@ public class Test_CanvasEffectPropertyGenerator OnYChanged(value); OnYChanged(oldValue, value); - InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Update); + InvalidateEffectGraph(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.Creation); } } diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Incrementality.cs b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Incrementality.cs new file mode 100644 index 00000000..33934ced --- /dev/null +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Incrementality.cs @@ -0,0 +1,116 @@ +using ComputeSharp.D2D1.WinUI.SourceGenerators; +using ComputeSharp.Tests.SourceGenerators.Helpers; +using Microsoft.CodeAnalysis; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.D2D1.WinUI.Tests.SourceGenerators; + +[TestClass] +public class Test_CanvasEffectPropertyGenerator_Incrementality +{ + [TestMethod] + public void ModifiedOptions_ModifiesOutput() + { + const string source = """" + using ComputeSharp.D2D1.WinUI; + + abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public int Number { get; set; } + } + """"; + + const string updatedSource = """" + using ComputeSharp.D2D1.WinUI; + + abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty(CanvasEffectInvalidationType.Creation)] + public int Number { get; set; } + } + """"; + + CSharpGeneratorTest.VerifyIncrementalSteps( + source, + updatedSource, + executeReason: IncrementalStepRunReason.Modified, + diagnosticsReason: null, + outputReason: IncrementalStepRunReason.Modified, + diagnosticsSourceReason: null, + sourceReason: IncrementalStepRunReason.Modified); + } + + [TestMethod] + public void AddedLeadingTrivia_DoesNotModifyOutput() + { + const string source = """" + using ComputeSharp.D2D1.WinUI; + + abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public int Number { get; set; } + } + """"; + + const string updatedSource = """" + using ComputeSharp.D2D1.WinUI; + + abstract partial class MyEffect : CanvasEffect + { + /// + /// This is some property. + /// + [GeneratedCanvasEffectProperty] + public int Number { get; set; } + } + """"; + + CSharpGeneratorTest.VerifyIncrementalSteps( + source, + updatedSource, + executeReason: IncrementalStepRunReason.Unchanged, + diagnosticsReason: null, + outputReason: IncrementalStepRunReason.Cached, + diagnosticsSourceReason: null, + sourceReason: IncrementalStepRunReason.Cached); + } + + [TestMethod] + public void AddedOtherMember_DoesNotModifyOutput() + { + const string source = """" + using ComputeSharp.D2D1.WinUI; + + abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public int Number { get; set; } + } + """"; + + const string updatedSource = """" + using ComputeSharp.D2D1.WinUI; + + abstract partial class MyEffect : CanvasEffect + { + public void Foo() + { + } + + [GeneratedCanvasEffectProperty] + public int Number { get; set; } + } + """"; + + CSharpGeneratorTest.VerifyIncrementalSteps( + source, + updatedSource, + executeReason: IncrementalStepRunReason.Unchanged, + diagnosticsReason: null, + outputReason: IncrementalStepRunReason.Cached, + diagnosticsSourceReason: null, + sourceReason: IncrementalStepRunReason.Cached); + } +} \ No newline at end of file From 17874acc2546c0674ba053037a81ef6d44b18030 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 10 Jun 2024 16:48:13 -0700 Subject: [PATCH 24/46] Add workaround for build failure due to MSBuild bug --- build/Directory.Build.targets | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/build/Directory.Build.targets b/build/Directory.Build.targets index 277272c1..0a467697 100644 --- a/build/Directory.Build.targets +++ b/build/Directory.Build.targets @@ -43,4 +43,16 @@ True + + + + false + \ No newline at end of file From 2869754fefb3f11e0b39dbea51e0a443e6672370 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 12 Jun 2024 00:07:56 -0700 Subject: [PATCH 25/46] Enable WinUI.SourceGenerators tests in CI --- .github/workflows/dotnet.yml | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 488d14e1..b3de1cbc 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -164,13 +164,24 @@ jobs: - name: Build ComputeSharp.D2D1.WinUI.Tests run: msbuild tests\ComputeSharp.D2D1.WinUI.Tests\ComputeSharp.D2D1.WinUI.Tests.csproj /restore -t:build /p:Configuration=Release /p:Platform=x64 - # Run the D2D1 WinAppSDK unit tests with VS Test again + # Run the D2D1 WinAppSDK unit tests with VS Test - name: Run ComputeSharp.D2D1.WinUI.Tests run: > $vs_path = vswhere -latest -products * -requires Microsoft.VisualStudio.Workload.ManagedDesktop -requiresAny -property installationPath; $vstest_path = join-path $vs_path 'Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe'; & $vstest_path /Platform:x64 tests\ComputeSharp.D2D1.WinUI.Tests\bin\x64\Release\net8.0-windows10.0.22621.0\win-x64\ComputeSharp.D2D1.WinUI.Tests.build.appxrecipe + # Build the D2D1 WinAppSDK source generators tests + - name: Build ComputeSharp.D2D1.WinUI.Tests.SourceGenerators + run: msbuild tests\ComputeSharp.D2D1.WinUI.Tests.SourceGenerators\ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj /restore -t:build /p:Configuration=Release /p:Platform=x64 + + # Run the D2D1 WinAppSDK source generators tests (same as above) + - name: Run ComputeSharp.D2D1.WinUI.Tests.SourceGenerators + run: > + $vs_path = vswhere -latest -products * -requires Microsoft.VisualStudio.Workload.ManagedDesktop -requiresAny -property installationPath; + $vstest_path = join-path $vs_path 'Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe'; + & $vstest_path /Platform:x64 tests\ComputeSharp.D2D1.WinUI.Tests.SourceGenerators\bin\x64\Release\net8.0-windows10.0.22621.0\ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.dll + # Run all the local samples to ensure they build and run with no errors run-samples: needs: [build-solution] From b86d8fb2fe689e163117176fc8849274f98115de Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 30 Jun 2024 15:49:04 -0700 Subject: [PATCH 26/46] Use preview Windows SDK in test project --- .../ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj index 034fc6d3..b4641a15 100644 --- a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj @@ -2,6 +2,7 @@ net8.0-windows10.0.22621.0 10.0.17763.0 + 10.0.22621.35-preview x64;ARM64 win-x64;win-arm64 From 39e53ca9d0cdc8a5a153757d0e670970952cb8ca Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 30 Jun 2024 15:52:02 -0700 Subject: [PATCH 27/46] Replace legacy project GUIDs --- ComputeSharp.sln | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ComputeSharp.sln b/ComputeSharp.sln index bd3ed8d0..e295949f 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -180,7 +180,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.SwapChain.D2D1 EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.D2D1.WinUI.SourceGenerators", "src\ComputeSharp.D2D1.WinUI.SourceGenerators\ComputeSharp.D2D1.WinUI.SourceGenerators.csproj", "{FEBEC83A-FE70-4D4B-9B00-76DB31E75F17}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.D2D1.WinUI.Tests.SourceGenerators", "tests\ComputeSharp.D2D1.WinUI.Tests.SourceGenerators\ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj", "{916331A5-1EA6-41D7-B199-2E50C513EFDE}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1.WinUI.Tests.SourceGenerators", "tests\ComputeSharp.D2D1.WinUI.Tests.SourceGenerators\ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj", "{916331A5-1EA6-41D7-B199-2E50C513EFDE}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution From 5bf06260100426fd8dfff21251bea62af9256d84 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 14 Aug 2024 00:24:58 -0700 Subject: [PATCH 28/46] Update NuGet packages in new test project --- ...Sharp.D2D1.WinUI.Tests.SourceGenerators.csproj | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj index b4641a15..bbc582be 100644 --- a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj @@ -2,24 +2,19 @@ net8.0-windows10.0.22621.0 10.0.17763.0 - 10.0.22621.35-preview + 10.0.22621.39 x64;ARM64 win-x64;win-arm64 - - https://api.nuget.org/v3/index.json; - https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json; - $(DefineConstants);D2D1_WINUI_TESTS - - - - - + + + + From 012d1b9d10e216bf0d63678979a2bd862ca5c277 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 15 Aug 2024 19:13:51 -0700 Subject: [PATCH 29/46] Update Roslyn dependency to 4.11 --- .../ComputeSharp.D2D1.WinUI.SourceGenerators.csproj | 2 +- src/ComputeSharp.D2D1.WinUI/ComputeSharp.D2D1.WinUI.targets | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj index 8003250d..824cc76a 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj @@ -11,7 +11,7 @@ - + diff --git a/src/ComputeSharp.D2D1.WinUI/ComputeSharp.D2D1.WinUI.targets b/src/ComputeSharp.D2D1.WinUI/ComputeSharp.D2D1.WinUI.targets index 7aaabd02..e178811f 100644 --- a/src/ComputeSharp.D2D1.WinUI/ComputeSharp.D2D1.WinUI.targets +++ b/src/ComputeSharp.D2D1.WinUI/ComputeSharp.D2D1.WinUI.targets @@ -7,7 +7,7 @@ - + @(ComputeSharpD2D1WinUICurrentCompilerAssemblyIdentity->'%(Version)') - true + true - + From bbb0134494782cf16edad601a3af9fcbd4e574c3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 15 Aug 2024 19:19:09 -0700 Subject: [PATCH 30/46] Check partial property syntax in generator --- .../CanvasEffectPropertyGenerator.Execute.cs | 8 +++++++- .../CanvasEffectPropertyGenerator.cs | 6 ++++++ .../ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj | 4 ++-- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs index 6afb2900..bcc229e6 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs @@ -25,7 +25,13 @@ partial class CanvasEffectPropertyGenerator public static bool IsCandidatePropertyDeclaration(SyntaxNode node, CancellationToken token) { // The node must be a property declaration with two accessors - if (node is not PropertyDeclarationSyntax { AccessorList.Accessors: { Count: 2 } accessors }) + if (node is not PropertyDeclarationSyntax { AccessorList.Accessors: { Count: 2 } accessors } property) + { + return false; + } + + // The property must be partial (we'll check that it's a declaration from its symbol) + if (!property.Modifiers.Any(SyntaxKind.PartialKeyword)) { return false; } diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs index 2af0f5a2..18b41a58 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -35,6 +35,12 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato return default; } + // Ensure that the property declaration is a partial definition with no implementation + if (propertySymbol is not { IsPartialDefinition: true, PartialImplementationPart: null }) + { + return default; + } + // Ensure that the containing type derives from CanvasEffect if (!typeSymbol.InheritsFromFullyQualifiedMetadataName("ComputeSharp.D2D1.WinUI.CanvasEffect")) { diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj index bbc582be..eff9423e 100644 --- a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj @@ -9,13 +9,13 @@ - + - + From d8f9b35c9edf171704014faa3198f37f05fd555b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 18 Aug 2024 19:05:51 -0700 Subject: [PATCH 31/46] Update unit tests to use partial properties --- .../Test_CanvasEffectPropertyGenerator.cs | 43 +++++++++---------- ...CanvasEffectPropertyGenerator_Analyzers.cs | 19 ++++---- ...sEffectPropertyGenerator_Incrementality.cs | 12 +++--- .../CSharpGeneratorTest{TGenerator}.cs | 18 +++++--- 4 files changed, 48 insertions(+), 44 deletions(-) diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs index e27f4a7a..e637788a 100644 --- a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs @@ -1,6 +1,6 @@ -using System.Threading.Tasks; using ComputeSharp.D2D1.WinUI.SourceGenerators; using ComputeSharp.Tests.SourceGenerators.Helpers; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.D2D1.WinUI.Tests.SourceGenerators; @@ -9,7 +9,7 @@ namespace ComputeSharp.D2D1.WinUI.Tests.SourceGenerators; public class Test_CanvasEffectPropertyGenerator { [TestMethod] - public async Task SingleProperty() + public void SingleProperty() { const string source = """ using ComputeSharp.D2D1.WinUI; @@ -19,7 +19,7 @@ public class Test_CanvasEffectPropertyGenerator public abstract partial class MyEffect : CanvasEffect { [GeneratedCanvasEffectProperty] - public int Number { get; set; } + public partial int Number { get; set; } } """; @@ -89,11 +89,11 @@ public class Test_CanvasEffectPropertyGenerator } """"; - await VerifyGeneratedDiagnosticsAsync(source, ("MyNamespace.MyEffect.g.cs", result)); + VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result)); } [TestMethod] - public async Task SingleProperty_WithNullabilityAnnotations() + public void SingleProperty_WithNullabilityAnnotations() { const string source = """ using ComputeSharp.D2D1.WinUI; @@ -103,7 +103,7 @@ public class Test_CanvasEffectPropertyGenerator public abstract partial class MyEffect : CanvasEffect { [GeneratedCanvasEffectProperty] - public object? Instance { get; set; } + public partial object? Instance { get; set; } } """; @@ -173,11 +173,11 @@ public class Test_CanvasEffectPropertyGenerator } """"; - await VerifyGeneratedDiagnosticsAsync(source, ("MyNamespace.MyEffect.g.cs", result)); + VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result)); } [TestMethod] - public async Task SingleProperty_WithNotNullableReferenceType() + public void SingleProperty_WithNotNullableReferenceType() { const string source = """ using ComputeSharp.D2D1.WinUI; @@ -187,7 +187,7 @@ public class Test_CanvasEffectPropertyGenerator public abstract partial class MyEffect : CanvasEffect { [GeneratedCanvasEffectProperty] - public object Instance { get; set; } + public partial object Instance { get; set; } } """; @@ -257,11 +257,11 @@ public class Test_CanvasEffectPropertyGenerator } """"; - await VerifyGeneratedDiagnosticsAsync(source, ("MyNamespace.MyEffect.g.cs", result)); + VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result)); } [TestMethod] - public async Task SingleProperty_WithCustomAccessorVisibility() + public void SingleProperty_WithCustomAccessorVisibility() { const string source = """ using ComputeSharp.D2D1.WinUI; @@ -271,7 +271,7 @@ public class Test_CanvasEffectPropertyGenerator public abstract partial class MyEffect : CanvasEffect { [GeneratedCanvasEffectProperty] - public int Number { get; private set; } + public partial int Number { get; private set; } } """; @@ -341,11 +341,11 @@ public class Test_CanvasEffectPropertyGenerator } """"; - await VerifyGeneratedDiagnosticsAsync(source, ("MyNamespace.MyEffect.g.cs", result)); + VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result)); } [TestMethod] - public async Task MultipleProperties() + public void MultipleProperties() { const string source = """ using ComputeSharp.D2D1.WinUI; @@ -355,10 +355,10 @@ public class Test_CanvasEffectPropertyGenerator public abstract partial class MyEffect : CanvasEffect { [GeneratedCanvasEffectProperty] - public int X { get; set; } + public partial int X { get; set; } [GeneratedCanvasEffectProperty(CanvasEffectInvalidationType.Creation)] - public int Y { get; set; } + public partial int Y { get; set; } } """; @@ -482,7 +482,7 @@ public class Test_CanvasEffectPropertyGenerator } """"; - await VerifyGeneratedDiagnosticsAsync(source, ("MyNamespace.MyEffect.g.cs", result)); + VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result)); } /// @@ -491,11 +491,10 @@ public class Test_CanvasEffectPropertyGenerator /// The input source to process. /// The expected source to be generated. /// The task for the operation. - private static async Task VerifyGeneratedDiagnosticsAsync(string source, (string Filename, string Source) result) + private static void VerifyGeneratedDiagnostics(string source, (string Filename, string Source) result) { - await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); - await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); - - CSharpGeneratorTest.VerifySources(source, result); + // We cannot run the analyzers on the input source, because they'd report unwanted dsiagnostics due to the + // partial properties missing an implementation part. For this generator, we just test analyzers individually. + CSharpGeneratorTest.VerifySources(source, result, languageVersion: LanguageVersion.Preview); } } \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs index b37a091b..b56cd23d 100644 --- a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs @@ -1,6 +1,7 @@ using System.Threading.Tasks; using ComputeSharp.D2D1.WinUI.SourceGenerators; using ComputeSharp.Tests.SourceGenerators.Helpers; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.D2D1.WinUI.Tests.SourceGenerators; @@ -14,14 +15,14 @@ public class Test_CanvasEffectPropertyGenerator_Analyzers const string source = """ using ComputeSharp.D2D1.WinUI; - public class MyEffect + public partial class MyEffect { [{|CMPSD2DWINUI0001:GeneratedCanvasEffectProperty|}] - public int Number { get; set; } + public partial int {|CS9248:Number|} { get; set; } } """; - await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); } [TestMethod] @@ -30,14 +31,14 @@ public class Test_CanvasEffectPropertyGenerator_Analyzers const string source = """ using ComputeSharp.D2D1.WinUI; - public class MyEffect + public partial class MyEffect { [{|CMPSD2DWINUI0002:GeneratedCanvasEffectProperty|}] - public int Number { get; } + public partial int {|CS9248:Number|} { get; } } """; - await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); } [TestMethod] @@ -46,13 +47,13 @@ public class Test_CanvasEffectPropertyGenerator_Analyzers const string source = """ using ComputeSharp.D2D1.WinUI; - public abstract class MyEffect : CanvasEffect + public abstract partial class MyEffect : CanvasEffect { [{|CMPSD2DWINUI0002:GeneratedCanvasEffectProperty|}] - public int Number { get; init; } + public partial int {|CS9248:Number|} { get; init; } } """; - await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); } } \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Incrementality.cs b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Incrementality.cs index 33934ced..ae987d10 100644 --- a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Incrementality.cs +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Incrementality.cs @@ -17,7 +17,7 @@ public class Test_CanvasEffectPropertyGenerator_Incrementality abstract partial class MyEffect : CanvasEffect { [GeneratedCanvasEffectProperty] - public int Number { get; set; } + public partial int Number { get; set; } } """"; @@ -27,7 +27,7 @@ public class Test_CanvasEffectPropertyGenerator_Incrementality abstract partial class MyEffect : CanvasEffect { [GeneratedCanvasEffectProperty(CanvasEffectInvalidationType.Creation)] - public int Number { get; set; } + public partial int Number { get; set; } } """"; @@ -50,7 +50,7 @@ public class Test_CanvasEffectPropertyGenerator_Incrementality abstract partial class MyEffect : CanvasEffect { [GeneratedCanvasEffectProperty] - public int Number { get; set; } + public partial int Number { get; set; } } """"; @@ -63,7 +63,7 @@ public class Test_CanvasEffectPropertyGenerator_Incrementality /// This is some property. /// [GeneratedCanvasEffectProperty] - public int Number { get; set; } + public partial int Number { get; set; } } """"; @@ -86,7 +86,7 @@ public class Test_CanvasEffectPropertyGenerator_Incrementality abstract partial class MyEffect : CanvasEffect { [GeneratedCanvasEffectProperty] - public int Number { get; set; } + public partial int Number { get; set; } } """"; @@ -100,7 +100,7 @@ public class Test_CanvasEffectPropertyGenerator_Incrementality } [GeneratedCanvasEffectProperty] - public int Number { get; set; } + public partial int Number { get; set; } } """"; diff --git a/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs b/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs index 463ac95e..7670c841 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs @@ -57,9 +57,10 @@ internal static class CSharpGeneratorTest /// /// The input source to process. /// The expected source to be generated. - public static void VerifySources(string source, (string Filename, string Source) result) + /// The language version to use to run the test. + public static void VerifySources(string source, (string Filename, string Source) result, LanguageVersion languageVersion = LanguageVersion.CSharp12) { - RunGenerator(source, out Compilation compilation, out ImmutableArray diagnostics); + RunGenerator(source, out Compilation compilation, out ImmutableArray diagnostics, languageVersion); // Ensure that no diagnostics were generated CollectionAssert.AreEquivalent(Array.Empty(), diagnostics); @@ -171,8 +172,9 @@ internal static class CSharpGeneratorTest /// Creates a compilation from a given source. /// /// The input source to process. + /// The language version to use to run the test. /// The resulting object. - private static CSharpCompilation CreateCompilation(string source) + private static CSharpCompilation CreateCompilation(string source, LanguageVersion languageVersion = LanguageVersion.CSharp12) { // Get all assembly references for the .NET TFM and ComputeSharp IEnumerable metadataReferences = @@ -189,10 +191,10 @@ internal static class CSharpGeneratorTest #endif ]; - // Parse the source text (C# 12) + // Parse the source text SyntaxTree sourceTree = CSharpSyntaxTree.ParseText( source, - CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); + CSharpParseOptions.Default.WithLanguageVersion(languageVersion)); // Create the original compilation return CSharpCompilation.Create( @@ -208,12 +210,14 @@ internal static class CSharpGeneratorTest /// The input source to process. /// /// + /// The language version to use to run the test. private static void RunGenerator( string source, out Compilation compilation, - out ImmutableArray diagnostics) + out ImmutableArray diagnostics, + LanguageVersion languageVersion = LanguageVersion.CSharp12) { - Compilation originalCompilation = CreateCompilation(source); + Compilation originalCompilation = CreateCompilation(source, languageVersion); // Create the generator driver with the D2D shader generator GeneratorDriver driver = CSharpGeneratorDriver.Create(new TGenerator()).WithUpdatedParseOptions(originalCompilation.SyntaxTrees.First().Options); From 0bb328f14b9a1ea56e3d918c17fa2d1352225227 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 18 Aug 2024 19:32:18 -0700 Subject: [PATCH 32/46] Add 'InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer' --- .../AnalyzerReleases.Shipped.md | 4 + .../CanvasEffectPropertyGenerator.cs | 6 ++ ...CanvasEffectPropertyDeclarationAnalyzer.cs | 90 +++++++++++++++++++ .../Diagnostics/DiagnosticDescriptors.cs | 66 +++++++++++++- 4 files changed, 165 insertions(+), 1 deletion(-) create mode 100644 src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md index 6d5cfa5f..3449845d 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md @@ -9,3 +9,7 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- CMPSD2DWINUI0001 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2DWINUI0002 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DWINUI0003 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DWINUI0004 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DWINUI0005 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DWINUI0006 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs index 18b41a58..a63a7152 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -41,6 +41,12 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato return default; } + // Also ignore all properties that have an invalid declaration + if (propertySymbol.IsStatic || propertySymbol.ReturnsByRef || propertySymbol.ReturnsByRefReadonly || propertySymbol.Type.IsRefLikeType) + { + return default; + } + // Ensure that the containing type derives from CanvasEffect if (!typeSymbol.InheritsFromFullyQualifiedMetadataName("ComputeSharp.D2D1.WinUI.CanvasEffect")) { diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs new file mode 100644 index 00000000..94482d0a --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs @@ -0,0 +1,90 @@ +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.WinUI.SourceGenerators; + +/// +/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] has invalid accessors. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = + [ + InvalidGeneratedCanvasEffectPropertyDeclarationIsStatic, + InvalidGeneratedCanvasEffectPropertyDeclarationIsNotIncompletePartialDefinition, + InvalidGeneratedCanvasEffectPropertyDeclarationReturnsByRef, + InvalidGeneratedCanvasEffectPropertyDeclarationReturnsRefLikeType + ]; + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static context => + { + // Get the [GeneratedCanvasEffectProperty] symbols + if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute") is not { } generatedCanvasEffectPropertyAttributeSymbol) + { + return; + } + + context.RegisterSymbolAction(context => + { + // Ensure that we have some target property to analyze + if (context.Symbol is not IPropertySymbol propertySymbol) + { + return; + } + + // If the property is not using [GeneratedCanvasEffectProperty], there's nothing to do + if (!context.Symbol.TryGetAttributeWithType(generatedCanvasEffectPropertyAttributeSymbol, out AttributeData? generatedCanvasEffectPropertyAttribute)) + { + return; + } + + // Emit an error if the property is static + if (propertySymbol.IsStatic) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidGeneratedCanvasEffectPropertyDeclarationIsStatic, + generatedCanvasEffectPropertyAttribute.GetLocation(), + context.Symbol)); + } + + // Emit an error if the property is not a partial definition with no implementation + if (propertySymbol is not { IsPartialDefinition: true, PartialImplementationPart: null }) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidGeneratedCanvasEffectPropertyDeclarationIsNotIncompletePartialDefinition, + generatedCanvasEffectPropertyAttribute.GetLocation(), + context.Symbol)); + } + + // Emit an error if the property returns a value by ref + if (propertySymbol.ReturnsByRef || propertySymbol.ReturnsByRefReadonly) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidGeneratedCanvasEffectPropertyDeclarationReturnsByRef, + generatedCanvasEffectPropertyAttribute.GetLocation(), + context.Symbol)); + } + + // Emit an error if the property type is a ref struct + if (propertySymbol.Type.IsRefLikeType) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidGeneratedCanvasEffectPropertyDeclarationReturnsRefLikeType, + generatedCanvasEffectPropertyAttribute.GetLocation(), + context.Symbol)); + } + }, SymbolKind.Property); + }); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 21218efb..05a7daa4 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -31,11 +31,75 @@ internal static class DiagnosticDescriptors /// public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyAccessors = new( id: "CMPSD2DWINUI0002", - title: "Invalid generated CanvasEffect property declaration", + title: "Invalid generated CanvasEffect property accessors", messageFormat: """The property "{0}" does not have a getter and a setter ([GeneratedCanvasEffectProperty] must be used on properties with get and set accessors)""", category: "ComputeSharp.D2D1.WinUI.Effects", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A property using [GeneratedCanvasEffectProperty] does not have a getter and a setter ([GeneratedCanvasEffectProperty] must be used on properties with get and set accessors).", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a static CanvasEffect property. + /// + /// Format: "The property "{0}" is static ([GeneratedCanvasEffectProperty] must be used on instance properties)". + /// + /// + public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationIsStatic = new( + id: "CMPSD2DWINUI0003", + title: "Invalid generated CanvasEffect property declaration (static member)", + messageFormat: """The property "{0}" is static ([GeneratedCanvasEffectProperty] must be used on instance properties)""", + category: "ComputeSharp.D2D1.WinUI.Effects", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A property using [GeneratedCanvasEffectProperty] cannot be static ([GeneratedCanvasEffectProperty] must be used on instance properties).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a CanvasEffect property with invalid accessors. + /// + /// Format: "The property "{0}" is not an incomplete partial definition ([GeneratedCanvasEffectProperty] must be used on partial property definitions with no implementation part)". + /// + /// + public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationIsNotIncompletePartialDefinition = new( + id: "CMPSD2DWINUI0004", + title: "Invalid generated CanvasEffect property declaration (not incomplete partial definition)", + messageFormat: """The property "{0}" is not an incomplete partial definition ([GeneratedCanvasEffectProperty] must be used on partial property definitions with no implementation part)""", + category: "ComputeSharp.D2D1.WinUI.Effects", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A property using [GeneratedCanvasEffectProperty] is either not partial, or a partial implementation part ([GeneratedCanvasEffectProperty] must be used on partial property definitions with no implementation par).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a CanvasEffect property with invalid accessors. + /// + /// Format: "The property "{0}" returns a value by reference ([GeneratedCanvasEffectProperty] must be used on properties returning a type by value)". + /// + /// + public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationReturnsByRef = new( + id: "CMPSD2DWINUI0005", + title: "Invalid generated CanvasEffect property declaration (returns byref)", + messageFormat: """The property "{0}" returns a value by reference ([GeneratedCanvasEffectProperty] must be used on properties returning a type by value)""", + category: "ComputeSharp.D2D1.WinUI.Effects", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A property using [GeneratedCanvasEffectProperty] returns a value by reference ([GeneratedCanvasEffectProperty] must be used on properties returning a type by value).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a CanvasEffect property with invalid accessors. + /// + /// Format: "The property "{0}" returns a ref struct value ([GeneratedCanvasEffectProperty] must be used on properties with a type that is not a ref struct)". + /// + /// + public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationReturnsRefLikeType = new( + id: "CMPSD2DWINUI0006", + title: "Invalid generated CanvasEffect property declaration (returns ref struct type)", + messageFormat: """The property "{0}" returns a ref struct value ([GeneratedCanvasEffectProperty] must be used on properties with a type that is not a ref struct)""", + category: "ComputeSharp.D2D1.WinUI.Effects", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A property using [GeneratedCanvasEffectProperty] has a ref struct type ([GeneratedCanvasEffectProperty] must be used on properties with a type that is not a ref struct).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } \ No newline at end of file From afe8e1d93a1e83a599c09b1ae9399c5a2c573bc3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 18 Aug 2024 19:47:11 -0700 Subject: [PATCH 33/46] Add unit tests for new analyzer diagnostics --- ...edCanvasEffectPropertyAccessorsAnalyzer.cs | 6 + ...vasEffectPropertyContainingTypeAnalyzer.cs | 4 +- ...CanvasEffectPropertyDeclarationAnalyzer.cs | 4 +- ...CanvasEffectPropertyGenerator_Analyzers.cs | 117 ++++++++++++++++++ 4 files changed, 127 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs index 163601a6..58d2de2b 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs @@ -37,6 +37,12 @@ public sealed class InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer : Diag return; } + // Skip implementation parts to avoid duplicate errors + if (context.Symbol is IPropertySymbol { PartialDefinitionPart: not null }) + { + return; + } + // If the property is using [GeneratedCanvasEffectProperty], emit the diagnostic if (context.Symbol.TryGetAttributeWithType(generatedCanvasEffectPropertyAttributeSymbol, out AttributeData? generatedCanvasEffectPropertyAttribute)) { diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs index f002420b..05e85c87 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs @@ -32,8 +32,8 @@ public sealed class InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer : context.RegisterSymbolAction(context => { - // Validate that we have a valid containing type - if (context.Symbol is not IPropertySymbol { ContainingType: { } containingTypeSymbol }) + // Validate that we have a valid containing type (also skip implementation parts) + if (context.Symbol is not IPropertySymbol { ContainingType: { } containingTypeSymbol, PartialDefinitionPart: null }) { return; } diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs index 94482d0a..68222d64 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs @@ -37,8 +37,8 @@ public sealed class InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer : Di context.RegisterSymbolAction(context => { - // Ensure that we have some target property to analyze - if (context.Symbol is not IPropertySymbol propertySymbol) + // Ensure that we have some target property to analyze (also skip implementation parts) + if (context.Symbol is not IPropertySymbol { PartialDefinitionPart: null } propertySymbol) { return; } diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs index b56cd23d..91b4b164 100644 --- a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs @@ -56,4 +56,121 @@ public class Test_CanvasEffectPropertyGenerator_Analyzers await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); } + + [TestMethod] + public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_StaticProperty_Warns() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + public abstract partial class MyEffect : CanvasEffect + { + [{|CMPSD2DWINUI0003:GeneratedCanvasEffectProperty|}] + public static partial int {|CS9248:Number|} { get; set; } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); + } + + [TestMethod] + public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_NotPartialProperty_Warns() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + public abstract partial class MyEffect : CanvasEffect + { + [{|CMPSD2DWINUI0004:GeneratedCanvasEffectProperty|}] + public int Number { get; set; } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); + } + + [TestMethod] + public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_PartialPropertyWithImplementation_Warns() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + public abstract partial class MyEffect : CanvasEffect + { + [{|CMPSD2DWINUI0004:GeneratedCanvasEffectProperty|}] + public partial int Number { get; set; } + + public partial int Number { get => 42; set { } } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); + } + + [TestMethod] + public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_PartialPropertyImplementationPart_Warns() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + public abstract partial class MyEffect : CanvasEffect + { + public partial int Number { get; set; } + + [{|CMPSD2DWINUI0004:GeneratedCanvasEffectProperty|}] + public partial int Number { get => 42; set { } } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); + } + + [TestMethod] + public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_ReturnsByRef_Warns() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + public abstract partial class MyEffect : CanvasEffect + { + [{|CMPSD2DWINUI0005:GeneratedCanvasEffectProperty|}] + public partial ref int {|CS9248:Number|} { get; {|CS8147:set|}; } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); + } + + [TestMethod] + public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_ReturnsByRefReadonly_Warns() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + public abstract partial class MyEffect : CanvasEffect + { + [{|CMPSD2DWINUI0005:GeneratedCanvasEffectProperty|}] + public partial ref readonly int {|CS9248:Number|} { get; {|CS8147:set|}; } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); + } + + [TestMethod] + public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_ReturnsRefStructType_Warns() + { + const string source = """ + using System; + using ComputeSharp.D2D1.WinUI; + + public abstract partial class MyEffect : CanvasEffect + { + [{|CMPSD2DWINUI0006:GeneratedCanvasEffectProperty|}] + public partial Span {|CS9248:Number|} { get; set; } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); + } } \ No newline at end of file From f57bf4252a35446c62469953f75d6344ff4868f2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 26 Aug 2024 20:01:33 -0700 Subject: [PATCH 34/46] Add 'RequireCSharpLanguageVersionPreviewAnalyzer' --- .../Diagnostics/DiagnosticDescriptors.cs | 4 +- .../AnalyzerReleases.Shipped.md | 1 + .../CanvasEffectPropertyGenerator.cs | 6 ++ ...ireCSharpLanguageVersionPreviewAnalyzer.cs | 57 +++++++++++++++++++ .../Diagnostics/DiagnosticDescriptors.cs | 16 ++++++ .../Extensions/CompilationExtensions.cs | 10 ++++ .../Diagnostics/DiagnosticDescriptors.cs | 4 +- 7 files changed, 94 insertions(+), 4 deletions(-) create mode 100644 src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 83836ddd..6e8dd5b9 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -944,13 +944,13 @@ partial class DiagnosticDescriptors /// /// Gets a for when the AllowUnsafeBlocks option is not set. /// - /// Format: "Using [D2DGeneratedPixelShaderDescriptor] requires unsafe blocks being enabled, as they needed by the source generators to emit valid code (add <AllowUnsafeBlocks>true</AllowUnsafeBlocks> to your .csproj/.props file)". + /// Format: "Using [D2DGeneratedPixelShaderDescriptor] requires unsafe blocks being enabled, as they are needed by the source generators to emit valid code (add <AllowUnsafeBlocks>true</AllowUnsafeBlocks> to your .csproj/.props file)". /// /// public static readonly DiagnosticDescriptor MissingAllowUnsafeBlocksOption = new( id: "CMPSD2D0064", title: "Missing 'AllowUnsafeBlocks' compilation option", - messageFormat: "Using [D2DGeneratedPixelShaderDescriptor] requires unsafe blocks being enabled, as they needed by the source generators to emit valid code (add true to your .csproj/.props file)", + messageFormat: "Using [D2DGeneratedPixelShaderDescriptor] requires unsafe blocks being enabled, as they are needed by the source generators to emit valid code (add true to your .csproj/.props file)", category: "ComputeSharp.D2D1.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md index 3449845d..a67085fd 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/AnalyzerReleases.Shipped.md @@ -13,3 +13,4 @@ CMPSD2DWINUI0003 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](htt CMPSD2DWINUI0004 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2DWINUI0005 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2DWINUI0006 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DWINUI0007 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs index a63a7152..a9f20c6e 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -29,6 +29,12 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato Execute.IsCandidatePropertyDeclaration, static (context, token) => { + // This generator requires C# preview to be used (due to the use of the 'field' keyword) + if (!context.SemanticModel.Compilation.IsLanguageVersionPreview()) + { + return default; + } + // Ensure we do have a property with a valid containing type if (context.TargetSymbol is not IPropertySymbol { ContainingType: INamedTypeSymbol typeSymbol } propertySymbol) { diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs new file mode 100644 index 00000000..d9bc6943 --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs @@ -0,0 +1,57 @@ +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.WinUI.SourceGenerators; + +/// +/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] is in a project with the C# language version not set to preview. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class RequireCSharpLanguageVersionPreviewAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = [CSharpLanguageVersionIsNotPreview]; + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static context => + { + // If the language version is set to preview, we'll never emit diagnostics + if (context.Compilation.IsLanguageVersionPreview()) + { + return; + } + + // Get the [GeneratedCanvasEffectProperty] symbols + if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute") is not { } generatedCanvasEffectPropertyAttributeSymbol) + { + return; + } + + context.RegisterSymbolAction(context => + { + // We only want to target partial property definitions (also include non-partial ones for diagnostics) + if (context.Symbol is not IPropertySymbol { PartialDefinitionPart: null }) + { + return; + } + + // If the property is using [GeneratedCanvasEffectProperty], emit the diagnostic + if (context.Symbol.TryGetAttributeWithType(generatedCanvasEffectPropertyAttributeSymbol, out AttributeData? generatedCanvasEffectPropertyAttribute)) + { + context.ReportDiagnostic(Diagnostic.Create( + CSharpLanguageVersionIsNotPreview, + generatedCanvasEffectPropertyAttribute.GetLocation(), + context.Symbol)); + } + }, SymbolKind.Property); + }); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 05a7daa4..3dc9d5fd 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -102,4 +102,20 @@ internal static class DiagnosticDescriptors isEnabledByDefault: true, description: "A property using [GeneratedCanvasEffectProperty] has a ref struct type ([GeneratedCanvasEffectProperty] must be used on properties with a type that is not a ref struct).", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a CanvasEffect property with invalid accessors. + /// + /// Format: "Using [GeneratedCanvasEffectProperty] requires the C# language version to be set to 'preview', as support for the 'field' keyword is needed by the source generators to emit valid code (add <LangVersion>preview</LangVersion> to your .csproj/.props file)". + /// + /// + public static readonly DiagnosticDescriptor CSharpLanguageVersionIsNotPreview = new( + id: "CMPSD2DWINUI0007", + title: "C# language version is not 'preview'", + messageFormat: """Using [GeneratedCanvasEffectProperty] requires the C# language version to be set to 'preview', as support for the 'field' keyword is needed by the source generators to emit valid code (add preview to your .csproj/.props file)""", + category: "ComputeSharp.D2D1.WinUI.Effects", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The C# language version must be set to 'preview' when using [GeneratedComputeShaderDescriptor] for the source generators to emit valid code (the preview option must be set in the .csproj/.props file).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Extensions/CompilationExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/CompilationExtensions.cs index 364a639a..ec2db073 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/CompilationExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/CompilationExtensions.cs @@ -46,6 +46,16 @@ internal static class CompilationExtensions return true; } + /// + /// Checks whether a given compilation (assumed to be for C#) is using the preview language version. + /// + /// The to consider for analysis. + /// Whether is using the preview language version. + public static bool IsLanguageVersionPreview(this Compilation compilation) + { + return ((CSharpCompilation)compilation).LanguageVersion == LanguageVersion.Preview; + } + /// /// Checks whether the AllowUnsafeBlocks option is set for a given compilation. /// diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index e55d2a4d..b71dfda1 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -720,13 +720,13 @@ partial class DiagnosticDescriptors /// /// Gets a for when the AllowUnsafeBlocks option is not set. /// - /// Format: "Using [GeneratedComputeShaderDescriptor] requires unsafe blocks being enabled, as they needed by the source generators to emit valid code (add <AllowUnsafeBlocks>true</AllowUnsafeBlocks> to your .csproj/.props file)". + /// Format: "Using [GeneratedComputeShaderDescriptor] requires unsafe blocks being enabled, as they are needed by the source generators to emit valid code (add <AllowUnsafeBlocks>true</AllowUnsafeBlocks> to your .csproj/.props file)". /// /// public static readonly DiagnosticDescriptor MissingAllowUnsafeBlocksOption = new( id: "CMPS0052", title: "Missing 'AllowUnsafeBlocks' compilation option", - messageFormat: "Using [GeneratedComputeShaderDescriptor] requires unsafe blocks being enabled, as they needed by the source generators to emit valid code (add true to your .csproj/.props file)", + messageFormat: "Using [GeneratedComputeShaderDescriptor] requires unsafe blocks being enabled, as they are needed by the source generators to emit valid code (add true to your .csproj/.props file)", category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, From bba179583ffaa1c5666a0e01c7bbb311a6991d75 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 26 Aug 2024 20:01:48 -0700 Subject: [PATCH 35/46] Update unit tests for 'preview' required --- .../Test_CanvasEffectPropertyGenerator.cs | 60 +++++++++---------- ...CanvasEffectPropertyGenerator_Analyzers.cs | 34 +++++++++++ ...sEffectPropertyGenerator_Incrementality.cs | 10 +++- .../CSharpGeneratorTest{TGenerator}.cs | 8 ++- 4 files changed, 76 insertions(+), 36 deletions(-) diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs index e637788a..6597d5ac 100644 --- a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs @@ -33,7 +33,7 @@ public class Test_CanvasEffectPropertyGenerator partial class MyEffect { /// - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] [global::System.Diagnostics.DebuggerNonUserCode] [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial int Number @@ -63,27 +63,27 @@ public class Test_CanvasEffectPropertyGenerator /// Executes the logic for when is changing. /// The new property value being set. /// This method is invoked right before the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnNumberChanging(int newValue); /// Executes the logic for when is changing. /// The previous property value that is being replaced. /// The new property value being set. /// This method is invoked right before the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnNumberChanging(int oldValue, int newValue); /// Executes the logic for when has just changed. /// The new property value that has been set. /// This method is invoked right after the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnNumberChanged(int newValue); /// Executes the logic for when has just changed. /// The previous property value that has been replaced. /// The new property value that has been set. /// This method is invoked right after the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnNumberChanged(int oldValue, int newValue); } } @@ -117,7 +117,7 @@ public class Test_CanvasEffectPropertyGenerator partial class MyEffect { /// - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] [global::System.Diagnostics.DebuggerNonUserCode] [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial object? Instance @@ -147,27 +147,27 @@ public class Test_CanvasEffectPropertyGenerator /// Executes the logic for when is changing. /// The new property value being set. /// This method is invoked right before the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnInstanceChanging(object? newValue); /// Executes the logic for when is changing. /// The previous property value that is being replaced. /// The new property value being set. /// This method is invoked right before the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnInstanceChanging(object? oldValue, object? newValue); /// Executes the logic for when has just changed. /// The new property value that has been set. /// This method is invoked right after the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnInstanceChanged(object? newValue); /// Executes the logic for when has just changed. /// The previous property value that has been replaced. /// The new property value that has been set. /// This method is invoked right after the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnInstanceChanged(object? oldValue, object? newValue); } } @@ -201,7 +201,7 @@ public class Test_CanvasEffectPropertyGenerator partial class MyEffect { /// - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] [global::System.Diagnostics.DebuggerNonUserCode] [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial object Instance @@ -231,27 +231,27 @@ public class Test_CanvasEffectPropertyGenerator /// Executes the logic for when is changing. /// The new property value being set. /// This method is invoked right before the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnInstanceChanging(object newValue); /// Executes the logic for when is changing. /// The previous property value that is being replaced. /// The new property value being set. /// This method is invoked right before the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnInstanceChanging(object? oldValue, object newValue); /// Executes the logic for when has just changed. /// The new property value that has been set. /// This method is invoked right after the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnInstanceChanged(object newValue); /// Executes the logic for when has just changed. /// The previous property value that has been replaced. /// The new property value that has been set. /// This method is invoked right after the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnInstanceChanged(object? oldValue, object newValue); } } @@ -285,7 +285,7 @@ public class Test_CanvasEffectPropertyGenerator partial class MyEffect { /// - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] [global::System.Diagnostics.DebuggerNonUserCode] [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial int Number @@ -315,27 +315,27 @@ public class Test_CanvasEffectPropertyGenerator /// Executes the logic for when is changing. /// The new property value being set. /// This method is invoked right before the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnNumberChanging(int newValue); /// Executes the logic for when is changing. /// The previous property value that is being replaced. /// The new property value being set. /// This method is invoked right before the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnNumberChanging(int oldValue, int newValue); /// Executes the logic for when has just changed. /// The new property value that has been set. /// This method is invoked right after the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnNumberChanged(int newValue); /// Executes the logic for when has just changed. /// The previous property value that has been replaced. /// The new property value that has been set. /// This method is invoked right after the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnNumberChanged(int oldValue, int newValue); } } @@ -372,7 +372,7 @@ public class Test_CanvasEffectPropertyGenerator partial class MyEffect { /// - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] [global::System.Diagnostics.DebuggerNonUserCode] [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial int X @@ -400,7 +400,7 @@ public class Test_CanvasEffectPropertyGenerator } /// - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] [global::System.Diagnostics.DebuggerNonUserCode] [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial int Y @@ -430,53 +430,53 @@ public class Test_CanvasEffectPropertyGenerator /// Executes the logic for when is changing. /// The new property value being set. /// This method is invoked right before the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnXChanging(int newValue); /// Executes the logic for when is changing. /// The previous property value that is being replaced. /// The new property value being set. /// This method is invoked right before the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnXChanging(int oldValue, int newValue); /// Executes the logic for when has just changed. /// The new property value that has been set. /// This method is invoked right after the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnXChanged(int newValue); /// Executes the logic for when has just changed. /// The previous property value that has been replaced. /// The new property value that has been set. /// This method is invoked right after the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnXChanged(int oldValue, int newValue); /// Executes the logic for when is changing. /// The new property value being set. /// This method is invoked right before the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnYChanging(int newValue); /// Executes the logic for when is changing. /// The previous property value that is being replaced. /// The new property value being set. /// This method is invoked right before the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnYChanging(int oldValue, int newValue); /// Executes the logic for when has just changed. /// The new property value that has been set. /// This method is invoked right after the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnYChanged(int newValue); /// Executes the logic for when has just changed. /// The previous property value that has been replaced. /// The new property value that has been set. /// This method is invoked right after the value of is changed. - [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "3.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] partial void OnYChanged(int oldValue, int newValue); } } diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs index 91b4b164..7489ecf7 100644 --- a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs @@ -173,4 +173,38 @@ public class Test_CanvasEffectPropertyGenerator_Analyzers await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); } + + [TestMethod] + public async Task RequireCSharpLanguageVersionPreviewAnalyzer_LanguageVersionIsNotPreview_Warns() + { + const string source = """ + using System; + using ComputeSharp.D2D1.WinUI; + + public abstract partial class MyEffect : CanvasEffect + { + [{|CMPSD2DWINUI0007:GeneratedCanvasEffectProperty|}] + public int Number { get; set; } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task RequireCSharpLanguageVersionPreviewAnalyzer_LanguageVersionIsPreview_DoesNotWarn() + { + const string source = """ + using System; + using ComputeSharp.D2D1.WinUI; + + public abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public int Number { get; set; } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); + } } \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Incrementality.cs b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Incrementality.cs index ae987d10..2248b818 100644 --- a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Incrementality.cs +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Incrementality.cs @@ -1,6 +1,7 @@ using ComputeSharp.D2D1.WinUI.SourceGenerators; using ComputeSharp.Tests.SourceGenerators.Helpers; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.D2D1.WinUI.Tests.SourceGenerators; @@ -38,7 +39,8 @@ public class Test_CanvasEffectPropertyGenerator_Incrementality diagnosticsReason: null, outputReason: IncrementalStepRunReason.Modified, diagnosticsSourceReason: null, - sourceReason: IncrementalStepRunReason.Modified); + sourceReason: IncrementalStepRunReason.Modified, + languageVersion: LanguageVersion.Preview); } [TestMethod] @@ -74,7 +76,8 @@ public class Test_CanvasEffectPropertyGenerator_Incrementality diagnosticsReason: null, outputReason: IncrementalStepRunReason.Cached, diagnosticsSourceReason: null, - sourceReason: IncrementalStepRunReason.Cached); + sourceReason: IncrementalStepRunReason.Cached, + languageVersion: LanguageVersion.Preview); } [TestMethod] @@ -111,6 +114,7 @@ public class Test_CanvasEffectPropertyGenerator_Incrementality diagnosticsReason: null, outputReason: IncrementalStepRunReason.Cached, diagnosticsSourceReason: null, - sourceReason: IncrementalStepRunReason.Cached); + sourceReason: IncrementalStepRunReason.Cached, + languageVersion: LanguageVersion.Preview); } } \ No newline at end of file diff --git a/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs b/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs index 7670c841..1d29bfaf 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs @@ -83,6 +83,7 @@ internal static class CSharpGeneratorTest /// The reason for the "Output" step. /// The reason for the output step for the diagnostics. /// The reason for the final output source. + /// The language version to use to run the test. public static void VerifyIncrementalSteps( string source, string updatedSource, @@ -90,9 +91,10 @@ internal static class CSharpGeneratorTest IncrementalStepRunReason? diagnosticsReason, IncrementalStepRunReason outputReason, IncrementalStepRunReason? diagnosticsSourceReason, - IncrementalStepRunReason sourceReason) + IncrementalStepRunReason sourceReason, + LanguageVersion languageVersion = LanguageVersion.CSharp12) { - Compilation compilation = CreateCompilation(source); + Compilation compilation = CreateCompilation(source, languageVersion); GeneratorDriver driver = CSharpGeneratorDriver.Create( generators: [new TGenerator().AsSourceGenerator()], @@ -104,7 +106,7 @@ internal static class CSharpGeneratorTest // Update the compilation by replacing the source compilation = compilation.ReplaceSyntaxTree( compilation.SyntaxTrees.First(), - CSharpSyntaxTree.ParseText(updatedSource, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12))); + CSharpSyntaxTree.ParseText(updatedSource, CSharpParseOptions.Default.WithLanguageVersion(languageVersion))); // Run the generators again on the updated source driver = driver.RunGenerators(compilation); From d4ed2099a30a2a285c6bffd23ca23b8e2058cd62 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 17 Oct 2024 22:06:09 -0700 Subject: [PATCH 36/46] Add blank 'ComputeSharp.D2D1.UI.SourceGenerators' --- ComputeSharp.sln | 3 +++ .../ComputeSharp.D2D1.UI.SourceGenerators.projitems | 13 +++++++++++++ .../ComputeSharp.D2D1.UI.SourceGenerators.shproj | 13 +++++++++++++ 3 files changed, 29 insertions(+) create mode 100644 src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems create mode 100644 src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.shproj diff --git a/ComputeSharp.sln b/ComputeSharp.sln index e295949f..13124e1d 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -182,6 +182,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.D2D1.WinUI.Sou EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1.WinUI.Tests.SourceGenerators", "tests\ComputeSharp.D2D1.WinUI.Tests.SourceGenerators\ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj", "{916331A5-1EA6-41D7-B199-2E50C513EFDE}" EndProject +Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.D2D1.UI.SourceGenerators", "src\ComputeSharp.D2D1.UI.SourceGenerators\ComputeSharp.D2D1.UI.SourceGenerators.shproj", "{D20E610F-EB37-46E7-B028-04784D7400D5}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 @@ -590,6 +592,7 @@ Global src\ComputeSharp.D2D1.UI\ComputeSharp.D2D1.UI.projitems*{a2a2171b-0baf-4a2a-bfb3-3357ef714bf0}*SharedItemsImports = 13 src\ComputeSharp.D2D1.UI\ComputeSharp.D2D1.UI.projitems*{bd9e6556-357e-4c20-bfcd-fb131f9372fa}*SharedItemsImports = 5 samples\ComputeSharp.SwapChain.Shaders\ComputeSharp.SwapChain.Shaders.projitems*{c12d7ace-98ed-4813-8118-6667c34f484f}*SharedItemsImports = 5 + src\ComputeSharp.D2D1.UI.SourceGenerators\ComputeSharp.D2D1.UI.SourceGenerators.projitems*{d20e610f-eb37-46e7-b028-04784d7400d5}*SharedItemsImports = 13 src\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*SharedItemsImports = 5 src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*SharedItemsImports = 5 samples\ComputeSharp.SwapChain.Shaders\ComputeSharp.SwapChain.Shaders.projitems*{e7c9247d-016b-4819-af9f-0e9b3591e04b}*SharedItemsImports = 5 diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems b/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems new file mode 100644 index 00000000..c5c7a543 --- /dev/null +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems @@ -0,0 +1,13 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + d20e610f-eb37-46e7-b028-04784d7400d5 + + + ComputeSharp.D2D1.UI.SourceGenerators + + + + diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.shproj b/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.shproj new file mode 100644 index 00000000..0e319581 --- /dev/null +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.shproj @@ -0,0 +1,13 @@ + + + + d20e610f-eb37-46e7-b028-04784d7400d5 + 14.0 + + + + + + + + From 7f704fa3269919fbba9de3de061c37b4d587d050 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 17 Oct 2024 22:09:57 -0700 Subject: [PATCH 37/46] Move files to shared project --- .../CanvasEffectPropertyGenerator.Execute.cs | 0 .../CanvasEffectPropertyGenerator.cs | 0 .../ComputeSharp.D2D1.UI.SourceGenerators.projitems | 11 ++++++++++- ...dGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs | 0 ...ratedCanvasEffectPropertyContainingTypeAnalyzer.cs | 0 ...eneratedCanvasEffectPropertyDeclarationAnalyzer.cs | 0 .../RequireCSharpLanguageVersionPreviewAnalyzer.cs | 0 .../Diagnostics/DiagnosticDescriptors.cs | 0 .../Models/CanvasEffectPropertyInfo.cs | 0 9 files changed, 10 insertions(+), 1 deletion(-) rename src/{ComputeSharp.D2D1.WinUI.SourceGenerators => ComputeSharp.D2D1.UI.SourceGenerators}/CanvasEffectPropertyGenerator.Execute.cs (100%) rename src/{ComputeSharp.D2D1.WinUI.SourceGenerators => ComputeSharp.D2D1.UI.SourceGenerators}/CanvasEffectPropertyGenerator.cs (100%) rename src/{ComputeSharp.D2D1.WinUI.SourceGenerators => ComputeSharp.D2D1.UI.SourceGenerators}/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs (100%) rename src/{ComputeSharp.D2D1.WinUI.SourceGenerators => ComputeSharp.D2D1.UI.SourceGenerators}/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs (100%) rename src/{ComputeSharp.D2D1.WinUI.SourceGenerators => ComputeSharp.D2D1.UI.SourceGenerators}/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs (100%) rename src/{ComputeSharp.D2D1.WinUI.SourceGenerators => ComputeSharp.D2D1.UI.SourceGenerators}/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs (100%) rename src/{ComputeSharp.D2D1.WinUI.SourceGenerators => ComputeSharp.D2D1.UI.SourceGenerators}/Diagnostics/DiagnosticDescriptors.cs (100%) rename src/{ComputeSharp.D2D1.WinUI.SourceGenerators => ComputeSharp.D2D1.UI.SourceGenerators}/Models/CanvasEffectPropertyInfo.cs (100%) diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs similarity index 100% rename from src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs rename to src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs similarity index 100% rename from src/ComputeSharp.D2D1.WinUI.SourceGenerators/CanvasEffectPropertyGenerator.cs rename to src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems b/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems index c5c7a543..2607dd6a 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems @@ -9,5 +9,14 @@ ComputeSharp.D2D1.UI.SourceGenerators + + + + + + + + + - + \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs similarity index 100% rename from src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs rename to src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs similarity index 100% rename from src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs rename to src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs similarity index 100% rename from src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs rename to src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs similarity index 100% rename from src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs rename to src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs similarity index 100% rename from src/ComputeSharp.D2D1.WinUI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs rename to src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs similarity index 100% rename from src/ComputeSharp.D2D1.WinUI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs rename to src/ComputeSharp.D2D1.UI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs From 1d5fddd0f15a5ae5a8d49c406d2233c7c8b21d36 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 17 Oct 2024 22:12:24 -0700 Subject: [PATCH 38/46] Switch D2D1.WinUI generator to shared project --- ComputeSharp.sln | 1 + .../ComputeSharp.D2D1.WinUI.SourceGenerators.csproj | 7 +------ 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 13124e1d..a11402da 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -601,6 +601,7 @@ Global src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5 samples\ComputeSharp.SwapChain.Shaders.D2D1\ComputeSharp.SwapChain.Shaders.D2D1.projitems*{f8bf7666-7ccf-4fe4-b055-2eba4bcd4564}*SharedItemsImports = 13 src\ComputeSharp.UI\ComputeSharp.UI.projitems*{fa18ba9f-76bf-4de0-8d24-02fc7657e6cb}*SharedItemsImports = 5 + src\ComputeSharp.D2D1.UI.SourceGenerators\ComputeSharp.D2D1.UI.SourceGenerators.projitems*{febec83a-fe70-4d4b-9b00-76db31e75f17}*SharedItemsImports = 5 src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{febec83a-fe70-4d4b-9b00-76db31e75f17}*SharedItemsImports = 5 EndGlobalSection EndGlobal diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj index 824cc76a..51e65ab8 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj @@ -19,11 +19,6 @@ - - - - - - + From 9a1e81f20c042f649973d51246042a7cbbb6389c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 17 Oct 2024 22:13:15 -0700 Subject: [PATCH 39/46] Fix typo in defined constant --- src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs | 2 +- .../ComputeSharp.D2D1.WinUI.SourceGenerators.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs b/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs index aef4f100..bb2722e9 100644 --- a/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs +++ b/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs @@ -1,4 +1,4 @@ -#if !D2D1_UWINUI_SOURCE_GENERATOR +#if !D2D1_WINUI_SOURCE_GENERATOR using ABI.Microsoft.Graphics.Canvas; using Microsoft.Graphics.Canvas; #endif diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj index 51e65ab8..4d2c1c56 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj @@ -1,7 +1,7 @@ netstandard2.0 - $(DefineConstants);D2D1_UWINUI_SOURCE_GENERATOR + $(DefineConstants);D2D1_WINUI_SOURCE_GENERATOR From e4e04410ba293fe3eb6de9285971463de4a0af5a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 17 Oct 2024 22:15:19 -0700 Subject: [PATCH 40/46] Add UWP source generator project --- ComputeSharp.sln | 12 +++++++++++ .../AnalyzerReleases.Shipped.md | 16 ++++++++++++++ .../AnalyzerReleases.Unshipped.md | 2 ++ ...puteSharp.D2D1.Uwp.SourceGenerators.csproj | 21 +++++++++++++++++++ ...teSharp.D2D1.WinUI.SourceGenerators.csproj | 3 --- 5 files changed, 51 insertions(+), 3 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp.SourceGenerators/AnalyzerReleases.Shipped.md create mode 100644 src/ComputeSharp.D2D1.Uwp.SourceGenerators/AnalyzerReleases.Unshipped.md create mode 100644 src/ComputeSharp.D2D1.Uwp.SourceGenerators/ComputeSharp.D2D1.Uwp.SourceGenerators.csproj diff --git a/ComputeSharp.sln b/ComputeSharp.sln index a11402da..9be35f87 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -184,6 +184,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1.WinUI.Tes EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.D2D1.UI.SourceGenerators", "src\ComputeSharp.D2D1.UI.SourceGenerators\ComputeSharp.D2D1.UI.SourceGenerators.shproj", "{D20E610F-EB37-46E7-B028-04784D7400D5}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.D2D1.Uwp.SourceGenerators", "src\ComputeSharp.D2D1.Uwp.SourceGenerators\ComputeSharp.D2D1.Uwp.SourceGenerators.csproj", "{690C4014-A06B-44DB-B717-AEA4CAFA9D68}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 @@ -524,6 +526,14 @@ Global {916331A5-1EA6-41D7-B199-2E50C513EFDE}.Release|ARM64.Build.0 = Release|ARM64 {916331A5-1EA6-41D7-B199-2E50C513EFDE}.Release|x64.ActiveCfg = Release|x64 {916331A5-1EA6-41D7-B199-2E50C513EFDE}.Release|x64.Build.0 = Release|x64 + {690C4014-A06B-44DB-B717-AEA4CAFA9D68}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {690C4014-A06B-44DB-B717-AEA4CAFA9D68}.Debug|ARM64.Build.0 = Debug|Any CPU + {690C4014-A06B-44DB-B717-AEA4CAFA9D68}.Debug|x64.ActiveCfg = Debug|Any CPU + {690C4014-A06B-44DB-B717-AEA4CAFA9D68}.Debug|x64.Build.0 = Debug|Any CPU + {690C4014-A06B-44DB-B717-AEA4CAFA9D68}.Release|ARM64.ActiveCfg = Release|Any CPU + {690C4014-A06B-44DB-B717-AEA4CAFA9D68}.Release|ARM64.Build.0 = Release|Any CPU + {690C4014-A06B-44DB-B717-AEA4CAFA9D68}.Release|x64.ActiveCfg = Release|Any CPU + {690C4014-A06B-44DB-B717-AEA4CAFA9D68}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -582,6 +592,8 @@ Global src\ComputeSharp.Win32.D3D12\ComputeSharp.Win32.D3D12.projitems*{514ff00e-bbf0-4d55-a47c-eeeb6208adce}*SharedItemsImports = 13 src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{51d5a422-d3a5-4c4d-8a6d-a048940bf279}*SharedItemsImports = 13 src\ComputeSharp.CodeFixing\ComputeSharp.CodeFixing.projitems*{54654960-54b5-4e19-b3ed-993591ca39e5}*SharedItemsImports = 5 + src\ComputeSharp.D2D1.UI.SourceGenerators\ComputeSharp.D2D1.UI.SourceGenerators.projitems*{690c4014-a06b-44db-b717-aea4cafa9d68}*SharedItemsImports = 5 + src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{690c4014-a06b-44db-b717-aea4cafa9d68}*SharedItemsImports = 5 src\ComputeSharp.D2D1.UI\ComputeSharp.D2D1.UI.projitems*{716df19e-69ba-4a9c-9ca4-bfd196152f46}*SharedItemsImports = 5 samples\ComputeSharp.SwapChain.Shaders.D2D1\ComputeSharp.SwapChain.Shaders.D2D1.projitems*{73c32d0f-64db-4674-84e9-8fcc41228474}*SharedItemsImports = 5 src\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems*{9ac496a3-bbf0-4c8f-a50d-a20bf01c5e05}*SharedItemsImports = 13 diff --git a/src/ComputeSharp.D2D1.Uwp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.Uwp.SourceGenerators/AnalyzerReleases.Shipped.md new file mode 100644 index 00000000..a67085fd --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp.SourceGenerators/AnalyzerReleases.Shipped.md @@ -0,0 +1,16 @@ +; Shipped analyzer releases +; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md + +## Release 1.0 + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------- +CMPSD2DWINUI0001 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DWINUI0002 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DWINUI0003 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DWINUI0004 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DWINUI0005 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DWINUI0006 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DWINUI0007 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.Uwp.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.D2D1.Uwp.SourceGenerators/AnalyzerReleases.Unshipped.md new file mode 100644 index 00000000..6a6dd08d --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -0,0 +1,2 @@ +; Unshipped analyzer release +; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md diff --git a/src/ComputeSharp.D2D1.Uwp.SourceGenerators/ComputeSharp.D2D1.Uwp.SourceGenerators.csproj b/src/ComputeSharp.D2D1.Uwp.SourceGenerators/ComputeSharp.D2D1.Uwp.SourceGenerators.csproj new file mode 100644 index 00000000..1630e8b8 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp.SourceGenerators/ComputeSharp.D2D1.Uwp.SourceGenerators.csproj @@ -0,0 +1,21 @@ + + + netstandard2.0 + $(DefineConstants);D2D1_WINUI_SOURCE_GENERATOR + + + $(NoWarn);CS1574 + + + + + + + + + + + + + + diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj index 4d2c1c56..17984174 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj @@ -2,9 +2,6 @@ netstandard2.0 $(DefineConstants);D2D1_WINUI_SOURCE_GENERATOR - - - $(NoWarn);CS1574 From 1b127cd7c62c393ea7744e36527c43f51aebcb44 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 17 Oct 2024 22:26:33 -0700 Subject: [PATCH 41/46] Update namespaces and diagnostics for UWP --- .../CanvasEffectPropertyGenerator.Execute.cs | 8 +++ .../CanvasEffectPropertyGenerator.cs | 8 +++ ...edCanvasEffectPropertyAccessorsAnalyzer.cs | 8 +++ ...vasEffectPropertyContainingTypeAnalyzer.cs | 8 +++ ...CanvasEffectPropertyDeclarationAnalyzer.cs | 8 +++ ...ireCSharpLanguageVersionPreviewAnalyzer.cs | 8 +++ .../Diagnostics/DiagnosticDescriptors.cs | 52 ++++++++++++++----- .../Models/CanvasEffectPropertyInfo.cs | 4 ++ .../CanvasEffectInvalidationType.cs | 2 +- .../AnalyzerReleases.Shipped.md | 14 ++--- ...puteSharp.D2D1.Uwp.SourceGenerators.csproj | 2 +- ...teSharp.D2D1.WinUI.SourceGenerators.csproj | 2 +- 12 files changed, 100 insertions(+), 24 deletions(-) diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs index bcc229e6..5ad3b1ef 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs @@ -1,12 +1,20 @@ using System.Threading; +#if WINDOWS_UWP +using ComputeSharp.D2D1.Uwp.SourceGenerators.Models; +#else using ComputeSharp.D2D1.WinUI.SourceGenerators.Models; +#endif using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +#if WINDOWS_UWP +namespace ComputeSharp.D2D1.Uwp.SourceGenerators; +#else namespace ComputeSharp.D2D1.WinUI.SourceGenerators; +#endif /// partial class CanvasEffectPropertyGenerator diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs index a9f20c6e..c7c5c50c 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -1,4 +1,8 @@ +#if WINDOWS_UWP +using ComputeSharp.D2D1.Uwp.SourceGenerators.Models; +#else using ComputeSharp.D2D1.WinUI.SourceGenerators.Models; +#endif using ComputeSharp.SourceGeneration.Constants; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; @@ -6,7 +10,11 @@ using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; +#if WINDOWS_UWP +namespace ComputeSharp.D2D1.Uwp.SourceGenerators; +#else namespace ComputeSharp.D2D1.WinUI.SourceGenerators; +#endif /// /// A source generator creating implementations of effect properties. diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs index 58d2de2b..790e2d33 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs @@ -2,9 +2,17 @@ using System.Collections.Immutable; using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; +#if WINDOWS_UWP +using static ComputeSharp.D2D1.Uwp.SourceGenerators.DiagnosticDescriptors; +#else using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors; +#endif +#if WINDOWS_UWP +namespace ComputeSharp.D2D1.Uwp.SourceGenerators; +#else namespace ComputeSharp.D2D1.WinUI.SourceGenerators; +#endif /// /// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] has invalid accessors. diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs index 05e85c87..5f6e418c 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs @@ -2,9 +2,17 @@ using System.Collections.Immutable; using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; +#if WINDOWS_UWP +using static ComputeSharp.D2D1.Uwp.SourceGenerators.DiagnosticDescriptors; +#else using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors; +#endif +#if WINDOWS_UWP +namespace ComputeSharp.D2D1.Uwp.SourceGenerators; +#else namespace ComputeSharp.D2D1.WinUI.SourceGenerators; +#endif /// /// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] is in an invalid type. diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs index 68222d64..a1b95f8e 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs @@ -2,9 +2,17 @@ using System.Collections.Immutable; using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; +#if WINDOWS_UWP +using static ComputeSharp.D2D1.Uwp.SourceGenerators.DiagnosticDescriptors; +#else using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors; +#endif +#if WINDOWS_UWP +namespace ComputeSharp.D2D1.Uwp.SourceGenerators; +#else namespace ComputeSharp.D2D1.WinUI.SourceGenerators; +#endif /// /// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] has invalid accessors. diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs index d9bc6943..5142ad93 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs @@ -2,9 +2,17 @@ using System.Collections.Immutable; using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; +#if WINDOWS_UWP +using static ComputeSharp.D2D1.Uwp.SourceGenerators.DiagnosticDescriptors; +#else using static ComputeSharp.D2D1.WinUI.SourceGenerators.DiagnosticDescriptors; +#endif +#if WINDOWS_UWP +namespace ComputeSharp.D2D1.Uwp.SourceGenerators; +#else namespace ComputeSharp.D2D1.WinUI.SourceGenerators; +#endif /// /// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] is in a project with the C# language version not set to preview. diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 3dc9d5fd..64e1c2f0 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -1,12 +1,36 @@ using Microsoft.CodeAnalysis; +#if WINDOWS_UWP +namespace ComputeSharp.D2D1.Uwp.SourceGenerators; +#else namespace ComputeSharp.D2D1.WinUI.SourceGenerators; +#endif /// /// A container for all instances for errors reported by analyzers in this project. /// internal static class DiagnosticDescriptors { + /// + /// The prefix of all diagnostics for available analyzers. + /// + private const string DiagnosticIdPrefix = +#if WINDOWS_UWP + "CMPSD2DUWP"; +#else + "CMPSD2DWINUI"; +#endif + + /// + /// The category of all diagnostics for available analyzers. + /// + private const string DiagnosticCategory = +#if WINDOWS_UWP + "ComputeSharp.D2D1.Uwp.Effects"; +#else + "ComputeSharp.D2D1.WinUI.Effects"; +#endif + /// /// Gets a for an invalid CanvasEffect property. /// @@ -14,10 +38,10 @@ internal static class DiagnosticDescriptors /// /// public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyContainingType = new( - id: "CMPSD2DWINUI0001", + id: $"{DiagnosticIdPrefix}0001", title: "Invalid generated CanvasEffect property containing type", messageFormat: """The property "{0}" is not in a type that derives from CanvasEffect ([GeneratedCanvasEffectProperty] must be used in effect types that extend CanvasEffect)""", - category: "ComputeSharp.D2D1.WinUI.Effects", + category: DiagnosticCategory, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A property using [GeneratedCanvasEffectProperty] is in a type that does not derive from CanvasEffect ([GeneratedCanvasEffectProperty] must be used in effect types that extend CanvasEffect).", @@ -30,10 +54,10 @@ internal static class DiagnosticDescriptors /// /// public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyAccessors = new( - id: "CMPSD2DWINUI0002", + id: $"{DiagnosticIdPrefix}0002", title: "Invalid generated CanvasEffect property accessors", messageFormat: """The property "{0}" does not have a getter and a setter ([GeneratedCanvasEffectProperty] must be used on properties with get and set accessors)""", - category: "ComputeSharp.D2D1.WinUI.Effects", + category: DiagnosticCategory, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A property using [GeneratedCanvasEffectProperty] does not have a getter and a setter ([GeneratedCanvasEffectProperty] must be used on properties with get and set accessors).", @@ -46,10 +70,10 @@ internal static class DiagnosticDescriptors /// /// public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationIsStatic = new( - id: "CMPSD2DWINUI0003", + id: $"{DiagnosticIdPrefix}0003", title: "Invalid generated CanvasEffect property declaration (static member)", messageFormat: """The property "{0}" is static ([GeneratedCanvasEffectProperty] must be used on instance properties)""", - category: "ComputeSharp.D2D1.WinUI.Effects", + category: DiagnosticCategory, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A property using [GeneratedCanvasEffectProperty] cannot be static ([GeneratedCanvasEffectProperty] must be used on instance properties).", @@ -62,10 +86,10 @@ internal static class DiagnosticDescriptors /// /// public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationIsNotIncompletePartialDefinition = new( - id: "CMPSD2DWINUI0004", + id: $"{DiagnosticIdPrefix}0004", title: "Invalid generated CanvasEffect property declaration (not incomplete partial definition)", messageFormat: """The property "{0}" is not an incomplete partial definition ([GeneratedCanvasEffectProperty] must be used on partial property definitions with no implementation part)""", - category: "ComputeSharp.D2D1.WinUI.Effects", + category: DiagnosticCategory, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A property using [GeneratedCanvasEffectProperty] is either not partial, or a partial implementation part ([GeneratedCanvasEffectProperty] must be used on partial property definitions with no implementation par).", @@ -78,10 +102,10 @@ internal static class DiagnosticDescriptors /// /// public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationReturnsByRef = new( - id: "CMPSD2DWINUI0005", + id: $"{DiagnosticIdPrefix}0005", title: "Invalid generated CanvasEffect property declaration (returns byref)", messageFormat: """The property "{0}" returns a value by reference ([GeneratedCanvasEffectProperty] must be used on properties returning a type by value)""", - category: "ComputeSharp.D2D1.WinUI.Effects", + category: DiagnosticCategory, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A property using [GeneratedCanvasEffectProperty] returns a value by reference ([GeneratedCanvasEffectProperty] must be used on properties returning a type by value).", @@ -94,10 +118,10 @@ internal static class DiagnosticDescriptors /// /// public static readonly DiagnosticDescriptor InvalidGeneratedCanvasEffectPropertyDeclarationReturnsRefLikeType = new( - id: "CMPSD2DWINUI0006", + id: $"{DiagnosticIdPrefix}0006", title: "Invalid generated CanvasEffect property declaration (returns ref struct type)", messageFormat: """The property "{0}" returns a ref struct value ([GeneratedCanvasEffectProperty] must be used on properties with a type that is not a ref struct)""", - category: "ComputeSharp.D2D1.WinUI.Effects", + category: DiagnosticCategory, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A property using [GeneratedCanvasEffectProperty] has a ref struct type ([GeneratedCanvasEffectProperty] must be used on properties with a type that is not a ref struct).", @@ -110,10 +134,10 @@ internal static class DiagnosticDescriptors /// /// public static readonly DiagnosticDescriptor CSharpLanguageVersionIsNotPreview = new( - id: "CMPSD2DWINUI0007", + id: $"{DiagnosticIdPrefix}0007", title: "C# language version is not 'preview'", messageFormat: """Using [GeneratedCanvasEffectProperty] requires the C# language version to be set to 'preview', as support for the 'field' keyword is needed by the source generators to emit valid code (add preview to your .csproj/.props file)""", - category: "ComputeSharp.D2D1.WinUI.Effects", + category: DiagnosticCategory, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "The C# language version must be set to 'preview' when using [GeneratedComputeShaderDescriptor] for the source generators to emit valid code (the preview option must be set in the .csproj/.props file).", diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs index a49fb448..3116543b 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs @@ -1,7 +1,11 @@ using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; +#if WINDOWS_UWP +namespace ComputeSharp.D2D1.Uwp.SourceGenerators.Models; +#else namespace ComputeSharp.D2D1.WinUI.SourceGenerators.Models; +#endif /// /// A model representing a generated canvas effect property. diff --git a/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs b/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs index bb2722e9..31905e32 100644 --- a/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs +++ b/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs @@ -1,4 +1,4 @@ -#if !D2D1_WINUI_SOURCE_GENERATOR +#if !D2D1_UI_SOURCE_GENERATOR using ABI.Microsoft.Graphics.Canvas; using Microsoft.Graphics.Canvas; #endif diff --git a/src/ComputeSharp.D2D1.Uwp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.Uwp.SourceGenerators/AnalyzerReleases.Shipped.md index a67085fd..8c38544e 100644 --- a/src/ComputeSharp.D2D1.Uwp.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.Uwp.SourceGenerators/AnalyzerReleases.Shipped.md @@ -7,10 +7,10 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- -CMPSD2DWINUI0001 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPSD2DWINUI0002 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPSD2DWINUI0003 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPSD2DWINUI0004 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPSD2DWINUI0005 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPSD2DWINUI0006 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPSD2DWINUI0007 | ComputeSharp.D2D1.WinUI.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DUWP0001 | ComputeSharp.D2D1.Uwp.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DUWP0002 | ComputeSharp.D2D1.Uwp.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DUWP0003 | ComputeSharp.D2D1.Uwp.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DUWP0004 | ComputeSharp.D2D1.Uwp.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DUWP0005 | ComputeSharp.D2D1.Uwp.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DUWP0006 | ComputeSharp.D2D1.Uwp.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2DUWP0007 | ComputeSharp.D2D1.Uwp.Effects | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.Uwp.SourceGenerators/ComputeSharp.D2D1.Uwp.SourceGenerators.csproj b/src/ComputeSharp.D2D1.Uwp.SourceGenerators/ComputeSharp.D2D1.Uwp.SourceGenerators.csproj index 1630e8b8..2500e683 100644 --- a/src/ComputeSharp.D2D1.Uwp.SourceGenerators/ComputeSharp.D2D1.Uwp.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.Uwp.SourceGenerators/ComputeSharp.D2D1.Uwp.SourceGenerators.csproj @@ -1,7 +1,7 @@ netstandard2.0 - $(DefineConstants);D2D1_WINUI_SOURCE_GENERATOR + $(DefineConstants);WINDOWS_UWP;D2D1_UI_SOURCE_GENERATOR $(NoWarn);CS1574 diff --git a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj index 17984174..1781f0d7 100644 --- a/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj @@ -1,7 +1,7 @@ netstandard2.0 - $(DefineConstants);D2D1_WINUI_SOURCE_GENERATOR + $(DefineConstants);D2D1_UI_SOURCE_GENERATOR $(NoWarn);CS1574 From 3969ea2924f3751d8446362f6b90327ebe24a186 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 17 Oct 2024 22:46:49 -0700 Subject: [PATCH 42/46] Update type names matched by analyzers --- .../CanvasEffectPropertyGenerator.cs | 13 ++++++-- ...teSharp.D2D1.UI.SourceGenerators.projitems | 1 + .../Constants/WellKnownTypeNames.cs | 31 +++++++++++++++++++ ...edCanvasEffectPropertyAccessorsAnalyzer.cs | 7 ++++- ...vasEffectPropertyContainingTypeAnalyzer.cs | 9 ++++-- ...CanvasEffectPropertyDeclarationAnalyzer.cs | 7 ++++- ...ireCSharpLanguageVersionPreviewAnalyzer.cs | 7 ++++- 7 files changed, 67 insertions(+), 8 deletions(-) create mode 100644 src/ComputeSharp.D2D1.UI.SourceGenerators/Constants/WellKnownTypeNames.cs diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs index c7c5c50c..49c19ea3 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -1,6 +1,8 @@ #if WINDOWS_UWP +using ComputeSharp.D2D1.Uwp.SourceGenerators.Constants; using ComputeSharp.D2D1.Uwp.SourceGenerators.Models; #else +using ComputeSharp.D2D1.WinUI.SourceGenerators.Constants; using ComputeSharp.D2D1.WinUI.SourceGenerators.Models; #endif using ComputeSharp.SourceGeneration.Constants; @@ -25,7 +27,12 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato /// /// The name of generator to include in the generated code. /// - private const string GeneratorName = "ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator"; + private const string GeneratorName = +#if WINDOWS_UWP + "ComputeSharp.D2D1.Uwp.CanvasEffectPropertyGenerator"; +#else + "ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator"; +#endif /// public void Initialize(IncrementalGeneratorInitializationContext context) @@ -33,7 +40,7 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato IncrementalValuesProvider propertyInfo = context.SyntaxProvider .ForAttributeWithMetadataName( - "ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute", + WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute, Execute.IsCandidatePropertyDeclaration, static (context, token) => { @@ -62,7 +69,7 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato } // Ensure that the containing type derives from CanvasEffect - if (!typeSymbol.InheritsFromFullyQualifiedMetadataName("ComputeSharp.D2D1.WinUI.CanvasEffect")) + if (!typeSymbol.InheritsFromFullyQualifiedMetadataName(WellKnownTypeNames.CanvasEffect)) { return default; } diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems b/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems index 2607dd6a..b21e1a36 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems @@ -11,6 +11,7 @@ + diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Constants/WellKnownTypeNames.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Constants/WellKnownTypeNames.cs new file mode 100644 index 00000000..cba56733 --- /dev/null +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Constants/WellKnownTypeNames.cs @@ -0,0 +1,31 @@ +#if WINDOWS_UWP +namespace ComputeSharp.D2D1.Uwp.SourceGenerators.Constants; +#else +namespace ComputeSharp.D2D1.WinUI.SourceGenerators.Constants; +#endif + +/// +/// The well known names for types used by source generators and analyzers. +/// +internal static class WellKnownTypeNames +{ + /// + /// The fully qualified type name for the [GeneratedCanvasEffectPropertyAttribute] type. + /// + public const string GeneratedCanvasEffectPropertyAttribute = +#if WINDOWS_UWP + "ComputeSharp.D2D1.Uwp.GeneratedCanvasEffectPropertyAttribute"; +#else + "ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute"; +#endif + + /// + /// The fully qualified type name for the [CanvasEffect] type. + /// + public const string CanvasEffect = +#if WINDOWS_UWP + "ComputeSharp.D2D1.Uwp.CanvasEffect"; +#else + "ComputeSharp.D2D1.WinUI.CanvasEffect"; +#endif +} diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs index 790e2d33..41489bab 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs @@ -1,4 +1,9 @@ using System.Collections.Immutable; +#if WINDOWS_UWP +using ComputeSharp.D2D1.Uwp.SourceGenerators.Constants; +#else +using ComputeSharp.D2D1.WinUI.SourceGenerators.Constants; +#endif using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; @@ -32,7 +37,7 @@ public sealed class InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer : Diag context.RegisterCompilationStartAction(static context => { // Get the [GeneratedCanvasEffectProperty] symbols - if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute") is not { } generatedCanvasEffectPropertyAttributeSymbol) + if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not { } generatedCanvasEffectPropertyAttributeSymbol) { return; } diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs index 5f6e418c..bedd55d5 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs @@ -1,4 +1,9 @@ using System.Collections.Immutable; +#if WINDOWS_UWP +using ComputeSharp.D2D1.Uwp.SourceGenerators.Constants; +#else +using ComputeSharp.D2D1.WinUI.SourceGenerators.Constants; +#endif using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; @@ -32,8 +37,8 @@ public sealed class InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer : context.RegisterCompilationStartAction(static context => { // Get the [GeneratedCanvasEffectProperty] and CanvasEffect symbols - if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute") is not { } generatedCanvasEffectPropertyAttributeSymbol || - context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.CanvasEffect") is not { } canvasEffectSymbol) + if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not { } generatedCanvasEffectPropertyAttributeSymbol || + context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.CanvasEffect) is not { } canvasEffectSymbol) { return; } diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs index a1b95f8e..5ece0ec7 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs @@ -1,4 +1,9 @@ using System.Collections.Immutable; +#if WINDOWS_UWP +using ComputeSharp.D2D1.Uwp.SourceGenerators.Constants; +#else +using ComputeSharp.D2D1.WinUI.SourceGenerators.Constants; +#endif using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; @@ -38,7 +43,7 @@ public sealed class InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer : Di context.RegisterCompilationStartAction(static context => { // Get the [GeneratedCanvasEffectProperty] symbols - if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute") is not { } generatedCanvasEffectPropertyAttributeSymbol) + if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not { } generatedCanvasEffectPropertyAttributeSymbol) { return; } diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs index 5142ad93..dead1781 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs @@ -1,4 +1,9 @@ using System.Collections.Immutable; +#if WINDOWS_UWP +using ComputeSharp.D2D1.Uwp.SourceGenerators.Constants; +#else +using ComputeSharp.D2D1.WinUI.SourceGenerators.Constants; +#endif using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; @@ -38,7 +43,7 @@ public sealed class RequireCSharpLanguageVersionPreviewAnalyzer : DiagnosticAnal } // Get the [GeneratedCanvasEffectProperty] symbols - if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute") is not { } generatedCanvasEffectPropertyAttributeSymbol) + if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not { } generatedCanvasEffectPropertyAttributeSymbol) { return; } From 8e3f7676322ffb2a8acab7855d6b32398596b6fd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 18 Oct 2024 18:41:10 -0700 Subject: [PATCH 43/46] Do not warn for valid generated properties --- .../CanvasEffectPropertyGenerator.cs | 2 +- ...CanvasEffectPropertyDeclarationAnalyzer.cs | 26 ++++++++++++++----- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs index 49c19ea3..269650a1 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -27,7 +27,7 @@ public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerato /// /// The name of generator to include in the generated code. /// - private const string GeneratorName = + internal const string GeneratorName = #if WINDOWS_UWP "ComputeSharp.D2D1.Uwp.CanvasEffectPropertyGenerator"; #else diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs index 5ece0ec7..3875dcae 100644 --- a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs @@ -42,8 +42,9 @@ public sealed class InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer : Di context.RegisterCompilationStartAction(static context => { - // Get the [GeneratedCanvasEffectProperty] symbols - if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not { } generatedCanvasEffectPropertyAttributeSymbol) + // Get the [GeneratedCanvasEffectProperty] and [GeneratedCode] symbols + if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not { } generatedCanvasEffectPropertyAttributeSymbol || + context.Compilation.GetTypeByMetadataName("System.CodeDom.Compiler.GeneratedCodeAttribute") is not { } generatedCodeAttributeSymbol) { return; } @@ -71,13 +72,24 @@ public sealed class InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer : Di context.Symbol)); } - // Emit an error if the property is not a partial definition with no implementation + // Emit an error if the property is not a partial definition with no implementation... if (propertySymbol is not { IsPartialDefinition: true, PartialImplementationPart: null }) { - context.ReportDiagnostic(Diagnostic.Create( - InvalidGeneratedCanvasEffectPropertyDeclarationIsNotIncompletePartialDefinition, - generatedCanvasEffectPropertyAttribute.GetLocation(), - context.Symbol)); + // ...But only if it wasn't actually generated by the [GeneratedCanvasEffectProperty] generator. + bool isImplementationAllowed = + propertySymbol is { IsPartialDefinition: true, PartialImplementationPart: IPropertySymbol implementationPartSymbol } && + implementationPartSymbol.TryGetAttributeWithType(generatedCodeAttributeSymbol, out AttributeData? generatedCodeAttributeData) && + generatedCodeAttributeData.TryGetConstructorArgument(0, out string? toolName) && + toolName == CanvasEffectPropertyGenerator.GeneratorName; + + // Emit the diagnostic only for cases that were not valid generator outputs + if (!isImplementationAllowed) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidGeneratedCanvasEffectPropertyDeclarationIsNotIncompletePartialDefinition, + generatedCanvasEffectPropertyAttribute.GetLocation(), + context.Symbol)); + } } // Emit an error if the property returns a value by ref From bc4768a37a05338ca386815343a80f04c10e1aab Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 18 Oct 2024 18:41:25 -0700 Subject: [PATCH 44/46] Add analyzer unit test for generated property --- ...CanvasEffectPropertyGenerator_Analyzers.cs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs index 7489ecf7..72ff0814 100644 --- a/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs @@ -107,6 +107,26 @@ public class Test_CanvasEffectPropertyGenerator_Analyzers await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); } + [TestMethod] + public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_PartialPropertyWithImplementation_GeneratedByGenerator_DoesNotWarn() + { + const string source = """ + using System.CodeDom.Compiler; + using ComputeSharp.D2D1.WinUI; + + public abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public partial int Number { get; set; } + + [GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", "1.0.0")] + public partial int Number { get => 42; set { } } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); + } + [TestMethod] public async Task InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer_PartialPropertyImplementationPart_Warns() { From 71ecea9c721fde0a562d0b535bde7cfd174d6be1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 18 Oct 2024 18:44:13 -0700 Subject: [PATCH 45/46] Add .targets for source generators to UWP package --- .../ComputeSharp.D2D1.Uwp.targets | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.targets diff --git a/src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.targets b/src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.targets new file mode 100644 index 00000000..976c3a7c --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.targets @@ -0,0 +1,55 @@ + + + + + + <_ComputeSharpD2D1UwpAnalyzer Include="@(Analyzer)" Condition="'%(Analyzer.NuGetPackageId)' == 'ComputeSharp.D2D1.Uwp'" /> + + + + + + + + + + + + + + + @(ComputeSharpD2D1UwpCurrentCompilerAssemblyIdentity->'%(Version)') + + + true + + + + + + + + + + + + + + + + + + + + From 1fadf95197ee0d35345afe8680243e9ccb14809f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 20 Oct 2024 21:36:17 -0700 Subject: [PATCH 46/46] Move new attribute type to shared project --- .../Attributes/GeneratedCanvasEffectPropertyAttribute.cs | 4 ++++ src/ComputeSharp.D2D1.UI/ComputeSharp.D2D1.UI.projitems | 1 + 2 files changed, 5 insertions(+) rename src/{ComputeSharp.D2D1.WinUI => ComputeSharp.D2D1.UI}/Attributes/GeneratedCanvasEffectPropertyAttribute.cs (97%) diff --git a/src/ComputeSharp.D2D1.WinUI/Attributes/GeneratedCanvasEffectPropertyAttribute.cs b/src/ComputeSharp.D2D1.UI/Attributes/GeneratedCanvasEffectPropertyAttribute.cs similarity index 97% rename from src/ComputeSharp.D2D1.WinUI/Attributes/GeneratedCanvasEffectPropertyAttribute.cs rename to src/ComputeSharp.D2D1.UI/Attributes/GeneratedCanvasEffectPropertyAttribute.cs index 48ead4d1..3fee1203 100644 --- a/src/ComputeSharp.D2D1.WinUI/Attributes/GeneratedCanvasEffectPropertyAttribute.cs +++ b/src/ComputeSharp.D2D1.UI/Attributes/GeneratedCanvasEffectPropertyAttribute.cs @@ -1,6 +1,10 @@ using System; +#if WINDOWS_UWP +namespace ComputeSharp.D2D1.Uwp; +#else namespace ComputeSharp.D2D1.WinUI; +#endif /// /// An attribute that indicates that a given property represents an effect property, which should invalidate the effect. diff --git a/src/ComputeSharp.D2D1.UI/ComputeSharp.D2D1.UI.projitems b/src/ComputeSharp.D2D1.UI/ComputeSharp.D2D1.UI.projitems index 48baaaa1..16b740b2 100644 --- a/src/ComputeSharp.D2D1.UI/ComputeSharp.D2D1.UI.projitems +++ b/src/ComputeSharp.D2D1.UI/ComputeSharp.D2D1.UI.projitems @@ -23,6 +23,7 @@ +