diff --git a/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs
index 9b84bdcc..6d78bed9 100644
--- a/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs
+++ b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs
@@ -20,20 +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 (node, _) => node is StructDeclarationSyntax structDeclaration,
+ static (context, _) =>
+ {
+ 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)
- .WithComparers(HierarchyInfo.Comparer.Default, ConstructorInfo.Comparer.Default);
+ 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);
// 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.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 fb64cfa0..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;
@@ -20,76 +21,74 @@ 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 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, token) =>
+ {
+ 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 the processed HLSL first and check for cancellation
+ string hlslSource = Execute.GetHlslSource(diagnostics, methodSymbol);
- HlslShaderMethodSourceInfo sourceInfo = new(
- modifiers,
- methodName,
- invalidReturnType,
- hlslSource,
- shaderProfile,
- compileOptions,
- HasErrors: diagnostics.Count > 0);
+ token.ThrowIfCancellationRequested();
- HierarchyInfo hierarchy = HierarchyInfo.From(item.Symbol.ContainingType!);
+ // 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);
+ D2D1ShaderProfile shaderProfile = Execute.GetShaderProfile(diagnostics, methodSymbol);
+ D2D1CompileOptions compileOptions = Execute.GetCompileOptions(diagnostics, methodSymbol);
- 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 =
+ context.ReportDiagnostics(
shaderInfoWithErrors
- .Select(static (item, token) => (item.Hierarchy, item.Source))
- .WithComparers(HierarchyInfo.Comparer.Default, HlslShaderMethodSourceInfo.Comparer.Default);
+ .Select(static (item, _) => item.Diagnostcs)
+ .WithComparer(EqualityComparer.Default.ForImmutableArray()));
// Compile the requested shader bytecodes
- IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeMethodInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors =
- shaderInfo
+ IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeMethodInfo BytecodeInfo, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors =
+ shaderInfoWithErrors
.Select(static (item, token) =>
{
ImmutableArray bytecode = Execute.GetBytecode(
- item.Source,
+ item.HlslShaderMethodSource,
token,
- out DiagnosticInfo? diagnostic);
+ out DeferredDiagnosticInfo? 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);
});
// 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)
@@ -97,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
@@ -110,8 +106,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/Diagnostics/Analyzers/InvalidAssemblyLevelCompileOptionsAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidAssemblyLevelCompileOptionsAnalyzer.cs
new file mode 100644
index 00000000..50d4843b
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidAssemblyLevelCompileOptionsAnalyzer.cs
@@ -0,0 +1,48 @@
+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/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs
new file mode 100644
index 00000000..1b599546
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DResourceTextureIndexUseAnalyzer.cs
@@ -0,0 +1,48 @@
+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.First(),
+ fieldSymbol.Name,
+ fieldSymbol.ContainingType,
+ fieldSymbol.Type);
+
+ context.ReportDiagnostic(diagnostic);
+ }
+ }
+ }, SymbolKind.Field);
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Suppressors/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs
similarity index 93%
rename from src/ComputeSharp.D2D1.SourceGenerators/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs
rename to src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Suppressors/D2D1ResourceTextureUninitializedFieldDiagnosticSuppressor.cs
index 43e4f83c..6a34ff49 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/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
@@ -61,7 +60,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.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs
index 0e0e3986..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;
@@ -19,26 +19,9 @@ 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
- // 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)
- };
-
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.BuildHlslSource(out string hlslSource)
@@ -55,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.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 a8dd4db6..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))
{
@@ -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.
///
@@ -151,7 +123,7 @@ partial class ID2D1ShaderGenerator
HlslShaderSourceInfo sourceInfo,
CancellationToken token,
out D2D1CompileOptions options,
- out DiagnosticInfo? diagnostic)
+ out DeferredDiagnosticInfo? diagnostic)
{
ImmutableArray bytecode = ImmutableArray.Empty;
@@ -193,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 04228cff..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,17 +21,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 +60,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 +76,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.CreateLoadResourceTextureDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs
index ad3f07cf..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)
@@ -106,30 +107,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.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 fad72415..e4502804 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
@@ -25,129 +25,122 @@ public sealed partial class ID2D1ShaderGenerator : 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"));
- // 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 ID2D1PixelShader interface
- IncrementalValueProvider pixelShaderInterface =
- context.CompilationProvider
- .Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(ID2D1PixelShader).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 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)));
+ // Check that the shader implements the ID2D1PixelShader interface
+ if (!IsD2D1PixelShaderType(typeSymbol, context.SemanticModel.Compilation))
+ {
+ return default;
+ }
- // 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();
+ ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder();
- // LoadDispatchData() info
- ImmutableArray fieldInfos = LoadDispatchData.GetInfo(
- diagnostics,
- item.Left.Symbol,
- out int constantBufferSizeInBytes);
+ // LoadDispatchData() info
+ ImmutableArray fieldInfos = LoadDispatchData.GetInfo(
+ diagnostics,
+ typeSymbol,
+ out int constantBufferSizeInBytes);
- token.ThrowIfCancellationRequested();
+ token.ThrowIfCancellationRequested();
- DispatchDataInfo dispatchDataInfo = new(fieldInfos, constantBufferSizeInBytes);
+ // Get the input info for GetInputInfo()
+ GetInputType.GetInfo(
+ diagnostics,
+ typeSymbol,
+ out int inputCount,
+ out ImmutableArray inputSimpleIndices,
+ out ImmutableArray inputComplexIndices,
+ out ImmutableArray inputTypes);
- // Get the input info for GetInputInfo()
- GetInputType.GetInfo(
- diagnostics,
- item.Left.Symbol,
- 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);
- InputTypesInfo inputTypesInfo = new(inputTypes);
+ // Get HLSL source for BuildHlslSource()
+ string hlslSource = BuildHlslSource.GetHlslSource(
+ diagnostics,
+ context.SemanticModel.Compilation,
+ typeDeclaration,
+ typeSymbol,
+ inputCount,
+ inputSimpleIndices,
+ inputComplexIndices);
- // Get the resource texture info for LoadResourceTextureDescriptions()
- LoadResourceTextureDescriptions.GetInfo(
- diagnostics,
- item.Left.Symbol,
- inputCount,
- out ImmutableArray resourceTextureDescriptions);
+ token.ThrowIfCancellationRequested();
- ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo = new(resourceTextureDescriptions);
+ // 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);
- // Get HLSL source for BuildHlslSource()
- string hlslSource = BuildHlslSource.GetHlslSource(
- diagnostics,
- item.Right,
- item.Left.Syntax,
- item.Left.Symbol,
- inputCount,
- inputSimpleIndices,
- inputComplexIndices);
+ token.ThrowIfCancellationRequested();
- token.ThrowIfCancellationRequested();
+ // Get the info for GetOutputBuffer()
+ GetOutputBuffer.GetInfo(typeSymbol, out D2D1BufferPrecision bufferPrecision, out D2D1ChannelDepth channelDepth);
- // 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);
+ token.ThrowIfCancellationRequested();
- HlslShaderSourceInfo sourceInfo = new(
- hlslSource,
- shaderProfile,
- compileOptions,
- isLinkingSupported,
- HasErrors: diagnostics.Count > 0);
+ // Get the info for LoadInputDescriptions()
+ LoadInputDescriptions.GetInfo(
+ diagnostics,
+ typeSymbol,
+ out ImmutableArray inputDescriptions);
- token.ThrowIfCancellationRequested();
+ token.ThrowIfCancellationRequested();
- return (
- item.Left.Hierarchy,
- dispatchDataInfo,
- inputTypesInfo,
- resourceTextureDescriptionsInfo,
- sourceInfo,
- diagnostics.ToImmutableArray());
- });
+ // Get the info for GetPixelOptions()
+ GetPixelOptions.GetInfo(typeSymbol, out D2D1PixelOptions pixelOptions);
- // Output the diagnostics
- context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Diagnostics));
+ token.ThrowIfCancellationRequested();
- // 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)))
+ 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)!;
- // 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 =
+ // Output the diagnostics, if any
+ context.ReportDiagnostics(
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, _) => item.Diagnostcs)
+ .WithComparer(EqualityComparer.Default.ForImmutableArray()));
- // 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))
- .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default);
+ shaderInfoWithErrors
+ .Select(static (item, _) => (item.Hierarchy, item.InputTypes.InputTypes.Length));
// Generate the GetInputCount() methods
context.RegisterSourceOutput(inputCountInfo, static (context, item) =>
@@ -158,11 +151,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))
- .WithComparers(HierarchyInfo.Comparer.Default, InputTypesInfo.Comparer.Default);
+ shaderInfoWithErrors
+ .Select(static (item, _) => (item.Hierarchy, item.InputTypes));
// Generate the GetInputType() methods
context.RegisterSourceOutput(inputTypesInfo, static (context, item) =>
@@ -173,38 +165,27 @@ 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))
- .WithComparers(HierarchyInfo.Comparer.Default, ResourceTextureDescriptionsInfo.Comparer.Default);
+ shaderInfoWithErrors
+ .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 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);
-
- // 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));
- });
+ // 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 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);
@@ -212,34 +193,41 @@ 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
- IncrementalValuesProvider<(HierarchyInfo Hierarchy, string HlslSource)> hlslSourceInfo =
- shaderInfo
- .Select(static (item, token) => (item.Hierarchy, item.Source.HlslSource))
- .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default);
+ // 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);
- // 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) =>
+ // Generate the LoadDispatchData() methods
+ context.RegisterSourceOutput(dispatchDataInfo, 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 loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Info.Dispatch);
+ CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, loadDispatchDataMethod, item.CanUseSkipLocalsInit);
- context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
+ context.AddSource($"{item.Info.Hierarchy.FilenameHint}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
- // Get a filtered sequence to enable caching
+ // Get the BuildHlslSource() info (hierarchy and HLSL source)
+ IncrementalValuesProvider<(HierarchyInfo Hierarchy, string HlslSource)> hlslSourceInfo =
+ shaderInfoWithErrors
+ .Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource.HlslSource));
+
+ // Generate the BuildHlslSource() methods
+ context.RegisterSourceOutput(hlslSourceInfo, static (context, item) =>
+ {
+ MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.HlslSource, item.Hierarchy.Hierarchy.Length);
+ CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: false);
+
+ context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
+ });
+
+ // 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))
- .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default);
+ shaderInfoWithErrors
+ .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) =>
{
@@ -247,7 +235,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
item.Source,
token,
out D2D1CompileOptions options,
- out DiagnosticInfo? diagnostic);
+ out DeferredDiagnosticInfo? diagnostic);
token.ThrowIfCancellationRequested();
@@ -261,29 +249,25 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
});
// Gather the diagnostics
- IncrementalValuesProvider embeddedBytecodeDiagnostics =
+ 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)!;
-
- 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
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, token) => (item.Hierarchy, item.BytecodeInfo))
- .WithComparers(HierarchyInfo.Comparer.Default, EmbeddedBytecodeInfo.Comparer.Default);
+ .Select(static (item, _) => (item.Hierarchy, item.BytecodeInfo));
// Generate the LoadBytecode() methods
context.RegisterSourceOutput(embeddedBytecode, static (context, item) =>
@@ -295,103 +279,47 @@ 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);
- })
- .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default);
+ // 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))
- .WithComparers(HierarchyInfo.Comparer.Default, InputDescriptionsInfo.Comparer.Default);
+ // Get the LoadInputDescriptions() info (hierarchy and input descriptions)
+ IncrementalValuesProvider<((HierarchyInfo Hierarchy, InputDescriptionsInfo InputDescriptions) Info, bool CanUseSkipLocalsInit) > inputDescriptionsInfo =
+ shaderInfoWithErrors
+ .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.Info);
- 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 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);
- })
- .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default);
+ // 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));
});
-
- // 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);
}
}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs
new file mode 100644
index 00000000..2a3e64dc
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs
@@ -0,0 +1,49 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
+using ComputeSharp.SourceGeneration.Models;
+
+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);
+ }
+ }
+}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs
new file mode 100644
index 00000000..643889ba
--- /dev/null
+++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs
@@ -0,0 +1,73 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
+using ComputeSharp.SourceGeneration.Models;
+
+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.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.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/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.
///
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.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 eb8eff64..83b77644 100644
--- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems
+++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems
@@ -15,14 +15,13 @@
-
+
-
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs
index 8426ed9c..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;
@@ -10,67 +10,35 @@ namespace ComputeSharp.SourceGeneration.Extensions;
internal static class DiagnosticsExtensions
{
///
- /// Adds a new diagnostics to the current compilation.
+ /// Adds a new diagnostics to the target builder.
///
- /// The instance currently in use.
+ /// 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 ReportDiagnostic(
- this GeneratorExecutionContext context,
+ public static void Add(
+ this ImmutableArray.Builder diagnostics,
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));
+ diagnostics.Add(DiagnosticInfo.Create(descriptor, symbol, args));
}
///
/// Adds a new diagnostics to the target builder.
///
- /// 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,
- DiagnosticDescriptor descriptor,
- ISymbol symbol,
- params object[] args)
- {
- diagnostics.Add(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), 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));
}
///
@@ -78,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());
});
}
@@ -91,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/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.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));
- }
- }
-}
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 88639f74..6eb80f9a 100644
--- a/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs
+++ b/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs
@@ -1,32 +1,87 @@
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);
+
+ ///
+ 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 .
///
- public sealed class Comparer : Comparer
+ private sealed class Comparer : Comparer
{
///
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);
}
///
@@ -34,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/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.SourceGeneration/Models/Result{T}.cs b/src/ComputeSharp.SourceGeneration/Models/Result{T}.cs
deleted file mode 100644
index 923ec833..00000000
--- a/src/ComputeSharp.SourceGeneration/Models/Result{T}.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using System.Collections.Immutable;
-using Microsoft.CodeAnalysis;
-
-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);
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,
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs
index 8f7b86c7..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;
@@ -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,30 +117,13 @@ partial class IShaderGenerator
sizeHint += textBuilder.Length;
- // If raw multiline string literal expressions are used, create a token to represent it. 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)
- };
-
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();
}
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs
index 020a1e84..a4b31e9c 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;
@@ -30,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);
@@ -54,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
@@ -62,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,
@@ -94,7 +91,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 +100,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 +183,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 +191,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 +253,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 +309,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 +319,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 +438,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 +500,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.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.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs
index 8ecf75a9..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);
}
@@ -149,7 +140,7 @@ partial class IShaderGenerator
ThreadIdsInfo threadIds,
string hlslSource,
CancellationToken token,
- out DiagnosticInfo? diagnostic)
+ out DeferredDiagnosticInfo? diagnostic)
{
ImmutableArray bytecode = ImmutableArray.Empty;
@@ -189,11 +180,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.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 665162db..bfdb56ec 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;
@@ -23,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 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(
+ ImmutableArray.Builder diagnostics,
ITypeSymbol structDeclarationSymbol,
- Type shaderInterfaceType,
+ 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(
@@ -87,11 +88,9 @@ 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 = shaderInterfaceType == typeof(IComputeShader);
+ bool isComputeShader = shaderType == ShaderType.ComputeShader;
int initialRawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
StrongBox resourceOffsetAsBox = new();
StrongBox rawDataOffsetAsBox = new(initialRawDataOffset);
@@ -123,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.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 10ce11fb..3c207729 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs
@@ -25,203 +25,175 @@ 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))))
- .WithComparers(HierarchyInfo.Comparer.Default, DispatchIdInfo.Comparer.Default);
+ ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder();
+
+ // GetDispatchId() info
+ ImmutableArray dispatchIdInfo = GetDispatchId.GetInfo(typeSymbol);
+
+ token.ThrowIfCancellationRequested();
+
+ // LoadDispatchData() info
+ ImmutableArray fieldInfos = LoadDispatchData.GetInfo(
+ diagnostics,
+ typeSymbol,
+ shaderType,
+ out int resourceCount,
+ out int root32BitConstantCount);
+
+ token.ThrowIfCancellationRequested();
+
+ // BuildHlslSource() info
+ HlslShaderSourceInfo hlslSourceInfo = BuildHlslSource.GetInfo(
+ diagnostics,
+ context.SemanticModel.Compilation,
+ typeDeclaration,
+ typeSymbol);
+
+ 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(
+ diagnostics,
+ typeSymbol,
+ !hlslSourceInfo.Delegates.IsEmpty,
+ IsDynamicCompilationSupported(context.SemanticModel.Compilation));
+
+ token.ThrowIfCancellationRequested();
+
+ 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))
- .WithComparers(DispatchDataInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default, EqualityComparer.Default);
-
- // Get a filtered sequence to enable caching
- IncrementalValuesProvider dispatchDataInfo =
- shaderInfo
- .Select(static (item, token) => item.Dispatch)
- .WithComparer(DispatchDataInfo.Comparer.Default);
+ .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))
- .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 });
+ // 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).Combine(canUseRawMultiLineStringLiterals), static (context, item) =>
+ context.RegisterSourceOutput(hlslSourceInfo, 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.Info.HlslShaderSource, item.Options.SupportsDynamicShaders, item.Info.Hierarchy.Hierarchy.Length);
+ CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, buildHlslStringMethod, item.Options.CanUseSkipLocalsInit);
- context.AddSource($"{item.Left.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);
- })
- .WithComparers(HierarchyInfo.Comparer.Default, DispatchMetadataInfo.Comparer.Default);
+ // 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))
- .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default, EqualityComparer.Default);
+ shaderInfoWithErrors
+ .Select(static (item, token) => (item.Hierarchy, BuildHlslSource.GetNonDynamicHlslSource(item.HlslShaderSource), item.ThreadIds));
// Compile the requested shader bytecodes
- IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors =
+ IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode, 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();
@@ -235,7 +207,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)
@@ -243,30 +215,27 @@ 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
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))
- .WithComparers(HierarchyInfo.Comparer.Default, EmbeddedBytecodeInfo.Comparer.Default);
+ .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 a87e21f0..e733ea62 100644
--- a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs
+++ b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs
@@ -3,36 +3,38 @@ 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)
{
+ ///
+ 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.Type);
- hashCode.AddRange(obj.FieldInfos, FieldInfo.Comparer.Default);
+ hashCode.AddRange(obj.FieldInfos);
hashCode.Add(obj.ResourceCount);
hashCode.Add(obj.Root32BitConstantCount);
}
@@ -41,9 +43,8 @@ internal sealed record DispatchDataInfo(
protected override bool AreEqual(DispatchDataInfo x, DispatchDataInfo y)
{
return
- HierarchyInfo.Comparer.Default.Equals(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/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/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/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
diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs
index e7323701..dd06162d 100644
--- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs
@@ -28,43 +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