using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Mappings; 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.Helpers.SyntaxFactoryHelper; #pragma warning disable CS0618 namespace ComputeSharp.SourceGenerators { [Generator] public class IComputeShaderSourceGenerator : ISourceGenerator { /// public void Initialize(GeneratorInitializationContext context) { } /// public void Execute(GeneratorExecutionContext context) { // Find all the struct declarations ImmutableArray structDeclarations = ( from tree in context.Compilation.SyntaxTrees from structDeclaration in tree.GetRoot().DescendantNodes().OfType() select structDeclaration).ToImmutableArray(); foreach (StructDeclarationSyntax structDeclaration in structDeclarations) { 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(structDeclarationSymbol, discoveredTypes).ToArray(); var sharedBuffers = GetGroupSharedMembers(structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, localFunctions) = GetProcessedMethods(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(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(structDeclarationSymbol.GetFullMetadataName()))), 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. /// /// The input instance to process. /// The collection of currently discovered types. /// A sequence of captured members in . [Pure] private static IEnumerable> GetProcessedMembers(INamedTypeSymbol structDeclarationSymbol, ICollection types) { foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { if (fieldSymbol.IsStatic) continue; INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; string typeName = HlslKnownTypes.GetMappedName(typeSymbol); _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); // Yield back the current mapping for the name (if the name used a reserved keyword) yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName }; // Track the type of items in the current buffer if (HlslKnownTypes.IsTypedResourceType(typeSymbol.GetFullMetadataName()) && typeSymbol.TypeArguments.Length == 1) { types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); } } } /// /// Gets a sequence of captured members and their mapped names. /// /// The input instance to process. /// The collection of currently discovered types. /// A sequence of captured members in . [Pure] private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers(INamedTypeSymbol structDeclarationSymbol, ICollection types) { foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { if (!fieldSymbol.IsStatic) continue; AttributeData attribute = fieldSymbol.GetAttributes().First(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; IArrayTypeSymbol typeSymbol = (IArrayTypeSymbol)fieldSymbol.Type; string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); yield return (mapping ?? fieldSymbol.Name, typeName, bufferSize); types.Add((INamedTypeSymbol)typeSymbol.ElementType); } } /// /// Gets a sequence of processed methods declared within a given type. /// /// The type symbol for the shader type. /// The instance for the current type. /// The instance for the type to process. /// The collection of currently discovered types. /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. /// A sequence of processed methods in , and the entry point. [Pure] private static (string EntryPoint, IEnumerable Methods) GetProcessedMethods( StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, SemanticModel semanticModel, ICollection discoveredTypes, IDictionary staticMethods, IDictionary constantDefinitions) { // Find all declared methods in the type ImmutableArray methodDeclarations = ( from syntaxNode in structDeclaration.DescendantNodes() where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); string? entryPoint = null; List methods = new(); foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) { IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!; ShaderSourceRewriter shaderSourceRewriter = new(structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); // Rewrite the method syntax tree MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); // If the method is the shader entry point, do additional processing if (methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && methodDeclarationSymbol.ReturnsVoid && methodDeclarationSymbol.TypeParameters.Length == 0 && methodDeclarationSymbol.Parameters.Length == 0) { processedMethod = new ExecuteMethodRewriter().Visit(processedMethod)!; entryPoint = processedMethod.NormalizeWhitespace().ToFullString(); } else methods.Add(processedMethod); // Emit the extracted local functions foreach (var localFunction in shaderSourceRewriter.LocalFunctions) { methods.Add(localFunction.Value); } } return (entryPoint!, methods); } /// /// Gets a sequence of discovered constants. /// /// The collection of discovered constant definitions. /// A sequence of discovered constants to declare in the shader. [Pure] internal static IEnumerable> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) { foreach (var constant in constantDefinitions) { var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().Replace(".", "__"); var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; yield return new string[] { constantName, constant.Value }; } } /// /// Gets the sequence of processed discovered custom types. /// /// The sequence of discovered custom types. /// A sequence of custom type definitions to add to the shader source. internal static IEnumerable GetProcessedTypes(IEnumerable types) { foreach (var type in HlslKnownTypes.GetCustomTypes(types)) { var structType = type.GetFullMetadataName().Replace(".", "__"); var structDeclaration = StructDeclaration(structType); // Declare the fields of the current type foreach (var field in type.GetMembers().OfType()) { INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; // Convert the name to the fully qualified HLSL version if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) { mapped = fieldType.GetFullMetadataName().Replace(".", "__"); } structDeclaration = structDeclaration.AddMembers( FieldDeclaration(VariableDeclaration( IdentifierName(mapped!)).AddVariables( VariableDeclarator(Identifier(field.Name))))); } // Insert the trailing ; right after the closing bracket (after normalization) yield return structDeclaration .NormalizeWhitespace() .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) .ToFullString(); } } } }