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] diff --git a/ComputeSharp.sln b/ComputeSharp.sln index ecce3d87..9be35f87 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -178,6 +178,14 @@ 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 +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 +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 @@ -502,6 +510,30 @@ 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 + {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 + {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 @@ -542,6 +574,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} @@ -559,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 @@ -569,6 +604,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 @@ -577,5 +613,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/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 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.UI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs new file mode 100644 index 00000000..5ad3b1ef --- /dev/null +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.Execute.cs @@ -0,0 +1,241 @@ +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 +{ + /// + /// 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 } 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; + } + + // 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; + } + + /// + /// 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. + /// + /// 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; + } + + 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) + { + string oldValueTypeNameAsNullable = GetOldValueTypeNameAsNullable(propertyInfo); + + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine($$""" + {{GetExpressionWithTrailingSpace(propertyInfo.DeclaredAccessibility)}}partial {{propertyInfo.TypeNameWithNullabilityAnnotations}} {{propertyInfo.PropertyName}} + { + {{GetExpressionWithTrailingSpace(propertyInfo.GetterAccessibility)}}get => field; + {{GetExpressionWithTrailingSpace(propertyInfo.SetterAccessibility)}}set + { + if (global::System.Collections.Generic.EqualityComparer<{{oldValueTypeNameAsNullable}}>.Default.Equals(field, value)) + { + return; + } + + {{oldValueTypeNameAsNullable}} 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(global::ComputeSharp.D2D1.WinUI.CanvasEffectInvalidationType.{{propertyInfo.InvalidationType}}); + } + } + """, 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(skipIfPresent: true); + 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);"); + + string oldValueTypeNameAsNullable = GetOldValueTypeNameAsNullable(propertyInfo); + + // 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.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs new file mode 100644 index 00000000..269650a1 --- /dev/null +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/CanvasEffectPropertyGenerator.cs @@ -0,0 +1,143 @@ +#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; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +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. +/// +[Generator(LanguageNames.CSharp)] +public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerator +{ + /// + /// The name of generator to include in the generated code. + /// + internal const string GeneratorName = +#if WINDOWS_UWP + "ComputeSharp.D2D1.Uwp.CanvasEffectPropertyGenerator"; +#else + "ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator"; +#endif + + /// + public void Initialize(IncrementalGeneratorInitializationContext context) + { + IncrementalValuesProvider propertyInfo = + context.SyntaxProvider + .ForAttributeWithMetadataName( + WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute, + 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) + { + return default; + } + + // Ensure that the property declaration is a partial definition with no implementation + if (propertySymbol is not { IsPartialDefinition: true, PartialImplementationPart: null }) + { + 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(WellKnownTypeNames.CanvasEffect)) + { + return default; + } + + 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(); + + 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). + bool isReferenceTypeOrUnconstraindTypeParameter = !propertySymbol.Type.IsValueType; + + // Finally, get the hierarchy too + HierarchyInfo hierarchyInfo = HierarchyInfo.From(typeSymbol); + + token.ThrowIfCancellationRequested(); + + return new CanvasEffectPropertyInfo( + Hierarchy: hierarchyInfo, + PropertyName: propertySymbol.Name, + DeclaredAccessibility: declaredAccessibility, + GetterAccessibility: getterAccessibility, + SetterAccessibility: setterAccessibility, + TypeNameWithNullabilityAnnotations: typeNameWithNullabilityAnnotations, + 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) + .WithTrackingName(WellKnownTrackingNames.Output); + + // 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.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems b/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems new file mode 100644 index 00000000..b21e1a36 --- /dev/null +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/ComputeSharp.D2D1.UI.SourceGenerators.projitems @@ -0,0 +1,23 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + d20e610f-eb37-46e7-b028-04784d7400d5 + + + ComputeSharp.D2D1.UI.SourceGenerators + + + + + + + + + + + + + + \ No newline at end of file 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 + + + + + + + + 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 new file mode 100644 index 00000000..41489bab --- /dev/null +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs @@ -0,0 +1,70 @@ +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; +#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. +/// +[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(WellKnownTypeNames.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; + } + + // 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)) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidGeneratedCanvasEffectPropertyAccessors, + generatedCanvasEffectPropertyAttribute.GetLocation(), + context.Symbol)); + } + }, SymbolKind.Property); + }); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs new file mode 100644 index 00000000..bedd55d5 --- /dev/null +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs @@ -0,0 +1,71 @@ +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; +#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. +/// +[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(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not { } generatedCanvasEffectPropertyAttributeSymbol || + context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.CanvasEffect) is not { } canvasEffectSymbol) + { + return; + } + + context.RegisterSymbolAction(context => + { + // Validate that we have a valid containing type (also skip implementation parts) + if (context.Symbol is not IPropertySymbol { ContainingType: { } containingTypeSymbol, PartialDefinitionPart: null }) + { + 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.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs new file mode 100644 index 00000000..3875dcae --- /dev/null +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs @@ -0,0 +1,115 @@ +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; +#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. +/// +[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] and [GeneratedCode] symbols + if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.GeneratedCanvasEffectPropertyAttribute) is not { } generatedCanvasEffectPropertyAttributeSymbol || + context.Compilation.GetTypeByMetadataName("System.CodeDom.Compiler.GeneratedCodeAttribute") is not { } generatedCodeAttributeSymbol) + { + return; + } + + context.RegisterSymbolAction(context => + { + // Ensure that we have some target property to analyze (also skip implementation parts) + if (context.Symbol is not IPropertySymbol { PartialDefinitionPart: null } 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 }) + { + // ...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 + 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.UI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs new file mode 100644 index 00000000..dead1781 --- /dev/null +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/Analyzers/RequireCSharpLanguageVersionPreviewAnalyzer.cs @@ -0,0 +1,70 @@ +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; +#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. +/// +[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(WellKnownTypeNames.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.UI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs new file mode 100644 index 00000000..64e1c2f0 --- /dev/null +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -0,0 +1,145 @@ +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. + /// + /// 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: $"{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: 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).", + 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: $"{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: 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).", + 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: $"{DiagnosticIdPrefix}0003", + title: "Invalid generated CanvasEffect property declaration (static member)", + messageFormat: """The property "{0}" is static ([GeneratedCanvasEffectProperty] must be used on instance properties)""", + category: DiagnosticCategory, + 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: $"{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: 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).", + 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: $"{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: 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).", + 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: $"{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: 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).", + 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: $"{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: 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).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.UI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs b/src/ComputeSharp.D2D1.UI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs new file mode 100644 index 00000000..3116543b --- /dev/null +++ b/src/ComputeSharp.D2D1.UI.SourceGenerators/Models/CanvasEffectPropertyInfo.cs @@ -0,0 +1,29 @@ +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. +/// +/// The hierarchy info for the shader type. +/// 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); diff --git a/src/ComputeSharp.D2D1.UI/Attributes/GeneratedCanvasEffectPropertyAttribute.cs b/src/ComputeSharp.D2D1.UI/Attributes/GeneratedCanvasEffectPropertyAttribute.cs new file mode 100644 index 00000000..3fee1203 --- /dev/null +++ b/src/ComputeSharp.D2D1.UI/Attributes/GeneratedCanvasEffectPropertyAttribute.cs @@ -0,0 +1,69 @@ +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. +/// 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 diff --git a/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs b/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs index 00b24c07..31905e32 100644 --- a/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs +++ b/src/ComputeSharp.D2D1.UI/CanvasEffectInvalidationType.cs @@ -1,5 +1,7 @@ +#if !D2D1_UI_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.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 @@ + 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..8c38544e --- /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 +--------|----------|----------|------- +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/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..2500e683 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp.SourceGenerators/ComputeSharp.D2D1.Uwp.SourceGenerators.csproj @@ -0,0 +1,21 @@ + + + netstandard2.0 + $(DefineConstants);WINDOWS_UWP;D2D1_UI_SOURCE_GENERATOR + + + $(NoWarn);CS1574 + + + + + + + + + + + + + + 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 + + + + + + + + + + + + + + + + + + + + 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..a67085fd --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI.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.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 new file mode 100644 index 00000000..1781f0d7 --- /dev/null +++ b/src/ComputeSharp.D2D1.WinUI.SourceGenerators/ComputeSharp.D2D1.WinUI.SourceGenerators.csproj @@ -0,0 +1,21 @@ + + + netstandard2.0 + $(DefineConstants);D2D1_UI_SOURCE_GENERATOR + + + $(NoWarn);CS1574 + + + + + + + + + + + + + + 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..e178811f --- /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 + + + + + + + + + + + + + + + + + + + + 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.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..b68d6000 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -9,16 +9,20 @@ 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/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 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.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..687fabdc 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/ITypeSymbolExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/ITypeSymbolExtensions.cs @@ -44,6 +44,52 @@ 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 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. /// 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; + }); + } +} 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]"""); + } } } 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 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 @@ - + 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, 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..eff9423e --- /dev/null +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators.csproj @@ -0,0 +1,32 @@ + + + net8.0-windows10.0.22621.0 + 10.0.17763.0 + 10.0.22621.39 + x64;ARM64 + win-x64;win-arm64 + $(DefineConstants);D2D1_WINUI_TESTS + + + + + + + + + + + + + + + + + + + + + + + + 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..6597d5ac --- /dev/null +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator.cs @@ -0,0 +1,500 @@ +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; + +[TestClass] +public class Test_CanvasEffectPropertyGenerator +{ + [TestMethod] + public void SingleProperty() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + namespace MyNamespace; + + public abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public partial int Number { get; set; } + } + """; + + const string result = """" + // + #pragma warning disable + + namespace MyNamespace + { + /// + partial class MyEffect + { + /// + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] + [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", )] + 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", )] + 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", )] + 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", )] + partial void OnNumberChanged(int oldValue, int newValue); + } + } + """"; + + VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result)); + } + + [TestMethod] + public void SingleProperty_WithNullabilityAnnotations() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + namespace MyNamespace; + + public abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public partial object? Instance { get; set; } + } + """; + + const string result = """" + // + #pragma warning disable + + namespace MyNamespace + { + /// + partial class MyEffect + { + /// + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] + [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", )] + 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", )] + 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", )] + 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", )] + partial void OnInstanceChanged(object? oldValue, object? newValue); + } + } + """"; + + VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result)); + } + + [TestMethod] + public void SingleProperty_WithNotNullableReferenceType() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + namespace MyNamespace; + + public abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public partial object Instance { get; set; } + } + """; + + const string result = """" + // + #pragma warning disable + + namespace MyNamespace + { + /// + partial class MyEffect + { + /// + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] + [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", )] + 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", )] + 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", )] + 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", )] + partial void OnInstanceChanged(object? oldValue, object newValue); + } + } + """"; + + VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result)); + } + + [TestMethod] + public void SingleProperty_WithCustomAccessorVisibility() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + namespace MyNamespace; + + public abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public partial 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", )] + [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", )] + 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", )] + 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", )] + 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", )] + partial void OnNumberChanged(int oldValue, int newValue); + } + } + """"; + + VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result)); + } + + [TestMethod] + public void MultipleProperties() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + namespace MyNamespace; + + public abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public partial int X { get; set; } + + [GeneratedCanvasEffectProperty(CanvasEffectInvalidationType.Creation)] + public partial int Y { get; set; } + } + """; + + const string result = """" + // + #pragma warning disable + + namespace MyNamespace + { + /// + partial class MyEffect + { + /// + [global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", )] + [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", )] + [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.Creation); + } + } + + /// 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", )] + 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", )] + 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", )] + 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", )] + 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", )] + 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", )] + 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", )] + 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", )] + partial void OnYChanged(int oldValue, int newValue); + } + } + """"; + + VerifyGeneratedDiagnostics(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 void VerifyGeneratedDiagnostics(string source, (string Filename, string 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 new file mode 100644 index 00000000..72ff0814 --- /dev/null +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Analyzers.cs @@ -0,0 +1,230 @@ +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; + +[TestClass] +public class Test_CanvasEffectPropertyGenerator_Analyzers +{ + [TestMethod] + public async Task InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer_NoBaseType_Warns() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + public partial class MyEffect + { + [{|CMPSD2DWINUI0001:GeneratedCanvasEffectProperty|}] + public partial int {|CS9248:Number|} { get; set; } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); + } + + [TestMethod] + public async Task InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer_ReadOnlyProperty_Warns() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + public partial class MyEffect + { + [{|CMPSD2DWINUI0002:GeneratedCanvasEffectProperty|}] + public partial int {|CS9248:Number|} { get; } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview); + } + + [TestMethod] + public async Task InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer_InitOnlyProperty_Warns() + { + const string source = """ + using ComputeSharp.D2D1.WinUI; + + public abstract partial class MyEffect : CanvasEffect + { + [{|CMPSD2DWINUI0002:GeneratedCanvasEffectProperty|}] + public partial int {|CS9248:Number|} { get; init; } + } + """; + + 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_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() + { + 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); + } + + [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 new file mode 100644 index 00000000..2248b818 --- /dev/null +++ b/tests/ComputeSharp.D2D1.WinUI.Tests.SourceGenerators/Test_CanvasEffectPropertyGenerator_Incrementality.cs @@ -0,0 +1,120 @@ +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; + +[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 partial int Number { get; set; } + } + """"; + + const string updatedSource = """" + using ComputeSharp.D2D1.WinUI; + + abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty(CanvasEffectInvalidationType.Creation)] + public partial int Number { get; set; } + } + """"; + + CSharpGeneratorTest.VerifyIncrementalSteps( + source, + updatedSource, + executeReason: IncrementalStepRunReason.Modified, + diagnosticsReason: null, + outputReason: IncrementalStepRunReason.Modified, + diagnosticsSourceReason: null, + sourceReason: IncrementalStepRunReason.Modified, + languageVersion: LanguageVersion.Preview); + } + + [TestMethod] + public void AddedLeadingTrivia_DoesNotModifyOutput() + { + const string source = """" + using ComputeSharp.D2D1.WinUI; + + abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public partial int Number { get; set; } + } + """"; + + const string updatedSource = """" + using ComputeSharp.D2D1.WinUI; + + abstract partial class MyEffect : CanvasEffect + { + /// + /// This is some property. + /// + [GeneratedCanvasEffectProperty] + public partial int Number { get; set; } + } + """"; + + CSharpGeneratorTest.VerifyIncrementalSteps( + source, + updatedSource, + executeReason: IncrementalStepRunReason.Unchanged, + diagnosticsReason: null, + outputReason: IncrementalStepRunReason.Cached, + diagnosticsSourceReason: null, + sourceReason: IncrementalStepRunReason.Cached, + languageVersion: LanguageVersion.Preview); + } + + [TestMethod] + public void AddedOtherMember_DoesNotModifyOutput() + { + const string source = """" + using ComputeSharp.D2D1.WinUI; + + abstract partial class MyEffect : CanvasEffect + { + [GeneratedCanvasEffectProperty] + public partial int Number { get; set; } + } + """"; + + const string updatedSource = """" + using ComputeSharp.D2D1.WinUI; + + abstract partial class MyEffect : CanvasEffect + { + public void Foo() + { + } + + [GeneratedCanvasEffectProperty] + public partial int Number { get; set; } + } + """"; + + CSharpGeneratorTest.VerifyIncrementalSteps( + source, + updatedSource, + executeReason: IncrementalStepRunReason.Unchanged, + diagnosticsReason: null, + outputReason: IncrementalStepRunReason.Cached, + diagnosticsSourceReason: null, + sourceReason: IncrementalStepRunReason.Cached, + languageVersion: LanguageVersion.Preview); + } +} \ No newline at end of file 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..1d29bfaf 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; @@ -54,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); @@ -79,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, @@ -86,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()], @@ -100,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); @@ -168,25 +174,29 @@ 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 = [ .. 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) #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( @@ -202,12 +212,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);