diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs index 4266885c..2bf72336 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs @@ -2,6 +2,7 @@ using System.Collections.Immutable; using System.ComponentModel; using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Constants; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; @@ -197,13 +198,22 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene HlslInfo: hlslInfo, Diagnostcs: diagnostics.ToImmutable()); }) + .WithTrackingName(WellKnownTrackingNames.Execute) .Where(static item => item is not null)!; - // We need to create two more incremental steps to ensure we correctly emit diagnostics and re-generate sources: - // - One with just the diagnostics, which will trigger every time any of them changes - // - One with just the shader info (and no diagnostics), so that changes there don't trigger generation unnecessarily - IncrementalValuesProvider> diagnosticInfo = shaderInfo.Select(static (item, _) => item.Diagnostcs); - IncrementalValuesProvider outputInfo = shaderInfo.Select(static (item, _) => item with { Diagnostcs = default }); + // We need to create two more incremental steps to ensure we correctly emit diagnostics and re-generate sources. + // First, select an incremental provider with just the diagnostics, which will trigger every time any of them changes. + IncrementalValuesProvider> diagnosticInfo = + shaderInfo + .Select(static (item, _) => item.Diagnostcs) + .WithTrackingName(WellKnownTrackingNames.Diagnostics) + .Where(static item => !item.IsEmpty); + + // Next, select one with just the shader info (and no diagnostics), so that changes there don't trigger generation unnecessarily + IncrementalValuesProvider outputInfo = + shaderInfo + .Select(static (item, _) => item with { Diagnostcs = default }) + .WithTrackingName(WellKnownTrackingNames.Output); // Output the diagnostics, if any context.ReportDiagnostics(diagnosticInfo); diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems index 5b6c9f91..0124d463 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -9,6 +9,7 @@ ComputeSharp.SourceGeneration.Hlsl + diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Constants/WellKnownTrackingNames.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Constants/WellKnownTrackingNames.cs new file mode 100644 index 00000000..30f2b227 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Constants/WellKnownTrackingNames.cs @@ -0,0 +1,22 @@ +namespace ComputeSharp.SourceGeneration.Constants; + +/// +/// The well known names for tracking steps, to test the incremental generators. +/// +internal static class WellKnownTrackingNames +{ + /// + /// The initial transform node. + /// + public const string Execute = nameof(Execute); + + /// + /// The filtered transform with just output diagnostics. + /// + public const string Diagnostics = nameof(Diagnostics); + + /// + /// The filtered transform with just output sources. + /// + public const string Output = nameof(Output); +} diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs index 4d3e6cbd..10b60cfe 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs @@ -1,6 +1,7 @@ using System.Collections.Immutable; using System.ComponentModel; using System.Linq; +using ComputeSharp.SourceGeneration.Constants; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; @@ -146,11 +147,21 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener HlslInfo: hlslInfo, Diagnostcs: diagnostics.ToImmutable()); }) + .WithTrackingName(WellKnownTrackingNames.Execute) .Where(static item => item is not null)!; // Split the diagnostics, and drop them from the output provider (see more notes in the D2D1 generator) - IncrementalValuesProvider> diagnosticInfo = shaderInfo.Select(static (item, _) => item.Diagnostcs); - IncrementalValuesProvider outputInfo = shaderInfo.Select(static (item, _) => item with { Diagnostcs = default }); + IncrementalValuesProvider> diagnosticInfo = + shaderInfo + .Select(static (item, _) => item.Diagnostcs) + .WithTrackingName(WellKnownTrackingNames.Diagnostics) + .Where(static item => !item.IsEmpty); + + // Gather the models to produce sources for + IncrementalValuesProvider outputInfo = + shaderInfo + .Select(static (item, _) => item with { Diagnostcs = default }) + .WithTrackingName(WellKnownTrackingNames.Output); // Output the diagnostics, if any context.ReportDiagnostics(diagnosticInfo); diff --git a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderSourceGenerator.cs b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator.cs similarity index 99% rename from tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderSourceGenerator.cs rename to tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator.cs index d72bf52e..e9ce7e4a 100644 --- a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderSourceGenerator.cs +++ b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator.cs @@ -6,7 +6,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.D2D1.Tests.SourceGenerators; [TestClass] -public class Test_D2DPixelShaderSourceGenerator +public class Test_D2DPixelShaderDescriptorGenerator { [TestMethod] public async Task SimpleShader() diff --git a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderSourceGenerator_Diagnostics.cs b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Diagnostics.cs similarity index 96% rename from tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderSourceGenerator_Diagnostics.cs rename to tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Diagnostics.cs index 3a1347e8..caf81758 100644 --- a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderSourceGenerator_Diagnostics.cs +++ b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Diagnostics.cs @@ -5,7 +5,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.D2D1.Tests.SourceGenerators; [TestClass] -public class Test_D2DPixelShaderSourceGenerator_Diagnostics +public class Test_D2DPixelShaderDescriptorGenerator_Diagnostics { [TestMethod] public void MissingD2DRequiresDoublePrecisionSupportAttribute() diff --git a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Incrementality.cs b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Incrementality.cs new file mode 100644 index 00000000..f2d97272 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Incrementality.cs @@ -0,0 +1,150 @@ +using ComputeSharp.D2D1.SourceGenerators; +using ComputeSharp.Tests.SourceGenerators.Helpers; +using Microsoft.CodeAnalysis; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.D2D1.Tests.SourceGenerators; + +[TestClass] +public class Test_D2DPixelShaderDescriptorGenerator_Incrementality +{ + [TestMethod] + public void ModifiedStatement_ModifiesOutput() + { + const string source = """ + using ComputeSharp; + using ComputeSharp.D2D1; + using float4 = global::ComputeSharp.Float4; + + [D2DInputCount(0)] + [D2DGeneratedPixelShaderDescriptor] + internal readonly partial struct MyShader : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + const string updatedSource = """ + using ComputeSharp; + using ComputeSharp.D2D1; + using float4 = global::ComputeSharp.Float4; + + [D2DInputCount(0)] + [D2DGeneratedPixelShaderDescriptor] + internal readonly partial struct MyShader : ID2D1PixelShader + { + public float4 Execute() + { + // Some dummy comment + return 42; + } + } + """; + + CSharpGeneratorTest.VerifyIncrementalSteps( + source, + updatedSource, + executeReason: IncrementalStepRunReason.Modified, + diagnosticsReason: null, + outputReason: IncrementalStepRunReason.Modified, + diagnosticsSourceReason: null, + sourceReason: IncrementalStepRunReason.Modified); + } + + [TestMethod] + public void AddedComment_DoesNotModifyOutput() + { + const string source = """ + using ComputeSharp; + using ComputeSharp.D2D1; + using float4 = global::ComputeSharp.Float4; + + [D2DInputCount(0)] + [D2DGeneratedPixelShaderDescriptor] + internal readonly partial struct MyShader : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + const string updatedSource = """ + using ComputeSharp; + using ComputeSharp.D2D1; + using float4 = global::ComputeSharp.Float4; + + [D2DInputCount(0)] + [D2DGeneratedPixelShaderDescriptor] + internal readonly partial struct MyShader : ID2D1PixelShader + { + public float4 Execute() + { + // Some dummy comment + return 0; + } + } + """; + + CSharpGeneratorTest.VerifyIncrementalSteps( + source, + updatedSource, + executeReason: IncrementalStepRunReason.Unchanged, + diagnosticsReason: null, + outputReason: IncrementalStepRunReason.Cached, + diagnosticsSourceReason: null, + sourceReason: IncrementalStepRunReason.Cached); + } + + [TestMethod] + public void AddedRequiresDoublePrecisionSupport_DoesNotModifyOutput() + { + const string source = """ + using ComputeSharp; + using ComputeSharp.D2D1; + using float4 = global::ComputeSharp.Float4; + + [D2DInputCount(1)] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] + [D2DGeneratedPixelShaderDescriptor] + internal readonly partial struct MyShader(double factor) : ID2D1PixelShader + { + public float4 Execute() + { + return (float4)((double4)D2D.GetInput(0) * factor); + } + } + """; + + const string updatedSource = """ + using ComputeSharp; + using ComputeSharp.D2D1; + using float4 = global::ComputeSharp.Float4; + + [D2DInputCount(1)] + [D2DRequiresDoublePrecisionSupport] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] + [D2DGeneratedPixelShaderDescriptor] + internal readonly partial struct MyShader(double factor) : ID2D1PixelShader + { + public float4 Execute() + { + return (float4)((double4)D2D.GetInput(0) * factor); + } + } + """; + + CSharpGeneratorTest.VerifyIncrementalSteps( + source, + updatedSource, + executeReason: IncrementalStepRunReason.Modified, + diagnosticsReason: IncrementalStepRunReason.Modified, + outputReason: IncrementalStepRunReason.Unchanged, + diagnosticsSourceReason: IncrementalStepRunReason.Modified, + sourceReason: IncrementalStepRunReason.Cached); + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs b/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs index 14bf09a3..739f5110 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpGeneratorTest{TGenerator}.cs @@ -70,15 +70,106 @@ internal static class CSharpGeneratorTest } /// - /// Runs a generator and gathers the output results. + /// Verifies the incremental generator steps for a given source generator. /// /// The input source to process. - /// - /// - private static void RunGenerator( + /// The updated source to process. + /// The reason for the first "Execute" step. + /// The reason for the "Diagnostics" step. + /// The reason for the "Output" step. + /// The reason for the output step for the diagnostics. + /// The reason for the final output source. + public static void VerifyIncrementalSteps( string source, - out Compilation compilation, - out ImmutableArray diagnostics) + string updatedSource, + IncrementalStepRunReason executeReason, + IncrementalStepRunReason? diagnosticsReason, + IncrementalStepRunReason outputReason, + IncrementalStepRunReason? diagnosticsSourceReason, + IncrementalStepRunReason sourceReason) + { + Compilation compilation = CreateCompilation(source); + + GeneratorDriver driver = CSharpGeneratorDriver.Create( + generators: [new TGenerator().AsSourceGenerator()], + driverOptions: new GeneratorDriverOptions(IncrementalGeneratorOutputKind.None, trackIncrementalGeneratorSteps: true)); + + // Run the generator on the initial sources + driver = driver.RunGenerators(compilation); + + // Update the compilation by replacing the source + compilation = compilation.ReplaceSyntaxTree( + compilation.SyntaxTrees.First(), + CSharpSyntaxTree.ParseText(updatedSource, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12))); + + // Run the generators again on the updated source + driver = driver.RunGenerators(compilation); + + GeneratorRunResult result = driver.GetRunResult().Results.Single(); + + // Get the generated sources and validate them. We have two possible cases: if no diagnostics + // are produced, then just the output source node is triggered. Otherwise, we'll also have one + // output node which is used to emit the gathered diagnostics from the initial transform step. + if (diagnosticsSourceReason is not null) + { + Assert.AreEqual( + expected: 2, + actual: + result.TrackedOutputSteps + .SelectMany(outputStep => outputStep.Value) + .SelectMany(output => output.Outputs) + .Count()); + + // The "Diagnostics" name has one more parent compared to "Output", because it also + // has one extra Where(...) call on the node (used to filter out empty diagnostics). + Assert.AreEqual( + expected: diagnosticsSourceReason, + actual: + result.TrackedOutputSteps + .Single().Value + .Single(run => run.Inputs[0].Source.Inputs[0].Source.Name == "Diagnostics") + .Outputs.Single().Reason); + + Assert.AreEqual( + expected: sourceReason, + actual: + result.TrackedOutputSteps + .Single().Value + .Single(run => run.Inputs[0].Source.Name == "Output") + .Outputs.Single().Reason); + } + else + { + (object Value, IncrementalStepRunReason Reason)[] sourceOuputs = + result.TrackedOutputSteps + .SelectMany(outputStep => outputStep.Value) + .SelectMany(output => output.Outputs) + .ToArray(); + + Assert.AreEqual(1, sourceOuputs.Length); + Assert.AreEqual(sourceReason, sourceOuputs[0].Reason); + } + + Assert.AreEqual(executeReason, result.TrackedSteps["Execute"].Single().Outputs[0].Reason); + Assert.AreEqual(outputReason, result.TrackedSteps["Output"].Single().Outputs[0].Reason); + + // Check the diagnostics reason, which might not be present + if (diagnosticsReason is not null) + { + Assert.AreEqual(diagnosticsReason, result.TrackedSteps["Diagnostics"].Single().Outputs[0].Reason); + } + else + { + Assert.IsFalse(result.TrackedSteps.ContainsKey("Diagnostics")); + } + } + + /// + /// Creates a compilation from a given source. + /// + /// The input source to process. + /// The resulting object. + private static CSharpCompilation CreateCompilation(string source) { // Get all assembly references for the .NET TFM and ComputeSharp IEnumerable metadataReferences = @@ -98,14 +189,28 @@ internal static class CSharpGeneratorTest CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)); // Create the original compilation - CSharpCompilation originalCompilation = CSharpCompilation.Create( + return CSharpCompilation.Create( "original", [sourceTree], metadataReferences, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true)); + } + + /// + /// Runs a generator and gathers the output results. + /// + /// The input source to process. + /// + /// + private static void RunGenerator( + string source, + out Compilation compilation, + out ImmutableArray diagnostics) + { + Compilation originalCompilation = CreateCompilation(source); // Create the generator driver with the D2D shader generator - GeneratorDriver driver = CSharpGeneratorDriver.Create(new TGenerator()).WithUpdatedParseOptions((CSharpParseOptions)sourceTree.Options); + GeneratorDriver driver = CSharpGeneratorDriver.Create(new TGenerator()).WithUpdatedParseOptions(originalCompilation.SyntaxTrees.First().Options); // Run all source generators on the input source code _ = driver.RunGeneratorsAndUpdateCompilation(originalCompilation, out compilation, out diagnostics); diff --git a/tests/ComputeSharp.Tests.SourceGenerators/Test_ComputeShaderDescriptorGenerator_Incrementality.cs b/tests/ComputeSharp.Tests.SourceGenerators/Test_ComputeShaderDescriptorGenerator_Incrementality.cs new file mode 100644 index 00000000..e2726fc1 --- /dev/null +++ b/tests/ComputeSharp.Tests.SourceGenerators/Test_ComputeShaderDescriptorGenerator_Incrementality.cs @@ -0,0 +1,98 @@ +using ComputeSharp.SourceGenerators; +using ComputeSharp.Tests.SourceGenerators.Helpers; +using Microsoft.CodeAnalysis; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests.SourceGenerators; + +[TestClass] +public class Test_ComputeShaderDescriptorGenerator_Incrementality +{ + [TestMethod] + public void AddedStatement_ModifiesOutput() + { + const string source = """ + using ComputeSharp; + + [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [GeneratedComputeShaderDescriptor] + internal readonly partial struct MyShader : IComputeShader + { + private readonly ReadWriteBuffer buffer; + + public void Execute() + { + } + } + """; + + const string updatedSource = """ + using ComputeSharp; + + [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [GeneratedComputeShaderDescriptor] + internal readonly partial struct MyShader : IComputeShader + { + private readonly ReadWriteBuffer buffer; + + public void Execute() + { + buffer[ThreadIds.X] *= 2.0; + } + } + """; + + CSharpGeneratorTest.VerifyIncrementalSteps( + source, + updatedSource, + executeReason: IncrementalStepRunReason.Modified, + diagnosticsReason: null, + outputReason: IncrementalStepRunReason.Modified, + diagnosticsSourceReason: null, + sourceReason: IncrementalStepRunReason.Modified); + } + + [TestMethod] + public void AddedComment_DoesNotModifyOutput() + { + const string source = """ + using ComputeSharp; + + [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [GeneratedComputeShaderDescriptor] + internal readonly partial struct MyShader : IComputeShader + { + private readonly ReadWriteBuffer buffer; + + public void Execute() + { + } + } + """; + + const string updatedSource = """ + using ComputeSharp; + + [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [GeneratedComputeShaderDescriptor] + internal readonly partial struct MyShader : IComputeShader + { + private readonly ReadWriteBuffer buffer; + + public void Execute() + { + // Some dummy comment + } + } + """; + + CSharpGeneratorTest.VerifyIncrementalSteps( + source, + updatedSource, + executeReason: IncrementalStepRunReason.Unchanged, + diagnosticsReason: null, + outputReason: IncrementalStepRunReason.Cached, + diagnosticsSourceReason: null, + sourceReason: IncrementalStepRunReason.Cached); + } +} \ No newline at end of file