diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md index 6d879574..64faf974 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -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) \ No newline at end of file +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) \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs index 7111ff4b..463b416b 100644 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs @@ -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() - 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()) + try { - typeDeclarationSyntax = parentType - .WithMembers(SingletonList(typeDeclarationSyntax)) - .WithConstraintClauses(List()) - .WithBaseList(null) - .WithAttributeLists(List()) - .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(), SourceText.From(source, Encoding.UTF8)); } } + + /// + /// Processes a given target type. + /// + /// The input instance to use. + /// The node to process. + /// The for . + 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() + 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 = parentType + .WithMembers(SingletonList(typeDeclarationSyntax)) + .WithConstraintClauses(List()) + .WithBaseList(null) + .WithAttributeLists(List()) + .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(), SourceText.From(source, Encoding.UTF8)); + } } } diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 80e8437f..25dbe67e 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -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"); + + /// + /// Gets a for an internal error in . + /// + /// Format: "The generator AutoConstructorGenerator failed to execute on type {0}, and its constructor might not be available". + /// + /// + 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"); + + /// + /// Gets a for an internal error in . + /// + /// Format: "The generator IComputeShaderDataLoaderGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash". + /// + /// + 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"); + + /// + /// Gets a for an internal error in . + /// + /// Format: "The generator IComputeShaderHashCodeGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash". + /// + /// + 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"); + + /// + /// Gets a for an internal error in . + /// + /// Format: "The generator IComputeShaderSourceGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash". + /// + /// + 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"); + + /// + /// Gets a for an internal error in . + /// + /// Format: "The generator ShaderMethodSourceGenerator failed to execute on method {0}, and using it in a shader might result in a runtime crash". + /// + /// + 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"); } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index e7bc5c2d..0f72f7b2 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -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(); - - // Add the method source attribute - context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); + try + { + OnExecute(context, structDeclaration, structDeclarationSymbol, ref attributes); + } + catch + { + context.ReportDiagnostic(IComputeShaderDataLoaderGeneratorError, structDeclaration, structDeclarationSymbol); + } } } + /// + /// Processes a given target type. + /// + /// The input instance to use. + /// The node to process. + /// The for . + /// The list of instances to append to the first copy of the partial class being generated. + 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(); + + // Add the method source attribute + context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); + } + /// /// Gets a sequence of statements to load the dispatch data for a given shader /// diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs index b5dad985..31ffe4a4 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -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(); - - // Add the method source attribute - context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); + try + { + OnExecute(context, structDeclaration, structDeclarationSymbol, ref attributes); + } + catch + { + context.ReportDiagnostic(IComputeShaderHashCodeGeneratorError, structDeclaration, structDeclarationSymbol); + } } } + /// + /// Processes a given target type. + /// + /// The input instance to use. + /// The node to process. + /// The for . + /// The list of instances to append to the first copy of the partial class being generated. + 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(); + + // Add the method source attribute + context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); + } + /// /// Gets a sequence of statements to process the hashcode of the captured delegates. /// diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index b6c54421..1970146f 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -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 discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary staticMethods = new(SymbolEqualityComparer.Default); - Dictionary 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(), SourceText.From(source, Encoding.UTF8)); + try + { + OnExecute(context, structDeclaration, semanticModel, structDeclarationSymbol); + } + catch + { + context.ReportDiagnostic(IComputeShaderSourceGeneratorError, structDeclaration, structDeclarationSymbol); + } } } + /// + /// Processes a given target type. + /// + /// The input instance to use. + /// The node to process. + /// The with metadata on the types being processed. + /// The for . + 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 discoveredTypes = new(SymbolEqualityComparer.Default); + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary 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(), SourceText.From(source, Encoding.UTF8)); + } + /// /// Gets a sequence of captured members and their mapped names. /// diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 2bdf88e4..6939758f 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -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 discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary staticMethods = new(SymbolEqualityComparer.Default); - Dictionary 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(), SourceText.From(source, Encoding.UTF8)); + try + { + OnExecute(context, methodDeclaration, semanticModel, methodDeclarationSymbol); + } + catch + { + context.ReportDiagnostic(ShaderMethodSourceGeneratorError, methodDeclaration, methodDeclarationSymbol); + } } } + /// + /// Processes a given target method. + /// + /// The input instance to use. + /// The node to process. + /// The with metadata on the types being processed. + /// The for . + 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 discoveredTypes = new(SymbolEqualityComparer.Default); + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary 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(), SourceText.From(source, Encoding.UTF8)); + } + /// /// Gets a sequence of processed methods from a target method declaration. /// diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 9c640fa4..637d6c36 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -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 {