From 5cd53f3077e943597fc6ff592afc7746a2f92449 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 16 Sep 2022 23:03:35 +0200 Subject: [PATCH 01/20] Remove conditional paths for raw multiline strings --- ...ator.CreateBuildHlslSourceMethod.Syntax.cs | 22 ++++++--------- .../ID2D1ShaderGenerator.cs | 13 +++------ ...ator.CreateBuildHlslSourceMethod.Syntax.cs | 27 +++++++------------ .../IShaderGenerator.cs | 13 +++------ 4 files changed, 26 insertions(+), 49 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index 0e0e3986..e50afcf4 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -19,25 +19,19 @@ partial class ID2D1ShaderGenerator /// /// The input HLSL source. /// The depth of the hierarchy for this type (used to calculate the right indentation). - /// Whether to use a raw multiline string literal expression /// The resulting instance for the BuildHlslSource method. - public static MethodDeclarationSyntax GetSyntax(string hlslSource, int hierarchyDepth, bool useRawMultiLineStringLiteralExpression) + public static MethodDeclarationSyntax GetSyntax(string hlslSource, int hierarchyDepth) { - // If raw multiline string literal expressions are used, create a token to represent it. Here some spaces are + // Create a token to represent the raw multiline string literal expression with the HLSL source. Here some spaces are // also added to properly align the resulting text with one indentation below the declaring string constant. // The spaces are: 4 for each containing type, 4 for the containing method, and 4 for the one additional indentation. string indentation = new(' ', 4 * hierarchyDepth + 4 + 4); - SyntaxToken hlslSourceLiteralToken = useRawMultiLineStringLiteralExpression switch - { - true => - Token( - TriviaList(), - SyntaxKind.MultiLineRawStringLiteralToken, - $"\"\"\"\n{indentation}{hlslSource.Replace("\n", $"\n{indentation}")}\"\"\"", - hlslSource, - TriviaList()), - false => Literal(hlslSource) - }; + SyntaxToken hlslSourceLiteralToken = Token( + TriviaList(), + SyntaxKind.MultiLineRawStringLiteralToken, + $"\"\"\"\n{indentation}{hlslSource.Replace("\n", $"\n{indentation}")}\"\"\"", + hlslSource, + TriviaList()); // This code produces a method declaration as follows: // diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index fad72415..e070c17b 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -218,18 +218,13 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator .Select(static (item, token) => (item.Hierarchy, item.Source.HlslSource)) .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default); - // Check whether raw multiline string literals can be used (C# preview) - IncrementalValueProvider canUseRawMultiLineStringLiterals = - context.ParseOptionsProvider - .Select((item, _) => item is CSharpParseOptions { LanguageVersion: >= LanguageVersion.Preview }); - // Generate the BuildHlslSource() methods - context.RegisterSourceOutput(hlslSourceInfo.Combine(canUseRawMultiLineStringLiterals), static (context, item) => + context.RegisterSourceOutput(hlslSourceInfo, static (context, item) => { - MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.Left.HlslSource, item.Left.Hierarchy.Hierarchy.Length, item.Right); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: false); + MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.HlslSource, item.Hierarchy.Hierarchy.Length); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: false); - context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); + context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); // Get a filtered sequence to enable caching diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index 8f7b86c7..524e7fd5 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -24,13 +24,12 @@ partial class IShaderGenerator /// The input instance to use. /// Indicates whether or not dynamic shaders are supported. /// The depth of the hierarchy for this type (used to calculate the right indentation). - /// Whether to use a raw multiline string literal expression /// The resulting instance for the BuildHlslSource method. - public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo, bool supportsDynamicShaders, int hierarchyDepth, bool useRawMultiLineStringLiteralExpression) + public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo, bool supportsDynamicShaders, int hierarchyDepth) { // Generate the necessary body statements depending on whether dynamic shaders are supported ImmutableArray bodyStatements = supportsDynamicShaders - ? GenerateRenderMethodBody(hlslSourceInfo, hierarchyDepth, useRawMultiLineStringLiteralExpression) + ? GenerateRenderMethodBody(hlslSourceInfo, hierarchyDepth) : GenerateEmptyMethodBody(); // This code produces a method declaration as follows: @@ -82,9 +81,8 @@ partial class IShaderGenerator /// /// The input instance to use. /// The depth of the hierarchy for this type (used to calculate the right indentation). - /// Whether to use a raw multiline string literal expression /// The series of statements to build the HLSL source to compile to execute the current shader. - private static ImmutableArray GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth, bool useRawMultiLineStringLiteralExpression) + private static ImmutableArray GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth) { ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); StringBuilder textBuilder = new(); @@ -119,24 +117,19 @@ partial class IShaderGenerator sizeHint += textBuilder.Length; - // If raw multiline string literal expressions are used, create a token to represent it. Here some spaces are + // Create a token to represent the raw multiline string literal expression. Here some spaces are // also added to properly align the resulting text with one indentation below the declaring string constant. // The spaces are: 4 for each containing type, 4 for the containing method, and 4 for the one additional indentation. // An extra newline and indentation has to be added to the raw text when there is no trailing newline, as not doing // so would otherwise case the terminating """ token to fall on the same line, which is invalid syntax. This is only // needed to make the code valid, as the actual literal context of the string is not affected and remains the same. string indentation = new(' ', 4 * hierarchyDepth + 4 + 4); - SyntaxToken textToken = useRawMultiLineStringLiteralExpression switch - { - true => - Token( - TriviaList(), - SyntaxKind.MultiLineRawStringLiteralToken, - $"\"\"\"\n{indentation}{text.Replace("\n", $"\n{indentation}")}{(text.EndsWith("\n") ? "" : $"\n{indentation}")}\"\"\"", - text, - TriviaList()), - false => Literal(text) - }; + SyntaxToken textToken = Token( + TriviaList(), + SyntaxKind.MultiLineRawStringLiteralToken, + $"\"\"\"\n{indentation}{text.Replace("\n", $"\n{indentation}")}{(text.EndsWith("\n") ? "" : $"\n{indentation}")}\"\"\"", + text, + TriviaList()); statements.Add( ExpressionStatement( diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 10ce11fb..4a8e2b5e 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -170,18 +170,13 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator .Select(static (item, token) => (item.Left.Dispatch.Hierarchy, item.Left.Hlsl, item.Right)) .WithComparers(HierarchyInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default, EqualityComparer.Default); - // Check whether raw multiline string literals can be used (C# preview) - IncrementalValueProvider canUseRawMultiLineStringLiterals = - context.ParseOptionsProvider - .Select((item, _) => item is CSharpParseOptions { LanguageVersion: >= LanguageVersion.Preview }); - // Generate the BuildHlslSource() methods - context.RegisterSourceOutput(hlslSourceInfo.Combine(canUseSkipLocalsInit).Combine(canUseRawMultiLineStringLiterals), static (context, item) => + context.RegisterSourceOutput(hlslSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) => { - MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.Left.Left.SourceInfo, item.Left.Left.SupportsDynamicShaders, item.Left.Left.Hierarchy.Hierarchy.Length, item.Right); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Left.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: item.Left.Right); + MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.Left.SourceInfo, item.Left.SupportsDynamicShaders, item.Left.Hierarchy.Hierarchy.Length); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: item.Right); - context.AddSource($"{item.Left.Left.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); + context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); // Get the dispatch metadata info From e2de10bcae700d730ba432460f0bd5767d5282f1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 16 Sep 2022 23:10:49 +0200 Subject: [PATCH 02/20] Remove symbols from AutoConstructorGenerator pipeline --- .../AutoConstructorGenerator.cs | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs index 9b84bdcc..0eeb5abb 100644 --- a/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs @@ -20,19 +20,30 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator /// public void Initialize(IncrementalGeneratorInitializationContext context) { - // Get all declared struct symbols with the [AutoConstructor] attribute - IncrementalValuesProvider structSymbols = + // Get all declared struct symbols with the [AutoConstructor] attribute and + // extract the type hierarchy and fields info for each of the annotated types + IncrementalValuesProvider<(HierarchyInfo Left, ConstructorInfo Right)> constructorInfo = context.SyntaxProvider .ForAttributeWithMetadataName( typeof(AutoConstructorAttribute).FullName, static (node, token) => node is StructDeclarationSyntax structDeclaration, - static (context, token) => (INamedTypeSymbol)context.TargetSymbol); + static (context, token) => + { + INamedTypeSymbol typeSymbol = (INamedTypeSymbol)context.TargetSymbol; - // Get the type hierarchy and fields info - IncrementalValuesProvider<(HierarchyInfo Left, ConstructorInfo Right)> constructorInfo = - structSymbols - .Select(static (item, token) => (Hierarchy: HierarchyInfo.From(item), Info: Ctor.GetData(item))) - .Where(static item => !item.Info.Parameters.IsEmpty) + ConstructorInfo constructorInfo = Ctor.GetData(typeSymbol); + + // If the type has no parameters, just do nothing + if (constructorInfo.Parameters.IsEmpty) + { + return default; + } + + HierarchyInfo hierarchyInfo = HierarchyInfo.From(typeSymbol); + + return (Hierarchy: hierarchyInfo, constructorInfo); + }) + .Where(static item => item.Hierarchy is not null) .WithComparers(HierarchyInfo.Comparer.Default, ConstructorInfo.Comparer.Default); // Generate the constructors From b45629b839730cbe6f085f2715aa1057e6509185 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 16 Sep 2022 23:19:17 +0200 Subject: [PATCH 03/20] Remove symbols from D2DPixelShaderSourceGenerator pipeline --- .../AutoConstructorGenerator.cs | 4 +- .../D2DPixelShaderSourceGenerator.cs | 54 +++++++++---------- 2 files changed, 28 insertions(+), 30 deletions(-) diff --git a/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs index 0eeb5abb..c4d20e61 100644 --- a/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs @@ -26,8 +26,8 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator context.SyntaxProvider .ForAttributeWithMetadataName( typeof(AutoConstructorAttribute).FullName, - static (node, token) => node is StructDeclarationSyntax structDeclaration, - static (context, token) => + static (node, _) => node is StructDeclarationSyntax structDeclaration, + static (context, _) => { INamedTypeSymbol typeSymbol = (INamedTypeSymbol)context.TargetSymbol; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs index fb64cfa0..ec82efbd 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs @@ -20,42 +20,40 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato /// public void Initialize(IncrementalGeneratorInitializationContext context) { - // Get all method declarations with the [D2DPixelShaderSource] attribute - IncrementalValuesProvider<(MethodDeclarationSyntax Syntax, IMethodSymbol Symbol)> methodDeclarationsAndSymbols = + // Get all method declarations with the [D2DPixelShaderSource] attribute and gather all necessary info + IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderMethodSourceInfo Source, ImmutableArray Diagnostics)> shaderInfoWithErrors = context.SyntaxProvider .ForAttributeWithMetadataName( typeof(D2DPixelShaderSourceAttribute).FullName, - static (node, token) => node is MethodDeclarationSyntax, - static (context, token) => ((MethodDeclarationSyntax)context.TargetNode, (IMethodSymbol)context.TargetSymbol)); + static (node, _) => node is MethodDeclarationSyntax, + static (context, _) => + { + MethodDeclarationSyntax methodDeclaration = (MethodDeclarationSyntax)context.TargetNode; + IMethodSymbol methodSymbol = (IMethodSymbol)context.TargetSymbol; - // Gather info for all annotated methods - IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderMethodSourceInfo Source, ImmutableArray Diagnostics)> shaderInfoWithErrors = - methodDeclarationsAndSymbols - .Select(static (item, _) => - { - ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); - // Get all necessary info for the current shader - ImmutableArray modifiers = item.Syntax.Modifiers.Select(token => token.Kind()).ToImmutableArray(); - string methodName = item.Symbol.Name; - string? invalidReturnType = Execute.GetInvalidReturnType(diagnostics, item.Symbol); - string hlslSource = Execute.GetHlslSource(diagnostics, item.Symbol); - D2D1ShaderProfile shaderProfile = Execute.GetShaderProfile(diagnostics, item.Symbol); - D2D1CompileOptions compileOptions = Execute.GetCompileOptions(diagnostics, item.Symbol); + // Get all necessary info for the current shader + ImmutableArray modifiers = methodDeclaration.Modifiers.Select(token => token.Kind()).ToImmutableArray(); + string methodName = methodSymbol.Name; + string? invalidReturnType = Execute.GetInvalidReturnType(diagnostics, methodSymbol); + string hlslSource = Execute.GetHlslSource(diagnostics, methodSymbol); + D2D1ShaderProfile shaderProfile = Execute.GetShaderProfile(diagnostics, methodSymbol); + D2D1CompileOptions compileOptions = Execute.GetCompileOptions(diagnostics, methodSymbol); - HlslShaderMethodSourceInfo sourceInfo = new( - modifiers, - methodName, - invalidReturnType, - hlslSource, - shaderProfile, - compileOptions, - HasErrors: diagnostics.Count > 0); + HlslShaderMethodSourceInfo sourceInfo = new( + modifiers, + methodName, + invalidReturnType, + hlslSource, + shaderProfile, + compileOptions, + HasErrors: diagnostics.Count > 0); - HierarchyInfo hierarchy = HierarchyInfo.From(item.Symbol.ContainingType!); + HierarchyInfo hierarchy = HierarchyInfo.From(methodSymbol.ContainingType!); - return (hierarchy, sourceInfo, diagnostics.ToImmutable()); - }); + return (hierarchy, sourceInfo, diagnostics.ToImmutable()); + }); // Output the diagnostics context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, _) => item.Diagnostics)); From 080011fe8fb2dd41563bab7ebc5307eef5a652ff Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Sep 2022 12:58:01 +0200 Subject: [PATCH 04/20] Share raw multiline string literal formatting logic --- ...ator.CreateBuildHlslSourceMethod.Syntax.cs | 17 +++------ ...mputeSharp.SourceGeneration.Hlsl.projitems | 1 + .../Helpers/SyntaxTokenHelper.cs | 35 +++++++++++++++++++ ...ator.CreateBuildHlslSourceMethod.Syntax.cs | 20 +++-------- 4 files changed, 44 insertions(+), 29 deletions(-) create mode 100644 src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxTokenHelper.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index e50afcf4..675fd0e5 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -1,5 +1,5 @@ using ComputeSharp.D2D1.__Internals; -using Microsoft.CodeAnalysis; +using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -22,17 +22,6 @@ partial class ID2D1ShaderGenerator /// The resulting instance for the BuildHlslSource method. public static MethodDeclarationSyntax GetSyntax(string hlslSource, int hierarchyDepth) { - // Create a token to represent the raw multiline string literal expression with the HLSL source. Here some spaces are - // also added to properly align the resulting text with one indentation below the declaring string constant. - // The spaces are: 4 for each containing type, 4 for the containing method, and 4 for the one additional indentation. - string indentation = new(' ', 4 * hierarchyDepth + 4 + 4); - SyntaxToken hlslSourceLiteralToken = Token( - TriviaList(), - SyntaxKind.MultiLineRawStringLiteralToken, - $"\"\"\"\n{indentation}{hlslSource.Replace("\n", $"\n{indentation}")}\"\"\"", - hlslSource, - TriviaList()); - // This code produces a method declaration as follows: // // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.BuildHlslSource(out string hlslSource) @@ -49,7 +38,9 @@ partial class ID2D1ShaderGenerator AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName("hlslSource"), - LiteralExpression(SyntaxKind.StringLiteralExpression, hlslSourceLiteralToken))))); + LiteralExpression( + SyntaxKind.StringLiteralExpression, + SyntaxTokenHelper.CreateRawMultilineStringLiteral(hlslSource, hierarchyDepth)))))); } } } diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems index 829cb1e5..d609eae6 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -12,6 +12,7 @@ + diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxTokenHelper.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxTokenHelper.cs new file mode 100644 index 00000000..48415734 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxTokenHelper.cs @@ -0,0 +1,35 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGeneration.Helpers; + +/// +/// Helpers to create and work with -s. +/// +internal static class SyntaxTokenHelper +{ + /// + /// Creates a representing a raw multiline string literal with the given text. + /// + /// The text to use for the created raw multiline string literal token. + /// The current indentation level to use. + /// A representing a raw multiline string literal with the value of . + public static SyntaxToken CreateRawMultilineStringLiteral(string text, int indentationLevel) + { + // Create a token to represent the raw multiline string literal expression. Here some spaces are + // also added to properly align the resulting text with one indentation below the declaring string constant. + // The spaces are: 4 for each containing type, 4 for the containing method, and 4 for the one additional indentation. + // An extra newline and indentation has to be added to the raw text when there is no trailing newline, as not doing + // so would otherwise case the terminating """ token to fall on the same line, which is invalid syntax. This is only + // needed to make the code valid, as the actual literal context of the string is not affected and remains the same. + string indentation = new(' ', 4 * indentationLevel + 4 + 4); + + return Token( + TriviaList(), + SyntaxKind.MultiLineRawStringLiteralToken, + $"\"\"\"\n{indentation}{text.Replace("\n", $"\n{indentation}")}{(text.EndsWith("\n") ? "" : $"\n{indentation}")}\"\"\"", + text, + TriviaList()); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index 524e7fd5..8a8f4556 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -2,8 +2,8 @@ using System.Collections.Immutable; using System.Text; using ComputeSharp.__Internals; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGenerators.Models; -using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -117,25 +117,13 @@ partial class IShaderGenerator sizeHint += textBuilder.Length; - // Create a token to represent the raw multiline string literal expression. Here some spaces are - // also added to properly align the resulting text with one indentation below the declaring string constant. - // The spaces are: 4 for each containing type, 4 for the containing method, and 4 for the one additional indentation. - // An extra newline and indentation has to be added to the raw text when there is no trailing newline, as not doing - // so would otherwise case the terminating """ token to fall on the same line, which is invalid syntax. This is only - // needed to make the code valid, as the actual literal context of the string is not affected and remains the same. - string indentation = new(' ', 4 * hierarchyDepth + 4 + 4); - SyntaxToken textToken = Token( - TriviaList(), - SyntaxKind.MultiLineRawStringLiteralToken, - $"\"\"\"\n{indentation}{text.Replace("\n", $"\n{indentation}")}{(text.EndsWith("\n") ? "" : $"\n{indentation}")}\"\"\"", - text, - TriviaList()); - statements.Add( ExpressionStatement( InvocationExpression( MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, textToken))))); + .AddArgumentListArguments(Argument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + SyntaxTokenHelper.CreateRawMultilineStringLiteral(text, hierarchyDepth)))))); textBuilder.Clear(); } From 65ee05bf10883863836d5c678a94a8da4eebe2eb Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Sep 2022 12:59:16 +0200 Subject: [PATCH 05/20] Move D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor --- .../D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/ComputeSharp.D2D1.SourceGenerators/{ => Diagnostics/Suppressors}/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs (100%) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Suppressors/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs similarity index 100% rename from src/ComputeSharp.D2D1.SourceGenerators/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs rename to src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Suppressors/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs From 5204402c499e6997480c1f5526e54a7cff3571b2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Sep 2022 13:07:21 +0200 Subject: [PATCH 06/20] Add new InvalidAssemblyLevelCompileOptionsAnalyzer analyzer --- ...alidAssemblyLevelCompileOptionsAnalyzer.cs | 52 +++++++++++++++++++ ...haderGenerator.CreateLoadBytecodeMethod.cs | 28 ---------- .../ID2D1ShaderGenerator.cs | 9 ---- 3 files changed, 52 insertions(+), 37 deletions(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidAssemblyLevelCompileOptionsAnalyzer.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidAssemblyLevelCompileOptionsAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidAssemblyLevelCompileOptionsAnalyzer.cs new file mode 100644 index 00000000..602437a9 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidAssemblyLevelCompileOptionsAnalyzer.cs @@ -0,0 +1,52 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +/// A diagnostic analyzer that generates an error whenever invalid options are used in an assembly-level [D2D1CompileOptions] attribute. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class InvalidAssemblyLevelCompileOptionsAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(InvalidPackMatrixColumnMajorOption); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + context.RegisterCompilationAction(static context => + { + IAssemblySymbol assemblySymbol = context.Compilation.Assembly; + + // In order to emit diagnostics for [D2D1CompileOptions] attributes at the assembly level, the following is needed: + // - The type symbol for the assembly, to get the AttributeData object for the [D2D1CompileOptions] attribute, if used. + // - The syntax node representing the attribute targeting the assembly, to get a location (this is retrieved from the AttributeData). + // - The input D2D1CompileOptions value, which can be retrieved from the constructor arguments of the AttributeData object. + if (assemblySymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData)) + { + D2D1CompileOptions options = (D2D1CompileOptions)attributeData!.ConstructorArguments[0].Value!; + + if ((options & D2D1CompileOptions.PackMatrixColumnMajor) != 0) + { + Diagnostic diagnostic = Diagnostic.Create( + InvalidPackMatrixColumnMajorOption, + attributeData.ApplicationSyntaxReference?.GetSyntax(context.CancellationToken).GetLocation(), + assemblySymbol); + + context.ReportDiagnostic(diagnostic); + } + } + }); + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs index a8dd4db6..8b7be511 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs @@ -78,34 +78,6 @@ partial class ID2D1ShaderGenerator return null; } - /// - /// Gets a -s for invalid assembly-level [D2D1CompileOptions] attribute, if one is present. - /// - /// The input instance to process. - /// The for the operation. - /// The diagnostic for the attribute, if invalid. - public static Diagnostic? GetAssemblyLevelCompileOptionsDiagnostics(IAssemblySymbol assemblySymbol, CancellationToken cancellationToken) - { - // In order to emit diagnostics for [D2D1CompileOptions] attributes at the assembly level, the following is needed: - // - The type symbol for the assembly, to get the AttributeData object for the [D2D1CompileOptions] attribute, if used. - // - The syntax node representing the attribute targeting the assembly, to get a location (this is retrieved from the AttributeData). - // - The input D2D1CompileOptions value, which can be retrieved from the constructor arguments of the AttributeData object. - if (assemblySymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData)) - { - D2D1CompileOptions options = (D2D1CompileOptions)attributeData!.ConstructorArguments[0].Value!; - - if ((options & D2D1CompileOptions.PackMatrixColumnMajor) != 0) - { - return Diagnostic.Create( - InvalidPackMatrixColumnMajorOption, - attributeData.ApplicationSyntaxReference?.GetSyntax(cancellationToken).GetLocation(), - assemblySymbol); - } - } - - return null; - } - /// /// Extracts the metadata definition for the current shader. /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index e070c17b..e372204e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -128,15 +128,6 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Output the diagnostics context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Diagnostics)); - // Get all errors for invalid [D2D1CompileOptions] attributes added to the assembly level - IncrementalValuesProvider d2DCompileOptionsAtAssemblyLevelErrors = - context.CompilationProvider - .SelectMany(static (compilation, token) => ImmutableArray.Create(LoadBytecode.GetAssemblyLevelCompileOptionsDiagnostics(compilation.Assembly, token))) - .Where(static item => item is not null)!; - - // Output the diagnostics - context.ReportDiagnostics(d2DCompileOptionsAtAssemblyLevelErrors.Select(static (item, token) => item)); - // Filter all items to enable caching at a coarse level, and remove diagnostics IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, ResourceTextureDescriptionsInfo ResourceTextureDescriptions, HlslShaderSourceInfo Source)> shaderInfo = shaderInfoWithErrors From f27e98f2fae7e1e48bd86921b54851e349abc168 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Sep 2022 13:11:14 +0200 Subject: [PATCH 07/20] Add new InvalidD2DResourceTextureIndexUseAnalyzer analyzer --- ...validD2DResourceTextureIndexUseAnalyzer.cs | 52 +++++++++++++++++++ ...teLoadResourceTextureDescriptionsMethod.cs | 25 --------- .../ID2D1ShaderGenerator.cs | 13 ----- 3 files changed, 52 insertions(+), 38 deletions(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs new file mode 100644 index 00000000..f8cb979e --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs @@ -0,0 +1,52 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Immutable; +using System.Linq; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +/// A diagnostic analyzer that generates an error whenever [D2DResourceTextureIndex] is used incorrectly to annotate an invalid field. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class InvalidD2DResourceTextureIndexUseAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(InvalidD2DResourceTextureIndexAttributeUse); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + context.RegisterSymbolAction(static context => + { + IFieldSymbol fieldSymbol = (IFieldSymbol)context.Symbol; + + if (fieldSymbol.HasAttributeWithFullyQualifiedName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute")) + { + string metadataName = fieldSymbol.Type.GetFullMetadataName(); + + if (!HlslKnownTypes.IsResourceTextureType(metadataName)) + { + Diagnostic diagnostic = Diagnostic.Create( + InvalidD2DResourceTextureIndexAttributeUse, + fieldSymbol.Locations.FirstOrDefault(), + fieldSymbol.Name, + fieldSymbol.ContainingType, + fieldSymbol.Type); + + context.ReportDiagnostic(diagnostic); + } + } + }, SymbolKind.Field); + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs index ad3f07cf..fb4b0ee4 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs @@ -106,30 +106,5 @@ partial class ID2D1ShaderGenerator diagnostics.Add(RepeatedD2DResourceTextureIndices, structDeclarationSymbol, structDeclarationSymbol); } } - - /// - /// Gets the diagnostics for a field with invalid [D2DResourceTextureIndex] attribute use, if that is the case. - /// - /// The input instance to process. - /// The resulting instance for , if needed. - public static Diagnostic? GetDiagnosticForFieldWithInvalidD2DResourceTextureIndexAttribute(IFieldSymbol fieldSymbol) - { - if (fieldSymbol.HasAttributeWithFullyQualifiedName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute")) - { - string metadataName = fieldSymbol.Type.GetFullMetadataName(); - - if (!HlslKnownTypes.IsResourceTextureType(metadataName)) - { - return Diagnostic.Create( - InvalidD2DResourceTextureIndexAttributeUse, - fieldSymbol.Locations.FirstOrDefault(), - fieldSymbol.Name, - fieldSymbol.ContainingType, - fieldSymbol.Type); - } - } - - return null; - } } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index e372204e..0a7dec29 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -366,18 +366,5 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetPixelOptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); - - // Get all diagnostics for invalid [D2DResourceTextureIndex] uses - IncrementalValuesProvider invalidD2DResourceTextureIndexUseErrors = - context.SyntaxProvider - .CreateSyntaxProvider( - static (node, _) => node is FieldDeclarationSyntax { AttributeLists.Count: > 0 }, - static (context, _) => ((FieldDeclarationSyntax)context.Node).Declaration.Variables.Select(v => (IFieldSymbol)context.SemanticModel.GetDeclaredSymbol(v)!)) - .SelectMany(static (item, _) => item) - .Select(static (item, token) => LoadResourceTextureDescriptions.GetDiagnosticForFieldWithInvalidD2DResourceTextureIndexAttribute(item)) - .Where(static diagnostic => diagnostic is not null)!; - - // Output the diagnostics - context.ReportDiagnostics(invalidD2DResourceTextureIndexUseErrors); } } From 87f2e04ca0bd42f982899e643f11191273c08c34 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Sep 2022 14:48:33 +0200 Subject: [PATCH 08/20] Make all models directly equatable --- .../AutoConstructorGenerator.cs | 3 +- .../Models/ConstructorInfo.cs | 8 +- .../D2DPixelShaderSourceGenerator.cs | 6 +- .../ID2D1ShaderGenerator.cs | 33 ++-- .../Models/DispatchDataInfo.cs | 12 +- .../Models/EmbeddedBytecodeInfo.cs | 8 +- .../Models/EmbeddedBytecodeMethodInfo.cs | 8 +- .../Models/FieldInfo.cs | 103 ++++++------ .../Models/HlslShaderMethodSourceInfo.cs | 8 +- .../Models/InputDescriptionsInfo.cs | 8 +- .../Models/InputTypesInfo.cs | 8 +- .../Models/ResourceTextureDescriptionsInfo.cs | 8 +- .../Models/DiagnosticInfo.cs | 8 +- .../Models/HierarchyInfo.cs | 8 +- .../IShaderGenerator.cs | 21 +-- .../Models/DispatchDataInfo.cs | 16 +- .../Models/DispatchIdInfo.cs | 8 +- .../Models/DispatchMetadataInfo.cs | 8 +- .../Models/EmbeddedBytecodeInfo.cs | 8 +- .../Models/FieldInfo.cs | 147 +++++++++++------- .../Models/HlslMethodSourceInfo.cs | 8 +- .../Models/HlslShaderSourceInfo.cs | 8 +- .../ShaderMethodSourceGenerator.cs | 3 +- 23 files changed, 287 insertions(+), 169 deletions(-) diff --git a/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs index c4d20e61..6d78bed9 100644 --- a/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs @@ -43,8 +43,7 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator return (Hierarchy: hierarchyInfo, constructorInfo); }) - .Where(static item => item.Hierarchy is not null) - .WithComparers(HierarchyInfo.Comparer.Default, ConstructorInfo.Comparer.Default); + .Where(static item => item.Hierarchy is not null); // Generate the constructors context.RegisterSourceOutput(constructorInfo, static (context, item) => diff --git a/src/ComputeSharp.Core.SourceGenerators/Models/ConstructorInfo.cs b/src/ComputeSharp.Core.SourceGenerators/Models/ConstructorInfo.cs index 684014b0..93075030 100644 --- a/src/ComputeSharp.Core.SourceGenerators/Models/ConstructorInfo.cs +++ b/src/ComputeSharp.Core.SourceGenerators/Models/ConstructorInfo.cs @@ -13,10 +13,16 @@ namespace ComputeSharp.Core.SourceGenerators.Models; /// The names of ignored fields that should be defaulted. internal sealed record ConstructorInfo(ImmutableArray Parameters, ImmutableArray DefaultedFields) { + /// + public bool Equals(ConstructorInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, ConstructorInfo obj) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs index ec82efbd..b7e22c8e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs @@ -61,8 +61,7 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato // Filter all items to enable caching at a coarse level, and remove diagnostics IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderMethodSourceInfo Source)> shaderInfo = shaderInfoWithErrors - .Select(static (item, token) => (item.Hierarchy, item.Source)) - .WithComparers(HierarchyInfo.Comparer.Default, HlslShaderMethodSourceInfo.Comparer.Default); + .Select(static (item, token) => (item.Hierarchy, item.Source)); // Compile the requested shader bytecodes IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeMethodInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = @@ -108,8 +107,7 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato // Get the filtered sequence to enable caching IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeMethodInfo BytecodeInfo)> embeddedBytecode = embeddedBytecodeWithErrors - .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo)) - .WithComparers(HierarchyInfo.Comparer.Default, EmbeddedBytecodeMethodInfo.Comparer.Default); + .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo)); // Generate the shader bytecode methods context.RegisterSourceOutput(embeddedBytecode, static (context, item) => diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 0a7dec29..4a174c41 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -131,14 +131,12 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Filter all items to enable caching at a coarse level, and remove diagnostics IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, ResourceTextureDescriptionsInfo ResourceTextureDescriptions, HlslShaderSourceInfo Source)> shaderInfo = shaderInfoWithErrors - .Select(static (item, token) => (item.Hierarchy, item.Dispatch, item.InputTypes, item.ResourceTextureDescriptions, item.Source)) - .WithComparers(HierarchyInfo.Comparer.Default, DispatchDataInfo.Comparer.Default, InputTypesInfo.Comparer.Default, ResourceTextureDescriptionsInfo.Comparer.Default, EqualityComparer.Default); + .Select(static (item, token) => (item.Hierarchy, item.Dispatch, item.InputTypes, item.ResourceTextureDescriptions, item.Source)); // Filter items to enable caching for the input count methods IncrementalValuesProvider<(HierarchyInfo Hierarchy, int InputCount)> inputCountInfo = shaderInfo - .Select(static (item, token) => (item.Hierarchy, item.InputTypes.InputTypes.Length)) - .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default); + .Select(static (item, token) => (item.Hierarchy, item.InputTypes.InputTypes.Length)); // Generate the GetInputCount() methods context.RegisterSourceOutput(inputCountInfo, static (context, item) => @@ -152,8 +150,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Get a filtered sequence to enable caching IncrementalValuesProvider<(HierarchyInfo Hierarchy, InputTypesInfo InputTypes)> inputTypesInfo = shaderInfo - .Select(static (item, token) => (item.Hierarchy, item.InputTypes)) - .WithComparers(HierarchyInfo.Comparer.Default, InputTypesInfo.Comparer.Default); + .Select(static (item, token) => (item.Hierarchy, item.InputTypes)); // Generate the GetInputType() methods context.RegisterSourceOutput(inputTypesInfo, static (context, item) => @@ -167,8 +164,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Get a filtered sequence to enable caching IncrementalValuesProvider<(HierarchyInfo Hierarchy, ResourceTextureDescriptionsInfo ResourceTextureDescriptions)> resourceTextureDescriptionsInfo = shaderInfo - .Select(static (item, token) => (item.Hierarchy, item.ResourceTextureDescriptions)) - .WithComparers(HierarchyInfo.Comparer.Default, ResourceTextureDescriptionsInfo.Comparer.Default); + .Select(static (item, token) => (item.Hierarchy, item.ResourceTextureDescriptions)); // Generate the LoadResourceTextureDescriptions() methods context.RegisterSourceOutput(resourceTextureDescriptionsInfo.Combine(canUseSkipLocalsInit), static (context, item) => @@ -182,8 +178,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Get a filtered sequence to enable caching IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch)> dispatchDataInfo = shaderInfo - .Select(static (item, token) => (item.Hierarchy, item.Dispatch)) - .WithComparers(HierarchyInfo.Comparer.Default, DispatchDataInfo.Comparer.Default); + .Select(static (item, token) => (item.Hierarchy, item.Dispatch)); // Generate the LoadDispatchData() methods context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) => @@ -206,8 +201,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Get the filtered sequence to enable caching IncrementalValuesProvider<(HierarchyInfo Hierarchy, string HlslSource)> hlslSourceInfo = shaderInfo - .Select(static (item, token) => (item.Hierarchy, item.Source.HlslSource)) - .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default); + .Select(static (item, token) => (item.Hierarchy, item.Source.HlslSource)); // Generate the BuildHlslSource() methods context.RegisterSourceOutput(hlslSourceInfo, static (context, item) => @@ -221,8 +215,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Get a filtered sequence to enable caching IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo Source)> shaderBytecodeInfo = shaderInfo - .Select(static (item, token) => (item.Hierarchy, item.Source)) - .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default); + .Select(static (item, token) => (item.Hierarchy, item.Source)); // Compile the requested shader bytecodes IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = @@ -268,8 +261,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Get the filtered sequence to enable caching IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode = embeddedBytecodeWithErrors - .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo)) - .WithComparers(HierarchyInfo.Comparer.Default, EmbeddedBytecodeInfo.Comparer.Default); + .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo)); // Generate the LoadBytecode() methods context.RegisterSourceOutput(embeddedBytecode, static (context, item) => @@ -295,8 +287,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator OutputBufferInfo outputBufferInfo = new(bufferPrecision, channelDepth); return (item.Hierarchy, outputBufferInfo); - }) - .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default); + }); // Generate the GetOutputBuffer() methods context.RegisterSourceOutput(outputBufferInfo, static (context, item) => @@ -331,8 +322,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Get the filtered sequence to enable caching IncrementalValuesProvider<(HierarchyInfo Hierarchy, InputDescriptionsInfo Info)> inputDescriptionsInfo = inputDescriptionsInfoWithErrors - .Select(static (item, token) => (item.Hierarchy, item.Info.Value)) - .WithComparers(HierarchyInfo.Comparer.Default, InputDescriptionsInfo.Comparer.Default); + .Select(static (item, token) => (item.Hierarchy, item.Info.Value)); // Generate the LoadInputDescriptions() methods context.RegisterSourceOutput(inputDescriptionsInfo.Combine(canUseSkipLocalsInit), static (context, item) => @@ -355,8 +345,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator token.ThrowIfCancellationRequested(); return (item.Hierarchy, pixelOptions); - }) - .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default); + }); // Generate the GetPixelOptions() methods context.RegisterSourceOutput(pixelOptionsInfo, static (context, item) => diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/DispatchDataInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/DispatchDataInfo.cs index fc36a429..e99830bb 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/DispatchDataInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/DispatchDataInfo.cs @@ -13,15 +13,21 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// The size of the shader constant buffer. internal sealed record DispatchDataInfo(ImmutableArray FieldInfos, int ConstantBufferSizeInBytes) { + /// + public bool Equals(DispatchDataInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, DispatchDataInfo obj) { - hashCode.AddRange(obj.FieldInfos, FieldInfo.Comparer.Default); + hashCode.AddRange(obj.FieldInfos); hashCode.Add(obj.ConstantBufferSizeInBytes); } @@ -29,7 +35,7 @@ internal sealed record DispatchDataInfo(ImmutableArray FieldInfos, in protected override bool AreEqual(DispatchDataInfo x, DispatchDataInfo y) { return - x.FieldInfos.SequenceEqual(y.FieldInfos, FieldInfo.Comparer.Default) && + x.FieldInfos.SequenceEqual(y.FieldInfos) && x.ConstantBufferSizeInBytes == y.ConstantBufferSizeInBytes; } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs index cf51ee76..2a901c51 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs @@ -15,10 +15,16 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// The compiled shader bytecode, if available. internal sealed record EmbeddedBytecodeInfo(string HlslSource, D2D1ShaderProfile? ShaderProfile, D2D1CompileOptions? CompileOptions, ImmutableArray Bytecode) { + /// + public bool Equals(EmbeddedBytecodeInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, EmbeddedBytecodeInfo obj) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeMethodInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeMethodInfo.cs index 5cb0a4b3..9e8c1298 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeMethodInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeMethodInfo.cs @@ -23,10 +23,16 @@ internal sealed record EmbeddedBytecodeMethodInfo( string HlslSource, ImmutableArray Bytecode) { + /// + public bool Equals(EmbeddedBytecodeMethodInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, EmbeddedBytecodeMethodInfo obj) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/FieldInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/FieldInfo.cs index 073900bd..fc65ddbb 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/FieldInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/FieldInfo.cs @@ -17,7 +17,37 @@ internal abstract record FieldInfo /// The path of the field with respect to the shader instance. /// The full metadata name for the primitive type. /// The byte offset of the value within the root signature. - public sealed record Primitive(ImmutableArray FieldPath, string TypeName, int Offset) : FieldInfo; + public sealed record Primitive(ImmutableArray FieldPath, string TypeName, int Offset) : FieldInfo + { + /// + public bool Equals(Primitive? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + + /// + /// An implementation for . + /// + private sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, Primitive obj) + { + hashCode.AddRange(obj.FieldPath); + hashCode.Add(obj.TypeName); + hashCode.Add(obj.Offset); + } + + /// + protected override bool AreEqual(Primitive x, Primitive y) + { + return + x.FieldPath.SequenceEqual(y.FieldPath) && + x.TypeName == y.TypeName && + x.Offset == y.Offset; + } + } + } /// /// A captured non linear matrix value. @@ -34,58 +64,41 @@ internal abstract record FieldInfo string ElementName, int Rows, int Columns, - ImmutableArray Offsets) : FieldInfo; - - /// - /// An implementation for . - /// - public sealed class Comparer : Comparer + ImmutableArray Offsets) : FieldInfo { /// - protected override void AddToHashCode(ref HashCode hashCode, FieldInfo obj) - { - switch (obj) - { - case Primitive primitive: - hashCode.AddRange(primitive.FieldPath); - hashCode.Add(primitive.TypeName); - hashCode.Add(primitive.Offset); - break; - case NonLinearMatrix matrix: - hashCode.AddRange(matrix.FieldPath); - hashCode.Add(matrix.TypeName); - hashCode.Add(matrix.ElementName); - hashCode.Add(matrix.Rows); - hashCode.Add(matrix.Columns); - hashCode.AddRange(matrix.Offsets); - break; - default: - break; - } - } + public bool Equals(NonLinearMatrix? obj) => Comparer.Default.Equals(this, obj); /// - protected override bool AreEqual(FieldInfo x, FieldInfo y) + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + + /// + /// An implementation for . + /// + private sealed class Comparer : Comparer { - if (x is Primitive primitiveX && y is Primitive primitiveY) + /// + protected override void AddToHashCode(ref HashCode hashCode, NonLinearMatrix obj) { - return - primitiveX.FieldPath.SequenceEqual(primitiveY.FieldPath) && - primitiveX.TypeName == primitiveY.TypeName && - primitiveX.Offset == primitiveY.Offset; - } - else if (x is NonLinearMatrix matrixX && y is NonLinearMatrix matrixY) - { - return - matrixX.FieldPath.SequenceEqual(matrixY.FieldPath) && - matrixX.TypeName == matrixY.TypeName && - matrixX.ElementName == matrixY.ElementName && - matrixX.Rows == matrixY.Rows && - matrixY.Columns == matrixY.Columns && - matrixX.Offsets.SequenceEqual(matrixY.Offsets); + hashCode.AddRange(obj.FieldPath); + hashCode.Add(obj.TypeName); + hashCode.Add(obj.ElementName); + hashCode.Add(obj.Rows); + hashCode.Add(obj.Columns); + hashCode.AddRange(obj.Offsets); } - return false; + /// + protected override bool AreEqual(NonLinearMatrix x, NonLinearMatrix y) + { + return + x.FieldPath.SequenceEqual(y.FieldPath) && + x.TypeName == y.TypeName && + x.ElementName == y.ElementName && + x.Rows == y.Rows && + x.Columns == y.Columns && + x.Offsets.SequenceEqual(y.Offsets); + } } } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderMethodSourceInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderMethodSourceInfo.cs index 25b20451..6e252b26 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderMethodSourceInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderMethodSourceInfo.cs @@ -26,10 +26,16 @@ internal sealed record HlslShaderMethodSourceInfo( D2D1CompileOptions CompileOptions, bool HasErrors) { + /// + public bool Equals(HlslShaderMethodSourceInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, HlslShaderMethodSourceInfo obj) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs index 81869b59..644ab2cb 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs @@ -11,10 +11,16 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// The input descriptions for a given shader. internal sealed record InputDescriptionsInfo(ImmutableArray InputDescriptions) { + /// + public bool Equals(InputDescriptionsInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, InputDescriptionsInfo obj) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputTypesInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputTypesInfo.cs index 0a3c10c2..e8169190 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputTypesInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputTypesInfo.cs @@ -12,10 +12,16 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// The input types for a given shader. internal sealed record InputTypesInfo(ImmutableArray InputTypes) { + /// + public bool Equals(InputTypesInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, InputTypesInfo obj) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescriptionsInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescriptionsInfo.cs index b5a174d5..b0d9a817 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescriptionsInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescriptionsInfo.cs @@ -11,10 +11,16 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// The resource textures for the current shader. internal sealed record ResourceTextureDescriptionsInfo(ImmutableArray ResourceTextureDescriptions) { + /// + public bool Equals(ResourceTextureDescriptionsInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, ResourceTextureDescriptionsInfo obj) diff --git a/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs b/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs index 88639f74..98649b75 100644 --- a/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs +++ b/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs @@ -13,10 +13,16 @@ namespace ComputeSharp.SourceGeneration.Models; /// The diagnostic args. internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, params object[] Args) { + /// + public bool Equals(DiagnosticInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, DiagnosticInfo obj) diff --git a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs index a093c45b..1b069322 100644 --- a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs +++ b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs @@ -111,10 +111,16 @@ internal sealed partial record HierarchyInfo(string FilenameHint, string FullyQu .NormalizeWhitespace(eol: "\n"); } + /// + public bool Equals(HierarchyInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, HierarchyInfo obj) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 4a8e2b5e..40022e47 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -63,8 +63,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Get the hierarchy info and delegate field names for each shader type IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchIdInfo Info)> hierarchyAndDispatchIdInfo = shaderDeclarations - .Select(static (item, token) => (item.Hierarchy, new DispatchIdInfo(GetDispatchId.GetInfo(item.Symbol)))) - .WithComparers(HierarchyInfo.Comparer.Default, DispatchIdInfo.Comparer.Default); + .Select(static (item, token) => (item.Hierarchy, new DispatchIdInfo(GetDispatchId.GetInfo(item.Symbol)))); // Generate the GetDispatchId() methods context.RegisterSourceOutput(hierarchyAndDispatchIdInfo.Combine(supportsDynamicShaders), static (context, item) => @@ -141,14 +140,12 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Filter all items to enable caching at a coarse level, and remove diagnostics IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslShaderSourceInfo Hlsl, ThreadIdsInfo ThreadIds)> shaderInfo = shaderInfoWithErrors - .Select(static (item, token) => (item.Dispatch.Value, item.Hlsl.Value, item.ThreadIds.Value)) - .WithComparers(DispatchDataInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default, EqualityComparer.Default); + .Select(static (item, token) => (item.Dispatch.Value, item.Hlsl.Value, item.ThreadIds.Value)); // Get a filtered sequence to enable caching IncrementalValuesProvider dispatchDataInfo = shaderInfo - .Select(static (item, token) => item.Dispatch) - .WithComparer(DispatchDataInfo.Comparer.Default); + .Select(static (item, token) => item.Dispatch); // Generate the LoadDispatchData() methods context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) => @@ -167,8 +164,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo SourceInfo, bool SupportsDynamicShaders)> hlslSourceInfo = shaderInfo .Combine(supportsDynamicShaders) - .Select(static (item, token) => (item.Left.Dispatch.Hierarchy, item.Left.Hlsl, item.Right)) - .WithComparers(HierarchyInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default, EqualityComparer.Default); + .Select(static (item, token) => (item.Left.Dispatch.Hierarchy, item.Left.Hlsl, item.Right)); // Generate the BuildHlslSource() methods context.RegisterSourceOutput(hlslSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) => @@ -193,8 +189,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator token.ThrowIfCancellationRequested(); return (item.Dispatch.Hierarchy, dispatchMetadataInfo); - }) - .WithComparers(HierarchyInfo.Comparer.Default, DispatchMetadataInfo.Comparer.Default); + }); // Generate the LoadDispatchMetadata() methods context.RegisterSourceOutput(dispatchMetadataInfo.Combine(canUseSkipLocalsInit), static (context, item) => @@ -208,8 +203,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Transform the raw HLSL source to compile IncrementalValuesProvider<(HierarchyInfo Hierarchy, string Hlsl, ThreadIdsInfo ThreadIds)> shaderBytecodeInfo = shaderInfo - .Select(static (item, token) => (item.Dispatch.Hierarchy, BuildHlslSource.GetNonDynamicHlslSource(item.Hlsl), item.ThreadIds)) - .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default, EqualityComparer.Default); + .Select(static (item, token) => (item.Dispatch.Hierarchy, BuildHlslSource.GetNonDynamicHlslSource(item.Hlsl), item.ThreadIds)); // Compile the requested shader bytecodes IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = @@ -251,8 +245,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Get the filtered sequence to enable caching IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode = embeddedBytecodeWithErrors - .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo)) - .WithComparers(HierarchyInfo.Comparer.Default, EmbeddedBytecodeInfo.Comparer.Default); + .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo)); // Generate the TryGetBytecode() methods context.RegisterSourceOutput(embeddedBytecode.Combine(supportsDynamicShaders), static (context, item) => diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs index a87e21f0..4bb4d834 100644 --- a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs @@ -22,17 +22,23 @@ internal sealed record DispatchDataInfo( int ResourceCount, int Root32BitConstantCount) { + /// + public bool Equals(DispatchDataInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, DispatchDataInfo obj) { - hashCode.Add(HierarchyInfo.Comparer.Default.GetHashCode(obj.Hierarchy)); + hashCode.Add(obj.Hierarchy); hashCode.Add(obj.Type); - hashCode.AddRange(obj.FieldInfos, FieldInfo.Comparer.Default); + hashCode.AddRange(obj.FieldInfos); hashCode.Add(obj.ResourceCount); hashCode.Add(obj.Root32BitConstantCount); } @@ -41,9 +47,9 @@ internal sealed record DispatchDataInfo( protected override bool AreEqual(DispatchDataInfo x, DispatchDataInfo y) { return - HierarchyInfo.Comparer.Default.Equals(x.Hierarchy, y.Hierarchy) && + x.Hierarchy == y.Hierarchy && x.Type == y.Type && - x.FieldInfos.SequenceEqual(y.FieldInfos, FieldInfo.Comparer.Default) && + x.FieldInfos.SequenceEqual(y.FieldInfos) && x.ResourceCount == y.ResourceCount && x.Root32BitConstantCount == y.Root32BitConstantCount; } diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs index 348ef0c7..d0b590cb 100644 --- a/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs @@ -12,10 +12,16 @@ namespace ComputeSharp.SourceGenerators.Models; /// The list of delegate field names for the shader. internal sealed record DispatchIdInfo(ImmutableArray Delegates) { + /// + public bool Equals(DispatchIdInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, DispatchIdInfo obj) diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs index f49ccb64..93ca74ff 100644 --- a/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs @@ -17,10 +17,16 @@ internal sealed record DispatchMetadataInfo( bool IsSamplerUsed, ImmutableArray ResourceDescriptors) { + /// + public bool Equals(DispatchMetadataInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, DispatchMetadataInfo obj) diff --git a/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs b/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs index df2931af..ca2f6093 100644 --- a/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs @@ -15,10 +15,16 @@ namespace ComputeSharp.SourceGenerators.Models; /// The compiled shader bytecode, if available. internal sealed record EmbeddedBytecodeInfo(int X, int Y, int Z, ImmutableArray Bytecode) { + /// + public bool Equals(EmbeddedBytecodeInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, EmbeddedBytecodeInfo obj) diff --git a/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs b/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs index ccfecb7b..44344c73 100644 --- a/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs @@ -17,7 +17,37 @@ internal abstract record FieldInfo /// The name of the resource field. /// The full metadata name for the resource type. /// The offset for the resource within the root signature. - public sealed record Resource(string FieldName, string TypeName, int Offset) : FieldInfo; + public sealed record Resource(string FieldName, string TypeName, int Offset) : FieldInfo + { + /// + public bool Equals(Resource? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + + /// + /// An implementation for . + /// + private sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, Resource obj) + { + hashCode.Add(obj.FieldName); + hashCode.Add(obj.TypeName); + hashCode.Add(obj.Offset); + } + + /// + protected override bool AreEqual(Resource x, Resource y) + { + return + x.FieldName == y.FieldName && + x.TypeName == y.TypeName && + x.Offset == y.Offset; + } + } + } /// /// A captured primitive value (either a scalar, a vector, or a linear matrix). @@ -25,7 +55,37 @@ internal abstract record FieldInfo /// The path of the field with respect to the shader instance. /// The full metadata name for the primitive type. /// The byte offset of the value within the root signature. - public sealed record Primitive(ImmutableArray FieldPath, string TypeName, int Offset) : FieldInfo; + public sealed record Primitive(ImmutableArray FieldPath, string TypeName, int Offset) : FieldInfo + { + /// + public bool Equals(Primitive? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + + /// + /// An implementation for . + /// + private sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, Primitive obj) + { + hashCode.AddRange(obj.FieldPath); + hashCode.Add(obj.TypeName); + hashCode.Add(obj.Offset); + } + + /// + protected override bool AreEqual(Primitive x, Primitive y) + { + return + x.FieldPath.SequenceEqual(y.FieldPath) && + x.TypeName == y.TypeName && + x.Offset == y.Offset; + } + } + } /// /// A captured non linear matrix value. @@ -42,70 +102,41 @@ internal abstract record FieldInfo string ElementName, int Rows, int Columns, - ImmutableArray Offsets) : FieldInfo; - - /// - /// An implementation for . - /// - public sealed class Comparer : Comparer + ImmutableArray Offsets) : FieldInfo { /// - protected override void AddToHashCode(ref HashCode hashCode, FieldInfo obj) - { - switch (obj) - { - case Resource resource: - hashCode.Add(resource.FieldName); - hashCode.Add(resource.TypeName); - hashCode.Add(resource.Offset); - break; - case Primitive primitive: - hashCode.AddRange(primitive.FieldPath); - hashCode.Add(primitive.TypeName); - hashCode.Add(primitive.Offset); - break; - case NonLinearMatrix matrix: - hashCode.AddRange(matrix.FieldPath); - hashCode.Add(matrix.TypeName); - hashCode.Add(matrix.ElementName); - hashCode.Add(matrix.Rows); - hashCode.Add(matrix.Columns); - hashCode.AddRange(matrix.Offsets); - break; - default: - break; - } - } + public bool Equals(NonLinearMatrix? obj) => Comparer.Default.Equals(this, obj); /// - protected override bool AreEqual(FieldInfo x, FieldInfo y) + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + + /// + /// An implementation for . + /// + private sealed class Comparer : Comparer { - if (x is Resource resourceX && y is Resource resourceY) + /// + protected override void AddToHashCode(ref HashCode hashCode, NonLinearMatrix obj) { - return - resourceX.FieldName == resourceY.FieldName && - resourceX.TypeName == resourceY.TypeName && - resourceX.Offset == resourceY.Offset; - } - else if (x is Primitive primitiveX && y is Primitive primitiveY) - { - return - primitiveX.FieldPath.SequenceEqual(primitiveY.FieldPath) && - primitiveX.TypeName == primitiveY.TypeName && - primitiveX.Offset == primitiveY.Offset; - } - else if (x is NonLinearMatrix matrixX && y is NonLinearMatrix matrixY) - { - return - matrixX.FieldPath.SequenceEqual(matrixY.FieldPath) && - matrixX.TypeName == matrixY.TypeName && - matrixX.ElementName == matrixY.ElementName && - matrixX.Rows == matrixY.Rows && - matrixY.Columns == matrixY.Columns && - matrixX.Offsets.SequenceEqual(matrixY.Offsets); + hashCode.AddRange(obj.FieldPath); + hashCode.Add(obj.TypeName); + hashCode.Add(obj.ElementName); + hashCode.Add(obj.Rows); + hashCode.Add(obj.Columns); + hashCode.AddRange(obj.Offsets); } - return false; + /// + protected override bool AreEqual(NonLinearMatrix x, NonLinearMatrix y) + { + return + x.FieldPath.SequenceEqual(y.FieldPath) && + x.TypeName == y.TypeName && + x.ElementName == y.ElementName && + x.Rows == y.Rows && + x.Columns == y.Columns && + x.Offsets.SequenceEqual(y.Offsets); + } } } } diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs index f2d18357..ca4b2921 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs @@ -21,10 +21,16 @@ internal sealed record HlslMethodSourceInfo( ImmutableArray<(string Name, string Value)> DefinedConstants, ImmutableArray<(string Signature, string Definition)> DependentMethods) { + /// + public bool Equals(HlslMethodSourceInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, HlslMethodSourceInfo obj) diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs index 46f21c35..bf44b779 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs @@ -39,10 +39,16 @@ internal sealed record HlslShaderSourceInfo( ImmutableArray MethodSignatures, ImmutableArray Delegates) { + /// + public bool Equals(HlslShaderSourceInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// /// An implementation for . /// - public sealed class Comparer : Comparer + private sealed class Comparer : Comparer { /// protected override void AddToHashCode(ref HashCode hashCode, HlslShaderSourceInfo obj) diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index e7323701..936069b3 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -57,8 +57,7 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator // Get the filtered sequence to enable caching IncrementalValuesProvider methodSourceInfo = methodSourceInfoWithErrors - .Select(static (item, token) => item.Value) - .WithComparer(HlslMethodSourceInfo.Comparer.Default); + .Select(static (item, token) => item.Value); // Generate the [ShaderMethodSource] attributes context.RegisterSourceOutput(methodSourceInfo, static (context, item) => From 2e21e02fc672c0a81fbda9ce01508f445b941263 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Sep 2022 15:21:46 +0200 Subject: [PATCH 09/20] Remove leftover comparer extensions --- .../ComputeSharp.SourceGeneration.projitems | 1 - .../IncrementalValuesProviderExtensions.cs | 323 ------------------ 2 files changed, 324 deletions(-) delete mode 100644 src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index eb8eff64..9b0bfa64 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -15,7 +15,6 @@ - diff --git a/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs deleted file mode 100644 index a338cc34..00000000 --- a/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs +++ /dev/null @@ -1,323 +0,0 @@ -using System; -using System.Collections.Generic; -using Microsoft.CodeAnalysis; - -namespace ComputeSharp.SourceGeneration.Extensions; - -/// -/// Extension methods for . -/// -internal static class IncrementalValuesProviderExtensions -{ - /// - /// Creates a new instance with a gven pair of comparers. - /// - /// The type of left items in each tuple. - /// The type of right items in each tuple. - /// The input instance. - /// An instance for items. - /// An instance for items. - /// An with the specified comparers applied to each item. - public static IncrementalValuesProvider<(TLeft Left, TRight Right)> WithComparers( - this IncrementalValuesProvider<(TLeft Left, TRight Right)> source, - IEqualityComparer comparerLeft, - IEqualityComparer comparerRight) - { - return source.WithComparer(new Comparer(comparerLeft, comparerRight)); - } - - /// - /// Creates a new instance with a gven pair of comparers. - /// - /// The type of first items in each tuple. - /// The type of second items in each tuple. - /// The type of third items in each tuple. - /// The input instance. - /// An instance for items. - /// An instance for items. - /// An instance for items. - /// An with the specified comparers applied to each item. - public static IncrementalValuesProvider<(T1, T2, T3)> WithComparers( - this IncrementalValuesProvider<(T1, T2, T3)> source, - IEqualityComparer comparer1, - IEqualityComparer comparer2, - IEqualityComparer comparer3) - { - return source.WithComparer(new Comparer(comparer1, comparer2, comparer3)); - } - - /// - /// Creates a new instance with a gven pair of comparers. - /// - /// The type of first items in each tuple. - /// The type of second items in each tuple. - /// The type of third items in each tuple. - /// The type of fourth items in each tuple. - /// The input instance. - /// An instance for items. - /// An instance for items. - /// An instance for items. - /// An instance for items. - /// An with the specified comparers applied to each item. - public static IncrementalValuesProvider<(T1, T2, T3, T4)> WithComparers( - this IncrementalValuesProvider<(T1, T2, T3, T4)> source, - IEqualityComparer comparer1, - IEqualityComparer comparer2, - IEqualityComparer comparer3, - IEqualityComparer comparer4) - { - return source.WithComparer(new Comparer(comparer1, comparer2, comparer3, comparer4)); - } - - /// - /// Creates a new instance with a gven pair of comparers. - /// - /// The type of first items in each tuple. - /// The type of second items in each tuple. - /// The type of third items in each tuple. - /// The type of fourth items in each tuple. - /// The type of fourth items in each tuple. - /// The input instance. - /// An instance for items. - /// An instance for items. - /// An instance for items. - /// An instance for items. - /// An instance for items. - /// An with the specified comparers applied to each item. - public static IncrementalValuesProvider<(T1, T2, T3, T4, T5)> WithComparers( - this IncrementalValuesProvider<(T1, T2, T3, T4, T5)> source, - IEqualityComparer comparer1, - IEqualityComparer comparer2, - IEqualityComparer comparer3, - IEqualityComparer comparer4, - IEqualityComparer comparer5) - { - return source.WithComparer(new Comparer(comparer1, comparer2, comparer3, comparer4, comparer5)); - } - - /// - /// An implementation for a value tuple. - /// - public sealed class Comparer : IEqualityComparer<(TLeft Left, TRight Right)> - { - /// - /// The comparer. - /// - private readonly IEqualityComparer comparerLeft; - - /// - /// The comparer. - /// - private readonly IEqualityComparer comparerRight; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The comparer. - /// The comparer. - public Comparer(IEqualityComparer comparerLeft, IEqualityComparer comparerRight) - { - this.comparerLeft = comparerLeft; - this.comparerRight = comparerRight; - } - - /// - public bool Equals((TLeft Left, TRight Right) x, (TLeft Left, TRight Right) y) - { - return - this.comparerLeft.Equals(x.Left, y.Left) && - this.comparerRight.Equals(x.Right, y.Right); - } - - /// - public int GetHashCode((TLeft Left, TRight Right) obj) - { - return HashCode.Combine( - this.comparerLeft.GetHashCode(obj.Left), - this.comparerRight.GetHashCode(obj.Right)); - } - } - - /// - /// An implementation for a value tuple. - /// - public sealed class Comparer : IEqualityComparer<(T1, T2, T3)> - { - /// - /// The comparer. - /// - private readonly IEqualityComparer comparer1; - - /// - /// The comparer. - /// - private readonly IEqualityComparer comparer2; - - /// - /// The comparer. - /// - private readonly IEqualityComparer comparer3; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The comparer. - /// The comparer. - /// The comparer. - public Comparer(IEqualityComparer comparer1, IEqualityComparer comparer2, IEqualityComparer comparer3) - { - this.comparer1 = comparer1; - this.comparer2 = comparer2; - this.comparer3 = comparer3; - } - - /// - public bool Equals((T1, T2, T3) x, (T1, T2, T3) y) - { - return - this.comparer1.Equals(x.Item1, y.Item1) && - this.comparer2.Equals(x.Item2, y.Item2) && - this.comparer3.Equals(x.Item3, y.Item3); - } - - /// - public int GetHashCode((T1, T2, T3) obj) - { - return HashCode.Combine( - this.comparer1.GetHashCode(obj.Item1), - this.comparer2.GetHashCode(obj.Item2), - this.comparer3.GetHashCode(obj.Item3)); - } - } - - /// - /// An implementation for a value tuple. - /// - public sealed class Comparer : IEqualityComparer<(T1, T2, T3, T4)> - { - /// - /// The comparer. - /// - private readonly IEqualityComparer comparer1; - - /// - /// The comparer. - /// - private readonly IEqualityComparer comparer2; - - /// - /// The comparer. - /// - private readonly IEqualityComparer comparer3; - - /// - /// The comparer. - /// - private readonly IEqualityComparer comparer4; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The comparer. - /// The comparer. - /// The comparer. - /// The comparer. - public Comparer(IEqualityComparer comparer1, IEqualityComparer comparer2, IEqualityComparer comparer3, IEqualityComparer comparer4) - { - this.comparer1 = comparer1; - this.comparer2 = comparer2; - this.comparer3 = comparer3; - this.comparer4 = comparer4; - } - - /// - public bool Equals((T1, T2, T3, T4) x, (T1, T2, T3, T4) y) - { - return - this.comparer1.Equals(x.Item1, y.Item1) && - this.comparer2.Equals(x.Item2, y.Item2) && - this.comparer3.Equals(x.Item3, y.Item3) && - this.comparer4.Equals(x.Item4, y.Item4); - } - - /// - public int GetHashCode((T1, T2, T3, T4) obj) - { - return HashCode.Combine( - this.comparer1.GetHashCode(obj.Item1), - this.comparer2.GetHashCode(obj.Item2), - this.comparer3.GetHashCode(obj.Item3), - this.comparer4.GetHashCode(obj.Item4)); - } - } - - /// - /// An implementation for a value tuple. - /// - public sealed class Comparer : IEqualityComparer<(T1, T2, T3, T4, T5)> - { - /// - /// The comparer. - /// - private readonly IEqualityComparer comparer1; - - /// - /// The comparer. - /// - private readonly IEqualityComparer comparer2; - - /// - /// The comparer. - /// - private readonly IEqualityComparer comparer3; - - /// - /// The comparer. - /// - private readonly IEqualityComparer comparer4; - - /// - /// The comparer. - /// - private readonly IEqualityComparer comparer5; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The comparer. - /// The comparer. - /// The comparer. - /// The comparer. - /// The comparer. - public Comparer(IEqualityComparer comparer1, IEqualityComparer comparer2, IEqualityComparer comparer3, IEqualityComparer comparer4, IEqualityComparer comparer5) - { - this.comparer1 = comparer1; - this.comparer2 = comparer2; - this.comparer3 = comparer3; - this.comparer4 = comparer4; - this.comparer5 = comparer5; - } - - /// - public bool Equals((T1, T2, T3, T4, T5) x, (T1, T2, T3, T4, T5) y) - { - return - this.comparer1.Equals(x.Item1, y.Item1) && - this.comparer2.Equals(x.Item2, y.Item2) && - this.comparer3.Equals(x.Item3, y.Item3) && - this.comparer4.Equals(x.Item4, y.Item4) && - this.comparer5.Equals(x.Item5, y.Item5); - } - - /// - public int GetHashCode((T1, T2, T3, T4, T5) obj) - { - return HashCode.Combine( - this.comparer1.GetHashCode(obj.Item1), - this.comparer2.GetHashCode(obj.Item2), - this.comparer3.GetHashCode(obj.Item3), - this.comparer4.GetHashCode(obj.Item4), - this.comparer5.GetHashCode(obj.Item5)); - } - } -} From d62c4596334086d80ce84e781e6c080e70aed11c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Sep 2022 16:43:13 +0200 Subject: [PATCH 10/20] Remove symbols from ID2D1ShaderGenerator pipeline --- ...eUninitializedFieldDiagnosticSuppressor.cs | 2 +- ...rator.CreateLoadInputDescriptionsMethod.cs | 20 +- .../ID2D1ShaderGenerator.Helpers.cs | 16 +- .../ID2D1ShaderGenerator.cs | 320 ++++++++---------- .../Models/D2D1ShaderInfo.cs | 74 ++++ .../Extensions/SyntaxNodeExtensions.cs | 34 ++ 6 files changed, 266 insertions(+), 200 deletions(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Suppressors/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Suppressors/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs index 43e4f83c..02822084 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Suppressors/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Suppressors/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs @@ -61,7 +61,7 @@ public sealed class D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor : } // Also check if the containing type is in fact a D2D1 pixel shader type - if (ID2D1ShaderGenerator.IsD2D1PixelShaderType(structSymbol, pixelShaderInterfaceSymbol)) + if (ID2D1ShaderGenerator.IsD2D1PixelShaderType(structSymbol, semanticModel.Compilation)) { context.ReportSuppression(Suppression.Create(UninitializedD2D1ResourceTextureField, diagnostic)); } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs index 04228cff..1bfbf0c5 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs @@ -20,17 +20,16 @@ partial class ID2D1ShaderGenerator /// /// Extracts the input descriptions for the current shader. /// + /// The collection of produced instances. /// The input instance to process. /// The produced input descriptions for the shader. - /// The collection of produced instances. public static void GetInfo( + ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol, - out ImmutableArray inputDescriptions, - out ImmutableArray diagnostics) + out ImmutableArray inputDescriptions) { int inputCount = 0; ImmutableArray.Builder inputDescriptionsBuilder = ImmutableArray.CreateBuilder(); - ImmutableArray.Builder diagnosticsBuilder = ImmutableArray.CreateBuilder(); foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes()) { @@ -60,15 +59,15 @@ partial class ID2D1ShaderGenerator // Validate the input count (ignore if invalid, this will be validated by GetInputType() generator) if (inputCount is not (>= 0 and <= 8)) { - goto End; + return; } // All simple indices must be in range if (inputDescriptionsBuilder.Any(description => description.Index >= inputCount)) { - diagnosticsBuilder.Add(OutOfRangeInputDescriptionIndex, structDeclarationSymbol, structDeclarationSymbol); + diagnostics.Add(OutOfRangeInputDescriptionIndex, structDeclarationSymbol, structDeclarationSymbol); - goto End; + return; } HashSet inputDescriptionIndices = new(inputDescriptionsBuilder.Select(description => description.Index)); @@ -76,15 +75,12 @@ partial class ID2D1ShaderGenerator // All input description indices must be unique if (inputDescriptionIndices.Count != inputDescriptionsBuilder.Count) { - diagnosticsBuilder.Add(RepeatedD2DInputDescriptionIndices, structDeclarationSymbol, structDeclarationSymbol); + diagnostics.Add(RepeatedD2DInputDescriptionIndices, structDeclarationSymbol, structDeclarationSymbol); - goto End; + return; } inputDescriptions = inputDescriptionsBuilder.ToImmutable(); - - End: - diagnostics = diagnosticsBuilder.ToImmutable(); } } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs index b213fcc4..6d1c78fc 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs @@ -14,16 +14,20 @@ partial class ID2D1ShaderGenerator /// Gets the shader type for a given shader, if any. /// /// The input instance to check. - /// The instance for . - /// Whether or not implements . - public static bool IsD2D1PixelShaderType(INamedTypeSymbol typeSymbol, INamedTypeSymbol d2D1PixelShaderSymbol) + /// The instance currently in use. + /// Whether or not is a D2D1 interface type. + public static bool IsD2D1PixelShaderType(INamedTypeSymbol typeSymbol, Compilation compilation) { foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.AllInterfaces) { - if (interfaceSymbol.Name == nameof(ID2D1PixelShader) && - SymbolEqualityComparer.Default.Equals(interfaceSymbol, d2D1PixelShaderSymbol)) + if (interfaceSymbol.Name == nameof(ID2D1PixelShader)) { - return true; + INamedTypeSymbol d2D1PixelShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.D2D1.ID2D1PixelShader")!; + + if (SymbolEqualityComparer.Default.Equals(interfaceSymbol, d2D1PixelShaderSymbol)) + { + return true; + } } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 4a174c41..a3350ad5 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; @@ -22,121 +21,121 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator /// public void Initialize(IncrementalGeneratorInitializationContext context) { + IncrementalValuesProvider shaderInfoWithErrors = + context.SyntaxProvider + .CreateSyntaxProvider( + static (node, _) => node.IsTypeDeclarationWithOrPotentiallyWithBaseTypes(), + static (context, token) => + { + StructDeclarationSyntax typeDeclaration = (StructDeclarationSyntax)context.Node; + + // If the type symbol doesn't have at least one interface, it can't possibly be a shader type + if (context.SemanticModel.GetDeclaredSymbol(typeDeclaration, token) is not INamedTypeSymbol { AllInterfaces.Length: > 0 } typeSymbol) + { + return default; + } + + // Check that the shader implements the ID2D1PixelShader interface + if (!IsD2D1PixelShaderType(typeSymbol, context.SemanticModel.Compilation)) + { + return default; + } + + ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + + // LoadDispatchData() info + ImmutableArray fieldInfos = LoadDispatchData.GetInfo( + diagnostics, + typeSymbol, + out int constantBufferSizeInBytes); + + token.ThrowIfCancellationRequested(); + + // Get the input info for GetInputInfo() + GetInputType.GetInfo( + diagnostics, + typeSymbol, + out int inputCount, + out ImmutableArray inputSimpleIndices, + out ImmutableArray inputComplexIndices, + out ImmutableArray inputTypes); + + // Get the resource texture info for LoadResourceTextureDescriptions() + LoadResourceTextureDescriptions.GetInfo( + diagnostics, + typeSymbol, + inputCount, + out ImmutableArray resourceTextureDescriptions); + + // Get HLSL source for BuildHlslSource() + string hlslSource = BuildHlslSource.GetHlslSource( + diagnostics, + context.SemanticModel.Compilation, + typeDeclaration, + typeSymbol, + inputCount, + inputSimpleIndices, + inputComplexIndices); + + token.ThrowIfCancellationRequested(); + + // Get the shader profile and linking info for LoadBytecode() + D2D1ShaderProfile? shaderProfile = LoadBytecode.GetShaderProfile(typeSymbol); + D2D1CompileOptions? compileOptions = LoadBytecode.GetCompileOptions(diagnostics, typeSymbol); + bool isLinkingSupported = LoadBytecode.IsSimpleInputShader(typeSymbol, inputCount); + + token.ThrowIfCancellationRequested(); + + // Get the info for GetOutputBuffer() + GetOutputBuffer.GetInfo(typeSymbol, out D2D1BufferPrecision bufferPrecision, out D2D1ChannelDepth channelDepth); + + token.ThrowIfCancellationRequested(); + + // Get the info for LoadInputDescriptions() + LoadInputDescriptions.GetInfo( + diagnostics, + typeSymbol, + out ImmutableArray inputDescriptions); + + token.ThrowIfCancellationRequested(); + + // Get the info for GetPixelOptions() + GetPixelOptions.GetInfo(typeSymbol, out D2D1PixelOptions pixelOptions); + + token.ThrowIfCancellationRequested(); + + return new D2D1ShaderInfo( + Hierarchy: HierarchyInfo.From(typeSymbol), + DispatchData: new DispatchDataInfo(fieldInfos, constantBufferSizeInBytes), + InputTypes: new InputTypesInfo(inputTypes), + ResourceTextureDescriptions: new ResourceTextureDescriptionsInfo(resourceTextureDescriptions), + HlslShaderSource: new HlslShaderSourceInfo( + hlslSource, + shaderProfile, + compileOptions, + isLinkingSupported, + HasErrors: diagnostics.Count > 0), + OutputBuffer: new OutputBufferInfo(bufferPrecision, channelDepth), + InputDescriptions: new InputDescriptionsInfo(inputDescriptions), + PixelOptions: pixelOptions, + Diagnostcs: diagnostics.ToImmutable()); + }) + .Where(static item => item is not null)!; + // Check whether [SkipLocalsInit] can be used IncrementalValueProvider canUseSkipLocalsInit = context.CompilationProvider - .Select(static (compilation, token) => + .Select(static (compilation, _) => compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } && compilation.HasAccessibleTypeWithMetadataName("System.Runtime.CompilerServices.SkipLocalsInitAttribute")); - // Get all declared struct types and their type symbols - IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol)> structDeclarations = - context.SyntaxProvider - .CreateSyntaxProvider( - static (node, token) => node is StructDeclarationSyntax structDeclaration, - static (context, token) => ( - (StructDeclarationSyntax)context.Node, - Symbol: (INamedTypeSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token))) - .Where(static pair => pair.Symbol is { Interfaces.IsEmpty: false })!; - - // Get the symbol for the ID2D1PixelShader interface - IncrementalValueProvider pixelShaderInterface = - context.CompilationProvider - .Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(ID2D1PixelShader).FullName)!); - - // Filter struct declarations that implement the shader interface, and also gather the hierarchy info - IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol, HierarchyInfo Hierarchy)> shaderDeclarations = - structDeclarations - .Combine(pixelShaderInterface) - .Where(static item => IsD2D1PixelShaderType(item.Left.Symbol, item.Right)) - .Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, HierarchyInfo.From(item.Left.Symbol))); - - // Get the dispatch data, input types, resource texture descriptions, HLSL source and embedded bytecode info. This info - // is computed on the same step as parts are shared in following sub-branches in the incremental generator pipeline. - IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, ResourceTextureDescriptionsInfo ResourceTextureDescriptions, HlslShaderSourceInfo Source, ImmutableArray Diagnostics)> shaderInfoWithErrors = - shaderDeclarations - .Combine(context.CompilationProvider) - .Select(static (item, token) => - { - ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); - - // LoadDispatchData() info - ImmutableArray fieldInfos = LoadDispatchData.GetInfo( - diagnostics, - item.Left.Symbol, - out int constantBufferSizeInBytes); - - token.ThrowIfCancellationRequested(); - - DispatchDataInfo dispatchDataInfo = new(fieldInfos, constantBufferSizeInBytes); - - // Get the input info for GetInputInfo() - GetInputType.GetInfo( - diagnostics, - item.Left.Symbol, - out int inputCount, - out ImmutableArray inputSimpleIndices, - out ImmutableArray inputComplexIndices, - out ImmutableArray inputTypes); - - InputTypesInfo inputTypesInfo = new(inputTypes); - - // Get the resource texture info for LoadResourceTextureDescriptions() - LoadResourceTextureDescriptions.GetInfo( - diagnostics, - item.Left.Symbol, - inputCount, - out ImmutableArray resourceTextureDescriptions); - - ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo = new(resourceTextureDescriptions); - - // Get HLSL source for BuildHlslSource() - string hlslSource = BuildHlslSource.GetHlslSource( - diagnostics, - item.Right, - item.Left.Syntax, - item.Left.Symbol, - inputCount, - inputSimpleIndices, - inputComplexIndices); - - token.ThrowIfCancellationRequested(); - - // Get the shader profile and linking info for LoadBytecode() - D2D1ShaderProfile? shaderProfile = LoadBytecode.GetShaderProfile(item.Left.Symbol); - D2D1CompileOptions? compileOptions = LoadBytecode.GetCompileOptions(diagnostics, item.Left.Symbol); - bool isLinkingSupported = LoadBytecode.IsSimpleInputShader(item.Left.Symbol, inputCount); - - HlslShaderSourceInfo sourceInfo = new( - hlslSource, - shaderProfile, - compileOptions, - isLinkingSupported, - HasErrors: diagnostics.Count > 0); - - token.ThrowIfCancellationRequested(); - - return ( - item.Left.Hierarchy, - dispatchDataInfo, - inputTypesInfo, - resourceTextureDescriptionsInfo, - sourceInfo, - diagnostics.ToImmutableArray()); - }); - // Output the diagnostics - context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Diagnostics)); + context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, _) => item.Diagnostcs)); - // Filter all items to enable caching at a coarse level, and remove diagnostics - IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, ResourceTextureDescriptionsInfo ResourceTextureDescriptions, HlslShaderSourceInfo Source)> shaderInfo = - shaderInfoWithErrors - .Select(static (item, token) => (item.Hierarchy, item.Dispatch, item.InputTypes, item.ResourceTextureDescriptions, item.Source)); - - // Filter items to enable caching for the input count methods + // Get the GetInputCount() info (hierarchy and input count) IncrementalValuesProvider<(HierarchyInfo Hierarchy, int InputCount)> inputCountInfo = - shaderInfo - .Select(static (item, token) => (item.Hierarchy, item.InputTypes.InputTypes.Length)); + shaderInfoWithErrors + .Select(static (item, _) => (item.Hierarchy, item.InputTypes.InputTypes.Length)); // Generate the GetInputCount() methods context.RegisterSourceOutput(inputCountInfo, static (context, item) => @@ -147,10 +146,10 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetInputCount)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); - // Get a filtered sequence to enable caching + // Get the GetInputType() info (hierarchy and input types) IncrementalValuesProvider<(HierarchyInfo Hierarchy, InputTypesInfo InputTypes)> inputTypesInfo = - shaderInfo - .Select(static (item, token) => (item.Hierarchy, item.InputTypes)); + shaderInfoWithErrors + .Select(static (item, _) => (item.Hierarchy, item.InputTypes)); // Generate the GetInputType() methods context.RegisterSourceOutput(inputTypesInfo, static (context, item) => @@ -161,10 +160,10 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetInputType)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); - // Get a filtered sequence to enable caching + // Get the LoadResourceTextureDescriptions() info (hierarchy and resource texture descriptions) IncrementalValuesProvider<(HierarchyInfo Hierarchy, ResourceTextureDescriptionsInfo ResourceTextureDescriptions)> resourceTextureDescriptionsInfo = - shaderInfo - .Select(static (item, token) => (item.Hierarchy, item.ResourceTextureDescriptions)); + shaderInfoWithErrors + .Select(static (item, _) => (item.Hierarchy, item.ResourceTextureDescriptions)); // Generate the LoadResourceTextureDescriptions() methods context.RegisterSourceOutput(resourceTextureDescriptionsInfo.Combine(canUseSkipLocalsInit), static (context, item) => @@ -175,10 +174,10 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadResourceTextureDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); - // Get a filtered sequence to enable caching + // Get the info for both LoadDispatchData() and InitializeFromDispatchData() (hierarchy and dispatch data) IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch)> dispatchDataInfo = - shaderInfo - .Select(static (item, token) => (item.Hierarchy, item.Dispatch)); + shaderInfoWithErrors + .Select(static (item, _) => (item.Hierarchy, item.DispatchData)); // Generate the LoadDispatchData() methods context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) => @@ -198,10 +197,10 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(InitializeFromDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); - // Get the filtered sequence to enable caching + // Get the BuildHlslSource() info (hierarchy and HLSL source) IncrementalValuesProvider<(HierarchyInfo Hierarchy, string HlslSource)> hlslSourceInfo = - shaderInfo - .Select(static (item, token) => (item.Hierarchy, item.Source.HlslSource)); + shaderInfoWithErrors + .Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource.HlslSource)); // Generate the BuildHlslSource() methods context.RegisterSourceOutput(hlslSourceInfo, static (context, item) => @@ -212,10 +211,10 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); - // Get a filtered sequence to enable caching + // Get a filtered sequence to enable caching for the HLSL source info, before the shader compilation step IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo Source)> shaderBytecodeInfo = - shaderInfo - .Select(static (item, token) => (item.Hierarchy, item.Source)); + shaderInfoWithErrors + .Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource)); // Compile the requested shader bytecodes IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = @@ -242,10 +241,10 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Gather the diagnostics IncrementalValuesProvider embeddedBytecodeDiagnostics = embeddedBytecodeWithErrors - .Select(static (item, token) => (item.Hierarchy.FullyQualifiedMetadataName, item.Diagnostic)) + .Select(static (item, _) => (item.Hierarchy.FullyQualifiedMetadataName, item.Diagnostic)) .Where(static item => item.Diagnostic is not null) .Combine(context.CompilationProvider) - .Select(static (item, token) => + .Select(static (item, _) => { INamedTypeSymbol typeSymbol = item.Right.GetTypeByMetadataName(item.Left.FullyQualifiedMetadataName)!; @@ -261,7 +260,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Get the filtered sequence to enable caching IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode = embeddedBytecodeWithErrors - .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo)); + .Select(static (item, _) => (item.Hierarchy, item.BytecodeInfo)); // Generate the LoadBytecode() methods context.RegisterSourceOutput(embeddedBytecode, static (context, item) => @@ -273,84 +272,43 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(LoadBytecode)}.g.cs", text); }); - // Get the output buffer data, which can be computed separately from all other generation steps. - // Caching at a fine grained level can be enabled immediately, as both models are comparable. - IncrementalValuesProvider<(HierarchyInfo Hierarchy, OutputBufferInfo Info)> outputBufferInfo = - shaderDeclarations - .Select(static (item, token) => - { - // GetOutputBuffer() info - GetOutputBuffer.GetInfo(item.Symbol, out D2D1BufferPrecision bufferPrecision, out D2D1ChannelDepth channelDepth); - - token.ThrowIfCancellationRequested(); - - OutputBufferInfo outputBufferInfo = new(bufferPrecision, channelDepth); - - return (item.Hierarchy, outputBufferInfo); - }); + // Get the GetOutputBuffer() info (hierarchy and output buffers) + IncrementalValuesProvider<(HierarchyInfo Hierarchy, OutputBufferInfo OutputBuffer)> outputBufferInfo = + shaderInfoWithErrors + .Select(static (item, _) => (item.Hierarchy, item.OutputBuffer)); // Generate the GetOutputBuffer() methods context.RegisterSourceOutput(outputBufferInfo, static (context, item) => { - MethodDeclarationSyntax getOutputBufferMethod = GetOutputBuffer.GetSyntax(item.Info); + MethodDeclarationSyntax getOutputBufferMethod = GetOutputBuffer.GetSyntax(item.OutputBuffer); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getOutputBufferMethod, canUseSkipLocalsInit: false); context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetOutputBuffer)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); - // Get the input description data, which can also be computed separately from all other generation steps. - IncrementalValuesProvider<(HierarchyInfo Hierarchy, Result Info)> inputDescriptionsInfoWithErrors = - shaderDeclarations - .Select(static (item, token) => - { - // LoadInputDescriptions() info - LoadInputDescriptions.GetInfo( - item.Symbol, - out ImmutableArray inputDescriptions, - out ImmutableArray diagnostics); - - token.ThrowIfCancellationRequested(); - - InputDescriptionsInfo inputDescriptionsInfo = new(inputDescriptions); - - return (item.Hierarchy, new Result(inputDescriptionsInfo, diagnostics)); - }); - - // Output the diagnostics - context.ReportDiagnostics(inputDescriptionsInfoWithErrors.Select(static (item, token) => item.Info.Errors)); - - // Get the filtered sequence to enable caching - IncrementalValuesProvider<(HierarchyInfo Hierarchy, InputDescriptionsInfo Info)> inputDescriptionsInfo = - inputDescriptionsInfoWithErrors - .Select(static (item, token) => (item.Hierarchy, item.Info.Value)); + // Get the LoadInputDescriptions() info (hierarchy and input descriptions) + IncrementalValuesProvider<(HierarchyInfo Hierarchy, InputDescriptionsInfo InputDescriptions)> inputDescriptionsInfo = + shaderInfoWithErrors + .Select(static (item, _) => (item.Hierarchy, item.InputDescriptions)); // Generate the LoadInputDescriptions() methods context.RegisterSourceOutput(inputDescriptionsInfo.Combine(canUseSkipLocalsInit), static (context, item) => { - MethodDeclarationSyntax loadInputDescriptionsMethod = LoadInputDescriptions.GetSyntax(item.Left.Info); + MethodDeclarationSyntax loadInputDescriptionsMethod = LoadInputDescriptions.GetSyntax(item.Left.InputDescriptions); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, loadInputDescriptionsMethod, canUseSkipLocalsInit: item.Right); context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadInputDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); - // Get the pixel options, again independently from other generation steps. - // This can also be immediately cached at a fine grained level. - IncrementalValuesProvider<(HierarchyInfo Hierarchy, D2D1PixelOptions Options)> pixelOptionsInfo = - shaderDeclarations - .Select(static (item, token) => - { - // GetPixelOptions() info - GetPixelOptions.GetInfo(item.Symbol, out D2D1PixelOptions pixelOptions); - - token.ThrowIfCancellationRequested(); - - return (item.Hierarchy, pixelOptions); - }); + // Get the GetPixelOptions() info (hierarchy and pixel options) + IncrementalValuesProvider<(HierarchyInfo Hierarchy, D2D1PixelOptions PixelOptions)> pixelOptionsInfo = + shaderInfoWithErrors + .Select(static (item, _) => (item.Hierarchy, item.PixelOptions)); // Generate the GetPixelOptions() methods context.RegisterSourceOutput(pixelOptionsInfo, static (context, item) => { - MethodDeclarationSyntax getPixelOptionsMethod = GetPixelOptions.GetSyntax(item.Options); + MethodDeclarationSyntax getPixelOptionsMethod = GetPixelOptions.GetSyntax(item.PixelOptions); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getPixelOptionsMethod, canUseSkipLocalsInit: false); context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetPixelOptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs new file mode 100644 index 00000000..ed1692f0 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model representing all necessary info for a full generation pass for a D2D1 shader. +/// +/// The hierarchy info for the shader type. +/// The gathered shader dispatch data. +/// The gathered input types for the shader. +/// The gathered resource texture descriptions for the shader. +/// The processed HLSL source for the shader. +/// The output buffer info for the shader. +/// The gathered input descriptions for the shader. +/// The pixel options used by the shader. +/// The discovered diagnostics, if any. +internal sealed record D2D1ShaderInfo( + HierarchyInfo Hierarchy, + DispatchDataInfo DispatchData, + InputTypesInfo InputTypes, + ResourceTextureDescriptionsInfo ResourceTextureDescriptions, + HlslShaderSourceInfo HlslShaderSource, + OutputBufferInfo OutputBuffer, + InputDescriptionsInfo InputDescriptions, + D2D1PixelOptions PixelOptions, + ImmutableArray Diagnostcs) +{ + /// + public bool Equals(D2D1ShaderInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + + /// + /// An implementation for . + /// + private sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, D2D1ShaderInfo obj) + { + hashCode.Add(obj.Hierarchy); + hashCode.Add(obj.DispatchData); + hashCode.Add(obj.InputTypes); + hashCode.Add(obj.ResourceTextureDescriptions); + hashCode.Add(obj.HlslShaderSource); + hashCode.Add(obj.OutputBuffer); + hashCode.Add(obj.InputDescriptions); + hashCode.Add(obj.PixelOptions); + hashCode.AddRange(obj.Diagnostcs); + } + + /// + protected override bool AreEqual(D2D1ShaderInfo x, D2D1ShaderInfo y) + { + return + x.Hierarchy == y.Hierarchy && + x.DispatchData == y.DispatchData && + x.InputTypes == y.InputTypes && + x.ResourceTextureDescriptions == y.ResourceTextureDescriptions && + x.HlslShaderSource == y.HlslShaderSource && + x.OutputBuffer == y.OutputBuffer && + x.InputDescriptions == y.InputDescriptions && + x.PixelOptions == y.PixelOptions && + x.Diagnostcs.SequenceEqual(y.Diagnostcs); + } + } +} diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Extensions/SyntaxNodeExtensions.cs index 86d574e5..d9a2fd78 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/Extensions/SyntaxNodeExtensions.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Extensions/SyntaxNodeExtensions.cs @@ -13,6 +13,40 @@ namespace ComputeSharp.SourceGeneration.Extensions; /// internal static class SyntaxNodeExtensions { + /// + /// Checks whether a given is a given type declaration with or potentially with any base types, using only syntax. + /// + /// The type of declaration to check for. + /// The input to check. + /// Whether is a given type declaration with or potentially with any base types. + public static bool IsTypeDeclarationWithOrPotentiallyWithBaseTypes(this SyntaxNode node) + where T : TypeDeclarationSyntax + { + // Immediately bail if the node is not a type declaration of the specified type + if (node is not T typeDeclaration) + { + return false; + } + + // If the base types list is not empty, the type can definitely has implemented interfaces + if (typeDeclaration.BaseList is { Types.Count: > 0 }) + { + return true; + } + + // If the base types list is empty, check if the type is partial. If it is, it means + // that there could be another partial declaration with a non-empty base types list. + foreach (SyntaxToken modifier in typeDeclaration.Modifiers) + { + if (modifier.IsKind(SyntaxKind.PartialKeyword)) + { + return true; + } + } + + return false; + } + /// /// Checks a value and replaces the value type to be HLSL compatible, if needed. /// From 2b01a73233f2ec1ec0523d343f2327427dc14f64 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Sep 2022 16:49:37 +0200 Subject: [PATCH 11/20] Remove leftover extensions --- .../Extensions/DiagnosticsExtensions.cs | 32 ------------------- 1 file changed, 32 deletions(-) diff --git a/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs index 8426ed9c..69745a4e 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs @@ -9,38 +9,6 @@ namespace ComputeSharp.SourceGeneration.Extensions; /// internal static class DiagnosticsExtensions { - /// - /// Adds a new diagnostics to the current compilation. - /// - /// The instance currently in use. - /// The input for the diagnostics to create. - /// The source to attach the diagnostics to. - /// The optional arguments for the formatted message to include. - public static void ReportDiagnostic( - this GeneratorExecutionContext context, - DiagnosticDescriptor descriptor, - ISymbol symbol, - params object[] args) - { - context.ReportDiagnostic(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args)); - } - - /// - /// Adds a new diagnostics to the current compilation. - /// - /// The instance currently in use. - /// The input for the diagnostics to create. - /// The source to attach the diagnostics to. - /// The optional arguments for the formatted message to include. - public static void ReportDiagnostic( - this GeneratorExecutionContext context, - DiagnosticDescriptor descriptor, - SyntaxNode node, - params object[] args) - { - context.ReportDiagnostic(Diagnostic.Create(descriptor, node.GetLocation(), args)); - } - /// /// Adds a new diagnostics to the target builder. /// From bdaf402a4ccdc0182c66d52c259c679f043c7817 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Sep 2022 16:54:11 +0200 Subject: [PATCH 12/20] Add aggregate model for D2D1PixelShaderSourceInfo --- .../D2DPixelShaderSourceGenerator.cs | 54 +++++++++---------- .../Models/D2D1PixelShaderSourceInfo.cs | 50 +++++++++++++++++ 2 files changed, 76 insertions(+), 28 deletions(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs index b7e22c8e..8216e002 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs @@ -21,65 +21,63 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato public void Initialize(IncrementalGeneratorInitializationContext context) { // Get all method declarations with the [D2DPixelShaderSource] attribute and gather all necessary info - IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderMethodSourceInfo Source, ImmutableArray Diagnostics)> shaderInfoWithErrors = + IncrementalValuesProvider shaderInfoWithErrors = context.SyntaxProvider .ForAttributeWithMetadataName( typeof(D2DPixelShaderSourceAttribute).FullName, static (node, _) => node is MethodDeclarationSyntax, - static (context, _) => + static (context, token) => { MethodDeclarationSyntax methodDeclaration = (MethodDeclarationSyntax)context.TargetNode; IMethodSymbol methodSymbol = (IMethodSymbol)context.TargetSymbol; ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); - // Get all necessary info for the current shader + // Get the processed HLSL first and check for cancellation + string hlslSource = Execute.GetHlslSource(diagnostics, methodSymbol); + + token.ThrowIfCancellationRequested(); + + // Get the remaining info for the current shader ImmutableArray modifiers = methodDeclaration.Modifiers.Select(token => token.Kind()).ToImmutableArray(); string methodName = methodSymbol.Name; string? invalidReturnType = Execute.GetInvalidReturnType(diagnostics, methodSymbol); - string hlslSource = Execute.GetHlslSource(diagnostics, methodSymbol); D2D1ShaderProfile shaderProfile = Execute.GetShaderProfile(diagnostics, methodSymbol); D2D1CompileOptions compileOptions = Execute.GetCompileOptions(diagnostics, methodSymbol); - HlslShaderMethodSourceInfo sourceInfo = new( - modifiers, - methodName, - invalidReturnType, - hlslSource, - shaderProfile, - compileOptions, - HasErrors: diagnostics.Count > 0); - - HierarchyInfo hierarchy = HierarchyInfo.From(methodSymbol.ContainingType!); - - return (hierarchy, sourceInfo, diagnostics.ToImmutable()); + return new D2D1PixelShaderSourceInfo( + Hierarchy: HierarchyInfo.From(methodSymbol.ContainingType!), + HlslShaderMethodSource: new HlslShaderMethodSourceInfo( + modifiers, + methodName, + invalidReturnType, + hlslSource, + shaderProfile, + compileOptions, + HasErrors: diagnostics.Count > 0), + Diagnostcs: diagnostics.ToImmutable()); }); // Output the diagnostics - context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, _) => item.Diagnostics)); - - // Filter all items to enable caching at a coarse level, and remove diagnostics - IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderMethodSourceInfo Source)> shaderInfo = - shaderInfoWithErrors - .Select(static (item, token) => (item.Hierarchy, item.Source)); + context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, _) => item.Diagnostcs)); // Compile the requested shader bytecodes IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeMethodInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = - shaderInfo + shaderInfoWithErrors .Select(static (item, token) => { ImmutableArray bytecode = Execute.GetBytecode( - item.Source, + item.HlslShaderMethodSource, token, out DiagnosticInfo? diagnostic); token.ThrowIfCancellationRequested(); EmbeddedBytecodeMethodInfo bytecodeInfo = new( - item.Source.Modifiers, - item.Source.MethodName, - item.Source.InvalidReturnType, - item.Source.HlslSource, + item.HlslShaderMethodSource.Modifiers, + item.HlslShaderMethodSource.MethodName, + item.HlslShaderMethodSource.InvalidReturnType, + item.HlslShaderMethodSource.HlslSource, bytecode); return (item.Hierarchy, bytecodeInfo, diagnostic); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs new file mode 100644 index 00000000..41e1011c --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model representing all necessary info for a full generation pass for a [D2D1PixelShaderSource] attribute. +/// +/// The hierarchy info for the shader type. +/// The processed HLSL source for the shader. +/// The discovered diagnostics, if any. +internal sealed record D2D1PixelShaderSourceInfo( + HierarchyInfo Hierarchy, + HlslShaderMethodSourceInfo HlslShaderMethodSource, + ImmutableArray Diagnostcs) +{ + /// + public bool Equals(D2D1PixelShaderSourceInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + + /// + /// An implementation for . + /// + private sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, D2D1PixelShaderSourceInfo obj) + { + hashCode.Add(obj.Hierarchy); + hashCode.Add(obj.HlslShaderMethodSource); + hashCode.AddRange(obj.Diagnostcs); + } + + /// + protected override bool AreEqual(D2D1PixelShaderSourceInfo x, D2D1PixelShaderSourceInfo y) + { + return + x.Hierarchy == y.Hierarchy && + x.HlslShaderMethodSource == y.HlslShaderMethodSource && + x.Diagnostcs.SequenceEqual(y.Diagnostcs); + } + } +} From 9eac3c779df6ddc522d709e53b578722d53b4ce8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Sep 2022 17:58:44 +0200 Subject: [PATCH 13/20] Refactor diagnostic models to be properly equatable --- .../D2DPixelShaderSourceGenerator.Execute.cs | 22 +++--- .../D2DPixelShaderSourceGenerator.cs | 21 +++--- ...validD2DResourceTextureIndexUseAnalyzer.cs | 2 +- ...erGenerator.CreateBuildHlslSourceMethod.cs | 29 ++++---- ...haderGenerator.CreateGetInputTypeMethod.cs | 5 +- ...haderGenerator.CreateLoadBytecodeMethod.cs | 10 +-- ...rGenerator.CreateLoadDispatchDataMethod.cs | 5 +- ...rator.CreateLoadInputDescriptionsMethod.cs | 5 +- ...teLoadResourceTextureDescriptionsMethod.cs | 5 +- .../ID2D1ShaderGenerator.cs | 21 +++--- .../Models/D2D1PixelShaderSourceInfo.cs | 3 +- .../Models/D2D1ShaderInfo.cs | 3 +- .../SyntaxRewriters/HlslSourceRewriter.cs | 9 +-- .../SyntaxRewriters/ShaderSourceRewriter.cs | 9 +-- .../SyntaxRewriters/StaticFieldRewriter.cs | 5 +- .../ComputeSharp.SourceGeneration.projitems | 1 + .../Extensions/DiagnosticsExtensions.cs | 24 +++---- .../Extensions/IEqualityComparerExtensions.cs | 2 +- .../Models/DeferredDiagnosticInfo.cs | 55 +++++++++++++++ .../Models/DiagnosticInfo.cs | 69 ++++++++++++++++--- .../Models/Result{T}.cs | 3 +- ...erGenerator.CreateBuildHlslSourceMethod.cs | 29 ++++---- ...haderGenerator.CreateLoadBytecodeMethod.cs | 10 +-- ...rGenerator.CreateLoadDispatchDataMethod.cs | 5 +- .../IShaderGenerator.cs | 19 +++-- .../ShaderMethodSourceGenerator.cs | 10 +-- 26 files changed, 247 insertions(+), 134 deletions(-) create mode 100644 src/ComputeSharp.SourceGeneration/Models/DeferredDiagnosticInfo.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs index decf1272..e475010c 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs @@ -26,10 +26,10 @@ partial class D2DPixelShaderSourceGenerator /// /// Validates that the return type of the annotated method is valid and returns the type name. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input instance to process. /// The HLSL source to compile, if present. - public static string? GetInvalidReturnType(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + public static string? GetInvalidReturnType(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) { if (!(methodSymbol.ReturnType is INamedTypeSymbol { @@ -55,10 +55,10 @@ partial class D2DPixelShaderSourceGenerator /// /// Extracts the HLSL source from a method with the annotation. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input instance to process. /// The HLSL source to compile, if present. - public static string GetHlslSource(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + public static string GetHlslSource(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) { _ = methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute", out AttributeData? attributeData); @@ -77,10 +77,10 @@ partial class D2DPixelShaderSourceGenerator /// /// Extracts the shader profile for a target method, if present. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input instance to process. /// The shader profile to use to compile the shader, if present. - public static D2D1ShaderProfile GetShaderProfile(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + public static D2D1ShaderProfile GetShaderProfile(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) { if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out AttributeData? attributeData)) { @@ -104,10 +104,10 @@ partial class D2DPixelShaderSourceGenerator /// /// Extracts the compile options for the current shader. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input instance to process. /// The compile options to use to compile the shader, if present. - public static D2D1CompileOptions GetCompileOptions(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + public static D2D1CompileOptions GetCompileOptions(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) { if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData)) { @@ -135,7 +135,7 @@ partial class D2DPixelShaderSourceGenerator /// The used to cancel the operation, if needed. /// The resulting diagnostic from the processing operation, if any. /// The instance with the compiled shader bytecode. - public static unsafe ImmutableArray GetBytecode(HlslShaderMethodSourceInfo sourceInfo, CancellationToken token, out DiagnosticInfo? diagnostic) + public static unsafe ImmutableArray GetBytecode(HlslShaderMethodSourceInfo sourceInfo, CancellationToken token, out DeferredDiagnosticInfo? diagnostic) { ImmutableArray bytecode = ImmutableArray.Empty; @@ -169,7 +169,7 @@ partial class D2DPixelShaderSourceGenerator } catch (Win32Exception e) { - diagnostic = new DiagnosticInfo( + diagnostic = DeferredDiagnosticInfo.Create( D2DPixelShaderSourceCompilationFailedWithWin32Exception, sourceInfo.MethodName, e.HResult, @@ -177,7 +177,7 @@ partial class D2DPixelShaderSourceGenerator } catch (FxcCompilationException e) { - diagnostic = new DiagnosticInfo( + diagnostic = DeferredDiagnosticInfo.Create( D2DPixelShaderSourceCompilationFailedWithFxcCompilationException, sourceInfo.MethodName, ID2D1ShaderGenerator.LoadBytecode.FixupExceptionMessage(e.Message)); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs index 8216e002..431050d1 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; @@ -31,7 +32,7 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato MethodDeclarationSyntax methodDeclaration = (MethodDeclarationSyntax)context.TargetNode; IMethodSymbol methodSymbol = (IMethodSymbol)context.TargetSymbol; - ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); // Get the processed HLSL first and check for cancellation string hlslSource = Execute.GetHlslSource(diagnostics, methodSymbol); @@ -59,17 +60,20 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato }); // Output the diagnostics - context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, _) => item.Diagnostcs)); + context.ReportDiagnostics( + shaderInfoWithErrors + .Select(static (item, _) => item.Diagnostcs) + .WithComparer(EqualityComparer.Default.ForImmutableArray())); // Compile the requested shader bytecodes - IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeMethodInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeMethodInfo BytecodeInfo, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = shaderInfoWithErrors .Select(static (item, token) => { ImmutableArray bytecode = Execute.GetBytecode( item.HlslShaderMethodSource, token, - out DiagnosticInfo? diagnostic); + out DeferredDiagnosticInfo? diagnostic); token.ThrowIfCancellationRequested(); @@ -84,7 +88,7 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato }); // Gather the diagnostics - IncrementalValuesProvider embeddedBytecodeDiagnostics = + IncrementalValuesProvider embeddedBytecodeDiagnostics = embeddedBytecodeWithErrors .Select(static (item, token) => (item.Hierarchy.FullyQualifiedMetadataName, item.Diagnostic)) .Where(static item => item.Diagnostic is not null) @@ -92,11 +96,8 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato .Select(static (item, token) => { INamedTypeSymbol typeSymbol = item.Right.GetTypeByMetadataName(item.Left.FullyQualifiedMetadataName)!; - - return Diagnostic.Create( - item.Left.Diagnostic!.Descriptor, - typeSymbol.Locations.FirstOrDefault(), - new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Args).ToArray()); + + return DiagnosticInfo.Create(item.Left.Diagnostic!.Descriptor, typeSymbol, new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Arguments).ToArray()); }); // Output the diagnostics diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs index f8cb979e..711ff539 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs @@ -39,7 +39,7 @@ public sealed class InvalidD2DResourceTextureIndexUseAnalyzer : DiagnosticAnalyz { Diagnostic diagnostic = Diagnostic.Create( InvalidD2DResourceTextureIndexAttributeUse, - fieldSymbol.Locations.FirstOrDefault(), + fieldSymbol.Locations.First(), fieldSymbol.Name, fieldSymbol.ContainingType, fieldSymbol.Type); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs index 537ff7f4..0cef3803 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -6,6 +6,7 @@ using System.Text; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGeneration.SyntaxRewriters; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -28,7 +29,7 @@ partial class ID2D1ShaderGenerator /// /// Gathers all necessary information on a transpiled HLSL source for a given shader type. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input object currently in use. /// The node to process. /// The for . @@ -37,7 +38,7 @@ partial class ID2D1ShaderGenerator /// The indicess of the complex shader inputs. /// The HLSL source for the shader. public static string GetHlslSource( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, Compilation compilation, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -94,13 +95,13 @@ partial class ID2D1ShaderGenerator /// /// Gets a sequence of captured fields and their mapped names. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input instance to process. /// The collection of currently discovered types. /// The sequence of captured fields in . /// The sequence of captured resource textures in . private static void GetInstanceFields( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol, ICollection types, out ImmutableArray<(string Name, string HlslType)> valueFields, @@ -182,7 +183,7 @@ partial class ID2D1ShaderGenerator /// /// Gets a sequence of shader static fields and their mapped names. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The instance for the type to process. /// The instance for the current type. /// The type symbol for the shader type. @@ -191,7 +192,7 @@ partial class ID2D1ShaderGenerator /// Whether or not the shader needs the [D2DRequiresScenePosition] annotation. /// A sequence of static constant fields in . private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, SemanticModelProvider semanticModel, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -251,7 +252,7 @@ partial class ID2D1ShaderGenerator /// /// Gets a sequence of processed methods declared within a given type. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The type symbol for the shader type. /// The instance for the current type. /// The instance for the type to process. @@ -261,7 +262,7 @@ partial class ID2D1ShaderGenerator /// Whether or not the shader needs the [D2DRequiresScenePosition] annotation. /// A sequence of processed methods in , and the entry point. private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods) GetProcessedMethods( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, SemanticModelProvider semanticModel, @@ -370,12 +371,12 @@ partial class ID2D1ShaderGenerator /// /// Gets the sequence of processed discovered custom types. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The type symbol for the shader type. /// The sequence of discovered custom types. /// A sequence of custom type definitions to add to the shader source. private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol, IEnumerable types) { @@ -434,9 +435,9 @@ partial class ID2D1ShaderGenerator /// /// Finds and reports all invalid declared properties in a shader. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input instance to process. - private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) { foreach (var memberSymbol in structDeclarationSymbol.GetMembers()) { @@ -457,12 +458,12 @@ partial class ID2D1ShaderGenerator /// /// Reports diagnostics for invalid uses of [D2DRequiresScenePosition] in a shader. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input instance to process. /// Whether the shader type is declaring the need for scene position. /// Whether the shader is using APIs that rely on scene position. private static void ReportInvalidD2DRequiresScenePositionUse( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol, bool requiresScenePosition, bool usesPositionDependentMethods) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs index 255b23bb..d9583b49 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -19,14 +20,14 @@ partial class ID2D1ShaderGenerator /// /// Extracts the input info for the current shader. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input instance to process. /// The number of shader inputs to declare. /// The indicess of the simple shader inputs. /// The indices of the complex shader inputs. /// The combined and serialized input types for each available input. public static void GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol, out int inputCount, out ImmutableArray inputSimpleIndices, diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs index 8b7be511..2661e394 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs @@ -48,10 +48,10 @@ partial class ID2D1ShaderGenerator /// /// Extracts the compile options for the current shader. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input instance to process. /// The compile options to use to compile the shader, if present. - public static D2D1CompileOptions? GetCompileOptions(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + public static D2D1CompileOptions? GetCompileOptions(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) { if (structDeclarationSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData)) { @@ -123,7 +123,7 @@ partial class ID2D1ShaderGenerator HlslShaderSourceInfo sourceInfo, CancellationToken token, out D2D1CompileOptions options, - out DiagnosticInfo? diagnostic) + out DeferredDiagnosticInfo? diagnostic) { ImmutableArray bytecode = ImmutableArray.Empty; @@ -165,12 +165,12 @@ partial class ID2D1ShaderGenerator catch (Win32Exception e) { options = default; - diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, FixupExceptionMessage(e.Message)); + diagnostic = DeferredDiagnosticInfo.Create(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, FixupExceptionMessage(e.Message)); } catch (FxcCompilationException e) { options = default; - diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithFxcCompilationException, FixupExceptionMessage(e.Message)); + diagnostic = DeferredDiagnosticInfo.Create(EmbeddedBytecodeFailedWithFxcCompilationException, FixupExceptionMessage(e.Message)); } End: diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs index a99339bc..25b20138 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -7,6 +7,7 @@ using ComputeSharp.Core.Helpers; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -23,12 +24,12 @@ partial class ID2D1ShaderGenerator /// /// Explores a given type hierarchy and generates statements to load fields. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The current shader type being explored. /// The size of the shader constant buffer. /// The sequence of instances for all captured resources and values. public static ImmutableArray GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, ITypeSymbol structDeclarationSymbol, out int constantBufferSizeInBytes) { diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs index 1bfbf0c5..ca9a12e4 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -20,11 +21,11 @@ partial class ID2D1ShaderGenerator /// /// Extracts the input descriptions for the current shader. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input instance to process. /// The produced input descriptions for the shader. public static void GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol, out ImmutableArray inputDescriptions) { diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs index fb4b0ee4..3a128e56 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs @@ -4,6 +4,7 @@ using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -20,12 +21,12 @@ partial class ID2D1ShaderGenerator /// /// Extracts the resource texture descriptions for the current shader. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input instance to process. /// The number of inputs for the shader. /// The produced resource texture descriptions for the shader. public static void GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol, int inputCount, out ImmutableArray resourceTextureDescriptions) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index a3350ad5..7d89a486 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; @@ -41,7 +42,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator return default; } - ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); // LoadDispatchData() info ImmutableArray fieldInfos = LoadDispatchData.GetInfo( @@ -130,7 +131,10 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator compilation.HasAccessibleTypeWithMetadataName("System.Runtime.CompilerServices.SkipLocalsInitAttribute")); // Output the diagnostics - context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, _) => item.Diagnostcs)); + context.ReportDiagnostics( + shaderInfoWithErrors + .Select(static (item, _) => item.Diagnostcs) + .WithComparer(EqualityComparer.Default.ForImmutableArray())); // Get the GetInputCount() info (hierarchy and input count) IncrementalValuesProvider<(HierarchyInfo Hierarchy, int InputCount)> inputCountInfo = @@ -217,7 +221,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator .Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource)); // Compile the requested shader bytecodes - IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = shaderBytecodeInfo .Select(static (item, token) => { @@ -225,7 +229,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator item.Source, token, out D2D1CompileOptions options, - out DiagnosticInfo? diagnostic); + out DeferredDiagnosticInfo? diagnostic); token.ThrowIfCancellationRequested(); @@ -239,7 +243,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator }); // Gather the diagnostics - IncrementalValuesProvider embeddedBytecodeDiagnostics = + IncrementalValuesProvider embeddedBytecodeDiagnostics = embeddedBytecodeWithErrors .Select(static (item, _) => (item.Hierarchy.FullyQualifiedMetadataName, item.Diagnostic)) .Where(static item => item.Diagnostic is not null) @@ -247,11 +251,8 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator .Select(static (item, _) => { INamedTypeSymbol typeSymbol = item.Right.GetTypeByMetadataName(item.Left.FullyQualifiedMetadataName)!; - - return Diagnostic.Create( - item.Left.Diagnostic!.Descriptor, - typeSymbol.Locations.FirstOrDefault(), - new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Args).ToArray()); + + return DiagnosticInfo.Create(item.Left.Diagnostic!.Descriptor, typeSymbol, new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Arguments).ToArray()); }); // Output the diagnostics diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs index 41e1011c..2a3e64dc 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs @@ -4,7 +4,6 @@ using System.Collections.Immutable; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; -using Microsoft.CodeAnalysis; namespace ComputeSharp.D2D1.SourceGenerators.Models; @@ -17,7 +16,7 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; internal sealed record D2D1PixelShaderSourceInfo( HierarchyInfo Hierarchy, HlslShaderMethodSourceInfo HlslShaderMethodSource, - ImmutableArray Diagnostcs) + ImmutableArray Diagnostcs) { /// public bool Equals(D2D1PixelShaderSourceInfo? obj) => Comparer.Default.Equals(this, obj); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs index ed1692f0..643889ba 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs @@ -4,7 +4,6 @@ using System.Collections.Immutable; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; -using Microsoft.CodeAnalysis; namespace ComputeSharp.D2D1.SourceGenerators.Models; @@ -29,7 +28,7 @@ internal sealed record D2D1ShaderInfo( OutputBufferInfo OutputBuffer, InputDescriptionsInfo InputDescriptions, D2D1PixelOptions PixelOptions, - ImmutableArray Diagnostcs) + ImmutableArray Diagnostcs) { /// public bool Equals(D2D1ShaderInfo? obj) => Comparer.Default.Equals(this, obj); diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs index bda83b72..be59ad0a 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs @@ -6,6 +6,7 @@ using System.Linq; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -42,9 +43,9 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter protected readonly IDictionary ConstantDefinitions; /// - /// The collection of produced instances. + /// The collection of produced instances. /// - protected readonly ImmutableArray.Builder Diagnostics; + protected readonly ImmutableArray.Builder Diagnostics; /// /// Creates a new instance with the specified parameters. @@ -52,12 +53,12 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// The instance for the target syntax tree. /// The set of discovered custom types. /// The collection of discovered constant definitions. - /// The collection of produced instances. + /// The collection of produced instances. protected HlslSourceRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) + ImmutableArray.Builder diagnostics) { SemanticModel = semanticModel; DiscoveredTypes = discoveredTypes; diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index 6a960102..c32f24ef 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -6,6 +6,7 @@ using System.Linq; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -63,7 +64,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// The set of discovered custom types. /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. - /// The collection of produced instances. + /// The collection of produced instances. /// Whether or not the current instance is processing a shader entry point. public ShaderSourceRewriter( INamedTypeSymbol shaderType, @@ -71,7 +72,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter ICollection discoveredTypes, IDictionary staticMethods, IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, bool isEntryPoint) : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { @@ -89,13 +90,13 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// The set of discovered custom types. /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. - /// The collection of produced instances. + /// The collection of produced instances. public ShaderSourceRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary staticMethods, IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) + ImmutableArray.Builder diagnostics) : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { this.staticMethods = staticMethods; diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs index 9bef84d5..653d08d5 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs @@ -6,6 +6,7 @@ using System.Linq; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -25,12 +26,12 @@ internal sealed partial class StaticFieldRewriter : HlslSourceRewriter /// The instance for the target syntax tree. /// The set of discovered custom types. /// The collection of discovered constant definitions. - /// The collection of produced instances. + /// The collection of produced instances. public StaticFieldRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) + ImmutableArray.Builder diagnostics) : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { } diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index 9b0bfa64..754e9d60 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -19,6 +19,7 @@ + diff --git a/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs index 69745a4e..01923f37 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs @@ -1,5 +1,5 @@ using System.Collections.Immutable; -using System.Linq; +using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; namespace ComputeSharp.SourceGeneration.Extensions; @@ -12,33 +12,33 @@ internal static class DiagnosticsExtensions /// /// Adds a new diagnostics to the target builder. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input for the diagnostics to create. /// The source to attach the diagnostics to. /// The optional arguments for the formatted message to include. public static void Add( - this ImmutableArray.Builder diagnostics, + this ImmutableArray.Builder diagnostics, DiagnosticDescriptor descriptor, ISymbol symbol, params object[] args) { - diagnostics.Add(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args)); + diagnostics.Add(DiagnosticInfo.Create(descriptor, symbol, args)); } /// /// Adds a new diagnostics to the target builder. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input for the diagnostics to create. /// The source to attach the diagnostics to. /// The optional arguments for the formatted message to include. public static void Add( - this ImmutableArray.Builder diagnostics, + this ImmutableArray.Builder diagnostics, DiagnosticDescriptor descriptor, SyntaxNode node, params object[] args) { - diagnostics.Add(Diagnostic.Create(descriptor, node.GetLocation(), args)); + diagnostics.Add(DiagnosticInfo.Create(descriptor, node, args)); } /// @@ -46,11 +46,11 @@ internal static class DiagnosticsExtensions /// /// The input instance. /// The input sequence of diagnostics. - public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider diagnostics) + public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider diagnostics) { context.RegisterSourceOutput(diagnostics, static (context, diagnostic) => { - context.ReportDiagnostic(diagnostic); + context.ReportDiagnostic(diagnostic.ToDiagnostic()); }); } @@ -59,13 +59,13 @@ internal static class DiagnosticsExtensions /// /// The input instance. /// The input sequence of diagnostics. - public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider> diagnostics) + public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider> diagnostics) { context.RegisterSourceOutput(diagnostics, static (context, diagnostics) => { - foreach (Diagnostic diagnostic in diagnostics) + foreach (DiagnosticInfo diagnostic in diagnostics) { - context.ReportDiagnostic(diagnostic); + context.ReportDiagnostic(diagnostic.ToDiagnostic()); } }); } diff --git a/src/ComputeSharp.SourceGeneration/Extensions/IEqualityComparerExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IEqualityComparerExtensions.cs index 0c7a9aa7..e76d9a93 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/IEqualityComparerExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/IEqualityComparerExtensions.cs @@ -22,7 +22,7 @@ internal static class IEqualityComparerExtensions /// /// An implementation for an value. /// - public sealed class Comparer : IEqualityComparer> + private sealed class Comparer : IEqualityComparer> { /// /// The comparer. diff --git a/src/ComputeSharp.SourceGeneration/Models/DeferredDiagnosticInfo.cs b/src/ComputeSharp.SourceGeneration/Models/DeferredDiagnosticInfo.cs new file mode 100644 index 00000000..32034299 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Models/DeferredDiagnosticInfo.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGeneration.Models; + +/// +/// A model for a serializeable diagnostic info to be reconstructed later in a pipeline. +/// +/// The wrapped instance. +/// The diagnostic arguments. +internal sealed record DeferredDiagnosticInfo(DiagnosticDescriptor Descriptor, ImmutableArray Arguments) +{ + /// + public bool Equals(DeferredDiagnosticInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + + /// + /// Creates a new instance with the specified parameters. + /// + /// The input for the diagnostics to create. + /// The optional arguments for the formatted message to include. + /// A new instance with the specified parameters. + public static DeferredDiagnosticInfo Create(DiagnosticDescriptor descriptor, params object[] args) + { + return new(descriptor, args.Select(static arg => arg.ToString()).ToImmutableArray()); + } + + /// + /// An implementation for . + /// + private sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, DeferredDiagnosticInfo obj) + { + hashCode.Add(obj.Descriptor); + hashCode.AddRange(obj.Arguments); + } + + /// + protected override bool AreEqual(DeferredDiagnosticInfo x, DeferredDiagnosticInfo y) + { + return + x.Descriptor.Equals(y.Descriptor) && + x.Arguments.SequenceEqual(y.Arguments); + } + } +} diff --git a/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs b/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs index 98649b75..6eb80f9a 100644 --- a/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs +++ b/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs @@ -1,17 +1,26 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Text; namespace ComputeSharp.SourceGeneration.Models; /// -/// A model for a serializeable diagnostic provider. +/// A model for a serializeable diagnostic info. /// /// The wrapped instance. -/// The diagnostic args. -internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, params object[] Args) +/// The tree to use as location for the diagnostic, if available. +/// The span to use as location for the diagnostic. +/// The diagnostic arguments. +internal sealed record DiagnosticInfo( + DiagnosticDescriptor Descriptor, + SyntaxTree? SyntaxTree, + TextSpan TextSpan, + ImmutableArray Arguments) { /// public bool Equals(DiagnosticInfo? obj) => Comparer.Default.Equals(this, obj); @@ -19,6 +28,48 @@ internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, params ob /// public override int GetHashCode() => Comparer.Default.GetHashCode(this); + /// + /// Creates a new instance with the state from this model. + /// + /// A new instance with the state from this model. + public Diagnostic ToDiagnostic() + { + if (SyntaxTree is not null) + { + return Diagnostic.Create(Descriptor, Location.Create(SyntaxTree, TextSpan), Arguments.ToArray()); + } + + return Diagnostic.Create(Descriptor, null, Arguments.ToArray()); + } + + /// + /// Creates a new instance with the specified parameters. + /// + /// The input for the diagnostics to create. + /// The source to attach the diagnostics to. + /// The optional arguments for the formatted message to include. + /// A new instance with the specified parameters. + public static DiagnosticInfo Create(DiagnosticDescriptor descriptor, ISymbol symbol, params object[] args) + { + Location location = symbol.Locations.First(); + + return new(descriptor, location.SourceTree, location.SourceSpan, args.Select(static arg => arg.ToString()).ToImmutableArray()); + } + + /// + /// Creates a new instance with the specified parameters. + /// + /// The input for the diagnostics to create. + /// The source to attach the diagnostics to. + /// The optional arguments for the formatted message to include. + /// A new instance with the specified parameters. + public static DiagnosticInfo Create(DiagnosticDescriptor descriptor, SyntaxNode node, params object[] args) + { + Location location = node.GetLocation(); + + return new(descriptor, location.SourceTree, location.SourceSpan, args.Select(static arg => arg.ToString()).ToImmutableArray()); + } + /// /// An implementation for . /// @@ -28,11 +79,9 @@ internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, params ob protected override void AddToHashCode(ref HashCode hashCode, DiagnosticInfo obj) { hashCode.Add(obj.Descriptor); - - foreach (object arg in obj.Args) - { - hashCode.Add(arg); - } + hashCode.Add(obj.SyntaxTree); + hashCode.Add(obj.TextSpan); + hashCode.AddRange(obj.Arguments); } /// @@ -40,7 +89,9 @@ internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, params ob { return x.Descriptor.Equals(y.Descriptor) && - x.Args.SequenceEqual(y.Args); + x.SyntaxTree == y.SyntaxTree && + x.TextSpan.Equals(y.TextSpan) && + x.Arguments.SequenceEqual(y.Arguments); } } } diff --git a/src/ComputeSharp.SourceGeneration/Models/Result{T}.cs b/src/ComputeSharp.SourceGeneration/Models/Result{T}.cs index 923ec833..5b300a5b 100644 --- a/src/ComputeSharp.SourceGeneration/Models/Result{T}.cs +++ b/src/ComputeSharp.SourceGeneration/Models/Result{T}.cs @@ -1,5 +1,4 @@ using System.Collections.Immutable; -using Microsoft.CodeAnalysis; namespace ComputeSharp.SourceGeneration.Models; @@ -9,4 +8,4 @@ namespace ComputeSharp.SourceGeneration.Models; /// The type of the wrapped value. /// The wrapped value for the current result. /// The associated diagnostic errors, if any. -internal sealed record Result(TValue Value, ImmutableArray Errors); +internal sealed record Result(TValue Value, ImmutableArray Errors); diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs index 020a1e84..2bb75f0e 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -6,6 +6,7 @@ using System.Text; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGeneration.SyntaxRewriters; using ComputeSharp.SourceGenerators.Models; using ComputeSharp.SourceGenerators.SyntaxRewriters; @@ -39,9 +40,9 @@ partial class IShaderGenerator Compilation compilation, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, - out ImmutableArray diagnostics) + out ImmutableArray diagnostics) { - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); // Detect invalid properties DetectAndReportInvalidPropertyDeclarations(builder, structDeclarationSymbol); @@ -94,7 +95,7 @@ partial class IShaderGenerator /// /// Gets a sequence of captured fields and their mapped names. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input instance to process. /// The collection of currently discovered types. /// Indicates whether or not represents a compute shader. @@ -103,7 +104,7 @@ partial class IShaderGenerator ImmutableArray<(string MetadataName, string Name, string HlslType)>, ImmutableArray<(string Name, string HlslType)>) GetInstanceFields( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol, ICollection types, bool isComputeShader) @@ -186,7 +187,7 @@ partial class IShaderGenerator /// /// Gets a sequence of shader static fields and their mapped names. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The instance for the type to process. /// The instance for the current type. /// The type symbol for the shader type. @@ -194,7 +195,7 @@ partial class IShaderGenerator /// The collection of discovered constant definitions. /// A sequence of static constant fields in . private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, SemanticModelProvider semanticModel, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -256,12 +257,12 @@ partial class IShaderGenerator /// /// Gets a sequence of captured members and their mapped names. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input instance to process. /// The collection of currently discovered types. /// A sequence of captured members in . private static ImmutableArray<(string Name, string Type, int? Count)> GetSharedBuffers( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol, ICollection types) { @@ -312,7 +313,7 @@ partial class IShaderGenerator /// /// Gets a sequence of processed methods declared within a given type. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The type symbol for the shader type. /// The instance for the current type. /// The instance for the type to process. @@ -322,7 +323,7 @@ partial class IShaderGenerator /// Indicates whether or not represents a compute shader. /// A sequence of processed methods in , and the entry point. private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods, bool IsSamplerUser) GetProcessedMethods( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, SemanticModelProvider semanticModel, @@ -441,10 +442,10 @@ partial class IShaderGenerator /// /// The sequence of discovered custom types. /// The symbol for the current object being processed. - /// The collection of produced instances. + /// The collection of produced instances. /// A sequence of custom type definitions to add to the shader source. internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, ISymbol sourceSymbol, IEnumerable types) { @@ -503,9 +504,9 @@ partial class IShaderGenerator /// /// Finds and reports all invalid declared properties in a shader. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The input instance to process. - private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) { foreach (var memberSymbol in structDeclarationSymbol.GetMembers()) { diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs index 8ecf75a9..2326268c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs @@ -42,9 +42,9 @@ partial class IShaderGenerator INamedTypeSymbol structDeclarationSymbol, bool isDynamicShader, bool supportsDynamicShaders, - out ImmutableArray diagnostics) + out ImmutableArray diagnostics) { - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); AttributeData? attribute = structDeclarationSymbol .GetAttributes() @@ -149,7 +149,7 @@ partial class IShaderGenerator ThreadIdsInfo threadIds, string hlslSource, CancellationToken token, - out DiagnosticInfo? diagnostic) + out DeferredDiagnosticInfo? diagnostic) { ImmutableArray bytecode = ImmutableArray.Empty; @@ -189,11 +189,11 @@ partial class IShaderGenerator } catch (Win32Exception e) { - diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, FixupExceptionMessage(e.Message)); + diagnostic = DeferredDiagnosticInfo.Create(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, FixupExceptionMessage(e.Message)); } catch (DxcCompilationException e) { - diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithDxcCompilationException, FixupExceptionMessage(e.Message)); + diagnostic = DeferredDiagnosticInfo.Create(EmbeddedBytecodeFailedWithDxcCompilationException, FixupExceptionMessage(e.Message)); } End: diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs index 665162db..932c1e3a 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -6,6 +6,7 @@ using System.Runtime.CompilerServices; using ComputeSharp.Core.Helpers; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -34,7 +35,7 @@ partial class IShaderGenerator Type shaderInterfaceType, out int resourceCount, out int root32BitConstantCount, - out ImmutableArray diagnostics) + out ImmutableArray diagnostics) { // Helper method that uses boxes instead of ref-s (illegal in enumerators) static IEnumerable GetCapturedFieldInfos( @@ -87,7 +88,7 @@ partial class IShaderGenerator } } - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); // Setup the resource and byte offsets for tracking. Pixel shaders have only two // implicitly captured int values, as they're always dispatched over a 2D texture. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 40022e47..9f0a1608 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -88,7 +88,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator item.Left.Left.Type, out int resourceCount, out int root32BitConstantCount, - out ImmutableArray dispatchDataDiagnostics); + out ImmutableArray dispatchDataDiagnostics); token.ThrowIfCancellationRequested(); @@ -106,7 +106,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator item.Right, item.Left.Left.Syntax, item.Left.Left.Symbol, - out ImmutableArray hlslSourceDiagnostics); + out ImmutableArray hlslSourceDiagnostics); token.ThrowIfCancellationRequested(); @@ -115,7 +115,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator item.Left.Left.Symbol, !hlslSourceInfo.Delegates.IsEmpty, item.Left.Right, - out ImmutableArray threadIdsDiagnostics); + out ImmutableArray threadIdsDiagnostics); token.ThrowIfCancellationRequested(); @@ -206,11 +206,11 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator .Select(static (item, token) => (item.Dispatch.Hierarchy, BuildHlslSource.GetNonDynamicHlslSource(item.Hlsl), item.ThreadIds)); // Compile the requested shader bytecodes - IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = shaderBytecodeInfo .Select(static (item, token) => { - ImmutableArray bytecode = LoadBytecode.GetBytecode(item.ThreadIds, item.Hlsl, token, out DiagnosticInfo? diagnostic); + ImmutableArray bytecode = LoadBytecode.GetBytecode(item.ThreadIds, item.Hlsl, token, out DeferredDiagnosticInfo? diagnostic); token.ThrowIfCancellationRequested(); @@ -224,7 +224,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator }); // Gather the diagnostics - IncrementalValuesProvider embeddedBytecodeDiagnostics = + IncrementalValuesProvider embeddedBytecodeDiagnostics = embeddedBytecodeWithErrors .Select(static (item, token) => (item.Hierarchy.FullyQualifiedMetadataName, item.Diagnostic)) .Where(static item => item.Diagnostic is not null) @@ -232,11 +232,8 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator .Select(static (item, token) => { INamedTypeSymbol typeSymbol = item.Right.GetTypeByMetadataName(item.Left.FullyQualifiedMetadataName)!; - - return Diagnostic.Create( - item.Left.Diagnostic!.Descriptor, - typeSymbol.Locations.FirstOrDefault(), - new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Args).ToArray()); + + return DiagnosticInfo.Create(item.Left.Diagnostic!.Descriptor, typeSymbol, new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Arguments).ToArray()); }); // Output the diagnostics diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 936069b3..d1998d13 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -46,7 +46,7 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator item.Right, item.Left.Syntax, item.Left.Symbol, - out ImmutableArray diagnostics); + out ImmutableArray diagnostics); return new Result(sourceInfo, diagnostics); }); @@ -85,9 +85,9 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator Compilation compilation, CSharpSyntaxNode methodDeclaration, IMethodSymbol methodSymbol, - out ImmutableArray diagnostics) + out ImmutableArray diagnostics) { - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); @@ -112,14 +112,14 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator /// /// Gets a sequence of processed methods from a target method declaration. /// - /// The collection of produced instances. + /// The collection of produced instances. /// The or instance for the current method. /// The instance for the method to process. /// The collection of currently discovered types. /// The collection of discovered constant definitions. /// A sequence of processed methods in (main method and all captured methods). private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods( - ImmutableArray.Builder diagnostics, + ImmutableArray.Builder diagnostics, CSharpSyntaxNode methodDeclaration, SemanticModelProvider semanticModel, ICollection discoveredTypes, From a205efe6fa128a8b790b968c75adcf92bb95e736 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Sep 2022 20:35:38 +0200 Subject: [PATCH 14/20] Remove symbols from IShaderGenerator pipeline --- .../ID2D1ShaderGenerator.cs | 19 +- ...erator.CreateGetDispatchIdMethod.Syntax.cs | 23 +- ...tor.CreateLoadDispatchDataMethod.Syntax.cs | 15 +- ...rGenerator.CreateLoadDispatchDataMethod.cs | 6 +- .../IShaderGenerator.Helpers.cs | 47 +-- .../IShaderGenerator.cs | 287 +++++++++--------- .../Models/DispatchDataInfo.cs | 7 +- .../Models/ShaderInfo.cs | 65 ++++ .../Models/ShaderType.cs | 17 ++ 9 files changed, 283 insertions(+), 203 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs create mode 100644 src/ComputeSharp.SourceGenerators/Models/ShaderType.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 7d89a486..f9259a85 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -22,6 +22,14 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator /// public void Initialize(IncrementalGeneratorInitializationContext context) { + // Check whether [SkipLocalsInit] can be used + IncrementalValueProvider canUseSkipLocalsInit = + context.CompilationProvider + .Select(static (compilation, _) => + compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } && + compilation.HasAccessibleTypeWithMetadataName("System.Runtime.CompilerServices.SkipLocalsInitAttribute")); + + // Discover all shader types and extract all the necessary info from each of them IncrementalValuesProvider shaderInfoWithErrors = context.SyntaxProvider .CreateSyntaxProvider( @@ -123,14 +131,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator }) .Where(static item => item is not null)!; - // Check whether [SkipLocalsInit] can be used - IncrementalValueProvider canUseSkipLocalsInit = - context.CompilationProvider - .Select(static (compilation, _) => - compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } && - compilation.HasAccessibleTypeWithMetadataName("System.Runtime.CompilerServices.SkipLocalsInitAttribute")); - - // Output the diagnostics + // Output the diagnostics, if any context.ReportDiagnostics( shaderInfoWithErrors .Select(static (item, _) => item.Diagnostcs) @@ -258,7 +259,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Output the diagnostics context.ReportDiagnostics(embeddedBytecodeDiagnostics); - // Get the filtered sequence to enable caching + // Get the LoadBytecode() info (hierarchy and compiled bytecode) IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode = embeddedBytecodeWithErrors .Select(static (item, _) => (item.Hierarchy, item.BytecodeInfo)); diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs index e2ce418e..974dcb73 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs @@ -18,10 +18,9 @@ partial class IShaderGenerator /// /// Creates a instance for the GetDispatchId method. /// - /// The names of all instance fields within the current shader type.\ - /// Indicates whether or not dynamic shaders are supported. + /// The names of all instance fields within the current shader type. /// The resulting instance for the GetDispatchId method. - public static MethodDeclarationSyntax GetSyntax(ImmutableArray delegateFieldNames, bool supportsDynamicShaders) + public static MethodDeclarationSyntax GetSyntax(ImmutableArray delegateFieldNames) { // This code produces a method declaration as follows: // @@ -35,18 +34,17 @@ partial class IShaderGenerator Identifier("GetDispatchId")) .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithBody(GetShaderHashCodeBody(delegateFieldNames, supportsDynamicShaders)); + .WithBody(GetShaderHashCodeBody(delegateFieldNames)); } /// /// Gets a instance with the logic to compute the hashcode of a given shader type. /// /// The names of all instance fields within the current shader type. - /// Indicates whether or not dynamic shaders are supported. /// The instance to hash the input shader. - private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames, bool supportsDynamicShaders) + private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames) { - if (delegateFieldNames.Length == 0 || !supportsDynamicShaders) + if (delegateFieldNames.Length == 0) { // return 0; return @@ -56,17 +54,18 @@ partial class IShaderGenerator Literal(0)))); } - List blockStatements = new(4); - - // global::System.HashCode hashCode = default; - blockStatements.Add(LocalDeclarationStatement( + List blockStatements = new(4) + { + // global::System.HashCode hashCode = default; + LocalDeclarationStatement( VariableDeclaration(IdentifierName("global::System.HashCode")) .AddVariables( VariableDeclarator(Identifier("hashCode")) .WithInitializer(EqualsValueClause( LiteralExpression( SyntaxKind.DefaultLiteralExpression, - Token(SyntaxKind.DefaultKeyword))))))); + Token(SyntaxKind.DefaultKeyword)))))) + }; foreach (string fieldName in delegateFieldNames) { diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index 1d3a8c4d..53b0caa3 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Immutable; +using System.Collections.Immutable; using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis.CSharp; @@ -19,13 +18,13 @@ partial class IShaderGenerator /// /// Creates a instance for the LoadDispatchDataMethod method. /// - /// The type of shader interface urrently being processed. + /// The type of shader interface currently being processed. /// The array of values for all captured fields. /// The total number of captured resources in the shader. /// The total number of needed 32 bit constants in the shader root signature. /// The resulting instance for the LoadDispatchDataMethod method. public static MethodDeclarationSyntax GetSyntax( - Type shaderInterfaceType, + ShaderType shaderType, ImmutableArray fieldInfos, int resourceCount, int root32BitConstantsCount) @@ -51,25 +50,25 @@ partial class IShaderGenerator Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .WithBody(Block(GetDispatchDataLoadingStatements(shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount))); + .WithBody(Block(GetDispatchDataLoadingStatements(shaderType, fieldInfos, resourceCount, root32BitConstantsCount))); } /// /// Gets a sequence of statements to load the dispatch data for a given shader. /// - /// The type of shader interface urrently being processed. + /// The type of shader interface currently being processed. /// The array of values for all captured fields. /// The total number of captured resources in the shader. /// The total number of needed 32 bit constants in the shader root signature. /// The sequence of instances to load shader dispatch data. private static ImmutableArray GetDispatchDataLoadingStatements( - Type shaderInterfaceType, + ShaderType shaderType, ImmutableArray fieldInfos, int resourceCount, int root32BitConstantsCount) { ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); - bool isComputeShader = shaderInterfaceType == typeof(IComputeShader); + bool isComputeShader = shaderType == ShaderType.ComputeShader; // Append the statements for the dispatch ranges: // diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs index 932c1e3a..33bd6a0f 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -25,14 +25,14 @@ partial class IShaderGenerator /// Explores a given type hierarchy and generates statements to load fields. /// /// The current shader type being explored. - /// The type of shader interface urrently being processed. + /// The type of shader currently being processed. /// The total number of captured resources in the shader. /// The total number of needed 32 bit constants in the shader root signature. /// The resulting diagnostics from the processing operation. /// The sequence of instances for all captured resources and values. public static ImmutableArray GetInfo( ITypeSymbol structDeclarationSymbol, - Type shaderInterfaceType, + ShaderType shaderType, out int resourceCount, out int root32BitConstantCount, out ImmutableArray diagnostics) @@ -92,7 +92,7 @@ partial class IShaderGenerator // Setup the resource and byte offsets for tracking. Pixel shaders have only two // implicitly captured int values, as they're always dispatched over a 2D texture. - bool isComputeShader = shaderInterfaceType == typeof(IComputeShader); + bool isComputeShader = shaderType == ShaderType.ComputeShader; int initialRawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2); StrongBox resourceOffsetAsBox = new(); StrongBox rawDataOffsetAsBox = new(initialRawDataOffset); diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs index 77462b98..62efe0a5 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs @@ -1,6 +1,7 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; +using System.Linq; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -15,33 +16,45 @@ partial class IShaderGenerator /// Gets the shader type for a given shader, if any. /// /// The input instance to check. - /// The instance for . - /// The instance for . - /// Either or , or . - private static Type? GetShaderType( - INamedTypeSymbol typeSymbol, - INamedTypeSymbol iComputeShaderSymbol, - INamedTypeSymbol iPixelShaderSymbol) + /// The instance currently in use. + /// The shader type for , or . + private static ShaderType? GetShaderType(INamedTypeSymbol typeSymbol, Compilation compilation) { foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.AllInterfaces) { - if (interfaceSymbol.Name == nameof(IComputeShader) && - SymbolEqualityComparer.Default.Equals(interfaceSymbol, iComputeShaderSymbol)) + if (interfaceSymbol.Name == nameof(IComputeShader)) { - return typeof(IComputeShader); - } + INamedTypeSymbol computeShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IComputeShader")!; - if (interfaceSymbol.IsGenericType && - interfaceSymbol.Name == nameof(IPixelShader) && - SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, iPixelShaderSymbol)) + if (SymbolEqualityComparer.Default.Equals(interfaceSymbol, computeShaderSymbol)) + { + return ShaderType.ComputeShader; + } + } + else if (interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }) { - return typeof(IPixelShader<>); + INamedTypeSymbol pixelShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IPixelShader`1")!; + + if (SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, pixelShaderSymbol)) + { + return ShaderType.PixelShader; + } } } return null; } + /// + /// Checks whether dynamic shaders are supported in a given compilation. + /// + /// The instance currently in use. + /// Whether dynamic shaders are supported in the input compilation. + private static bool IsDynamicCompilationSupported(Compilation compilation) + { + return compilation.ReferencedAssemblyNames.Any(static identity => identity.Name is "ComputeSharp.Dynamic"); + } + /// /// Creates a instance wrapping the given method. /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 9f0a1608..6d112bd5 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -25,188 +25,178 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Check whether [SkipLocalsInit] can be used IncrementalValueProvider canUseSkipLocalsInit = context.CompilationProvider - .Select(static (compilation, token) => + .Select(static (compilation, _) => compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } && compilation.HasAccessibleTypeWithMetadataName("System.Runtime.CompilerServices.SkipLocalsInitAttribute")); // Check whether or not dynamic shaders are supported IncrementalValueProvider supportsDynamicShaders = context.CompilationProvider - .Select(static (compilation, token) => compilation.ReferencedAssemblyNames.Any( - static identity => identity.Name is "ComputeSharp.Dynamic")); + .Select(static (compilation, _) => IsDynamicCompilationSupported(compilation)); - // Get all declared struct types and their type symbols - IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol)> structDeclarations = + // Discover all shader types and extract all the necessary info from each of them + IncrementalValuesProvider shaderInfoWithErrors = context.SyntaxProvider .CreateSyntaxProvider( - static (node, token) => node is StructDeclarationSyntax structDeclaration, - static (context, token) => ( - (StructDeclarationSyntax)context.Node, - Symbol: (INamedTypeSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token))) - .Where(static pair => pair.Symbol is { Interfaces.IsEmpty: false })!; + static (node, _) => node.IsTypeDeclarationWithOrPotentiallyWithBaseTypes(), + static (context, token) => + { + StructDeclarationSyntax typeDeclaration = (StructDeclarationSyntax)context.Node; - // Get the symbol for the IComputeShader and IPixelShader interfaces - IncrementalValueProvider<(INamedTypeSymbol Compute, INamedTypeSymbol Pixel) > shaderInterfaces = - context.CompilationProvider - .Select(static (compilation, token) => ( - Compute: compilation.GetTypeByMetadataName(typeof(IComputeShader).FullName)!, - Pixel: compilation.GetTypeByMetadataName(typeof(IPixelShader<>).FullName)!)); + // If the type symbol doesn't have at least one interface, it can't possibly be a shader type + if (context.SemanticModel.GetDeclaredSymbol(typeDeclaration, token) is not INamedTypeSymbol { AllInterfaces.Length: > 0 } typeSymbol) + { + return default; + } - // Filter struct declarations that implement a shader interface, and also gather the hierarchy info and shader type - IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol, HierarchyInfo Hierarchy, Type Type)> shaderDeclarations = - structDeclarations - .Combine(shaderInterfaces) - .Select(static (item, token) => (item.Left, Type: GetShaderType(item.Left.Symbol, item.Right.Compute, item.Right.Pixel))) - .Where(static item => item.Type is not null) - .Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, HierarchyInfo.From(item.Left.Symbol), item.Type!)); + // Get the shader type, or return if none is present + if (GetShaderType(typeSymbol, context.SemanticModel.Compilation) is not ShaderType shaderType) + { + return default; + } - // Get the hierarchy info and delegate field names for each shader type - IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchIdInfo Info)> hierarchyAndDispatchIdInfo = - shaderDeclarations - .Select(static (item, token) => (item.Hierarchy, new DispatchIdInfo(GetDispatchId.GetInfo(item.Symbol)))); + ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + + // GetDispatchId() info + ImmutableArray dispatchIdInfo = GetDispatchId.GetInfo(typeSymbol); + + token.ThrowIfCancellationRequested(); + + // LoadDispatchData() info + ImmutableArray fieldInfos = LoadDispatchData.GetInfo( + typeSymbol, + shaderType, + out int resourceCount, + out int root32BitConstantCount, + out ImmutableArray dispatchDataDiagnostics); + + token.ThrowIfCancellationRequested(); + + // BuildHlslSource() info + HlslShaderSourceInfo hlslSourceInfo = BuildHlslSource.GetInfo( + context.SemanticModel.Compilation, + typeDeclaration, + typeSymbol, + out ImmutableArray hlslSourceDiagnostics); + + token.ThrowIfCancellationRequested(); + + // GetDispatchMetadata() info + DispatchMetadataInfo dispatchMetadataInfo = LoadDispatchMetadata.GetInfo( + root32BitConstantCount, + hlslSourceInfo.ImplicitTextureType is not null, + hlslSourceInfo.IsSamplerUsed, + fieldInfos); + + token.ThrowIfCancellationRequested(); + + // TryGetBytecode() info + ThreadIdsInfo threadIds = LoadBytecode.GetInfo( + typeSymbol, + !hlslSourceInfo.Delegates.IsEmpty, + IsDynamicCompilationSupported(context.SemanticModel.Compilation), + out ImmutableArray threadIdsDiagnostics); + + token.ThrowIfCancellationRequested(); + + // Ensure the bytecode generation is disabled if any errors are present + if (!dispatchDataDiagnostics.IsDefaultOrEmpty || + !hlslSourceDiagnostics.IsDefaultOrEmpty) + { + threadIds = new ThreadIdsInfo(true, 0, 0, 0); + } + + return new ShaderInfo( + Hierarchy: HierarchyInfo.From(typeSymbol), + DispatchId: new DispatchIdInfo(dispatchIdInfo), + DispatchData: new DispatchDataInfo( + shaderType, + fieldInfos, + resourceCount, + root32BitConstantCount), + DispatchMetadata: dispatchMetadataInfo, + HlslShaderSource: hlslSourceInfo, + ThreadIds: threadIds, + Diagnostcs: diagnostics.ToImmutable()); + }) + .Where(static item => item is not null)!; + + // Output the diagnostics, if any + context.ReportDiagnostics( + shaderInfoWithErrors + .Select(static (item, _) => item.Diagnostcs) + .WithComparer(EqualityComparer.Default.ForImmutableArray())); + + // Get the GetDispatchId() info (hierarchy and dispatch id info) + IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchIdInfo DispatchId)> dispatchIdInfo = + shaderInfoWithErrors + .Select(static (item, _) => (item.Hierarchy, item.DispatchId)); // Generate the GetDispatchId() methods - context.RegisterSourceOutput(hierarchyAndDispatchIdInfo.Combine(supportsDynamicShaders), static (context, item) => + context.RegisterSourceOutput(dispatchIdInfo, static (context, item) => { - MethodDeclarationSyntax getDispatchIdMethod = GetDispatchId.GetSyntax(item.Left.Info.Delegates, item.Right); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, getDispatchIdMethod, canUseSkipLocalsInit: false); + MethodDeclarationSyntax getDispatchIdMethod = GetDispatchId.GetSyntax(item.DispatchId.Delegates); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getDispatchIdMethod, canUseSkipLocalsInit: false); - context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(GetDispatchId)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); + context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetDispatchId)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); - // Get the dispatch data, HLSL source and embedded bytecode info. This info is computed on the - // same step as parts are shared in following sub-branches in the incremental generator pipeline. - IncrementalValuesProvider<(Result Dispatch, Result Hlsl, Result ThreadIds)> shaderInfoWithErrors = - shaderDeclarations - .Combine(supportsDynamicShaders) - .Combine(context.CompilationProvider) - .Select(static (item, token) => - { - // LoadDispatchData() info - ImmutableArray fieldInfos = LoadDispatchData.GetInfo( - item.Left.Left.Symbol, - item.Left.Left.Type, - out int resourceCount, - out int root32BitConstantCount, - out ImmutableArray dispatchDataDiagnostics); - - token.ThrowIfCancellationRequested(); - - DispatchDataInfo dispatchDataInfo = new( - item.Left.Left.Hierarchy, - item.Left.Left.Type, - fieldInfos, - resourceCount, - root32BitConstantCount); - - token.ThrowIfCancellationRequested(); - - // BuildHlslSource() info - HlslShaderSourceInfo hlslSourceInfo = BuildHlslSource.GetInfo( - item.Right, - item.Left.Left.Syntax, - item.Left.Left.Symbol, - out ImmutableArray hlslSourceDiagnostics); - - token.ThrowIfCancellationRequested(); - - // TryGetBytecode() info - ThreadIdsInfo threadIds = LoadBytecode.GetInfo( - item.Left.Left.Symbol, - !hlslSourceInfo.Delegates.IsEmpty, - item.Left.Right, - out ImmutableArray threadIdsDiagnostics); - - token.ThrowIfCancellationRequested(); - - // Ensure the bytecode generation is disabled if any errors are present - if (!dispatchDataDiagnostics.IsDefaultOrEmpty || - !hlslSourceDiagnostics.IsDefaultOrEmpty) - { - threadIds = new ThreadIdsInfo(true, 0, 0, 0); - } - - return ( - new Result(dispatchDataInfo, dispatchDataDiagnostics), - new Result(hlslSourceInfo, hlslSourceDiagnostics), - new Result(threadIds, threadIdsDiagnostics)); - }); - - // Output the diagnostics - context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Dispatch.Errors)); - context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Hlsl.Errors)); - context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.ThreadIds.Errors)); - - // Filter all items to enable caching at a coarse level, and remove diagnostics - IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslShaderSourceInfo Hlsl, ThreadIdsInfo ThreadIds)> shaderInfo = + // Get the LoadDispatchData() info (hierarchy and dispatch data info) + IncrementalValuesProvider<((HierarchyInfo Hierarchy, DispatchDataInfo DispatchData) Info, bool CanUseSkipLocalsInit) > dispatchDataInfo = shaderInfoWithErrors - .Select(static (item, token) => (item.Dispatch.Value, item.Hlsl.Value, item.ThreadIds.Value)); - - // Get a filtered sequence to enable caching - IncrementalValuesProvider dispatchDataInfo = - shaderInfo - .Select(static (item, token) => item.Dispatch); + .Select(static (item, _) => (item.Hierarchy, item.DispatchData)) + .Combine(canUseSkipLocalsInit); // Generate the LoadDispatchData() methods - context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) => + context.RegisterSourceOutput(dispatchDataInfo, static (context, item) => { MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax( - item.Left.Type, - item.Left.FieldInfos, - item.Left.ResourceCount, - item.Left.Root32BitConstantCount); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, loadDispatchDataMethod, canUseSkipLocalsInit: item.Right); + item.Info.DispatchData.Type, + item.Info.DispatchData.FieldInfos, + item.Info.DispatchData.ResourceCount, + item.Info.DispatchData.Root32BitConstantCount); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, loadDispatchDataMethod, item.CanUseSkipLocalsInit); - context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); + context.AddSource($"{item.Info.Hierarchy.FilenameHint}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); - // Get the filtered sequence to enable caching - IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo SourceInfo, bool SupportsDynamicShaders)> hlslSourceInfo = - shaderInfo - .Combine(supportsDynamicShaders) - .Select(static (item, token) => (item.Left.Dispatch.Hierarchy, item.Left.Hlsl, item.Right)); + // Get the BuildHlslSource info (hierarchy, HLSL source and parsing options) + IncrementalValuesProvider<((HierarchyInfo Hierarchy, HlslShaderSourceInfo HlslShaderSource) Info, (bool CanUseSkipLocalsInit, bool SupportsDynamicShaders) Options)> hlslSourceInfo = + shaderInfoWithErrors + .Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource)) + .Combine(canUseSkipLocalsInit.Combine(supportsDynamicShaders)); // Generate the BuildHlslSource() methods - context.RegisterSourceOutput(hlslSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) => + context.RegisterSourceOutput(hlslSourceInfo, static (context, item) => { - MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.Left.SourceInfo, item.Left.SupportsDynamicShaders, item.Left.Hierarchy.Hierarchy.Length); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: item.Right); + MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.Info.HlslShaderSource, item.Options.SupportsDynamicShaders, item.Info.Hierarchy.Hierarchy.Length); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, buildHlslStringMethod, item.Options.CanUseSkipLocalsInit); - context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); + context.AddSource($"{item.Info.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); - // Get the dispatch metadata info - IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchMetadataInfo MetadataInfo)> dispatchMetadataInfo = - shaderInfo - .Select(static (item, token) => - { - DispatchMetadataInfo dispatchMetadataInfo = LoadDispatchMetadata.GetInfo( - item.Dispatch.Root32BitConstantCount, - item.Hlsl.ImplicitTextureType is not null, - item.Hlsl.IsSamplerUsed, - item.Dispatch.FieldInfos); - - token.ThrowIfCancellationRequested(); - - return (item.Dispatch.Hierarchy, dispatchMetadataInfo); - }); + // Get the LoadDispatchMetadata() info (hierarchy and dispatch metadata info) + IncrementalValuesProvider<((HierarchyInfo Hierarchy, DispatchMetadataInfo DispatchMetadata) Info, bool CanUseSkipLocalsInit)> dispatchMetadataInfo = + shaderInfoWithErrors + .Select(static (item, _) => (item.Hierarchy, item.DispatchMetadata)) + .Combine(canUseSkipLocalsInit); // Generate the LoadDispatchMetadata() methods - context.RegisterSourceOutput(dispatchMetadataInfo.Combine(canUseSkipLocalsInit), static (context, item) => + context.RegisterSourceOutput(dispatchMetadataInfo, static (context, item) => { - MethodDeclarationSyntax buildHlslStringMethod = LoadDispatchMetadata.GetSyntax(item.Left.MetadataInfo); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: item.Right); + MethodDeclarationSyntax buildHlslStringMethod = LoadDispatchMetadata.GetSyntax(item.Info.DispatchMetadata); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, buildHlslStringMethod, item.CanUseSkipLocalsInit); - context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadDispatchMetadata)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); + context.AddSource($"{item.Info.Hierarchy.FilenameHint}.{nameof(LoadDispatchMetadata)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); - // Transform the raw HLSL source to compile + // Transform the raw HLSL source to compile (this step aggregates the HLSL source to ensure compilation is only done for actual HLSL changes) IncrementalValuesProvider<(HierarchyInfo Hierarchy, string Hlsl, ThreadIdsInfo ThreadIds)> shaderBytecodeInfo = - shaderInfo - .Select(static (item, token) => (item.Dispatch.Hierarchy, BuildHlslSource.GetNonDynamicHlslSource(item.Hlsl), item.ThreadIds)); + shaderInfoWithErrors + .Select(static (item, token) => (item.Hierarchy, BuildHlslSource.GetNonDynamicHlslSource(item.HlslShaderSource), item.ThreadIds)); // Compile the requested shader bytecodes - IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = shaderBytecodeInfo .Select(static (item, token) => { @@ -239,19 +229,20 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Output the diagnostics context.ReportDiagnostics(embeddedBytecodeDiagnostics); - // Get the filtered sequence to enable caching - IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode = + // Get the TryGetBytecode() info (hierarchy and compiled bytecode) + IncrementalValuesProvider<((HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode) Info, bool SupportsDynamicShaders)> embeddedBytecodeInfo = embeddedBytecodeWithErrors - .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo)); + .Select(static (item, token) => (item.Hierarchy, item.EmbeddedBytecode)) + .Combine(supportsDynamicShaders); // Generate the TryGetBytecode() methods - context.RegisterSourceOutput(embeddedBytecode.Combine(supportsDynamicShaders), static (context, item) => + context.RegisterSourceOutput(embeddedBytecodeInfo, static (context, item) => { - MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.Left.BytecodeInfo, item.Right, out Func fixup); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, tryGetBytecodeMethod, canUseSkipLocalsInit: false); + MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.Info.EmbeddedBytecode, item.SupportsDynamicShaders, out Func fixup); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, tryGetBytecodeMethod, canUseSkipLocalsInit: false); SourceText text = fixup(compilationUnit); - context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadBytecode)}.g.cs", text); + context.AddSource($"{item.Info.Hierarchy.FilenameHint}.{nameof(LoadBytecode)}.g.cs", text); }); } } diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs index 4bb4d834..e733ea62 100644 --- a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs @@ -3,21 +3,18 @@ using System.Collections.Generic; using System.Collections.Immutable; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Models; namespace ComputeSharp.SourceGenerators.Models; /// /// A model representing gathered info on a shader dispatch data. /// -/// The hierarchy data for the shader. /// The shader interface type. /// The description on shader instance fields. /// The total number of captured resources. /// The size of the shader root signature, in 32 bit constants. internal sealed record DispatchDataInfo( - HierarchyInfo Hierarchy, - Type Type, + ShaderType Type, ImmutableArray FieldInfos, int ResourceCount, int Root32BitConstantCount) @@ -36,7 +33,6 @@ internal sealed record DispatchDataInfo( /// protected override void AddToHashCode(ref HashCode hashCode, DispatchDataInfo obj) { - hashCode.Add(obj.Hierarchy); hashCode.Add(obj.Type); hashCode.AddRange(obj.FieldInfos); hashCode.Add(obj.ResourceCount); @@ -47,7 +43,6 @@ internal sealed record DispatchDataInfo( protected override bool AreEqual(DispatchDataInfo x, DispatchDataInfo y) { return - x.Hierarchy == y.Hierarchy && x.Type == y.Type && x.FieldInfos.SequenceEqual(y.FieldInfos) && x.ResourceCount == y.ResourceCount && diff --git a/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs new file mode 100644 index 00000000..fa4613f3 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model representing all necessary info for a full generation pass for a shader. +/// +/// The hierarchy info for the shader type. +/// The gathered dispatch id for the shader type. +/// The gathered shader dispatch data. +/// The gathered shader dispatch metadata. +/// The processed HLSL source for the shader. +/// The thread ids for the shader, if compilation is requested. +/// The discovered diagnostics, if any. +internal sealed record ShaderInfo( + HierarchyInfo Hierarchy, + DispatchIdInfo DispatchId, + DispatchDataInfo DispatchData, + DispatchMetadataInfo DispatchMetadata, + HlslShaderSourceInfo HlslShaderSource, + ThreadIdsInfo ThreadIds, + ImmutableArray Diagnostcs) +{ + /// + public bool Equals(ShaderInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + + /// + /// An implementation for . + /// + private sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, ShaderInfo obj) + { + hashCode.Add(obj.Hierarchy); + hashCode.Add(obj.DispatchId); + hashCode.Add(obj.DispatchData); + hashCode.Add(obj.DispatchMetadata); + hashCode.Add(obj.HlslShaderSource); + hashCode.Add(obj.ThreadIds); + hashCode.AddRange(obj.Diagnostcs); + } + + /// + protected override bool AreEqual(ShaderInfo x, ShaderInfo y) + { + return + x.Hierarchy == y.Hierarchy && + x.DispatchId == y.DispatchId && + x.DispatchData == y.DispatchData && + x.DispatchMetadata == y.DispatchMetadata && + x.HlslShaderSource == y.HlslShaderSource && + x.ThreadIds == y.ThreadIds && + x.Diagnostcs.SequenceEqual(y.Diagnostcs); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/ShaderType.cs b/src/ComputeSharp.SourceGenerators/Models/ShaderType.cs new file mode 100644 index 00000000..f70a62c0 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/ShaderType.cs @@ -0,0 +1,17 @@ +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// Indicates a type of shader being processed. +/// +public enum ShaderType +{ + /// + /// A compute shader. + /// + ComputeShader, + + /// + /// A pixel shader. + /// + PixelShader +} \ No newline at end of file From d8aefe3128999ddbcf2ed40cb1c0667b3a62c8d2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Sep 2022 20:49:17 +0200 Subject: [PATCH 15/20] Remove symbols from ShaderMethodSourceGenerator pipeline --- .../Models/ShaderMethodInfo.cs | 43 +++++++++++++++++ .../ShaderMethodSourceGenerator.cs | 48 ++++++++----------- 2 files changed, 63 insertions(+), 28 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Models/ShaderMethodInfo.cs diff --git a/src/ComputeSharp.SourceGenerators/Models/ShaderMethodInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ShaderMethodInfo.cs new file mode 100644 index 00000000..0975348f --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/ShaderMethodInfo.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model representing all necessary info for a full generation pass for a shader method. +/// +/// The processed HLSL source for the shader method. +/// The discovered diagnostics, if any. +internal sealed record ShaderMethodInfo(HlslMethodSourceInfo HlslMethodSource, ImmutableArray Diagnostcs) +{ + /// + public bool Equals(ShaderMethodInfo? obj) => Comparer.Default.Equals(this, obj); + + /// + public override int GetHashCode() => Comparer.Default.GetHashCode(this); + + /// + /// An implementation for . + /// + private sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, ShaderMethodInfo obj) + { + hashCode.Add(obj.HlslMethodSource); + hashCode.AddRange(obj.Diagnostcs); + } + + /// + protected override bool AreEqual(ShaderMethodInfo x, ShaderMethodInfo y) + { + return + x.HlslMethodSource == y.HlslMethodSource && + x.Diagnostcs.SequenceEqual(y.Diagnostcs); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index d1998d13..dd06162d 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -28,42 +28,34 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator /// public void Initialize(IncrementalGeneratorInitializationContext context) { - // Get all declared methods (including global function declarations) with the [ShaderMethod] attribute - IncrementalValuesProvider<(MethodDeclarationSyntax Syntax, IMethodSymbol Symbol)> methodDeclarationsAndSymbols = + // Get all declared methods (including global function declarations) with the [ShaderMethod] attribute, and their info + IncrementalValuesProvider methodInfoWithErrors = context.SyntaxProvider .ForAttributeWithMetadataName( typeof(ShaderMethodAttribute).FullName, - static (node, token) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 } or LocalFunctionStatementSyntax { Parent: GlobalStatementSyntax { Parent: CompilationUnitSyntax }, AttributeLists.Count: > 0 }, - static (context, token) => ((MethodDeclarationSyntax)context.TargetNode, (IMethodSymbol)context.TargetSymbol)); + static (node, _) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 } or LocalFunctionStatementSyntax { Parent: GlobalStatementSyntax { Parent: CompilationUnitSyntax } }, + static (context, token) => + { + HlslMethodSourceInfo hlslMethodSourceInfo = Execute.GetData( + context.SemanticModel.Compilation, + (CSharpSyntaxNode)context.TargetNode, + (IMethodSymbol)context.TargetSymbol, + out ImmutableArray diagnostics); - // Get the source info for each method - IncrementalValuesProvider> methodSourceInfoWithErrors = - methodDeclarationsAndSymbols - .Combine(context.CompilationProvider) - .Select(static (item, token) => - { - HlslMethodSourceInfo sourceInfo = Execute.GetData( - item.Right, - item.Left.Syntax, - item.Left.Symbol, - out ImmutableArray diagnostics); + return new ShaderMethodInfo(hlslMethodSourceInfo, diagnostics); + }); - return new Result(sourceInfo, diagnostics); - }); - - // Output the diagnostics - context.ReportDiagnostics(methodSourceInfoWithErrors.Select(static (item, token) => item.Errors)); - - // Get the filtered sequence to enable caching - IncrementalValuesProvider methodSourceInfo = - methodSourceInfoWithErrors - .Select(static (item, token) => item.Value); + // Output the diagnostics, if any + context.ReportDiagnostics( + methodInfoWithErrors + .Select(static (item, _) => item.Diagnostcs) + .WithComparer(EqualityComparer.Default.ForImmutableArray())); // Generate the [ShaderMethodSource] attributes - context.RegisterSourceOutput(methodSourceInfo, static (context, item) => + context.RegisterSourceOutput(methodInfoWithErrors, static (context, item) => { - CompilationUnitSyntax compilationUnit = Execute.GetSyntax(item); - string filename = item.MetadataName.Replace('`', '-').Replace('+', '.'); + CompilationUnitSyntax compilationUnit = Execute.GetSyntax(item.HlslMethodSource); + string filename = item.HlslMethodSource.MetadataName.Replace('`', '-').Replace('+', '.'); context.AddSource($"{filename}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); From 50e82fce31d921eab64b439ab90a90bbce4b13ca Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Sep 2022 20:55:15 +0200 Subject: [PATCH 16/20] Remove leftover Result type --- .../ComputeSharp.SourceGeneration.projitems | 1 - src/ComputeSharp.SourceGeneration/Models/Result{T}.cs | 11 ----------- 2 files changed, 12 deletions(-) delete mode 100644 src/ComputeSharp.SourceGeneration/Models/Result{T}.cs diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index 754e9d60..83b77644 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -22,7 +22,6 @@ - \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Models/Result{T}.cs b/src/ComputeSharp.SourceGeneration/Models/Result{T}.cs deleted file mode 100644 index 5b300a5b..00000000 --- a/src/ComputeSharp.SourceGeneration/Models/Result{T}.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Collections.Immutable; - -namespace ComputeSharp.SourceGeneration.Models; - -/// -/// A model representing a value and an associated set of diagnostic errors. -/// -/// The type of the wrapped value. -/// The wrapped value for the current result. -/// The associated diagnostic errors, if any. -internal sealed record Result(TValue Value, ImmutableArray Errors); From 527a134082a2f8d1efbf01c0e34143c7a7c95e50 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Sep 2022 23:01:50 +0200 Subject: [PATCH 17/20] Fix diagnostics propagation in ComputeSharp generator --- .../Extensions/ISymbolExtensions.cs | 11 ++--- ...erGenerator.CreateBuildHlslSourceMethod.cs | 24 +++++------ ...haderGenerator.CreateLoadBytecodeMethod.cs | 41 ++++++++----------- ...rGenerator.CreateLoadDispatchDataMethod.cs | 12 ++---- .../IShaderGenerator.cs | 19 +++------ 5 files changed, 39 insertions(+), 68 deletions(-) diff --git a/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs index eb8d1951..2061543e 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/ISymbolExtensions.cs @@ -1,5 +1,4 @@ -using System.Collections.Immutable; -using System.Linq; +using System.Linq; using System.Text; using Microsoft.CodeAnalysis; @@ -131,9 +130,7 @@ internal static class ISymbolExtensions /// Whether or not has an attribute with the specified name. public static bool HasAttributeWithFullyQualifiedName(this ISymbol symbol, string name) { - ImmutableArray attributes = symbol.GetAttributes(); - - foreach (AttributeData attribute in attributes) + foreach (AttributeData attribute in symbol.GetAttributes()) { if (attribute.AttributeClass?.HasFullyQualifiedName(name) == true) { @@ -153,9 +150,7 @@ internal static class ISymbolExtensions /// Whether or not has an attribute with the specified name. public static bool TryGetAttributeWithFullMetadataName(this ISymbol symbol, string name, out AttributeData? attributeData) { - ImmutableArray attributes = symbol.GetAttributes(); - - foreach (AttributeData attribute in attributes) + foreach (AttributeData attribute in symbol.GetAttributes()) { if (attribute.AttributeClass?.GetFullMetadataName() == name) { diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs index 2bb75f0e..a4b31e9c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -31,21 +31,19 @@ partial class IShaderGenerator /// /// Gathers all necessary information on a transpiled HLSL source for a given shader type. /// + /// The collection of produced instances. /// The input object currently in use. /// The node to process. /// The for . - /// The resulting diagnostics from the processing operation. /// The resulting info on the processed shader. public static HlslShaderSourceInfo GetInfo( + ImmutableArray.Builder diagnostics, Compilation compilation, StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - out ImmutableArray diagnostics) + INamedTypeSymbol structDeclarationSymbol) { - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); - // Detect invalid properties - DetectAndReportInvalidPropertyDeclarations(builder, structDeclarationSymbol); + DetectAndReportInvalidPropertyDeclarations(diagnostics, structDeclarationSymbol); // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); @@ -55,7 +53,7 @@ partial class IShaderGenerator // A given type can only represent a single shader type if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) { - builder.Add(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); + diagnostics.Add(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); } // Explore the syntax tree and extract the processed info @@ -63,19 +61,17 @@ partial class IShaderGenerator var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); var isComputeShader = pixelShaderSymbol is null; var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); - var (resourceFields, valueFields) = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader); + var (resourceFields, valueFields) = GetInstanceFields(diagnostics, structDeclarationSymbol, discoveredTypes, isComputeShader); var delegateInstanceFields = GetDispatchId.GetInfo(structDeclarationSymbol); - var sharedBuffers = GetSharedBuffers(builder, structDeclarationSymbol, discoveredTypes); - var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); + var sharedBuffers = GetSharedBuffers(diagnostics, structDeclarationSymbol, discoveredTypes); + var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); - var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); + var staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); // Process the discovered types and constants - var declaredTypes = GetDeclaredTypes(builder, structDeclarationSymbol, discoveredTypes); + var declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes); var definedConstants = GetDefinedConstants(constantDefinitions); - diagnostics = builder.ToImmutable(); - // Get the HLSL source data with the intermediate info return GetHlslSourceInfo( definedConstants, diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs index 2326268c..8443bf2c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs @@ -3,7 +3,6 @@ using System.Collections.Immutable; using System.ComponentModel; using System.Globalization; using System.IO; -using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -33,33 +32,26 @@ partial class IShaderGenerator /// /// Gets the thread ids values for a given shader type, if available. /// + /// The collection of produced instances. /// The input instance to process. /// Indicates whether or not the shader is dynamic (ie. captures delegates). /// Indicates whether or not dynamic shaders are supported. - /// The resulting diagnostics from the processing operation. /// The thread ids for the precompiled shader, if available. public static ThreadIdsInfo GetInfo( + ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol, bool isDynamicShader, - bool supportsDynamicShaders, - out ImmutableArray diagnostics) + bool supportsDynamicShaders) { - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); - - AttributeData? attribute = structDeclarationSymbol - .GetAttributes() - .FirstOrDefault(static a => a.AttributeClass?.ToDisplayString() == typeof(EmbeddedBytecodeAttribute).FullName); - - if (attribute is null) + // Try to get the attribute that controls shader precompilation (has to be present when ComputeSharp.Dynamic is not referenced) + if (!structDeclarationSymbol.TryGetAttributeWithFullMetadataName(typeof(EmbeddedBytecodeAttribute).FullName, out AttributeData? attribute)) { // Emit the diagnostics if dynamic shaders are not supported if (!supportsDynamicShaders) { - builder.Add(MissingEmbeddedBytecodeAttributeWhenDynamicShaderCompilationIsNotSupported, structDeclarationSymbol, structDeclarationSymbol); + diagnostics.Add(MissingEmbeddedBytecodeAttributeWhenDynamicShaderCompilationIsNotSupported, structDeclarationSymbol, structDeclarationSymbol); } - diagnostics = builder.ToImmutable(); - return new(true, 0, 0, 0); } @@ -68,7 +60,7 @@ partial class IShaderGenerator int threadsZ; // Check for a dispatch axis argument first - if (attribute.ConstructorArguments.Length == 1) + if (attribute!.ConstructorArguments.Length == 1) { int dispatchAxis = (int)attribute.ConstructorArguments[0].Value!; @@ -87,9 +79,7 @@ partial class IShaderGenerator // Validate the dispatch axis argument if ((threadsX, threadsY, threadsZ) is (0, 0, 0)) { - builder.Add(InvalidEmbeddedBytecodeDispatchAxis, structDeclarationSymbol, structDeclarationSymbol); - - diagnostics = builder.ToImmutable(); + diagnostics.Add(InvalidEmbeddedBytecodeDispatchAxis, structDeclarationSymbol, structDeclarationSymbol); return new(true, 0, 0, 0); } @@ -104,9 +94,7 @@ partial class IShaderGenerator explicitThreadsZ is < 1 or > 64) { // Failed to validate the thread number arguments - builder.Add(InvalidEmbeddedBytecodeThreadIds, structDeclarationSymbol, structDeclarationSymbol); - - diagnostics = builder.ToImmutable(); + diagnostics.Add(InvalidEmbeddedBytecodeThreadIds, structDeclarationSymbol, structDeclarationSymbol); return new(true, 0, 0, 0); } @@ -120,14 +108,17 @@ partial class IShaderGenerator // If the current shader is dynamic, emit a diagnostic error if (isDynamicShader) { - builder.Add(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol); - - diagnostics = builder.ToImmutable(); + diagnostics.Add(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol); return new(true, 0, 0, 0); } - diagnostics = builder.ToImmutable(); + // Ensure the bytecode generation is disabled if any errors are present. This step is done last to ensure that + // all available diagnostics are still emitted correctly before reaching this point, instead of being disabled. + if (diagnostics.Count > 0) + { + return new(true, 0, 0, 0); + } return new(false, threadsX, threadsY, threadsZ); } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs index 33bd6a0f..bfdb56ec 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -24,18 +24,18 @@ partial class IShaderGenerator /// /// Explores a given type hierarchy and generates statements to load fields. /// + /// The collection of produced instances. /// The current shader type being explored. /// The type of shader currently being processed. /// The total number of captured resources in the shader. /// The total number of needed 32 bit constants in the shader root signature. - /// The resulting diagnostics from the processing operation. /// The sequence of instances for all captured resources and values. public static ImmutableArray GetInfo( + ImmutableArray.Builder diagnostics, ITypeSymbol structDeclarationSymbol, ShaderType shaderType, out int resourceCount, - out int root32BitConstantCount, - out ImmutableArray diagnostics) + out int root32BitConstantCount) { // Helper method that uses boxes instead of ref-s (illegal in enumerators) static IEnumerable GetCapturedFieldInfos( @@ -88,8 +88,6 @@ partial class IShaderGenerator } } - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); - // Setup the resource and byte offsets for tracking. Pixel shaders have only two // implicitly captured int values, as they're always dispatched over a 2D texture. bool isComputeShader = shaderType == ShaderType.ComputeShader; @@ -124,11 +122,9 @@ partial class IShaderGenerator if (rootSignatureDwordSize > 64) { - builder.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); + diagnostics.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); } - diagnostics = builder.ToImmutable(); - return fieldInfos; } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 6d112bd5..3c207729 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -64,20 +64,20 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // LoadDispatchData() info ImmutableArray fieldInfos = LoadDispatchData.GetInfo( + diagnostics, typeSymbol, shaderType, out int resourceCount, - out int root32BitConstantCount, - out ImmutableArray dispatchDataDiagnostics); + out int root32BitConstantCount); token.ThrowIfCancellationRequested(); // BuildHlslSource() info HlslShaderSourceInfo hlslSourceInfo = BuildHlslSource.GetInfo( + diagnostics, context.SemanticModel.Compilation, typeDeclaration, - typeSymbol, - out ImmutableArray hlslSourceDiagnostics); + typeSymbol); token.ThrowIfCancellationRequested(); @@ -92,20 +92,13 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // TryGetBytecode() info ThreadIdsInfo threadIds = LoadBytecode.GetInfo( + diagnostics, typeSymbol, !hlslSourceInfo.Delegates.IsEmpty, - IsDynamicCompilationSupported(context.SemanticModel.Compilation), - out ImmutableArray threadIdsDiagnostics); + IsDynamicCompilationSupported(context.SemanticModel.Compilation)); token.ThrowIfCancellationRequested(); - // Ensure the bytecode generation is disabled if any errors are present - if (!dispatchDataDiagnostics.IsDefaultOrEmpty || - !hlslSourceDiagnostics.IsDefaultOrEmpty) - { - threadIds = new ThreadIdsInfo(true, 0, 0, 0); - } - return new ShaderInfo( Hierarchy: HierarchyInfo.From(typeSymbol), DispatchId: new DispatchIdInfo(dispatchIdInfo), From c7583eb3c7bbfd2c7768fbac9a551c65b14783bd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 18 Sep 2022 14:22:21 +0200 Subject: [PATCH 18/20] Minor tweaks and improvements to ID2D1ShaderGenerator --- .../ID2D1ShaderGenerator.cs | 50 +++++++++++-------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index f9259a85..e4502804 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -171,30 +171,21 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator .Select(static (item, _) => (item.Hierarchy, item.ResourceTextureDescriptions)); // Generate the LoadResourceTextureDescriptions() methods - context.RegisterSourceOutput(resourceTextureDescriptionsInfo.Combine(canUseSkipLocalsInit), static (context, item) => + context.RegisterSourceOutput(resourceTextureDescriptionsInfo, static (context, item) => { - MethodDeclarationSyntax getInputTypeMethod = LoadResourceTextureDescriptions.GetSyntax(item.Left.ResourceTextureDescriptions); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false); + MethodDeclarationSyntax getInputTypeMethod = LoadResourceTextureDescriptions.GetSyntax(item.ResourceTextureDescriptions); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false); - context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadResourceTextureDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); + context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(LoadResourceTextureDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); - // Get the info for both LoadDispatchData() and InitializeFromDispatchData() (hierarchy and dispatch data) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch)> dispatchDataInfo = + // Get the info for InitializeFromDispatchData() (hierarchy and dispatch data) + IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch)> initializeFromDispatchDataInfo = shaderInfoWithErrors .Select(static (item, _) => (item.Hierarchy, item.DispatchData)); - // Generate the LoadDispatchData() methods - context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) => - { - MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Left.Dispatch); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, loadDispatchDataMethod, canUseSkipLocalsInit: item.Right); - - context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - // Generate the InitializeFromDispatchData() methods - context.RegisterSourceOutput(dispatchDataInfo, static (context, item) => + context.RegisterSourceOutput(initializeFromDispatchDataInfo, static (context, item) => { MethodDeclarationSyntax loadDispatchDataMethod = InitializeFromDispatchData.GetSyntax(item.Dispatch); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadDispatchDataMethod, canUseSkipLocalsInit: false); @@ -202,6 +193,20 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(InitializeFromDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); + // Get the info for LoadDispatchData() (same as InitializeFromDispatchData(), but with [SkipLocalsInit] support flag as well) + IncrementalValuesProvider<((HierarchyInfo Hierarchy, DispatchDataInfo Dispatch) Info, bool CanUseSkipLocalsInit)> dispatchDataInfo = + initializeFromDispatchDataInfo + .Combine(canUseSkipLocalsInit); + + // Generate the LoadDispatchData() methods + context.RegisterSourceOutput(dispatchDataInfo, static (context, item) => + { + MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Info.Dispatch); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, loadDispatchDataMethod, item.CanUseSkipLocalsInit); + + context.AddSource($"{item.Info.Hierarchy.FilenameHint}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); + }); + // Get the BuildHlslSource() info (hierarchy and HLSL source) IncrementalValuesProvider<(HierarchyInfo Hierarchy, string HlslSource)> hlslSourceInfo = shaderInfoWithErrors @@ -289,17 +294,18 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator }); // Get the LoadInputDescriptions() info (hierarchy and input descriptions) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, InputDescriptionsInfo InputDescriptions)> inputDescriptionsInfo = + IncrementalValuesProvider<((HierarchyInfo Hierarchy, InputDescriptionsInfo InputDescriptions) Info, bool CanUseSkipLocalsInit) > inputDescriptionsInfo = shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.InputDescriptions)); + .Select(static (item, _) => (item.Hierarchy, item.InputDescriptions)) + .Combine(canUseSkipLocalsInit); // Generate the LoadInputDescriptions() methods - context.RegisterSourceOutput(inputDescriptionsInfo.Combine(canUseSkipLocalsInit), static (context, item) => + context.RegisterSourceOutput(inputDescriptionsInfo, static (context, item) => { - MethodDeclarationSyntax loadInputDescriptionsMethod = LoadInputDescriptions.GetSyntax(item.Left.InputDescriptions); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, loadInputDescriptionsMethod, canUseSkipLocalsInit: item.Right); + MethodDeclarationSyntax loadInputDescriptionsMethod = LoadInputDescriptions.GetSyntax(item.Info.InputDescriptions); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, loadInputDescriptionsMethod, item.CanUseSkipLocalsInit); - context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadInputDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); + context.AddSource($"{item.Info.Hierarchy.FilenameHint}.{nameof(LoadInputDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); // Get the GetPixelOptions() info (hierarchy and pixel options) From ff04ee384c1228dd61e0ed1dadf65f2c91b142c0 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 18 Sep 2022 14:38:10 +0200 Subject: [PATCH 19/20] Minor code tweaks --- .../Analyzers/InvalidAssemblyLevelCompileOptionsAnalyzer.cs | 4 ---- .../Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs | 4 ---- ...D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs | 3 +-- 3 files changed, 1 insertion(+), 10 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidAssemblyLevelCompileOptionsAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidAssemblyLevelCompileOptionsAnalyzer.cs index 602437a9..50d4843b 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidAssemblyLevelCompileOptionsAnalyzer.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidAssemblyLevelCompileOptionsAnalyzer.cs @@ -1,7 +1,3 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - using System.Collections.Immutable; using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs index 711ff539..1b599546 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs @@ -1,7 +1,3 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - using System.Collections.Immutable; using System.Linq; using ComputeSharp.SourceGeneration.Extensions; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Suppressors/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Suppressors/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs index 02822084..6a34ff49 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Suppressors/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Suppressors/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs @@ -48,8 +48,7 @@ public sealed class D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor : ISymbol? declaredSymbol = semanticModel.GetDeclaredSymbol(syntaxNode, context.CancellationToken); // Check if the field is in a struct and it's of a D2D1 resource texture type - if (declaredSymbol is IFieldSymbol fieldSymbol && - fieldSymbol.ContainingType is { TypeKind: TypeKind.Struct } structSymbol && + if (declaredSymbol is IFieldSymbol { ContainingType: { TypeKind: TypeKind.Struct } structSymbol } fieldSymbol && HlslKnownTypes.IsResourceTextureType(fieldSymbol.Type.GetFullMetadataName())) { // Get the ID2D1PixelShader interface symbol to the check the containing type of the field From 9d8aa1d57b3d9a710fa83e29bcb15e35039659e2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 18 Sep 2022 14:39:00 +0200 Subject: [PATCH 20/20] Fix message for CMPS0044 error --- .../Diagnostics/DiagnosticDescriptors.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 29869604..5e95f4e8 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -605,13 +605,13 @@ partial class DiagnosticDescriptors /// /// Gets a for an embedded bytecode shader with invalid thread ids values. /// - /// Format: "The shader of type {0} is annotated with invalid thread ids values ({1}, {2}, {3})". + /// Format: "The shader of type {0} is annotated with invalid thread ids values". /// /// public static readonly DiagnosticDescriptor InvalidEmbeddedBytecodeThreadIds = new DiagnosticDescriptor( id: "CMPS0044", title: "Invalid thread ids for shader with embedded bytecode", - messageFormat: "The shader of type {0} is annotated with invalid thread ids values ({1}, {2}, {3})", + messageFormat: "The shader of type {0} is annotated with invalid thread ids values", category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true,