using System.Collections.Generic; using System.Linq; using System.Text; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; namespace ComputeSharp.SourceGenerators; /// /// 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); MethodDeclarationSyntax loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants); MethodDeclarationSyntax buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed); MethodDeclarationSyntax 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 List attributes = new() { AttributeList(SingletonSeparatedList( Attribute(IdentifierName("global::System.CodeDom.Compiler.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("global::System.Diagnostics.DebuggerNonUserCode")))), AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))), AttributeList(SingletonSeparatedList( Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments( AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))), AttributeList(SingletonSeparatedList( Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments( AttributeArgument(LiteralExpression( SyntaxKind.StringLiteralExpression, Literal("This method is not intended to be used directly by user code")))))) }; // Add [SkipLocalsInit] if the target project allows it if (context.Compilation.Options is CSharpCompilationOptions { AllowUnsafe: true }) { attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit"))))); } 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())).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 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: // // #pragma warning disable // // namespace ; // // var source = CompilationUnit().AddMembers( FileScopedNamespaceDeclaration(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. /// The resulting instance for the BuildHlslString method. private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod( GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed); /// /// 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); }