diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs new file mode 100644 index 00000000..53d58a4c --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs @@ -0,0 +1,113 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using System.Linq; +using ComputeSharp.__Internals; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator +{ + /// + /// Extracts the names of all instance fields of a type. + /// + /// The input instance to process. + /// The names of all instance fields within . + [Pure] + private static ImmutableArray GetDelegateFieldNames(INamedTypeSymbol structDeclarationSymbol) + { + return + structDeclarationSymbol + .GetMembers() + .OfType() + .Where(static member => member.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }) + .Select(static member => member.Name) + .ToImmutableArray(); + } + + /// + /// Creates a instance for the GetDispatchId method. + /// + ///The names of all instance fields within the current shader type. + /// The resulting instance for the GetDispatchId method. + private static MethodDeclarationSyntax CreateGetDispatchIdMethod(ImmutableArray delegateFieldNames) + { + // This code produces a method declaration as follows: + // + // readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId() + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.IntKeyword)), + Identifier("GetDispatchId")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .WithBody(GetShaderHashCodeBody(delegateFieldNames)); + } + + /// + /// Gets a instance with the logic to compute the hashcode of a given shader type. + /// + /// The names of all instance fields within the current shader type. + /// The instance to hash the input shader. + [Pure] + private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames) + { + if (delegateFieldNames.Length == 0) + { + // return 0; + return + Block(ReturnStatement( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))); + } + + List blockStatements = new(4); + + // global::System.HashCode hashCode = default; + blockStatements.Add(LocalDeclarationStatement( + VariableDeclaration(IdentifierName("global::System.HashCode")) + .AddVariables( + VariableDeclarator(Identifier("hashCode")) + .WithInitializer(EqualsValueClause( + LiteralExpression( + SyntaxKind.DefaultLiteralExpression, + Token(SyntaxKind.DefaultKeyword))))))); + + foreach (string fieldName in delegateFieldNames) + { + // hashCode.Add(delegateField.Method); + blockStatements.Add(ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("hashCode"), + IdentifierName("Add"))) + .AddArgumentListArguments(Argument( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(fieldName), + IdentifierName("Method")))))); + } + + // return hashCode.ToHashCode(); + blockStatements.Add(ReturnStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("hashCode"), + IdentifierName("ToHashCode"))))); + + return Block(blockStatements); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs new file mode 100644 index 00000000..0f1d1c87 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs @@ -0,0 +1,182 @@ +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; + +/// +public sealed partial class IShaderGenerator : 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 shader type + IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol, 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, item.Type!)); + + // Get the hierarchy info and delegate field names for each shader type + IncrementalValuesProvider<(HierarchyInfo Hierarchy, ImmutableArray Delegates)> hierarchyInfoAndShaderFieldNames = + shaderDeclarations + .Select(static (item, token) => (HierarchyInfo.From(item.Symbol), GetDelegateFieldNames(item.Symbol))); + + // Generate the GetDispatchId() methods + context.RegisterSourceOutput(hierarchyInfoAndShaderFieldNames.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)); + }); + } + + /// + /// 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, interfaceSymbol.ConstructUnboundGenericType())) + { + 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"); + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs new file mode 100644 index 00000000..6d098bed --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using ComputeSharp.SourceGenerators.Extensions; +using Microsoft.CodeAnalysis; +using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model describing the hierarchy info for a specific type. +/// +/// The filename hint for the current type. +/// Gets the namespace for the current type. +/// Gets the sequence of type definitions containing the current type. +internal sealed record HierarchyInfo(string FilenameHint, string Namespace, ImmutableArray Names) +{ + /// + /// Creates a new instance from a given . + /// + /// The input instance to gather info for. + /// A instance describing . + [Pure] + public static HierarchyInfo From(INamedTypeSymbol typeSymbol) + { + ImmutableArray.Builder names = ImmutableArray.CreateBuilder(); + + for (INamedTypeSymbol? parent = typeSymbol; + parent is not null; + parent = parent.ContainingType) + { + names.Add(parent.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); + } + + return new( + typeSymbol.GetGeneratedFileName(), + typeSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)), + names.ToImmutable()); + } + + /// + [Pure] + public bool Equals(HierarchyInfo? other) + { + return + other is not null && + (ReferenceEquals(this, other) || + (Namespace == other.Namespace && + (Names == other.Names || + Names.AsSpan().SequenceEqual(other.Names.AsSpan())))); + } + + /// + [Pure] + public override int GetHashCode() + { + return HashCode.Combine(Namespace, Names, Names[0]); + } +}