Merge pull request #382 from Sergio0694/dev/generator-tweaks

Revamp and optimize source generators
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2022-09-18 07:20:27 -07:00
コミット 46f0dcbacd
61ファイル変更
+1379 -1289

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

+20 -10
ファイルの表示
@@ -20,20 +20,30 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator
/// <inheritdoc/>
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Get all declared struct symbols with the [AutoConstructor] attribute
IncrementalValuesProvider<INamedTypeSymbol> 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) =>
+7 -1
ファイルの表示
@@ -13,10 +13,16 @@ namespace ComputeSharp.Core.SourceGenerators.Models;
/// <param name="DefaultedFields">The names of ignored fields that should be defaulted.</param>
internal sealed record ConstructorInfo(ImmutableArray<ParameterInfo> Parameters, ImmutableArray<string> DefaultedFields)
{
/// <inheritdoc/>
public bool Equals(ConstructorInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="ConstructorInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<ConstructorInfo, Comparer>
private sealed class Comparer : Comparer<ConstructorInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, ConstructorInfo obj)
+11 -11
ファイルの表示
@@ -26,10 +26,10 @@ partial class D2DPixelShaderSourceGenerator
/// <summary>
/// Validates that the return type of the annotated method is valid and returns the type name.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
/// <returns>The HLSL source to compile, if present.</returns>
public static string? GetInvalidReturnType(ImmutableArray<Diagnostic>.Builder diagnostics, IMethodSymbol methodSymbol)
public static string? GetInvalidReturnType(ImmutableArray<DiagnosticInfo>.Builder diagnostics, IMethodSymbol methodSymbol)
{
if (!(methodSymbol.ReturnType is INamedTypeSymbol
{
@@ -55,10 +55,10 @@ partial class D2DPixelShaderSourceGenerator
/// <summary>
/// Extracts the HLSL source from a method with the <see cref="D2DPixelShaderSourceAttribute"/> annotation.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
/// <returns>The HLSL source to compile, if present.</returns>
public static string GetHlslSource(ImmutableArray<Diagnostic>.Builder diagnostics, IMethodSymbol methodSymbol)
public static string GetHlslSource(ImmutableArray<DiagnosticInfo>.Builder diagnostics, IMethodSymbol methodSymbol)
{
_ = methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute", out AttributeData? attributeData);
@@ -77,10 +77,10 @@ partial class D2DPixelShaderSourceGenerator
/// <summary>
/// Extracts the shader profile for a target method, if present.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
/// <returns>The shader profile to use to compile the shader, if present.</returns>
public static D2D1ShaderProfile GetShaderProfile(ImmutableArray<Diagnostic>.Builder diagnostics, IMethodSymbol methodSymbol)
public static D2D1ShaderProfile GetShaderProfile(ImmutableArray<DiagnosticInfo>.Builder diagnostics, IMethodSymbol methodSymbol)
{
if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out AttributeData? attributeData))
{
@@ -104,10 +104,10 @@ partial class D2DPixelShaderSourceGenerator
/// <summary>
/// Extracts the compile options for the current shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
/// <returns>The compile options to use to compile the shader, if present.</returns>
public static D2D1CompileOptions GetCompileOptions(ImmutableArray<Diagnostic>.Builder diagnostics, IMethodSymbol methodSymbol)
public static D2D1CompileOptions GetCompileOptions(ImmutableArray<DiagnosticInfo>.Builder diagnostics, IMethodSymbol methodSymbol)
{
if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData))
{
@@ -135,7 +135,7 @@ partial class D2DPixelShaderSourceGenerator
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <param name="diagnostic">The resulting diagnostic from the processing operation, if any.</param>
/// <returns>The <see cref="ImmutableArray{T}"/> instance with the compiled shader bytecode.</returns>
public static unsafe ImmutableArray<byte> GetBytecode(HlslShaderMethodSourceInfo sourceInfo, CancellationToken token, out DiagnosticInfo? diagnostic)
public static unsafe ImmutableArray<byte> GetBytecode(HlslShaderMethodSourceInfo sourceInfo, CancellationToken token, out DeferredDiagnosticInfo? diagnostic)
{
ImmutableArray<byte> bytecode = ImmutableArray<byte>.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));
+45 -50
ファイルの表示
@@ -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
/// <inheritdoc/>
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<D2D1PixelShaderSourceInfo> 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<Diagnostic> Diagnostics)> shaderInfoWithErrors =
methodDeclarationsAndSymbols
.Select(static (item, _) =>
{
ImmutableArray<Diagnostic>.Builder diagnostics = ImmutableArray.CreateBuilder<Diagnostic>();
ImmutableArray<DiagnosticInfo>.Builder diagnostics = ImmutableArray.CreateBuilder<DiagnosticInfo>();
// Get all necessary info for the current shader
ImmutableArray<SyntaxKind> 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<SyntaxKind> 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<DiagnosticInfo>.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<byte> 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<Diagnostic> embeddedBytecodeDiagnostics =
IncrementalValuesProvider<DiagnosticInfo> 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) =>
@@ -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;
/// <summary>
/// A diagnostic analyzer that generates an error whenever invalid options are used in an assembly-level [D2D1CompileOptions] attribute.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class InvalidAssemblyLevelCompileOptionsAnalyzer : DiagnosticAnalyzer
{
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(InvalidPackMatrixColumnMajorOption);
/// <inheritdoc/>
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);
}
}
});
}
}
@@ -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;
/// <summary>
/// A diagnostic analyzer that generates an error whenever [D2DResourceTextureIndex] is used incorrectly to annotate an invalid field.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class InvalidD2DResourceTextureIndexUseAnalyzer : DiagnosticAnalyzer
{
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(InvalidD2DResourceTextureIndexAttributeUse);
/// <inheritdoc/>
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);
}
}
@@ -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));
}
@@ -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
/// </summary>
/// <param name="hlslSource">The input HLSL source.</param>
/// <param name="hierarchyDepth">The depth of the hierarchy for this type (used to calculate the right indentation).</param>
/// <param name="useRawMultiLineStringLiteralExpression">Whether to use a raw multiline string literal expression</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslSource</c> method.</returns>
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))))));
}
}
}
@@ -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
/// <summary>
/// Gathers all necessary information on a transpiled HLSL source for a given shader type.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
@@ -37,7 +38,7 @@ partial class ID2D1ShaderGenerator
/// <param name="inputComplexIndices">The indicess of the complex shader inputs.</param>
/// <returns>The HLSL source for the shader.</returns>
public static string GetHlslSource(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
Compilation compilation,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
@@ -94,13 +95,13 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Gets a sequence of captured fields and their mapped names.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="types">The collection of currently discovered types.</param>
/// <param name="valueFields">The sequence of captured fields in <paramref name="structDeclarationSymbol"/>.</param>
/// <param name="resourceTextureFields">The sequence of captured resource textures in <paramref name="structDeclarationSymbol"/>.</param>
private static void GetInstanceFields(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> types,
out ImmutableArray<(string Name, string HlslType)> valueFields,
@@ -182,7 +183,7 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Gets a sequence of shader static fields and their mapped names.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the current type.</param>
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
@@ -191,7 +192,7 @@ partial class ID2D1ShaderGenerator
/// <param name="needsD2D1RequiresScenePosition">Whether or not the shader needs the <c>[D2DRequiresScenePosition]</c> annotation.</param>
/// <returns>A sequence of static constant fields in <paramref name="structDeclarationSymbol"/>.</returns>
private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
SemanticModelProvider semanticModel,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
@@ -251,7 +252,7 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Gets a sequence of processed methods declared within a given type.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the current type.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
@@ -261,7 +262,7 @@ partial class ID2D1ShaderGenerator
/// <param name="needsD2D1RequiresScenePosition">Whether or not the shader needs the <c>[D2DRequiresScenePosition]</c> annotation.</param>
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods) GetProcessedMethods(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
SemanticModelProvider semanticModel,
@@ -370,12 +371,12 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Gets the sequence of processed discovered custom types.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
/// <param name="types">The sequence of discovered custom types.</param>
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
IEnumerable<INamedTypeSymbol> types)
{
@@ -434,9 +435,9 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Finds and reports all invalid declared properties in a shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArray<Diagnostic>.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol)
private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArray<DiagnosticInfo>.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol)
{
foreach (var memberSymbol in structDeclarationSymbol.GetMembers())
{
@@ -457,12 +458,12 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Reports diagnostics for invalid uses of <c>[D2DRequiresScenePosition]</c> in a shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="requiresScenePosition">Whether the shader type is declaring the need for scene position.</param>
/// <param name="usesPositionDependentMethods">Whether the shader is using APIs that rely on scene position.</param>
private static void ReportInvalidD2DRequiresScenePositionUse(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
bool requiresScenePosition,
bool usesPositionDependentMethods)
@@ -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
/// <summary>
/// Extracts the input info for the current shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="inputCount">The number of shader inputs to declare.</param>
/// <param name="inputSimpleIndices">The indicess of the simple shader inputs.</param>
/// <param name="inputComplexIndices">The indices of the complex shader inputs.</param>
/// <param name="combinedInputTypes">The combined and serialized input types for each available input.</param>
public static void GetInfo(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
out int inputCount,
out ImmutableArray<int> inputSimpleIndices,
+5 -33
ファイルの表示
@@ -48,10 +48,10 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Extracts the compile options for the current shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The compile options to use to compile the shader, if present.</returns>
public static D2D1CompileOptions? GetCompileOptions(ImmutableArray<Diagnostic>.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol)
public static D2D1CompileOptions? GetCompileOptions(ImmutableArray<DiagnosticInfo>.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol)
{
if (structDeclarationSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData))
{
@@ -78,34 +78,6 @@ partial class ID2D1ShaderGenerator
return null;
}
/// <summary>
/// Gets a <see cref="Diagnostic"/>-s for invalid assembly-level <c>[D2D1CompileOptions]</c> attribute, if one is present.
/// </summary>
/// <param name="assemblySymbol">The input <see cref="IAssemblySymbol"/> instance to process.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation.</param>
/// <returns>The diagnostic for the attribute, if invalid.</returns>
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;
}
/// <summary>
/// Extracts the metadata definition for the current shader.
/// </summary>
@@ -151,7 +123,7 @@ partial class ID2D1ShaderGenerator
HlslShaderSourceInfo sourceInfo,
CancellationToken token,
out D2D1CompileOptions options,
out DiagnosticInfo? diagnostic)
out DeferredDiagnosticInfo? diagnostic)
{
ImmutableArray<byte> bytecode = ImmutableArray<byte>.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:
@@ -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
/// <summary>
/// Explores a given type hierarchy and generates statements to load fields.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
/// <returns>The sequence of <see cref="FieldInfo"/> instances for all captured resources and values.</returns>
public static ImmutableArray<FieldInfo> GetInfo(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ITypeSymbol structDeclarationSymbol,
out int constantBufferSizeInBytes)
{
@@ -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
/// <summary>
/// Extracts the input descriptions for the current shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="inputDescriptions">The produced input descriptions for the shader.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
public static void GetInfo(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
out ImmutableArray<InputDescription> inputDescriptions,
out ImmutableArray<Diagnostic> diagnostics)
out ImmutableArray<InputDescription> inputDescriptions)
{
int inputCount = 0;
ImmutableArray<InputDescription>.Builder inputDescriptionsBuilder = ImmutableArray.CreateBuilder<InputDescription>();
ImmutableArray<Diagnostic>.Builder diagnosticsBuilder = ImmutableArray.CreateBuilder<Diagnostic>();
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<uint> 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();
}
}
}
@@ -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
/// <summary>
/// Extracts the resource texture descriptions for the current shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="inputCount">The number of inputs for the shader.</param>
/// <param name="resourceTextureDescriptions">The produced resource texture descriptions for the shader.</param>
public static void GetInfo(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
int inputCount,
out ImmutableArray<ResourceTextureDescription> resourceTextureDescriptions)
@@ -106,30 +107,5 @@ partial class ID2D1ShaderGenerator
diagnostics.Add(RepeatedD2DResourceTextureIndices, structDeclarationSymbol, structDeclarationSymbol);
}
}
/// <summary>
/// Gets the diagnostics for a field with invalid <c>[D2DResourceTextureIndex]</c> attribute use, if that is the case.
/// </summary>
/// <param name="fieldSymbol">The input <see cref="IFieldSymbol"/> instance to process.</param>
/// <returns>The resulting <see cref="Diagnostic"/> instance for <paramref name="fieldSymbol"/>, if needed.</returns>
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;
}
}
}
+10 -6
ファイルの表示
@@ -14,16 +14,20 @@ partial class ID2D1ShaderGenerator
/// Gets the shader type for a given shader, if any.
/// </summary>
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance to check.</param>
/// <param name="d2D1PixelShaderSymbol">The <see cref="INamedTypeSymbol"/> instance for <see cref="ID2D1PixelShader"/>.</param>
/// <returns>Whether or not <paramref name="typeSymbol"/> implements <paramref name="d2D1PixelShaderSymbol"/>.</returns>
public static bool IsD2D1PixelShaderType(INamedTypeSymbol typeSymbol, INamedTypeSymbol d2D1PixelShaderSymbol)
/// <param name="compilation">The <see cref="Compilation"/> instance currently in use.</param>
/// <returns>Whether or not <paramref name="typeSymbol"/> is a D2D1 interface type.</returns>
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;
}
}
}
+157 -229
ファイルの表示
@@ -25,129 +25,122 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
// Check whether [SkipLocalsInit] can be used
IncrementalValueProvider<bool> 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<D2D1ShaderInfo> 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<StructDeclarationSyntax>(),
static (context, token) =>
{
StructDeclarationSyntax typeDeclaration = (StructDeclarationSyntax)context.Node;
// Get the symbol for the ID2D1PixelShader interface
IncrementalValueProvider<INamedTypeSymbol> 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<Diagnostic> Diagnostics)> shaderInfoWithErrors =
shaderDeclarations
.Combine(context.CompilationProvider)
.Select(static (item, token) =>
{
ImmutableArray<Diagnostic>.Builder diagnostics = ImmutableArray.CreateBuilder<Diagnostic>();
ImmutableArray<DiagnosticInfo>.Builder diagnostics = ImmutableArray.CreateBuilder<DiagnosticInfo>();
// LoadDispatchData() info
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
diagnostics,
item.Left.Symbol,
out int constantBufferSizeInBytes);
// LoadDispatchData() info
ImmutableArray<FieldInfo> 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<int> inputSimpleIndices,
out ImmutableArray<int> inputComplexIndices,
out ImmutableArray<uint> inputTypes);
// Get the input info for GetInputInfo()
GetInputType.GetInfo(
diagnostics,
item.Left.Symbol,
out int inputCount,
out ImmutableArray<int> inputSimpleIndices,
out ImmutableArray<int> inputComplexIndices,
out ImmutableArray<uint> inputTypes);
// Get the resource texture info for LoadResourceTextureDescriptions()
LoadResourceTextureDescriptions.GetInfo(
diagnostics,
typeSymbol,
inputCount,
out ImmutableArray<ResourceTextureDescription> 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<ResourceTextureDescription> 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<InputDescription> 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<Diagnostic> 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<HlslShaderSourceInfo>.Default);
.Select(static (item, _) => item.Diagnostcs)
.WithComparer(EqualityComparer<DiagnosticInfo>.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<int>.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<string>.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<bool> 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<HlslShaderSourceInfo>.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<Diagnostic> embeddedBytecodeDiagnostics =
IncrementalValuesProvider<DiagnosticInfo> 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<OutputBufferInfo>.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<InputDescriptionsInfo> Info)> inputDescriptionsInfoWithErrors =
shaderDeclarations
.Select(static (item, token) =>
{
// LoadInputDescriptions() info
LoadInputDescriptions.GetInfo(
item.Symbol,
out ImmutableArray<InputDescription> inputDescriptions,
out ImmutableArray<Diagnostic> diagnostics);
token.ThrowIfCancellationRequested();
InputDescriptionsInfo inputDescriptionsInfo = new(inputDescriptions);
return (item.Hierarchy, new Result<InputDescriptionsInfo>(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<D2D1PixelOptions>.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<Diagnostic> 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);
}
}
+49
ファイルの表示
@@ -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;
/// <summary>
/// A model representing all necessary info for a full generation pass for a [D2D1PixelShaderSource] attribute.
/// </summary>
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
/// <param name="HlslShaderMethodSource">The processed HLSL source for the shader.</param>
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
internal sealed record D2D1PixelShaderSourceInfo(
HierarchyInfo Hierarchy,
HlslShaderMethodSourceInfo HlslShaderMethodSource,
ImmutableArray<DiagnosticInfo> Diagnostcs)
{
/// <inheritdoc/>
public bool Equals(D2D1PixelShaderSourceInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="D2D1PixelShaderSourceInfo"/>.
/// </summary>
private sealed class Comparer : Comparer<D2D1PixelShaderSourceInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, D2D1PixelShaderSourceInfo obj)
{
hashCode.Add(obj.Hierarchy);
hashCode.Add(obj.HlslShaderMethodSource);
hashCode.AddRange(obj.Diagnostcs);
}
/// <inheritdoc/>
protected override bool AreEqual(D2D1PixelShaderSourceInfo x, D2D1PixelShaderSourceInfo y)
{
return
x.Hierarchy == y.Hierarchy &&
x.HlslShaderMethodSource == y.HlslShaderMethodSource &&
x.Diagnostcs.SequenceEqual(y.Diagnostcs);
}
}
}
+73
ファイルの表示
@@ -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;
/// <summary>
/// A model representing all necessary info for a full generation pass for a D2D1 shader.
/// </summary>
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
/// <param name="DispatchData">The gathered shader dispatch data.</param>
/// <param name="InputTypes">The gathered input types for the shader.</param>
/// <param name="ResourceTextureDescriptions">The gathered resource texture descriptions for the shader.</param>
/// <param name="HlslShaderSource">The processed HLSL source for the shader.</param>
/// <param name="OutputBuffer">The output buffer info for the shader.</param>
/// <param name="InputDescriptions">The gathered input descriptions for the shader.</param>
/// <param name="PixelOptions">The pixel options used by the shader.</param>
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
internal sealed record D2D1ShaderInfo(
HierarchyInfo Hierarchy,
DispatchDataInfo DispatchData,
InputTypesInfo InputTypes,
ResourceTextureDescriptionsInfo ResourceTextureDescriptions,
HlslShaderSourceInfo HlslShaderSource,
OutputBufferInfo OutputBuffer,
InputDescriptionsInfo InputDescriptions,
D2D1PixelOptions PixelOptions,
ImmutableArray<DiagnosticInfo> Diagnostcs)
{
/// <inheritdoc/>
public bool Equals(D2D1ShaderInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="D2D1ShaderInfo"/>.
/// </summary>
private sealed class Comparer : Comparer<D2D1ShaderInfo, Comparer>
{
/// <inheritdoc/>
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);
}
/// <inheritdoc/>
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);
}
}
}
+9 -3
ファイルの表示
@@ -13,15 +13,21 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <param name="ConstantBufferSizeInBytes">The size of the shader constant buffer.</param>
internal sealed record DispatchDataInfo(ImmutableArray<FieldInfo> FieldInfos, int ConstantBufferSizeInBytes)
{
/// <inheritdoc/>
public bool Equals(DispatchDataInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DispatchDataInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<DispatchDataInfo, Comparer>
private sealed class Comparer : Comparer<DispatchDataInfo, Comparer>
{
/// <inheritdoc/>
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<FieldInfo> 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;
}
}
+7 -1
ファイルの表示
@@ -15,10 +15,16 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <param name="Bytecode">The compiled shader bytecode, if available.</param>
internal sealed record EmbeddedBytecodeInfo(string HlslSource, D2D1ShaderProfile? ShaderProfile, D2D1CompileOptions? CompileOptions, ImmutableArray<byte> Bytecode)
{
/// <inheritdoc/>
public bool Equals(EmbeddedBytecodeInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="EmbeddedBytecodeInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<EmbeddedBytecodeInfo, Comparer>
private sealed class Comparer : Comparer<EmbeddedBytecodeInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, EmbeddedBytecodeInfo obj)
+7 -1
ファイルの表示
@@ -23,10 +23,16 @@ internal sealed record EmbeddedBytecodeMethodInfo(
string HlslSource,
ImmutableArray<byte> Bytecode)
{
/// <inheritdoc/>
public bool Equals(EmbeddedBytecodeMethodInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="EmbeddedBytecodeMethodInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<EmbeddedBytecodeMethodInfo, Comparer>
private sealed class Comparer : Comparer<EmbeddedBytecodeMethodInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, EmbeddedBytecodeMethodInfo obj)
+58 -45
ファイルの表示
@@ -17,7 +17,37 @@ internal abstract record FieldInfo
/// <param name="FieldPath">The path of the field with respect to the shader instance.</param>
/// <param name="TypeName">The full metadata name for the primitive type.</param>
/// <param name="Offset">The byte offset of the value within the root signature.</param>
public sealed record Primitive(ImmutableArray<string> FieldPath, string TypeName, int Offset) : FieldInfo;
public sealed record Primitive(ImmutableArray<string> FieldPath, string TypeName, int Offset) : FieldInfo
{
/// <inheritdoc/>
public bool Equals(Primitive? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="Primitive"/>.
/// </summary>
private sealed class Comparer : Comparer<Primitive, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, Primitive obj)
{
hashCode.AddRange(obj.FieldPath);
hashCode.Add(obj.TypeName);
hashCode.Add(obj.Offset);
}
/// <inheritdoc/>
protected override bool AreEqual(Primitive x, Primitive y)
{
return
x.FieldPath.SequenceEqual(y.FieldPath) &&
x.TypeName == y.TypeName &&
x.Offset == y.Offset;
}
}
}
/// <summary>
/// A captured non linear matrix value.
@@ -34,58 +64,41 @@ internal abstract record FieldInfo
string ElementName,
int Rows,
int Columns,
ImmutableArray<int> Offsets) : FieldInfo;
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="FieldInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<FieldInfo, Comparer>
ImmutableArray<int> Offsets) : FieldInfo
{
/// <inheritdoc/>
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);
/// <inheritdoc/>
protected override bool AreEqual(FieldInfo x, FieldInfo y)
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="NonLinearMatrix"/>.
/// </summary>
private sealed class Comparer : Comparer<NonLinearMatrix, Comparer>
{
if (x is Primitive primitiveX && y is Primitive primitiveY)
/// <inheritdoc/>
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;
/// <inheritdoc/>
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);
}
}
}
}
+7 -1
ファイルの表示
@@ -26,10 +26,16 @@ internal sealed record HlslShaderMethodSourceInfo(
D2D1CompileOptions CompileOptions,
bool HasErrors)
{
/// <inheritdoc/>
public bool Equals(HlslShaderMethodSourceInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HlslShaderMethodSourceInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<HlslShaderMethodSourceInfo, Comparer>
private sealed class Comparer : Comparer<HlslShaderMethodSourceInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, HlslShaderMethodSourceInfo obj)
+7 -1
ファイルの表示
@@ -11,10 +11,16 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <param name="InputDescriptions">The input descriptions for a given shader.</param>
internal sealed record InputDescriptionsInfo(ImmutableArray<InputDescription> InputDescriptions)
{
/// <inheritdoc/>
public bool Equals(InputDescriptionsInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="InputDescriptionsInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<InputDescriptionsInfo, Comparer>
private sealed class Comparer : Comparer<InputDescriptionsInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, InputDescriptionsInfo obj)
+7 -1
ファイルの表示
@@ -12,10 +12,16 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <param name="InputTypes">The input types for a given shader.</param>
internal sealed record InputTypesInfo(ImmutableArray<uint> InputTypes)
{
/// <inheritdoc/>
public bool Equals(InputTypesInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="InputTypesInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<InputTypesInfo, Comparer>
private sealed class Comparer : Comparer<InputTypesInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, InputTypesInfo obj)
+7 -1
ファイルの表示
@@ -11,10 +11,16 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <param name="ResourceTextureDescriptions">The resource textures for the current shader.</param>
internal sealed record ResourceTextureDescriptionsInfo(ImmutableArray<ResourceTextureDescription> ResourceTextureDescriptions)
{
/// <inheritdoc/>
public bool Equals(ResourceTextureDescriptionsInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="ResourceTextureDescriptionsInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<ResourceTextureDescriptionsInfo, Comparer>
private sealed class Comparer : Comparer<ResourceTextureDescriptionsInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, ResourceTextureDescriptionsInfo obj)
@@ -12,6 +12,7 @@
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\DiagnosticDescriptors.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\StringExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxNodeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\SyntaxTokenHelper.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Mappings\HlslKnownFields.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Mappings\HlslKnownKeywords.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Mappings\HlslKnownMethods.cs" />
+34
ファイルの表示
@@ -13,6 +13,40 @@ namespace ComputeSharp.SourceGeneration.Extensions;
/// </summary>
internal static class SyntaxNodeExtensions
{
/// <summary>
/// Checks whether a given <see cref="SyntaxNode"/> is a given type declaration with or potentially with any base types, using only syntax.
/// </summary>
/// <typeparam name="T">The type of declaration to check for.</typeparam>
/// <param name="node">The input <see cref="SyntaxNode"/> to check.</param>
/// <returns>Whether <paramref name="node"/> is a given type declaration with or potentially with any base types.</returns>
public static bool IsTypeDeclarationWithOrPotentiallyWithBaseTypes<T>(this SyntaxNode node)
where T : TypeDeclarationSyntax
{
// Immediately bail if the node is not a type declaration of the specified type
if (node is not T typeDeclaration)
{
return false;
}
// If the base types list is not empty, the type can definitely has implemented interfaces
if (typeDeclaration.BaseList is { Types.Count: > 0 })
{
return true;
}
// If the base types list is empty, check if the type is partial. If it is, it means
// that there could be another partial declaration with a non-empty base types list.
foreach (SyntaxToken modifier in typeDeclaration.Modifiers)
{
if (modifier.IsKind(SyntaxKind.PartialKeyword))
{
return true;
}
}
return false;
}
/// <summary>
/// Checks a <see cref="SyntaxNode"/> value and replaces the value type to be HLSL compatible, if needed.
/// </summary>
+35
ファイルの表示
@@ -0,0 +1,35 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGeneration.Helpers;
/// <summary>
/// Helpers to create and work with <see cref="SyntaxToken"/>-s.
/// </summary>
internal static class SyntaxTokenHelper
{
/// <summary>
/// Creates a <see cref="SyntaxToken"/> representing a raw multiline string literal with the given text.
/// </summary>
/// <param name="text">The text to use for the created raw multiline string literal token.</param>
/// <param name="indentationLevel">The current indentation level to use.</param>
/// <returns>A <see cref="SyntaxToken"/> representing a raw multiline string literal with the value of <paramref name="text"/>.</returns>
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());
}
}
+5 -4
ファイルの表示
@@ -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<IFieldSymbol, string> ConstantDefinitions;
/// <summary>
/// The collection of produced <see cref="Diagnostic"/> instances.
/// The collection of produced <see cref="DiagnosticInfo"/> instances.
/// </summary>
protected readonly ImmutableArray<Diagnostic>.Builder Diagnostics;
protected readonly ImmutableArray<DiagnosticInfo>.Builder Diagnostics;
/// <summary>
/// Creates a new <see cref="HlslSourceRewriter"/> instance with the specified parameters.
@@ -52,12 +53,12 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <param name="semanticModel">The <see cref="Microsoft.CodeAnalysis.SemanticModel"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
protected HlslSourceRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArray<Diagnostic>.Builder diagnostics)
ImmutableArray<DiagnosticInfo>.Builder diagnostics)
{
SemanticModel = semanticModel;
DiscoveredTypes = discoveredTypes;
+5 -4
ファイルの表示
@@ -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
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="isEntryPoint">Whether or not the current instance is processing a shader entry point.</param>
public ShaderSourceRewriter(
INamedTypeSymbol shaderType,
@@ -71,7 +72,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
bool isEntryPoint)
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
{
@@ -89,13 +90,13 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
public ShaderSourceRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArray<Diagnostic>.Builder diagnostics)
ImmutableArray<DiagnosticInfo>.Builder diagnostics)
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
{
this.staticMethods = staticMethods;
+3 -2
ファイルの表示
@@ -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
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
public StaticFieldRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArray<Diagnostic>.Builder diagnostics)
ImmutableArray<DiagnosticInfo>.Builder diagnostics)
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
{
}
+1 -2
ファイルの表示
@@ -15,14 +15,13 @@
<Compile Include="$(MSBuildThisFileDirectory)Extensions\HashCodeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IEqualityComparerExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ImmutableArrayExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IncrementalValuesProviderExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\Comparer{T,TSelf}.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\HashCode.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\SemanticModelProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\DeferredDiagnosticInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\DiagnosticInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\HierarchyInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\Result{T}.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\TypeInfo.cs" />
</ItemGroup>
</Project>
+14 -46
ファイルの表示
@@ -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
{
/// <summary>
/// Adds a new diagnostics to the current compilation.
/// Adds a new diagnostics to the target builder.
/// </summary>
/// <param name="context">The <see cref="GeneratorExecutionContext"/> instance currently in use.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
/// <param name="symbol">The source <see cref="ISymbol"/> to attach the diagnostics to.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
public static void ReportDiagnostic(
this GeneratorExecutionContext context,
public static void Add(
this ImmutableArray<DiagnosticInfo>.Builder diagnostics,
DiagnosticDescriptor descriptor,
ISymbol symbol,
params object[] args)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args));
}
/// <summary>
/// Adds a new diagnostics to the current compilation.
/// </summary>
/// <param name="context">The <see cref="GeneratorExecutionContext"/> instance currently in use.</param>
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
/// <param name="node">The source <see cref="SyntaxNode"/> to attach the diagnostics to.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
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));
}
/// <summary>
/// Adds a new diagnostics to the target builder.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
/// <param name="symbol">The source <see cref="ISymbol"/> to attach the diagnostics to.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
public static void Add(
this ImmutableArray<Diagnostic>.Builder diagnostics,
DiagnosticDescriptor descriptor,
ISymbol symbol,
params object[] args)
{
diagnostics.Add(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args));
}
/// <summary>
/// Adds a new diagnostics to the target builder.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
/// <param name="node">The source <see cref="SyntaxNode"/> to attach the diagnostics to.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
public static void Add(
this ImmutableArray<Diagnostic>.Builder diagnostics,
this ImmutableArray<DiagnosticInfo>.Builder diagnostics,
DiagnosticDescriptor descriptor,
SyntaxNode node,
params object[] args)
{
diagnostics.Add(Diagnostic.Create(descriptor, node.GetLocation(), args));
diagnostics.Add(DiagnosticInfo.Create(descriptor, node, args));
}
/// <summary>
@@ -78,11 +46,11 @@ internal static class DiagnosticsExtensions
/// </summary>
/// <param name="context">The input <see cref="IncrementalGeneratorInitializationContext"/> instance.</param>
/// <param name="diagnostics">The input <see cref="IncrementalValuesProvider{TValues}"/> sequence of diagnostics.</param>
public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider<Diagnostic> diagnostics)
public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider<DiagnosticInfo> diagnostics)
{
context.RegisterSourceOutput(diagnostics, static (context, diagnostic) =>
{
context.ReportDiagnostic(diagnostic);
context.ReportDiagnostic(diagnostic.ToDiagnostic());
});
}
@@ -91,13 +59,13 @@ internal static class DiagnosticsExtensions
/// </summary>
/// <param name="context">The input <see cref="IncrementalGeneratorInitializationContext"/> instance.</param>
/// <param name="diagnostics">The input <see cref="IncrementalValuesProvider{TValues}"/> sequence of diagnostics.</param>
public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider<ImmutableArray<Diagnostic>> diagnostics)
public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider<ImmutableArray<DiagnosticInfo>> diagnostics)
{
context.RegisterSourceOutput(diagnostics, static (context, diagnostics) =>
{
foreach (Diagnostic diagnostic in diagnostics)
foreach (DiagnosticInfo diagnostic in diagnostics)
{
context.ReportDiagnostic(diagnostic);
context.ReportDiagnostic(diagnostic.ToDiagnostic());
}
});
}
+1 -1
ファイルの表示
@@ -22,7 +22,7 @@ internal static class IEqualityComparerExtensions
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for an <see cref="ImmutableArray{T}"/> value.
/// </summary>
public sealed class Comparer<T> : IEqualityComparer<ImmutableArray<T>>
private sealed class Comparer<T> : IEqualityComparer<ImmutableArray<T>>
{
/// <summary>
/// The <typeparamref name="T"/> comparer.
+3 -8
ファイルの表示
@@ -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
/// <returns>Whether or not <paramref name="symbol"/> has an attribute with the specified name.</returns>
public static bool HasAttributeWithFullyQualifiedName(this ISymbol symbol, string name)
{
ImmutableArray<AttributeData> 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
/// <returns>Whether or not <paramref name="symbol"/> has an attribute with the specified name.</returns>
public static bool TryGetAttributeWithFullMetadataName(this ISymbol symbol, string name, out AttributeData? attributeData)
{
ImmutableArray<AttributeData> attributes = symbol.GetAttributes();
foreach (AttributeData attribute in attributes)
foreach (AttributeData attribute in symbol.GetAttributes())
{
if (attribute.AttributeClass?.GetFullMetadataName() == name)
{
-323
ファイルの表示
@@ -1,323 +0,0 @@
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGeneration.Extensions;
/// <summary>
/// Extension methods for <see cref="IncrementalValuesProvider{TValues}"/>.
/// </summary>
internal static class IncrementalValuesProviderExtensions
{
/// <summary>
/// Creates a new <see cref="IncrementalValuesProvider{TValues}"/> instance with a gven pair of comparers.
/// </summary>
/// <typeparam name="TLeft">The type of left items in each tuple.</typeparam>
/// <typeparam name="TRight">The type of right items in each tuple.</typeparam>
/// <param name="source">The input <see cref="IncrementalValuesProvider{TValues}"/> instance.</param>
/// <param name="comparerLeft">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="TLeft"/> items.</param>
/// <param name="comparerRight">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="TRight"/> items.</param>
/// <returns>An <see cref="IncrementalValuesProvider{TValues}"/> with the specified comparers applied to each item.</returns>
public static IncrementalValuesProvider<(TLeft Left, TRight Right)> WithComparers<TLeft, TRight>(
this IncrementalValuesProvider<(TLeft Left, TRight Right)> source,
IEqualityComparer<TLeft> comparerLeft,
IEqualityComparer<TRight> comparerRight)
{
return source.WithComparer(new Comparer<TLeft, TRight>(comparerLeft, comparerRight));
}
/// <summary>
/// Creates a new <see cref="IncrementalValuesProvider{TValues}"/> instance with a gven pair of comparers.
/// </summary>
/// <typeparam name="T1">The type of first items in each tuple.</typeparam>
/// <typeparam name="T2">The type of second items in each tuple.</typeparam>
/// <typeparam name="T3">The type of third items in each tuple.</typeparam>
/// <param name="source">The input <see cref="IncrementalValuesProvider{TValues}"/> instance.</param>
/// <param name="comparer1">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T1"/> items.</param>
/// <param name="comparer2">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T2"/> items.</param>
/// <param name="comparer3">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T3"/> items.</param>
/// <returns>An <see cref="IncrementalValuesProvider{TValues}"/> with the specified comparers applied to each item.</returns>
public static IncrementalValuesProvider<(T1, T2, T3)> WithComparers<T1, T2, T3>(
this IncrementalValuesProvider<(T1, T2, T3)> source,
IEqualityComparer<T1> comparer1,
IEqualityComparer<T2> comparer2,
IEqualityComparer<T3> comparer3)
{
return source.WithComparer(new Comparer<T1, T2, T3>(comparer1, comparer2, comparer3));
}
/// <summary>
/// Creates a new <see cref="IncrementalValuesProvider{TValues}"/> instance with a gven pair of comparers.
/// </summary>
/// <typeparam name="T1">The type of first items in each tuple.</typeparam>
/// <typeparam name="T2">The type of second items in each tuple.</typeparam>
/// <typeparam name="T3">The type of third items in each tuple.</typeparam>
/// <typeparam name="T4">The type of fourth items in each tuple.</typeparam>
/// <param name="source">The input <see cref="IncrementalValuesProvider{TValues}"/> instance.</param>
/// <param name="comparer1">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T1"/> items.</param>
/// <param name="comparer2">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T2"/> items.</param>
/// <param name="comparer3">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T3"/> items.</param>
/// <param name="comparer4">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T4"/> items.</param>
/// <returns>An <see cref="IncrementalValuesProvider{TValues}"/> with the specified comparers applied to each item.</returns>
public static IncrementalValuesProvider<(T1, T2, T3, T4)> WithComparers<T1, T2, T3, T4>(
this IncrementalValuesProvider<(T1, T2, T3, T4)> source,
IEqualityComparer<T1> comparer1,
IEqualityComparer<T2> comparer2,
IEqualityComparer<T3> comparer3,
IEqualityComparer<T4> comparer4)
{
return source.WithComparer(new Comparer<T1, T2, T3, T4>(comparer1, comparer2, comparer3, comparer4));
}
/// <summary>
/// Creates a new <see cref="IncrementalValuesProvider{TValues}"/> instance with a gven pair of comparers.
/// </summary>
/// <typeparam name="T1">The type of first items in each tuple.</typeparam>
/// <typeparam name="T2">The type of second items in each tuple.</typeparam>
/// <typeparam name="T3">The type of third items in each tuple.</typeparam>
/// <typeparam name="T4">The type of fourth items in each tuple.</typeparam>
/// <typeparam name="T5">The type of fourth items in each tuple.</typeparam>
/// <param name="source">The input <see cref="IncrementalValuesProvider{TValues}"/> instance.</param>
/// <param name="comparer1">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T1"/> items.</param>
/// <param name="comparer2">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T2"/> items.</param>
/// <param name="comparer3">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T3"/> items.</param>
/// <param name="comparer4">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T4"/> items.</param>
/// <param name="comparer5">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T5"/> items.</param>
/// <returns>An <see cref="IncrementalValuesProvider{TValues}"/> with the specified comparers applied to each item.</returns>
public static IncrementalValuesProvider<(T1, T2, T3, T4, T5)> WithComparers<T1, T2, T3, T4, T5>(
this IncrementalValuesProvider<(T1, T2, T3, T4, T5)> source,
IEqualityComparer<T1> comparer1,
IEqualityComparer<T2> comparer2,
IEqualityComparer<T3> comparer3,
IEqualityComparer<T4> comparer4,
IEqualityComparer<T5> comparer5)
{
return source.WithComparer(new Comparer<T1, T2, T3, T4, T5>(comparer1, comparer2, comparer3, comparer4, comparer5));
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for a value tuple.
/// </summary>
public sealed class Comparer<TLeft, TRight> : IEqualityComparer<(TLeft Left, TRight Right)>
{
/// <summary>
/// The <typeparamref name="TLeft"/> comparer.
/// </summary>
private readonly IEqualityComparer<TLeft> comparerLeft;
/// <summary>
/// The <typeparamref name="TRight"/> comparer.
/// </summary>
private readonly IEqualityComparer<TRight> comparerRight;
/// <summary>
/// Creates a new <see cref="Comparer{TLeft, TRight}"/> instance with the specified parameters.
/// </summary>
/// <param name="comparerLeft">The <typeparamref name="TLeft"/> comparer.</param>
/// <param name="comparerRight">The <typeparamref name="TRight"/> comparer.</param>
public Comparer(IEqualityComparer<TLeft> comparerLeft, IEqualityComparer<TRight> comparerRight)
{
this.comparerLeft = comparerLeft;
this.comparerRight = comparerRight;
}
/// <inheritdoc/>
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);
}
/// <inheritdoc/>
public int GetHashCode((TLeft Left, TRight Right) obj)
{
return HashCode.Combine(
this.comparerLeft.GetHashCode(obj.Left),
this.comparerRight.GetHashCode(obj.Right));
}
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for a value tuple.
/// </summary>
public sealed class Comparer<T1, T2, T3> : IEqualityComparer<(T1, T2, T3)>
{
/// <summary>
/// The <typeparamref name="T1"/> comparer.
/// </summary>
private readonly IEqualityComparer<T1> comparer1;
/// <summary>
/// The <typeparamref name="T2"/> comparer.
/// </summary>
private readonly IEqualityComparer<T2> comparer2;
/// <summary>
/// The <typeparamref name="T3"/> comparer.
/// </summary>
private readonly IEqualityComparer<T3> comparer3;
/// <summary>
/// Creates a new <see cref="Comparer{T1, T2, T3}"/> instance with the specified parameters.
/// </summary>
/// <param name="comparer1">The <typeparamref name="T1"/> comparer.</param>
/// <param name="comparer2">The <typeparamref name="T2"/> comparer.</param>
/// <param name="comparer3">The <typeparamref name="T3"/> comparer.</param>
public Comparer(IEqualityComparer<T1> comparer1, IEqualityComparer<T2> comparer2, IEqualityComparer<T3> comparer3)
{
this.comparer1 = comparer1;
this.comparer2 = comparer2;
this.comparer3 = comparer3;
}
/// <inheritdoc/>
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);
}
/// <inheritdoc/>
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));
}
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for a value tuple.
/// </summary>
public sealed class Comparer<T1, T2, T3, T4> : IEqualityComparer<(T1, T2, T3, T4)>
{
/// <summary>
/// The <typeparamref name="T1"/> comparer.
/// </summary>
private readonly IEqualityComparer<T1> comparer1;
/// <summary>
/// The <typeparamref name="T2"/> comparer.
/// </summary>
private readonly IEqualityComparer<T2> comparer2;
/// <summary>
/// The <typeparamref name="T3"/> comparer.
/// </summary>
private readonly IEqualityComparer<T3> comparer3;
/// <summary>
/// The <typeparamref name="T4"/> comparer.
/// </summary>
private readonly IEqualityComparer<T4> comparer4;
/// <summary>
/// Creates a new <see cref="Comparer{T1, T2, T3, T4}"/> instance with the specified parameters.
/// </summary>
/// <param name="comparer1">The <typeparamref name="T1"/> comparer.</param>
/// <param name="comparer2">The <typeparamref name="T2"/> comparer.</param>
/// <param name="comparer3">The <typeparamref name="T3"/> comparer.</param>
/// <param name="comparer4">The <typeparamref name="T4"/> comparer.</param>
public Comparer(IEqualityComparer<T1> comparer1, IEqualityComparer<T2> comparer2, IEqualityComparer<T3> comparer3, IEqualityComparer<T4> comparer4)
{
this.comparer1 = comparer1;
this.comparer2 = comparer2;
this.comparer3 = comparer3;
this.comparer4 = comparer4;
}
/// <inheritdoc/>
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);
}
/// <inheritdoc/>
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));
}
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for a value tuple.
/// </summary>
public sealed class Comparer<T1, T2, T3, T4, T5> : IEqualityComparer<(T1, T2, T3, T4, T5)>
{
/// <summary>
/// The <typeparamref name="T1"/> comparer.
/// </summary>
private readonly IEqualityComparer<T1> comparer1;
/// <summary>
/// The <typeparamref name="T2"/> comparer.
/// </summary>
private readonly IEqualityComparer<T2> comparer2;
/// <summary>
/// The <typeparamref name="T3"/> comparer.
/// </summary>
private readonly IEqualityComparer<T3> comparer3;
/// <summary>
/// The <typeparamref name="T4"/> comparer.
/// </summary>
private readonly IEqualityComparer<T4> comparer4;
/// <summary>
/// The <typeparamref name="T5"/> comparer.
/// </summary>
private readonly IEqualityComparer<T5> comparer5;
/// <summary>
/// Creates a new <see cref="Comparer{T1, T2, T3, T4, T5}"/> instance with the specified parameters.
/// </summary>
/// <param name="comparer1">The <typeparamref name="T1"/> comparer.</param>
/// <param name="comparer2">The <typeparamref name="T2"/> comparer.</param>
/// <param name="comparer3">The <typeparamref name="T3"/> comparer.</param>
/// <param name="comparer4">The <typeparamref name="T4"/> comparer.</param>
/// <param name="comparer5">The <typeparamref name="T5"/> comparer.</param>
public Comparer(IEqualityComparer<T1> comparer1, IEqualityComparer<T2> comparer2, IEqualityComparer<T3> comparer3, IEqualityComparer<T4> comparer4, IEqualityComparer<T5> comparer5)
{
this.comparer1 = comparer1;
this.comparer2 = comparer2;
this.comparer3 = comparer3;
this.comparer4 = comparer4;
this.comparer5 = comparer5;
}
/// <inheritdoc/>
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);
}
/// <inheritdoc/>
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));
}
}
}
+55
ファイルの表示
@@ -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;
/// <summary>
/// A model for a serializeable diagnostic info to be reconstructed later in a pipeline.
/// </summary>
/// <param name="Descriptor">The wrapped <see cref="DiagnosticDescriptor"/> instance.</param>
/// <param name="Arguments">The diagnostic arguments.</param>
internal sealed record DeferredDiagnosticInfo(DiagnosticDescriptor Descriptor, ImmutableArray<string> Arguments)
{
/// <inheritdoc/>
public bool Equals(DeferredDiagnosticInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// Creates a new <see cref="DeferredDiagnosticInfo"/> instance with the specified parameters.
/// </summary>
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
/// <returns>A new <see cref="DeferredDiagnosticInfo"/> instance with the specified parameters.</returns>
public static DeferredDiagnosticInfo Create(DiagnosticDescriptor descriptor, params object[] args)
{
return new(descriptor, args.Select(static arg => arg.ToString()).ToImmutableArray());
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DeferredDiagnosticInfo"/>.
/// </summary>
private sealed class Comparer : Comparer<DeferredDiagnosticInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, DeferredDiagnosticInfo obj)
{
hashCode.Add(obj.Descriptor);
hashCode.AddRange(obj.Arguments);
}
/// <inheritdoc/>
protected override bool AreEqual(DeferredDiagnosticInfo x, DeferredDiagnosticInfo y)
{
return
x.Descriptor.Equals(y.Descriptor) &&
x.Arguments.SequenceEqual(y.Arguments);
}
}
}
+67 -10
ファイルの表示
@@ -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;
/// <summary>
/// A model for a serializeable diagnostic provider.
/// A model for a serializeable diagnostic info.
/// </summary>
/// <param name="Descriptor">The wrapped <see cref="DiagnosticDescriptor"/> instance.</param>
/// <param name="Args">The diagnostic args.</param>
internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, params object[] Args)
/// <param name="SyntaxTree">The tree to use as location for the diagnostic, if available.</param>
/// <param name="TextSpan">The span to use as location for the diagnostic.</param>
/// <param name="Arguments">The diagnostic arguments.</param>
internal sealed record DiagnosticInfo(
DiagnosticDescriptor Descriptor,
SyntaxTree? SyntaxTree,
TextSpan TextSpan,
ImmutableArray<string> Arguments)
{
/// <inheritdoc/>
public bool Equals(DiagnosticInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// Creates a new <see cref="Diagnostic"/> instance with the state from this model.
/// </summary>
/// <returns>A new <see cref="Diagnostic"/> instance with the state from this model.</returns>
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());
}
/// <summary>
/// Creates a new <see cref="DiagnosticInfo"/> instance with the specified parameters.
/// </summary>
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
/// <param name="symbol">The source <see cref="ISymbol"/> to attach the diagnostics to.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
/// <returns>A new <see cref="DiagnosticInfo"/> instance with the specified parameters.</returns>
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());
}
/// <summary>
/// Creates a new <see cref="DiagnosticInfo"/> instance with the specified parameters.
/// </summary>
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
/// <param name="node">The source <see cref="SyntaxNode"/> to attach the diagnostics to.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
/// <returns>A new <see cref="DiagnosticInfo"/> instance with the specified parameters.</returns>
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());
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DiagnosticInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<DiagnosticInfo, Comparer>
private sealed class Comparer : Comparer<DiagnosticInfo, Comparer>
{
/// <inheritdoc/>
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);
}
/// <inheritdoc/>
@@ -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);
}
}
}
+7 -1
ファイルの表示
@@ -111,10 +111,16 @@ internal sealed partial record HierarchyInfo(string FilenameHint, string FullyQu
.NormalizeWhitespace(eol: "\n");
}
/// <inheritdoc/>
public bool Equals(HierarchyInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HierarchyInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<HierarchyInfo, Comparer>
private sealed class Comparer : Comparer<HierarchyInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, HierarchyInfo obj)
-12
ファイルの表示
@@ -1,12 +0,0 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGeneration.Models;
/// <summary>
/// A model representing a value and an associated set of diagnostic errors.
/// </summary>
/// <typeparam name="TValue">The type of the wrapped value.</typeparam>
/// <param name="Value">The wrapped value for the current result.</param>
/// <param name="Errors">The associated diagnostic errors, if any.</param>
internal sealed record Result<TValue>(TValue Value, ImmutableArray<Diagnostic> Errors);
+2 -2
ファイルの表示
@@ -605,13 +605,13 @@ partial class DiagnosticDescriptors
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an embedded bytecode shader with invalid thread ids values.
/// <para>
/// Format: <c>"The shader of type {0} is annotated with invalid thread ids values ({1}, {2}, {3})"</c>.
/// Format: <c>"The shader of type {0} is annotated with invalid thread ids values"</c>.
/// </para>
/// </summary>
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,
+7 -26
ファイルの表示
@@ -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
/// <param name="hlslSourceInfo">The input <see cref="HlslShaderSourceInfo"/> instance to use.</param>
/// <param name="supportsDynamicShaders">Indicates whether or not dynamic shaders are supported.</param>
/// <param name="hierarchyDepth">The depth of the hierarchy for this type (used to calculate the right indentation).</param>
/// <param name="useRawMultiLineStringLiteralExpression">Whether to use a raw multiline string literal expression</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslSource</c> method.</returns>
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<StatementSyntax> 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
/// </summary>
/// <param name="hlslSourceInfo">The input <see cref="HlslShaderSourceInfo"/> instance to use.</param>
/// <param name="hierarchyDepth">The depth of the hierarchy for this type (used to calculate the right indentation).</param>
/// <param name="useRawMultiLineStringLiteralExpression">Whether to use a raw multiline string literal expression</param>
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
private static ImmutableArray<StatementSyntax> GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth, bool useRawMultiLineStringLiteralExpression)
private static ImmutableArray<StatementSyntax> GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth)
{
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
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();
}
+23 -26
ファイルの表示
@@ -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
/// <summary>
/// Gathers all necessary information on a transpiled HLSL source for a given shader type.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
/// <returns>The resulting info on the processed shader.</returns>
public static HlslShaderSourceInfo GetInfo(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
Compilation compilation,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
out ImmutableArray<Diagnostic> diagnostics)
INamedTypeSymbol structDeclarationSymbol)
{
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
// Detect invalid properties
DetectAndReportInvalidPropertyDeclarations(builder, structDeclarationSymbol);
DetectAndReportInvalidPropertyDeclarations(diagnostics, structDeclarationSymbol);
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> 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<byte>) }) > 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<byte>) });
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
/// <summary>
/// Gets a sequence of captured fields and their mapped names.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="types">The collection of currently discovered types.</param>
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
@@ -103,7 +100,7 @@ partial class IShaderGenerator
ImmutableArray<(string MetadataName, string Name, string HlslType)>,
ImmutableArray<(string Name, string HlslType)>)
GetInstanceFields(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> types,
bool isComputeShader)
@@ -186,7 +183,7 @@ partial class IShaderGenerator
/// <summary>
/// Gets a sequence of shader static fields and their mapped names.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the current type.</param>
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
@@ -194,7 +191,7 @@ partial class IShaderGenerator
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of static constant fields in <paramref name="structDeclarationSymbol"/>.</returns>
private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
SemanticModelProvider semanticModel,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
@@ -256,12 +253,12 @@ partial class IShaderGenerator
/// <summary>
/// Gets a sequence of captured members and their mapped names.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="types">The collection of currently discovered types.</param>
/// <returns>A sequence of captured members in <paramref name="structDeclarationSymbol"/>.</returns>
private static ImmutableArray<(string Name, string Type, int? Count)> GetSharedBuffers(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> types)
{
@@ -312,7 +309,7 @@ partial class IShaderGenerator
/// <summary>
/// Gets a sequence of processed methods declared within a given type.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the current type.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
@@ -322,7 +319,7 @@ partial class IShaderGenerator
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods, bool IsSamplerUser) GetProcessedMethods(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
SemanticModelProvider semanticModel,
@@ -441,10 +438,10 @@ partial class IShaderGenerator
/// </summary>
/// <param name="types">The sequence of discovered custom types.</param>
/// <param name="sourceSymbol">The symbol for the current object being processed.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ISymbol sourceSymbol,
IEnumerable<INamedTypeSymbol> types)
{
@@ -503,9 +500,9 @@ partial class IShaderGenerator
/// <summary>
/// Finds and reports all invalid declared properties in a shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArray<Diagnostic>.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol)
private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArray<DiagnosticInfo>.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol)
{
foreach (var memberSymbol in structDeclarationSymbol.GetMembers())
{
+11 -12
ファイルの表示
@@ -18,10 +18,9 @@ partial class IShaderGenerator
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.
/// </summary>
/// <param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>\
/// <param name="supportsDynamicShaders">Indicates whether or not dynamic shaders are supported.</param>
/// <param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(ImmutableArray<string> delegateFieldNames, bool supportsDynamicShaders)
public static MethodDeclarationSyntax GetSyntax(ImmutableArray<string> 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));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to compute the hashcode of a given shader type.
/// </summary>
/// <param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>
/// <param name="supportsDynamicShaders">Indicates whether or not dynamic shaders are supported.</param>
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
private static BlockSyntax GetShaderHashCodeBody(ImmutableArray<string> delegateFieldNames, bool supportsDynamicShaders)
private static BlockSyntax GetShaderHashCodeBody(ImmutableArray<string> delegateFieldNames)
{
if (delegateFieldNames.Length == 0 || !supportsDynamicShaders)
if (delegateFieldNames.Length == 0)
{
// return 0;
return
@@ -56,17 +54,18 @@ partial class IShaderGenerator
Literal(0))));
}
List<StatementSyntax> blockStatements = new(4);
// global::System.HashCode hashCode = default;
blockStatements.Add(LocalDeclarationStatement(
List<StatementSyntax> 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)
{
+19 -28
ファイルの表示
@@ -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
/// <summary>
/// Gets the thread ids values for a given shader type, if available.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="isDynamicShader">Indicates whether or not the shader is dynamic (ie. captures delegates).</param>
/// <param name="supportsDynamicShaders">Indicates whether or not dynamic shaders are supported.</param>
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
/// <returns>The thread ids for the precompiled shader, if available.</returns>
public static ThreadIdsInfo GetInfo(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
bool isDynamicShader,
bool supportsDynamicShaders,
out ImmutableArray<Diagnostic> diagnostics)
bool supportsDynamicShaders)
{
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
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<byte> bytecode = ImmutableArray<byte>.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:
@@ -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
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
/// </summary>
/// <param name="shaderInterfaceType">The type of shader interface urrently being processed.</param>
/// <param name="shaderType">The type of shader interface currently being processed.</param>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
/// <param name="root32BitConstantsCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(
Type shaderInterfaceType,
ShaderType shaderType,
ImmutableArray<FieldInfo> 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)));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch data for a given shader.
/// </summary>
/// <param name="shaderInterfaceType">The type of shader interface urrently being processed.</param>
/// <param name="shaderType">The type of shader interface currently being processed.</param>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
/// <param name="root32BitConstantsCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static ImmutableArray<StatementSyntax> GetDispatchDataLoadingStatements(
Type shaderInterfaceType,
ShaderType shaderType,
ImmutableArray<FieldInfo> fieldInfos,
int resourceCount,
int root32BitConstantsCount)
{
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
bool isComputeShader = shaderInterfaceType == typeof(IComputeShader);
bool isComputeShader = shaderType == ShaderType.ComputeShader;
// Append the statements for the dispatch ranges:
//
+8 -11
ファイルの表示
@@ -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
/// <summary>
/// Explores a given type hierarchy and generates statements to load fields.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
/// <param name="shaderInterfaceType">The type of shader interface urrently being processed.</param>
/// <param name="shaderType">The type of shader currently being processed.</param>
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
/// <param name="root32BitConstantCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
/// <returns>The sequence of <see cref="FieldInfo"/> instances for all captured resources and values.</returns>
public static ImmutableArray<FieldInfo> GetInfo(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ITypeSymbol structDeclarationSymbol,
Type shaderInterfaceType,
ShaderType shaderType,
out int resourceCount,
out int root32BitConstantCount,
out ImmutableArray<Diagnostic> diagnostics)
out int root32BitConstantCount)
{
// Helper method that uses boxes instead of ref-s (illegal in enumerators)
static IEnumerable<FieldInfo> GetCapturedFieldInfos(
@@ -87,11 +88,9 @@ partial class IShaderGenerator
}
}
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
// 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<int> resourceOffsetAsBox = new();
StrongBox<int> 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;
}
+30 -17
ファイルの表示
@@ -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.
/// </summary>
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance to check.</param>
/// <param name="iComputeShaderSymbol">The <see cref="INamedTypeSymbol"/> instance for <see cref="IComputeShader"/>.</param>
/// <param name="iPixelShaderSymbol">The <see cref="INamedTypeSymbol"/> instance for <see cref="IPixelShader{TPixel}"/>.</param>
/// <returns>Either <see cref="IComputeShader"/> or <see cref="IPixelShader{TPixel}"/>, or <see langword="null"/>.</returns>
private static Type? GetShaderType(
INamedTypeSymbol typeSymbol,
INamedTypeSymbol iComputeShaderSymbol,
INamedTypeSymbol iPixelShaderSymbol)
/// <param name="compilation">The <see cref="Compilation"/> instance currently in use.</param>
/// <returns>The shader type for <paramref name="typeSymbol"/>, or <see langword="null"/>.</returns>
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<byte>) &&
SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, iPixelShaderSymbol))
if (SymbolEqualityComparer.Default.Equals(interfaceSymbol, computeShaderSymbol))
{
return ShaderType.ComputeShader;
}
}
else if (interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) })
{
return typeof(IPixelShader<>);
INamedTypeSymbol pixelShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IPixelShader`1")!;
if (SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, pixelShaderSymbol))
{
return ShaderType.PixelShader;
}
}
}
return null;
}
/// <summary>
/// Checks whether dynamic shaders are supported in a given compilation.
/// </summary>
/// <param name="compilation">The <see cref="Compilation"/> instance currently in use.</param>
/// <returns>Whether dynamic shaders are supported in the input compilation.</returns>
private static bool IsDynamicCompilationSupported(Compilation compilation)
{
return compilation.ReferencedAssemblyNames.Any(static identity => identity.Name is "ComputeSharp.Dynamic");
}
/// <summary>
/// Creates a <see cref="CompilationUnitSyntax"/> instance wrapping the given method.
/// </summary>
+136 -167
ファイルの表示
@@ -25,203 +25,175 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
// Check whether [SkipLocalsInit] can be used
IncrementalValueProvider<bool> 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<bool> 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<ShaderInfo> 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<StructDeclarationSyntax>(),
static (context, token) =>
{
StructDeclarationSyntax typeDeclaration = (StructDeclarationSyntax)context.Node;
// Get the symbol for the IComputeShader and IPixelShader<TPixel> 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<DiagnosticInfo>.Builder diagnostics = ImmutableArray.CreateBuilder<DiagnosticInfo>();
// GetDispatchId() info
ImmutableArray<string> dispatchIdInfo = GetDispatchId.GetInfo(typeSymbol);
token.ThrowIfCancellationRequested();
// LoadDispatchData() info
ImmutableArray<FieldInfo> 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<DiagnosticInfo>.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<DispatchDataInfo> Dispatch, Result<HlslShaderSourceInfo> Hlsl, Result<ThreadIdsInfo> ThreadIds)> shaderInfoWithErrors =
shaderDeclarations
.Combine(supportsDynamicShaders)
.Combine(context.CompilationProvider)
.Select(static (item, token) =>
{
// LoadDispatchData() info
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
item.Left.Left.Symbol,
item.Left.Left.Type,
out int resourceCount,
out int root32BitConstantCount,
out ImmutableArray<Diagnostic> 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<Diagnostic> hlslSourceDiagnostics);
token.ThrowIfCancellationRequested();
// TryGetBytecode() info
ThreadIdsInfo threadIds = LoadBytecode.GetInfo(
item.Left.Left.Symbol,
!hlslSourceInfo.Delegates.IsEmpty,
item.Left.Right,
out ImmutableArray<Diagnostic> 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>(dispatchDataInfo, dispatchDataDiagnostics),
new Result<HlslShaderSourceInfo>(hlslSourceInfo, hlslSourceDiagnostics),
new Result<ThreadIdsInfo>(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<ThreadIdsInfo>.Default);
// Get a filtered sequence to enable caching
IncrementalValuesProvider<DispatchDataInfo> 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<bool>.Default);
// Check whether raw multiline string literals can be used (C# preview)
IncrementalValueProvider<bool> 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<string>.Default, EqualityComparer<ThreadIdsInfo>.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<byte> bytecode = LoadBytecode.GetBytecode(item.ThreadIds, item.Hlsl, token, out DiagnosticInfo? diagnostic);
ImmutableArray<byte> 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<Diagnostic> embeddedBytecodeDiagnostics =
IncrementalValuesProvider<DiagnosticInfo> 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<SyntaxNode, SourceText> fixup);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, tryGetBytecodeMethod, canUseSkipLocalsInit: false);
MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.Info.EmbeddedBytecode, item.SupportsDynamicShaders, out Func<SyntaxNode, SourceText> 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);
});
}
}
+10 -9
ファイルの表示
@@ -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;
/// <summary>
/// A model representing gathered info on a shader dispatch data.
/// </summary>
/// <param name="Hierarchy">The hierarchy data for the shader.</param>
/// <param name="Type">The shader interface type.</param>
/// <param name="FieldInfos">The description on shader instance fields.</param>
/// <param name="ResourceCount">The total number of captured resources.</param>
/// <param name="Root32BitConstantCount">The size of the shader root signature, in 32 bit constants.</param>
internal sealed record DispatchDataInfo(
HierarchyInfo Hierarchy,
Type Type,
ShaderType Type,
ImmutableArray<FieldInfo> FieldInfos,
int ResourceCount,
int Root32BitConstantCount)
{
/// <inheritdoc/>
public bool Equals(DispatchDataInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DispatchDataInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<DispatchDataInfo, Comparer>
private sealed class Comparer : Comparer<DispatchDataInfo, Comparer>
{
/// <inheritdoc/>
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;
}
+7 -1
ファイルの表示
@@ -12,10 +12,16 @@ namespace ComputeSharp.SourceGenerators.Models;
/// <param name="Delegates">The list of delegate field names for the shader.</param>
internal sealed record DispatchIdInfo(ImmutableArray<string> Delegates)
{
/// <inheritdoc/>
public bool Equals(DispatchIdInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DispatchIdInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<DispatchIdInfo, Comparer>
private sealed class Comparer : Comparer<DispatchIdInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, DispatchIdInfo obj)
+7 -1
ファイルの表示
@@ -17,10 +17,16 @@ internal sealed record DispatchMetadataInfo(
bool IsSamplerUsed,
ImmutableArray<ResourceDescriptor> ResourceDescriptors)
{
/// <inheritdoc/>
public bool Equals(DispatchMetadataInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DispatchMetadataInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<DispatchMetadataInfo, Comparer>
private sealed class Comparer : Comparer<DispatchMetadataInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, DispatchMetadataInfo obj)
+7 -1
ファイルの表示
@@ -15,10 +15,16 @@ namespace ComputeSharp.SourceGenerators.Models;
/// <param name="Bytecode">The compiled shader bytecode, if available.</param>
internal sealed record EmbeddedBytecodeInfo(int X, int Y, int Z, ImmutableArray<byte> Bytecode)
{
/// <inheritdoc/>
public bool Equals(EmbeddedBytecodeInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="EmbeddedBytecodeInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<EmbeddedBytecodeInfo, Comparer>
private sealed class Comparer : Comparer<EmbeddedBytecodeInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, EmbeddedBytecodeInfo obj)
+89 -58
ファイルの表示
@@ -17,7 +17,37 @@ internal abstract record FieldInfo
/// <param name="FieldName">The name of the resource field.</param>
/// <param name="TypeName">The full metadata name for the resource type.</param>
/// <param name="Offset">The offset for the resource within the root signature.</param>
public sealed record Resource(string FieldName, string TypeName, int Offset) : FieldInfo;
public sealed record Resource(string FieldName, string TypeName, int Offset) : FieldInfo
{
/// <inheritdoc/>
public bool Equals(Resource? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="Resource"/>.
/// </summary>
private sealed class Comparer : Comparer<Resource, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, Resource obj)
{
hashCode.Add(obj.FieldName);
hashCode.Add(obj.TypeName);
hashCode.Add(obj.Offset);
}
/// <inheritdoc/>
protected override bool AreEqual(Resource x, Resource y)
{
return
x.FieldName == y.FieldName &&
x.TypeName == y.TypeName &&
x.Offset == y.Offset;
}
}
}
/// <summary>
/// A captured primitive value (either a scalar, a vector, or a linear matrix).
@@ -25,7 +55,37 @@ internal abstract record FieldInfo
/// <param name="FieldPath">The path of the field with respect to the shader instance.</param>
/// <param name="TypeName">The full metadata name for the primitive type.</param>
/// <param name="Offset">The byte offset of the value within the root signature.</param>
public sealed record Primitive(ImmutableArray<string> FieldPath, string TypeName, int Offset) : FieldInfo;
public sealed record Primitive(ImmutableArray<string> FieldPath, string TypeName, int Offset) : FieldInfo
{
/// <inheritdoc/>
public bool Equals(Primitive? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="Primitive"/>.
/// </summary>
private sealed class Comparer : Comparer<Primitive, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, Primitive obj)
{
hashCode.AddRange(obj.FieldPath);
hashCode.Add(obj.TypeName);
hashCode.Add(obj.Offset);
}
/// <inheritdoc/>
protected override bool AreEqual(Primitive x, Primitive y)
{
return
x.FieldPath.SequenceEqual(y.FieldPath) &&
x.TypeName == y.TypeName &&
x.Offset == y.Offset;
}
}
}
/// <summary>
/// A captured non linear matrix value.
@@ -42,70 +102,41 @@ internal abstract record FieldInfo
string ElementName,
int Rows,
int Columns,
ImmutableArray<int> Offsets) : FieldInfo;
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="FieldInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<FieldInfo, Comparer>
ImmutableArray<int> Offsets) : FieldInfo
{
/// <inheritdoc/>
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);
/// <inheritdoc/>
protected override bool AreEqual(FieldInfo x, FieldInfo y)
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="NonLinearMatrix"/>.
/// </summary>
private sealed class Comparer : Comparer<NonLinearMatrix, Comparer>
{
if (x is Resource resourceX && y is Resource resourceY)
/// <inheritdoc/>
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;
/// <inheritdoc/>
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);
}
}
}
}
+7 -1
ファイルの表示
@@ -21,10 +21,16 @@ internal sealed record HlslMethodSourceInfo(
ImmutableArray<(string Name, string Value)> DefinedConstants,
ImmutableArray<(string Signature, string Definition)> DependentMethods)
{
/// <inheritdoc/>
public bool Equals(HlslMethodSourceInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HlslMethodSourceInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<HlslMethodSourceInfo, Comparer>
private sealed class Comparer : Comparer<HlslMethodSourceInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, HlslMethodSourceInfo obj)
+7 -1
ファイルの表示
@@ -39,10 +39,16 @@ internal sealed record HlslShaderSourceInfo(
ImmutableArray<string> MethodSignatures,
ImmutableArray<string> Delegates)
{
/// <inheritdoc/>
public bool Equals(HlslShaderSourceInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HlslShaderSourceInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<HlslShaderSourceInfo, Comparer>
private sealed class Comparer : Comparer<HlslShaderSourceInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, HlslShaderSourceInfo obj)
+65
ファイルの表示
@@ -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;
/// <summary>
/// A model representing all necessary info for a full generation pass for a shader.
/// </summary>
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
/// <param name="DispatchId">The gathered dispatch id for the shader type.</param>
/// <param name="DispatchData">The gathered shader dispatch data.</param>
/// <param name="DispatchMetadata">The gathered shader dispatch metadata.</param>
/// <param name="HlslShaderSource">The processed HLSL source for the shader.</param>
/// <param name="ThreadIds">The thread ids for the shader, if compilation is requested.</param>
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
internal sealed record ShaderInfo(
HierarchyInfo Hierarchy,
DispatchIdInfo DispatchId,
DispatchDataInfo DispatchData,
DispatchMetadataInfo DispatchMetadata,
HlslShaderSourceInfo HlslShaderSource,
ThreadIdsInfo ThreadIds,
ImmutableArray<DiagnosticInfo> Diagnostcs)
{
/// <inheritdoc/>
public bool Equals(ShaderInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="ShaderInfo"/>.
/// </summary>
private sealed class Comparer : Comparer<ShaderInfo, Comparer>
{
/// <inheritdoc/>
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);
}
/// <inheritdoc/>
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);
}
}
}
+43
ファイルの表示
@@ -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;
/// <summary>
/// A model representing all necessary info for a full generation pass for a shader method.
/// </summary>
/// <param name="HlslMethodSource">The processed HLSL source for the shader method.</param>
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
internal sealed record ShaderMethodInfo(HlslMethodSourceInfo HlslMethodSource, ImmutableArray<DiagnosticInfo> Diagnostcs)
{
/// <inheritdoc/>
public bool Equals(ShaderMethodInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="ShaderMethodInfo"/>.
/// </summary>
private sealed class Comparer : Comparer<ShaderMethodInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, ShaderMethodInfo obj)
{
hashCode.Add(obj.HlslMethodSource);
hashCode.AddRange(obj.Diagnostcs);
}
/// <inheritdoc/>
protected override bool AreEqual(ShaderMethodInfo x, ShaderMethodInfo y)
{
return
x.HlslMethodSource == y.HlslMethodSource &&
x.Diagnostcs.SequenceEqual(y.Diagnostcs);
}
}
}
+17
ファイルの表示
@@ -0,0 +1,17 @@
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// Indicates a type of shader being processed.
/// </summary>
public enum ShaderType
{
/// <summary>
/// A compute shader.
/// </summary>
ComputeShader,
/// <summary>
/// A pixel shader.
/// </summary>
PixelShader
}
+24 -33
ファイルの表示
@@ -28,43 +28,34 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
/// <inheritdoc/>
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<ShaderMethodInfo> 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<DiagnosticInfo> diagnostics);
// Get the source info for each method
IncrementalValuesProvider<Result<HlslMethodSourceInfo>> methodSourceInfoWithErrors =
methodDeclarationsAndSymbols
.Combine(context.CompilationProvider)
.Select(static (item, token) =>
{
HlslMethodSourceInfo sourceInfo = Execute.GetData(
item.Right,
item.Left.Syntax,
item.Left.Symbol,
out ImmutableArray<Diagnostic> diagnostics);
return new ShaderMethodInfo(hlslMethodSourceInfo, diagnostics);
});
return new Result<HlslMethodSourceInfo>(sourceInfo, diagnostics);
});
// Output the diagnostics
context.ReportDiagnostics(methodSourceInfoWithErrors.Select(static (item, token) => item.Errors));
// Get the filtered sequence to enable caching
IncrementalValuesProvider<HlslMethodSourceInfo> methodSourceInfo =
methodSourceInfoWithErrors
.Select(static (item, token) => item.Value)
.WithComparer(HlslMethodSourceInfo.Comparer.Default);
// Output the diagnostics, if any
context.ReportDiagnostics(
methodInfoWithErrors
.Select(static (item, _) => item.Diagnostcs)
.WithComparer(EqualityComparer<DiagnosticInfo>.Default.ForImmutableArray()));
// Generate the [ShaderMethodSource] attributes
context.RegisterSourceOutput(methodSourceInfo, static (context, item) =>
context.RegisterSourceOutput(methodInfoWithErrors, static (context, item) =>
{
CompilationUnitSyntax compilationUnit = Execute.GetSyntax(item);
string filename = item.MetadataName.Replace('`', '-').Replace('+', '.');
CompilationUnitSyntax compilationUnit = Execute.GetSyntax(item.HlslMethodSource);
string filename = item.HlslMethodSource.MetadataName.Replace('`', '-').Replace('+', '.');
context.AddSource($"{filename}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
@@ -86,9 +77,9 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
Compilation compilation,
CSharpSyntaxNode methodDeclaration,
IMethodSymbol methodSymbol,
out ImmutableArray<Diagnostic> diagnostics)
out ImmutableArray<DiagnosticInfo> diagnostics)
{
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
ImmutableArray<DiagnosticInfo>.Builder builder = ImmutableArray.CreateBuilder<DiagnosticInfo>();
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
@@ -113,14 +104,14 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
/// <summary>
/// Gets a sequence of processed methods from a target method declaration.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> or <see cref="LocalFunctionStatementSyntax"/> instance for the current method.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the method to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of processed methods in <paramref name="methodDeclaration"/> (main method and all captured methods).</returns>
private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods(
ImmutableArray<Diagnostic>.Builder diagnostics,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
CSharpSyntaxNode methodDeclaration,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,