Merge pull request #813 from Sergio0694/dev/generated-canvas-effect-property

Add [GeneratedCanvasEffectProperty] generator and analyzers
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2024-10-20 21:53:37 -07:00
コミット c2bc4e45a5
45ファイル変更
+2412 -56

検索条件に一致するファイルはありません

+12 -1
ファイルの表示
@@ -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]
+38
ファイルの表示
@@ -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
+12
ファイルの表示
@@ -43,4 +43,16 @@
<AutoGen>True</AutoGen>
</Compile>
</ItemGroup>
<!--
Setting this property is needed as a temporary workaround for an MSBuild bug triggered by WinAppSDK,
around 'GetReferenceTargetPlatformMonikers'. That target is currently producing multiple items and breaking
the build (in particular here it causes aliases to be lost/overwritten, and to ignore some attributes such
as 'PrivateAssets', causing potential type collisions across different projects) when compiling projects.
This can be removed once the bug is fixed in MSBuild and the tooling is updated here (likely VS 17.12).
See: https://github.com/dotnet/msbuild/pull/10220.
-->
<PropertyGroup>
<FindInvalidProjectReferences>false</FindInvalidProjectReferences>
</PropertyGroup>
</Project>
+2 -2
ファイルの表示
@@ -944,13 +944,13 @@ partial class DiagnosticDescriptors
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for when the <c>AllowUnsafeBlocks</c> option is not set.
/// <para>
/// Format: <c>"Using [D2DGeneratedPixelShaderDescriptor] requires unsafe blocks being enabled, as they needed by the source generators to emit valid code (add &lt;AllowUnsafeBlocks&gt;true&lt;/AllowUnsafeBlocks&gt; to your .csproj/.props file)"</c>.
/// Format: <c>"Using [D2DGeneratedPixelShaderDescriptor] requires unsafe blocks being enabled, as they are needed by the source generators to emit valid code (add &lt;AllowUnsafeBlocks&gt;true&lt;/AllowUnsafeBlocks&gt; to your .csproj/.props file)"</c>.
/// </para>
/// </summary>
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 <AllowUnsafeBlocks>true</AllowUnsafeBlocks> 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 <AllowUnsafeBlocks>true</AllowUnsafeBlocks> to your .csproj/.props file)",
category: "ComputeSharp.D2D1.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
+241
ファイルの表示
@@ -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
/// <inheritdoc/>
partial class CanvasEffectPropertyGenerator
{
/// <summary>
/// A container for all the logic for <see cref="CanvasEffectPropertyGenerator"/>.
/// </summary>
private static partial class Execute
{
/// <summary>
/// Checks whether an input syntax node is a candidate property declaration for the generator.
/// </summary>
/// <param name="node">The input syntax node to check.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <returns>Whether <paramref name="node"/> is a candidate property declaration.</returns>
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<ClassDeclarationSyntax>() == true;
}
/// <summary>
/// Tries to get the accessibility of the property and accessors, if possible.
/// </summary>
/// <param name="node">The input <see cref="PropertyDeclarationSyntax"/> node.</param>
/// <param name="symbol">The input <see cref="IPropertySymbol"/> instance.</param>
/// <param name="declaredAccessibility">The accessibility of the property, if available.</param>
/// <param name="getterAccessibility">The accessibility of the <see langword="get"/> accessor, if available.</param>
/// <param name="setterAccessibility">The accessibility of the <see langword="set"/> accessor, if available.</param>
/// <returns>Whether the property was valid and the accessibilities could be retrieved.</returns>
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;
}
/// <summary>
/// Gets the invalidation type to use for the generated effect property.
/// </summary>
/// <param name="attributeData">The <see cref="AttributeData"/> instance for the processed attribute.</param>
/// <returns>The resulting <see cref="CanvasEffectInvalidationType"/> to use for the generated property.</returns>
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<CanvasEffectPropertyInfo> 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("/// <inheritdoc/>");
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)
{
// On<PROPERTY_NAME>Changing, only with new value
writer.WriteLine(skipIfPresent: true);
writer.WriteLine($"""
/// <summary>Executes the logic for when <see cref="{propertyInfo.PropertyName}"/> is changing.</summary>
/// <param name="value">The new property value being set.</param>
/// <remarks>This method is invoked right before the value of <see cref="{propertyInfo.PropertyName}"/> is changed.</remarks>
""", isMultiline: true);
writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false);
writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changing({propertyInfo.TypeNameWithNullabilityAnnotations} newValue);");
string oldValueTypeNameAsNullable = GetOldValueTypeNameAsNullable(propertyInfo);
// On<PROPERTY_NAME>Changing, with both values
writer.WriteLine();
writer.WriteLine($"""
/// <summary>Executes the logic for when <see cref="{propertyInfo.PropertyName}"/> is changing.</summary>
/// <param name="oldValue">The previous property value that is being replaced.</param>
/// <param name="newValue">The new property value being set.</param>
/// <remarks>This method is invoked right before the value of <see cref="{propertyInfo.PropertyName}"/> is changed.</remarks>
""", isMultiline: true);
writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false);
writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changing({oldValueTypeNameAsNullable} oldValue, {propertyInfo.TypeNameWithNullabilityAnnotations} newValue);");
// On<PROPERTY_NAME>Changed, only with new value
writer.WriteLine();
writer.WriteLine($"""
/// <summary>Executes the logic for when <see cref="{propertyInfo.PropertyName}"/> has just changed.</summary>
/// <param name="value">The new property value that has been set.</param>
/// <remarks>This method is invoked right after the value of <see cref="{propertyInfo.PropertyName}"/> is changed.</remarks>
""", isMultiline: true);
writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false);
writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changed({propertyInfo.TypeNameWithNullabilityAnnotations} newValue);");
// On<PROPERTY_NAME>Changed, with both values
writer.WriteLine();
writer.WriteLine($"""
/// <summary>Executes the logic for when <see cref="{propertyInfo.PropertyName}"/> has just changed.</summary>
/// <param name="oldValue">The previous property value that has been replaced.</param>
/// <param name="newValue">The new property value that has been set.</param>
/// <remarks>This method is invoked right after the value of <see cref="{propertyInfo.PropertyName}"/> is changed.</remarks>
""", isMultiline: true);
writer.WriteGeneratedAttributes(GeneratorName, includeNonUserCodeAttributes: false);
writer.WriteLine($"partial void On{propertyInfo.PropertyName}Changed({oldValueTypeNameAsNullable} oldValue, {propertyInfo.TypeNameWithNullabilityAnnotations} newValue);");
}
}
}
}
+143
ファイルの表示
@@ -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
/// <summary>
/// A source generator creating implementations of effect properties.
/// </summary>
[Generator(LanguageNames.CSharp)]
public sealed partial class CanvasEffectPropertyGenerator : IIncrementalGenerator
{
/// <summary>
/// The name of generator to include in the generated code.
/// </summary>
internal const string GeneratorName =
#if WINDOWS_UWP
"ComputeSharp.D2D1.Uwp.CanvasEffectPropertyGenerator";
#else
"ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator";
#endif
/// <inheritdoc/>
public void Initialize(IncrementalGeneratorInitializationContext context)
{
IncrementalValuesProvider<CanvasEffectPropertyInfo> 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<CanvasEffectPropertyInfo> 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());
});
}
}
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<MSBuildAllProjects Condition="'$(MSBuildVersion)' == '' Or '$(MSBuildVersion)' &lt; '16.0'">$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
<HasSharedItems>true</HasSharedItems>
<SharedGUID>d20e610f-eb37-46e7-b028-04784d7400d5</SharedGUID>
</PropertyGroup>
<PropertyGroup Label="Configuration">
<Import_RootNamespace>ComputeSharp.D2D1.UI.SourceGenerators</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)CanvasEffectPropertyGenerator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CanvasEffectPropertyGenerator.Execute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Constants\WellKnownTypeNames.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\RequireCSharpLanguageVersionPreviewAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\DiagnosticDescriptors.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\CanvasEffectPropertyInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\ComputeSharp.D2D1.UI\CanvasEffectInvalidationType.cs" Link="ComputeSharp.D2D1.UI\CanvasEffectInvalidationType.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<ProjectGuid>d20e610f-eb37-46e7-b028-04784d7400d5</ProjectGuid>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
<PropertyGroup />
<Import Project="ComputeSharp.D2D1.UI.SourceGenerators.projitems" Label="Shared" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
</Project>
+31
ファイルの表示
@@ -0,0 +1,31 @@
#if WINDOWS_UWP
namespace ComputeSharp.D2D1.Uwp.SourceGenerators.Constants;
#else
namespace ComputeSharp.D2D1.WinUI.SourceGenerators.Constants;
#endif
/// <summary>
/// The well known names for types used by source generators and analyzers.
/// </summary>
internal static class WellKnownTypeNames
{
/// <summary>
/// The fully qualified type name for the <c>[GeneratedCanvasEffectPropertyAttribute]</c> type.
/// </summary>
public const string GeneratedCanvasEffectPropertyAttribute =
#if WINDOWS_UWP
"ComputeSharp.D2D1.Uwp.GeneratedCanvasEffectPropertyAttribute";
#else
"ComputeSharp.D2D1.WinUI.GeneratedCanvasEffectPropertyAttribute";
#endif
/// <summary>
/// The fully qualified type name for the <c>[CanvasEffect]</c> type.
/// </summary>
public const string CanvasEffect =
#if WINDOWS_UWP
"ComputeSharp.D2D1.Uwp.CanvasEffect";
#else
"ComputeSharp.D2D1.WinUI.CanvasEffect";
#endif
}
@@ -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
/// <summary>
/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] has invalid accessors.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer : DiagnosticAnalyzer
{
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidGeneratedCanvasEffectPropertyAccessors];
/// <inheritdoc/>
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);
});
}
}
@@ -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
/// <summary>
/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] is in an invalid type.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer : DiagnosticAnalyzer
{
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [InvalidGeneratedCanvasEffectPropertyContainingType];
/// <inheritdoc/>
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);
});
}
}
@@ -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
/// <summary>
/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] has invalid accessors.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer : DiagnosticAnalyzer
{
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
[
InvalidGeneratedCanvasEffectPropertyDeclarationIsStatic,
InvalidGeneratedCanvasEffectPropertyDeclarationIsNotIncompletePartialDefinition,
InvalidGeneratedCanvasEffectPropertyDeclarationReturnsByRef,
InvalidGeneratedCanvasEffectPropertyDeclarationReturnsRefLikeType
];
/// <inheritdoc/>
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);
});
}
}
@@ -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
/// <summary>
/// A diagnostic analyzer that generates errors when a property using [GeneratedCanvasEffectProperty] is in a project with the C# language version not set to preview.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class RequireCSharpLanguageVersionPreviewAnalyzer : DiagnosticAnalyzer
{
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = [CSharpLanguageVersionIsNotPreview];
/// <inheritdoc/>
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);
});
}
}
+145
ファイルの表示
@@ -0,0 +1,145 @@
using Microsoft.CodeAnalysis;
#if WINDOWS_UWP
namespace ComputeSharp.D2D1.Uwp.SourceGenerators;
#else
namespace ComputeSharp.D2D1.WinUI.SourceGenerators;
#endif
/// <summary>
/// A container for all <see cref="DiagnosticDescriptor"/> instances for errors reported by analyzers in this project.
/// </summary>
internal static class DiagnosticDescriptors
{
/// <summary>
/// The prefix of all diagnostics for available analyzers.
/// </summary>
private const string DiagnosticIdPrefix =
#if WINDOWS_UWP
"CMPSD2DUWP";
#else
"CMPSD2DWINUI";
#endif
/// <summary>
/// The category of all diagnostics for available analyzers.
/// </summary>
private const string DiagnosticCategory =
#if WINDOWS_UWP
"ComputeSharp.D2D1.Uwp.Effects";
#else
"ComputeSharp.D2D1.WinUI.Effects";
#endif
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid CanvasEffect property.
/// <para>
/// Format: <c>"The property "{0}" is not in a type that derives from CanvasEffect ([GeneratedCanvasEffectProperty] must be used in effect types that extend CanvasEffect)"</c>.
/// </para>
/// </summary>
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");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a CanvasEffect property with invalid accessors.
/// <para>
/// Format: <c>"The property "{0}" does not have a getter and a setter ([GeneratedCanvasEffectProperty] must be used on properties with get and set accessors)"</c>.
/// </para>
/// </summary>
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");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a static CanvasEffect property.
/// <para>
/// Format: <c>"The property "{0}" is static ([GeneratedCanvasEffectProperty] must be used on instance properties)"</c>.
/// </para>
/// </summary>
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");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a CanvasEffect property with invalid accessors.
/// <para>
/// Format: <c>"The property "{0}" is not an incomplete partial definition ([GeneratedCanvasEffectProperty] must be used on partial property definitions with no implementation part)"</c>.
/// </para>
/// </summary>
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");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a CanvasEffect property with invalid accessors.
/// <para>
/// Format: <c>"The property "{0}" returns a value by reference ([GeneratedCanvasEffectProperty] must be used on properties returning a type by value)"</c>.
/// </para>
/// </summary>
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");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a CanvasEffect property with invalid accessors.
/// <para>
/// Format: <c>"The property "{0}" returns a ref struct value ([GeneratedCanvasEffectProperty] must be used on properties with a type that is not a ref struct)"</c>.
/// </para>
/// </summary>
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");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a CanvasEffect property with invalid accessors.
/// <para>
/// Format: <c>"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 &lt;LangVersion&gt;preview&lt;/LangVersion&gt; to your .csproj/.props file)"</c>.
/// </para>
/// </summary>
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 <LangVersion>preview</LangVersion> 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 <LangVersion>preview</LangVersion> option must be set in the .csproj/.props file).",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
}
+29
ファイルの表示
@@ -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
/// <summary>
/// A model representing a generated canvas effect property.
/// </summary>
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
/// <param name="PropertyName">The generated property name.</param>
/// <param name="DeclaredAccessibility">The accessibility of the property, if available.</param>
/// <param name="GetterAccessibility">The accessibility of the <see langword="get"/> accessor, if available.</param>
/// <param name="SetterAccessibility">The accessibility of the <see langword="set"/> accessor, if available.</param>
/// <param name="TypeNameWithNullabilityAnnotations">The type name for the generated property, including nullability annotations.</param>
/// <param name="IsReferenceTypeOrUnconstraindTypeParameter">Indicates whether the property is of a reference type or an unconstrained type parameter.</param>
/// <param name="InvalidationType">The invalidation type to request.</param>
internal sealed record CanvasEffectPropertyInfo(
HierarchyInfo Hierarchy,
string PropertyName,
Accessibility DeclaredAccessibility,
Accessibility GetterAccessibility,
Accessibility SetterAccessibility,
string TypeNameWithNullabilityAnnotations,
bool IsReferenceTypeOrUnconstraindTypeParameter,
CanvasEffectInvalidationType InvalidationType);
+69
ファイルの表示
@@ -0,0 +1,69 @@
using System;
#if WINDOWS_UWP
namespace ComputeSharp.D2D1.Uwp;
#else
namespace ComputeSharp.D2D1.WinUI;
#endif
/// <summary>
/// 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 <see cref="CanvasEffect"/>.
/// <para>
/// This attribute can be used as follows:
/// <code>
/// partial class MyEffect : CanvasEffect
/// {
/// [GeneratedCanvasEffectProperty]
/// public int BlurAmount { get; set; }
/// }
/// </code>
/// </para>
/// And with this, code analogous to this will be generated:
/// <code>
/// partial class MyEffect
/// {
/// public partial int BlurAmount
/// {
/// get => field;
/// set
/// {
/// if (EqualityComparer&lt;int&gt;.Default.Equals(field, value))
/// {
/// return;
/// }
///
/// int oldValue = field;
///
/// OnBlurAmountChanging(value);
/// OnBlurAmountChanging(oldValue, value);
///
/// field = value;
///
/// OnBlurAmountChanged(value);
/// OnBlurAmountChanged(oldValue, value);
///
/// InvalidateEffectGraph(&lt;INVALIDATION_TYPE&gt;);
/// }
/// }
///
/// partial void OnBlurAmountChanging(int newValue);
/// partial void OnBlurAmountChanging(int oldValue, int newValue);
/// partial void OnBlurAmountChanged(int newValue);
/// partial void OnBlurAmountChanged(int oldValue, int newValue);
/// }
/// </code>
/// </summary>
/// <param name="invalidationType">The invalidation type to request.</param>
/// <remarks>
/// The generated <c>OnChanging</c> and <c>OnChanged</c> methods will be completely removed by
/// the compiler if an implementation for the is not provided, making them fully pay-for-play.
/// </remarks>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class GeneratedCanvasEffectPropertyAttribute(CanvasEffectInvalidationType invalidationType = CanvasEffectInvalidationType.Update) : Attribute
{
/// <summary>
/// Gets the requested invalidation type for the effect graph when changing the proprty value.
/// </summary>
public CanvasEffectInvalidationType InvalidationType { get; } = invalidationType;
}
+2
ファイルの表示
@@ -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;
+1
ファイルの表示
@@ -23,6 +23,7 @@
<Compile Include="$(MSBuildThisFileDirectory)ABI.Microsoft.Graphics.Canvas\Win2D.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ABI.Microsoft.Graphics.Canvas\WIN2D_GET_D2D_IMAGE_FLAGS.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ABI.Microsoft.Graphics.Canvas\WIN2D_GET_DEVICE_ASSOCIATION_TYPE.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Attributes\GeneratedCanvasEffectPropertyAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Buffers\GraphicsEffectSourceBuffer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Buffers\ResourceTextureManagerBuffer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Buffers\SourceReference.cs" />
+16
ファイルの表示
@@ -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)
+2
ファイルの表示
@@ -0,0 +1,2 @@
; Unshipped analyzer release
; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<DefineConstants>$(DefineConstants);WINDOWS_UWP;D2D1_UI_SOURCE_GENERATOR</DefineConstants>
<!-- Same suppression as the WinUI generator -->
<NoWarn>$(NoWarn);CS1574</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.11.0" PrivateAssets="all" Pack="false" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Include="AnalyzerReleases.Shipped.md" />
<AdditionalFiles Include="AnalyzerReleases.Unshipped.md" />
</ItemGroup>
<Import Project="..\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems" Label="Shared" />
<Import Project="..\ComputeSharp.D2D1.UI.SourceGenerators\ComputeSharp.D2D1.UI.SourceGenerators.projitems" Label="Shared" />
</Project>
+55
ファイルの表示
@@ -0,0 +1,55 @@
<Project>
<!-- Get the analyzer from the ComputeSharp.D2D1.Uwp NuGet package -->
<Target Name="_ComputeSharpD2D1UwpGatherAnalyzers">
<ItemGroup>
<_ComputeSharpD2D1UwpAnalyzer Include="@(Analyzer)" Condition="'%(Analyzer.NuGetPackageId)' == 'ComputeSharp.D2D1.Uwp'" />
</ItemGroup>
</Target>
<!-- Remove the analyzer if using Roslyn < 4.11 (ComputeSharp.D2D1.Uwp's generators require Roslyn 4.11) -->
<Target Name="_ComputeSharpD2D1UwpRemoveAnalyzersForRoslyn3"
Condition="'$(CSharpCoreTargetsPath)' != ''"
AfterTargets="ResolvePackageDependenciesForBuild;ResolveNuGetPackageAssets"
DependsOnTargets="_ComputeSharpD2D1UwpGatherAnalyzers">
<!--
Use the CSharpCoreTargetsPath property to find the version of the compiler we are using. This is the same mechanism
MSBuild uses to find the compiler. We could check the assembly version for any compiler assembly (since they all have
the same version) but Microsoft.Build.Tasks.CodeAnalysis.dll is where MSBuild loads the compiler tasks from so if
someone is getting creative with msbuild tasks/targets this is the "most correct" assembly to check.
-->
<GetAssemblyIdentity AssemblyFiles="$([System.IO.Path]::Combine(`$([System.IO.Path]::GetDirectoryName($(CSharpCoreTargetsPath)))`,`Microsoft.Build.Tasks.CodeAnalysis.dll`))">
<Output TaskParameter="Assemblies" ItemName="ComputeSharpD2D1UwpCurrentCompilerAssemblyIdentity"/>
</GetAssemblyIdentity>
<PropertyGroup>
<!-- Transform the resulting item from GetAssemblyIdentity into a property representing its assembly version -->
<ComputeSharpD2D1UwpCurrentCompilerVersion>@(ComputeSharpD2D1UwpCurrentCompilerAssemblyIdentity->'%(Version)')</ComputeSharpD2D1UwpCurrentCompilerVersion>
<!-- The CurrentCompilerVersionIsNotNewEnough property can now be defined based on the Roslyn assembly version -->
<ComputeSharpD2D1UwpCurrentCompilerVersionIsNotNewEnough Condition="$([MSBuild]::VersionLessThan($(ComputeSharpD2D1UwpCurrentCompilerVersion), 4.11))">true</ComputeSharpD2D1UwpCurrentCompilerVersionIsNotNewEnough>
</PropertyGroup>
<!-- If the Roslyn version is < 4.11, disable the source generators -->
<ItemGroup Condition ="'$(ComputeSharpD2D1UwpCurrentCompilerVersionIsNotNewEnough)' == 'true'">
<Analyzer Remove="@(_ComputeSharpD2D1UwpAnalyzer)"/>
</ItemGroup>
<!-- There is no need to emit a warning here, as this package is always a transitive dependency from ComputeSharp.D2D1, which does emit the warning -->
</Target>
<!-- Remove the analyzer if Roslyn is missing -->
<Target Name="_ComputeSharpD2D1UwpRemoveAnalyzersForRosynNotFound"
Condition="'$(CSharpCoreTargetsPath)' == ''"
AfterTargets="ResolvePackageDependenciesForBuild;ResolveNuGetPackageAssets"
DependsOnTargets="_ComputeSharpD2D1UwpGatherAnalyzers">
<!-- If no Roslyn assembly could be found, just remove the analyzer without emitting a warning -->
<ItemGroup>
<Analyzer Remove="@(_ComputeSharpD2D1UwpAnalyzer)"/>
</ItemGroup>
</Target>
</Project>
+16
ファイルの表示
@@ -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)
+2
ファイルの表示
@@ -0,0 +1,2 @@
; Unshipped analyzer release
; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<DefineConstants>$(DefineConstants);D2D1_UI_SOURCE_GENERATOR</DefineConstants>
<!-- Ignore warnings for unresolved XML cref attributes (for imported types, same as in the D3D12 generator) -->
<NoWarn>$(NoWarn);CS1574</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.11.0" PrivateAssets="all" Pack="false" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Include="AnalyzerReleases.Shipped.md" />
<AdditionalFiles Include="AnalyzerReleases.Unshipped.md" />
</ItemGroup>
<Import Project="..\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems" Label="Shared" />
<Import Project="..\ComputeSharp.D2D1.UI.SourceGenerators\ComputeSharp.D2D1.UI.SourceGenerators.projitems" Label="Shared" />
</Project>
+55
ファイルの表示
@@ -0,0 +1,55 @@
<Project>
<!-- Get the analyzer from the ComputeSharp.D2D1.WinUI NuGet package -->
<Target Name="_ComputeSharpD2D1WinUIGatherAnalyzers">
<ItemGroup>
<_ComputeSharpD2D1WinUIAnalyzer Include="@(Analyzer)" Condition="'%(Analyzer.NuGetPackageId)' == 'ComputeSharp.D2D1.WinUI'" />
</ItemGroup>
</Target>
<!-- Remove the analyzer if using Roslyn < 4.11 (ComputeSharp.D2D1.WinUI's generators require Roslyn 4.11) -->
<Target Name="_ComputeSharpD2D1WinUIRemoveAnalyzersForRoslyn3"
Condition="'$(CSharpCoreTargetsPath)' != ''"
AfterTargets="ResolvePackageDependenciesForBuild;ResolveNuGetPackageAssets"
DependsOnTargets="_ComputeSharpD2D1WinUIGatherAnalyzers">
<!--
Use the CSharpCoreTargetsPath property to find the version of the compiler we are using. This is the same mechanism
MSBuild uses to find the compiler. We could check the assembly version for any compiler assembly (since they all have
the same version) but Microsoft.Build.Tasks.CodeAnalysis.dll is where MSBuild loads the compiler tasks from so if
someone is getting creative with msbuild tasks/targets this is the "most correct" assembly to check.
-->
<GetAssemblyIdentity AssemblyFiles="$([System.IO.Path]::Combine(`$([System.IO.Path]::GetDirectoryName($(CSharpCoreTargetsPath)))`,`Microsoft.Build.Tasks.CodeAnalysis.dll`))">
<Output TaskParameter="Assemblies" ItemName="ComputeSharpD2D1WinUICurrentCompilerAssemblyIdentity"/>
</GetAssemblyIdentity>
<PropertyGroup>
<!-- Transform the resulting item from GetAssemblyIdentity into a property representing its assembly version -->
<ComputeSharpD2D1WinUICurrentCompilerVersion>@(ComputeSharpD2D1WinUICurrentCompilerAssemblyIdentity->'%(Version)')</ComputeSharpD2D1WinUICurrentCompilerVersion>
<!-- The CurrentCompilerVersionIsNotNewEnough property can now be defined based on the Roslyn assembly version -->
<ComputeSharpD2D1WinUICurrentCompilerVersionIsNotNewEnough Condition="$([MSBuild]::VersionLessThan($(ComputeSharpD2D1WinUICurrentCompilerVersion), 4.11))">true</ComputeSharpD2D1WinUICurrentCompilerVersionIsNotNewEnough>
</PropertyGroup>
<!-- If the Roslyn version is < 4.11, disable the source generators -->
<ItemGroup Condition ="'$(ComputeSharpD2D1WinUICurrentCompilerVersionIsNotNewEnough)' == 'true'">
<Analyzer Remove="@(_ComputeSharpD2D1WinUIAnalyzer)"/>
</ItemGroup>
<!-- There is no need to emit a warning here, as this package is always a transitive dependency from ComputeSharp.D2D1, which does emit the warning -->
</Target>
<!-- Remove the analyzer if Roslyn is missing -->
<Target Name="_ComputeSharpD2D1WinUIRemoveAnalyzersForRosynNotFound"
Condition="'$(CSharpCoreTargetsPath)' == ''"
AfterTargets="ResolvePackageDependenciesForBuild;ResolveNuGetPackageAssets"
DependsOnTargets="_ComputeSharpD2D1WinUIGatherAnalyzers">
<!-- If no Roslyn assembly could be found, just remove the analyzer without emitting a warning -->
<ItemGroup>
<Analyzer Remove="@(_ComputeSharpD2D1WinUIAnalyzer)"/>
</ItemGroup>
</Target>
</Project>
@@ -9,7 +9,6 @@
<Import_RootNamespace>ComputeSharp.SourceGeneration.Hlsl</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Constants\WellKnownTrackingNames.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\NotAccessibleFieldTypeInGeneratedShaderDescriptorAttributeTargetAnalyzerBase.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\NotReadOnlyShaderTypeWithFieldsAnalyzerBase.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\NotAccessibleGeneratedShaderDescriptorAttributeTargetAnalyzerBase.cs" />
+2 -30
ファイルの表示
@@ -6,37 +6,9 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGeneration.Extensions;
/// <summary>
/// A <see langword="class"/> with some extension methods for C# syntax nodes.
/// </summary>
internal static class SyntaxNodeExtensions
/// <inheritdoc/>
partial class SyntaxNodeExtensions
{
/// <summary>
/// Checks whether a given <see cref="SyntaxNode"/> is a given type declaration with or potentially with any base types, using only syntax.
/// </summary>
/// <typeparam name="T">The type of declaration to check for.</typeparam>
/// <param name="node">The input <see cref="SyntaxNode"/> to check.</param>
/// <returns>Whether <paramref name="node"/> is a given type declaration with or potentially with any base types.</returns>
public static bool IsTypeDeclarationWithOrPotentiallyWithBaseTypes<T>(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);
}
/// <summary>
/// Returns a <see cref="MethodDeclarationSyntax"/> with a block body.
/// </summary>
+4
ファイルの表示
@@ -9,16 +9,20 @@
<Import_RootNamespace>ComputeSharp.SourceGeneration</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Constants\WellKnownTrackingNames.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\AccessibilityExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\AttributeDataExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\CompilationExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticsExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IMethodSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)extensions\IncrementalValueProviderExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IndentedTextWriterExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IPropertySymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IFieldSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ITypeSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SymbolInfoExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxNodeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)helpers\DynamicCache{TKey,TValue}.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\EquatableArray{T}.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\HashCode.cs" />
+28
ファイルの表示
@@ -0,0 +1,28 @@
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGeneration.Extensions;
/// <summary>
/// Extension methods for the <see cref="Accessibility"/> type.
/// </summary>
internal static class AccessibilityExtensions
{
/// <summary>
/// Gets the expression for a given <see cref="Accessibility"/> value.
/// </summary>
/// <param name="accessibility">The input <see cref="Accessibility"/> value.</param>
/// <returns>The expression for <paramref name="accessibility"/>.</returns>
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",
_ => ""
};
}
}
+10
ファイルの表示
@@ -46,6 +46,16 @@ internal static class CompilationExtensions
return true;
}
/// <summary>
/// Checks whether a given compilation (assumed to be for C#) is using the preview language version.
/// </summary>
/// <param name="compilation">The <see cref="Compilation"/> to consider for analysis.</param>
/// <returns>Whether <paramref name="compilation"/> is using the preview language version.</returns>
public static bool IsLanguageVersionPreview(this Compilation compilation)
{
return ((CSharpCompilation)compilation).LanguageVersion == LanguageVersion.Preview;
}
/// <summary>
/// Checks whether the <c>AllowUnsafeBlocks</c> option is set for a given compilation.
/// </summary>
+10
ファイルの表示
@@ -59,6 +59,16 @@ internal static class ISymbolExtensions
: symbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat);
}
/// <summary>
/// Gets the fully qualified name for a given symbol, including nullability annotations
/// </summary>
/// <param name="symbol">The input <see cref="ISymbol"/> instance.</param>
/// <returns>The fully qualified name for <paramref name="symbol"/>.</returns>
public static string GetFullyQualifiedNameWithNullabilityAnnotations(this ISymbol symbol)
{
return symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier));
}
/// <summary>
/// Checks whether or not a given symbol has an attribute with the specified type.
/// </summary>
+46
ファイルの表示
@@ -44,6 +44,52 @@ internal static class ITypeSymbolExtensions
return builder.WrittenSpan.SequenceEqual(name.AsSpan());
}
/// <summary>
/// Checks whether or not a given <see cref="ITypeSymbol"/> inherits from a specified type.
/// </summary>
/// <param name="typeSymbol">The target <see cref="ITypeSymbol"/> instance to check.</param>
/// <param name="name">The full name of the type to check for inheritance.</param>
/// <returns>Whether or not <paramref name="typeSymbol"/> inherits from <paramref name="name"/>.</returns>
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;
}
/// <summary>
/// Checks whether or not a given <see cref="ITypeSymbol"/> inherits from a specified type.
/// </summary>
/// <param name="typeSymbol">The target <see cref="ITypeSymbol"/> instance to check.</param>
/// <param name="baseTypeSymbol">The <see cref="ITypeSymbol"/> instane to check for inheritance from.</param>
/// <returns>Whether or not <paramref name="typeSymbol"/> inherits from <paramref name="baseTypeSymbol"/>.</returns>
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;
}
/// <summary>
/// Checks whether or not a given <see cref="ITypeSymbol"/> implements an interface of a specified type.
/// </summary>
+64
ファイルの表示
@@ -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;
/// <summary>
/// Extension methods for <see cref="IncrementalValuesProvider{TValues}"/>.
/// </summary>
internal static class IncrementalValuesProviderExtensions
{
/// <summary>
/// Groups items in a given <see cref="IncrementalValuesProvider{TValue}"/> sequence by a specified key.
/// </summary>
/// <typeparam name="TValues">The type of value that this source provides access to.</typeparam>
/// <typeparam name="TKey">The type of resulting key elements.</typeparam>
/// <typeparam name="TElement">The type of resulting projected elements.</typeparam>
/// <param name="source">The input <see cref="IncrementalValuesProvider{TValues}"/> instance.</param>
/// <param name="keySelector">The key selection <see cref="Func{T, TResult}"/>.</param>
/// <param name="elementSelector">The element selection <see cref="Func{T, TResult}"/>.</param>
/// <returns>An <see cref="IncrementalValuesProvider{TValues}"/> with the grouped results.</returns>
public static IncrementalValuesProvider<(TKey Key, EquatableArray<TElement> Right)> GroupBy<TValues, TKey, TElement>(
this IncrementalValuesProvider<TValues> source,
Func<TValues, TKey> keySelector,
Func<TValues, TElement> elementSelector)
where TValues : IEquatable<TValues>
where TKey : IEquatable<TKey>
where TElement : IEquatable<TElement>
{
return source.Collect().SelectMany((item, token) =>
{
Dictionary<TKey, ImmutableArray<TElement>.Builder> map = [];
foreach (TValues value in item)
{
TKey key = keySelector(value);
TElement element = elementSelector(value);
if (!map.TryGetValue(key, out ImmutableArray<TElement>.Builder builder))
{
builder = ImmutableArray.CreateBuilder<TElement>();
map.Add(key, builder);
}
builder.Add(element);
}
token.ThrowIfCancellationRequested();
ImmutableArray<(TKey Key, EquatableArray<TElement> Elements)>.Builder result =
ImmutableArray.CreateBuilder<(TKey, EquatableArray<TElement>)>();
foreach (KeyValuePair<TKey, ImmutableArray<TElement>.Builder> entry in map)
{
result.Add((entry.Key, entry.Value.ToImmutable()));
}
return result;
});
}
}
+18 -5
ファイルの表示
@@ -21,7 +21,12 @@ internal static class IndentedTextWriterExtensions
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="generatorName">The name of the generator.</param>
/// <param name="useFullyQualifiedTypeNames">Whether to use fully qualified type names or not.</param>
public static void WriteGeneratedAttributes(this IndentedTextWriter writer, string generatorName, bool useFullyQualifiedTypeNames = true)
/// <param name="includeNonUserCodeAttributes">Whether to also include the attribute for non-user code.</param>
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]""");
}
}
}
+38
ファイルの表示
@@ -0,0 +1,38 @@
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.SourceGeneration.Extensions;
/// <summary>
/// A <see langword="class"/> with some extension methods for C# syntax nodes.
/// </summary>
internal static partial class SyntaxNodeExtensions
{
/// <summary>
/// Checks whether a given <see cref="SyntaxNode"/> is a given type declaration with or potentially with any base types, using only syntax.
/// </summary>
/// <typeparam name="T">The type of declaration to check for.</typeparam>
/// <param name="node">The input <see cref="SyntaxNode"/> to check.</param>
/// <returns>Whether <paramref name="node"/> is a given type declaration with or potentially with any base types.</returns>
public static bool IsTypeDeclarationWithOrPotentiallyWithBaseTypes<T>(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);
}
}
+1 -1
ファイルの表示
@@ -73,7 +73,7 @@
<EmbeddedResource Include="..\..\libs\arm64\dxil.dll" Link="ComputeSharp\Libraries\arm64\dxil.dll" />
</ItemGroup>
<!-- Shared project with common helpers -->
<!-- Shared projects with common helpers -->
<Import Project="..\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems" Label="Shared" />
<Import Project="..\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems" Label="Shared" />
+2 -2
ファイルの表示
@@ -720,13 +720,13 @@ partial class DiagnosticDescriptors
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for when the <c>AllowUnsafeBlocks</c> option is not set.
/// <para>
/// Format: <c>"Using [GeneratedComputeShaderDescriptor] requires unsafe blocks being enabled, as they needed by the source generators to emit valid code (add &lt;AllowUnsafeBlocks&gt;true&lt;/AllowUnsafeBlocks&gt; to your .csproj/.props file)"</c>.
/// Format: <c>"Using [GeneratedComputeShaderDescriptor] requires unsafe blocks being enabled, as they are needed by the source generators to emit valid code (add &lt;AllowUnsafeBlocks&gt;true&lt;/AllowUnsafeBlocks&gt; to your .csproj/.props file)"</c>.
/// </para>
/// </summary>
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 <AllowUnsafeBlocks>true</AllowUnsafeBlocks> 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 <AllowUnsafeBlocks>true</AllowUnsafeBlocks> to your .csproj/.props file)",
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
<WindowsSdkPackageVersion>10.0.22621.39</WindowsSdkPackageVersion>
<Platforms>x64;ARM64</Platforms>
<RuntimeIdentifiers>win-x64;win-arm64</RuntimeIdentifiers>
<DefineConstants>$(DefineConstants);D2D1_WINUI_TESTS</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Basic.Reference.Assemblies.Net80" Version="1.7.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.5.2" />
<PackageReference Include="MSTest.TestFramework" Version="3.5.2" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing" Version="1.1.2" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing" Version="1.1.2" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.11.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" Aliases="Core" />
<ProjectReference Include="..\..\src\ComputeSharp.D2D1\ComputeSharp.D2D1.csproj" Aliases="D2D1" />
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.WinUI\ComputeSharp.D2D1.WinUI.csproj" Aliases="D2D1_WinUI" />
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.WinUI.SourceGenerators\ComputeSharp.D2D1.WinUI.SourceGenerators.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\ComputeSharp.Tests.SourceGenerators\Helpers\CSharpAnalyzerWithLanguageVersionTest{TAnalyzer}.cs" Link="Helpers\CSharpAnalyzerWithLanguageVersionTest{TAnalyzer}.cs" />
<Compile Include="..\ComputeSharp.Tests.SourceGenerators\Helpers\CSharpGeneratorTest{TGenerator}.cs" Link="Helpers\CSharpGeneratorTest{TGenerator}.cs" />
</ItemGroup>
</Project>
@@ -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 = """"
// <auto-generated/>
#pragma warning disable
namespace MyNamespace
{
/// <inheritdoc cref="MyEffect"/>
partial class MyEffect
{
/// <inheritdoc/>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public partial int Number
{
get => field;
set
{
if (global::System.Collections.Generic.EqualityComparer<int>.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);
}
}
/// <summary>Executes the logic for when <see cref="Number"/> is changing.</summary>
/// <param name="value">The new property value being set.</param>
/// <remarks>This method is invoked right before the value of <see cref="Number"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnNumberChanging(int newValue);
/// <summary>Executes the logic for when <see cref="Number"/> is changing.</summary>
/// <param name="oldValue">The previous property value that is being replaced.</param>
/// <param name="newValue">The new property value being set.</param>
/// <remarks>This method is invoked right before the value of <see cref="Number"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnNumberChanging(int oldValue, int newValue);
/// <summary>Executes the logic for when <see cref="Number"/> has just changed.</summary>
/// <param name="value">The new property value that has been set.</param>
/// <remarks>This method is invoked right after the value of <see cref="Number"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnNumberChanged(int newValue);
/// <summary>Executes the logic for when <see cref="Number"/> has just changed.</summary>
/// <param name="oldValue">The previous property value that has been replaced.</param>
/// <param name="newValue">The new property value that has been set.</param>
/// <remarks>This method is invoked right after the value of <see cref="Number"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
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 = """"
// <auto-generated/>
#pragma warning disable
namespace MyNamespace
{
/// <inheritdoc cref="MyEffect"/>
partial class MyEffect
{
/// <inheritdoc/>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public partial object? Instance
{
get => field;
set
{
if (global::System.Collections.Generic.EqualityComparer<object?>.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);
}
}
/// <summary>Executes the logic for when <see cref="Instance"/> is changing.</summary>
/// <param name="value">The new property value being set.</param>
/// <remarks>This method is invoked right before the value of <see cref="Instance"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnInstanceChanging(object? newValue);
/// <summary>Executes the logic for when <see cref="Instance"/> is changing.</summary>
/// <param name="oldValue">The previous property value that is being replaced.</param>
/// <param name="newValue">The new property value being set.</param>
/// <remarks>This method is invoked right before the value of <see cref="Instance"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnInstanceChanging(object? oldValue, object? newValue);
/// <summary>Executes the logic for when <see cref="Instance"/> has just changed.</summary>
/// <param name="value">The new property value that has been set.</param>
/// <remarks>This method is invoked right after the value of <see cref="Instance"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnInstanceChanged(object? newValue);
/// <summary>Executes the logic for when <see cref="Instance"/> has just changed.</summary>
/// <param name="oldValue">The previous property value that has been replaced.</param>
/// <param name="newValue">The new property value that has been set.</param>
/// <remarks>This method is invoked right after the value of <see cref="Instance"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
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 = """"
// <auto-generated/>
#pragma warning disable
namespace MyNamespace
{
/// <inheritdoc cref="MyEffect"/>
partial class MyEffect
{
/// <inheritdoc/>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public partial object Instance
{
get => field;
set
{
if (global::System.Collections.Generic.EqualityComparer<object?>.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);
}
}
/// <summary>Executes the logic for when <see cref="Instance"/> is changing.</summary>
/// <param name="value">The new property value being set.</param>
/// <remarks>This method is invoked right before the value of <see cref="Instance"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnInstanceChanging(object newValue);
/// <summary>Executes the logic for when <see cref="Instance"/> is changing.</summary>
/// <param name="oldValue">The previous property value that is being replaced.</param>
/// <param name="newValue">The new property value being set.</param>
/// <remarks>This method is invoked right before the value of <see cref="Instance"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnInstanceChanging(object? oldValue, object newValue);
/// <summary>Executes the logic for when <see cref="Instance"/> has just changed.</summary>
/// <param name="value">The new property value that has been set.</param>
/// <remarks>This method is invoked right after the value of <see cref="Instance"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnInstanceChanged(object newValue);
/// <summary>Executes the logic for when <see cref="Instance"/> has just changed.</summary>
/// <param name="oldValue">The previous property value that has been replaced.</param>
/// <param name="newValue">The new property value that has been set.</param>
/// <remarks>This method is invoked right after the value of <see cref="Instance"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
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 = """"
// <auto-generated/>
#pragma warning disable
namespace MyNamespace
{
/// <inheritdoc cref="MyEffect"/>
partial class MyEffect
{
/// <inheritdoc/>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public partial int Number
{
get => field;
private set
{
if (global::System.Collections.Generic.EqualityComparer<int>.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);
}
}
/// <summary>Executes the logic for when <see cref="Number"/> is changing.</summary>
/// <param name="value">The new property value being set.</param>
/// <remarks>This method is invoked right before the value of <see cref="Number"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnNumberChanging(int newValue);
/// <summary>Executes the logic for when <see cref="Number"/> is changing.</summary>
/// <param name="oldValue">The previous property value that is being replaced.</param>
/// <param name="newValue">The new property value being set.</param>
/// <remarks>This method is invoked right before the value of <see cref="Number"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnNumberChanging(int oldValue, int newValue);
/// <summary>Executes the logic for when <see cref="Number"/> has just changed.</summary>
/// <param name="value">The new property value that has been set.</param>
/// <remarks>This method is invoked right after the value of <see cref="Number"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnNumberChanged(int newValue);
/// <summary>Executes the logic for when <see cref="Number"/> has just changed.</summary>
/// <param name="oldValue">The previous property value that has been replaced.</param>
/// <param name="newValue">The new property value that has been set.</param>
/// <remarks>This method is invoked right after the value of <see cref="Number"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
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 = """"
// <auto-generated/>
#pragma warning disable
namespace MyNamespace
{
/// <inheritdoc cref="MyEffect"/>
partial class MyEffect
{
/// <inheritdoc/>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public partial int X
{
get => field;
set
{
if (global::System.Collections.Generic.EqualityComparer<int>.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);
}
}
/// <inheritdoc/>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public partial int Y
{
get => field;
set
{
if (global::System.Collections.Generic.EqualityComparer<int>.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);
}
}
/// <summary>Executes the logic for when <see cref="X"/> is changing.</summary>
/// <param name="value">The new property value being set.</param>
/// <remarks>This method is invoked right before the value of <see cref="X"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnXChanging(int newValue);
/// <summary>Executes the logic for when <see cref="X"/> is changing.</summary>
/// <param name="oldValue">The previous property value that is being replaced.</param>
/// <param name="newValue">The new property value being set.</param>
/// <remarks>This method is invoked right before the value of <see cref="X"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnXChanging(int oldValue, int newValue);
/// <summary>Executes the logic for when <see cref="X"/> has just changed.</summary>
/// <param name="value">The new property value that has been set.</param>
/// <remarks>This method is invoked right after the value of <see cref="X"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnXChanged(int newValue);
/// <summary>Executes the logic for when <see cref="X"/> has just changed.</summary>
/// <param name="oldValue">The previous property value that has been replaced.</param>
/// <param name="newValue">The new property value that has been set.</param>
/// <remarks>This method is invoked right after the value of <see cref="X"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnXChanged(int oldValue, int newValue);
/// <summary>Executes the logic for when <see cref="Y"/> is changing.</summary>
/// <param name="value">The new property value being set.</param>
/// <remarks>This method is invoked right before the value of <see cref="Y"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnYChanging(int newValue);
/// <summary>Executes the logic for when <see cref="Y"/> is changing.</summary>
/// <param name="oldValue">The previous property value that is being replaced.</param>
/// <param name="newValue">The new property value being set.</param>
/// <remarks>This method is invoked right before the value of <see cref="Y"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnYChanging(int oldValue, int newValue);
/// <summary>Executes the logic for when <see cref="Y"/> has just changed.</summary>
/// <param name="value">The new property value that has been set.</param>
/// <remarks>This method is invoked right after the value of <see cref="Y"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnYChanged(int newValue);
/// <summary>Executes the logic for when <see cref="Y"/> has just changed.</summary>
/// <param name="oldValue">The previous property value that has been replaced.</param>
/// <param name="newValue">The new property value that has been set.</param>
/// <remarks>This method is invoked right after the value of <see cref="Y"/> is changed.</remarks>
[global::System.CodeDom.Compiler.GeneratedCode("ComputeSharp.D2D1.WinUI.CanvasEffectPropertyGenerator", <ASSEMBLY_VERSION>)]
partial void OnYChanged(int oldValue, int newValue);
}
}
"""";
VerifyGeneratedDiagnostics(source, ("MyNamespace.MyEffect.g.cs", result));
}
/// <summary>
/// Verifies the output of a source generator.
/// </summary>
/// <param name="source">The input source to process.</param>
/// <param name="result">The expected source to be generated.</param>
/// <returns>The task for the operation.</returns>
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<CanvasEffectPropertyGenerator>.VerifySources(source, result, languageVersion: LanguageVersion.Preview);
}
}
@@ -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<InvalidGeneratedCanvasEffectPropertyContainingTypeAnalyzer>.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<InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer>.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<InvalidGeneratedCanvasEffectPropertyAccessorsAnalyzer>.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<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.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<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.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<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.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<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.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<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.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<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.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<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.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<int> {|CS9248:Number|} { get; set; }
}
""";
await CSharpAnalyzerWithLanguageVersionTest<InvalidGeneratedCanvasEffectPropertyDeclarationAnalyzer>.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<RequireCSharpLanguageVersionPreviewAnalyzer>.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<RequireCSharpLanguageVersionPreviewAnalyzer>.VerifyAnalyzerAsync(source, languageVersion: LanguageVersion.Preview);
}
}
@@ -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<CanvasEffectPropertyGenerator>.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
{
/// <summary>
/// This is some property.
/// </summary>
[GeneratedCanvasEffectProperty]
public partial int Number { get; set; }
}
"""";
CSharpGeneratorTest<CanvasEffectPropertyGenerator>.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<CanvasEffectPropertyGenerator>.VerifyIncrementalSteps(
source,
updatedSource,
executeReason: IncrementalStepRunReason.Unchanged,
diagnosticsReason: null,
outputReason: IncrementalStepRunReason.Cached,
diagnosticsSourceReason: null,
sourceReason: IncrementalStepRunReason.Cached,
languageVersion: LanguageVersion.Preview);
}
}
@@ -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<TAnalyzer> : 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));
+24 -12
ファイルの表示
@@ -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<TGenerator>
/// </summary>
/// <param name="source">The input source to process.</param>
/// <param name="result">The expected source to be generated.</param>
public static void VerifySources(string source, (string Filename, string Source) result)
/// <param name="languageVersion">The language version to use to run the test.</param>
public static void VerifySources(string source, (string Filename, string Source) result, LanguageVersion languageVersion = LanguageVersion.CSharp12)
{
RunGenerator(source, out Compilation compilation, out ImmutableArray<Diagnostic> diagnostics);
RunGenerator(source, out Compilation compilation, out ImmutableArray<Diagnostic> diagnostics, languageVersion);
// Ensure that no diagnostics were generated
CollectionAssert.AreEquivalent(Array.Empty<Diagnostic>(), diagnostics);
@@ -79,6 +83,7 @@ internal static class CSharpGeneratorTest<TGenerator>
/// <param name="outputReason">The reason for the <c>"Output"</c> step.</param>
/// <param name="diagnosticsSourceReason">The reason for the output step for the diagnostics.</param>
/// <param name="sourceReason">The reason for the final output source.</param>
/// <param name="languageVersion">The language version to use to run the test.</param>
public static void VerifyIncrementalSteps(
string source,
string updatedSource,
@@ -86,9 +91,10 @@ internal static class CSharpGeneratorTest<TGenerator>
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<TGenerator>
// 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<TGenerator>
/// Creates a compilation from a given source.
/// </summary>
/// <param name="source">The input source to process.</param>
/// <param name="languageVersion">The language version to use to run the test.</param>
/// <returns>The resulting <see cref="Compilation"/> object.</returns>
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<MetadataReference> 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<TGenerator>
/// <param name="source">The input source to process.</param>
/// <param name="compilation"><inheritdoc cref="GeneratorDriver.RunGeneratorsAndUpdateCompilation" path="/param[@name='outputCompilation']/node()"/></param>
/// <param name="diagnostics"><inheritdoc cref="GeneratorDriver.RunGeneratorsAndUpdateCompilation" path="/param[@name='diagnostics']/node()"/></param>
/// <param name="languageVersion">The language version to use to run the test.</param>
private static void RunGenerator(
string source,
out Compilation compilation,
out ImmutableArray<Diagnostic> diagnostics)
out ImmutableArray<Diagnostic> 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);