using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// /// A source generator creating data loaders for and types. /// [Generator] public sealed partial class IShaderGenerator2 : IIncrementalGenerator { /// public void Initialize(IncrementalGeneratorInitializationContext context) { // Check whether [SkipLocalsInit] can be used IncrementalValueProvider canUseSkipLocalsInit = context.CompilationProvider .Select(static (compilation, token) => compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } && compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.SkipLocalsInit") is not null); // Get all declared struct types and their type symbols IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol)> structDeclarations = context.SyntaxProvider.CreateSyntaxProvider( static (node, token) => node is StructDeclarationSyntax structDeclaration, static (context, token) => ( (StructDeclarationSyntax)context.Node, Symbol: (INamedTypeSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token))) .Where(static pair => pair.Symbol is not null)!; // Get the symbol for the IComputeShader interface IncrementalValueProvider iComputeShaderSymbol = context.CompilationProvider .Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(IComputeShader).FullName))!; // Get the symbol for the IPixelShader interface IncrementalValueProvider iPixelShaderSymbol = context.CompilationProvider .Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(IPixelShader<>).FullName))!; // Filter struct declarations that implement a shader interface, and also gather the hierarchy info and shader type IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol, HierarchyInfo Hierarchy, Type Type)> shaderDeclarations = structDeclarations .Combine(iComputeShaderSymbol.Combine(iPixelShaderSymbol)) .Select(static (item, token) => (item.Left, Type: GetShaderType(item.Left.Symbol, item.Right.Left, item.Right.Right))) .Where(static item => item.Type is not null) .Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, HierarchyInfo.From(item.Left.Symbol), item.Type!)); // Get the hierarchy info and delegate field names for each shader type IncrementalValuesProvider<(HierarchyInfo Hierarchy, ImmutableArray Delegates)> hierarchyInfoAndDelegateFieldNames = shaderDeclarations .Select(static (item, token) => (item.Hierarchy, GetDelegateFieldNames(item.Symbol))); // Generate the GetDispatchId() methods context.RegisterSourceOutput(hierarchyInfoAndDelegateFieldNames.Combine(canUseSkipLocalsInit), static (context, item) => { MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(item.Left.Delegates); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, getDispatchIdMethod, item.Right); context.AddSource($"{item.Left.Hierarchy.FilenameHint}.GetDispatchId", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); }); // Get the hierarchy info and captured field infos for each shader type IncrementalValuesProvider<(HierarchyInfo Hierarchy, Type Type, ImmutableArray FieldInfos, int ResourceCount, int Root32BitConstantCount)> hierarchyInfoAndCaptureFieldInfos = shaderDeclarations .Select(static (item, token) => ( item.Hierarchy, item.Type, FieldInfos: GetCapturedFieldInfos(item.Symbol, item.Type, out int resourceCount, out int root32BitConstantCount), ResourceCount: resourceCount, Root32BitConstantCount: root32BitConstantCount)); // Generate the LoadDispatchData() methods context.RegisterSourceOutput(hierarchyInfoAndCaptureFieldInfos.Combine(canUseSkipLocalsInit), static (context, item) => { MethodDeclarationSyntax loadDispatchDataMethod = CreateLoadDispatchDataMethod( context, item.Left.Type, item.Left.FieldInfos, item.Left.ResourceCount, item.Left.Root32BitConstantCount); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, loadDispatchDataMethod, item.Right); context.AddSource($"{item.Left.Hierarchy.FilenameHint}.LoadDispatchData", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); }); } /// /// Gets the shader type for a given shader, if any. /// /// The input instance to check. /// The instance for . /// The instance for . /// Either or , or . [Pure] private static Type? GetShaderType( INamedTypeSymbol typeSymbol, INamedTypeSymbol iComputeShaderSymbol, INamedTypeSymbol iPixelShaderSymbol) { foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.Interfaces) { if (interfaceSymbol.Name == nameof(IComputeShader) && SymbolEqualityComparer.Default.Equals(interfaceSymbol, iComputeShaderSymbol)) { return typeof(IComputeShader); } if (interfaceSymbol.IsGenericType && interfaceSymbol.Name == nameof(IPixelShader) && SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, iPixelShaderSymbol)) { return typeof(IPixelShader<>); } } return null; } /// /// Creates a instance wrapping the given method. /// /// The instance for the current type. /// The item to insert. /// Whether [SkipLocalsInit] can be used. /// A object wrapping . [Pure] private static CompilationUnitSyntax GetCompilationUnitFromMethod( HierarchyInfo hierarchyInfo, MethodDeclarationSyntax methodDeclaration, bool canUseSkipLocalsInit) { // 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 (canUseSkipLocalsInit) { attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit"))))); } // Create the partial shader type declaration with the given method implementation. // This code produces a struct declaration as follows: // // partial struct // { // // } StructDeclarationSyntax structDeclarationSyntax = StructDeclaration(hierarchyInfo.Names[0]) .AddModifiers(Token(SyntaxKind.PartialKeyword)) .AddMembers(methodDeclaration.AddAttributeLists(attributes.ToArray())); TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; // Add all parent types in ascending order, if any foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1)) { typeDeclarationSyntax = ClassDeclaration(parentType) .AddModifiers(Token(SyntaxKind.PartialKeyword)) .AddMembers(typeDeclarationSyntax); } // 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 ; // // return CompilationUnit().AddMembers( FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace)) .AddMembers(typeDeclarationSyntax) .WithNamespaceKeyword(Token(TriviaList( Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) .NormalizeWhitespace(eol: "\n"); } }