Removed previous individual source generators for shaders

このコミットが含まれているのは:
Sergio Pedri committed 2021-07-12 15:58:52 +02:00
1 親 a5a4a77e65
コミット f8207f11ff
11ファイル変更
+105 -1768

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

+43 -45
ファイルの表示
@@ -7,50 +7,48 @@
Rule ID | Category | Severity | Notes
--------|----------|----------|-------
CMPS0001 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0002 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0003 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0004 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0005 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0006 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0007 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0008 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0009 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0010 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0011 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0012 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0013 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0014 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0015 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0016 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0017 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0018 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0019 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0020 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0021 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0022 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0023 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0024 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0025 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0026 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0027 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0028 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0029 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0030 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0031 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0032 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0033 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0034 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0035 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0036 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0001 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0002 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0003 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0004 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0005 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0006 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0007 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0008 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0009 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0010 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0011 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0012 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0013 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0014 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0015 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0016 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0017 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0018 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0019 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0020 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0021 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0022 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0023 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0024 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0025 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0026 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0027 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0028 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0029 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0030 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0031 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0032 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0033 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0034 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0035 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0036 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0037 | ComputeSharp.SourceGenerators.AutoConstructorGenerator | Warning | AutoConstructorGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0038 | ComputeSharp.SourceGenerators.IComputeShaderDataLoaderGenerator | Warning | IComputeShaderDataLoaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0039 | ComputeSharp.SourceGenerators.IComputeShaderHashCodeGenerator | Warning | IComputeShaderHashCodeGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0040 | ComputeSharp.SourceGenerators.IComputeShaderSourceGenerator | Warning | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0040 | ComputeSharp.SourceGenerators.IShaderGenerator | Warning | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0041 | ComputeSharp.SourceGenerators.ShaderMethodSourceGenerator | Warning | ShaderMethodSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0042 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0043 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0044 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0045 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0046 | ComputeSharp.IComputeShader | Error | IComputeShaderDataLoaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0047 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0042 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0043 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0044 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0045 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0046 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0047 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+8 -40
ファイルの表示
@@ -513,51 +513,19 @@ namespace ComputeSharp.SourceGenerators.Diagnostics
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an internal error in <see cref="IComputeShaderDataLoaderGenerator"/>.
/// Gets a <see cref="DiagnosticDescriptor"/> for an internal error in <see cref="IShaderGenerator"/>.
/// <para>
/// Format: <c>"The generator IComputeShaderDataLoaderGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash"</c>.
/// Format: <c>"The generator IShaderGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor IComputeShaderDataLoaderGeneratorError = new(
id: "CMPS0038",
title: $"Internal error for {nameof(IComputeShaderDataLoaderGenerator)}",
messageFormat: $"The generator {nameof(IComputeShaderDataLoaderGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash",
category: typeof(IComputeShaderDataLoaderGenerator).FullName,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: $"The {nameof(IComputeShaderDataLoaderGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an internal error in <see cref="IComputeShaderHashCodeGenerator"/>.
/// <para>
/// Format: <c>"The generator IComputeShaderHashCodeGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor IComputeShaderHashCodeGeneratorError = new(
id: "CMPS0039",
title: $"Internal error for {nameof(IComputeShaderHashCodeGenerator)}",
messageFormat: $"The generator {nameof(IComputeShaderHashCodeGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash",
category: typeof(IComputeShaderHashCodeGenerator).FullName,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: $"The {nameof(IComputeShaderHashCodeGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an internal error in <see cref="IComputeShaderSourceGenerator"/>.
/// <para>
/// Format: <c>"The generator IComputeShaderSourceGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor IComputeShaderSourceGeneratorError = new(
public static readonly DiagnosticDescriptor IShaderGeneratorError = new(
id: "CMPS0040",
title: $"Internal error for {nameof(IComputeShaderSourceGenerator)}",
messageFormat: $"The generator {nameof(IComputeShaderSourceGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash",
category: typeof(IComputeShaderSourceGenerator).FullName,
title: $"Internal error for {nameof(IShaderGenerator)}",
messageFormat: $"The generator {nameof(IShaderGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash",
category: typeof(IShaderGenerator).FullName,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: $"The {nameof(IComputeShaderSourceGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
description: $"The {nameof(IShaderGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
@@ -657,7 +625,7 @@ namespace ComputeSharp.SourceGenerators.Diagnostics
id: "CMPS0047",
title: "Multiple shader implementations for type declaration",
messageFormat: $"The shader of type {{0}} cannot implement more than one shader interface",
category: typeof(IComputeShaderSourceGenerator).FullName,
category: typeof(IShaderGenerator).FullName,
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A shader type cannot implement more than one shader interface.",
@@ -1,49 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.SourceGenerators
{
/// <inheritdoc/>
public sealed partial class IComputeShaderDataLoaderGenerator
{
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
{
/// <summary>
/// The list of info gathered during exploration.
/// </summary>
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
if (context.Node is StructDeclarationSyntax structDeclaration &&
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
structSymbol.Interfaces.Any(static interfaceSymbol =>
interfaceSymbol.Name == nameof(IComputeShader) ||
interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) }))
{
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
}
}
/// <summary>
/// A model for a group of item representing a discovered type to process.
/// </summary>
/// <param name="StructDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the target struct declaration.</param>
/// <param name="StructSymbol">The <see cref="INamedTypeSymbol"/> instance for <paramref name="StructDeclaration"/>.</param>
public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol);
}
}
}
-468
ファイルの表示
@@ -1,468 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.Core.Helpers;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Mappings;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators
{
/// <summary>
/// A source generator creating data loaders for <see cref="IComputeShader"/> types.
/// </summary>
[Generator]
public sealed partial class IComputeShaderDataLoaderGenerator : ISourceGenerator
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
return;
}
// Method attributes
AttributeListSyntax[] attributes = new[]
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderDataLoaderGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderDataLoaderGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be used directly by user code"))))))
};
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
{
try
{
OnExecute(context, item.StructDeclaration, item.StructSymbol, attributes);
}
catch
{
context.ReportDiagnostic(IComputeShaderDataLoaderGeneratorError, item.StructDeclaration, item.StructSymbol);
}
}
}
/// <summary>
/// Processes a given target type.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to 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="attributes">The list of <see cref="AttributeListSyntax"/> instances to append to the generated method.</param>
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, AttributeListSyntax[] attributes)
{
string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
string structName = structDeclaration.Identifier.Text;
SyntaxTokenList structModifiers = structDeclaration.Modifiers;
IEnumerable<StatementSyntax> blockStatements = GetDispatchDataLoadingStatements(context, structDeclarationSymbol, out int root32BitConstantsCount);
// Create the partial shader type declaration with the hashcode interface method implementation.
// This code produces a struct declaration as follows:
//
// public struct ShaderType : IShader<ShaderType>
// {
// [GeneratedCode("...", "...")]
// [DebuggerNonUserCode]
// [ExcludeFromCodeCoverage]
// [EditorBrowsable(EditorBrowsableState.Never)]
// [Obsolete("This method is not intended to be called directly by user code")]
// [return: ComputeRoot32BitConstants(42)]
// public readonly void LoadDispatchData<TDataLoader>(ref TDataLoader loader, GraphicsDevice device, int x, int y, int z)
// where TDataLoader : struct, IDispatchDataLoader
// {
// <BODY>
// }
// }
var structDeclarationSyntax =
StructDeclaration(structName).WithModifiers(structModifiers)
.AddBaseListTypes(SimpleBaseType(
GenericName(Identifier("IShader"))
.AddTypeArgumentListArguments(IdentifierName(structName)))).AddMembers(
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchData"))
.AddAttributeLists(attributes)
.AddAttributeLists(AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(nameof(ComputeRoot32BitConstantsAttribute).Replace("Attribute", "")))
.AddArgumentListArguments(AttributeArgument(LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(root32BitConstantsCount))))))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.ReturnKeyword))))
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TDataLoader")),
Parameter(Identifier("device")).WithType(IdentifierName("GraphicsDevice")),
Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
.AddConstraintClauses(
TypeParameterConstraintClause(IdentifierName("TDataLoader"))
.AddConstraints(
ClassOrStructConstraint(SyntaxKind.StructConstraint),
TypeConstraint(IdentifierName("IDispatchDataLoader"))))
.WithBody(Block(blockStatements)));
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (var parentType in structDeclaration.Ancestors().OfType<TypeDeclarationSyntax>())
{
typeDeclarationSyntax = parentType
.WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax))
.WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>())
.WithBaseList(null)
.WithAttributeLists(List<AttributeListSyntax>())
.WithoutTrivia();
}
// Create a static method to create the combined hashcode for a given shader type.
// This code takes a block syntax and produces a compilation unit as follows:
//
// using System;
// using System.CodeDom.Compiler;
// using System.ComponentModel;
// using System.Diagnostics;
// using System.Diagnostics.CodeAnalysis;
// using System.Runtime.CompilerServices;
// using ComputeSharp.__Internals;
//
// #pragma warning disable
//
// namespace <SHADER_NAMESPACE>
// {
// <SHADER_DECLARATION>
// }
var source =
CompilationUnit().AddUsings(
UsingDirective(IdentifierName("System")),
UsingDirective(IdentifierName("System.CodeDom.Compiler")),
UsingDirective(IdentifierName("System.ComponentModel")),
UsingDirective(IdentifierName("System.Diagnostics")),
UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")),
UsingDirective(IdentifierName("System.Runtime.CompilerServices")),
UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddMembers(
NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
.NormalizeWhitespace()
.ToFullString();
// Add the method source attribute
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch data for a given shader
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="count">The total number of 32 bit root constants to load.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
[Pure]
private static IEnumerable<StatementSyntax> GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out int count)
{
List<StatementSyntax> statements = new();
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
var isComputeShader = pixelShaderSymbol is null;
int
resourceOffset = 0,
rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
// Append the statements for the dispatch ranges:
//
// span0[0] = (uint)x;
// span0[1] = (uint)y;
// span0[2] = (uint)z;
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x")))));
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y")))));
if (isComputeShader)
{
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z")))));
}
// Append the statements to load all fields (both resources and other captured values)
AppendFields(structDeclarationSymbol, Array.Empty<string>(), ref resourceOffset, ref rawDataOffset, statements);
// After all the captured fields have been processed, ansure the reported byte size for
// the local variables is padded to a multiple of a 32 bit value. This is necessary to
// enable loading all the dispatch data after reinterpreting it to a sequence of values
// of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int));
count = rawDataOffset / sizeof(int);
// A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
// Loaded values in the root signature have the following costs:
// - Root constants cost 1 DWORD each, since they are 32-bit values.
// - Descriptor tables cost 1 DWORD each.
// - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each.
// So here we check whether the current signature respects that constraint,
// and emit a build error otherwise. For more info on this, see the docs here:
// https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits.
int rootSignatureDwordSize = count + resourceOffset;
if (rootSignatureDwordSize > 64)
{
context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
}
// Span<uint> span0 = stackalloc uint[<VARIABLES>];
statements.Insert(0,
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span0"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(count)))))))))));
// ref uint r0 = ref span0[0];
statements.Insert(1,
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// loader.LoadCapturedValues(span0);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadCapturedValues")))
.AddArgumentListArguments(Argument(IdentifierName("span0")))));
if (resourceOffset > 0)
{
// Span<ulong> span1 = stackalloc ulong[<RESOURCES>];
statements.Insert(1,
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceOffset)))))))))));
// ref ulong r1 = ref span1[0];
statements.Insert(3,
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// loader.LoadCapturedResources(span1);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadCapturedResources")))
.AddArgumentListArguments(Argument(IdentifierName("span1")))));
}
return statements;
}
/// <summary>
/// Explores a given type hierarchy and generates statements to load fields.
/// </summary>
/// <param name="currentTypeSymbol">The current type being explored.</param>
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
/// <param name="resourceOffset">The current offset in the root table of loaded resources.</param>
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
/// <param name="statements">The target list of statements being generated.</param>
private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection<string> fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection<StatementSyntax> statements)
{
bool isFirstField = true;
foreach (
IFieldSymbol fieldSymbol in
from fieldSymbol in currentTypeSymbol.GetMembers().OfType<IFieldSymbol>()
where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } &&
!fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer
select fieldSymbol)
{
string
fieldName = fieldSymbol.Name,
typeName = fieldSymbol.Type.GetFullMetadataName();
// Disambiguates the name of target fields against the current input parameters
if (fieldName is "loader" or "device" or "x" or "y" or "z")
{
fieldName = $"this.{fieldName}";
}
// The first item in each nested struct needs to be aligned to 16 bytes
if (isFirstField && fieldPath.Count > 0)
{
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
isFirstField = false;
}
if (HlslKnownTypes.IsTypedResourceType(typeName))
{
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.Add(ref r1, {resourceOffset++})"),
ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldName}, device)"))));
}
else if (HlslKnownTypes.IsKnownHlslType(typeName))
{
AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldName }), typeName, ref rawDataOffset, statements);
}
else if (fieldSymbol.Type.IsUnmanagedType)
{
// Custom struct type defined by the user
AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldName }).ToArray(), ref resourceOffset, ref rawDataOffset, statements);
}
}
}
/// <summary>
/// Generates a loading statement for a known HLSL primitive type field (scalar, vector or matrix).
/// </summary>
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
/// <param name="typeName">The type name currently being read.</param>
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
/// <param name="statements">The target list of statements being generated.</param>
private static void AppendHlslKnownTypeField(IEnumerable<string> fieldPath, string typeName, ref int rawDataOffset, ICollection<StatementSyntax> statements)
{
// For scalar, vector and linear matrix types, serialize the value normally.
// Only the initial alignment needs to be considered, while data is packed.
var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
// Check if the current type is a matrix type with more than one row. In this
// case, each row is aligned as if it was a separate array, so the start of
// each row needs to be at a multiple of 16 bytes (a float4 register).
if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
{
string
rowTypeName = $"ComputeSharp.{elementName}{columns}",
rowLocalName = $"__{string.Join("_", fieldPath)}__row0";
statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref Unsafe.As<{typeName}, {rowTypeName}>(ref Unsafe.AsRef(in {string.Join(".", fieldPath)}));"));
// Generate the loading code for each individual row, with proper alignment.
// This will result in the following (assuming Float2x3 m):
//
// ref Float3 __m__row0 = ref Unsafe.As<Float2x3, Float3>(ref Unsafe.AsRef(in m));
// Unsafe.As<uint, Float3>(ref Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, Unsafe.Add(ref __m__row0, 0);
// Unsafe.As<uint, Float3>(ref Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = Unsafe.Add(ref __m__row0, 1);
for (int j = 0; j < rows; j++)
{
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.As<uint, {rowTypeName}>(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"),
ParseExpression($"Unsafe.Add(ref {rowLocalName}, {j})"))));
rawDataOffset += fieldPack * columns;
}
}
else
{
// Calculate the right offset with 16-bytes padding (HLSL constant buffer).
// Since we're in a constant buffer, we need to both pad the starting offset
// to be aligned to the packing size of the type, and also to align the initial
// offset to ensure that values do not cross 16 bytes boundaries either.
rawDataOffset = AlignmentHelper.AlignToBoundary(
AlignmentHelper.Pad(rawDataOffset, fieldPack),
fieldSize,
16);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.As<uint, {typeName}>(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"),
ParseExpression($"{string.Join(".", fieldPath)}"))));
rawDataOffset += fieldSize;
}
}
}
}
-49
ファイルの表示
@@ -1,49 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.SourceGenerators
{
/// <inheritdoc/>
public sealed partial class IComputeShaderHashCodeGenerator
{
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
{
/// <summary>
/// The list of info gathered during exploration.
/// </summary>
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
if (context.Node is StructDeclarationSyntax structDeclaration &&
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
structSymbol.Interfaces.Any(static interfaceSymbol =>
interfaceSymbol.Name == nameof(IComputeShader) ||
interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) }))
{
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
}
}
/// <summary>
/// A model for a group of item representing a discovered type to process.
/// </summary>
/// <param name="StructDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the target struct declaration.</param>
/// <param name="StructSymbol">The <see cref="INamedTypeSymbol"/> instance for <paramref name="StructDeclaration"/>.</param>
public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol);
}
}
}
-221
ファイルの表示
@@ -1,221 +0,0 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
namespace ComputeSharp.SourceGenerators
{
/// <summary>
/// A source generator creating hash code factories for <see cref="IComputeShader"/> types.
/// </summary>
[Generator]
public sealed partial class IComputeShaderHashCodeGenerator : ISourceGenerator
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
return;
}
// Method attributes
AttributeListSyntax[] attributes = new[]
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be used directly by user code"))))))
};
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
{
try
{
OnExecute(context, item.StructDeclaration, item.StructSymbol, attributes);
}
catch
{
context.ReportDiagnostic(IComputeShaderHashCodeGeneratorError, item.StructDeclaration, item.StructSymbol);
}
}
}
/// <summary>
/// Processes a given target type.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to 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="attributes">The list of <see cref="AttributeListSyntax"/> instances to append to the generated method.</param>
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, AttributeListSyntax[] attributes)
{
string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
string structName = structDeclaration.Identifier.Text;
SyntaxTokenList structModifiers = structDeclaration.Modifiers;
// Create the partial shader type declaration with the hashcode interface method implementation.
// This code produces a struct declaration as follows:
//
// public struct ShaderType : IShader<ShaderType>
// {
// [GeneratedCode("...", "...")]
// [DebuggerNonUserCode]
// [ExcludeFromCodeCoverage]
// [EditorBrowsable(EditorBrowsableState.Never)]
// [Obsolete("This method is not intended to be called directly by user code")]
// public readonly int GetDispatchId()
// {
// <BODY>
// }
// }
var structDeclarationSyntax =
StructDeclaration(structName).WithModifiers(structModifiers)
.AddBaseListTypes(SimpleBaseType(
GenericName(Identifier("IShader"))
.AddTypeArgumentListArguments(IdentifierName(structName)))).AddMembers(
MethodDeclaration(
PredefinedType(Token(SyntaxKind.IntKeyword)),
Identifier("GetDispatchId"))
.AddAttributeLists(attributes)
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword))
.WithBody(GetShaderHashCodeBody(structDeclarationSymbol)));
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (var parentType in structDeclaration.Ancestors().OfType<TypeDeclarationSyntax>())
{
typeDeclarationSyntax = parentType
.WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax))
.WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>())
.WithBaseList(null)
.WithAttributeLists(List<AttributeListSyntax>())
.WithoutTrivia();
}
// Create a static method to create the combined hashcode for a given shader type.
// This code takes a block syntax and produces a compilation unit as follows:
//
// using System;
// using System.CodeDom.Compiler;
// using System.ComponentModel;
// using System.Diagnostics;
// using System.Diagnostics.CodeAnalysis;
// using ComputeSharp.__Internals;
//
// #pragma warning disable
//
// namespace <SHADER_NAMESPACE>
// {
// <SHADER_DECLARATION>
// }
var source =
CompilationUnit().AddUsings(
UsingDirective(IdentifierName("System")),
UsingDirective(IdentifierName("System.CodeDom.Compiler")),
UsingDirective(IdentifierName("System.ComponentModel")),
UsingDirective(IdentifierName("System.Diagnostics")),
UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")),
UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddMembers(
NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
.NormalizeWhitespace()
.ToFullString();
// Add the method source attribute
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to compute the hashcode of a given shader type.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
[Pure]
private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol)
{
var delegateFields = structDeclarationSymbol
.GetMembers()
.OfType<IFieldSymbol>()
.Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false })
.ToImmutableArray();
if (delegateFields.Length == 0)
{
// return 0;
return
Block(ReturnStatement(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))));
}
List<StatementSyntax> blockStatements = new(4);
// HashCode hashCode = default;
blockStatements.Add(LocalDeclarationStatement(
VariableDeclaration(IdentifierName("HashCode"))
.AddVariables(
VariableDeclarator(Identifier("hashCode"))
.WithInitializer(EqualsValueClause(
LiteralExpression(
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword)))))));
foreach (IFieldSymbol fieldSymbol in delegateFields)
{
// hashCode.Add(delegateField.Method);
blockStatements.Add(ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("Add")))
.AddArgumentListArguments(Argument(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(fieldSymbol.Name),
IdentifierName("Method"))))));
}
// return hashCode.ToHashCode();
blockStatements.Add(ReturnStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("ToHashCode")))));
return Block(blockStatements);
}
}
}
-49
ファイルの表示
@@ -1,49 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.SourceGenerators
{
/// <inheritdoc/>
public sealed partial class IComputeShaderSourceGenerator
{
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
{
/// <summary>
/// The list of info gathered during exploration.
/// </summary>
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
if (context.Node is StructDeclarationSyntax structDeclaration &&
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
structSymbol.Interfaces.Any(static interfaceSymbol =>
interfaceSymbol.Name == nameof(IComputeShader) ||
interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) }))
{
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
}
}
/// <summary>
/// A model for a group of item representing a discovered type to process.
/// </summary>
/// <param name="StructDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the target struct declaration.</param>
/// <param name="StructSymbol">The <see cref="INamedTypeSymbol"/> instance for <paramref name="StructDeclaration"/>.</param>
public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol);
}
}
}
-793
ファイルの表示
@@ -1,793 +0,0 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Helpers;
using ComputeSharp.SourceGenerators.Mappings;
using ComputeSharp.SourceGenerators.SyntaxRewriters;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators
{
/// <summary>
/// A source generator for processing <see cref="IComputeShader"/> types.
/// </summary>
[Generator]
public sealed partial class IComputeShaderSourceGenerator : ISourceGenerator
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
return;
}
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
{
SemanticModelProvider semanticModel = new(context.Compilation);
try
{
OnExecute(context, item.StructDeclaration, semanticModel, item.StructSymbol);
}
catch
{
context.ReportDiagnostic(IComputeShaderSourceGeneratorError, item.StructDeclaration, item.StructSymbol);
}
}
}
/// <summary>
/// Processes a given target type.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> with metadata on the types being processed.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, SemanticModelProvider semanticModel, INamedTypeSymbol structDeclarationSymbol)
{
// Properties are not supported
DetectAndReportPropertyDeclarations(context, structDeclarationSymbol);
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
// 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)
{
context.ReportDiagnostic(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol);
}
// Explore the syntax tree and extract the processed info
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 processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray();
var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
var (entryPoint, processedMethods, forwardDeclarations, isSamplerUsed) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader);
var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?);
var processedTypes = GetProcessedTypes(discoveredTypes).ToArray();
var processedConstants = GetProcessedConstants(constantDefinitions);
var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
GenerateRenderMethod(
context,
structDeclaration,
structDeclarationSymbol,
processedConstants,
staticFields,
processedTypes,
isComputeShader,
processedMembers,
implicitTextureType,
isSamplerUsed,
sharedBuffers,
forwardDeclarations,
processedMethods,
entryPoint);
// Create the compilation unit with the source attribute
var source =
CompilationUnit().AddUsings(
UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments(
AttributeArgument(TypeOfExpression(IdentifierName(structDeclarationSymbol.ToDisplayString()))),
AttributeArgument(ArrayExpression(Array.Empty<string>())), // TODO
AttributeArgument(ArrayExpression(Array.Empty<string>())), // TODO
AttributeArgument(ArrayExpression(Array.Empty<string>())), // TODO
AttributeArgument(NestedArrayExpression(Array.Empty<string[]>())), // TODO
AttributeArgument(ArrayExpression(Array.Empty<string>())), // TODO
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(""))), // TODO
AttributeArgument(ArrayExpression(Array.Empty<string>())), // TODO
AttributeArgument(NestedArrayExpression(Array.Empty<string[]>())), // TODO
AttributeArgument(NestedArrayExpression(Array.Empty<string[]>())), // TODO
AttributeArgument(NestedArrayExpression(Array.Empty<string[]>()))))) // TODO
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
.NormalizeWhitespace()
.ToFullString();
// Add the method source attribute
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
/// <summary>
/// Gets a sequence of captured fields and their mapped names.
/// </summary>
/// <param name="context">The current generator context in use.</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>
/// <returns>A sequence of captured fields in <paramref name="structDeclarationSymbol"/>.</returns>
[Pure]
private static IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> GetProcessedFields(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> types,
bool isComputeShader)
{
bool hlslResourceFound = false;
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
if (fieldSymbol.IsStatic) continue;
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
// Group shared fields must be static
if (attribute is not null)
{
context.ReportDiagnostic(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name);
}
// Captured fields must be named type symbols
if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol)
{
context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
continue;
}
string metadataName = typeSymbol.GetFullMetadataName();
// Allowed fields must be either resources, unmanaged values or delegates
if (HlslKnownTypes.IsTypedResourceType(metadataName))
{
hlslResourceFound = true;
// Track the type of items in the current buffer
if (HlslKnownTypes.IsStructuredBufferType(metadataName))
{
types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]);
}
}
else if (!typeSymbol.IsUnmanagedType &&
typeSymbol.TypeKind != TypeKind.Delegate)
{
// Shaders can only capture valid HLSL resource types or unmanaged types
context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol);
continue;
}
else if (typeSymbol.IsUnmanagedType &&
!HlslKnownTypes.IsKnownHlslType(metadataName))
{
// Track the type if it's a custom struct
types.Add(typeSymbol);
}
string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
// Yield back the current mapping for the name (if the name used a reserved keyword)
yield return (fieldSymbol, mapping ?? fieldSymbol.Name, typeName);
}
// If the shader is a compute one (so no implicit output texture), it has to contain at least one resource
if (!hlslResourceFound && isComputeShader)
{
context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol);
}
}
/// <summary>
/// Gets a sequence of shader static fields and their mapped names.
/// </summary>
/// <param name="context">The current generator context in use.</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>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of static constant fields in <paramref name="structDeclarationSymbol"/>.</returns>
[Pure]
private static IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
GeneratorExecutionContext context,
SemanticModelProvider semanticModel,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
foreach (var fieldDeclaration in structDeclaration.Members.OfType<FieldDeclarationSyntax>())
{
foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables)
{
IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!;
if (!fieldSymbol.IsStatic || fieldSymbol.IsConst)
{
continue;
}
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
if (attribute is not null) continue;
// Constant properties must be of a primitive, vector or matrix type
if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol ||
!HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName()))
{
context.ReportDiagnostic(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
continue;
}
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
string typeDeclaration = fieldSymbol.IsReadOnly switch
{
true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}",
false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}"
};
StaticFieldRewriter staticFieldRewriter = new(
semanticModel,
discoveredTypes,
constantDefinitions,
context);
string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace().ToFullString();
yield return (mapping ?? fieldSymbol.Name, typeDeclaration, assignment);
}
}
}
/// <summary>
/// Gets a sequence of captured members and their mapped names.
/// </summary>
/// <param name="context">The current generator context in use.</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>
[Pure]
private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> types)
{
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
if (!fieldSymbol.IsStatic) continue;
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
if (attribute is null) continue;
if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol)
{
context.ReportDiagnostic(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
continue;
}
if (!typeSymbol.ElementType.IsUnmanagedType)
{
context.ReportDiagnostic(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
continue;
}
int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value;
string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol);
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
yield return (mapping ?? fieldSymbol.Name, typeName, bufferSize);
types.Add((INamedTypeSymbol)typeSymbol.ElementType);
}
}
/// <summary>
/// Gets a sequence of processed methods declared within a given type.
/// </summary>
/// <param name="context">The current generator context in use.</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>
/// <param name="discoveredTypes">The collection of currently discovered 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="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>
[Pure]
private static (string EntryPoint, IEnumerable<string> Methods, IEnumerable<string> Declarations, bool IsSamplerUser) GetProcessedMethods(
GeneratorExecutionContext context,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
bool isComputeShader)
{
// Find all declared methods in the type
ImmutableArray<MethodDeclarationSyntax> methodDeclarations = (
from syntaxNode in structDeclaration.DescendantNodes()
where syntaxNode.IsKind(SyntaxKind.MethodDeclaration)
select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray();
string? entryPoint = null;
List<string> methods = new();
List<string> declarations = new();
bool isSamplerUsed = false;
foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations)
{
IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!;
bool isShaderEntryPoint =
(isComputeShader &&
methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) &&
methodDeclarationSymbol.ReturnsVoid &&
methodDeclarationSymbol.TypeParameters.Length == 0 &&
methodDeclarationSymbol.Parameters.Length == 0) ||
(!isComputeShader &&
methodDeclarationSymbol.Name == nameof(IPixelShader<byte>.Execute) &&
methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type
methodDeclarationSymbol.TypeParameters.Length == 0 &&
methodDeclarationSymbol.Parameters.Length == 0);
// Create the source rewriter for the current method
ShaderSourceRewriter shaderSourceRewriter = new(
structDeclarationSymbol,
semanticModel,
discoveredTypes,
staticMethods,
constantDefinitions,
context,
isShaderEntryPoint);
// Rewrite the method syntax tree
MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia();
// Track the implicit sampler, if used
isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed;
// Emit the extracted local functions first
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
{
methods.Add(localFunction.Value.NormalizeWhitespace().ToFullString());
declarations.Add(localFunction.Value.AsDefinition().NormalizeWhitespace().ToFullString());
}
// If the method is the shader entry point, do additional processing
if (isShaderEntryPoint)
{
processedMethod = isComputeShader switch
{
true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!,
false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)!
};
entryPoint = processedMethod.NormalizeWhitespace().ToFullString();
}
else
{
methods.Add(processedMethod.NormalizeWhitespace().ToFullString());
declarations.Add(processedMethod.AsDefinition().NormalizeWhitespace().ToFullString());
}
}
// Process static methods as well
foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values)
{
methods.Add(staticMethod.NormalizeWhitespace().ToFullString());
declarations.Add(staticMethod.AsDefinition().NormalizeWhitespace().ToFullString());
}
return (entryPoint!, methods, declarations, isSamplerUsed);
}
/// <summary>
/// Gets a sequence of discovered constants.
/// </summary>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of discovered constants to declare in the shader.</returns>
[Pure]
internal static IEnumerable<(string Name, string Value)> GetProcessedConstants(IReadOnlyDictionary<IFieldSymbol, string> constantDefinitions)
{
foreach (var constant in constantDefinitions)
{
var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
var constantName = $"__{ownerTypeName}__{constant.Key.Name}";
yield return (constantName, constant.Value);
}
}
/// <summary>
/// Gets the sequence of processed discovered custom types.
/// </summary>
/// <param name="types">The sequence of discovered custom types.</param>
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
internal static IEnumerable<string> GetProcessedTypes(IEnumerable<INamedTypeSymbol> types)
{
foreach (var type in HlslKnownTypes.GetCustomTypes(types))
{
var structType = type.GetFullMetadataName().ToHlslIdentifierName();
var structDeclaration = StructDeclaration(structType);
// Declare the fields of the current type
foreach (var field in type.GetMembers().OfType<IFieldSymbol>())
{
INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type;
// Convert the name to the fully qualified HLSL version
if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped))
{
mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName();
}
structDeclaration = structDeclaration.AddMembers(
FieldDeclaration(VariableDeclaration(
IdentifierName(mapped!)).AddVariables(
VariableDeclarator(Identifier(field.Name)))));
}
// Insert the trailing ; right after the closing bracket (after normalization)
yield return
structDeclaration
.NormalizeWhitespace()
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
.ToFullString();
}
}
/// <summary>
/// Finds and reports all declared properties in a shader.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
private static void DetectAndReportPropertyDeclarations(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol)
{
foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType<IPropertySymbol>())
{
context.ReportDiagnostic(DiagnosticDescriptors.PropertyDeclaration, propertySymbol);
}
}
private static void GenerateRenderMethod(
GeneratorExecutionContext context,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
IEnumerable<(string Name, string Value)> definedConstants,
IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
IEnumerable<string> declaredTypes,
bool isComputeShader,
IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields,
string? implicitTextureType,
bool isSamplerUsed,
IEnumerable<(string Name, string Type, int? Count)> sharedBuffers,
IEnumerable<string>? forwardDeclarations,
IEnumerable<string> processedMethods,
string executeMethod)
{
string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
string structName = structDeclaration.Identifier.Text;
SyntaxTokenList structModifiers = structDeclaration.Modifiers;
IEnumerable<StatementSyntax> bodyStatements = GenerateRenderMethodBody(
definedConstants,
staticFields,
declaredTypes,
isComputeShader,
instanceFields,
implicitTextureType,
isSamplerUsed,
sharedBuffers,
forwardDeclarations,
processedMethods,
executeMethod);
// Create the partial shader type declaration with the hashcode interface method implementation.
// This code produces a struct declaration as follows:
//
// public struct ShaderType : IShader<ShaderType>
// {
// [GeneratedCode("...", "...")]
// [DebuggerNonUserCode]
// [ExcludeFromCodeCoverage]
// [EditorBrowsable(EditorBrowsableState.Never)]
// [Obsolete("This method is not intended to be called directly by user code")]
// public readonly void BuildHlslString(ref ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ)
// {
// <BODY>
// }
// }
var structDeclarationSyntax =
StructDeclaration(structName).WithModifiers(structModifiers)
.AddBaseListTypes(SimpleBaseType(
GenericName(Identifier("IShader"))
.AddTypeArgumentListArguments(IdentifierName(structName)))).AddMembers(
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("BuildHlslString"))
.AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be used directly by user code")))))))
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword))
.AddParameterListParameters(
Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("ArrayPoolStringBuilder")),
Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
.WithBody(Block(bodyStatements)));
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (var parentType in structDeclaration.Ancestors().OfType<TypeDeclarationSyntax>())
{
typeDeclarationSyntax = parentType
.WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax))
.WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>())
.WithBaseList(null)
.WithAttributeLists(List<AttributeListSyntax>())
.WithoutTrivia();
}
// Create a static method to create the combined hashcode for a given shader type.
// This code takes a block syntax and produces a compilation unit as follows:
//
// using System;
// using System.CodeDom.Compiler;
// using System.ComponentModel;
// using System.Diagnostics;
// using System.Diagnostics.CodeAnalysis;
// using ComputeSharp.__Internals;
//
// #pragma warning disable
//
// namespace <SHADER_NAMESPACE>
// {
// <SHADER_DECLARATION>
// }
var source =
CompilationUnit().AddUsings(
UsingDirective(IdentifierName("System")),
UsingDirective(IdentifierName("System.CodeDom.Compiler")),
UsingDirective(IdentifierName("System.ComponentModel")),
UsingDirective(IdentifierName("System.Diagnostics")),
UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")),
UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddMembers(
NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
.NormalizeWhitespace()
.ToFullString();
// Add the method source attribute
context.AddSource("PREVIEW" + structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
private static IEnumerable<StatementSyntax> GenerateRenderMethodBody(
IEnumerable<(string Name, string Value)> definedConstants,
IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
IEnumerable<string> declaredTypes,
bool isComputeShader,
IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields,
string? implicitTextureType,
bool isSamplerUsed,
IEnumerable<(string Name, string Type, int? Count)> sharedBuffers,
IEnumerable<string>? forwardDeclarations,
IEnumerable<string> processedMethods,
string executeMethod)
{
// Header
yield return ParseStatement("builder.AppendLine(\"// ================================================\");");
yield return ParseStatement("builder.AppendLine(\"// AUTO GENERATED\");");
yield return ParseStatement("builder.AppendLine(\"// ================================================\");");
yield return ParseStatement("builder.AppendLine(\"// This shader was created by ComputeSharp.\");");
yield return ParseStatement("builder.AppendLine(\"// See: https://github.com/Sergio0694/ComputeSharp.\");");
// Group size constants
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement("builder.Append(\"#define __GroupSize__get_X \");");
yield return ParseStatement("builder.AppendLine(threadsX.ToString());");
yield return ParseStatement("builder.Append(\"#define __GroupSize__get_Y \");");
yield return ParseStatement("builder.AppendLine(threadsY.ToString());");
yield return ParseStatement("builder.Append(\"#define __GroupSize__get_Z \");");
yield return ParseStatement("builder.AppendLine(threadsZ.ToString());");
// Define declarations
foreach (var (name, value) in definedConstants)
{
yield return ParseStatement($"builder.AppendLine(\"#define {name} {value}\");");
}
// Static fields
if (staticFields.Any())
{
yield return ParseStatement("builder.AppendLine();");
foreach (var field in staticFields)
{
if (field.Assignment is string assignment)
{
yield return ParseStatement($"builder.AppendLine(\"{field.TypeDeclaration} {field.Name} = {assignment};\");");
}
else
{
yield return ParseStatement($"builder.AppendLine(\"{field.TypeDeclaration} {field.Name};\");");
}
}
}
// Declared types
foreach (var type in declaredTypes)
{
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement($"builder.AppendLine(\"{type}\");");
}
// Captured variables
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement("builder.AppendLine(\"cbuffer _ : register(b0)\");");
yield return ParseStatement("builder.AppendLine('{');");
yield return ParseStatement("builder.AppendLine(\" uint __x;\");");
yield return ParseStatement("builder.AppendLine(\" uint __y;\");");
if (isComputeShader)
{
yield return ParseStatement("builder.AppendLine(\" uint __z;\");");
}
// User-defined values
foreach (var instanceField in instanceFields)
{
if (instanceField.Symbol.Type.IsUnmanagedType)
{
yield return ParseStatement($"builder.AppendLine(\" {instanceField.HlslType} {instanceField.HlslName};\");");
}
}
yield return ParseStatement("builder.AppendLine('}');");
int
constantBuffersCount = 0,
readOnlyBuffersCount = 0,
readWriteBuffersCount = 0;
// Optional implicit texture field
if (!isComputeShader)
{
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement($"builder.AppendLine(\"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});\");");
}
// Optional sampler field
if (isSamplerUsed)
{
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement("builder.AppendLine(\"SamplerState __sampler : register(s);\");");
}
// Resources
foreach (var instanceField in instanceFields)
{
string metadataName = instanceField.Symbol.GetFullMetadataName();
if (HlslKnownTypes.IsConstantBufferType(metadataName))
{
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement($"builder.AppendLine(\"cbuffer _{instanceField.HlslName} : register(b{constantBuffersCount++})\");");
yield return ParseStatement("builder.AppendLine('{');");
yield return ParseStatement($"builder.AppendLine(\" {instanceField.HlslType} {instanceField.HlslName}[2];\");");
yield return ParseStatement("builder.AppendLine('}');");
}
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName))
{
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement($"builder.AppendLine(\"{instanceField.HlslType} : register(t{readOnlyBuffersCount++});\");");
}
else if (HlslKnownTypes.IsTypedResourceType(metadataName))
{
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement($"builder.AppendLine(\"{instanceField.HlslType} : register(u{readWriteBuffersCount++});\");");
}
}
// Shared buffers
foreach (var sharedBuffer in sharedBuffers)
{
object count = (object?)sharedBuffer.Count ?? "threadsX * threadsY * threadsZ";
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement($"builder.AppendLine(\"groupshared {sharedBuffer.Type} {sharedBuffer.Name} [{count}];\");");
}
// Forward declarations
if (forwardDeclarations is not null)
{
foreach (var forwardDeclaration in forwardDeclarations)
{
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement($"builder.AppendLine(\"{forwardDeclaration}\");");
}
}
// Captured methods
if (processedMethods is not null)
{
foreach (var method in processedMethods)
{
yield return ParseStatement("builder.AppendLine();");
yield return
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine")))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(method)))));
}
}
// Entry point
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement("builder.AppendLine(\"[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]\");");
yield return
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine")))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(executeMethod)))));
}
}
}
+3 -3
ファイルの表示
@@ -42,7 +42,7 @@ namespace ComputeSharp.SourceGenerators
}
catch
{
context.ReportDiagnostic(IComputeShaderDataLoaderGeneratorError, item.StructDeclaration, item.StructSymbol);
context.ReportDiagnostic(IShaderGeneratorError, item.StructDeclaration, item.StructSymbol);
}
}
}
@@ -76,8 +76,8 @@ namespace ComputeSharp.SourceGenerators
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderDataLoaderGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderDataLoaderGenerator).Assembly.GetName().Version.ToString())))))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))),
AttributeList(SingletonSeparatedList(
+2 -2
ファイルの表示
@@ -72,8 +72,8 @@ namespace ComputeSharp.SourceGenerators
// Explore the syntax tree and extract the processed info
var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
var processedTypes = IComputeShaderSourceGenerator.GetProcessedTypes(discoveredTypes).ToArray();
var processedConstants = IComputeShaderSourceGenerator.GetProcessedConstants(constantDefinitions);
var processedTypes = IShaderGenerator.GetProcessedTypes(discoveredTypes).ToArray();
var processedConstants = IShaderGenerator.GetProcessedConstants(constantDefinitions);
// Create the compilation unit with the source attribute
var source =
+49 -49
ファイルの表示
@@ -35,7 +35,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0001");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0001");
}
[TestMethod]
@@ -60,7 +60,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0001");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0001");
}
[TestMethod]
@@ -88,7 +88,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0002");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0002");
}
[TestMethod]
@@ -116,7 +116,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0003");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0003");
}
[TestMethod]
@@ -142,7 +142,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0004");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0004");
}
[TestMethod]
@@ -159,7 +159,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0005");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0005");
}
[TestMethod]
@@ -194,7 +194,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}}
}}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, diagnosticsId);
VerifyGeneratedDiagnostics<IShaderGenerator>(source, diagnosticsId);
}
[TestMethod]
@@ -226,7 +226,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}}
}}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, diagnosticsId);
VerifyGeneratedDiagnostics<IShaderGenerator>(source, diagnosticsId);
}
[TestMethod]
@@ -256,7 +256,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}}
}}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0006");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0006");
}
[TestMethod]
@@ -283,7 +283,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0010");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0010");
}
[TestMethod]
@@ -310,7 +310,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0010");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0010");
}
[TestMethod]
@@ -337,7 +337,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0011");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0011");
}
[TestMethod]
@@ -366,7 +366,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0012");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0012");
}
[TestMethod]
@@ -392,7 +392,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0012");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0012");
}
[TestMethod]
@@ -419,7 +419,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0012", "CMPS0013");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0012", "CMPS0013");
}
[TestMethod]
@@ -448,7 +448,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}}
}}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0014");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0014");
}
[TestMethod]
@@ -480,7 +480,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}}
}}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0015");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0015");
}
[TestMethod]
@@ -512,7 +512,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0016", "CMPS0032");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0016", "CMPS0032");
}
[TestMethod]
@@ -544,7 +544,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0017");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0017");
}
[TestMethod]
@@ -573,7 +573,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0018");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0018");
}
[TestMethod]
@@ -603,7 +603,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0019");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0019");
}
[TestMethod]
@@ -633,7 +633,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0020");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0020");
}
[TestMethod]
@@ -665,7 +665,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0021");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0021");
}
[TestMethod]
@@ -695,7 +695,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0022");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0022");
}
[TestMethod]
@@ -727,7 +727,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0023");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0023");
}
[TestMethod]
@@ -754,7 +754,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0024");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0024");
}
[TestMethod]
@@ -781,7 +781,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0032", "CMPS0025");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0032", "CMPS0025");
}
[TestMethod]
@@ -808,7 +808,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0026");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0026");
}
[TestMethod]
@@ -840,7 +840,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0027");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0027");
}
[TestMethod]
@@ -867,7 +867,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0028");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0028");
}
[TestMethod]
@@ -894,7 +894,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0029");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0029");
}
[TestMethod]
@@ -923,7 +923,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0029");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0029");
}
[TestMethod]
@@ -956,7 +956,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0030");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0030");
}
[TestMethod]
@@ -983,7 +983,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0031");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0031");
}
[TestMethod]
@@ -1010,7 +1010,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0032");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0032");
}
[TestMethod]
@@ -1037,7 +1037,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0033");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0033");
}
[TestMethod]
@@ -1066,7 +1066,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0034");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0034");
}
[TestMethod]
@@ -1095,7 +1095,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0035");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0035");
}
[TestMethod]
@@ -1124,7 +1124,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0035");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0035");
}
[TestMethod]
@@ -1151,7 +1151,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0036");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0036");
}
[TestMethod]
@@ -1192,7 +1192,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0042");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0042");
}
[TestMethod]
@@ -1220,7 +1220,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0043");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0043");
}
[TestMethod]
@@ -1248,7 +1248,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0045");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0045");
}
[TestMethod]
@@ -1279,7 +1279,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0045");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0045");
}
[TestMethod]
@@ -1307,7 +1307,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0045");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0045");
}
[TestMethod]
@@ -1335,7 +1335,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0045");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0045");
}
[TestMethod]
@@ -1367,7 +1367,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderDataLoaderGenerator>(source, "CMPS0046");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0046");
}
[TestMethod]
@@ -1392,7 +1392,7 @@ namespace ComputeSharp.Tests.SourceGenerators
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0047");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0047");
}
/// <summary>
@@ -1402,7 +1402,7 @@ namespace ComputeSharp.Tests.SourceGenerators
/// <param name="source">The input source to process.</param>
/// <param name="index">The target index to check in the resulting output.</param>
/// <param name="expectedBody">The expected body to compare with the generated code.</param>
private void VerifyGeneratedDiagnostics<TGenerator>(string source, params string[] diagnosticsIds)
private static void VerifyGeneratedDiagnostics<TGenerator>(string source, params string[] diagnosticsIds)
where TGenerator : class, ISourceGenerator, new()
{
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source);