Added warnings on source generator failures
このコミットが含まれているのは:
1 親
6784750179
コミット
a5217eef08
8ファイル変更
+430
-243
検索条件に一致するファイルはありません
@@ -40,4 +40,9 @@ CMPS0032 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator,
|
||||
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)
|
||||
CMPS0036 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [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)
|
||||
CMPS0041 | ComputeSharp.SourceGenerators.ShaderMethodSourceGenerator | Warning | ShaderMethodSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
@@ -1,11 +1,13 @@
|
||||
using System.Collections.Immutable;
|
||||
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;
|
||||
|
||||
@@ -37,59 +39,77 @@ namespace ComputeSharp.SourceGenerators
|
||||
SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree);
|
||||
INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!;
|
||||
|
||||
// Extract the info on the type to process
|
||||
var namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
|
||||
var structName = structDeclaration.Identifier.Text;
|
||||
var structModifiers = structDeclaration.Modifiers;
|
||||
var fields = (
|
||||
from fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>()
|
||||
where !fieldSymbol.IsConst && !fieldSymbol.IsStatic
|
||||
let typeName = fieldSymbol.Type!.ToDisplayString()
|
||||
let fieldFullType = ParseTypeName(typeName)
|
||||
select (Type: fieldFullType, Identifier: Identifier(fieldSymbol.Name))).ToImmutableArray();
|
||||
|
||||
// Create the constructor declaration for the type. This will
|
||||
// produce a constructor with simple initialization of all variables:
|
||||
//
|
||||
// public MyType(Foo a, Bar b, Baz c, ...)
|
||||
// {
|
||||
// this.a = a;
|
||||
// this.b = b;
|
||||
// this.c = c;
|
||||
// ...
|
||||
// }
|
||||
var structDeclarationSyntax =
|
||||
StructDeclaration(structName).WithModifiers(structModifiers).AddMembers(
|
||||
ConstructorDeclaration(structName)
|
||||
.AddModifiers(Token(SyntaxKind.PublicKeyword))
|
||||
.AddParameterListParameters(fields.Select(field => Parameter(field.Identifier).WithType(field.Type)).ToArray())
|
||||
.AddBodyStatements(fields.Select(field => ParseStatement($"this.{field.Identifier} = {field.Identifier};")).ToArray()));
|
||||
|
||||
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
|
||||
|
||||
// Add all parent types in ascending order, if any
|
||||
foreach (var parentType in structDeclaration.Ancestors().OfType<TypeDeclarationSyntax>())
|
||||
try
|
||||
{
|
||||
typeDeclarationSyntax = parentType
|
||||
.WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax))
|
||||
.WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>())
|
||||
.WithBaseList(null)
|
||||
.WithAttributeLists(List<AttributeListSyntax>())
|
||||
.WithoutTrivia();
|
||||
OnExecute(context, structDeclaration, structDeclarationSymbol);
|
||||
}
|
||||
catch
|
||||
{
|
||||
context.ReportDiagnostic(AutoConstructorGeneratorError, attribute, structDeclarationSymbol);
|
||||
}
|
||||
|
||||
// Create the compilation unit with the namespace and target member.
|
||||
// From this, we can finally generate the source code to output.
|
||||
var source =
|
||||
CompilationUnit().AddMembers(
|
||||
NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax))
|
||||
.NormalizeWhitespace()
|
||||
.ToFullString();
|
||||
|
||||
// Add the partial type
|
||||
context.AddSource(structDeclarationSymbol.GetGeneratedFileName<AutoConstructorGenerator>(), SourceText.From(source, Encoding.UTF8));
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
// Extract the info on the type to process
|
||||
var namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
|
||||
var structName = structDeclaration.Identifier.Text;
|
||||
var structModifiers = structDeclaration.Modifiers;
|
||||
var fields = (
|
||||
from fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>()
|
||||
where !fieldSymbol.IsConst && !fieldSymbol.IsStatic
|
||||
let typeName = fieldSymbol.Type!.ToDisplayString()
|
||||
let fieldFullType = ParseTypeName(typeName)
|
||||
select (Type: fieldFullType, Identifier: Identifier(fieldSymbol.Name))).ToImmutableArray();
|
||||
|
||||
// Create the constructor declaration for the type. This will
|
||||
// produce a constructor with simple initialization of all variables:
|
||||
//
|
||||
// public MyType(Foo a, Bar b, Baz c, ...)
|
||||
// {
|
||||
// this.a = a;
|
||||
// this.b = b;
|
||||
// this.c = c;
|
||||
// ...
|
||||
// }
|
||||
var structDeclarationSyntax =
|
||||
StructDeclaration(structName).WithModifiers(structModifiers).AddMembers(
|
||||
ConstructorDeclaration(structName)
|
||||
.AddModifiers(Token(SyntaxKind.PublicKeyword))
|
||||
.AddParameterListParameters(fields.Select(field => Parameter(field.Identifier).WithType(field.Type)).ToArray())
|
||||
.AddBodyStatements(fields.Select(field => ParseStatement($"this.{field.Identifier} = {field.Identifier};")).ToArray()));
|
||||
|
||||
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 the compilation unit with the namespace and target member.
|
||||
// From this, we can finally generate the source code to output.
|
||||
var source =
|
||||
CompilationUnit().AddMembers(
|
||||
NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax))
|
||||
.NormalizeWhitespace()
|
||||
.ToFullString();
|
||||
|
||||
// Add the partial type
|
||||
context.AddSource(structDeclarationSymbol.GetGeneratedFileName<AutoConstructorGenerator>(), SourceText.From(source, Encoding.UTF8));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -507,5 +507,85 @@ namespace ComputeSharp.SourceGenerators.Diagnostics
|
||||
isEnabledByDefault: true,
|
||||
description: "String literal expressions cannot be used in a compute shader.",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for an internal error in <see cref="AutoConstructorGenerator"/>.
|
||||
/// <para>
|
||||
/// Format: <c>"The generator AutoConstructorGenerator failed to execute on type {0}, and its constructor might not be available"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor AutoConstructorGeneratorError = new(
|
||||
id: "CMPS0037",
|
||||
title: $"Internal error for {nameof(AutoConstructorGenerator)}",
|
||||
messageFormat: $"The generator {nameof(AutoConstructorGenerator)} failed to execute on type {{0}}, and its constructor might not be available",
|
||||
category: typeof(AutoConstructorGenerator).FullName,
|
||||
defaultSeverity: DiagnosticSeverity.Warning,
|
||||
isEnabledByDefault: true,
|
||||
description: $"The {nameof(AutoConstructorGenerator)} generator encountered an error while processing a type, and its constructor might not be available. 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="IComputeShaderDataLoaderGenerator"/>.
|
||||
/// <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>.
|
||||
/// </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(
|
||||
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,
|
||||
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.",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for an internal error in <see cref="ShaderMethodSourceGenerator"/>.
|
||||
/// <para>
|
||||
/// Format: <c>"The generator ShaderMethodSourceGenerator failed to execute on method {0}, and using it in a shader might result in a runtime crash"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor ShaderMethodSourceGeneratorError = new(
|
||||
id: "CMPS0041",
|
||||
title: $"Internal error for {nameof(ShaderMethodSourceGenerator)}",
|
||||
messageFormat: $"The generator {nameof(ShaderMethodSourceGenerator)} failed to execute on method {{0}}, and using it in a shader might result in a runtime crash",
|
||||
category: typeof(ShaderMethodSourceGenerator).FullName,
|
||||
defaultSeverity: DiagnosticSeverity.Warning,
|
||||
isEnabledByDefault: true,
|
||||
description: $"The {nameof(ShaderMethodSourceGenerator)} generator encountered an error while processing a method, and using it in a shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,14 @@ 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;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
@@ -53,77 +55,96 @@ namespace ComputeSharp.SourceGenerators
|
||||
SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree);
|
||||
INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!;
|
||||
|
||||
// Only process compute shader types
|
||||
if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue;
|
||||
|
||||
TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString());
|
||||
BlockSyntax block = Block(GetDispatchDataLoadingStatements(structDeclarationSymbol, out int root32BitConstantsCount));
|
||||
|
||||
// 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.ComponentModel;
|
||||
//
|
||||
// namespace ComputeSharp.__Internals
|
||||
// {
|
||||
// internal static partial class DispatchDataLoader
|
||||
// {
|
||||
// [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
|
||||
// [System.Obsolete("This method is not intended to be called directly by user code")]
|
||||
// [return: ComputeRoot32BitConstants(42)]
|
||||
// public static int LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1)
|
||||
// {
|
||||
// ...
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
var source =
|
||||
CompilationUnit().AddUsings(
|
||||
UsingDirective(IdentifierName("System")),
|
||||
UsingDirective(IdentifierName("System.ComponentModel")),
|
||||
UsingDirective(IdentifierName("System.Runtime.CompilerServices"))).AddMembers(
|
||||
NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers(
|
||||
ClassDeclaration("DispatchDataLoader").AddModifiers(
|
||||
Token(SyntaxKind.InternalKeyword),
|
||||
Token(SyntaxKind.StaticKeyword),
|
||||
Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers(
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.IntKeyword)),
|
||||
Identifier("LoadDispatchData")).AddAttributeLists(
|
||||
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 called directly by user code")))))),
|
||||
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.StaticKeyword)).AddParameterListParameters(
|
||||
Parameter(Identifier("device")).WithType(IdentifierName("ComputeSharp.GraphicsDevice")),
|
||||
Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType),
|
||||
Parameter(Identifier("r0")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ULongKeyword))),
|
||||
Parameter(Identifier("r1")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
|
||||
.WithBody(block)))
|
||||
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
|
||||
.NormalizeWhitespace()
|
||||
.ToFullString();
|
||||
|
||||
// Clear the attribute list to avoid duplicates
|
||||
attributes = Array.Empty<AttributeListSyntax>();
|
||||
|
||||
// Add the method source attribute
|
||||
context.AddSource(structDeclarationSymbol.GetGeneratedFileName<IComputeShaderDataLoaderGenerator>(), SourceText.From(source, Encoding.UTF8));
|
||||
try
|
||||
{
|
||||
OnExecute(context, structDeclaration, structDeclarationSymbol, ref attributes);
|
||||
}
|
||||
catch
|
||||
{
|
||||
context.ReportDiagnostic(IComputeShaderDataLoaderGeneratorError, structDeclaration, structDeclarationSymbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 first copy of the partial class being generated.</param>
|
||||
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, ref AttributeListSyntax[] attributes)
|
||||
{
|
||||
// Only process compute shader types
|
||||
if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) return;
|
||||
|
||||
TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString());
|
||||
BlockSyntax block = Block(GetDispatchDataLoadingStatements(structDeclarationSymbol, out int root32BitConstantsCount));
|
||||
|
||||
// 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.ComponentModel;
|
||||
//
|
||||
// namespace ComputeSharp.__Internals
|
||||
// {
|
||||
// internal static partial class DispatchDataLoader
|
||||
// {
|
||||
// [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
|
||||
// [System.Obsolete("This method is not intended to be called directly by user code")]
|
||||
// [return: ComputeRoot32BitConstants(42)]
|
||||
// public static int LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1)
|
||||
// {
|
||||
// ...
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
var source =
|
||||
CompilationUnit().AddUsings(
|
||||
UsingDirective(IdentifierName("System")),
|
||||
UsingDirective(IdentifierName("System.ComponentModel")),
|
||||
UsingDirective(IdentifierName("System.Runtime.CompilerServices"))).AddMembers(
|
||||
NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers(
|
||||
ClassDeclaration("DispatchDataLoader").AddModifiers(
|
||||
Token(SyntaxKind.InternalKeyword),
|
||||
Token(SyntaxKind.StaticKeyword),
|
||||
Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers(
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.IntKeyword)),
|
||||
Identifier("LoadDispatchData")).AddAttributeLists(
|
||||
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 called directly by user code")))))),
|
||||
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.StaticKeyword)).AddParameterListParameters(
|
||||
Parameter(Identifier("device")).WithType(IdentifierName("ComputeSharp.GraphicsDevice")),
|
||||
Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType),
|
||||
Parameter(Identifier("r0")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ULongKeyword))),
|
||||
Parameter(Identifier("r1")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
|
||||
.WithBody(block)))
|
||||
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
|
||||
.NormalizeWhitespace()
|
||||
.ToFullString();
|
||||
|
||||
// Clear the attribute list to avoid duplicates
|
||||
attributes = Array.Empty<AttributeListSyntax>();
|
||||
|
||||
// Add the method source attribute
|
||||
context.AddSource(structDeclarationSymbol.GetGeneratedFileName<IComputeShaderDataLoaderGenerator>(), SourceText.From(source, Encoding.UTF8));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of statements to load the dispatch data for a given shader
|
||||
/// </summary>
|
||||
|
||||
@@ -4,11 +4,13 @@ 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;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators
|
||||
@@ -48,68 +50,87 @@ namespace ComputeSharp.SourceGenerators
|
||||
SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree);
|
||||
INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!;
|
||||
|
||||
// Only process compute shader types
|
||||
if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue;
|
||||
|
||||
TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString());
|
||||
BlockSyntax block = Block(GetDelegateHashCodeStatements(structDeclarationSymbol));
|
||||
|
||||
if (block.Statements.Count == 1) continue;
|
||||
|
||||
// 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.ComponentModel;
|
||||
//
|
||||
// namespace ComputeSharp.__Internals
|
||||
// {
|
||||
// internal static partial class HashCodeProvider
|
||||
// {
|
||||
// [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
|
||||
// [System.Obsolete("This method is not intended to be called directly by user code")]
|
||||
// public static int CombineHashCode(int hash, in ShaderType shader)
|
||||
// {
|
||||
// return ...;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
var source =
|
||||
CompilationUnit().AddUsings(
|
||||
UsingDirective(IdentifierName("System")),
|
||||
UsingDirective(IdentifierName("System.ComponentModel"))).AddMembers(
|
||||
NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers(
|
||||
ClassDeclaration("HashCodeProvider").AddModifiers(
|
||||
Token(SyntaxKind.InternalKeyword),
|
||||
Token(SyntaxKind.StaticKeyword),
|
||||
Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers(
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.IntKeyword)),
|
||||
Identifier("CombineHash")).AddAttributeLists(
|
||||
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 called directly by user code"))))))).AddModifiers(
|
||||
Token(SyntaxKind.PublicKeyword),
|
||||
Token(SyntaxKind.StaticKeyword)).AddParameterListParameters(
|
||||
Parameter(Identifier("hash")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType))
|
||||
.WithBody(block))))
|
||||
.NormalizeWhitespace()
|
||||
.ToFullString();
|
||||
|
||||
// Clear the attribute list to avoid duplicates
|
||||
attributes = Array.Empty<AttributeListSyntax>();
|
||||
|
||||
// Add the method source attribute
|
||||
context.AddSource(structDeclarationSymbol.GetGeneratedFileName<IComputeShaderHashCodeGenerator>(), SourceText.From(source, Encoding.UTF8));
|
||||
try
|
||||
{
|
||||
OnExecute(context, structDeclaration, structDeclarationSymbol, ref attributes);
|
||||
}
|
||||
catch
|
||||
{
|
||||
context.ReportDiagnostic(IComputeShaderHashCodeGeneratorError, structDeclaration, structDeclarationSymbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 first copy of the partial class being generated.</param>
|
||||
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, ref AttributeListSyntax[] attributes)
|
||||
{
|
||||
// Only process compute shader types
|
||||
if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) return;
|
||||
|
||||
TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString());
|
||||
BlockSyntax block = Block(GetDelegateHashCodeStatements(structDeclarationSymbol));
|
||||
|
||||
if (block.Statements.Count == 1) return;
|
||||
|
||||
// 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.ComponentModel;
|
||||
//
|
||||
// namespace ComputeSharp.__Internals
|
||||
// {
|
||||
// internal static partial class HashCodeProvider
|
||||
// {
|
||||
// [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
|
||||
// [System.Obsolete("This method is not intended to be called directly by user code")]
|
||||
// public static int CombineHashCode(int hash, in ShaderType shader)
|
||||
// {
|
||||
// return ...;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
var source =
|
||||
CompilationUnit().AddUsings(
|
||||
UsingDirective(IdentifierName("System")),
|
||||
UsingDirective(IdentifierName("System.ComponentModel"))).AddMembers(
|
||||
NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers(
|
||||
ClassDeclaration("HashCodeProvider").AddModifiers(
|
||||
Token(SyntaxKind.InternalKeyword),
|
||||
Token(SyntaxKind.StaticKeyword),
|
||||
Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers(
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.IntKeyword)),
|
||||
Identifier("CombineHash")).AddAttributeLists(
|
||||
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 called directly by user code"))))))).AddModifiers(
|
||||
Token(SyntaxKind.PublicKeyword),
|
||||
Token(SyntaxKind.StaticKeyword)).AddParameterListParameters(
|
||||
Parameter(Identifier("hash")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType))
|
||||
.WithBody(block))))
|
||||
.NormalizeWhitespace()
|
||||
.ToFullString();
|
||||
|
||||
// Clear the attribute list to avoid duplicates
|
||||
attributes = Array.Empty<AttributeListSyntax>();
|
||||
|
||||
// Add the method source attribute
|
||||
context.AddSource(structDeclarationSymbol.GetGeneratedFileName<IComputeShaderHashCodeGenerator>(), SourceText.From(source, Encoding.UTF8));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of statements to process the hashcode of the captured delegates.
|
||||
/// </summary>
|
||||
|
||||
@@ -12,9 +12,9 @@ using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper;
|
||||
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
@@ -42,45 +42,64 @@ namespace ComputeSharp.SourceGenerators
|
||||
SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree);
|
||||
INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!;
|
||||
|
||||
// Only process compute shader types
|
||||
if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue;
|
||||
|
||||
// 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);
|
||||
|
||||
// Explore the syntax tree and extract the processed info
|
||||
var processedMembers = GetProcessedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
|
||||
var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
|
||||
var (entryPoint, localFunctions) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
|
||||
var processedTypes = GetProcessedTypes(discoveredTypes).ToArray();
|
||||
var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray();
|
||||
var processedConstants = GetProcessedConstants(constantDefinitions);
|
||||
|
||||
// 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(processedTypes)),
|
||||
AttributeArgument(NestedArrayExpression(processedMembers)),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))),
|
||||
AttributeArgument(ArrayExpression(processedMethods)),
|
||||
AttributeArgument(NestedArrayExpression(processedConstants)),
|
||||
AttributeArgument(NestedArrayExpression(sharedBuffers)))))
|
||||
.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<IComputeShaderSourceGenerator>(), SourceText.From(source, Encoding.UTF8));
|
||||
try
|
||||
{
|
||||
OnExecute(context, structDeclaration, semanticModel, structDeclarationSymbol);
|
||||
}
|
||||
catch
|
||||
{
|
||||
context.ReportDiagnostic(IComputeShaderSourceGeneratorError, structDeclaration, structDeclarationSymbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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="SemanticModel"/> 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, SemanticModel semanticModel, INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
// Only process compute shader types
|
||||
if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) return;
|
||||
|
||||
// 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);
|
||||
|
||||
// Explore the syntax tree and extract the processed info
|
||||
var processedMembers = GetProcessedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
|
||||
var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
|
||||
var (entryPoint, localFunctions) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
|
||||
var processedTypes = GetProcessedTypes(discoveredTypes).ToArray();
|
||||
var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray();
|
||||
var processedConstants = GetProcessedConstants(constantDefinitions);
|
||||
|
||||
// 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(processedTypes)),
|
||||
AttributeArgument(NestedArrayExpression(processedMembers)),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))),
|
||||
AttributeArgument(ArrayExpression(processedMethods)),
|
||||
AttributeArgument(NestedArrayExpression(processedConstants)),
|
||||
AttributeArgument(NestedArrayExpression(sharedBuffers)))))
|
||||
.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<IComputeShaderSourceGenerator>(), SourceText.From(source, Encoding.UTF8));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of captured members and their mapped names.
|
||||
/// </summary>
|
||||
|
||||
@@ -4,14 +4,16 @@ using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ComputeSharp.__Internals;
|
||||
using ComputeSharp.SourceGenerators.Diagnostics;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using ComputeSharp.SourceGenerators.SyntaxRewriters;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
|
||||
using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
@@ -42,36 +44,55 @@ namespace ComputeSharp.SourceGenerators
|
||||
SemanticModel semanticModel = context.Compilation.GetSemanticModel(methodDeclaration.SyntaxTree);
|
||||
IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!;
|
||||
|
||||
// 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);
|
||||
|
||||
// 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);
|
||||
|
||||
// Create the compilation unit with the source attribute
|
||||
var source =
|
||||
CompilationUnit().AddAttributeLists(
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))),
|
||||
AttributeArgument(ArrayExpression(processedTypes)),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))),
|
||||
AttributeArgument(ArrayExpression(processedMethods)),
|
||||
AttributeArgument(NestedArrayExpression(processedConstants)))))
|
||||
.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(methodDeclarationSymbol.GetGeneratedFileName<ShaderMethodSourceAttribute>(), SourceText.From(source, Encoding.UTF8));
|
||||
try
|
||||
{
|
||||
OnExecute(context, methodDeclaration, semanticModel, methodDeclarationSymbol);
|
||||
}
|
||||
catch
|
||||
{
|
||||
context.ReportDiagnostic(ShaderMethodSourceGeneratorError, methodDeclaration, methodDeclarationSymbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes a given target method.
|
||||
/// </summary>
|
||||
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
|
||||
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> node to process.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModel"/> with metadata on the types being processed.</param>
|
||||
/// <param name="methodDeclarationSymbol">The <see cref="IMethodSymbol"/> for <paramref name="methodDeclaration"/>.</param>
|
||||
private static void OnExecute(GeneratorExecutionContext context, MethodDeclarationSyntax methodDeclaration, SemanticModel semanticModel, IMethodSymbol methodDeclarationSymbol)
|
||||
{
|
||||
// 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);
|
||||
|
||||
// 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);
|
||||
|
||||
// Create the compilation unit with the source attribute
|
||||
var source =
|
||||
CompilationUnit().AddAttributeLists(
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))),
|
||||
AttributeArgument(ArrayExpression(processedTypes)),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))),
|
||||
AttributeArgument(ArrayExpression(processedMethods)),
|
||||
AttributeArgument(NestedArrayExpression(processedConstants)))))
|
||||
.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(methodDeclarationSymbol.GetGeneratedFileName<ShaderMethodSourceAttribute>(), SourceText.From(source, Encoding.UTF8));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of processed methods from a target method declaration.
|
||||
/// </summary>
|
||||
|
||||
@@ -9,8 +9,8 @@ using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Operations;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators.SyntaxRewriters
|
||||
{
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする