using System.Collections.Generic; using System.Linq; using System.Text; using ComputeSharp.__Internals; 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; #pragma warning disable CS0618 namespace ComputeSharp.SourceGenerators { /// /// A source generator creating data loaders for and types. /// [Generator] public sealed partial class IShaderGenerator : ISourceGenerator { /// public void Initialize(GeneratorInitializationContext context) { context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); } /// 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) { try { OnExecute(context, item.StructDeclaration, item.StructSymbol); } catch { context.ReportDiagnostic(IShaderGeneratorError, item.StructDeclaration, item.StructSymbol); } } } /// /// 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) { // Create the required interface methods for the current shader type MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol), loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants), buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed, out bool isHashSetDirectiveNeeded), loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(implicitTextureType, discoveredResources, root32BitConstants, isSamplerUsed); // Reorder the method declarations to respect the order in the interface definition MethodDeclarationSyntax[] methods = { getDispatchIdMethod, loadDispatchDataMethod, loadDispatchMetadataMethod, buildHlslStringMethod }; // Method attributes AttributeListSyntax[] attributes = new[] { AttributeList(SingletonSeparatedList( Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments( 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( 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")))))) }; 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 // { // // } var structDeclarationSyntax = StructDeclaration(structName) .WithModifiers(structModifiers) .AddMembers(methods.Select(m => m.AddAttributeLists(attributes)).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(); } // Prepare the necessary using directives List usingDirectives = new() { 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")), UsingDirective(IdentifierName("ComputeSharp.__Internals")) }; if (isHashSetDirectiveNeeded) { usingDirectives.Insert(2, UsingDirective(IdentifierName("System.Collections.Generic"))); } // 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 // { // // } var source = CompilationUnit().AddUsings(usingDirectives.ToArray()).AddMembers( NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) .NormalizeWhitespace(eol: "\n") .ToFullString(); // Add the method source attribute context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); } /// /// Creates a instance for the GetDispatchId method. /// /// The for . /// The resulting instance for the GetDispatchId method. private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol); /// /// Creates a instance for the LoadDispatchDataMethod method. /// /// The input instance to use. /// The for . /// The collection of discovered resources in the current shader type. /// The total number of 32 bit root constants being loaded for the current shader type. /// The resulting instance for the LoadDispatchDataMethod method. private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod( GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IReadOnlyCollection discoveredResources, out int root32BitConstantsCount); /// /// Creates a instance for the BuildHlslString method. /// /// The input instance to use. /// The node to process. /// The for . /// The implicit texture type, if available (if the shader is a pixel shader). /// Whether or not the current shader type requires a static sampler to be available. /// Indicates whether or not the directive for is needed. /// The resulting instance for the BuildHlslString method. private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod( GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed, out bool isHashSetDirectiveNeeded); /// /// Creates a instance for the LoadDispatchMetadata method. /// /// The implicit texture type, if available (if the shader is a pixel shader). /// The collection of resources used by the shader. /// The total number of 32 bit root constants being loaded for the shader. /// Whether or not the shader requires a static sampler to be available. /// The resulting instance for the LoadDispatchMetadata method. private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod( string? implicitTextureType, IReadOnlyCollection discoveredResources, int root32BitConstantsCount, bool isSamplerUsed); } }